@marko/run 0.2.18 → 0.3.1

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.
@@ -28,10 +28,13 @@ var __privateSet = (obj, member, value, setter) => {
28
28
  import sade from "sade";
29
29
 
30
30
  // src/cli/commands.ts
31
- import path3 from "path";
32
- import fs4 from "fs";
31
+ import path4 from "path";
32
+ import fs5 from "fs";
33
33
  import { fileURLToPath as fileURLToPath2 } from "url";
34
- import { build as viteBuild, resolveConfig } from "vite";
34
+ import {
35
+ build as viteBuild,
36
+ resolveConfig
37
+ } from "vite";
35
38
 
36
39
  // src/vite/utils/config.ts
37
40
  var PluginConfigKey = "__MARKO_RUN_PLUGIN_CONFIG__";
@@ -48,9 +51,6 @@ var setExternalPluginOptions = (viteConfig, value) => setConfig(viteConfig, Plug
48
51
  var getExternalAdapterOptions = (viteConfig) => getConfig(viteConfig, AdapterConfigKey);
49
52
  var setExternalAdapterOptions = (viteConfig, value) => setConfig(viteConfig, AdapterConfigKey, value);
50
53
 
51
- // src/cli/commands.ts
52
- import { MemoryStore } from "@marko/vite";
53
-
54
54
  // src/vite/utils/server.ts
55
55
  import net from "net";
56
56
  import cp from "child_process";
@@ -83,15 +83,14 @@ async function getAvailablePort(port) {
83
83
  }
84
84
 
85
85
  // src/vite/plugin.ts
86
- import path2 from "path";
87
- import crypto from "crypto";
88
- import fs3 from "fs";
86
+ import path3 from "path";
87
+ import fs4 from "fs";
89
88
  import { glob } from "glob";
90
89
  import { fileURLToPath } from "url";
91
90
  import browserslist from "browserslist";
92
91
  import { resolveToEsbuildTarget } from "esbuild-plugin-browserslist";
93
92
  import { mergeConfig } from "vite";
94
- import markoVitePlugin, { FileStore } from "@marko/vite";
93
+ import markoVitePlugin from "@marko/vite";
95
94
 
96
95
  // src/vite/constants.ts
97
96
  var markoRunFilePrefix = "__marko-run__";
@@ -172,10 +171,10 @@ var _VDir = class _VDir {
172
171
  });
173
172
  return value;
174
173
  }
