@marko/vite 3.1.6 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +0 -20
  2. package/dist/index.d.ts +3 -4
  3. package/dist/index.mjs +674 -103
  4. package/dist/manifest-generator.d.ts +1 -1
  5. package/dist/read-once-persisted-store.d.ts +6 -0
  6. package/dist/render-assets-runtime.d.ts +6 -0
  7. package/dist/serializer.d.ts +1 -1
  8. package/dist/server-entry-template.d.ts +1 -1
  9. package/package.json +20 -30
  10. package/dist/babel-plugin-cjs-interop.js +0 -117
  11. package/dist/babel-plugin-cjs-interop.mjs +0 -7
  12. package/dist/chunk-2E5QX7AF.mjs +0 -83
  13. package/dist/chunk-6IJ5UJ3N.mjs +0 -29
  14. package/dist/chunk-AEF7OQDP.mjs +0 -93
  15. package/dist/chunk-DCBMHGK4.mjs +0 -20
  16. package/dist/chunk-FCWFM7VD.mjs +0 -63
  17. package/dist/chunk-J6VIHWF4.mjs +0 -85
  18. package/dist/chunk-KIYHBIE6.mjs +0 -0
  19. package/dist/chunk-NTHVNXFC.mjs +0 -104
  20. package/dist/chunk-Y3E2OP42.mjs +0 -61
  21. package/dist/components/vite.marko +0 -74
  22. package/dist/esbuild-plugin.js +0 -113
  23. package/dist/esbuild-plugin.mjs +0 -6
  24. package/dist/index.js +0 -687
  25. package/dist/manifest-generator.js +0 -113
  26. package/dist/manifest-generator.mjs +0 -9
  27. package/dist/render-assets-transform.js +0 -41
  28. package/dist/render-assets-transform.mjs +0 -22
  29. package/dist/resolve.js +0 -94
  30. package/dist/resolve.mjs +0 -8
  31. package/dist/serializer.js +0 -127
  32. package/dist/serializer.mjs +0 -6
  33. package/dist/server-entry-template.js +0 -57
  34. package/dist/server-entry-template.mjs +0 -6
  35. package/dist/store/file-store.d.ts +0 -11
  36. package/dist/store/file-store.js +0 -91
  37. package/dist/store/file-store.mjs +0 -6
  38. package/dist/store/index.d.ts +0 -3
  39. package/dist/store/index.js +0 -41
  40. package/dist/store/index.mjs +0 -11
  41. package/dist/store/memory-store.d.ts +0 -8
  42. package/dist/store/memory-store.js +0 -38
  43. package/dist/store/memory-store.mjs +0 -6
  44. package/dist/store/types.d.ts +0 -5
  45. package/dist/store/types.js +0 -16
  46. package/dist/store/types.mjs +0 -0
package/dist/index.mjs CHANGED
@@ -1,49 +1,606 @@
1
- import "./chunk-KIYHBIE6.mjs";
2
- import {
3
- FileStore
4
- } from "./chunk-FCWFM7VD.mjs";
5
- import {
6
- MemoryStore
7
- } from "./chunk-DCBMHGK4.mjs";
8
- import {
9
- plugin
10
- } from "./chunk-AEF7OQDP.mjs";
11
- import {
12
- esbuildPlugin
13
- } from "./chunk-J6VIHWF4.mjs";
14
- import {
15
- generateDocManifest,
16
- generateInputDoc
17
- } from "./chunk-2E5QX7AF.mjs";
18
- import {
19
- isCJSModule
20
- } from "./chunk-Y3E2OP42.mjs";
21
- import "./chunk-NTHVNXFC.mjs";
22
- import {
23
- server_entry_template_default
24
- } from "./chunk-6IJ5UJ3N.mjs";
25
-
26
1
  // src/index.ts
27
- import fs from "fs";
28
- import path from "path";
2
+ import fs4 from "fs";
3
+ import path5 from "path";
29
4
  import crypto from "crypto";
30
5
  import anyMatch from "anymatch";
