@vite-hub/kv 0.3.1 → 0.4.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.
Files changed (41) hide show
  1. package/README.md +14 -12
  2. package/dist/cli.js +4 -3
  3. package/dist/{cloudflare-kv-BIEUFzRT.js → cloudflare-kv-C3NO4C21.js} +18 -4
  4. package/dist/{cloudflare-kv-local-BBw3ZT1K.js → cloudflare-kv-local-C2sbIrFy.js} +2 -2
  5. package/dist/{config-BXEVoZE3.js → config-LfpUj9hs.js} +25 -23
  6. package/dist/{create-storage-BGsrQKw3.js → create-storage-BORQm2a8.js} +5 -5
  7. package/dist/{cursor-history-BqIQePNP.js → cursor-history-DRHh5bO5.js} +1 -1
  8. package/dist/{database-72Jk3VVk.js → database-oJdy0ZVX.js} +1 -1
  9. package/dist/{deno-kv-BM9mYdUp.js → deno-kv-D_VtffFv.js} +2 -2
  10. package/dist/{driver-BwxgaQ-f.d.ts → driver-R4Z5Z5fl.d.ts} +2 -2
  11. package/dist/{error-diagnostics-BxqvtEIb.js → error-diagnostics-C54QQEhN.js} +10 -2
  12. package/dist/{errors-DbwufFZp.js → errors-DzD6YNEH.js} +31 -3
  13. package/dist/errors.d.ts +6 -1
  14. package/dist/errors.js +2 -2
  15. package/dist/fs-lite-BAgpmNAF.js +2 -0
  16. package/dist/{fs-lite-BLZId9_P.js → fs-lite-BaklCLuV.js} +1 -1
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +42 -27
  19. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
  20. package/dist/{operations-Ch-gKaey.js → operations-CtrWLmPK.js} +3 -9
  21. package/dist/{operations-B-WZ7P1h.js → operations-D2iI9oN4.js} +238 -226
  22. package/dist/operations.d.ts +2 -2
  23. package/dist/operations.js +3 -2
  24. package/dist/{redis-shared-E5mahECF.js → redis-shared-5ogRd3-Y.js} +1 -1
  25. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  26. package/dist/runtime/cloudflare-kv.js +1 -1
  27. package/dist/runtime/nitro-plugin.js +7 -4
  28. package/dist/runtime/redis-driver.d.ts +2 -2
  29. package/dist/runtime/redis-driver.js +2 -2
  30. package/dist/runtime/unstorage-driver.js +6 -2
  31. package/dist/runtime/upstash-driver.d.ts +2 -2
  32. package/dist/runtime/upstash-driver.js +2 -2
  33. package/dist/{types-DEiKew_3.d.ts → types-Dv-OSXZC.d.ts} +33 -20
  34. package/dist/{upstash-DDlqTttY.js → upstash-B-vaUYqO.js} +2 -2
  35. package/dist/virtual-module.d.ts +1 -0
  36. package/dist/vite.d.ts +17 -5
  37. package/dist/vite.js +601 -334
  38. package/package.json +5 -5
  39. package/dist/fs-lite-RAoxu8L0.js +0 -2
  40. package/dist/main-F3Y22_uV.js +0 -2353
  41. package/dist/rolldown-runtime-CMFfr-1z.js +0 -26
package/dist/vite.js CHANGED
@@ -1,18 +1,18 @@
1
- import { r as __toESM } from "./rolldown-runtime-CMFfr-1z.js";
2
1
  import { a as resolve$1, i as relative$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-BIKQsqX4.js";
2
+ import { D as readViteHubDevServerFile, M as internalErrorDiagnostics, S as shouldSkipViteProviderBuild, _ as VITEHUB_PROJECT_ROOT, b as isServerEnvironment, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, p as operationRpcPath, r as collectOperationContributions, v as createNoExternalAddition, x as resolveViteHubProjectRoot, y as hasNitroConfigContext } from "./operations-D2iI9oN4.js";
3
3
  import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
4
- import { A as writeViteHubDevServerFile, E as readViteHubDevServerFile, O as removeViteHubDevServerFile, _ as createNoExternalAddition, b as resolveViteHubProjectRoot, g as internalErrorDiagnostics, p as operationRpcPath, r as collectOperationContributions, v as hasNitroConfigContext, x as shouldSkipViteProviderBuild, y as isServerEnvironment } from "./operations-B-WZ7P1h.js";
5
4
  import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
6
- import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
7
- import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvWarning, o as resolveHostPreset, r as normalizeKVOptions } from "./config-BXEVoZE3.js";
8
- import { n as resolveUpstashRuntimeValues } from "./upstash-DDlqTttY.js";
5
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
6
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvHint, o as resolveHostPreset, r as normalizeKVOptions } from "./config-LfpUj9hs.js";
7
+ import { n as resolveUpstashRuntimeValues } from "./upstash-B-vaUYqO.js";
9
8
  import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
10
- import "node:module";
9
+ import { createRequire, isBuiltin } from "node:module";
11
10
  import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
12
11
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
- import { existsSync, readFileSync, renameSync, rmSync } from "node:fs";
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
13
+ import { formatDiagnostic } from "nostics";
14
14
  import { tmpdir } from "node:os";
15
- import { fileURLToPath } from "node:url";
15
+ import { fileURLToPath, pathToFileURL } from "node:url";
16
16
  import { createHash } from "node:crypto";
17
17
  //#region ../internal/src/build/paths.ts