175
- addDir(path4, segment) {
174
+ addDir(path5, segment) {
176
175
  const map = segment.type === "_" ? __privateGet(this, _pathlessDirs) ?? __privateSet(this, _pathlessDirs, /* @__PURE__ */ new Map()) : __privateGet(this, _dirs) ?? __privateSet(this, _dirs, /* @__PURE__ */ new Map());
177
176
  if (!map.has(segment.name)) {
178
- const dir = new _VDir(this, segment, path4);
177
+ const dir = new _VDir(this, segment, path5);
179
178
  map.set(segment.name, dir);
180
179
  return dir;
181
180
  }
@@ -221,10 +220,10 @@ var _VDir = class _VDir {
221
220
  const dirs = [];
222
221
  const unique = /* @__PURE__ */ new Set();
223
222
  for (const root of roots) {
224
- for (const path4 of paths) {
223
+ for (const path5 of paths) {
225
224
  let dir = root;
226
- for (const segment of path4.segments) {
227
- dir = dir.addDir(path4, segment);
225
+ for (const segment of path5.segments) {
226
+ dir = dir.addDir(path5, segment);
228
227
  }
229
228
  if (unique.has(dir.path)) {
230
229
  const sources = /* @__PURE__ */ new Set();
@@ -236,7 +235,7 @@ var _VDir = class _VDir {
236
235
  }
237
236
  }
238
237
  throw new Error(
239
- `Ambiguous directory structure: '${sourcePath}${path4.source}' defines '${dir.path}' multiple times.`
238
+ `Ambiguous directory structure: '${sourcePath}${path5.source}' defines '${dir.path}' multiple times.`
240
239
  );
241
240
  } else {
242
241
  unique.add(dir.path);
@@ -278,9 +277,9 @@ function parseFlatRoute(pattern) {
278
277
  } else if (charCode === 44) {
279
278
  if (!current) {
280
279
  segmentEnd(
281
- basePaths.map((path4) => ({
282
- ...path4,
283
- segments: path4.segments.slice()
280
+ basePaths.map((path5) => ({
281
+ ...path5,
282
+ segments: path5.segments.slice()
284
283
  })),
285
284
  "",
286
285
  "_",
@@ -310,9 +309,9 @@ function parseFlatRoute(pattern) {
310
309
  } else if (charCode === 36) {
311
310
  type = pattern.charCodeAt(i + 1) === 36 ? "$$" : "$";
312
311
  }
313
- current ?? (current = basePaths.map((path4) => ({
314
- ...path4,
315
- segments: path4.segments.slice()
312
+ current ?? (current = basePaths.map((path5) => ({
313
+ ...path5,
314
+ segments: path5.segments.slice()
316
315
  })));
317
316
  i = len;
318
317
  for (const char of delimiters) {
@@ -332,9 +331,9 @@ function parseFlatRoute(pattern) {
332
331
  }
333
332
  if (!current) {
334
333
  segmentEnd(
335
- basePaths.map((path4) => ({
336
- ...path4,
337
- segments: path4.segments.slice()
334
+ basePaths.map((path5) => ({
335
+ ...path5,
336
+ segments: path5.segments.slice()
338
337
  })),
339
338
  "",
340
339
  "_",
@@ -358,9 +357,9 @@ function parseFlatRoute(pattern) {
358
357
  segment.param = raw.slice(type.length);
359
358
  }
360
359
  }
361
- for (const path4 of paths) {
360
+ for (const path5 of paths) {
362
361
  if (segment) {
363
- if (path4.isCatchall) {
362
+ if (path5.isCatchall) {
364
363
  throw new Error(
365
364
  `Invalid route pattern: nested segments are not allowed after a catch-all parameter. Found '.' following '${pattern.slice(
366
365
  0,
@@ -368,22 +367,22 @@ function parseFlatRoute(pattern) {
368
367
  )}' in '${pattern}'.`
369
368
  );
370
369
  }
371
- path4.segments.push(segment);
372
- path4.id += path4.id === "/" ? segment.name : `/${segment.name}`;
370
+ path5.segments.push(segment);
371
+ path5.id += path5.id === "/" ? segment.name : `/${segment.name}`;
373
372
  if (type === "$$") {
374
- path4.isCatchall = true;
373
+ path5.isCatchall = true;
375
374
  }
376
375
  }
377
376
  if (map) {
378
- if (map.has(path4.id)) {
379
- const existing = map.get(path4.id);
377
+ if (map.has(path5.id)) {
378
+ const existing = map.get(path5.id);
380
379
  const existingExpansion = existing.segments.map((s) => s.raw).join(".");
381
- const currentExpansion = path4.segments.map((s) => s.raw).join(".");
380
+ const currentExpansion = path5.segments.map((s) => s.raw).join(".");
382
381
  throw new Error(
383
- `Invalid route pattern: route '${path4.id}' is ambiguous. Expansion '${currentExpansion}' collides with '${existingExpansion}' in '${pattern}'.`
382
+ `Invalid route pattern: route '${path5.id}' is ambiguous. Expansion '${currentExpansion}' collides with '${existingExpansion}' in '${pattern}'.`
384
383
  );
385
384
  }
386
- map.set(path4.id, path4);
385
+ map.set(path5.id, path5);
387
386
  }
388
387
  }
389
388
  }
@@ -439,7 +438,7 @@ async function buildRoutes(sources) {
439
438
  dirStack.length = prevDirStackLength;
440
439
  };
441
440
  },
442
- onFile({ name, path: path4 }) {
441
+ onFile({ name, path: path5 }) {
443
442
  const match = name.match(routeableFileRegex);
444
443
  if (!match) {
445
444
  return;
@@ -447,7 +446,7 @@ async function buildRoutes(sources) {
447
446
  const type = (match[1] || match[3]).toLowerCase();
448
447
  if (dirStack.length && isSpecialType(type)) {
449
448
  console.warn(
450
- `Special pages '${RoutableFileTypes.NotFound}' and '${RoutableFileTypes.Error}' are only considered in the root directory - ignoring ${path4}`
449
+ `Special pages '${RoutableFileTypes.NotFound}' and '${RoutableFileTypes.Error}' are only considered in the root directory - ignoring ${path5}`
451
450
  );
452
451
  return;
453
452
  }
@@ -462,7 +461,7 @@ async function buildRoutes(sources) {
462
461
  id: String(nextFileId++),
463
462
  name,
464
463
  type,
465
- filePath: path4,
464
+ filePath: path5,
466
465
  relativePath,
467
466
  importPath: `${importPrefix}/${relativePath}`,
468
467
  verbs: type === RoutableFileTypes.Page ? ["get"] : void 0
@@ -514,23 +513,23 @@ async function buildRoutes(sources) {
514
513
  }
515
514
  }
516
515
  if (page || handler) {
517
- const path4 = dir.pathInfo;
518
- if (uniqueRoutes.has(path4.id)) {
519
- const existing = uniqueRoutes.get(path4.id);
516
+ const path5 = dir.pathInfo;
517
+ if (uniqueRoutes.has(path5.id)) {
518
+ const existing = uniqueRoutes.get(path5.id);
520
519
  const route = routes[existing.index];
521
520
  const existingFiles = [route.handler, route.page].filter(Boolean).map((f) => f.filePath);
522
521
  const currentFiles = [handler, page].filter(Boolean).map((f) => f.filePath);
523
- throw new Error(`Duplicate routes for path '${path4.path}' were defined. A route established by:
522
+ throw new Error(`Duplicate routes for path '${path5.path}' were defined. A route established by:
524
523
  ${existingFiles.join(" and ")} via '${existing.dir.path}'
525
524
  collides with
526
525
  ${currentFiles.join(" and ")} via '${dir.path}'
527
526
  `);
528
527
  }
529
- uniqueRoutes.set(path4.id, { dir, index: routes.length });
528
+ uniqueRoutes.set(path5.id, { dir, index: routes.length });
530
529
  routes.push({
531
530
  index: nextRouteIndex++,
532
531
  key: dir.fullPath,
533
- paths: [path4],
532
+ paths: [path5],
534
533
  middleware: [...currentMiddleware],
535
534
  layouts: page ? [...currentLayouts] : [],
536
535
  meta: dir.files.get(RoutableFileTypes.Meta),
@@ -1193,7 +1192,7 @@ function writeRouterVerb(writer, trie, verb, level = 0, offset = 1) {
1193
1192
  if (useSwitch) {
1194
1193
  writer.writeBlockStart(`switch (${value}) {`);
1195
1194
  }
1196
- for (const { key, path: path4, route: route2 } of terminal) {
1195
+ for (const { key, path: path5, route: route2 } of terminal) {
1197
1196
  const decodedKey = decodeURIComponent(key);
1198
1197
  if (useSwitch) {
1199
1198
  writer.write(`case '${decodedKey}': `, true);
@@ -1201,7 +1200,7 @@ function writeRouterVerb(writer, trie, verb, level = 0, offset = 1) {
1201
1200
  writer.write(`if (${value} === '${decodedKey}') `, true);
1202
1201
  }
1203
1202
  writer.write(
1204
- `return ${renderMatch(verb, route2, path4)}; // ${path4.path}
1203
+ `return ${renderMatch(verb, route2, path5)}; // ${path5.path}
1205
1204
  `
1206
1205
  );
1207
1206
  }
@@ -1306,11 +1305,11 @@ function renderParams(params, pathIndex) {
1306
1305
  }
1307
1306
  return result ? result + " }" : "{}";
1308
1307
  }
1309
- function renderMatch(verb, route, path4, pathIndex) {
1308
+ function renderMatch(verb, route, path5, pathIndex) {
1310
1309
  const handler = `${verb}${route.index}`;
1311
- const params = path4.params ? renderParams(path4.params, pathIndex) : "{}";
1310
+ const params = path5.params ? renderParams(path5.params, pathIndex) : "{}";
1312
1311
  const meta = route.meta ? `meta${route.index}` : "{}";
1313
- const pathPattern = pathToURLPatternString(path4.path);
1312
+ const pathPattern = pathToURLPatternString(path5.path);
1314
1313
  return `{ handler: ${handler}, params: ${params}, meta: ${meta}, path: '${pathPattern}' }`;
1315
1314
  }
1316
1315
  function renderMiddleware(middleware) {
@@ -1331,15 +1330,15 @@ function renderMiddleware(middleware) {
1331
1330
  imports.join();
1332
1331
  return writer.end();
1333
1332
  }
1334
- function stripTsExtension(path4) {
1335
- const index = path4.lastIndexOf(".");
1333
+ function stripTsExtension(path5) {
1334
+ const index = path5.lastIndexOf(".");
1336
1335
  if (index !== -1) {
1337
- const ext = path4.slice(index + 1);
1336
+ const ext = path5.slice(index + 1);
1338
1337
  if (ext.toLowerCase() === "ts") {
1339
- return path4.slice(0, index);
1338
+ return path5.slice(0, index);
1340
1339
  }
1341
1340
  }
1342
- return path4;
1341
+ return path5;
1343
1342
  }
1344
1343
  async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
1345
1344
  var _a, _b;
@@ -1371,8 +1370,8 @@ async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
1371
1370
  const routeTypes = /* @__PURE__ */ new Map();
1372
1371
  for (const route of routes.list) {
1373
1372
  let routeType = "";
1374
- for (const path4 of route.paths) {
1375
- const pathType = `"${pathToURLPatternString(path4.path)}"`;
1373
+ for (const path5 of route.paths) {
1374
+ const pathType = `"${pathToURLPatternString(path5.path)}"`;
1376
1375
  routeType += routeType ? " | " + pathType : pathType;
1377
1376
  routesWriter.writeLines(`${pathType}: Routes["${route.key}"];`);
1378
1377
  }
@@ -1408,22 +1407,22 @@ async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
1408
1407
  const pageWriter = writer.branch("page");
1409
1408
  const layoutWriter = writer.branch("layout");
1410
1409
  for (const [file, types] of routeTypes) {
1411
- const path4 = `${pathPrefix}/${file.relativePath}`;
1410
+ const path5 = `${pathPrefix}/${file.relativePath}`;
1412
1411
  const routeType = `Run.Routes[${types.join(" | ")}]`;
1413
1412
  switch (file.type) {
1414
1413
  case RoutableFileTypes.Handler:
1415
- writeModuleDeclaration(handlerWriter, path4, routeType);
1414
+ writeModuleDeclaration(handlerWriter, path5, routeType);
1416
1415
  break;
1417
1416
  case RoutableFileTypes.Middleware:
1418
- writeModuleDeclaration(middlewareWriter, path4, routeType);
1417
+ writeModuleDeclaration(middlewareWriter, path5, routeType);
1419
1418
  break;
1420
1419
  case RoutableFileTypes.Page:
1421
- writeModuleDeclaration(pageWriter, path4, routeType);
1420
+ writeModuleDeclaration(pageWriter, path5, routeType);
1422
1421
  break;
1423
1422
  case RoutableFileTypes.Layout:
1424
1423
  writeModuleDeclaration(
1425
1424
  layoutWriter,
1426
- path4,
1425
+ path5,
1427
1426
  routeType,
1428
1427
  `
1429
1428
  export interface Input {
@@ -1434,7 +1433,7 @@ async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
1434
1433
  case RoutableFileTypes.Error:
1435
1434
  writeModuleDeclaration(
1436
1435
  writer,
1437
- path4,
1436
+ path5,
1438
1437
  "globalThis.MarkoRun.Route",
1439
1438
  `
1440
1439
  export interface Input {
@@ -1443,7 +1442,7 @@ async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
1443
1442
  );
1444
1443
  break;
1445
1444
  case RoutableFileTypes.NotFound:
1446
- writeModuleDeclaration(writer, path4, "Run.Route");
1445
+ writeModuleDeclaration(writer, path5, "Run.Route");
1447
1446
  break;
1448
1447
  }
1449
1448
  }
@@ -1478,13 +1477,13 @@ type Routes = {`);
1478
1477
  writer.writeBlockEnd("}");
1479
1478
  return writer.end();
1480
1479
  }
1481
- function writeModuleDeclaration(writer, path4, routeType, moduleTypes) {
1482
- writer.writeLines("").write(`declare module "${stripTsExtension(path4)}" {`);
1480
+ function writeModuleDeclaration(writer, path5, routeType, moduleTypes) {
1481
+ writer.writeLines("").write(`declare module "${stripTsExtension(path5)}" {`);
1483
1482
  if (moduleTypes) {
1484
1483
  writer.write(moduleTypes);
1485
1484
  }
1486
1485
  if (routeType) {
1487
- const isMarko = path4.endsWith(".marko");
1486
+ const isMarko = path5.endsWith(".marko");
1488
1487
  writer.write(`
1489
1488
  namespace MarkoRun {
1490
1489
  export { NotHandled, NotMatched, GetPaths, PostPaths, GetablePath, GetableHref, PostablePath, PostableHref, Platform };
@@ -1497,8 +1496,8 @@ function writeModuleDeclaration(writer, path4, routeType, moduleTypes) {
1497
1496
  writer.writeLines(`
1498
1497
  }`);
1499
1498
  }
1500
- function pathToURLPatternString(path4) {
1501
- return path4.replace(/\/\$(\$?)([^\/]*)/g, (_, catchAll, name) => {
1499
+ function pathToURLPatternString(path5) {
1500
+ return path5.replace(/\/\$(\$?)([^\/]*)/g, (_, catchAll, name) => {
1502
1501
  name = decodeURIComponent(name);
1503
1502
  return catchAll ? `/:${name || "rest"}*` : `/:${name}`;
1504
1503
  });
@@ -1507,11 +1506,11 @@ function createRouteTrie(routes) {
1507
1506
  const root = {
1508
1507
  key: ""
1509
1508
  };
1510
- function insert(path4, route) {
1509
+ function insert(path5, route) {
1511
1510
  let node = root;
1512
- for (const segment of path4.segments) {
1511
+ for (const segment of path5.segments) {
1513
1512
  if (segment === "$$") {
1514
- node.catchAll ?? (node.catchAll = { route, path: path4 });
1513
+ node.catchAll ?? (node.catchAll = { route, path: path5 });
1515
1514
  return;
1516
1515
  } else if (segment === "$") {
1517
1516
  node = node.dynamic ?? (node.dynamic = {
@@ -1529,12 +1528,12 @@ function createRouteTrie(routes) {
1529
1528
  node = next;
1530
1529
  }
1531
1530
  }
1532
- node.path ?? (node.path = path4);
1531
+ node.path ?? (node.path = path5);
1533
1532
  node.route ?? (node.route = route);
1534
1533
  }
1535
1534
  for (const route of routes) {
1536
- for (const path4 of route.paths) {
1537
- insert(path4, route);
1535
+ for (const path5 of route.paths) {
1536
+ insert(path5, route);
1538
1537
  }
1539
1538
  }
1540
1539
  return root;
@@ -1624,7 +1623,7 @@ function logRoutesTable(routes, bundle, options) {
1624
1623
  style: { compact: true }
1625
1624
  });
1626
1625
  for (const route of routes.list) {
1627
- for (const path4 of route.paths) {
1626
+ for (const path5 of route.paths) {
1628
1627
  const verbs = getVerbs(route).sort(
1629
1628
  (a, b) => HttpVerbOrder[a] - HttpVerbOrder[b]
1630
1629
  );
@@ -1643,7 +1642,7 @@ function logRoutesTable(routes, bundle, options) {
1643
1642
  kleur.bold(HttpVerbColors[verb](verb.toUpperCase()))
1644
1643
  ];
1645
1644
  if (verbs.length === 1 || firstRow) {
1646
- row.push({ rowSpan: verbs.length, content: prettyPath(path4.path) });
1645
+ row.push({ rowSpan: verbs.length, content: prettyPath(path5.path) });
1647
1646
  firstRow = false;
1648
1647
  }
1649
1648
  row.push(entryType.join(" -> "));
@@ -1707,18 +1706,66 @@ function prettySize([bytes, compBytes]) {
1707
1706
  str += kleur.bold(kleur.red(compSize));
1708
1707
  return str;
1709
1708
  }
1710
- function prettyPath(path4) {
1711
- return path4.replace(/\/\$\$(.*)$/, (_, p) => "/" + kleur.bold(kleur.dim(`*${p}`))).replace(/\/\$([^/]+)/g, (_, p) => "/" + kleur.bold(kleur.dim(`:${p}`)));
1709
+ function prettyPath(path5) {
1710
+ return path5.replace(/\/\$\$(.*)$/, (_, p) => "/" + kleur.bold(kleur.dim(`*${p}`))).replace(/\/\$([^/]+)/g, (_, p) => "/" + kleur.bold(kleur.dim(`:${p}`)));
1712
1711
  }
1713
1712
 
1714
1713
  // src/vite/plugin.ts
1715
1714
  import createDebug from "debug";
1715
+
1716
+ // src/vite/utils/read-once-persisted-store.ts
1717
+ import os from "os";
1718
+ import path2 from "path";
1719
+ import { promises as fs3 } from "fs";
1720
+ var noop = () => {
1721
+ };
1722
+ var tmpFile = path2.join(os.tmpdir(), "marko-run-storage.json");
1723
+ var values = /* @__PURE__ */ new Map();
1724
+ var loadedFromDisk;
1725
+ var ReadOncePersistedStore = class {
1726
+ constructor(uid) {
1727
+ this.uid = uid;
1728
+ }
1729
+ write(value) {
1730
+ values.set(this.uid, value);
1731
+ }
1732
+ async read() {
1733
+ const { uid } = this;
1734
+ if (values.has(uid)) {
1735
+ const value = values.get(uid);
1736
+ values.delete(uid);
1737
+ return value;
1738
+ }
1739
+ if (loadedFromDisk === true) {
1740
+ throw new Error(`Value for ${uid} could not be loaded.`);
1741
+ }
1742
+ await (loadedFromDisk || (loadedFromDisk = fs3.readFile(tmpFile, "utf-8").then(syncDataFromDisk).catch(finishLoadFromDisk)));
1743
+ return this.read();
1744
+ }
1745
+ };
1746
+ function syncDataFromDisk(data) {
1747
+ finishLoadFromDisk();
1748
+ fs3.unlink(tmpFile).catch(noop);
1749
+ for (const [k, v] of JSON.parse(data)) {
1750
+ values.set(k, v);
1751
+ }
1752
+ }
1753
+ function finishLoadFromDisk() {
1754
+ loadedFromDisk = true;
1755
+ }
1756
+ process.once("beforeExit", (code) => {
1757
+ if (code === 0 && values.size) {
1758
+ fs3.writeFile(tmpFile, JSON.stringify([...values])).catch(noop);
1759
+ }
1760
+ });
1761
+
1762
+ // src/vite/plugin.ts
1716
1763
  var debug = createDebug("@marko/run");
1717
- var __dirname = path2.dirname(fileURLToPath(import.meta.url));
1764
+ var __dirname = path3.dirname(fileURLToPath(import.meta.url));
1718
1765
  var PLUGIN_NAME_PREFIX = "marko-run-vite";
1719
1766
  var POSIX_SEP = "/";
1720
1767
  var WINDOWS_SEP = "\\";
1721
- var normalizePath = path2.sep === WINDOWS_SEP ? (id) => id.replace(/\\/g, POSIX_SEP) : (id) => id;
1768
+ var normalizePath = path3.sep === WINDOWS_SEP ? (id) => id.replace(/\\/g, POSIX_SEP) : (id) => id;
1722
1769
  function markoRun(opts = {}) {
1723
1770
  let { routesDir, adapter, ...markoVitePluginOptions } = opts;
1724
1771
  let compiler;
@@ -1735,7 +1782,6 @@ function markoRun(opts = {}) {
1735
1782
  let devServer;
1736
1783
  let routes;
1737
1784
  let routeData;
1738
- let routeDataFilename = "routes.json";
1739
1785
  let extractVerbs;
1740
1786
  let resolvedConfig;
1741
1787
  let typesFile;
@@ -1751,15 +1797,15 @@ function markoRun(opts = {}) {
1751
1797
  root,
1752
1798
  "{.tsconfig*,tsconfig*.json}"
1753
1799
  )))) {
1754
- const filepath = path2.join(typesDir, "routes.d.ts");
1800
+ const filepath = path3.join(typesDir, "routes.d.ts");
1755
1801
  const data = await renderRouteTypeInfo(
1756
1802
  routes2,
1757
- normalizePath(path2.relative(typesDir, resolvedRoutesDir)),
1803
+ normalizePath(path3.relative(typesDir, resolvedRoutesDir)),
1758
1804
  adapter
1759
1805
  );
1760
- if (data !== typesFile || !fs3.existsSync(filepath)) {
1806
+ if (data !== typesFile || !fs4.existsSync(filepath)) {
1761
1807
  await ensureDir(typesDir);
1762
- await fs3.promises.writeFile(filepath, typesFile = data);
1808
+ await fs4.promises.writeFile(filepath, typesFile = data);
1763
1809
  }
1764
1810
  }
1765
1811
  }
@@ -1794,24 +1840,24 @@ function markoRun(opts = {}) {
1794
1840
  }
1795
1841
  if (route.page) {
1796
1842
  virtualFiles.set(
1797
- path2.posix.join(root, `${route.entryName}.marko`),
1843
+ path3.posix.join(root, `${route.entryName}.marko`),
1798
1844
  render ? renderRouteTemplate(route) : ""
1799
1845
  );
1800
1846
  }
1801
1847
  virtualFiles.set(
1802
- path2.posix.join(root, `${route.entryName}.js`),
1848
+ path3.posix.join(root, `${route.entryName}.js`),
1803
1849
  render ? renderRouteEntry(route) : ""
1804
1850
  );
1805
1851
  }
1806
1852
  for (const route of Object.values(routes.special)) {
1807
1853
  virtualFiles.set(
1808
- path2.posix.join(root, `${route.entryName}.marko`),
1854
+ path3.posix.join(root, `${route.entryName}.marko`),
1809
1855
  render ? renderRouteTemplate(route) : ""
1810
1856
  );
1811
1857
  }
1812
1858
  if (routes.middleware.length) {
1813
1859
  virtualFiles.set(
1814
- path2.posix.join(root, `${markoRunFilePrefix}middleware.js`),
1860
+ path3.posix.join(root, `${markoRunFilePrefix}middleware.js`),
1815
1861
  render ? renderMiddleware(routes.middleware) : ""
1816
1862
  );
1817
1863
  }
@@ -1843,7 +1889,7 @@ function markoRun(opts = {}) {
1843
1889
  }
1844
1890
  console.error(err);
1845
1891
  virtualFiles.set(
1846
- path2.posix.join(root, `${markoRunFilePrefix}error.marko`),
1892
+ path3.posix.join(root, `${markoRunFilePrefix}error.marko`),
1847
1893
  renderEntryTemplate(`${markoRunFilePrefix}error`, ["<dev-error-page>"])
1848
1894
  );
1849
1895
  virtualFiles.set(
@@ -1887,25 +1933,25 @@ function markoRun(opts = {}) {
1887
1933
  compiler.taglib.register("@marko/run", {
1888
1934
  "<dev-error-page>": {
1889
1935
  template: normalizePath(
1890
- path2.resolve(__dirname, "../components/dev-error-page.marko")
1936
+ path3.resolve(__dirname, "../components/dev-error-page.marko")
1891
1937
  )
1892
1938
  },
1893
1939
  "<*>": {
1894
- transform: path2.resolve(
1940
+ transform: path3.resolve(
1895
1941
  __dirname,
1896
1942
  "../components/src-attributes-transformer.cjs"
1897
1943
  )
1898
1944
  }
1899
1945
  });
1900
1946
  routesDir = opts.routesDir || "src/routes";
1901
- markoVitePluginOptions.store = store = opts.store || new FileStore(
1902
- `marko-serve-vite-${crypto.createHash("SHA1").update(root).digest("hex")}`
1947
+ store = new ReadOncePersistedStore(
1948
+ `vite-marko-run${opts.runtimeId ? `-${opts.runtimeId}` : ""}`
1903
1949
  );
1904
1950
  markoVitePluginOptions.runtimeId = opts.runtimeId;
1905
1951
  markoVitePluginOptions.basePathVar = opts.basePathVar;
1906
- resolvedRoutesDir = path2.resolve(root, routesDir);
1907
- typesDir = path2.join(root, ".marko-run");
1908
- devEntryFile = path2.join(root, "index.html");
1952
+ resolvedRoutesDir = path3.resolve(root, routesDir);
1953
+ typesDir = path3.join(root, ".marko-run");
1954
+ devEntryFile = path3.join(root, "index.html");
1909
1955
  devEntryFilePosix = normalizePath(devEntryFile);
1910
1956
  const assetsDir = ((_d = config2.build) == null ? void 0 : _d.assetsDir) || "assets";
1911
1957
  let rollupOutputOptions = (_f = (_e = config2.build) == null ? void 0 : _e.rollupOptions) == null ? void 0 : _f.output;
@@ -1964,7 +2010,8 @@ function markoRun(opts = {}) {
1964
2010
  // Avoid server & client deleting files from each other.
1965
2011
  rollupOptions: {
1966
2012
  output: rollupOutputOptions
1967
- }
2013
+ },
2014
+ modulePreload: { polyfill: false }
1968
2015
  },
1969
2016
  optimizeDeps: {
1970
2017
  entries: !((_h = config2.optimizeDeps) == null ? void 0 : _h.entries) ? [
@@ -2014,7 +2061,7 @@ function markoRun(opts = {}) {
2014
2061
  configureServer(_server) {
2015
2062
  devServer = _server;
2016
2063
  devServer.watcher.on("all", async (type, filename) => {
2017
- const routableFileType = matchRoutableFile(path2.parse(filename).base);
2064
+ const routableFileType = matchRoutableFile(path3.parse(filename).base);
2018
2065
  if (filename.startsWith(resolvedRoutesDir) && routableFileType) {
2019
2066
  if (type === "add") {
2020
2067
  isStale = true;
@@ -2037,9 +2084,7 @@ function markoRun(opts = {}) {
2037
2084
  async buildStart(_options) {
2038
2085
  if (isBuild && !isSSRBuild) {
2039
2086
  try {
2040
- routeData = JSON.parse(
2041
- await store.get(routeDataFilename)
2042
- );
2087
+ routeData = await store.read();
2043
2088
  } catch {
2044
2089
  this.error(
2045
2090
  `You must run the "ssr" build before the "browser" build.`
@@ -2061,9 +2106,9 @@ function markoRun(opts = {}) {
2061
2106
  let virtualFilePath;
2062
2107
  if (importee.startsWith(virtualFilePrefix)) {
2063
2108
  virtualFilePath = importee.slice(virtualFilePrefix.length + 1);
2064
- importee = path2.resolve(root, virtualFilePath);
2109
+ importee = path3.resolve(root, virtualFilePath);
2065
2110
  } else if (!isBuild && importer && (importer === devEntryFile || normalizePath(importer) === devEntryFilePosix) && importee.startsWith(`/${markoRunFilePrefix}`)) {
2066
- importee = path2.resolve(root, "." + importee);
2111
+ importee = path3.resolve(root, "." + importee);
2067
2112
  }
2068
2113
  importee = normalizePath(importee);
2069
2114
  if (isStale) {
@@ -2072,7 +2117,7 @@ function markoRun(opts = {}) {
2072
2117
  if (virtualFiles.has(importee)) {
2073
2118
  resolved = importee;
2074
2119
  } else if (virtualFilePath) {
2075
- const filePath = path2.resolve(__dirname, "..", virtualFilePath);
2120
+ const filePath = path3.resolve(__dirname, "..", virtualFilePath);
2076
2121
  const resolution = await this.resolve(filePath, importer, {
2077
2122
  skipSelf: true
2078
2123
  });
@@ -2111,7 +2156,7 @@ function markoRun(opts = {}) {
2111
2156
  const builtEntries = Object.values(bundle).reduce(
2112
2157
  (acc, item) => {
2113
2158
  if (item.type === "chunk" && item.isEntry) {
2114
- acc.push(path2.join(options.dir, item.fileName));
2159
+ acc.push(path3.join(options.dir, item.fileName));
2115
2160
  }
2116
2161
  return acc;
2117
2162
  },
@@ -2127,7 +2172,7 @@ function markoRun(opts = {}) {
2127
2172
  for (const [key, code] of virtualFiles) {
2128
2173
  routeData.files.push({ key, code });
2129
2174
  }
2130
- await store.set(routeDataFilename, JSON.stringify(routeData));
2175
+ store.write(routeData);
2131
2176
  await ((_a = opts == null ? void 0 : opts.emitRoutes) == null ? void 0 : _a.call(opts, routes.list));
2132
2177
  } else if (process.env.MR_EXPLORER !== "true") {
2133
2178
  logRoutesTable(routes, bundle, options);
@@ -2202,17 +2247,17 @@ async function globFileExists(root, pattern) {
2202
2247
  return (await glob(pattern, { root })).length > 0;
2203
2248
  }
2204
2249
  async function ensureDir(dir) {
2205
- if (!fs3.existsSync(dir)) {
2206
- await fs3.promises.mkdir(dir, { recursive: true });
2250
+ if (!fs4.existsSync(dir)) {
2251
+ await fs4.promises.mkdir(dir, { recursive: true });
2207
2252
  }
2208
2253
  }
2209
2254
  async function getPackageData(dir) {
2210
2255
  do {
2211
- const pkgPath = path2.join(dir, "package.json");
2212
- if (fs3.existsSync(pkgPath)) {
2213
- return JSON.parse(await fs3.promises.readFile(pkgPath, "utf-8"));
2256
+ const pkgPath = path3.join(dir, "package.json");
2257
+ if (fs4.existsSync(pkgPath)) {
2258
+ return JSON.parse(await fs4.promises.readFile(pkgPath, "utf-8"));
2214
2259
  }
2215
- } while (dir !== (dir = path2.dirname(dir)));
2260
+ } while (dir !== (dir = path3.dirname(dir)));
2216
2261
  return null;
2217
2262
  }
2218
2263
  async function resolveAdapter(root, options, log) {
@@ -2244,10 +2289,10 @@ async function resolveAdapter(root, options, log) {
2244
2289
  log && debug("Using default adapter");
2245
2290
  return module.default();
2246
2291
  }
2247
- var markoEntryFileRegex = /__marko-run__([^.]+)\.(.+)\.marko\.([^.]+)$/;
2292
+ var markoEntryFileRegex = /__marko-run__([^.]+)(?:\.(.+))?\.marko\.([^.]+)$/;
2248
2293
  function getEntryFileName(file) {
2249
2294
  const match = file && markoEntryFileRegex.exec(file);
2250
- return match ? match[2] : void 0;
2295
+ return match ? match[2] || "index" : void 0;
2251
2296
  }
2252
2297
  function isPluginIncluded(config2) {
2253
2298
  return config2.plugins.some((plugin) => {
@@ -2256,7 +2301,7 @@ function isPluginIncluded(config2) {
2256
2301
  }
2257
2302
 
2258
2303
  // src/cli/commands.ts
2259
- var __dirname2 = path3.dirname(fileURLToPath2(import.meta.url));
2304
+ var __dirname2 = path4.dirname(fileURLToPath2(import.meta.url));
2260
2305
  var defaultPort = Number(process.env.PORT || 3e3);
2261
2306
  var defaultConfigFileBases = ["serve.config", "vite.config"];
2262
2307
  var defaultConfigFileExts = [".js", ".cjs", ".mjs", ".ts", ".mts"];
@@ -2267,7 +2312,9 @@ async function preview(entry, distEntry, cwd, configFile, port, outDir, envFile,
2267
2312
  "build"
2268
2313
  );
2269
2314
  const [availablePort, adapter] = await Promise.all([
2270
- getAvailablePort(port ?? resolvedConfig.preview.port ?? resolvedConfig.server.port ?? defaultPort),
2315
+ getAvailablePort(
2316
+ port ?? resolvedConfig.preview.port ?? resolvedConfig.server.port ?? defaultPort
2317
+ ),
2271
2318
  resolveAdapter2(resolvedConfig)
2272
2319
  ]);
2273
2320
  if (!adapter) {
@@ -2278,10 +2325,10 @@ async function preview(entry, distEntry, cwd, configFile, port, outDir, envFile,
2278
2325
  if (!entry) {
2279
2326
  entry = await ((_a = adapter.getEntryFile) == null ? void 0 : _a.call(adapter));
2280
2327
  }
2281
- const dir = path3.resolve(cwd, resolvedConfig.build.outDir);
2282
- const entryFile = distEntry ? path3.join(dir, distEntry) : await findFileWithExt(dir, "index", [".mjs", ".js"]);
2328
+ const dir = path4.resolve(cwd, resolvedConfig.build.outDir);
2329
+ const entryFile = distEntry ? path4.join(dir, distEntry) : await findFileWithExt(dir, "index", [".mjs", ".js"]);
2283
2330
  if (envFile) {
2284
- envFile = path3.resolve(cwd, envFile);
2331
+ envFile = path4.resolve(cwd, envFile);
2285
2332
  }
2286
2333
  const options = {
2287
2334
  cwd,
@@ -2300,10 +2347,12 @@ async function dev(entry, cwd, configFile, port, envFile, args = []) {
2300
2347
  "serve"
2301
2348
  );
2302
2349
  if (envFile) {
2303
- envFile = path3.resolve(cwd, envFile);
2350
+ envFile = path4.resolve(cwd, envFile);
2304
2351
  }
2305
2352
  const [availablePort, adapter] = await Promise.all([
2306
- getAvailablePort(port ?? resolvedConfig.server.port ?? resolvedConfig.preview.port ?? defaultPort),
2353
+ getAvailablePort(
2354
+ port ?? resolvedConfig.server.port ?? resolvedConfig.preview.port ?? defaultPort
2355
+ ),
2307
2356
  resolveAdapter2(resolvedConfig)
2308
2357
  ]);
2309
2358
  if (!adapter) {
@@ -2312,9 +2361,7 @@ async function dev(entry, cwd, configFile, port, envFile, args = []) {
2312
2361
  // Would the user know what a target is if presented with this error?
2313
2362
  );
2314
2363
  } else if (!adapter.startDev) {
2315
- throw new Error(
2316
- `Adapter '${adapter.name}' does not support 'dev' command`
2317
- );
2364
+ throw new Error(`Adapter '${adapter.name}' does not support 'dev' command`);
2318
2365
  }
2319
2366
  if (!entry) {
2320
2367
  entry = await ((_a = adapter.getEntryFile) == null ? void 0 : _a.call(adapter));
@@ -2322,7 +2369,7 @@ async function dev(entry, cwd, configFile, port, envFile, args = []) {
2322
2369
  const config2 = {
2323
2370
  root: cwd,
2324
2371
  configFile,
2325
- plugins: isPluginIncluded(resolvedConfig) ? void 0 : [markoRun()]
2372
+ plugins: isPluginIncluded(resolvedConfig) ? void 0 : markoRun()
2326
2373
  };
2327
2374
  const options = {
2328
2375
  cwd,
@@ -2352,28 +2399,26 @@ async function build(entry, cwd, configFile, outDir, envFile) {
2352
2399
  }
2353
2400
  }
2354
2401
  if (envFile) {
2355
- envFile = path3.resolve(cwd, envFile);
2402
+ envFile = path4.resolve(cwd, envFile);
2356
2403
  }
2357
- let buildConfig = {
2358
- root,
2359
- configFile,
2360
- build: {
2361
- ssr: false,
2362
- outDir
2404
+ const buildConfig = setExternalAdapterOptions(
2405
+ {
2406
+ root,
2407
+ configFile,
2408
+ plugins: isPluginIncluded(resolvedConfig) ? void 0 : markoRun(),
2409
+ build: {
2410
+ ssr: false,
2411
+ outDir
2412
+ }
2413
+ },
2414
+ {
2415
+ root,
2416
+ isBuild: true,
2417
+ envFile
2363
2418
  }
2364
- };
2365
- buildConfig = setExternalPluginOptions(buildConfig, {
2366
- store: new MemoryStore()
2367
- });
2368
- buildConfig = setExternalAdapterOptions(buildConfig, {
2369
- root,
2370
- isBuild: true,
2371
- envFile
2372
- });
2373
- const hasPlugin = isPluginIncluded(resolvedConfig);
2419
+ );
2374
2420
  await viteBuild({
2375
2421
  ...buildConfig,
2376
- plugins: hasPlugin ? void 0 : [markoRun()],
2377
2422
  build: {
2378
2423
  target: "esnext",
2379
2424
  ...buildConfig.build,
@@ -2388,7 +2433,6 @@ async function build(entry, cwd, configFile, outDir, envFile) {
2388
2433
  });
2389
2434
  await viteBuild({
2390
2435
  ...buildConfig,
2391
- plugins: hasPlugin ? void 0 : [markoRun()],
2392
2436
  build: {
2393
2437
  ...buildConfig.build,
2394
2438
  sourcemap: true
@@ -2397,8 +2441,8 @@ async function build(entry, cwd, configFile, outDir, envFile) {
2397
2441
  }
2398
2442
  function findFileWithExt(dir, base, extensions = defaultConfigFileExts) {
2399
2443
  for (const ext of extensions) {
2400
- const filePath = path3.join(dir, base + ext);
2401
- if (fs4.existsSync(filePath)) {
2444
+ const filePath = path4.join(dir, base + ext);
2445
+ if (fs5.existsSync(filePath)) {
2402
2446
  return filePath;
2403
2447
  }
2404
2448
  }
@@ -2406,8 +2450,8 @@ function findFileWithExt(dir, base, extensions = defaultConfigFileExts) {
2406
2450
  }
2407
2451
  async function getViteConfig(dir, configFile, bases = defaultConfigFileBases) {
2408
2452
  if (configFile) {
2409
- const configFilePath = path3.join(dir, configFile);
2410
- if (!fs4.existsSync(configFilePath)) {
2453
+ const configFilePath = path4.join(dir, configFile);
2454
+ if (!fs5.existsSync(configFilePath)) {
2411
2455
  throw new Error(`No config file found at '${configFilePath}'`);
2412
2456
  }
2413
2457
  return configFile;
@@ -2418,7 +2462,7 @@ async function getViteConfig(dir, configFile, bases = defaultConfigFileBases) {
2418
2462
  return configFile;
2419
2463
  }
2420
2464
  }
2421
- return path3.join(__dirname2, "default.config.mjs");
2465
+ return path4.join(__dirname2, "default.config.mjs");
2422
2466
  }
2423
2467
  async function resolveAdapter2(config2) {
2424
2468
  const options = getExternalPluginOptions(config2);
@@ -2460,7 +2504,8 @@ prog.command("dev [entry]", "", { default: true }).describe("Start development s
2460
2504
  "Port the dev server should listen on (defaults: 'preview.port' in config, or `$PORT` env variable, or 3000)"
2461
2505
  ).example("dev --config vite.config.js").action(async (entry, opts) => {
2462
2506
  const cwd = process.cwd();
2463
- const args = process.argv.slice(entry ? 4 : 3);
2507
+ const offset = (process.argv[2] === "dev" ? 3 : 2) + (entry ? 1 : 0);
2508
+ const args = process.argv.slice(offset);
2464
2509
  const config2 = await getViteConfig(cwd, opts.config);
2465
2510
  await dev(entry, cwd, config2, opts.port, opts.env, args);
2466
2511
  });