@vite-hub/workspace 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +17 -13
  2. package/dist/blob-database.d.ts +1 -1
  3. package/dist/blob-database.js +6 -6
  4. package/dist/checkout.js +1 -1
  5. package/dist/cloudflare.d.ts +1 -1
  6. package/dist/cloudflare.js +1 -1
  7. package/dist/{config-BQKcPawI.d.ts → config-CDeGd0RB.d.ts} +1 -1
  8. package/dist/{config-BAgL2dtB.js → config-D1QENneP.js} +21 -21
  9. package/dist/durability.d.ts +1 -1
  10. package/dist/durability.js +2 -2
  11. package/dist/{error-diagnostics-CtKjGtGb.js → error-diagnostics-B5s9kNEA.js} +10 -6
  12. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-CQ4BUqRe.js} +5 -1
  13. package/dist/{file-2pFYNtsU.js → file-CqG9zqiF.js} +1 -1
  14. package/dist/{files-BOo4SbwE.js → files-B6wpAhEx.js} +1 -1
  15. package/dist/files.d.ts +5 -5
  16. package/dist/files.js +4 -4
  17. package/dist/{github-CrYp4v8k.js → github-DKAlO0Vh.js} +3 -3
  18. package/dist/{glob-B8YGvTrZ.js → glob-BOqSKzSg.js} +1 -1
  19. package/dist/{host-BFBpXn0N.js → host-Bf1a2uo_.js} +4 -4
  20. package/dist/{hosted-vercel-blob-B3-wRdUm.js → hosted-vercel-blob-AbXG8fvR.js} +3 -3
  21. package/dist/hosted-vercel-blob.d.ts +1 -1
  22. package/dist/hosted-vercel-blob.js +1 -1
  23. package/dist/{hosted-KcUR_jPv.js → hosted-zG7HJaE4.js} +6 -6
  24. package/dist/hosted.d.ts +1 -1
  25. package/dist/hosted.js +1 -1
  26. package/dist/index.d.ts +12 -12
  27. package/dist/index.js +15 -15
  28. package/dist/{lifecycle-B-enk_4A.js → lifecycle-D8FdpBod.js} +4 -4
  29. package/dist/loader.d.ts +1 -1
  30. package/dist/loader.js +1 -1
  31. package/dist/{mcp-resources-DF0F5rcL.js → mcp-resources-DntxtmDU.js} +1 -1
  32. package/dist/{memory-BOexthyW.js → memory-D5jq9HZW.js} +1 -1
  33. package/dist/{metadata-target-CWz6KHKq.js → metadata-target-DDoOQNp1.js} +3 -3
  34. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
  35. package/dist/{operations-C6FpR8Rr.js → operations-D8uCpzhM.js} +4 -4
  36. package/dist/{operations-CE2drFih.js → operations-DsY2MQnG.js} +207 -141
  37. package/dist/operations.d.ts +2 -2
  38. package/dist/operations.js +1 -1
  39. package/dist/{path-AxMho1wo.d.ts → path-uxLkzrZm.d.ts} +1 -1
  40. package/dist/{plugins-C8C0auoW.d.ts → plugins-CsrXCA1Q.d.ts} +1 -1
  41. package/dist/{provider-9s4Ufkm5.js → provider-sm9uzkLg.js} +7 -6
  42. package/dist/providers/github/store.d.ts +1 -1
  43. package/dist/providers/github/store.js +1 -1
  44. package/dist/{registry-B3BBm4Ts.d.ts → registry-CFl1Htyc.d.ts} +1 -1
  45. package/dist/{registry-CYNN623b.d.ts → registry-CwryP59t.d.ts} +2 -2
  46. package/dist/{registry-CNphafBx.js → registry-DmVfUe4K.js} +2 -2
  47. package/dist/runtime/assets.d.ts +1 -1
  48. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  49. package/dist/runtime/empty-registry.d.ts +2 -2
  50. package/dist/runtime/registry.d.ts +1 -1
  51. package/dist/runtime/state.d.ts +4 -4
  52. package/dist/runtime/state.js +6 -6
  53. package/dist/runtime/workspace.d.ts +1 -1
  54. package/dist/runtime/workspace.js +1 -1
  55. package/dist/runtime.d.ts +7 -7
  56. package/dist/runtime.js +13 -13
  57. package/dist/{server-8tGltlGz.js → server-Cd4-iCh5.js} +4 -4
  58. package/dist/server.d.ts +2 -2
  59. package/dist/server.js +1 -1
  60. package/dist/{shared-B3_EUk89.js → shared-ovXVSV3-.js} +9 -5
  61. package/dist/source-metadata.d.ts +2 -2
  62. package/dist/source-metadata.js +3 -3
  63. package/dist/{state-BISnUf1s.d.ts → state-C-YtsaiJ.d.ts} +4 -4
  64. package/dist/{state-DbrW-njQ.js → state-Cb_hIyAw.js} +4 -4
  65. package/dist/{store-ybhyD38Z.js → store-NZoRto-Y.js} +107 -7
  66. package/dist/{sync-CCD_VYC8.js → sync-CrT8zjwc.js} +3 -3
  67. package/dist/{target-jWhTdIuF.js → target-Dm9dHAVJ.js} +1 -1
  68. package/dist/test.d.ts +1 -1
  69. package/dist/test.js +1 -1
  70. package/dist/{types-BbtwmBZ5.d.ts → types-1Z-tKK3g.d.ts} +17 -2
  71. package/dist/{use-CSpT5W87.js → use-B0o5HoBl.js} +8 -8
  72. package/dist/{use-C6lV3-wC.d.ts → use-CjbF8EO9.d.ts} +1 -1
  73. package/dist/{utils-CgMZCHsX.js → utils-Dw-WULEZ.js} +10 -4
  74. package/dist/vite.d.ts +4 -2
  75. package/dist/vite.js +559 -354
  76. package/dist/{workspace-CYB2xZ1T.d.ts → workspace-CIXgHeyX.d.ts} +1 -1
  77. package/dist/{workspace-sPWn2Jxj.js → workspace-DvKu5PRa.js} +12 -12
  78. package/package.json +14 -14
package/dist/vite.js CHANGED
@@ -1,19 +1,20 @@
1
1
  import { n as __exportAll$1, r as __toESM, t as __commonJSMin } from "./rolldown-runtime-rQ84J-ij.js";