18
18
  function resolveRuntimeModule(packageDir, modulePath) {
@@ -193,10 +193,9 @@ function resolveKVViteConfig(kv, input = {}) {
193
193
  return {
194
194
  hosting,
195
195
  kv: normalizeKVOptions(kv, {
196
- dev: input.dev,
196
+ ...input,
197
197
  env,
198
- hosting,
199
- postgresDatabase: input.postgresDatabase
198
+ hosting
200
199
  }) ?? false
201
200
  };
202
201
  }
@@ -414,20 +413,76 @@ function resolveViteHubBundleDefines(config) {
414
413
  return defines;
415
414
  }
416
415
  //#endregion
417
- //#region ../internal/src/build/esbuild.ts
418
- const viteRawNamespace = "vitehub-vite-raw";
419
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
416
+ //#region ../internal/src/build/ast-walk.ts
417
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
418
+ function moduleLanguage(file) {
419
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
420
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
421
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
422
+ return "ts";
423
+ }
424
+ function isNode(value) {
425
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
426
+ }
427
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
428
+ function walk(node, visit, parent) {
429
+ if (visit(node, parent) === false) return;
430
+ const fields = node;
431
+ for (const key in fields) {
432
+ const child = fields[key];
433
+ if (typeof child !== "object" || child === null || key === "parent") continue;
434
+ if (Array.isArray(child)) {
435
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
436
+ } else if (isNode(child)) walk(child, visit, node);
437
+ }
438
+ }
439
+ //#endregion
440
+ //#region ../internal/src/build/rolldown.ts
441
+ const viteRawPrefix = "\0vitehub-vite-raw:";
442
+ const markdownTemplatePrefix = "\0vitehub-markdown-template:";
420
443
  const markdownTemplateFileSuffix = ".template.md";
421
444
  const markdownTemplateModuleQuery = "markdown-template";
422
445
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
423
446
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
447
+ const resolvingViteAlias = "vitehubResolvingAlias";
424
448
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
449
+ /**
450
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
451
+ * Vite+, instead of installing a second bundler.
452
+ */
453
+ async function importRolldown() {
454
+ let entry;
455
+ try {
456
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
457
+ } catch (error) {
458
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
459
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
460
+ }
461
+ return await import(pathToFileURL(entry).href);
462
+ }
425
463
  function normalizePathSeparators(path) {
426
464
  return path.replaceAll("\\", "/");
427
465
  }
428
466
  function escapeRegExp(value) {
429
467
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
430
468
  }
469
+ function isRelativeSpecifier(path) {
470
+ return /^\.\.?[\\/]/.test(path);
471
+ }
472
+ function isBareSpecifier(id) {
473
+ return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
474
+ }
475
+ /** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
476
+ function importerDir(importer, workingDir) {
477
+ return importer && isAbsolute(importer) ? dirname(importer) : workingDir;
478
+ }
479
+ /** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
480
+ function importerFor(importer, workingDir) {
481
+ return importer ?? join(workingDir, "__vitehub_entry__.js");
482
+ }
483
+ function isFileResolution(resolved) {
484
+ return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
485
+ }
431
486
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
432
487
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
433
488
  if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
@@ -454,7 +509,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
454
509
  }
455
510
  return candidates;
456
511
  }
457
- function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
512
+ /**
513
+ * Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
514
+ * resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
515
+ * same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
516
+ */
517
+ function resolveFrom(context, specifier, request, workingDir, flag) {
518
+ return context.resolve(specifier, importerFor(request.importer, workingDir), {
519
+ custom: {
520
+ ...request.custom,
521
+ [flag]: true
522
+ },
523
+ isEntry: request.isEntry,
524
+ kind: request.kind,
525
+ skipSelf: true
526
+ });
527
+ }
528
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
458
529
  const entries = Object.entries(aliases || {});
459
530
  if (!entries.length) return;
460
531
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -474,186 +545,175 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
474
545
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
475
546
  };
476
547
  }));
