-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.ts
965 lines (851 loc) · 29 KB
/
index.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
import type * as vite from "vite";
import type * as Compiler from "@marko/compiler";
import fs from "fs";
import path from "path";
import crypto from "crypto";
import anyMatch from "anymatch";
import { pathToFileURL } from "url";
import getServerEntryTemplate from "./server-entry-template";
import {
generateInputDoc,
generateDocManifest,
type DocManifest,
} from "./manifest-generator";
import esbuildPlugin from "./esbuild-plugin";
import interopBabelPlugin from "./babel-plugin-cjs-interop";
import type { PluginObj } from "@babel/core";
import { isCJSModule } from "./resolve";
import {
getRenderAssetsRuntime,
renderAssetsRuntimeId,
} from "./render-assets-runtime";
import renderAssetsTransform from "./render-assets-transform";
import relativeAssetsTransform from "./relative-assets-transform";
import globImportTransformer from "./glob-import-transform";
import { ReadOncePersistedStore } from "./read-once-persisted-store";
export namespace API {
export type getMarkoAssetCodeForEntry = (id: string) => string | void;
}
export interface Options {
// Defaults to true, set to false to disable automatic component discovery and hydration.
linked?: boolean;
// Override the Marko compiler instance being used. (primarily for tools wrapping this module)
compiler?: string;
// Sets a custom runtimeId to avoid conflicts with multiple copies of Marko on the same page.
runtimeId?: string;
// Overrides the Marko translator being used.
translator?: string;
// If set, will use the provided string as a variable name and prefix all assets paths with that variable.
basePathVar?: string;
// Overrides the Babel config that Marko will use.
babelConfig?: Compiler.Config["babelConfig"];
}
interface BrowserManifest {
[id: string]: DocManifest;
}
interface ServerManifest {
// optimizedRegistryIds?: { [id: string]: string };
entries: {
[entryId: string]: string;
};
entrySources: {
[entryId: string]: string;
};
chunksNeedingAssets: string[];
}
interface VirtualFile {
code: string;
map?: any;
}
type DeferredPromise<T> = Promise<T> & {
resolve: (value: T) => void;
reject: (error: Error) => void;
};
const POSIX_SEP = "/";
const WINDOWS_SEP = "\\";
const normalizePath =
path.sep === WINDOWS_SEP
? (id: string) => id.replace(/\\/g, POSIX_SEP)
: (id: string) => id;
const virtualFiles = new Map<
string,
VirtualFile | DeferredPromise<VirtualFile>
>();
const extReg = /\.[^.]+$/;
const queryReg = /\?marko-[^?]+$/;
const browserEntryQuery = "?marko-browser-entry";
const serverEntryQuery = "?marko-server-entry";
const virtualFileQuery = "?marko-virtual";
const browserQuery = "?marko-browser";
const markoExt = ".marko";
const htmlExt = ".html";
const resolveOpts = { skipSelf: true };
const configsByFileSystem = new Map<
typeof fs,
Map<Compiler.Config, Compiler.Config>
>();
const cache = new Map<unknown, unknown>();
const babelCaller = {
name: "@marko/vite",
supportsStaticESM: true,
supportsDynamicImport: true,
supportsTopLevelAwait: true,
supportsExportNamespaceFrom: true,
};
// const optimizedRegistryIds: Map<string, string> = new Map();
let registeredTagLib = false;
// This package has a dependency on @parcel/source-map which uses native addons.
// Some enviroments like Stackblitz don't support loading these. So... load it
// with a dynamic import to avoid everything failing.
let cjsToEsm: typeof import("@chialab/cjs-to-esm").transform | null | undefined;
export default function markoPlugin(opts: Options = {}): vite.Plugin[] {
let compiler: typeof Compiler;
let { linked = true } = opts;
let runtimeId: string | undefined;
let basePathVar: string | undefined;
let baseConfig: Compiler.Config;
let ssrConfig: Compiler.Config;
let ssrCjsConfig: Compiler.Config;
let domConfig: Compiler.Config;
let hydrateConfig: Compiler.Config;
const resolveVirtualDependency: Compiler.Config["resolveVirtualDependency"] =
(from, dep) => {
const normalizedFrom = normalizePath(from);
const query = `${virtualFileQuery}&id=${
Buffer.from(dep.virtualPath).toString("base64url") +
path.extname(dep.virtualPath)
}`;
const id = normalizePath(normalizedFrom) + query;
if (devServer) {
const prev = virtualFiles.get(id);
if (isDeferredPromise(prev)) {
prev.resolve(dep);
}
}
virtualFiles.set(id, dep);
return `./${path.posix.basename(normalizedFrom) + query}`;
};
let root: string;
let devEntryFile: string;
let devEntryFilePosix: string;
let renderAssetsRuntimeCode: string;
let isTest = false;
let isBuild = false;
let isSSRBuild = false;
let devServer: vite.ViteDevServer;
let serverManifest: ServerManifest | undefined;
let basePath = "/";
let getMarkoAssetFns: undefined | API.getMarkoAssetCodeForEntry[];
const entryIds = new Set<string>();
const cachedSources = new Map<string, string>();
const transformWatchFiles = new Map<string, string[]>();
const transformOptionalFiles = new Map<string, string[]>();
const store = new ReadOncePersistedStore<ServerManifest>(
`vite-marko${runtimeId ? `-${runtimeId}` : ""}`,
);
return [
{
name: "marko-vite:pre",
enforce: "pre", // Must be pre to allow us to resolve assets before vite.
async config(config, env) {
let optimize = env.mode === "production";
if ("MARKO_DEBUG" in process.env) {
optimize =
process.env.MARKO_DEBUG === "false" ||
process.env.MARKO_DEBUG === "0";
} else {
process.env.MARKO_DEBUG = optimize ? "false" : "true";
}
compiler ??= (await import(
opts.compiler || "@marko/compiler"
)) as typeof Compiler;
runtimeId = opts.runtimeId;
basePathVar = opts.basePathVar;
if ("BASE_URL" in process.env && config.base == null) {
config.base = process.env.BASE_URL;
}
baseConfig = {
cache,
optimize,
// optimizedRegistryIds:
// optimize && linked ? optimizedRegistryIds : undefined,
runtimeId,
sourceMaps: true,
writeVersionComment: false,
babelConfig: opts.babelConfig
? {
...opts.babelConfig,
caller: opts.babelConfig.caller
? {
name: "@marko/vite",
supportsStaticESM: true,
supportsDynamicImport: true,
supportsTopLevelAwait: true,
supportsExportNamespaceFrom: true,
...opts.babelConfig.caller,
}
: babelCaller,
}
: {
babelrc: false,
configFile: false,
browserslistConfigFile: false,
caller: babelCaller,
},
};
if (linked) {
(baseConfig as any).markoViteLinked = linked;
}
ssrConfig = {
...baseConfig,
resolveVirtualDependency,
output: "html",
};
domConfig = {
...baseConfig,
resolveVirtualDependency,
output: "dom",
};
hydrateConfig = {
...baseConfig,
resolveVirtualDependency,
output: "hydrate",
};
compiler.configure(baseConfig);
root = normalizePath(config.root || process.cwd());
devEntryFile = path.join(root, "index.html");
devEntryFilePosix = normalizePath(devEntryFile);
isTest = env.mode === "test";
isBuild = env.command === "build";
isSSRBuild = isBuild && linked && Boolean(config.build!.ssr);
renderAssetsRuntimeCode = getRenderAssetsRuntime({
isBuild,
basePathVar,
runtimeId,
});
if (isTest) {
linked = false;
const { test } = config as any;
if ((test.environment as string | undefined)?.includes("dom")) {
config.resolve ??= {};
config.resolve.conditions ??= [];
config.resolve.conditions.push("browser");
test.deps ??= {};
test.deps.optimizer ??= {};
test.deps.optimizer.web ??= {};
test.deps.optimizer.web.enabled ??= true;
}
}
if (!registeredTagLib) {
registeredTagLib = true;
compiler.taglib.register("@marko/vite", {
transform: globImportTransformer,
"<head>": { transformer: renderAssetsTransform },
"<body>": { transformer: renderAssetsTransform },
"<*>": { transformer: relativeAssetsTransform },
});
}
const optimizeDeps = (config.optimizeDeps ??= {});
if (!isTest) {
optimizeDeps.entries ??= [
"**/*.marko",
"!**/__snapshots__/**",
`!**/__tests__/**`,
`!**/coverage/**`,
];
}
const domDeps = compiler.getRuntimeEntryFiles("dom", opts.translator);
optimizeDeps.include = optimizeDeps.include
? [...optimizeDeps.include, ...domDeps]
: domDeps;
const optimizeExtensions = (optimizeDeps.extensions ??= []);
optimizeExtensions.push(".marko");
const esbuildOptions = (optimizeDeps.esbuildOptions ??= {});
const esbuildPlugins = (esbuildOptions.plugins ??= []);
esbuildPlugins.push(esbuildPlugin(compiler, baseConfig));
const ssr = (config.ssr ??= {});
const { noExternal } = ssr;
if (noExternal !== true) {
const noExternalReg = /\.marko$/;
if (noExternal) {
if (Array.isArray(noExternal)) {
ssr.noExternal = [...noExternal, noExternalReg];
} else {
ssr.noExternal = [noExternal, noExternalReg];
}
} else {
ssr.noExternal = noExternalReg;
}
}
if (isSSRBuild && !config.build?.rollupOptions?.output) {
// For the server build vite will still output code split chunks to the `assets` directory by default.
// this is problematic since you might have server assets in your client assets folder.
// Here we change the default chunkFileNames config to instead output to the outDir directly.
config.build ??= {};
config.build.rollupOptions ??= {};
config.build.rollupOptions.output = {
chunkFileNames: `[name]-[hash].js`,
};
}
if (basePathVar) {
config.experimental ??= {};
if (config.experimental.renderBuiltUrl) {
throw new Error(
"Cannot use @marko/vite `basePathVar` with Vite's `renderBuiltUrl` option.",
);
}
const assetsDir =
config.build?.assetsDir?.replace(/[/\\]$/, "") ?? "assets";
const assetsDirLen = assetsDir.length;
const assetsDirEnd = assetsDirLen + 1;
const trimAssertsDir = (fileName: string) => {
if (fileName.startsWith(assetsDir)) {
switch (fileName[assetsDirLen]) {
case POSIX_SEP:
case WINDOWS_SEP:
return fileName.slice(assetsDirEnd);
}
}
return fileName;
};
config.experimental.renderBuiltUrl = (
fileName,
{ hostType, ssr },
) => {
switch (hostType) {
case "html":
return trimAssertsDir(fileName);
case "js":
return {
runtime: `${
ssr
? basePathVar
: `$mbp${runtimeId ? `_${runtimeId}` : ""}`
}+${JSON.stringify(trimAssertsDir(fileName))}`,
};
default:
return { relative: true };
}
};
}
return {
resolve: {
alias: [
{
find: /^~(?!\/)/,
replacement: "",
},
],
},
};
},
configResolved(config) {
basePath = config.base;
ssrCjsConfig = {
...ssrConfig,
babelConfig: {
...ssrConfig.babelConfig,
plugins: (
(ssrConfig.babelConfig!.plugins || []) as (
| PluginObj<any>
| string
)[]
).concat(
interopBabelPlugin({
extensions: config.resolve.extensions,
conditions: config.resolve.conditions,
filter: isBuild ? undefined : (path) => !/^\./.test(path),
}),
),
},
};
getMarkoAssetFns = undefined;
for (const plugin of config.plugins) {
const fn = plugin.api?.getMarkoAssetCodeForEntry as
| undefined
| API.getMarkoAssetCodeForEntry;
if (fn) {
if (getMarkoAssetFns) {
getMarkoAssetFns.push(fn);
} else {
getMarkoAssetFns = [fn];
}
}
}
},
configureServer(_server) {
ssrConfig.hot = domConfig.hot = true;
devServer = _server;
devServer.watcher.on("all", (type, originalFileName) => {
const fileName = normalizePath(originalFileName);
cachedSources.delete(fileName);
if (type === "unlink") {
entryIds.delete(fileName);
transformWatchFiles.delete(fileName);
transformOptionalFiles.delete(fileName);
}
for (const [id, files] of transformWatchFiles) {
if (anyMatch(files, fileName)) {
devServer.watcher.emit("change", id);
}
}
if (type === "add" || type === "unlink") {
for (const [id, files] of transformOptionalFiles) {
if (anyMatch(files, fileName)) {
devServer.watcher.emit("change", id);
}
}
}
});
},
handleHotUpdate(ctx) {
compiler.taglib.clearCaches();
baseConfig.cache!.clear();
for (const [, cache] of configsByFileSystem) {
cache.clear();
}
for (const mod of ctx.modules) {
if (mod.id && virtualFiles.has(mod.id)) {
virtualFiles.set(mod.id, createDeferredPromise());
}
}
},
async buildStart(inputOptions) {
if (isBuild && linked && !isSSRBuild) {
try {
serverManifest = await store.read();
// if (serverManifest.optimizedRegistryIds) {
// for (const id in serverManifest.optimizedRegistryIds) {
// optimizedRegistryIds.set(
// id,
// serverManifest.optimizedRegistryIds[id],
// );
// }
// }
inputOptions.input = toHTMLEntries(root, serverManifest.entries);
for (const entry in serverManifest.entrySources) {
const id = normalizePath(path.resolve(root, entry));
entryIds.add(id);
cachedSources.set(id, serverManifest.entrySources[entry]);
}
} catch (err) {
this.error(
`You must run the "ssr" build before the "browser" build.`,
);
}
if (isEmpty(inputOptions.input)) {
this.error("No Marko files were found when compiling the server.");
}
}
},
async resolveId(importee, importer, importOpts, ssr = importOpts.ssr) {
if (virtualFiles.has(importee)) {
return importee;
}
if (importee === renderAssetsRuntimeId) {
return { id: renderAssetsRuntimeId };
}
let importeeQuery = getMarkoQuery(importee);
if (importeeQuery) {
importee = importee.slice(0, -importeeQuery.length);
} else if (!(importOpts as any).scan) {
if (
ssr &&
linked &&
importer &&
importer[0] !== "\0" &&
(importer !== devEntryFile ||
normalizePath(importer) !== devEntryFilePosix) && // Vite tries to resolve against an `index.html` in some cases, we ignore it here.
isMarkoFile(importee) &&
!isMarkoFile(importer.replace(queryReg, ""))
) {
importeeQuery = serverEntryQuery;
} else if (
!ssr &&
isBuild &&
importer &&
isMarkoFile(importee) &&
this.getModuleInfo(importer)?.isEntry
) {
importeeQuery = browserEntryQuery;
} else if (
!isBuild &&
linked &&
!ssr &&
!importeeQuery &&
isMarkoFile(importee)
) {
importeeQuery = browserQuery;
}
}
if (importeeQuery) {
const resolved =
importee[0] === "."
? {
id: normalizePath(
importer
? path.resolve(importer, "..", importee)
: path.resolve(root, importee),
),
}
: await this.resolve(importee, importer, resolveOpts);
if (resolved) {
resolved.id += importeeQuery;
}
return resolved;
}
if (importer) {
const importerQuery = getMarkoQuery(importer);
if (importerQuery) {
importer = importer.slice(0, -importerQuery.length);
if (importee[0] === ".") {
const resolved = normalizePath(
path.resolve(importer, "..", importee),
);
if (resolved === normalizePath(importer)) return resolved;
}
return this.resolve(importee, importer, resolveOpts);
}
}
return null;
},
async load(rawId) {
const id = stripVersionAndTimeStamp(rawId);
if (id === renderAssetsRuntimeId) {
return renderAssetsRuntimeCode;
}
const query = getMarkoQuery(id);
switch (query) {
case serverEntryQuery: {
entryIds.add(id.slice(0, -query.length));
return null;
}
case browserEntryQuery:
case browserQuery: {
// The goal below is to cached source content when in linked mode
// to avoid loading from disk for both server and browser builds.
// This is to support virtual Marko entry files.
return cachedSources.get(id.slice(0, -query.length)) || null;
}
}
return virtualFiles.get(id) || null;
},
async transform(source, rawId, ssr) {
let id = stripVersionAndTimeStamp(rawId);
const info = isBuild ? this.getModuleInfo(id) : undefined;
const arcSourceId = info?.meta.arcSourceId;
if (arcSourceId) {
const arcFlagSet = info.meta.arcFlagSet;
id = arcFlagSet
? arcSourceId.replace(extReg, `[${arcFlagSet.join("+")}]$&`)
: arcSourceId;
}
const isSSR = typeof ssr === "object" ? ssr.ssr : ssr;
const query = getMarkoQuery(id);
if (query && !query.startsWith(virtualFileQuery)) {
id = id.slice(0, -query.length);
if (query === serverEntryQuery) {
const fileName = id;
let mainEntryData: string;
id = `${id.slice(0, -markoExt.length)}.entry.marko`;
cachedSources.set(fileName, source);
if (isBuild) {
const relativeFileName = path.posix.relative(root, fileName);
const entryId = toEntryId(relativeFileName);
serverManifest ??= {
entries: {},
entrySources: {},
chunksNeedingAssets: [],
};
serverManifest.entries[entryId] = relativeFileName;
serverManifest.entrySources[relativeFileName] = source;
mainEntryData = JSON.stringify(entryId);
} else {
mainEntryData = JSON.stringify(
await generateDocManifest(
basePath,
await devServer.transformIndexHtml(
"/",
generateInputDoc(
posixFileNameToURL(fileName, root) + browserEntryQuery,
),
),
),
);
}
const entryData = [mainEntryData];
if (getMarkoAssetFns) {
for (const getMarkoAsset of getMarkoAssetFns) {
const asset = getMarkoAsset(fileName);
if (asset) {
entryData.push(asset);
}
}
}
source = await getServerEntryTemplate({
fileName,
entryData,
runtimeId,
basePathVar: isBuild ? basePathVar : undefined,
});
}
}
if (!isMarkoFile(id)) {
if (!isBuild) {
const ext = path.extname(id);
if (ext === ".cjs" || (ext === ".js" && isCJSModule(id))) {
if (cjsToEsm === undefined) {
try {
cjsToEsm = (await import("@chialab/cjs-to-esm")).transform;
} catch {
cjsToEsm = null;
return null;
}
}
if (cjsToEsm) {
try {
return await cjsToEsm(source);
} catch {
return null;
}
}
}
}
return null;
}
if (isSSR) {
if (linked) {
cachedSources.set(id, source);
}
if (!query && isCJSModule(id)) {
if (isBuild) {
const { code, map, meta } = await compiler.compile(
source,
id,
getConfigForFileSystem(info, ssrCjsConfig),
);
return {
code,
map,
meta: { arcSourceCode: source, arcScanIds: meta.analyzedTags },
};
}
}
}
const compiled = await compiler.compile(
source,
id,
getConfigForFileSystem(
info,
isSSR
? isCJSModule(id)
? ssrCjsConfig
: ssrConfig
: query === browserEntryQuery
? hydrateConfig
: domConfig,
),
);
const { map, meta } = compiled;
let { code } = compiled;
if (query !== browserEntryQuery && devServer) {
code += `\nif (import.meta.hot) import.meta.hot.accept(() => {});`;
}
if (devServer) {
const templateName = getPosixBasenameWithoutExt(id);
const optionalFilePrefix =
path.dirname(id) +
path.sep +
(templateName === "index" ? "" : `${templateName}.`);
for (const file of meta.watchFiles) {
this.addWatchFile(file);
}
transformOptionalFiles.set(id, [
`${optionalFilePrefix}style.*`,
`${optionalFilePrefix}component.*`,
`${optionalFilePrefix}component-browser.*`,
`${optionalFilePrefix}marko-tag.json`,
]);
transformWatchFiles.set(id, meta.watchFiles);
}
return {
code,
map,
meta: isBuild
? { arcSourceCode: source, arcScanIds: meta.analyzedTags }
: undefined,
};
},
},
{
name: "marko-vite:post",
apply: "build",
enforce: "post", // We use a "post" plugin to allow us to read the final generated `.html` from vite.
async generateBundle(outputOptions, bundle, isWrite) {
if (!linked) {
return;
}
if (!isWrite) {
this.error(
`Linked builds are currently only supported when in "write" mode.`,
);
}
if (!serverManifest) {
this.error(
"No Marko files were found when bundling the server in linked mode.",
);
}
if (isSSRBuild) {
const dir = outputOptions.dir
? path.resolve(outputOptions.dir)
: path.resolve(outputOptions.file!, "..");
for (const fileName in bundle) {
const chunk = bundle[fileName];
if (chunk.type === "chunk") {
if (chunk.moduleIds.includes(renderAssetsRuntimeId)) {
serverManifest!.chunksNeedingAssets.push(
path.resolve(dir, fileName),
);
}
}
}
// serverManifest.optimizedRegistryIds =
// Object.fromEntries(optimizedRegistryIds);
store.write(serverManifest!);
} else {
const browserManifest: BrowserManifest = {};
for (const entryId in serverManifest!.entries) {
const fileName = serverManifest!.entries[entryId];
const chunkId = fileName + htmlExt;
const chunk = bundle[chunkId];
if (chunk?.type === "asset") {
browserManifest[entryId] = {
...(await generateDocManifest(
basePath,
chunk.source.toString(),
)),
preload: undefined, // clear out preload for prod builds.
} as any;
delete bundle[chunkId];
} else {
this.error(
`Marko template had unexpected output from vite, ${fileName}`,
);
}
}
const manifestStr = `;var __MARKO_MANIFEST__=${JSON.stringify(
browserManifest,
)};\n`;
for (const fileName of serverManifest!.chunksNeedingAssets) {
await fs.promises.appendFile(fileName, manifestStr);
}
}
},
},
];
}
function getMarkoQuery(id: string) {
return queryReg.exec(id)?.[0] || "";
}
function isMarkoFile(id: string) {
return id.endsWith(markoExt);
}
function toHTMLEntries(root: string, serverEntries: ServerManifest["entries"]) {
const result: string[] = [];
for (const id in serverEntries) {
const markoFile = path.posix.join(root, serverEntries[id]);
const htmlFile = markoFile + htmlExt;
virtualFiles.set(htmlFile, {
code: generateInputDoc(markoFile + browserEntryQuery),
});
result.push(htmlFile);
}
return result;
}
function toEntryId(id: string) {
const lastSepIndex = id.lastIndexOf(POSIX_SEP);
let name = id.slice(lastSepIndex + 1, id.indexOf(".", lastSepIndex));
if (name === "index" || name === "template") {
name = id.slice(
id.lastIndexOf(POSIX_SEP, lastSepIndex - 1) + 1,
lastSepIndex,
);
}
return `${name}_${crypto
.createHash("SHA1")
.update(id)
.digest("base64")
.replace(/[/+]/g, "-")
.slice(0, 4)}`;
}
function posixFileNameToURL(fileName: string, root: string) {
const relativeURL = path.posix.relative(
pathToFileURL(root).pathname,
pathToFileURL(fileName).pathname,
);
if (relativeURL[0] === ".") {
throw new Error(
"@marko/vite: Entry templates must exist under the current root directory.",
);
}
return `/${relativeURL}`;
}
function getPosixBasenameWithoutExt(file: string): string {
const baseStart = file.lastIndexOf(POSIX_SEP) + 1;
const extStart = file.indexOf(".", baseStart + 1);
return file.slice(baseStart, extStart);
}
function createDeferredPromise<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
}) as DeferredPromise<T>;
promise.resolve = resolve;
promise.reject = reject;
return promise;
}
function isDeferredPromise<T>(obj: unknown): obj is DeferredPromise<T> {
return typeof (obj as Promise<T>)?.then === "function";
}
function isEmpty(obj: unknown) {
for (const _ in obj as Record<string, unknown>) {
return false;
}
return true;
}
function stripVersionAndTimeStamp(id: string) {
const queryStart = id.indexOf("?");
if (queryStart === -1) return id;
const url = id.slice(0, queryStart);
const query = id.slice(queryStart + 1).replace(/(?:^|[&])[vt]=[^&]+/g, "");
if (query) return `${url}?${query}`;
return url;
}
/**
* For integration with arc-vite.
* We create a unique Marko config tied to each arcFileSystem.
*/
function getConfigForFileSystem(
info: vite.Rollup.ModuleInfo | undefined | null,
config: Compiler.Config,
) {
const fileSystem = info?.meta.arcFS;
if (!fileSystem) return config;
let configsForFileSystem = configsByFileSystem.get(fileSystem);
if (!configsForFileSystem) {
configsForFileSystem = new Map();
configsByFileSystem.set(fileSystem, configsForFileSystem);
}
let configForFileSystem = configsForFileSystem.get(config);
if (!configForFileSystem) {
configForFileSystem = {
...config,
fileSystem,
cache: configsForFileSystem,
};
configsForFileSystem.set(config, configForFileSystem);
}
return configForFileSystem;
}