-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathserve.ts
993 lines (901 loc) · 29 KB
/
serve.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
/*
* serve.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { info, warning } from "log/mod.ts";
import { existsSync } from "fs/mod.ts";
import { basename, dirname, extname, join, relative } from "path/mod.ts";
import * as colors from "fmt/colors.ts";
import * as ld from "../../core/lodash.ts";
import { DOMParser, initDenoDom } from "../../core/deno-dom.ts";
import { openUrl } from "../../core/shell.ts";
import {
contentType,
isDocxContent,
isHtmlContent,
isPdfContent,
isTextContent,
} from "../../core/mime.ts";
import { dirAndStem, isModifiedAfter } from "../../core/path.ts";
import { logError } from "../../core/log.ts";
import {
kProject404File,
kProjectType,
ProjectContext,
} from "../../project/types.ts";
import { resolvePreviewOptions } from "../../command/preview/preview.ts";
import {
isProjectInputFile,
projectExcludeDirs,
projectOutputDir,
projectPreviewServe,
} from "../../project/project-shared.ts";
import { projectContext } from "../../project/project-context.ts";
import { partitionedMarkdownForInput } from "../../project/project-config.ts";
import {
clearProjectIndex,
inputFileForOutputFile,
resolveInputTarget,
} from "../../project/project-index.ts";
import { websitePath } from "../../project/types/website/website-config.ts";
import { renderProject } from "../../command/render/project.ts";
import {
renderResultFinalOutput,
renderResultUrlPath,
} from "../../command/render/render.ts";
import {
httpContentResponse,
httpFileRequestHandler,
isBrowserPreviewable,
} from "../../core/http.ts";
import { HttpFileRequestOptions } from "../../core/http-types.ts";
import { ProjectWatcher, ServeOptions } from "./types.ts";
import { watchProject } from "./watch.ts";
import {
isPreviewRenderRequest,
isPreviewTerminateRequest,
previewRenderRequest,
previewRenderRequestIsCompatible,
} from "../../command/preview/preview.ts";
import {
previewUnableToRenderResponse,
printWatchingForChangesMessage,
render,
renderToken,
} from "../../command/render/render-shared.ts";
import { renderServices } from "../../command/render/render-services.ts";
import { renderProgress } from "../../command/render/render-info.ts";
import { resourceFilesFromFile } from "../../command/render/resources.ts";
import { projectType } from "../../project/types/project-types.ts";
import { htmlResourceResolverPostprocessor } from "../../project/types/website/website-resources.ts";
import { inputFilesDir } from "../../core/render.ts";
import { kResources, kTargetFormat } from "../../config/constants.ts";
import { resourcesFromMetadata } from "../../command/render/resources.ts";
import {
RenderFlags,
RenderOptions,
RenderResult,
} from "../../command/render/types.ts";
import {
kPdfJsInitialPath,
pdfJsBaseDir,
pdfJsFileHandler,
} from "../../core/pdfjs.ts";
import { isPdfOutput } from "../../config/format.ts";
import { bookOutputStem } from "../../project/types/book/book-shared.ts";
import { removePandocToArg } from "../../command/render/flags.ts";
import { isRStudioServer, isServerSession } from "../../core/platform.ts";
import { ServeRenderManager } from "./render.ts";
import { projectScratchPath } from "../project-scratch.ts";
import {
previewEnsureResources,
previewMonitorResources,
} from "../../core/quarto.ts";
import { exitWithCleanup, onCleanup } from "../../core/cleanup.ts";
import { projectExtensionDirs } from "../../extension/extension.ts";
import { findOpenPort } from "../../core/port.ts";
import { kLocalhost } from "../../core/port-consts.ts";
import { ProjectServe } from "../../resources/types/schema-types.ts";
import { handleHttpRequests } from "../../core/http-server.ts";
import { touch } from "../../core/file.ts";
import { staticResource } from "../../preview/preview-static.ts";
import { previewTextContent } from "../../preview/preview-text.ts";
import { kManuscriptType } from "../types/manuscript/manuscript-types.ts";
import {
previewURL,
printBrowsePreviewMessage,
} from "../../core/previewurl.ts";
import {
noPreviewServer,
PreviewServer,
runExternalPreviewServer,
} from "../../preview/preview-server.ts";
import { notebookContext } from "../../render/notebook/notebook-context.ts";
export const kRenderNone = "none";
export const kRenderDefault = "default";
export async function serveProject(
target: string | ProjectContext,
renderOptions: RenderOptions,
pandocArgs: string[],
options: ServeOptions,
noServe: boolean,
) {
let project: ProjectContext | undefined;
let flags = renderOptions.flags;
const nbContext = renderOptions.services.notebook;
if (typeof target === "string") {
if (target === ".") {
target = Deno.cwd();
}
project = await projectContext(
target,
nbContext,
renderOptions,
);
if (!project || !project?.config) {
throw new Error(`${target} is not a project`);
}
const isDocusaurusMd = (
format?: string | Record<string, unknown> | unknown,
) => {
if (!format) {
return false;
}
if (typeof format === "string") {
return format === "docusaurus-md";
} else if (typeof format === "object") {
const formats = Object.keys(format);
if (formats.length > 0) {
const firstFormat = Object.keys(format)[0];
return firstFormat === "docusaurus-md";
} else {
return false;
}
} else {
return false;
}
};
// Default project types can't be served
const projType = projectType(project?.config?.project?.[kProjectType]);
if (
projType.type === "default" && !isDocusaurusMd(project?.config?.format)
) {
const hasIndex = project.files.input.some((file) => {
let relPath = file;
if (project) {
relPath = relative(project.dir, file);
}
const [dir, stem] = dirAndStem(relPath);
return dir === "." && stem === "index";
});
if (!hasIndex && options.browser !== false) {
throw new Error(
`The project '${
project.config.project.title || ""
}' is a default type project which doesn't support project wide previewing unless there is an 'index' file present.\n\nPlease preview an individual file within this project instead.`,
);
}
}
} else {
project = target;
}
// acquire the preview lock
acquirePreviewLock(project);
// monitor the src dir
previewEnsureResources();
previewMonitorResources();
// clear the project index
clearProjectIndex(project.dir);
// set QUARTO_PROJECT_DIR
Deno.env.set("QUARTO_PROJECT_DIR", project.dir);
// resolve options
options = {
...options,
...(await resolvePreviewOptions(options, project)),
};
// are we rendering?
const renderBefore = options.render !== kRenderNone;
if (renderBefore) {
renderProgress("Rendering:");
} else {
renderProgress("Preparing to preview");
}
// get 'to' from --render
flags = {
...flags,
...(renderBefore && options.render !== kRenderDefault)
? { to: options.render }
: {},
};
// if there is no flags 'to' then set 'to' to the default format
if (flags.to === undefined) {
flags.to = kRenderDefault;
}
// are we targeting pdf output?
const pdfOutput = isPdfOutput(flags.to || "");
// Configure render services
const services = renderServices(nbContext);
// determines files to render and resourceFiles to monitor
// if we are in render 'none' mode then only render files whose output
// isn't up to date. for those files we aren't rendering, compute their
// resource files so we can watch them for changes
let files: string[] | undefined;
let resourceFiles: string[] = [];
if (!renderBefore) {
// if this is pdf output then we need to render all of the files
// so that the latex compiler can build the entire book
if (pdfOutput) {
files = project.files.input;
} else {
const srvFiles = await serveFiles(project);
files = srvFiles.files;
resourceFiles = srvFiles.resourceFiles;
}
}
let renderResult;
try {
renderResult = await renderProject(
project,
{
services,
progress: true,
useFreezer: !renderBefore,
flags,
pandocArgs,
previewServer: true,
},
files,
);
} finally {
services.cleanup();
}
// exit if there was an error
if (renderResult.error) {
throw renderResult.error;
}
// append resource files from render results
resourceFiles.push(...ld.uniq(
renderResult.files.flatMap((file) => file.resourceFiles),
) as string[]);
// scan for extension dirs
const extensionDirs = projectExtensionDirs(project);
// render manager for tracking need to re-render outputs
// (record any files we just rendered)
const renderManager = new ServeRenderManager();
renderManager.onRenderResult(
renderResult,
extensionDirs,
resourceFiles,
project,
);
// stop server function (will be reset if there is a serve action)
let stopServer = () => {};
// create project watcher. later we'll figure out if it should provide renderOutput
const watcher = await watchProject(
project,
extensionDirs,
resourceFiles,
{ ...renderOptions, flags },
pandocArgs,
options,
!pdfOutput, // we don't render on reload for pdf output
renderManager,
stopServer,
);
// print status
printWatchingForChangesMessage();
// are we serving? are we using a custom serve command?
const serve = noServe ? false : projectPreviewServe(project) || true;
const previewServer = serve === false
? await noPreviewServer()
: serve === true
? await internalPreviewServer(
project,
renderResult,
renderManager,
pdfOutput,
watcher,
extensionDirs,
resourceFiles,
flags,
pandocArgs,
options,
)
: await externalPreviewServer(
project,
serve,
options,
renderManager,
watcher,
extensionDirs,
resourceFiles,
flags,
pandocArgs,
);
// set stopServer hook
stopServer = previewServer.stop;
// start server (launch browser if a path is returned)
const path = await previewServer.start();
if (path !== undefined) {
printBrowsePreviewMessage(
options.host!,
options.port!,
path,
);
if (options.browser && !isServerSession()) {
await openUrl(previewURL(options.host!, options.port!, path));
}
}
// register the stopServer function as a cleanup handler
onCleanup(stopServer);
// if there is a touchPath then touch
if (options.touchPath) {
await touch(options.touchPath);
}
// run the server
await previewServer.serve();
}
function externalPreviewServer(
project: ProjectContext,
serve: ProjectServe,
options: ServeOptions,
renderManager: ServeRenderManager,
watcher: ProjectWatcher,
extensionDirs: string[],
resourceFiles: string[],
flags: RenderFlags,
pandocArgs: string[],
): Promise<PreviewServer> {
// run a control channel server for handling render requests
// if there was a renderToken() passed
let controlListener: Deno.Listener | undefined;
if (renderToken()) {
const outputDir = projectOutputDir(project);
const handlerOptions: HttpFileRequestOptions = {
// base dir
baseDir: outputDir,
// handle websocket upgrade and render requests
onRequest: previewControlChannelRequestHandler(
project,
renderManager,
watcher,
extensionDirs,
resourceFiles,
flags,
pandocArgs,
false,
),
};
const handler = httpFileRequestHandler(handlerOptions);
const port = findOpenPort();
controlListener = Deno.listen({ port, hostname: kLocalhost });
handleHttpRequests(controlListener, handler).then(() => {
// terminanted
}).catch((_error) => {
// ignore errors
});
info(`Preview service running (${port})`);
}
// parse command line args and interpolate host and port
const cmd = serve.cmd.split(/[\t ]/).map((arg, index) => {
if (Deno.build.os === "windows" && index === 0 && arg === "npm") {
return "npm.cmd";
} else if (arg === "{host}") {
return options.host || kLocalhost;
} else if (arg === "{port}") {
return String(options.port);
} else {
return arg;
}
});
// add custom args
if (serve.args) {
cmd.push(...serve.args);
}
const readyPattern = new RegExp(serve.ready);
const server = runExternalPreviewServer({
cmd,
readyPattern,
env: serve.env,
cwd: projectOutputDir(project),
});
return Promise.resolve({
start: async () => {
return server.start();
},
serve: async () => {
return server.serve();
},
stop: () => {
if (controlListener) {
controlListener.close();
}
return server.stop();
},
});
}
async function internalPreviewServer(
project: ProjectContext,
renderResult: RenderResult,
renderManager: ServeRenderManager,
pdfOutput: boolean,
watcher: ProjectWatcher,
extensionDirs: string[],
resourceFiles: string[],
flags: RenderFlags,
pandocArgs: string[],
options: ServeOptions,
): Promise<PreviewServer> {
const projType = projectType(project?.config?.project?.[kProjectType]);
const outputDir = projectOutputDir(project);
const finalOutput = renderResultFinalOutput(renderResult);
// function that can return the current target pdf output file
const pdfOutputFile = (finalOutput && pdfOutput)
? (): string => {
const project = watcher.project();
if (projType.type == kManuscriptType) {
// For manuscripts, just use the final output as is
return finalOutput;
} else {
const outputFile = join(
dirname(finalOutput),
bookOutputStem(project.dir, project.config) + ".pdf",
);
return outputFile;
}
}
: undefined;
const handlerOptions: HttpFileRequestOptions = {
// base dir
baseDir: outputDir,
// print all urls
printUrls: "all",
// handle websocket upgrade and render requests
onRequest: previewControlChannelRequestHandler(
project,
renderManager,
watcher,
extensionDirs,
resourceFiles,
flags,
pandocArgs,
isBrowserPreviewable(finalOutput),
),
// handle html file requests w/ re-renders
onFile: async (file: string, req: Request) => {
// check for static response
const baseDir = projectOutputDir(project);
const staticResponse = await staticResource(baseDir, file);
if (staticResponse) {
const resolveBody = () => {
if (staticResponse.injectClient) {
const contents = new TextDecoder().decode(staticResponse.contents);
return staticResponse.injectClient(
contents,
watcher.clientHtml(req),
);
} else {
return staticResponse.contents;
}
};
const body = resolveBody();
const response = {
body,
contentType: staticResponse.contentType,
};
return response;
} else if (
isHtmlContent(file) || isPdfContent(file) || isDocxContent(file) ||
isTextContent(file)
) {
// find the input file associated with this output and render it
// if we can't find an input file for this .html file it may have
// been an input added after the server started running, to catch
// this case run a refresh on the watcher then try again
const serveDir = projectOutputDir(watcher.project());
const filePathRelative = relative(serveDir, file);
let inputFile = await inputFileForOutputFile(
watcher.project(),
filePathRelative,
);
if (!inputFile || !existsSync(inputFile.file)) {
inputFile = await inputFileForOutputFile(
await watcher.refreshProject(),
filePathRelative,
);
}
let result: RenderResult | undefined;
let renderError: Error | undefined;
if (inputFile) {
// render the file if we haven't already done a render for the current input state
if (
renderManager.fileRequiresReRender(
file,
inputFile.file,
extensionDirs,
resourceFiles,
watcher.project(),
)
) {
const renderFlags = { ...flags, quiet: true };
// remove 'to' argument to allow the file to be rendered in it's default format
// (only if we are in a project type e.g. websites that allows multiple formats)
const renderPandocArgs = projType.projectFormatsOnly
? pandocArgs
: removePandocToArg(pandocArgs);
if (!projType.projectFormatsOnly) {
delete renderFlags?.to;
}
// if to is 'all' then choose html
if (renderFlags?.to == "all") {
renderFlags.to = isHtmlContent(file) ? "html" : "pdf";
}
// When previewing, the project type can request that the format that produced
// the output that is being requested should always be used to render the file
if (projType.incrementalFormatPreviewing) {
renderFlags.to = inputFile.format.identifier[kTargetFormat];
delete renderFlags?.clean;
}
const services = renderServices(notebookContext());
try {
result = await renderManager.submitRender(() =>
renderProject(
watcher.project(),
{
services,
useFreezer: true,
devServerReload: true,
flags: renderFlags,
pandocArgs: renderPandocArgs,
},
[inputFile!.file],
)
);
if (result.error) {
renderManager.onRenderError(result.error);
renderError = result.error;
} else {
renderManager.onRenderResult(
result,
extensionDirs,
resourceFiles,
project!,
);
}
} catch (e) {
logError(e);
renderError = e;
} finally {
services.cleanup();
}
}
}
// read the output file
const fileContents = renderError
? renderErrorPage(renderError)
: Deno.readFileSync(file);
// inject watcher client for html
if (isHtmlContent(file) && inputFile) {
const projInputFile = join(
project!.dir,
relative(watcher.project().dir, inputFile.file),
);
return watcher.injectClient(
req,
fileContents,
projInputFile,
);
} else if (isTextContent(file) && inputFile) {
return previewTextContent(
file,
inputFile.file,
inputFile.format,
req,
watcher.injectClient,
);
} else {
return { contentType: contentType(file), body: fileContents };
}
} else {
return undefined;
}
},
// handle 404 by returing site custom 404 page
on404: (url: string, req: Request) => {
const print = !basename(url).startsWith("jupyter-");
let body = new TextEncoder().encode("Not Found");
const custom404 = join(outputDir, kProject404File);
if (existsSync(custom404)) {
let content404 = Deno.readTextFileSync(custom404);
// replace site-path references with / so they work in dev server mode
const sitePath = websitePath(project?.config);
if (sitePath !== "/" || isRStudioServer()) {
// if we are in rstudio server port proxied mode then replace
// including the port proxy
let replacePath = "/";
const referer = req.headers.get("referer");
if (isRStudioServer() && referer) {
const match = referer.match(/\/p\/.*?\//);
if (match) {
replacePath = match[0];
}
}
content404 = content404.replaceAll(
new RegExp('((?:content|ref|src)=")(' + sitePath + ")", "g"),
"$1" + replacePath,
);
}
body = new TextEncoder().encode(content404);
}
return {
print,
response: watcher.injectClient(req, body),
};
},
};
// if this is a pdf then we tweak the options to correctly handle pdfjs
if (finalOutput && pdfOutput) {
// change the baseDir to the pdfjs directory
handlerOptions.baseDir = pdfJsBaseDir();
// install custom handler for pdfjs
handlerOptions.onFile = pdfJsFileHandler(
pdfOutputFile!,
async (file: string, req: Request) => {
// inject watcher client for html
if (isHtmlContent(file)) {
const fileContents = await Deno.readFile(file);
return watcher.injectClient(req, fileContents);
} else {
return undefined;
}
},
);
}
// create the handler
const handler = httpFileRequestHandler(handlerOptions);
// if we are passed a browser path, resolve the output file if its an input
let browserPath = options.browserPath
? options.browserPath.replace(/^\//, "")
: undefined;
if (browserPath) {
const browserPathTarget = await resolveInputTarget(
project,
browserPath,
false,
);
if (browserPathTarget) {
browserPath = browserPathTarget.outputHref;
}
}
// compute browse url
const targetPath = browserPath
? browserPath
: pdfOutput
? kPdfJsInitialPath
: renderResultUrlPath(renderResult);
// print browse url and open browser if requested
const path = (targetPath && targetPath !== "index.html") ? targetPath : "";
// start listening
const listener = Deno.listen({ port: options.port!, hostname: options.host });
return {
start: () => Promise.resolve(path),
serve: async () => {
await handleHttpRequests(listener, handler);
},
stop: () => {
listener.close();
return Promise.resolve();
},
};
}
function previewControlChannelRequestHandler(
project: ProjectContext,
renderManager: ServeRenderManager,
watcher: ProjectWatcher,
extensionDirs: string[],
resourceFiles: string[],
flags: RenderFlags,
pandocArgs: string[],
requireActiveClient: boolean,
): (req: Request) => Promise<Response | undefined> {
return async (req: Request) => {
if (watcher.handle(req)) {
return await watcher.request(req);
} else if (isPreviewTerminateRequest(req)) {
exitWithCleanup(0);
} else if (isPreviewRenderRequest(req)) {
const prevReq = previewRenderRequest(
req,
requireActiveClient ? watcher.hasClients() : true,
project!.dir,
);
if (
prevReq &&
(await previewRenderRequestIsCompatible(prevReq, flags.to, project))
) {
if (isProjectInputFile(prevReq.path, project!)) {
const services = renderServices(notebookContext());
// if there is no specific format requested then 'all' needs
// to become 'html' so we don't render all formats
const to = flags.to === "all" ? (prevReq.format || "html") : flags.to;
renderManager.submitRender(() =>
render(prevReq.path, {
services,
flags: { ...flags, to },
pandocArgs,
previewServer: true,
})
).then((result) => {
if (result.error) {
renderManager.onRenderError(result.error);
} else {
// print output created
const finalOutput = renderResultFinalOutput(
result,
dirname(prevReq.path),
);
if (!finalOutput) {
throw new Error(
"No output created by quarto render " +
basename(prevReq.path),
);
}
renderManager.onRenderResult(
result,
extensionDirs,
resourceFiles,
watcher.project(),
);
info("Output created: " + finalOutput + "\n");
// notify user we are watching for reload
printWatchingForChangesMessage();
watcher.reloadClients(
true,
!isPdfContent(finalOutput)
? join(dirname(prevReq.path), finalOutput)
: undefined,
);
}
}).finally(() => {
services.cleanup();
});
return httpContentResponse("rendered");
// if this is a plain markdown file w/ an external preview server
// then just return success (it's already been saved as a
// precursor to the render)
} else if (
extname(prevReq.path) === ".md" && projectPreviewServe(project)
) {
return httpContentResponse("rendered");
} else {
return previewUnableToRenderResponse();
}
} else {
return previewUnableToRenderResponse();
}
} else {
return undefined;
}
};
}
// https://deno.com/blog/v1.23#remove-unstable-denosleepsync-api
function sleepSync(timeout: number) {
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);
Atomics.wait(int32, 0, 0, timeout);
}
function acquirePreviewLock(project: ProjectContext) {
// get lockfile
const lockfile = previewLockFile(project);
// if there is a lockfile send a kill signal to the pid therin
if (existsSync(lockfile)) {
const pid = parseInt(Deno.readTextFileSync(lockfile)) || undefined;
if (pid) {
info(
colors.bold(colors.blue("Terminating existing preview server....")),
{ newline: false },
);
try {
Deno.kill(pid, "SIGTERM");
sleepSync(3000);
} catch {
//
} finally {
info(colors.bold(colors.blue("DONE\n")));
}
}
}
// write our pid to the lockfile
Deno.writeTextFileSync(lockfile, String(Deno.pid));
// rmeove the lockfile when we exit
onCleanup(() => releasePreviewLock(project));
}
function releasePreviewLock(project: ProjectContext) {
try {
Deno.removeSync(previewLockFile(project));
} catch {
//
}
}
function previewLockFile(project: ProjectContext) {
return projectScratchPath(project.dir, join("preview", "lock"));
}
function renderErrorPage(e: Error) {
const content = `
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Quarto Render Error</title>
<script id="quarto-render-error" type="text/plain">${e.message}</script>
</head>
<body>
</body>
</html>
`;
return new TextEncoder().encode(content);
}
async function serveFiles(
project: ProjectContext,
): Promise<{ files: string[]; resourceFiles: string[] }> {
const projType = projectType(project.config?.project?.[kProjectType]);
// one time denoDom init
await initDenoDom();
const files: string[] = [];
const resourceFiles: string[] = [];
for (let i = 0; i < project.files.input.length; i++) {
const inputFile = project.files.input[i];
const projRelative = relative(project.dir, inputFile);
const target = await resolveInputTarget(project, projRelative, false);
if (target) {
const outputFile = join(projectOutputDir(project), target?.outputHref);
if (
isModifiedAfter(inputFile, outputFile) ||
projType.previewSkipUnmodified === false // Project types can force not skipping the rendering of files
) {
// render this file
files.push(inputFile);
} else {
// we aren't rendering this file, so we need to compute it's resource files
// for monitoring during serve
// resource files referenced in html
const outputResources: string[] = [];
if (isHtmlContent(outputFile)) {
const htmlInput = Deno.readTextFileSync(outputFile);
const doc = new DOMParser().parseFromString(htmlInput, "text/html")!;
const resolver = htmlResourceResolverPostprocessor(
inputFile,
project,
);
outputResources.push(...(await resolver(doc)).resources);
}
// partition markdown and read globs
const partitioned = await partitionedMarkdownForInput(
project,
projRelative,
);
const globs: string[] = [];
if (partitioned?.yaml) {
const metadata = partitioned.yaml;
globs.push(...resourcesFromMetadata(metadata[kResources]));
}
// compute resource refs and add them
resourceFiles.push(
...(await resourceFilesFromFile(
project.dir,
projectExcludeDirs(project),
projRelative,
{ files: outputResources, globs },
false, // selfContained,
[join(dirname(projRelative), inputFilesDir(projRelative))],
partitioned,
)),
);
}
} else {
warning("Unabled to resolve output target for " + inputFile);
}
}
return { files, resourceFiles: ld.uniq(resourceFiles) as string[] };
}