548
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
477
549
  return {
478
550
  name: "vitehub-resolved-alias",
479
- setup(build) {
480
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
481
- build.onResolve({ filter: /.*/ }, async (args) => {
482
- if (args.pluginData?.[skipResolvedAlias]) return;
483
- const resolveWithContext = (specifier) => build.resolve(specifier, {
484
- importer: args.importer,
485
- kind: args.kind,
486
- namespace: args.namespace,
487
- pluginData: {
488
- ...args.pluginData,
489
- [skipResolvedAlias]: true
490
- },
491
- resolveDir: args.resolveDir,
492
- with: args.with
493
- });
494
- const aliases = await resolvedEntries;
495
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
496
- let matchedAlias = match?.specifier;
497
- let matchedSpecifier = match ? args.path : void 0;
498
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
499
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
500
- let canonicalSpecifier = normalizedSpecifier;
501
- const canonicalizeSpecifier = async () => {
502
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
503
- return canonicalSpecifier;
504
- };
505
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
506
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
507
- await canonicalizeSpecifier();
508
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
509
- }
510
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
511
- const candidates = [];
512
- for (const alias of aliases) {
513
- if (isAbsolute(alias.specifier)) continue;
514
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
515
- const aliasSegments = packageAlias.split("/");
516
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
517
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
518
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
519
- const scopeMarker = `/node_modules/${packageAlias}/`;
520
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
521
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
522
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
523
- }
524
- const packageMarker = `/node_modules/${packageName}/`;
525
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
526
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
527
- const cacheKey = [
528
- alias.specifier,
529
- alias.prefix,
530
- resolutionScope,
531
- normalizedSpecifier,
532
- args.importer,
533
- args.resolveDir,
534
- args.kind,
535
- args.namespace,
536
- JSON.stringify(args.with)
537
- ].join("\0");
538
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
539
- if (!resolution) {
540
- resolution = (async () => {
541
- let resolvedAliasPath;
542
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
543
- else if (resolutionScope) {
544
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
545
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
546
- if (!isRecord(parsedPackageJson)) return;
547
- const packageJson = parsedPackageJson;
548
- if (packageJson.exports === void 0 && !alias.prefix) {
549
- const resolvedCandidate = await resolveWithContext(alias.specifier);
550
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
551
- canonical: alias.specifier,
552
- normalized: alias.specifier,
553
- publicSpecifier: alias.specifier
554
- };
555
- return;
556
- }
557
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
558
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
559
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
560
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
561
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
562
- matchingPublicSpecifiers.add(publicSpecifier);
563
- }
564
- if (matchingPublicSpecifiers.size === 1) {
565
- const publicSpecifier = [...matchingPublicSpecifiers][0];
566
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
567
- canonical: publicSpecifier,
568
- normalized: publicSpecifier,
569
- publicSpecifier
570
- };
571
- }
551
+ async resolveId(source, importer, extra) {
552
+ if (extra.custom?.[skipResolvedAlias]) return;
553
+ const request = {
554
+ custom: extra.custom,
555
+ importer,
556
+ isEntry: extra.isEntry,
557
+ kind: extra.kind
558
+ };
559
+ const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
560
+ const resolveDir = importerDir(importer, workingDir);
561
+ const aliases = await resolvedEntries;
562
+ let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
563
+ let matchedAlias = match?.specifier;
564
+ let matchedSpecifier = match ? source : void 0;
565
+ const specifier = isRelativeSpecifier(source) ? resolve(resolveDir, source) : source;
566
+ const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
567
+ let canonicalSpecifier = normalizedSpecifier;
568
+ const canonicalizeSpecifier = async () => {
569
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
570
+ return canonicalSpecifier;
571
+ };
572
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
573
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
574
+ await canonicalizeSpecifier();
575
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
576
+ }
577
+ if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
578
+ const candidates = [];
579
+ for (const alias of aliases) {
580
+ if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
581
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
582
+ const aliasSegments = packageAlias.split("/");
583
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
584
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
585
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
586
+ const scopeMarker = `/node_modules/${packageAlias}/`;
587
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
588
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
589
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
590
+ }
591
+ const packageMarker = `/node_modules/${packageName}/`;
592
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
593
+ if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
594
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
595
+ const cacheKey = [
596
+ alias.specifier,
597
+ alias.prefix,
598
+ resolutionScope,
599
+ normalizedSpecifier,
600
+ importer,
601
+ extra.kind,
602
+ extra.isEntry
603
+ ].join("\0");
604
+ const cacheable = !extra.custom || !Object.keys(extra.custom).length;
605
+ let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
606
+ if (!resolution) {
607
+ resolution = (async () => {
608
+ let resolvedAliasPath;
609
+ if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
610
+ else if (resolutionScope) {
611
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
612
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
613
+ if (!isRecord(parsedPackageJson)) return;
614
+ const packageJson = parsedPackageJson;
615
+ if (packageJson.exports === void 0 && !alias.prefix) {
616
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
617
+ if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve(resolvedCandidate.id)) === normalizedSpecifier) return {
618
+ canonical: alias.specifier,
619
+ normalized: alias.specifier,
620
+ publicSpecifier: alias.specifier
621
+ };
572
622
  return;
573
- } else {
574
- const resolvedAlias = await resolveWithContext(alias.specifier);
575
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
576
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
577
623
  }
578
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
579
- return {
580
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
581
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
582
- };
583
- })();
584
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
585
- }
586
- candidates.push({
587
- alias,
588
- resolution
589
- });
624
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
625
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
626
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
627
+ if (!isFileResolution(resolvedCandidate)) continue;
628
+ if (normalizePathSeparators(resolve(resolvedCandidate.id)) !== normalizedSpecifier) continue;
629
+ matchingPublicSpecifiers.add(publicSpecifier);
630
+ }
631
+ if (matchingPublicSpecifiers.size === 1) {
632
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
633
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
634
+ canonical: publicSpecifier,
635
+ normalized: publicSpecifier,
636
+ publicSpecifier
637
+ };
638
+ }
639
+ return;
640
+ } else {
641
+ const resolvedAlias = await resolveWithContext(alias.specifier);
642
+ if (!isFileResolution(resolvedAlias)) return;
643
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.id));
644
+ }
645
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
646
+ return {
647
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
648
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
649
+ };
650
+ })();
651
+ if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
590
652
  }
591
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
592
- for (const { alias, resolution } of candidates) {
593
- const paths = await resolution;
594
- if (!paths) continue;
595
- if (paths.publicSpecifier) {
596
- match = alias;
597
- matchedAlias = alias.specifier;
598
- matchedSpecifier = paths.publicSpecifier;
599
- break;
600
- }
601
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
602
- let canonicalMatch = false;
603
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
604
- await canonicalizeSpecifier();
605
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
606
- }
607
- if (normalizedMatch || canonicalMatch) {
608
- match = alias;
609
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
610
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
611
- break;
612
- }
653
+ candidates.push({
654
+ alias,
655
+ resolution
656
+ });
657
+ }
658
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
659
+ for (const { alias, resolution } of candidates) {
660
+ const paths = await resolution;
661
+ if (!paths) continue;
662
+ if (paths.publicSpecifier) {
663
+ match = alias;
664
+ matchedAlias = alias.specifier;
665
+ matchedSpecifier = paths.publicSpecifier;
666
+ break;
667
+ }
668
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
669
+ let canonicalMatch = false;
670
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
671
+ await canonicalizeSpecifier();
672
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
673
+ }
674
+ if (normalizedMatch || canonicalMatch) {
675
+ match = alias;
676
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
677
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
678
+ break;
613
679
  }
614
680
  }