2
- import { t as createMemoryWorkspaceStore } from "./memory-BOexthyW.js";
2
+ import { t as createMemoryWorkspaceStore } from "./memory-D5jq9HZW.js";
3
3
  import { t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
4
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B5s9kNEA.js";
5
5
  import { assertNoSymlinks, checkoutFailure, conflictMarkerPatterns, folderOf, formatWorkspaceStatus, ignoredName, localCheckoutStatus, pullWorkspaces, pushWorkspaces, resolveWorkspaceConflicts, workspaceLockFile, workspaceStatus } from "./checkout.js";
6
6
  import { n as isRecordOrFunction, t as isRecord$1 } from "./object-Da1zyPCR.js";
7
- import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
8
- import { n as isWorkspaceStore, r as normalizeWorkspaceStoreOptions } from "./provider-9s4Ufkm5.js";
9
- import { i as installHostedWorkspaceRuntime } from "./hosted-KcUR_jPv.js";
10
- import { a as normalizeWorkspaceSources, n as createSourceContext } from "./config-BAgL2dtB.js";
11
- import { s as workspaceRegistryLoadError, t as normalizeWorkspaceDefinition } from "./registry-CNphafBx.js";
12
- import { n as installHostedVercelBlobWorkspaceRuntime } from "./hosted-vercel-blob-B3-wRdUm.js";
13
- import { _ as isServerEnvironment, a as readViteHubDevTargetOption, b as resolveViteHubProjectRoot, c as relativeDefinitionFile, d as relative$1, f as resolve$1, g as generatedViteHubWatchIgnoredAddition, h as createViteHubEnvImportAliases, i as fetchViteHubDevEndpoint, l as dirname$1, m as createNoExternalAddition, n as callOperationFromCli, o as resolveViteHubDevServerUrl, r as discoverViteHubDevServer, s as redactInspectionText, t as workspaceOperations, u as isAbsolute$1, v as loadNativePackageModule, x as shouldSkipViteProviderBuild, y as loadsViteHubPackagesNatively } from "./operations-CE2drFih.js";
14
- import { a as refreshWorkspaceDevToken, c as workspaceDevHeader, d as workspaceDevTokenHeader, f as workspaceDevTokenServerId, n as ensureWorkspaceDevToken, o as runWorkspaceDevCommand, p as isViteHubSecretEqual, r as readWorkspaceDevToken, s as validateWorkspaceDevToken, u as workspaceDevRoute } from "./server-8tGltlGz.js";
15
- import { n as syncWorkspaceDefinition } from "./lifecycle-B-enk_4A.js";
16
- import { createRequire } from "node:module";
7
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
8
+ import { n as isWorkspaceStore, r as normalizeWorkspaceStoreOptions } from "./provider-sm9uzkLg.js";
9
+ import { i as installHostedWorkspaceRuntime } from "./hosted-zG7HJaE4.js";
10
+ import { a as normalizeWorkspaceSources, n as createSourceContext } from "./config-D1QENneP.js";
11
+ import { s as workspaceRegistryLoadError, t as normalizeWorkspaceDefinition } from "./registry-DmVfUe4K.js";
12
+ import { n as installHostedVercelBlobWorkspaceRuntime } from "./hosted-vercel-blob-AbXG8fvR.js";
13
+ import { S as resolve$1, _ as redactInspectionText, a as createNoExternalAddition, b as isAbsolute$1, c as isProductionBuild, d as resolveViteHubProjectRoot, f as shouldSkipViteProviderBuild, g as requireViteHubDevServerUrl, h as readViteHubDevTargetOption, i as createNativePackageLoading, l as isServerEnvironment, m as fetchViteHubDevEndpoint, n as callOperationFromCli, o as createViteHubEnvImportAliases, p as discoverViteHubDevServer, s as generatedViteHubWatchIgnoredAddition, t as workspaceOperations, u as publishViteHubDevServer, v as relativeDefinitionFile, x as relative$1, y as dirname$1 } from "./operations-DsY2MQnG.js";
14
+ import { a as refreshWorkspaceDevToken, c as workspaceDevHeader, d as workspaceDevTokenHeader, f as workspaceDevTokenServerId, n as ensureWorkspaceDevToken, o as runWorkspaceDevCommand, p as isViteHubSecretEqual, r as readWorkspaceDevToken, s as validateWorkspaceDevToken, u as workspaceDevRoute } from "./server-Cd4-iCh5.js";
15
+ import { n as syncWorkspaceDefinition } from "./lifecycle-D8FdpBod.js";
16
+ import { createRequire, isBuiltin } from "node:module";
17
+ import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
17
18
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
18
19
  import { createHash } from "node:crypto";
19
20
  import { defineDiagnostics } from "nostics";
@@ -280,20 +281,76 @@ function resolveViteHubBundleDefines(config) {
280
281
  return defines;
281
282
  }
282
283
  //#endregion
283
- //#region ../internal/src/build/esbuild.ts
284
- const viteRawNamespace = "vitehub-vite-raw";
285
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
284
+ //#region ../internal/src/build/ast-walk.ts
285
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
286
+ function moduleLanguage(file) {
287
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
288
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
289
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
290
+ return "ts";
291
+ }
292
+ function isNode(value) {
293
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
294
+ }
295
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
296
+ function walk(node, visit, parent) {
297
+ if (visit(node, parent) === false) return;
298
+ const fields = node;
299
+ for (const key in fields) {
300
+ const child = fields[key];
301
+ if (typeof child !== "object" || child === null || key === "parent") continue;
302
+ if (Array.isArray(child)) {
303
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
304
+ } else if (isNode(child)) walk(child, visit, node);
305
+ }
306
+ }
307
+ //#endregion
308
+ //#region ../internal/src/build/rolldown.ts
309
+ const viteRawPrefix = "\0vitehub-vite-raw:";
310
+ const markdownTemplatePrefix = "\0vitehub-markdown-template:";
286
311
  const markdownTemplateFileSuffix = ".template.md";
287
312
  const markdownTemplateModuleQuery = "markdown-template";
288
313
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
289
314
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
315
+ const resolvingViteAlias = "vitehubResolvingAlias";
290
316
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
317
+ /**
318
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
319
+ * Vite+, instead of installing a second bundler.
320
+ */
321
+ async function importRolldown() {
322
+ let entry;
323
+ try {
324
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
325
+ } catch (error) {
326
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
327
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
328
+ }
329
+ return await import(pathToFileURL(entry).href);
330
+ }
291
331
  function normalizePathSeparators(path) {
292
332
  return path.replaceAll("\\", "/");
293
333
  }
294
334
  function escapeRegExp(value) {
295
335
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
296
336
  }
337
+ function isRelativeSpecifier(path) {
338
+ return /^\.\.?[\\/]/.test(path);
339
+ }
340
+ function isBareSpecifier(id) {
341
+ return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
342
+ }
343
+ /** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
344
+ function importerDir(importer, workingDir) {
345
+ return importer && isAbsolute(importer) ? dirname(importer) : workingDir;
346
+ }
347
+ /** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
348
+ function importerFor(importer, workingDir) {
349
+ return importer ?? join(workingDir, "__vitehub_entry__.js");
350
+ }
351
+ function isFileResolution(resolved) {
352
+ return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
353
+ }
297
354
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
298
355
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
299
356
  if (!Array.isArray(exportsValue) && !isRecord$1(exportsValue)) return [];
@@ -320,7 +377,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
320
377
  }
321
378
  return candidates;
322
379
  }
323
- function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
380
+ /**
381
+ * Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
382
+ * resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
383
+ * same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
384
+ */
385
+ function resolveFrom(context, specifier, request, workingDir, flag) {
386
+ return context.resolve(specifier, importerFor(request.importer, workingDir), {
387
+ custom: {
388
+ ...request.custom,
389
+ [flag]: true
390
+ },
391
+ isEntry: request.isEntry,
392
+ kind: request.kind,
393
+ skipSelf: true
394
+ });
395
+ }
396
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
324
397
  const entries = Object.entries(aliases || {});
325
398
  if (!entries.length) return;
326
399
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -340,186 +413,175 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
340
413
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
341
414
  };
342
415
  }));