31
- import { pathToFileURL, fileURLToPath } from "url";
6
+ import { pathToFileURL } from "url";
7
+
8
+ // src/server-entry-template.ts
9
+ import path from "path";
10
+
11
+ // src/render-assets-runtime.ts
12
+ var renderAssetsRuntimeId = "\0marko-render-assets.mjs";
13
+ function getRenderAssetsRuntime(opts) {
14
+ return `${!opts.basePathVar ? "const base = import.meta.env.BASE_URL;" : `const base = globalThis.${opts.basePathVar};
15
+ if (typeof base !== "string") throw new Error("${opts.basePathVar} must be defined when using basePathVar.");
16
+ if (!base.endsWith("/")) throw new Error("${opts.basePathVar} must end with a '/' when using basePathVar.");`}
17
+ export function addAssets(g, newEntries) {
18
+ const entries = g.___viteEntries;
19
+ if (entries) {
20
+ g.___viteEntries = entries.concat(newEntries);
21
+ } else {
22
+ g.___viteEntries = newEntries;
23
+ g.___viteRenderAssets = renderAssets;
24
+ g.___viteInjectAttrs = g.cspNonce
25
+ ? \` nonce="\${g.cspNonce.replace(/"/g, "'")}"\`
26
+ : "";
27
+ ${opts.runtimeId ? `$ g.runtimeId = ${JSON.stringify(opts.runtimeId)};` : ""}
28
+ }
29
+ }
30
+
31
+ function renderAssets(slot) {
32
+ const entries = this.___viteEntries;
33
+ let html = "";
34
+
35
+ if (entries) {
36
+ const slotWrittenEntriesKey = \`___viteWrittenEntries-\${slot}\`;
37
+ const lastWrittenEntry = this[slotWrittenEntriesKey] || 0;
38
+ const writtenEntries = (this[slotWrittenEntriesKey] = entries.length);
39
+
40
+ if(!this.___flushedMBP && slot !== "head-prepend") {
41
+ this.___flushedMBP = true;
42
+
43
+ html += \`<script\${this.___viteInjectAttrs}>${opts.runtimeId ? `$mbp_${opts.runtimeId}` : "$mbp"}=\${JSON.stringify(base)}</script>\`
44
+ }
45
+
46
+ for (let i = lastWrittenEntry; i < writtenEntries; i++) {
47
+ let entry = entries[i];
48
+
49
+ if (typeof entry === "string") {
50
+ entry = __MARKO_MANIFEST__[entry] || {};
51
+ }${opts.isBuild ? "" : ` else if (slot === "head") {
52
+ // In dev mode we have is a list entries of the top level modules that need to be imported.
53
+ // To avoid FOUC we will hide the page until all of these modules are loaded.
54
+ const { preload } = entry;
55
+ if (preload) {
56
+ let sep = "";
57
+ html += \`<script\${this.___viteInjectAttrs}>((root=document.documentElement)=>{\`;
58
+ html += "root.style.visibility='hidden';";
59
+ html += "document.currentScript.remove();";
60
+ html += "Promise.allSettled([";
61
+
62
+ for (const id of preload) {
63
+ html += \`\${sep}import(\${JSON.stringify(base + id)})\`;
64
+ sep = ",";
65
+ }
66
+
67
+ html += "]).then(()=>{";
68
+ html += "root.style.visibility='';";
69
+ html +=
70
+ "if(root.getAttribute('style')==='')root.removeAttribute('style')";
71
+ html += "})})()</script>";
72
+ }
73
+ }`}
74
+
75
+ const parts = entry[slot];
76
+
77
+ if (parts) {
78
+ for (const part of parts) {
79
+ html +=
80
+ part === 0 /** InjectType.AssetAttrs */
81
+ ? this.___viteInjectAttrs
82
+ : part === 1 /** InjectType.PublicPath */
83
+ ? base
84
+ : part;
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ return html;
91
+ }
92
+ `;
93
+ }
94
+
95
+ // src/server-entry-template.ts
96
+ var server_entry_template_default = async (opts) => {
97
+ const fileNameStr = JSON.stringify(`./${path.basename(opts.fileName)}`);
98
+ return `import template from ${fileNameStr};
99
+ export * from ${fileNameStr};
100
+ import { addAssets } from "${renderAssetsRuntimeId}";
101
+
102
+ $ const g = out.global;
103
+ $ addAssets(g, [${opts.entryData.join(",")}]);
104
+
105
+ <__flush_here_and_after__>
106
+ $!{
107
+ g.___viteRenderAssets("head-prepend") +
108
+ g.___viteRenderAssets("head") +
109
+ g.___viteRenderAssets("body-prepend")
110
+ }
111
+ </__flush_here_and_after__>
112
+
113
+ <\${template} ...input/>
114
+ <init-components/>
115
+ <await-reorderer/>
116
+
117
+ <__flush_here_and_after__>
118
+ $!{g.___viteRenderAssets("body")}
119
+ </__flush_here_and_after__>
120
+ `;
121
+ };
122
+
123
+ // src/manifest-generator.ts
124
+ import { Parser } from "htmlparser2";
125
+ import { ElementType as ElementType2 } from "domelementtype";
126
+ import { DomHandler } from "domhandler";
127
+
128
+ // src/serializer.ts
129
+ import { ElementType } from "domelementtype";
130
+ var voidElements = /* @__PURE__ */ new Set([
131
+ "area",
132
+ "base",
133
+ "br",
134
+ "col",
135
+ "embed",
136
+ "hr",
137
+ "img",
138
+ "input",
139
+ "link",
140
+ "meta",
141
+ "param",
142
+ "source",
143
+ "track",
144
+ "wbr"
145
+ ]);
146
+ function serialize(basePath, nodes, preload, parts) {
147
+ let curString = parts ? parts.pop() : "";
148
+ parts ??= [];
149
+ for (const node of nodes) {
150
+ switch (node.type) {
151
+ case ElementType.Tag:
152
+ case ElementType.Style:
153
+ case ElementType.Script: {
154
+ const tag = node;
155
+ const { name } = tag;
156
+ let urlAttr;
157
+ curString += `<${name}`;
158
+ switch (tag.tagName) {
159
+ case "script":
160
+ parts.push(curString, 0 /* AssetAttrs */);
161
+ urlAttr = "src";
162
+ curString = "";
163
+ break;
164
+ case "style":
165
+ parts.push(curString, 0 /* AssetAttrs */);
166
+ curString = "";
167
+ break;
168
+ case "link":
169
+ urlAttr = "href";
170
+ if (tag.attribs.rel === "stylesheet" || tag.attribs.rel === "modulepreload" || tag.attribs.as === "style" || tag.attribs.as === "script") {
171
+ parts.push(curString, 0 /* AssetAttrs */);
172
+ curString = "";
173
+ }
174
+ break;
175
+ }
176
+ for (const attr of tag.attributes) {
177
+ if (attr.value === "") {
178
+ curString += ` ${attr.name}`;
179
+ } else if (attr.name === urlAttr) {
180
+ const id = stripBasePath(basePath, attr.value).replace(/^\.\//, "");
181
+ if (tag.name === "script") {
182
+ preload.push(id);
183
+ }
184
+ curString += ` ${attr.name}="`;
185
+ parts.push(
186
+ curString,
187
+ 1 /* PublicPath */,
188
+ id.replace(/"/g, "&#39;") + '"'
189
+ );
190
+ curString = "";
191
+ } else {
192
+ curString += ` ${attr.name}="${attr.value.replace(/"/g, "&#39;")}"`;
193
+ }
194
+ }
195
+ curString += ">";
196
+ if (tag.children.length) {
197
+ parts.push(curString);
198
+ serialize(basePath, tag.children, preload, parts);
199
+ curString = parts.pop();
200
+ }
201
+ if (!voidElements.has(name)) {
202
+ curString += `</${name}>`;
203
+ }
204
+ break;
205
+ }
206
+ case ElementType.Text: {
207
+ const text = node.data;
208
+ if (!/^\s*$/.test(text)) {
209
+ curString += text;
210
+ }
211
+ break;
212
+ }
213
+ case ElementType.Comment:
214
+ curString += `<!--${node.data}-->`;
215
+ break;
216
+ }
217
+ }
218
+ if (curString) {
219
+ parts.push(curString);
220
+ }
221
+ return parts;
222
+ }
223
+ function stripBasePath(basePath, path6) {
224
+ if (path6.startsWith(basePath))
225
+ return path6.slice(basePath.length);
226
+ return path6;
227
+ }
228
+
229
+ // src/manifest-generator.ts
230
+ var MARKER_COMMENT = "MARKO_VITE";
231
+ function generateDocManifest(basePath, rawHtml) {
232
+ return new Promise((resolve2, reject) => {
233
+ const parser = new Parser(
234
+ new DomHandler(function(err, dom) {
235
+ if (err) {
236
+ return reject(err);
237
+ }
238
+ const htmlChildren = dom.find(isElement).childNodes;
239
+ const preload = [];
240
+ const headPrepend = [];
241
+ const head = [];
242
+ const bodyPrepend = [];
243
+ const body = [];
244
+ splitNodesByMarker(
245
+ htmlChildren.find(
246
+ (node) => isElement(node) && node.tagName === "head"
247
+ ).childNodes,
248
+ headPrepend,
249
+ head
250
+ );
251
+ splitNodesByMarker(
252
+ htmlChildren.find(
253
+ (node) => isElement(node) && node.tagName === "body"
254
+ ).childNodes,
255
+ bodyPrepend,
256
+ body
257
+ );
258
+ resolve2({
259
+ preload,
260
+ "head-prepend": serializeOrNull(basePath, headPrepend, preload),
261
+ head: serializeOrNull(basePath, head, preload),
262
+ "body-prepend": serializeOrNull(basePath, bodyPrepend, preload),
263
+ body: serializeOrNull(basePath, body, preload)
264
+ });
265
+ })
266
+ );
267
+ parser.write(rawHtml);
268
+ parser.end();
269
+ });
270
+ }
271
+ function generateInputDoc(entry) {
272
+ return `<!DOCTYPE html><html><head><!--${MARKER_COMMENT}--></head><body><!--${MARKER_COMMENT}--><script async type="module" src=${JSON.stringify(
273
+ entry
274
+ )}></script></body></html>`;
275
+ }
276
+ function serializeOrNull(basePath, nodes, preload) {
277
+ const result = serialize(basePath, nodes, preload);
278
+ if (result.length) {
279
+ return result;
280
+ }
281
+ return null;
282
+ }
283
+ function splitNodesByMarker(nodes, before, after) {
284
+ for (let i = 0; i < nodes.length; i++) {
285
+ let node = nodes[i];
286
+ if (node.data === MARKER_COMMENT) {
287
+ i++;
288
+ for (; i < nodes.length; i++) {
289
+ node = nodes[i];
290
+ after.push(node);
291
+ }
292
+ break;
293
+ }
294
+ before.push(node);
295
+ }
296
+ }
297
+ function isElement(node) {
298
+ return node.type === ElementType2.Tag;
299
+ }
300
+
301
+ // src/esbuild-plugin.ts
302
+ import fs from "fs";
303
+ import path2 from "path";
304
+ var markoErrorRegExp = /^(.+?)(?:\((\d+)(?:\s*,\s*(\d+))?\))?: (.*)$/gm;
305
+ function esbuildPlugin(compiler, config) {
306
+ return {
307
+ name: "marko",
308
+ async setup(build) {
309
+ const { platform = "browser" } = build.initialOptions;
310
+ const isScan = build.initialOptions.plugins?.some(
311
+ (v) => v.name === "vite:dep-scan"
312
+ );
313
+ const virtualFiles2 = /* @__PURE__ */ new Map();
314
+ const finalConfig = {
315
+ ...config,
316
+ output: isScan ? "hydrate" : platform === "browser" ? "dom" : "html",
317
+ resolveVirtualDependency(from, dep) {
318
+ virtualFiles2.set(path2.join(from, "..", dep.virtualPath), dep);
319
+ return dep.virtualPath;
320
+ }
321
+ };
322
+ build.onResolve({ filter: /\.marko\./ }, (args) => {
323
+ return {
324
+ namespace: "marko:virtual",
325
+ path: path2.resolve(args.resolveDir, args.path),
326
+ external: isScan
327
+ };
328
+ });
329
+ build.onLoad(
330
+ { filter: /\.marko\./, namespace: "marko:virtual" },
331
+ (args) => ({
332
+ contents: virtualFiles2.get(args.path).code,
333
+ loader: path2.extname(args.path).slice(1)
334
+ })
335
+ );
336
+ build.onLoad({ filter: /\.marko$/ }, async (args) => {
337
+ try {
338
+ const { code, meta } = await compiler.compileFile(
339
+ args.path,
340
+ finalConfig
341
+ );
342
+ return {
343
+ loader: "js",
344
+ contents: code,
345
+ watchFiles: meta.watchFiles,
346
+ resolveDir: path2.dirname(args.path)
347
+ };
348
+ } catch (e) {
349
+ const text = e.message;
350
+ const errors = [];
351
+ let match;
352
+ let lines;
353
+ while (match = markoErrorRegExp.exec(text)) {
354
+ const [, file, rawLine, rawCol, text2] = match;
355
+ const line = parseInt(rawLine, 10) || 1;
356
+ const column = parseInt(rawCol, 10) || 1;
357
+ lines ||= (await fs.promises.readFile(args.path, "utf-8")).split(
358
+ /\n/g
359
+ );
360
+ errors.push({
361
+ text: text2,
362
+ location: {
363
+ file,
364
+ line,
365
+ column,
366
+ lineText: ` ${lines[line - 1]}`
367
+ }
368
+ });
369
+ }
370
+ if (!errors.length) {
371
+ errors.push({ text });
372
+ }
373
+ return {
374
+ errors
375
+ };
376
+ }
377
+ });
378
+ }
379
+ };
380
+ }
381
+
382
+ // src/babel-plugin-cjs-interop.ts
383
+ import * as t from "@babel/types";
384
+
385
+ // src/resolve.ts
386
+ import { exports } from "resolve.exports";
387
+ import Resolve from "resolve";
388
+ import path3 from "path";
389
+ import fs2 from "fs";
390
+ var exportsMainFile = `__package_exports__`;
391
+ var modulePathReg = /^.*[/\\]node_modules[/\\](?:@[^/\\]+[/\\])?[^/\\]+[/\\]/;
392
+ var cjsModuleLookup = /* @__PURE__ */ new Map();
393
+ function isCJSModule(id) {
394
+ const modulePath = modulePathReg.exec(id)?.[0];
395
+ if (modulePath) {
396
+ const pkgPath = modulePath + "package.json";
397
+ let isCJS = cjsModuleLookup.get(pkgPath);
398
+ if (isCJS === void 0) {
399
+ try {
400
+ const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
401
+ isCJS = pkg.type !== "module" && !pkg.exports;
402
+ } catch {
403
+ isCJS = false;
404
+ }
405
+ cjsModuleLookup.set(pkgPath, isCJS);
406
+ }
407
+ return isCJS;
408
+ }
409
+ return false;
410
+ }
411
+ function resolve(id, from, extensions, conditions) {
412
+ return Resolve.sync(id, {
413
+ basedir: path3.dirname(from),
414
+ filename: from,
415
+ pathFilter,
416
+ packageFilter,
417
+ extensions
418
+ });
419
+ function pathFilter(pkg, pkgFile, relativePath) {
420
+ cjsModuleLookup.set(pkgFile, pkg.type !== "module" && !pkg.exports);
421
+ if (pkg.exports) {
422
+ return exports(
423
+ pkg,
424
+ relativePath === exportsMainFile ? "." : relativePath,
425
+ {
426
+ conditions
427
+ }
428
+ )?.[0];
429
+ }
430
+ return relativePath;
431
+ }
432
+ }
433
+ function packageFilter(pkg) {
434
+ if (pkg.exports) {
435
+ pkg.main = exportsMainFile;
436
+ }
437
+ return pkg;
438
+ }
439
+
440
+ // src/babel-plugin-cjs-interop.ts
441
+ function plugin(options) {
442
+ return {
443
+ name: "marko-import-interop",
444
+ visitor: {
445
+ ImportDeclaration(path6) {
446
+ if (!path6.node.specifiers.length || /\.(?:mjs|marko)$|\?/.test(path6.node.source.value)) {
447
+ return;
448
+ }
449
+ try {
450
+ const resolved = resolve(
451
+ path6.node.source.value,
452
+ path6.hub.file.opts.filename,
453
+ options.extensions,
454
+ options.conditions
455
+ );
456
+ if (!/\.c?js$/.test(resolved) || !isCJSModule(resolved)) {
457
+ return;
458
+ }
459
+ } catch (_) {
460
+ return;
461
+ }
462
+ let namespaceId;
463
+ let defaultImportId;
464
+ let imports;
465
+ for (const s of path6.node.specifiers) {
466
+ if (t.isImportSpecifier(s)) {
467
+ (imports ||= []).push({
468
+ name: t.isStringLiteral(s.imported) ? s.imported.value : s.imported.name,
469
+ alias: s.local.name
470
+ });
471
+ } else if (t.isImportDefaultSpecifier(s)) {
472
+ defaultImportId = s.local;
473
+ } else if (t.isImportNamespaceSpecifier(s)) {
474
+ namespaceId = s.local;
475
+ }
476
+ }
477
+ namespaceId ||= path6.scope.generateUidIdentifier(
478
+ defaultImportId?.name || path6.node.source.value
479
+ );
480
+ path6.node.specifiers = [t.importDefaultSpecifier(namespaceId)];
481
+ if (defaultImportId) {
482
+ path6.insertAfter(
483
+ t.variableDeclaration("const", [
484
+ t.variableDeclarator(
485
+ defaultImportId,
486
+ t.conditionalExpression(
487
+ t.optionalMemberExpression(
488
+ namespaceId,
489
+ t.identifier("__esModule"),
490
+ false,
491
+ true
492
+ ),
493
+ t.memberExpression(namespaceId, t.identifier("default")),
494
+ namespaceId
495
+ )
496
+ )
497
+ ])
498
+ );
499
+ }
500
+ if (imports) {
501
+ path6.insertAfter(
502
+ t.variableDeclaration("const", [
503
+ t.variableDeclarator(
504
+ t.objectPattern(
505
+ imports.map(
506
+ ({ name, alias }) => t.objectProperty(
507
+ t.identifier(name),
508
+ t.identifier(alias),
509
+ false,
510
+ name === alias
511
+ )
512
+ )
513
+ ),
514
+ namespaceId
515
+ )
516
+ ])
517
+ );
518
+ }
519
+ }
520
+ }
521
+ };
522
+ }
523
+
524
+ // src/render-assets-transform.ts
525
+ var render_assets_transform_default = (tag, t2) => {
526
+ const body = tag.get("body");
527
+ const tagName = tag.get("name").node.value;
528
+ body.unshiftContainer("body", renderAssetsCall(t2, `${tagName}-prepend`));
529
+ body.pushContainer("body", renderAssetsCall(t2, tagName));
530
+ };
531
+ function renderAssetsCall(t2, slot) {
532
+ return t2.markoPlaceholder(
533
+ t2.callExpression(
534
+ t2.memberExpression(
535
+ t2.memberExpression(t2.identifier("out"), t2.identifier("global")),
536
+ t2.identifier("___viteRenderAssets")
537
+ ),
538
+ [t2.stringLiteral(slot)]
539
+ ),
540
+ false
541
+ );
542
+ }
543
+
544
+ // src/read-once-persisted-store.ts
545
+ import os from "os";
546
+ import path4 from "path";
547
+ import { promises as fs3 } from "fs";
548
+ var noop = () => {
549
+ };
550
+ var tmpFile = path4.join(os.tmpdir(), "marko-vite-storage.json");
551
+ var values = /* @__PURE__ */ new Map();
552
+ var loadedFromDisk;
553
+ var ReadOncePersistedStore = class {
554
+ constructor(uid) {
555
+ this.uid = uid;
556
+ }
557
+ write(value) {
558
+ values.set(this.uid, value);
559
+ }
560
+ async read() {
561
+ const { uid } = this;
562
+ if (values.has(uid)) {
563
+ const value = values.get(uid);
564
+ values.delete(uid);
565
+ return value;
566
+ }
567
+ if (loadedFromDisk === true) {
568
+ throw new Error(`Value for ${uid} could not be loaded.`);
569
+ }
570
+ await (loadedFromDisk ||= fs3.readFile(tmpFile, "utf-8").then(syncDataFromDisk).catch(finishLoadFromDisk));
571
+ return this.read();
572
+ }
573
+ };
574
+ function syncDataFromDisk(data) {
575
+ finishLoadFromDisk();
576
+ fs3.unlink(tmpFile).catch(noop);
577
+ for (const [k, v] of JSON.parse(data)) {
578
+ values.set(k, v);
579
+ }
580
+ }
581
+ function finishLoadFromDisk() {
582
+ loadedFromDisk = true;
583
+ }
584
+ process.once("beforeExit", (code) => {
585
+ if (code === 0 && values.size) {
586
+ fs3.writeFile(tmpFile, JSON.stringify([...values])).catch(noop);
587
+ }
588
+ });
589
+
590
+ // src/index.ts
32
591
  var POSIX_SEP = "/";