615
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
616
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
617
- if (!match) return;
618
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
619
- if (!target) return;
620
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
621
- });
681
+ }
682
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
683
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
684
+ if (!match) return;
685
+ const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
686
+ if (!target) return;
687
+ const resolvedTarget = isRelativeSpecifier(target) ? resolve(aliasResolveDir, target) : target;
688
+ const resolved = await resolveWithContext(resolvedTarget);
689
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
690
+ return resolved;
622
691
  }
623
692
  };
624
693
  }
625
- function createViteAliasPlugin(aliases) {
694
+ function createViteAliasPlugin(aliases, workingDir) {
626
695
  if (!Array.isArray(aliases)) return;
627
- const resolvingAlias = "vitehubResolvingAlias";
628
696
  return {
629
697
  name: "vitehub-vite-alias",
630
- setup(build) {
631
- build.onResolve({ filter: /.*/ }, async (args) => {
632
- if (args.pluginData?.[resolvingAlias]) return;
633
- const alias = aliases.find(({ find }) => {
634
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
635
- find.lastIndex = 0;
636
- return find.test(args.path);
637
- });
638
- if (!alias) return;
639
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
640
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
641
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
642
- const result = await build.resolve(replacement, {
643
- importer: args.importer,
644
- kind: args.kind,
645
- namespace: args.namespace,
646
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
647
- resolveDir: args.resolveDir,
648
- with: args.with
649
- });
650
- const pluginData = Object.assign({}, result.pluginData);
651
- Reflect.deleteProperty(pluginData, resolvingAlias);
652
- return {
653
- ...result,
654
- pluginData
655
- };
698
+ async resolveId(source, importer, extra) {
699
+ if (extra.custom?.[resolvingViteAlias]) return;
700
+ const alias = aliases.find(({ find }) => {
701
+ if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
702
+ find.lastIndex = 0;
703
+ return find.test(source);
656
704
  });
705
+ if (!alias) return;
706
+ if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
707
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
708
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
709
+ const resolved = await resolveFrom(this, replacement, {
710
+ custom: extra.custom,
711
+ importer,
712
+ isEntry: extra.isEntry,
713
+ kind: extra.kind
714
+ }, workingDir, resolvingViteAlias);
715
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
716
+ return resolved;
657
717
  }
658
718
  };
659
719
  }
@@ -692,174 +752,255 @@ async function resolveViteRawSpecifier(path, rootDir) {
692
752
  return resolve(rootDir, rootRelativePath);
693
753
  }
694
754
  }
695
- function createViteRawPlugin(rootDir, frameworkRuntime) {
755
+ function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
696
756
  return {
697
757
  name: "vitehub-vite-raw",
698
- setup(build) {
699
- build.onResolve({
700
- filter: /^@vite-hub\/markdown-template$/,
701
- namespace: viteMarkdownTemplateNamespace
702
- }, async (args) => {
703
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
704
- return build.resolve("vite-hub/markdown-template", {
705
- importer: args.importer,
706
- kind: args.kind,
707
- resolveDir: args.resolveDir
758
+ async resolveId(source, importer, extra) {
759
+ if (source === markdownTemplateRuntimeSpecifier && importer?.startsWith(markdownTemplatePrefix)) {
760
+ if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier));
761
+ return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
762
+ custom: extra.custom,
763
+ kind: extra.kind
708
764
  });
709
- });
710
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
711
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
712
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
713
- const raw = hasViteRawQuery(args.path);
714
- if (!markdownTemplate && !raw) return;
715
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
716
- let pluginData = args.pluginData;
717
- if (markdownTemplate) pluginData = {
718
- ...args.pluginData,
719
- [skipMarkdownTemplateResolve]: true
720
- };
721
- const resolved = await build.resolve(specifier, {
722
- importer: args.importer,
723
- kind: args.kind,
724
- namespace: args.namespace,
725
- pluginData,
726
- resolveDir: args.resolveDir,
727
- with: args.with
728
- });
729
- if (resolved.errors.length) return {
730
- errors: resolved.errors,
731
- warnings: resolved.warnings
732
- };
733
- if (resolved.external) return {
734
- external: true,
735
- namespace: resolved.namespace,
736
- path: resolved.path,
737
- pluginData: resolved.pluginData,
738
- sideEffects: resolved.sideEffects,
739
- suffix: resolved.suffix,
740
- warnings: resolved.warnings
741
- };
742
- if (resolved.namespace !== "file") return {
743
- errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
744
- warnings: resolved.warnings
745
- };
746
- return {
747
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
748
- path: resolved.path,
749
- pluginData: resolved.pluginData,
750
- sideEffects: resolved.sideEffects,
751
- suffix: resolved.suffix,
752
- warnings: resolved.warnings
753
- };
754
- });
755
- build.onLoad({
756
- filter: /.*/,
757
- namespace: viteRawNamespace
758
- }, async (args) => ({
759
- contents: await readFile(args.path),
760
- loader: "text"
761
- }));
762
- build.onLoad({
763
- filter: /.*/,
764
- namespace: viteMarkdownTemplateNamespace
765
- }, async (args) => ({
766
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
767
- loader: "js",
768
- resolveDir: dirname(args.path)
769
- }));
765
+ }
766
+ if (extra.custom?.[skipMarkdownTemplateResolve]) return;
767
+ const markdownTemplate = parseMarkdownTemplateRequest(source);
768
+ const raw = hasViteRawQuery(source);
769
+ if (!markdownTemplate && !raw) return;
770
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
771
+ const resolved = await resolveFrom(this, specifier, {
772
+ custom: extra.custom,
773
+ importer,
774
+ isEntry: extra.isEntry,
775
+ kind: extra.kind
776
+ }, workingDir, skipMarkdownTemplateResolve);
777
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
778
+ if (resolved.external) return {
779
+ id: resolved.id,
780
+ external: resolved.external
781
+ };
782
+ const resolvedId = resolved.id;
783
+ if (!isFileResolution(resolved)) this.error(markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this raw import in a caller plugin.`);
784
+ return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
785
+ },
786
+ async load(id) {
787
+ if (id.startsWith(viteRawPrefix)) return {
788
+ code: await readFile(id.slice(18), "utf8"),
789
+ moduleType: "text"
790
+ };
791
+ if (id.startsWith(markdownTemplatePrefix)) return {
792
+ code: renderMarkdownTemplateModule(await readFile(id.slice(27), "utf8")),
793
+ moduleType: "js"
794
+ };
770
795
  }
771
796
  };
772
797
  }
773
798
  function createFileUrlPlugin() {
774
799
  return {
775
800
  name: "vitehub-file-url",
776
- setup(build) {
777
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
801
+ resolveId(source) {
802
+ if (source.startsWith("file:")) return fileURLToPath(source);
778
803
  }
779
804
  };
780
805
  }
781
806
  /**
782
807
  * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
783
808
  * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
809
+ * Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
784
810
  */
785
- function createWasmModulePlugin(outdir) {
811
+ function createWasmModulePlugin(outdir, workingDir, copy) {
786
812
  return {
787
813
  name: "vitehub-wasm-module",
788
- setup(build) {
789
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
790
- const resolved = await build.resolve(args.path.slice(0, -7), {
791
- importer: args.importer,
792
- kind: args.kind,
793
- resolveDir: args.resolveDir
794
- });
795
- if (resolved.errors.length) return { errors: resolved.errors };
796
- const bytes = await readFile(resolved.path);
797
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
798
- await mkdir(outdir, { recursive: true });
799
- await copyFile(resolved.path, join(outdir, name));
800
- return {
801
- external: true,
802
- path: `./${name}`
803
- };
814
+ async resolveId(source, importer, extra) {
815
+ if (!source.endsWith(".wasm?module")) return;
816
+ const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
817
+ custom: extra.custom,
818
+ kind: extra.kind
804
819
  });
820
+ if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
821
+ if (!copy) return resolved.id;
822
+ const bytes = await readFile(resolved.id);
823
+ const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
824
+ await mkdir(outdir, { recursive: true });
825
+ await copyFile(resolved.id, join(outdir, name));
826
+ return {
827
+ id: `./${name}`,
828
+ external: true
829
+ };
830
+ }
831
+ };
832
+ }
833
+ /**
834
+ * Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
835
+ */
836
+ function createExternalPackagesPlugin() {
837
+ return {
838
+ name: "vitehub-external-packages",
839
+ async resolveId(source, importer, extra) {
840
+ if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
841
+ id: source,
842
+ external: true
843
+ };
844
+ if (source.startsWith("#")) return await this.resolve(source, importer, {
845
+ custom: extra.custom,
846
+ kind: extra.kind
847
+ }) ?? {
848
+ id: source,
849
+ external: true
850
+ };
851
+ if (isBareSpecifier(source) && !isBuiltin(source)) return {
852
+ id: source,
853
+ external: true
854
+ };
855
+ }
856
+ };
857
+ }
858
+ function hasImportRejectionHandler(importNode, parents) {
859
+ let expression = importNode;
860
+ let parent = parents.get(expression);
861
+ while (parent?.type === "MemberExpression" && parent.object === expression) {
862
+ const call = parents.get(parent);
863
+ if (call?.type !== "CallExpression" || call.callee !== parent) break;
864
+ const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
865
+ const handler = call.arguments[method === "then" ? 1 : 0];
866
+ if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
867
+ if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
868
+ }
869
+ if (method !== "then" && method !== "finally") break;
870
+ expression = call;
871
+ parent = parents.get(expression);
872
+ }
873
+ if (parent?.type !== "AwaitExpression") return false;
874
+ for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
875
+ if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
876
+ if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
877
+ child = ancestor;
878
+ }
879
+ return false;
880
+ }
881
+ function createOptionalImportPlugin() {
882
+ const prefix = "\0vitehub-optional-import:";
883
+ return {
884
+ name: "vitehub-optional-import",
885
+ resolveId(source) {
886
+ if (source.startsWith(prefix)) return {
887
+ id: source.slice(25),
888
+ external: "absolute"
889
+ };
890
+ },
891
+ transform: {
892
+ order: "post",
893
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
894
+ async handler(code, id) {
895
+ const { parseSync } = await import("vite");
896
+ const module = parseSync(id, code, {
897
+ lang: moduleLanguage(id),
898
+ preserveParens: false,
899
+ sourceType: "module"
900
+ });
901
+ if (module.errors.length) return;
902
+ const parents = /* @__PURE__ */ new WeakMap();
903
+ const handled = [];
904
+ walk(module.program, (node, parent) => {
905
+ if (parent) parents.set(node, parent);
906
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
907
+ if (hasImportRejectionHandler(node, parents)) handled.push({
908
+ source: node.source.value,
909
+ start: node.source.start,
910
+ end: node.source.end
911
+ });
912
+ });
913
+ if (!handled.length) return;
914
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
915
+ for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
916
+ return code;
917
+ }
805
918
  }
806
919
  };
807
920
  }
921
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
922
+ function createExternalMatcher(patterns) {
923
+ if (!patterns?.length) return;
924
+ const matchers = patterns.map((pattern) => {
925
+ if (pattern.includes("*")) {
926
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`);
927
+ return (id) => expression.test(id);
928
+ }
929
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
930
+ });
931
+ return (id) => matchers.some((matches) => matches(id));
932
+ }
808
933
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
809
- const { build: bundle } = await import("./main-F3Y22_uV.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
934
+ const { rolldown } = await importRolldown();
810
935
  options.signal?.throwIfAborted();
811
936
  const format = options.format || "esm";
812
937
  const platform = options.platform || "neutral";
813
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
938
+ const workingDir = options.workingDir ?? process.cwd();
814
939
  const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
815
940
  const plugins = [];
816
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
941
+ plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
942
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
817
943
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
818
944
  plugins.push(...options.plugins ?? [], createFileUrlPlugin());
945
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
819
946
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
820
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
821
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
822
- const result = await bundle({
823
- absWorkingDir: options.workingDir,
824
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
825
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
826
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
827
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
828
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
829
- "}"
830
- ] : []].filter(Boolean).join("\n") } : void 0,
831
- bundle: true,
832
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
833
- define: options.define,
834
- entryPoints: [entryFile],
835
- external: options.external,
836
- format,
837
- keepNames: options.minifySyntax || options.minifyIdentifiers,
838
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
839
- logLevel: "silent",
840
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
841
- resolveExtensions: options.extensions,
842
- minifyIdentifiers: options.minifyIdentifiers,
843
- minifySyntax: options.minifySyntax,
844
- minifyWhitespace: options.minifyWhitespace,
845
- outfile,
846
- packages: options.packages,
947
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
948
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
949
+ plugins.push(createOptionalImportPlugin());
950
+ const isExternal = createExternalMatcher(options.external);
951
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
952
+ compress: options.minifySyntax ?? false,
953
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
954
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
955
+ } : false;
956
+ const banner = [options.banner, ...format === "esm" && platform === "node" ? [
957
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
958
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
959
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
960
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
961
+ "}"
962
+ ] : []].filter(Boolean).join("\n");
963
+ const bundle = await rolldown({
964
+ cwd: workingDir,
965
+ external: isExternal ? (id) => isExternal(id) : void 0,
966
+ input: entryFile,
967
+ onLog(level, log) {
968
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
969
+ },
970
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
847
971
  platform,
848
- preserveSymlinks: options.preserveSymlinks,
849
972
  plugins,
850
- sourcemap: false,
851
- target: "es2022",
852
- write: options.signal ? false : true
973
+ resolve: {
974
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
975
+ extensions: options.extensions,
976
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
977
+ symlinks: !options.preserveSymlinks
978
+ },
979
+ transform: {
980
+ define: options.define,
981
+ target: "es2022"
982
+ },
983
+ tsconfig: options.tsconfig ?? true
853
984
  });