416
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
343
417
  return {
344
418
  name: "vitehub-resolved-alias",
345
- setup(build) {
346
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
347
- build.onResolve({ filter: /.*/ }, async (args) => {
348
- if (args.pluginData?.[skipResolvedAlias]) return;
349
- const resolveWithContext = (specifier) => build.resolve(specifier, {
350
- importer: args.importer,
351
- kind: args.kind,
352
- namespace: args.namespace,
353
- pluginData: {
354
- ...args.pluginData,
355
- [skipResolvedAlias]: true
356
- },
357
- resolveDir: args.resolveDir,
358
- with: args.with
359
- });
360
- const aliases = await resolvedEntries;
361
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
362
- let matchedAlias = match?.specifier;
363
- let matchedSpecifier = match ? args.path : void 0;
364
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
365
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
366
- let canonicalSpecifier = normalizedSpecifier;
367
- const canonicalizeSpecifier = async () => {
368
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
369
- return canonicalSpecifier;
370
- };
371
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
372
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
373
- await canonicalizeSpecifier();
374
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
375
- }
376
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
377
- const candidates = [];
378
- for (const alias of aliases) {
379
- if (isAbsolute(alias.specifier)) continue;
380
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
381
- const aliasSegments = packageAlias.split("/");
382
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
383
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
384
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
385
- const scopeMarker = `/node_modules/${packageAlias}/`;
386
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
387
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
388
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
389
- }
390
- const packageMarker = `/node_modules/${packageName}/`;
391
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
392
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
393
- const cacheKey = [
394
- alias.specifier,
395
- alias.prefix,
396
- resolutionScope,
397
- normalizedSpecifier,
398
- args.importer,
399
- args.resolveDir,
400
- args.kind,
401
- args.namespace,
402
- JSON.stringify(args.with)
403
- ].join("\0");
404
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
405
- if (!resolution) {
406
- resolution = (async () => {
407
- let resolvedAliasPath;
408
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
409
- else if (resolutionScope) {
410
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
411
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
412
- if (!isRecord$1(parsedPackageJson)) return;
413
- const packageJson = parsedPackageJson;
414
- if (packageJson.exports === void 0 && !alias.prefix) {
415
- const resolvedCandidate = await resolveWithContext(alias.specifier);
416
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
417
- canonical: alias.specifier,
418
- normalized: alias.specifier,
419
- publicSpecifier: alias.specifier
420
- };
421
- return;
422
- }
423
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
424
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
425
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
426
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
427
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
428
- matchingPublicSpecifiers.add(publicSpecifier);
429
- }
430
- if (matchingPublicSpecifiers.size === 1) {
431
- const publicSpecifier = [...matchingPublicSpecifiers][0];
432
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
433
- canonical: publicSpecifier,
434
- normalized: publicSpecifier,
435
- publicSpecifier
436
- };
437
- }
419
+ async resolveId(source, importer, extra) {
420
+ if (extra.custom?.[skipResolvedAlias]) return;
421
+ const request = {
422
+ custom: extra.custom,
423
+ importer,
424
+ isEntry: extra.isEntry,
425
+ kind: extra.kind
426
+ };
427
+ const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
428
+ const resolveDir = importerDir(importer, workingDir);
429
+ const aliases = await resolvedEntries;
430
+ let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
431
+ let matchedAlias = match?.specifier;
432
+ let matchedSpecifier = match ? source : void 0;
433
+ const specifier = isRelativeSpecifier(source) ? resolve(resolveDir, source) : source;
434
+ const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
435
+ let canonicalSpecifier = normalizedSpecifier;
436
+ const canonicalizeSpecifier = async () => {
437
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
438
+ return canonicalSpecifier;
439
+ };
440
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
441
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
442
+ await canonicalizeSpecifier();
443
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
444
+ }
445
+ if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
446
+ const candidates = [];
447
+ for (const alias of aliases) {
448
+ if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
449
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
450
+ const aliasSegments = packageAlias.split("/");
451
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
452
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
453
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
454
+ const scopeMarker = `/node_modules/${packageAlias}/`;
455
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
456
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
457
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
458
+ }
459
+ const packageMarker = `/node_modules/${packageName}/`;
460
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
461
+ if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
462
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
463
+ const cacheKey = [
464
+ alias.specifier,
465
+ alias.prefix,
466
+ resolutionScope,
467
+ normalizedSpecifier,
468
+ importer,
469
+ extra.kind,
470
+ extra.isEntry
471
+ ].join("\0");
472
+ const cacheable = !extra.custom || !Object.keys(extra.custom).length;
473
+ let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
474
+ if (!resolution) {
475
+ resolution = (async () => {
476
+ let resolvedAliasPath;
477
+ if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
478
+ else if (resolutionScope) {
479
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
480
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
481
+ if (!isRecord$1(parsedPackageJson)) return;
482
+ const packageJson = parsedPackageJson;
483
+ if (packageJson.exports === void 0 && !alias.prefix) {
484
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
485
+ if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve(resolvedCandidate.id)) === normalizedSpecifier) return {
486
+ canonical: alias.specifier,
487
+ normalized: alias.specifier,
488
+ publicSpecifier: alias.specifier
489
+ };
438
490
  return;
439
- } else {
440
- const resolvedAlias = await resolveWithContext(alias.specifier);
441
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
442
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
443
491
  }
444
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
445
- return {
446
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
447
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
448
- };
449
- })();
450
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
451
- }
452
- candidates.push({
453
- alias,
454
- resolution
455
- });
492
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
493
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
494
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
495
+ if (!isFileResolution(resolvedCandidate)) continue;
496
+ if (normalizePathSeparators(resolve(resolvedCandidate.id)) !== normalizedSpecifier) continue;
497
+ matchingPublicSpecifiers.add(publicSpecifier);
498
+ }
499
+ if (matchingPublicSpecifiers.size === 1) {
500
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
501
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
502
+ canonical: publicSpecifier,
503
+ normalized: publicSpecifier,
504
+ publicSpecifier
505
+ };
506
+ }
507
+ return;
508
+ } else {
509
+ const resolvedAlias = await resolveWithContext(alias.specifier);
510
+ if (!isFileResolution(resolvedAlias)) return;
511
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.id));
512
+ }
513
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
514
+ return {
515
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
516
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
517
+ };
518
+ })();
519
+ if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
456
520
  }
457
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
458
- for (const { alias, resolution } of candidates) {
459
- const paths = await resolution;
460
- if (!paths) continue;
461
- if (paths.publicSpecifier) {
462
- match = alias;
463
- matchedAlias = alias.specifier;
464
- matchedSpecifier = paths.publicSpecifier;
465
- break;
466
- }
467
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
468
- let canonicalMatch = false;
469
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
470
- await canonicalizeSpecifier();
471
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
472
- }
473
- if (normalizedMatch || canonicalMatch) {
474
- match = alias;
475
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
476
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
477
- break;
478
- }
521
+ candidates.push({
522
+ alias,
523
+ resolution
524
+ });
525
+ }
526
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
527
+ for (const { alias, resolution } of candidates) {
528
+ const paths = await resolution;
529
+ if (!paths) continue;
530
+ if (paths.publicSpecifier) {
531
+ match = alias;
532
+ matchedAlias = alias.specifier;
533
+ matchedSpecifier = paths.publicSpecifier;
534
+ break;
535
+ }
536
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
537
+ let canonicalMatch = false;
538
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
539
+ await canonicalizeSpecifier();
540
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
541
+ }
542
+ if (normalizedMatch || canonicalMatch) {
543
+ match = alias;
544
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
545
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
546
+ break;
479
547
  }
480
548
  }
481
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
482
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
483
- if (!match) return;
484
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
485
- if (!target) return;
486
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
487
- });
549
+ }
550
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
551
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
552
+ if (!match) return;
553
+ const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
554
+ if (!target) return;
555
+ const resolvedTarget = isRelativeSpecifier(target) ? resolve(aliasResolveDir, target) : target;
556
+ const resolved = await resolveWithContext(resolvedTarget);
557
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
558
+ return resolved;
488
559
  }
489
560
  };
490
561
  }