33
592
  var WINDOWS_SEP = "\\";
34
- var normalizePath = path.sep === WINDOWS_SEP ? (id) => id.replace(/\\/g, POSIX_SEP) : (id) => id;
593
+ var normalizePath = path5.sep === WINDOWS_SEP ? (id) => id.replace(/\\/g, POSIX_SEP) : (id) => id;
35
594
  var virtualFiles = /* @__PURE__ */ new Map();
36
595
  var queryReg = /\?marko-[^?]+$/;
37
596
  var browserEntryQuery = "?marko-browser-entry";
38
597
  var serverEntryQuery = "?marko-server-entry";
39
598
  var virtualFileQuery = "?marko-virtual";
40
599
  var browserQuery = "?marko-browser";
41
- var manifestFileName = "manifest.json";
42
600
  var markoExt = ".marko";
43
601
  var htmlExt = ".html";
44
602
  var resolveOpts = { skipSelf: true };
45
603
  var cache = /* @__PURE__ */ new Map();
46
- var thisFile = typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url);
47
604
  var babelCaller = {
48
605
  name: "@marko/vite",
49
606
  supportsStaticESM: true,
@@ -51,7 +608,7 @@ var babelCaller = {
51
608
  supportsTopLevelAwait: true,
52
609
  supportsExportNamespaceFrom: true
53
610
  };
54
- var registeredTag = false;
611
+ var registeredTagLib = false;
55
612
  function markoPlugin(opts = {}) {
56
613
  let compiler;
57
614
  let { linked = true } = opts;
@@ -64,7 +621,7 @@ function markoPlugin(opts = {}) {
64
621
  let hydrateConfig;
65
622
  const resolveVirtualDependency = (from, dep) => {
66
623
  const normalizedFrom = normalizePath(from);
67
- const query = `${virtualFileQuery}&id=${Buffer.from(dep.virtualPath).toString("base64url") + path.extname(dep.virtualPath)}`;
624
+ const query = `${virtualFileQuery}&id=${Buffer.from(dep.virtualPath).toString("base64url") + path5.extname(dep.virtualPath)}`;
68
625
  const id = normalizePath(normalizedFrom) + query;
69
626
  if (devServer) {
70
627
  const prev = virtualFiles.get(id);
@@ -73,30 +630,33 @@ function markoPlugin(opts = {}) {
73
630
  }
74
631
  }
75
632
  virtualFiles.set(id, dep);
76
- return `./${path.posix.basename(normalizedFrom) + query}`;
633
+ return `./${path5.posix.basename(normalizedFrom) + query}`;
77
634
  };
78
635
  let root;
79
636
  let devEntryFile;
80
637
  let devEntryFilePosix;
638
+ let renderAssetsRuntimeCode;
81
639
  let isTest = false;
82
640
  let isBuild = false;
83
641
  let isSSRBuild = false;
84
642
  let devServer;
85
643
  let serverManifest;
86
- let store;
87
644
  let basePath = "/";
645
+ let getMarkoAssetFns;
88
646
  const entryIds = /* @__PURE__ */ new Set();
89
647
  const cachedSources = /* @__PURE__ */ new Map();
90
648
  const transformWatchFiles = /* @__PURE__ */ new Map();
91
649
  const transformOptionalFiles = /* @__PURE__ */ new Map();
650
+ const store = new ReadOncePersistedStore(
651
+ `vite-marko${runtimeId ? `-${runtimeId}` : ""}`
652
+ );
92
653
  return [
93
654
  {
94
655
  name: "marko-vite:pre",
95
656
  enforce: "pre",
96
657
  // Must be pre to allow us to resolve assets before vite.
97
658
  async config(config, env) {
98
- var _a, _b, _c, _d, _e;
99
- compiler ?? (compiler = await import(opts.compiler || "@marko/compiler"));
659
+ compiler ??= await import(opts.compiler || "@marko/compiler");
100
660
  runtimeId = opts.runtimeId;
101
661
  basePathVar = opts.basePathVar;
102
662
  baseConfig = {
@@ -138,53 +698,48 @@ function markoPlugin(opts = {}) {
138
698
  };
139
699
  compiler.configure(baseConfig);
140
700
  root = normalizePath(config.root || process.cwd());
141
- devEntryFile = path.join(root, "index.html");
701
+ devEntryFile = path5.join(root, "index.html");
142
702
  devEntryFilePosix = normalizePath(devEntryFile);
143
703
  isTest = env.mode === "test";
144
704
  isBuild = env.command === "build";
145
705
  isSSRBuild = isBuild && linked && Boolean(config.build.ssr);
146
- store = opts.store || new FileStore(
147
- `marko-vite-${crypto.createHash("SHA1").update(root).digest("hex")}`
148
- );
706
+ renderAssetsRuntimeCode = getRenderAssetsRuntime({
707
+ isBuild,
708
+ basePathVar,
709
+ runtimeId
710
+ });
149
711
  if (isTest) {
150
712
  linked = false;
151
- if ((_b = (_a = config.test) == null ? void 0 : _a.environment) == null ? void 0 : _b.includes(
713
+ if (config.test?.environment?.includes(
152
714
  "dom"
153
715
  )) {
154
- config.resolve ?? (config.resolve = {});
155
- (_c = config.resolve).conditions ?? (_c.conditions = []);
716
+ config.resolve ??= {};
717
+ config.resolve.conditions ??= [];
156
718
  config.resolve.conditions.push("browser");
157
719
  }
158
720
  }
159
- if (!registeredTag) {
160
- const transformer = path.resolve(
161
- thisFile,
162
- "../render-assets-transform"
163
- );
164
- registeredTag = normalizePath(
165
- path.resolve(thisFile, "../components", "vite.marko")
166
- );
721
+ if (!registeredTagLib) {
722
+ registeredTagLib = true;
167
723
  compiler.taglib.register("@marko/vite", {
168
- "<_vite>": { template: registeredTag },
169
- "<head>": { transformer },
170
- "<body>": { transformer }
724
+ "<head>": { transformer: render_assets_transform_default },
725
+ "<body>": { transformer: render_assets_transform_default }
171
726
  });
172
727
  }
173
- const optimizeDeps = config.optimizeDeps ?? (config.optimizeDeps = {});
174
- optimizeDeps.entries ?? (optimizeDeps.entries = [
728
+ const optimizeDeps = config.optimizeDeps ??= {};
729
+ optimizeDeps.entries ??= [
175
730
  "**/*.marko",
176
731
  "!**/__snapshots__/**",
177
732
  `!**/__tests__/**`,
178
733
  `!**/coverage/**`
179
- ]);
734
+ ];
180
735
  const domDeps = compiler.getRuntimeEntryFiles("dom", opts.translator);
181
736
  optimizeDeps.include = optimizeDeps.include ? [...optimizeDeps.include, ...domDeps] : domDeps;
182
- const optimizeExtensions = optimizeDeps.extensions ?? (optimizeDeps.extensions = []);
737
+ const optimizeExtensions = optimizeDeps.extensions ??= [];
183
738
  optimizeExtensions.push(".marko");
184
- const esbuildOptions = optimizeDeps.esbuildOptions ?? (optimizeDeps.esbuildOptions = {});
185
- const esbuildPlugins = esbuildOptions.plugins ?? (esbuildOptions.plugins = []);
739
+ const esbuildOptions = optimizeDeps.esbuildOptions ??= {};
740
+ const esbuildPlugins = esbuildOptions.plugins ??= [];
186
741
  esbuildPlugins.push(esbuildPlugin(compiler, baseConfig));
187
- const ssr = config.ssr ?? (config.ssr = {});
742
+ const ssr = config.ssr ??= {};
188
743
  let { noExternal } = ssr;
189
744
  if (noExternal !== true) {
190
745
  const noExternalReg = /\.marko$/;
@@ -199,13 +754,13 @@ function markoPlugin(opts = {}) {
199
754
  }
200
755
  }
201
756
  if (basePathVar) {
202
- config.experimental ?? (config.experimental = {});
757
+ config.experimental ??= {};
203
758
  if (config.experimental.renderBuiltUrl) {
204
759
  throw new Error(
205
760
  "Cannot use @marko/vite `basePathVar` with Vite's `renderBuiltUrl` option."
206
761
  );
207
762
  }
208
- const assetsDir = ((_e = (_d = config.build) == null ? void 0 : _d.assetsDir) == null ? void 0 : _e.replace(/[/\\]$/, "")) ?? "assets";
763
+ const assetsDir = config.build?.assetsDir?.replace(/[/\\]$/, "") ?? "assets";
209
764
  const assetsDirLen = assetsDir.length;
210
765
  const assetsDirEnd = assetsDirLen + 1;
211
766
  const trimAssertsDir = (fileName) => {
@@ -247,6 +802,17 @@ function markoPlugin(opts = {}) {
247
802
  )
248
803
  }
249
804
  };
805
+ getMarkoAssetFns = void 0;
806
+ for (const plugin2 of config.plugins) {
807
+ const fn = plugin2.api?.getMarkoAssetCodeForEntry;
808
+ if (fn) {
809
+ if (getMarkoAssetFns) {
810
+ getMarkoAssetFns.push(fn);
811
+ } else {
812
+ getMarkoAssetFns = [fn];
813
+ }
814
+ }
815
+ }
250
816
  },
251
817
  configureServer(_server) {
252
818
  ssrConfig.hot = domConfig.hot = true;
@@ -284,12 +850,10 @@ function markoPlugin(opts = {}) {
284
850
  async buildStart(inputOptions) {
285
851
  if (isBuild && linked && !isSSRBuild) {
286
852
  try {
287
- serverManifest = JSON.parse(
288
- await store.get(manifestFileName)
289
- );
853
+ serverManifest = await store.read();
290
854
  inputOptions.input = toHTMLEntries(root, serverManifest.entries);
291
855
  for (const entry in serverManifest.entrySources) {
292
- const id = normalizePath(path.resolve(root, entry));
856
+ const id = normalizePath(path5.resolve(root, entry));
293
857
  entryIds.add(id);
294
858
  cachedSources.set(id, serverManifest.entrySources[entry]);
295
859
  }
@@ -304,10 +868,12 @@ function markoPlugin(opts = {}) {
304
868
  }
305
869
  },
306
870
  async resolveId(importee, importer, importOpts, ssr = importOpts.ssr) {
307
- var _a;
308
871
  if (virtualFiles.has(importee)) {
309
872
  return importee;
310
873
  }
874
+ if (importee === renderAssetsRuntimeId) {
875
+ return { id: renderAssetsRuntimeId };
876
+ }
311
877
  let importeeQuery = getMarkoQuery(importee);
312
878
  if (importeeQuery) {
313
879
  importee = importee.slice(0, -importeeQuery.length);
@@ -315,7 +881,7 @@ function markoPlugin(opts = {}) {
315
881
  if (ssr && linked && importer && (importer !== devEntryFile || normalizePath(importer) !== devEntryFilePosix) && // Vite tries to resolve against an `index.html` in some cases, we ignore it here.
316
882
  isMarkoFile(importee) && !isMarkoFile(importer.replace(queryReg, ""))) {
317
883
  importeeQuery = serverEntryQuery;
318
- } else if (!ssr && isBuild && importer && isMarkoFile(importee) && ((_a = this.getModuleInfo(importer)) == null ? void 0 : _a.isEntry)) {
884
+ } else if (!ssr && isBuild && importer && isMarkoFile(importee) && this.getModuleInfo(importer)?.isEntry) {
319
885
  importeeQuery = browserEntryQuery;
320
886
  } else if (linked && !ssr && !importeeQuery && isMarkoFile(importee)) {
321
887
  importeeQuery = browserQuery;
@@ -324,7 +890,7 @@ function markoPlugin(opts = {}) {
324
890
  if (importeeQuery) {
325
891
  const resolved = importee[0] === "." ? {
326
892
  id: normalizePath(
327
- importer ? path.resolve(importer, "..", importee) : path.resolve(root, importee)
893
+ importer ? path5.resolve(importer, "..", importee) : path5.resolve(root, importee)
328
894
  )
329
895
  } : await this.resolve(importee, importer, resolveOpts);
330
896
  if (resolved) {
@@ -338,7 +904,7 @@ function markoPlugin(opts = {}) {
338
904
  importer = importer.slice(0, -importerQuery.length);
339
905
  if (importee[0] === ".") {
340
906
  const resolved = normalizePath(
341
- path.resolve(importer, "..", importee)
907
+ path5.resolve(importer, "..", importee)
342
908
  );
343
909
  if (resolved === normalizePath(importer))
344
910
  return resolved;
@@ -350,6 +916,9 @@ function markoPlugin(opts = {}) {
350
916
  },
351
917
  async load(rawId) {
352
918
  const id = stripVersionAndTimeStamp(rawId);
919
+ if (id === renderAssetsRuntimeId) {
920
+ return renderAssetsRuntimeCode;
921
+ }
353
922
  const query = getMarkoQuery(id);
354
923
  switch (query) {
355
924
  case serverEntryQuery: {
@@ -371,22 +940,22 @@ function markoPlugin(opts = {}) {
371
940
  id = id.slice(0, -query.length);
372
941
  if (query === serverEntryQuery) {
373
942
  const fileName = id;
374
- let entryData;
943
+ let mainEntryData;
375
944
  id = `${id.slice(0, -markoExt.length)}.entry.marko`;
376
945
  cachedSources.set(fileName, source);
377
946
  if (isBuild) {
378
- const relativeFileName = path.posix.relative(root, fileName);
947
+ const relativeFileName = path5.posix.relative(root, fileName);
379
948
  const entryId = toEntryId(relativeFileName);
380
- serverManifest ?? (serverManifest = {
949
+ serverManifest ??= {
381
950
  entries: {},
382
951
  entrySources: {},
383
952
  chunksNeedingAssets: []
384
- });
953
+ };
385
954
  serverManifest.entries[entryId] = relativeFileName;
386
955
  serverManifest.entrySources[relativeFileName] = source;
387
- entryData = JSON.stringify(entryId);
956
+ mainEntryData = JSON.stringify(entryId);
388
957
  } else {
389
- entryData = JSON.stringify(
958
+ mainEntryData = JSON.stringify(
390
959
  await generateDocManifest(
391
960
  basePath,
392
961
  await devServer.transformIndexHtml(
@@ -398,6 +967,15 @@ function markoPlugin(opts = {}) {
398
967
  )
399
968
  );
400
969
  }
970
+ const entryData = [mainEntryData];
971
+ if (getMarkoAssetFns) {
972
+ for (const getMarkoAsset of getMarkoAssetFns) {
973
+ const asset = getMarkoAsset(fileName);
974
+ if (asset) {
975
+ entryData.push(asset);
976
+ }
977
+ }
978
+ }
401
979
  source = await server_entry_template_default({
402
980
  fileName,
403
981
  entryData,
@@ -500,7 +1078,7 @@ if (import.meta.hot) import.meta.hot.accept(() => {});`;
500
1078
  }
501
1079
  if (devServer) {
502
1080
  const templateName = getPosixBasenameWithoutExt(id);
503
- const optionalFilePrefix = path.dirname(id) + path.sep + (templateName === "index" ? "" : `${templateName}.`);
1081
+ const optionalFilePrefix = path5.dirname(id) + path5.sep + (templateName === "index" ? "" : `${templateName}.`);
504
1082
  for (const file of meta.watchFiles) {
505
1083
  this.addWatchFile(file);
506
1084
  }
@@ -535,39 +1113,35 @@ if (import.meta.hot) import.meta.hot.accept(() => {});`;
535
1113
  );
536
1114
  }
537
1115
  if (isSSRBuild) {
538
- const dir = outputOptions.dir ? path.resolve(outputOptions.dir) : path.resolve(outputOptions.file, "..");
1116
+ const dir = outputOptions.dir ? path5.resolve(outputOptions.dir) : path5.resolve(outputOptions.file, "..");
539
1117
  for (const fileName in bundle) {
540
1118
  const chunk = bundle[fileName];
541
1119
  if (chunk.type === "chunk") {
542
1120
  for (const id in chunk.modules) {
543
- if (id === registeredTag) {
1121
+ if (id.endsWith(serverEntryQuery)) {
544
1122
  serverManifest.chunksNeedingAssets.push(
545
- path.resolve(dir, fileName)
1123
+ path5.resolve(dir, fileName)
546
1124
  );
547
1125
  break;
548
1126
  }
549
1127
  }
550
1128
  }
551
1129
  }
552
- await store.set(manifestFileName, JSON.stringify(serverManifest));
1130
+ store.write(serverManifest);
553
1131
  } else {
554
1132
  const browserManifest = {};
555
1133
  for (const entryId in serverManifest.entries) {
556
1134
  const fileName = serverManifest.entries[entryId];
557
- let chunkId = fileName + htmlExt;
558
- let chunk = bundle[chunkId];
559
- if (!chunk) {
560
- chunkId = chunkId.replace(/\//g, "\\");
561
- chunk = bundle[chunkId];
562
- }
563
- if ((chunk == null ? void 0 : chunk.type) === "asset") {
1135
+ const chunkId = fileName + htmlExt;
1136
+ const chunk = bundle[chunkId];
1137
+ if (chunk?.type === "asset") {
564
1138
  browserManifest[entryId] = {
565
1139
  ...await generateDocManifest(
566
1140
  basePath,
567
1141
  chunk.source.toString()
568
1142
  ),
569
- entries: void 0
570
- // clear out entries for prod builds.
1143
+ preload: void 0
1144
+ // clear out preload for prod builds.
571
1145
  };
572
1146
  delete bundle[chunkId];
573
1147
  } else {
@@ -581,7 +1155,7 @@ if (import.meta.hot) import.meta.hot.accept(() => {});`;
581
1155
  )};
582
1156
  `;
583
1157
  for (const fileName of serverManifest.chunksNeedingAssets) {
584
- await fs.promises.appendFile(fileName, manifestStr);
1158
+ await fs4.promises.appendFile(fileName, manifestStr);
585
1159
  }
586
1160
  }
587
1161
  }
@@ -589,8 +1163,7 @@ if (import.meta.hot) import.meta.hot.accept(() => {});`;
589
1163
  ];
590
1164
  }
591
1165
  function getMarkoQuery(id) {
592
- var _a;
593
- return ((_a = queryReg.exec(id)) == null ? void 0 : _a[0]) || "";
1166
+ return queryReg.exec(id)?.[0] || "";
594
1167
  }
595
1168
  function isMarkoFile(id) {
596
1169
  return id.endsWith(markoExt);
@@ -598,7 +1171,7 @@ function isMarkoFile(id) {
598
1171
  function toHTMLEntries(root, serverEntries) {
599
1172
  const result = [];
600
1173
  for (const id in serverEntries) {
601
- const markoFile = path.posix.join(root, serverEntries[id]);
1174
+ const markoFile = path5.posix.join(root, serverEntries[id]);
602
1175
  const htmlFile = markoFile + htmlExt;
603
1176
  virtualFiles.set(htmlFile, {
604
1177
  code: generateInputDoc(markoFile + browserEntryQuery)
@@ -619,7 +1192,7 @@ function toEntryId(id) {
619
1192
  return `${name}_${crypto.createHash("SHA1").update(id).digest("base64").replace(/[/+]/g, "-").slice(0, 4)}`;
620
1193
  }
621
1194
  function posixFileNameToURL(fileName, root) {
622
- const relativeURL = path.posix.relative(
1195
+ const relativeURL = path5.posix.relative(
623
1196
  pathToFileURL(root).pathname,
624
1197
  pathToFileURL(fileName).pathname
625
1198
  );
@@ -636,18 +1209,18 @@ function getPosixBasenameWithoutExt(file) {
636
1209
  return file.slice(baseStart, extStart);
637
1210
  }
638
1211
  function createDeferredPromise() {
639
- let resolve;
1212
+ let resolve2;
640
1213
  let reject;
641
1214
  const promise = new Promise((res, rej) => {
642
- resolve = res;
1215
+ resolve2 = res;
643
1216
  reject = rej;
644
1217
  });
645
- promise.resolve = resolve;
1218
+ promise.resolve = resolve2;
646
1219
  promise.reject = reject;
647
1220
  return promise;
648
1221
  }
649
1222
  function isDeferredPromise(obj) {
650
- return typeof (obj == null ? void 0 : obj.then) === "function";
1223
+ return typeof obj?.then === "function";
651
1224
  }
652
1225
  function isEmpty(obj) {
653
1226
  for (const _ in obj) {
@@ -666,7 +1239,5 @@ function stripVersionAndTimeStamp(id) {
666
1239
  return url;
667
1240
  }
668
1241
  export {
669
- FileStore,
670
- MemoryStore,
671
1242
  markoPlugin as default
672
1243
  };