854
- options.signal?.throwIfAborted();
855
- if (options.signal) {
856
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
857
- await mkdir(dirname(output.path), { recursive: true });
858
- options.signal.throwIfAborted();
859
- await writeFile(output.path, output.contents, { signal: options.signal });
860
- }));
861
- options.signal.throwIfAborted();
985
+ let output;
986
+ try {
987
+ output = (await bundle.generate({
988
+ banner: banner || void 0,
989
+ codeSplitting: false,
990
+ format,
991
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
992
+ minify,
993
+ polyfillRequire: !(format === "esm" && platform === "node"),
994
+ sourcemap: false
995
+ })).output;
996
+ } finally {
997
+ await bundle.close();
862
998
  }
999
+ options.signal?.throwIfAborted();
1000
+ const chunk = output.find((file) => file.type === "chunk");
1001
+ await mkdir(dirname(outfile), { recursive: true });
1002
+ await writeFile(outfile, chunk.code, { signal: options.signal });
1003
+ options.signal?.throwIfAborted();
863
1004
  }
864
1005
  //#endregion
865
1006
  //#region ../internal/src/build/provider-output-sources.ts
@@ -887,7 +1028,7 @@ function createNodeFunctionConfig(extra = {}) {
887
1028
  return {
888
1029
  handler: "index.mjs",
889
1030
  launcherType: "Nodejs",
890
- runtime: "nodejs22.x",
1031
+ runtime: "nodejs24.x",
891
1032
  shouldAddHelpers: false,
892
1033
  supportsResponseStreaming: true,
893
1034
  ...extra
@@ -1233,10 +1374,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
1233
1374
  assertNetlifyFunctionName(functionName);
1234
1375
  return resolve(functionsRoot, `${functionName}.mjs`);
1235
1376
  }
1377
+ async function declaresTopLevelBinding(code, name) {
1378
+ const { parseSync } = await import("vite");
1379
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
1380
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
1381
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
1382
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
1383
+ });
1384
+ }
1236
1385
  async function appendNetlifyFunctionConfig(outfile, config) {
1237
1386
  if (!config) return;
1238
1387
  const bundled = await readFile(outfile, "utf8");
1239
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
1388
+ const literal = stringifyProviderOutputConfig(config);
1389
+ let exported = `export const config = ${literal}`;
1390
+ if (await declaresTopLevelBinding(bundled, "config")) {
1391
+ const baseName = "vitehubNetlifyFunctionConfig";
1392
+ let name = baseName;
1393
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
1394
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
1395
+ }
1396
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
1240
1397
  }