491
- function createViteAliasPlugin(aliases) {
562
+ function createViteAliasPlugin(aliases, workingDir) {
492
563
  if (!Array.isArray(aliases)) return;
493
- const resolvingAlias = "vitehubResolvingAlias";
494
564
  return {
495
565
  name: "vitehub-vite-alias",
496
- setup(build) {
497
- build.onResolve({ filter: /.*/ }, async (args) => {
498
- if (args.pluginData?.[resolvingAlias]) return;
499
- const alias = aliases.find(({ find }) => {
500
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
501
- find.lastIndex = 0;
502
- return find.test(args.path);
503
- });
504
- if (!alias) return;
505
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
506
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
507
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
508
- const result = await build.resolve(replacement, {
509
- importer: args.importer,
510
- kind: args.kind,
511
- namespace: args.namespace,
512
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
513
- resolveDir: args.resolveDir,
514
- with: args.with
515
- });
516
- const pluginData = Object.assign({}, result.pluginData);
517
- Reflect.deleteProperty(pluginData, resolvingAlias);
518
- return {
519
- ...result,
520
- pluginData
521
- };
566
+ async resolveId(source, importer, extra) {
567
+ if (extra.custom?.[resolvingViteAlias]) return;
568
+ const alias = aliases.find(({ find }) => {
569
+ if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
570
+ find.lastIndex = 0;
571
+ return find.test(source);
522
572
  });
573
+ if (!alias) return;
574
+ if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
575
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
576
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
577
+ const resolved = await resolveFrom(this, replacement, {
578
+ custom: extra.custom,
579
+ importer,
580
+ isEntry: extra.isEntry,
581
+ kind: extra.kind
582
+ }, workingDir, resolvingViteAlias);
583
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
584
+ return resolved;
523
585
  }
524
586
  };
525
587
  }
@@ -558,174 +620,255 @@ async function resolveViteRawSpecifier(path, rootDir) {
558
620
  return resolve(rootDir, rootRelativePath);
559
621
  }
560
622
  }
561
- function createViteRawPlugin(rootDir, frameworkRuntime) {
623
+ function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
562
624
  return {
563
625
  name: "vitehub-vite-raw",
564
- setup(build) {
565
- build.onResolve({
566
- filter: /^@vite-hub\/markdown-template$/,
567
- namespace: viteMarkdownTemplateNamespace
568
- }, async (args) => {
569
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
570
- return build.resolve("vite-hub/markdown-template", {
571
- importer: args.importer,
572
- kind: args.kind,
573
- resolveDir: args.resolveDir
626
+ async resolveId(source, importer, extra) {
627
+ if (source === markdownTemplateRuntimeSpecifier && importer?.startsWith(markdownTemplatePrefix)) {
628
+ if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier));
629
+ return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
630
+ custom: extra.custom,
631
+ kind: extra.kind
574
632
  });
575
- });
576
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
577
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
578
- const markdownTemplate = parseMarkdownTemplateRequest$1(args.path);
579
- const raw = hasViteRawQuery(args.path);
580
- if (!markdownTemplate && !raw) return;
581
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
582
- let pluginData = args.pluginData;
583
- if (markdownTemplate) pluginData = {
584
- ...args.pluginData,
585
- [skipMarkdownTemplateResolve]: true
586
- };
587
- const resolved = await build.resolve(specifier, {
588
- importer: args.importer,
589
- kind: args.kind,
590
- namespace: args.namespace,
591
- pluginData,
592
- resolveDir: args.resolveDir,
593
- with: args.with
594
- });
595
- if (resolved.errors.length) return {
596
- errors: resolved.errors,
597
- warnings: resolved.warnings
598
- };
599
- if (resolved.external) return {
600
- external: true,
601
- namespace: resolved.namespace,
602
- path: resolved.path,
603
- pluginData: resolved.pluginData,
604
- sideEffects: resolved.sideEffects,
605
- suffix: resolved.suffix,
606
- warnings: resolved.warnings
607
- };
608
- if (resolved.namespace !== "file") return {
609
- 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.` }],
610
- warnings: resolved.warnings
611
- };
612
- return {
613
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
614
- path: resolved.path,
615
- pluginData: resolved.pluginData,
616
- sideEffects: resolved.sideEffects,
617
- suffix: resolved.suffix,
618
- warnings: resolved.warnings
619
- };
620
- });
621
- build.onLoad({
622
- filter: /.*/,
623
- namespace: viteRawNamespace
624
- }, async (args) => ({
625
- contents: await readFile(args.path),
626
- loader: "text"
627
- }));
628
- build.onLoad({
629
- filter: /.*/,
630
- namespace: viteMarkdownTemplateNamespace
631
- }, async (args) => ({
632
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
633
- loader: "js",
634
- resolveDir: dirname(args.path)
635
- }));
633
+ }
634
+ if (extra.custom?.[skipMarkdownTemplateResolve]) return;
635
+ const markdownTemplate = parseMarkdownTemplateRequest$1(source);
636
+ const raw = hasViteRawQuery(source);
637
+ if (!markdownTemplate && !raw) return;
638
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
639
+ const resolved = await resolveFrom(this, specifier, {
640
+ custom: extra.custom,
641
+ importer,
642
+ isEntry: extra.isEntry,
643
+ kind: extra.kind
644
+ }, workingDir, skipMarkdownTemplateResolve);
645
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
646
+ if (resolved.external) return {
647
+ id: resolved.id,
648
+ external: resolved.external
649
+ };
650
+ const resolvedId = resolved.id;
651
+ 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.`);
652
+ return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
653
+ },
654
+ async load(id) {
655
+ if (id.startsWith(viteRawPrefix)) return {
656
+ code: await readFile(id.slice(18), "utf8"),
657
+ moduleType: "text"
658
+ };
659
+ if (id.startsWith(markdownTemplatePrefix)) return {
660
+ code: renderMarkdownTemplateModule(await readFile(id.slice(27), "utf8")),
661
+ moduleType: "js"
662
+ };
636
663
  }
637
664
  };
638
665
  }
639
666
  function createFileUrlPlugin() {
640
667
  return {
641
668
  name: "vitehub-file-url",
642
- setup(build) {
643
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
669
+ resolveId(source) {
670
+ if (source.startsWith("file:")) return fileURLToPath(source);
644
671
  }
645
672
  };
646
673
  }
647
674
  /**
648
675
  * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
649
676
  * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
677
+ * Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
650
678
  */
651
- function createWasmModulePlugin(outdir) {
679
+ function createWasmModulePlugin(outdir, workingDir, copy) {
652
680
  return {
653
681
  name: "vitehub-wasm-module",
654
- setup(build) {
655
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
656
- const resolved = await build.resolve(args.path.slice(0, -7), {
657
- importer: args.importer,
658
- kind: args.kind,
659
- resolveDir: args.resolveDir
660
- });
661
- if (resolved.errors.length) return { errors: resolved.errors };
662
- const bytes = await readFile(resolved.path);
663
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
664
- await mkdir(outdir, { recursive: true });
665
- await copyFile(resolved.path, join(outdir, name));
666
- return {
667
- external: true,
668
- path: `./${name}`
669
- };
682
+ async resolveId(source, importer, extra) {
683
+ if (!source.endsWith(".wasm?module")) return;
684
+ const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
685
+ custom: extra.custom,
686
+ kind: extra.kind
670
687
  });
688
+ if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
689
+ if (!copy) return resolved.id;
690
+ const bytes = await readFile(resolved.id);
691
+ const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
692
+ await mkdir(outdir, { recursive: true });
693
+ await copyFile(resolved.id, join(outdir, name));
694
+ return {
695
+ id: `./${name}`,
696
+ external: true
697
+ };
698
+ }
699
+ };
700
+ }
701
+ /**
702
+ * Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
703
+ */
704
+ function createExternalPackagesPlugin() {
705
+ return {
706
+ name: "vitehub-external-packages",
707
+ async resolveId(source, importer, extra) {
708
+ if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
709
+ id: source,
710
+ external: true
711
+ };
712
+ if (source.startsWith("#")) return await this.resolve(source, importer, {
713
+ custom: extra.custom,
714
+ kind: extra.kind
715
+ }) ?? {
716
+ id: source,
717
+ external: true
718
+ };
719
+ if (isBareSpecifier(source) && !isBuiltin(source)) return {
720
+ id: source,
721
+ external: true
722
+ };
723
+ }
724
+ };
725
+ }
726
+ function hasImportRejectionHandler(importNode, parents) {
727
+ let expression = importNode;
728
+ let parent = parents.get(expression);
729
+ while (parent?.type === "MemberExpression" && parent.object === expression) {
730
+ const call = parents.get(parent);
731
+ if (call?.type !== "CallExpression" || call.callee !== parent) break;
732
+ const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
733
+ const handler = call.arguments[method === "then" ? 1 : 0];
734
+ if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
735
+ if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
736
+ }
737
+ if (method !== "then" && method !== "finally") break;
738
+ expression = call;
739
+ parent = parents.get(expression);
740
+ }
741
+ if (parent?.type !== "AwaitExpression") return false;
742
+ for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
743
+ if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
744
+ if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
745
+ child = ancestor;
746
+ }
747
+ return false;
748
+ }
749
+ function createOptionalImportPlugin() {
750
+ const prefix = "\0vitehub-optional-import:";
751
+ return {
752
+ name: "vitehub-optional-import",
753
+ resolveId(source) {
754
+ if (source.startsWith(prefix)) return {
755
+ id: source.slice(25),
756
+ external: "absolute"
757
+ };
758
+ },
759
+ transform: {
760
+ order: "post",
761
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
762
+ async handler(code, id) {
763
+ const { parseSync } = await import("vite");
764
+ const module = parseSync(id, code, {
765
+ lang: moduleLanguage(id),
766
+ preserveParens: false,
767
+ sourceType: "module"
768
+ });
769
+ if (module.errors.length) return;
770
+ const parents = /* @__PURE__ */ new WeakMap();
771
+ const handled = [];
772
+ walk(module.program, (node, parent) => {
773
+ if (parent) parents.set(node, parent);
774
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
775
+ if (hasImportRejectionHandler(node, parents)) handled.push({
776
+ source: node.source.value,
777
+ start: node.source.start,
778
+ end: node.source.end
779
+ });
780
+ });
781
+ if (!handled.length) return;
782
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
783
+ 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);
784
+ return code;
785
+ }
671
786
  }
672
787
  };
673
788
  }