1241
1398
  async function writeCloudflareDeploymentOutput(options, signal) {
1242
1399
  signal?.throwIfAborted();
@@ -2119,6 +2276,85 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2119
2276
  }
2120
2277
  }
2121
2278
  //#endregion
2279
+ //#region ../internal/src/hints.ts
2280
+ /**
2281
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
2282
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
2283
+ * the file instead of the terminal.
2284
+ */
2285
+ const viteHubHintsFile = ".vitehub/hints.json";
2286
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
2287
+ const runsKey = Symbol.for("vitehub.hints.runs");
2288
+ const shared = globalThis;
2289
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
2290
+ const startedKey = Symbol.for("vitehub.hints.started");
2291
+ const startedShared = globalThis;
2292
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
2293
+ /**
2294
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
2295
+ * Vite root in `app/`, one folder below.
2296
+ */
2297
+ function hintsFile(config) {
2298
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
2299
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
2300
+ }
2301
+ function startRun(config) {
2302
+ const file = hintsFile(config);
2303
+ const run = {
2304
+ file,
2305
+ report: {
2306
+ version: 1,
2307
+ command: config.command,
2308
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2309
+ hints: []
2310
+ },
2311
+ keys: /* @__PURE__ */ new Set()
2312
+ };
2313
+ runs.set(file, run);
2314
+ return run;
2315
+ }
2316
+ function write(run) {
2317
+ mkdirSync(dirname(run.file), { recursive: true });
2318
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
2319
+ }
2320
+ /**
2321
+ * Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
2322
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
2323
+ */
2324
+ function reportViteHubHint(config, diagnostic) {
2325
+ if (skipHints(config)) return;
2326
+ const nuxt = config[VITEHUB_NUXT_HINTS];
2327
+ if (typeof nuxt === "function") return nuxt(diagnostic);
2328
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
2329
+ const hint = {
2330
+ code: diagnostic.code,
2331
+ why: diagnostic.why,
2332
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
2333
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
2334
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
2335
+ };
2336
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
2337
+ if (run.keys.has(key)) return;
2338
+ run.keys.add(key);
2339
+ run.report.hints.push(hint);
2340
+ write(run);
2341
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
2342
+ }
2343
+ function skipHints(config) {
2344
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
2345
+ }
2346
+ /**
2347
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
2348
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
2349
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
2350
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
2351
+ */
2352
+ function startViteHubHints(config, owner = config) {
2353
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
2354
+ started.add(owner);
2355
+ write(startRun(config));
2356
+ }
2357
+ //#endregion
2122
2358
  //#region ../internal/src/provision-state.ts
2123
2359
  const PROVISION_STATE_FILE = ".vitehub/provision.json";
2124
2360
  function getProvisionStatePath(rootDir) {
@@ -2712,7 +2948,7 @@ function hasDatabaseStore(kv) {
2712
2948
  function findDatabasePlugin(plugins) {
2713
2949
  return plugins?.find((plugin) => plugin.name === DATABASE_VITE_PLUGIN_NAME);
2714
2950
  }
2715
- function serializeVirtualConfig(config, databaseImport, env) {
2951
+ function serializeVirtualConfig(config, databaseImport, durabilityReportsStores, env) {
2716
2952
  const resolveStore = (store) => env && store.driver === "upstash" ? resolveUpstashRuntimeValues(store, env) : store;
2717
2953
  const kv = config.kv && env ? {
2718
2954
  ...config.kv,
@@ -2722,6 +2958,7 @@ function serializeVirtualConfig(config, databaseImport, env) {
2722
2958
  return [
2723
2959
  `export const hosting = ${JSON.stringify(config.hosting)};`,
2724
2960
  `export const kv = ${JSON.stringify(kv)};`,
2961
+ `export const durabilityReportsStores = ${durabilityReportsStores};`,
2725
2962
  hasDatabaseStore(config.kv) ? `export const loadDatabases = () => import(${JSON.stringify(databaseImport)}).then(module => module.databases);` : "export const loadDatabases = undefined;",
2726
2963
  "export default { hosting, kv };"
2727
2964
  ].join("\n");
@@ -2802,7 +3039,7 @@ function createCloudflareKVWranglerConfig(kv, provisionState) {
2802
3039
  function serializeCloudflareRuntime(config) {
2803
3040
  return [
2804
3041
  `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
2805
- `import { kvInvalidLimitError, kvKeyLimitCodes, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
3042
+ `import { kvClearOptionsError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes, listKVKeys } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
2806
3043
  "",
2807
3044
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
2808
3045
  "const storages = new Map();",
@@ -2836,7 +3073,11 @@ function serializeCloudflareRuntime(config) {
2836
3073
  "// kvResult throws config errors, for example an unknown store, and returns the other errors.",
2837
3074
  "function createKVStorage(name = \"default\") {",
2838
3075
  " return {",
2839
- " async clear(base, options) { return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(base, options); }); },",
3076
+ " async clear(options) {",
3077
+ " const error = kvClearOptionsError(options);",
3078
+ " if (error) return [error, undefined];",
3079
+ " return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(options?.prefix); });",
3080
+ " },",
2840
3081
  " async delete(key, options) { return kvResult(\"delete\", name, async () => { await resolveStorage(name).removeItem(key, options); }, kvKeyLimitCodes); },",
2841
3082
  " async deleteIfEquals() { return unsupported(\"deleteIfEquals\", name); },",
2842
3083
  " async get(key, options) { return kvResult(\"get\", name, () => resolveStorage(name).getItem(key, options), kvKeyLimitCodes); },",
@@ -2844,9 +3085,8 @@ function serializeCloudflareRuntime(config) {
2844
3085
  " async getMany(keys, options) { return kvResult(\"getMany\", name, () => resolveStorage(name).getMany(keys, options), kvKeyLimitCodes); },",
2845
3086
  " async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options), kvKeyLimitCodes); },",
2846
3087
  " async increment() { return unsupported(\"increment\", name); },",
2847
- " async keys(base, options) { return kvResult(\"keys\", name, () => resolveStorage(name).getKeys(base, options)); },",
2848
3088
  " lock() { return { async acquire() { return unsupported(\"lock\", name); }, async run() { return unsupported(\"lock\", name); } }; },",
2849
- " async list(options) { if (!Number.isInteger(options.limit) || options.limit <= 0) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => resolveStorage(name).listKeys(options), [\"KV_INVALID_CURSOR\"]); },",
3089
+ " async list(options = {}) { if (kvListLimitInvalid(options)) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => listKVKeys(page => resolveStorage(name).listKeys(page), options), [\"KV_INVALID_CURSOR\"]); },",
2850
3090
  " async set(key, value, options) { return kvResult(\"set\", name, async () => { await resolveStorage(name).setItem(key, value, options); }, kvWriteLimitCodes); },",
2851
3091
  " async setMany(entries, options) { return kvResult(\"setMany\", name, async () => { await resolveStorage(name).setMany(entries, options); }, kvWriteLimitCodes); },",
2852
3092
  " async setIfAbsent() { return unsupported(\"setIfAbsent\", name); },",
@@ -2934,7 +3174,6 @@ function hubKV(options, input = {}) {
2934
3174
  postgresDatabase: postgresDatabase()
2935
3175
  });
2936
3176
  let nitroOwned = false;
2937
- let redisEnvWarned = false;
2938
3177
  let nitroOptions;
2939
3178
  const ownedNitroNamespaces = /* @__PURE__ */ new Set();
2940
3179
  let resolved;
@@ -2943,11 +3182,26 @@ function hubKV(options, input = {}) {
2943
3182
  let projectRoot = process.cwd();
2944
3183
  const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options, resolutionInput());
2945
3184
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
3185
+ function reportRedisEnvHint(config) {
3186
+ const hint = kvRedisEnvHint(options, {
3187
+ ...resolutionInput(),
3188
+ env: {
3189
+ ...viteEnv,
3190
+ ...process.env
3191
+ },
3192
+ hosting: getConfig().hosting
3193
+ });
3194
+ if (hint) reportViteHubHint(config, hint);
3195
+ }
2946
3196
  return {
2947
3197
  name: KV_VITE_PLUGIN_NAME,
2948
3198
  enforce: "post",
2949
3199
  api: {
2950
3200
  deploymentEnv: () => kvDeploymentEnv(getConfig().kv),
3201
+ getBuildConfig: () => resolveKVViteConfig(options, {
3202
+ hosting: input.hosting,
3203
+ postgresDatabase: postgresDatabase()
3204
+ }),
2951
3205
  getConfig
2952
3206
  },
2953
3207
  nitro: {
@@ -2955,6 +3209,20 @@ function hubKV(options, input = {}) {
2955
3209
  setup(nitro) {
2956
3210
  nitroOptions = nitro.options;
2957
3211
  if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
3212
+ nitro.hooks?.hook("prerender:config", (config) => {
3213
+ const prerender = resolveKVViteConfig(options, {
3214
+ hosting: input.hosting,
3215
+ prerender: true
3216
+ });
3217
+ if (prerender.kv && Object.values({
3218
+ ...prerender.kv.stores,
3219
+ default: prerender.kv.store
3220
+ }).some((store) => store.driver === "deno-kv")) return;
3221
+ config.virtual = {
3222
+ ...config.virtual,
3223
+ [KV_VIRTUAL_CONFIG_ID]: () => serializeVirtualConfig(prerender, databaseImport, true)
3224
+ };
3225
+ });
2958
3226
  }
2959
3227
  },
2960
3228
  vitehub: {
@@ -3031,6 +3299,7 @@ function hubKV(options, input = {}) {
3031
3299
  order: "pre",
3032
3300
  async handler(config) {
3033
3301
  resolved = config;
3302
+ startViteHubHints(config);
3034
3303
  if (config.command) command = config.command;
3035
3304
  mode = config.mode ?? mode;
3036
3305
  projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
@@ -3041,6 +3310,10 @@ function hubKV(options, input = {}) {
3041
3310
  const provisionState = readProvisionStateSync(projectRoot);
3042
3311
  if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
3043
3312
  if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
3313
+ if (!config.command && command === "build" && Reflect.get(config, "__vitehubNuxtHints")) reportRedisEnvHint({
3314
+ ...config,
3315
+ command
3316
+ });
3044
3317
  }
3045
3318
  },
3046
3319
  configureServer(server) {
@@ -3081,7 +3354,10 @@ function hubKV(options, input = {}) {
3081
3354
  const kv = getConfig().kv;
3082
3355
  if (command === "build" && isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
3083
3356
  }
3084
- if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig(), databaseImport, command === "serve" && options?.ssr ? viteEnv : void 0);
3357
+ if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) {
3358
+ const durabilityReportsStores = command === "build" && (resolved?.plugins?.some((plugin) => plugin.name === "vite-hub/durability/nitro") ?? false);
3359
+ return serializeVirtualConfig(getConfig(), databaseImport, durabilityReportsStores, command === "serve" && options?.ssr ? viteEnv : void 0);
3360
+ }
3085
3361
  }
3086
3362
  },
3087
3363
  buildStart: {
@@ -3089,17 +3365,8 @@ function hubKV(options, input = {}) {
3089
3365
  handler() {
3090
3366
  runtimeConfig = void 0;
3091
3367
  providerOutputGenerations.capture(this, providerOutput);
3092
- if (command !== "build" || redisEnvWarned) return;
3093
- redisEnvWarned = true;
3094
- const warning = kvRedisEnvWarning(options, {
3095
- ...resolutionInput(),
3096
- env: {
3097
- ...viteEnv,
3098
- ...process.env
3099
- },
3100
- hosting: getConfig().hosting
3101
- });
3102
- if (warning) console.warn(warning);
3368
+ if (command !== "build" || !resolved) return;
3369
+ reportRedisEnvHint(resolved);
3103
3370
  }
3104
3371
  },
3105
3372
  buildEnd: {