789
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
790
+ function createExternalMatcher(patterns) {
791
+ if (!patterns?.length) return;
792
+ const matchers = patterns.map((pattern) => {
793
+ if (pattern.includes("*")) {
794
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`);
795
+ return (id) => expression.test(id);
796
+ }
797
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
798
+ });
799
+ return (id) => matchers.some((matches) => matches(id));
800
+ }
674
801
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
675
- const { build: bundle } = await import("esbuild");
802
+ const { rolldown } = await importRolldown();
676
803
  options.signal?.throwIfAborted();
677
804
  const format = options.format || "esm";
678
805
  const platform = options.platform || "neutral";
679
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
806
+ const workingDir = options.workingDir ?? process.cwd();
680
807
  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/"));
681
808
  const plugins = [];
682
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
809
+ plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
810
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
683
811
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
684
812
  plugins.push(...options.plugins ?? [], createFileUrlPlugin());
813
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
685
814
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
686
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
687
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
688
- const result = await bundle({
689
- absWorkingDir: options.workingDir,
690
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
691
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
692
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
693
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
694
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
695
- "}"
696
- ] : []].filter(Boolean).join("\n") } : void 0,
697
- bundle: true,
698
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
699
- define: options.define,
700
- entryPoints: [entryFile],
701
- external: options.external,
702
- format,
703
- keepNames: options.minifySyntax || options.minifyIdentifiers,
704
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
705
- logLevel: "silent",
706
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
707
- resolveExtensions: options.extensions,
708
- minifyIdentifiers: options.minifyIdentifiers,
709
- minifySyntax: options.minifySyntax,
710
- minifyWhitespace: options.minifyWhitespace,
711
- outfile,
712
- packages: options.packages,
815
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
816
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
817
+ plugins.push(createOptionalImportPlugin());
818
+ const isExternal = createExternalMatcher(options.external);
819
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
820
+ compress: options.minifySyntax ?? false,
821
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
822
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
823
+ } : false;
824
+ const banner = [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");
831
+ const bundle = await rolldown({
832
+ cwd: workingDir,
833
+ external: isExternal ? (id) => isExternal(id) : void 0,
834
+ input: entryFile,
835
+ onLog(level, log) {
836
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
837
+ },
838
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
713
839
  platform,
714
- preserveSymlinks: options.preserveSymlinks,
715
840
  plugins,
716
- sourcemap: false,
717
- target: "es2022",
718
- write: options.signal ? false : true
841
+ resolve: {
842
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
843
+ extensions: options.extensions,
844
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
845
+ symlinks: !options.preserveSymlinks
846
+ },
847
+ transform: {
848
+ define: options.define,
849
+ target: "es2022"
850
+ },
851
+ tsconfig: options.tsconfig ?? true
719
852
  });
720
- options.signal?.throwIfAborted();
721
- if (options.signal) {
722
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
723
- await mkdir(dirname(output.path), { recursive: true });
724
- options.signal.throwIfAborted();
725
- await writeFile(output.path, output.contents, { signal: options.signal });
726
- }));
727
- options.signal.throwIfAborted();
853
+ let output;
854
+ try {
855
+ output = (await bundle.generate({
856
+ banner: banner || void 0,
857
+ codeSplitting: false,
858
+ format,
859
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
860
+ minify,
861
+ polyfillRequire: !(format === "esm" && platform === "node"),
862
+ sourcemap: false
863
+ })).output;
864
+ } finally {
865
+ await bundle.close();
728
866
  }
867
+ options.signal?.throwIfAborted();
868
+ const chunk = output.find((file) => file.type === "chunk");
869
+ await mkdir(dirname(outfile), { recursive: true });
870
+ await writeFile(outfile, chunk.code, { signal: options.signal });
871
+ options.signal?.throwIfAborted();
729
872
  }
730
873
  //#endregion
731
874
  //#region ../internal/src/build/paths.ts
@@ -794,7 +937,7 @@ function createNodeFunctionConfig(extra = {}) {
794
937
  return {
795
938
  handler: "index.mjs",
796
939
  launcherType: "Nodejs",
797
- runtime: "nodejs22.x",
940
+ runtime: "nodejs24.x",
798
941
  shouldAddHelpers: false,
799
942
  supportsResponseStreaming: true,
800
943
  ...extra
@@ -1140,10 +1283,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
1140
1283
  assertNetlifyFunctionName(functionName);
1141
1284
  return resolve(functionsRoot, `${functionName}.mjs`);
1142
1285
  }
1286
+ async function declaresTopLevelBinding(code, name) {
1287
+ const { parseSync } = await import("vite");
1288
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
1289
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
1290
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
1291
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
1292
+ });
1293
+ }
1143
1294
  async function appendNetlifyFunctionConfig(outfile, config) {
1144
1295
  if (!config) return;
1145
1296
  const bundled = await readFile(outfile, "utf8");
1146
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
1297
+ const literal = stringifyProviderOutputConfig(config);
1298
+ let exported = `export const config = ${literal}`;
1299
+ if (await declaresTopLevelBinding(bundled, "config")) {
1300
+ const baseName = "vitehubNetlifyFunctionConfig";
1301
+ let name = baseName;
1302
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
1303
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
1304
+ }
1305
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
1147
1306
  }
1148
1307
  async function writeCloudflareDeploymentOutput(options, signal) {
1149
1308
  signal?.throwIfAborted();
@@ -16818,10 +16977,10 @@ var binding_default = defineComarkPlugin((opts = {}) => {
16818
16977
  };
16819
16978
  });
16820
16979
  //#endregion
16821
- //#region ../markdown-template/dist/prepare-DKmD3SM8.js
16980
+ //#region ../markdown-template/dist/prepare-BUVd_uB_.js
16822
16981
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
16823
16982
  const markdownTemplateErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
16824
- docsBase: "https://vitehub.dev/docs/agents/diagnostics",
16983
+ docsBase: "https://vitehub.dev/docs/markdown-template/diagnostics",
16825
16984
  codes: {
16826
16985
  MARKDOWN_TEMPLATE_R0002: {
16827
16986
  ...dynamicError,
@@ -18577,7 +18736,7 @@ function decodeHTMLAttribute(htmlAttribute) {
18577
18736
  return decodeWithTrie(htmlAttribute, false, true);
18578
18737
  }
18579
18738
  //#endregion
18580
- //#region ../markdown-template/dist/render-CoOHaHxC.js
18739
+ //#region ../markdown-template/dist/render-CpaRdP2V.js
18581
18740
  function pathValue(value, parts) {
18582
18741
  if (!parts.length) return { value };
18583
18742
  if (value === null || typeof value !== "object" && typeof value !== "function") return void 0;
@@ -18945,7 +19104,7 @@ function conditionalBranches(node) {
18945
19104
  };
18946
19105
  }
18947
19106
  //#endregion
18948
- //#region ../markdown-template/dist/vite-DSPZnn1R.js
19107
+ //#region ../markdown-template/dist/vite-BGJ4jHJz.js
18949
19108
  function parseMarkdownTemplateRequest(id) {
18950
19109
  if (id.includes("#")) return;
18951
19110
  const queryIndex = id.indexOf("?");
@@ -19360,6 +19519,8 @@ function resolveWorkspaceRawSpecifier(path, rootDir) {
19360
19519
  const publicPath = join(rootDir, "public", rootRelativePath);
19361
19520
  return existsSync(publicPath) ? publicPath : join(rootDir, rootRelativePath);
19362
19521
  }
19522
+ const passModuleCaches = /* @__PURE__ */ new WeakMap();
19523
+ /** Creates the loader of one pass. Create a new loader for each pass, so that changed modules load again. */
19363
19524
  function createWorkspaceDefinitionLoader(rootDir, alias = {}) {
19364
19525
  let loader;
19365
19526
  const virtualModules = new Proxy(Object.create(null), {
@@ -19393,8 +19554,24 @@ function createWorkspaceDefinitionLoader(rootDir, alias = {}) {
19393
19554
  transform: createWorkspaceDefinitionTransform(),
19394
19555
  virtualModules
19395
19556
  });
19557
+ passModuleCaches.set(loader, Object.create(null));
19396
19558
  return loader;
19397
19559
  }
19560
+ async function importInPass(loader, file) {
19561
+ const shared = passModuleCaches.get(loader);
19562
+ if (!shared || !isAbsolute(file)) return await loader.import(file);
19563
+ const resolved = loader.esmResolve(file, { try: true });
19564
+ const filename = resolved?.startsWith("file:") ? fileURLToPath(resolved) : resolved;
19565
+ if (!filename || !isAbsolute(filename) || !/\.[cm]?tsx?$/.test(filename) || !existsSync(filename)) return await loader.import(file);
19566
+ const cache = { ...shared };
19567
+ const namespace = await loader.evalModule(readFileSync(filename, "utf8"), {
19568
+ async: true,
19569
+ cache,
19570
+ filename
19571
+ });
19572
+ for (const [path, module] of Object.entries(cache)) if (path !== filename && module?.loaded) shared[path] = module;
19573
+ return namespace;
19574
+ }
19398
19575
  /**
19399
19576
  * Resolves the module of a Workspace Definition to a file. Contributed package specifiers resolve from the
19400
19577
  * application root, not from this package. Returns the specifier when it cannot be resolved.
@@ -19409,7 +19586,7 @@ function resolveWorkspaceDefinitionModule(loader, definition, rootDir) {
19409
19586
  return resolved.startsWith("file:") ? fileURLToPath(resolved) : resolved;
19410
19587
  }
19411
19588
  async function loadDiscoveredWorkspaceDefinition(loader, definition, rootDir) {
19412
- const mod = await loader.import(resolveWorkspaceDefinitionModule(loader, definition, rootDir));
19589
+ const mod = await importInPass(loader, resolveWorkspaceDefinitionModule(loader, definition, rootDir));
19413
19590
  const exportName = definition.export ?? "default";
19414
19591
  const loaded = mod[exportName];
19415
19592
  if (!loaded) throw workspaceErrorDiagnostics.WORKSPACE_B0001({ message: `[vitehub] Workspace definition "${definition.name}" has no ${exportName === "default" ? "default export" : `export ${JSON.stringify(exportName)}`}.` });
@@ -20131,7 +20308,8 @@ const workspaceDevEndpoint = {
20131
20308
  const workspaceDevTargetErrors = {
20132
20309
  invalidInlineTimeout: (message) => workspaceErrorDiagnostics.WORKSPACE_R0006({ message }),
20133
20310
  invalidTimeout: (message) => workspaceErrorDiagnostics.WORKSPACE_R0005({ message }),
20134
- missingValue: (message) => workspaceErrorDiagnostics.WORKSPACE_R0004({ message })
20311
+ missingValue: (message) => workspaceErrorDiagnostics.WORKSPACE_R0004({ message }),
20312
+ unknownOption: (message) => workspaceErrorDiagnostics.WORKSPACE_R0007({ message })
20135
20313
  };
20136
20314
  const workspaceCommandFeedbackIntervalMs = 15e3;
20137
20315
  const workspaceCommandStartedMessage = "[workspace] command started; first run may materialize sources.\n";
@@ -20217,7 +20395,7 @@ function writeWorkspaceDevUsage(context) {
20217
20395
  "Omit exec to open the interactive command loop.",
20218
20396
  "",
20219
20397
  "Options:",
20220
- " --url <url> Compatible Vite Development Server URL. Defaults to http://localhost:5173.",
20398
+ " --url <url> App URL, such as http://localhost:3000. Defaults to the dev server of this project.",
20221
20399
  " --timeout <ms> Workspace command timeout.",
20222
20400
  " --path <path> Workspace path to materialize for command sessions. Repeatable.",
20223
20401
  " -h, --help Show this help.",
@@ -20229,11 +20407,8 @@ function readOptionValue(args, index, flag) {
20229
20407
  if (!value || value.startsWith("-")) throw workspaceErrorDiagnostics.WORKSPACE_R0004({ message: `Missing value for ${flag}.` });
20230
20408
  return value;
20231
20409
  }
20232
- function parseWorkspaceDevArgs(args, env) {
20233
- const parsed = {
20234
- help: false,
20235
- url: resolveViteHubDevServerUrl(env)
20236
- };
20410
+ function parseWorkspaceDevArgs(args, env, rootDir) {
20411
+ const parsed = { help: false };
20237
20412
  for (let index = 0; index < args.length; index += 1) {
20238
20413
  const arg = args[index];
20239
20414
  if (arg === "-h" || arg === "--help") {
@@ -20270,7 +20445,10 @@ function parseWorkspaceDevArgs(args, env) {
20270
20445
  }
20271
20446
  throw workspaceErrorDiagnostics.WORKSPACE_R0009({ message: `Unexpected argument: ${arg}. Use exec <command...> for one-shot commands.` });
20272
20447
  }
20273
- return parsed;
20448
+ return {
20449
+ ...parsed,
20450
+ url: parsed.url ?? (parsed.help ? "" : requireViteHubDevServerUrl([.../* @__PURE__ */ new Set([rootDir, resolveViteHubProjectRoot(rootDir)])], env, "workspace dev"))
20451
+ };
20274
20452
  }
20275
20453
  async function readWorkspaceDiscovery(parsed, context, fetchImpl) {
20276
20454
  if (!parsed.workspace) {
@@ -20362,9 +20540,9 @@ async function runInteractiveWorkspaceDev(parsed, context, fetchImpl, target) {
20362
20540
  async function runWorkspaceDevCli(args, context, options = {}) {
20363
20541
  let parsed;
20364
20542
  try {
20365
- parsed = parseWorkspaceDevArgs(args, context.env);
20543
+ parsed = parseWorkspaceDevArgs(args, context.env, context.rootDir);
20366
20544
  } catch (error) {
20367
- context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
20545
+ context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
20368
20546
  writeWorkspaceDevUsage(context);
20369
20547
  return 1;
20370
20548
  }
@@ -20635,6 +20813,7 @@ async function resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir,
20635
20813
  message: `[vitehub] Workspace "${definition.name}" sets a store that may need a Cloudflare Artifacts binding, but the build cannot load ${definitionFile} to read it: ${error instanceof Error ? error.message : String(error)}`
20636
20814
  });
20637
20815
  options.storeUsage?.add("unknown");
20816
+ if (store.driver === "github") options.storeUsage?.add("github");
20638
20817
  continue;
20639
20818
  }
20640
20819
  if (options.storeUsage && !await readStaticWorkspaceStore(definitionFile, loader, definition.export)) options.storeUsage.add("unknown");
@@ -20655,6 +20834,15 @@ async function resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir,
20655
20834
  }
20656
20835
  return configs;
20657
20836
  }
20837
+ /**
20838
+ * The Definitions that the config loads to find their Cloudflare Artifacts stores. A build loads all of them to learn
20839
+ * which stores it bundles. `vite dev` and CLI calls (`serve`) load them only on the Cloudflare host, because only a
20840
+ * Cloudflare server binds Artifacts. Loading runs app code outside Nitro, so its Nitro runtime imports would print
20841
+ * Nitro's "stub implementation" warning on every command.
20842
+ */
20843
+ function definitionsToLoad(definitions, command, hosting) {
20844
+ return command !== "serve" || getHostingProvider(hosting) === "cloudflare" ? definitions : [];
20845
+ }
20658
20846
  async function resolveCloudflareArtifactsConfigs(config, definitions, rootDir, options = {}) {
20659
20847
  return [...config.store.driver === "cloudflare" ? [config] : [], ...await resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir, options)];
20660
20848
  }
@@ -20889,9 +21077,9 @@ function hasExplicitWorkspaceRuntimeOptions(options) {
20889
21077
  function shouldInstallNitroWorkspacePlugin(config, options, normalized, definitions) {
20890
21078
  return isHostedWorkspaceStore(normalized.store) || hasExplicitWorkspaceRuntimeOptions(options) || hasNitroConfig(config) && definitions.length > 0;
20891
21079
  }
20892
- function mergeNitroWorkspaceConfig(value, dev) {
21080
+ function mergeNitroWorkspaceConfig(value, root, dev) {
20893
21081
  const kit = createNitroServerKit(isRecord(value) ? { ...value } : {});
20894
- kit.addPlugin(generatedNitroWorkspacePlugin, dev ? "start" : "end");
21082
+ kit.addPlugin(resolve(root, generatedNitroWorkspacePlugin), dev ? "start" : "end");
20895
21083
  kit.addHandler({
20896
21084
  handler: ownModule(import.meta.url, "runtime/request"),
20897
21085
  middleware: true
@@ -20947,18 +21135,11 @@ function runtimeWorkspaceConfig(config, options, cloudflareRuntime) {
20947
21135
  const isAbsent = (value) => typeof value === "undefined" || typeof value === "string" && value.trim().length === 0;
20948
21136
  for (const key of [
20949
21137
  "branch",
21138
+ "repo",
20950
21139
  "root",
20951
21140
  "token"
20952
21141
  ]) if (typeof store[key] === "function") runtimeStore[key] = store[key];
20953
- else if (isAbsent(store[key])) delete runtimeStore[key];
20954
- if (typeof store.repository === "function") runtimeStore.repository = store.repository;
20955
- else if (typeof store.repo === "function") {
20956
- runtimeStore.repo = store.repo;
20957
- delete runtimeStore.repository;
20958
- } else if (isAbsent(store.repository) && isAbsent(store.repo)) {
20959
- delete runtimeStore.repository;
20960
- delete runtimeStore.repo;
20961
- }
21142
+ else if (isAbsent(store[key]) && !(key === "root" && store.root === "")) delete runtimeStore[key];
20962
21143
  return {
20963
21144
  ...config,
20964
21145
  store: runtimeStore
@@ -21048,7 +21229,7 @@ async function createWorkspaceNitroConfig(options = {}) {
21048
21229
  if (!isHostedWorkspaceStore(normalized.store) && !hasExplicitWorkspaceRuntimeOptions(workspaceOptions) && definitions.length === 0) return null;
21049
21230
  const definitionOverrides = /* @__PURE__ */ new Map();
21050
21231
  const storeUsage = options.command === "build" ? /* @__PURE__ */ new Set() : void 0;
21051
- const cloudflareArtifactsConfigs = await resolveCloudflareArtifactsConfigs(normalized, definitions, roots.projectRoot, {
21232
+ const cloudflareArtifactsConfigs = await resolveCloudflareArtifactsConfigs(normalized, definitionsToLoad(definitions, hosting ? options.command : void 0, hosting), roots.projectRoot, {
21052
21233
  aliases: options.aliases,
21053
21234
  env: options.env,
21054
21235
  hosting,
@@ -21058,7 +21239,7 @@ async function createWorkspaceNitroConfig(options = {}) {
21058
21239
  const runtimeConfig = shouldConfigureRuntime(workspaceOptions, normalized) ? normalized : false;
21059
21240
  const cloudflareRuntime = cloudflareArtifactsConfigs.length > 0 || getHostingProvider(hosting) === "cloudflare";
21060
21241
  await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, workspaceOptions, definitions, cloudflareRuntime, definitionOverrides, storeUsage);
21061
- const nitro = mergeNitroWorkspaceConfig(options.nitro, options.command !== "build");
21242
+ const nitro = mergeNitroWorkspaceConfig(options.nitro, roots.projectRoot, options.command !== "build");
21062
21243
  if (options.command === "build") configureNitroWorkspaceAssets(nitro, roots.projectRoot);
21063
21244
  for (const config of cloudflareArtifactsConfigs) configureCloudflareArtifacts(nitro, config);
21064
21245
  if (cloudflareRuntime) configureCloudflareNitroRuntime(nitro);
@@ -21066,13 +21247,16 @@ async function createWorkspaceNitroConfig(options = {}) {
21066
21247
  }
21067
21248
  const setWorkspacePluginHosting = Symbol("vitehub.workspace.setHosting");
21068
21249
  function stripWorkspaceInternalOptions(options) {
21069
- if (!options || !Object.hasOwn(options, "hosting")) return options;
21250
+ if (!options || !["hosting", "assertGitHubStoreAvailable"].some((key) => Object.hasOwn(options, key))) return options;
21070
21251
  const publicOptions = { ...options };
21252
+ delete publicOptions.assertGitHubStoreAvailable;
21071
21253
  delete publicOptions.hosting;
21072
21254
  return publicOptions;
21073
21255
  }
21074
21256
  function hubWorkspace(options) {
21075
- let hosting = (options ? options : void 0)?.hosting;
21257
+ const packageLoading = createNativePackageLoading();
21258
+ const internalOptions = options;
21259
+ let hosting = internalOptions ? internalOptions.hosting : void 0;
21076
21260
  const publicOptions = stripWorkspaceInternalOptions(options);
21077
21261
  let resolved;
21078
21262
  let providerOutput;
@@ -21086,6 +21270,7 @@ function hubWorkspace(options) {
21086
21270
  let server;
21087
21271
  let serverDirs;
21088
21272
  let contributions = [];
21273
+ let hasArtifacts = false;
21089
21274
  async function refreshManifest(roots) {
21090
21275
  const definitions = discoverDefinitions(roots, serverDirs, contributions);
21091
21276
  const state = await refreshWorkspaceBuildState(roots.projectRoot, definitions);
@@ -21112,12 +21297,14 @@ function hubWorkspace(options) {
21112
21297
  }
21113
21298
  return {
21114
21299
  name: "@vite-hub/workspace/vite",
21300
+ nitro: packageLoading.nitro,
21115
21301
  enforce: "pre",
21116
21302
  [setWorkspacePluginHosting](value) {
21117
21303
  hosting = value;
21118
21304
  },
21119
21305
  api: { getWorkspaces: () => manifest.workspaces },
21120
21306
  async config(config, env) {
21307
+ hasArtifacts = false;
21121
21308
  serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
21122
21309
  const workspaceOptions = publicOptions;
21123
21310
  const roots = resolveWorkspacePluginRoots(config.root || process.cwd(), workspaceOptions);
@@ -21138,22 +21325,39 @@ function hubWorkspace(options) {
21138
21325
  const viteConfig = { server: { watch: { ignored: generatedViteHubWatchIgnoredAddition(config.server?.watch?.ignored) } } };
21139
21326
  if (normalized) contributions = await collectPluginWorkspaceContributions(config.plugins, roots, serverDirs);
21140
21327
  const definitions = normalized ? discoverDefinitions(roots, serverDirs, contributions) : [];
21328
+ const assertGitHubStoreAvailable = internalOptions && isProductionBuild(config, env) ? internalOptions.assertGitHubStoreAvailable : void 0;
21329
+ if (normalized && normalized.store.driver === "github") assertGitHubStoreAvailable?.();
21141
21330
  if (normalized && shouldInstallNitroWorkspacePlugin(config, runtimeOptions, normalized, definitions)) {
21142
21331
  const runtimeConfig = shouldConfigureRuntime(runtimeOptions, normalized) ? normalized : false;
21143
21332
  const definitionOverrides = /* @__PURE__ */ new Map();
21333
+ const aliases = config.resolve?.alias ? workspaceDefinitionLoaderAliases(config.resolve.alias) : void 0;
21144
21334
  const storeUsage = env?.command === "build" ? /* @__PURE__ */ new Set() : void 0;
21145
- const artifacts = await resolveCloudflareArtifactsConfigs(normalized, definitions, roots.projectRoot, {
21146
- aliases: config.resolve?.alias ? workspaceDefinitionLoaderAliases(config.resolve.alias) : void 0,
21335
+ const artifacts = await resolveCloudflareArtifactsConfigs(normalized, definitionsToLoad(definitions, env?.command, resolvedHosting), roots.projectRoot, {
21336
+ aliases,
21147
21337
  hosting: resolvedHosting,
21148
21338
  definitionOverrides,
21149
21339
  storeUsage
21150
21340
  });
21151
- const usesCloudflareRuntime = artifacts.length > 0 || getHostingProvider(resolvedHosting) === "cloudflare";
21341
+ if (normalized.store.driver !== "github" && storeUsage?.has("github")) assertGitHubStoreAvailable?.();
21342
+ hasArtifacts = artifacts.length > 0;
21343
+ const usesCloudflareRuntime = hasArtifacts || getHostingProvider(resolvedHosting) === "cloudflare";
21152
21344
  await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, runtimeOptions, definitions, usesCloudflareRuntime, definitionOverrides, storeUsage);
21153
- const nitro = mergeNitroWorkspaceConfig(config.nitro, env?.command === "serve");
21345
+ const nitro = mergeNitroWorkspaceConfig(config.nitro, roots.projectRoot, env?.command === "serve");
21154
21346
  if (env?.command === "build") configureNitroWorkspaceAssets(nitro, roots.projectRoot);
21155
21347
  for (const artifactConfig of artifacts) configureCloudflareArtifacts(nitro, artifactConfig);
21156
21348
  if (usesCloudflareRuntime) configureCloudflareNitroRuntime(nitro);
21349
+ if (env?.command === "serve" && definitions.length && getHostingProvider(resolvedHosting) !== "cloudflare") nitro.modules = [...Array.isArray(nitro.modules) ? nitro.modules : [], { async setup({ options }) {
21350
+ if (getHostingProvider(options.preset) !== "cloudflare") return;
21351
+ const configs = await resolveDefinitionCloudflareArtifactsConfigs(definitions, roots.projectRoot, {
21352
+ aliases,
21353
+ definitionOverrides,
21354
+ hosting: options.preset
21355
+ });
21356
+ hasArtifacts ||= configs.length > 0;
21357
+ for (const artifactConfig of configs) configureCloudflareArtifacts(options, artifactConfig);
21358
+ configureCloudflareNitroRuntime(options);
21359
+ await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, runtimeOptions, definitions, true, definitionOverrides);
21360
+ } }];
21157
21361
  config.nitro = nitro;
21158
21362
  }
21159
21363
  return viteConfig;
@@ -21186,7 +21390,7 @@ function hubWorkspace(options) {
21186
21390
  if (!isServerEnvironment(name, config)) return;
21187
21391
  return { resolve: {
21188
21392
  dedupe: dedupeAddition(config.resolve?.dedupe),
21189
- ...loadsViteHubPackagesNatively(name, env) ? {} : { noExternal: noExternalAddition(config.resolve?.noExternal) }
21393
+ ...packageLoading.configureEnvironment(name, env) ? {} : { noExternal: noExternalAddition(config.resolve?.noExternal) }
21190
21394
  } };
21191
21395
  },
21192
21396
  async buildStart() {
@@ -21238,6 +21442,7 @@ function hubWorkspace(options) {
21238
21442
  }
21239
21443
  },
21240
21444
  async configureServer(devServer) {
21445
+ publishViteHubDevServer(devServer);
21241
21446
  server = devServer;
21242
21447
  installHostedWorkspaceRuntime();
21243
21448
  installHostedVercelBlobWorkspaceRuntime();
@@ -21320,7 +21525,7 @@ function hubWorkspace(options) {
21320
21525
  });
21321
21526
  }
21322
21527
  }],
21323
- providerOutput: (resolvedOptions ? await resolveCloudflareArtifactsConfigs(resolvedOptions, discoverDefinitions(roots, serverDirs, contributions), roots.projectRoot, { aliases: resolved?.resolve ? workspaceDefinitionLoaderAliases(resolved.resolve.alias) : void 0 }) : []).length > 0 ? [{
21528
+ providerOutput: hasArtifacts || resolved?.command === "build" && resolvedOptions && (await resolveCloudflareArtifactsConfigs(resolvedOptions, discoverDefinitions(roots, serverDirs, contributions), roots.projectRoot, { aliases: resolved.resolve ? workspaceDefinitionLoaderAliases(resolved.resolve.alias) : void 0 })).length > 0 ? [{
21324
21529
  description: "Generated Cloudflare Workspace artifacts config",
21325
21530
  owner: "workspace",
21326
21531
  path: resolve(createDefaultCloudflareOutputRoot(roots.projectRoot), "wrangler.json")
@@ -21360,7 +21565,7 @@ function hubWorkspace(options) {
21360
21565
  entries: []
21361
21566
  })};\nexport default manifest;\n`;
21362
21567
  }
21363
- return loadNativePackageModule(id, this.environment?.name, resolved?.command ?? "build");
21568
+ return packageLoading.load(id, this.environment?.name);
21364
21569
  }
21365
21570
  }
21366
21571
  };