@vite-hub/workflow 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 +52 -35
  2. package/dist/{app-CmMq8l4t.js → app-He0GTrYZ.js} +1 -1
  3. package/dist/{client-CU5rELC0.js → client-DkwOxEiT.js} +88 -39
  4. package/dist/{cloudflare-BfFnNWB0.js → cloudflare-BHfClPvT.js} +1 -1
  5. package/dist/{config-DCvRDlxA.js → config-C3DvtjfJ.js} +1 -1
  6. package/dist/definition.d.ts +10 -11
  7. package/dist/definition.js +24 -22
  8. package/dist/{delay--ESDybVT.js → delay-D1-nq_VE.js} +6 -41
  9. package/dist/durability.d.ts +1 -1
  10. package/dist/{error-diagnostics-8YNJ37rP.js → error-diagnostics-0V2T3JFw.js} +45 -14
  11. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-CQ4BUqRe.js} +5 -1
  12. package/dist/{errors-DVwFb6Fd.d.ts → errors-uhP8DZTi.d.ts} +12 -1
  13. package/dist/index.d.ts +30 -11
  14. package/dist/index.js +12 -5
  15. package/dist/{openworkflow-TEaNk0LV.d.ts → openworkflow-BhzxV_Y3.d.ts} +3 -1
  16. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
  17. package/dist/{operations-B0L8kV5s.js → operations-D_WJwjrS.js} +9 -5
  18. package/dist/operations.d.ts +2 -2
  19. package/dist/operations.js +2 -2
  20. package/dist/{out-fRNaVslw.js → out-DxLKolA0.js} +1 -1
  21. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  22. package/dist/run-failed-gVGo1BaF.js +18 -0
  23. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  24. package/dist/runtime/cloudflare-runner.js +17 -5
  25. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  26. package/dist/runtime/cloudflare-vite.js +2 -2
  27. package/dist/runtime/execute.d.ts +25 -4
  28. package/dist/runtime/execute.js +108 -15
  29. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  30. package/dist/runtime/openworkflow-worker.js +1 -1
  31. package/dist/runtime/openworkflow.d.ts +1 -1
  32. package/dist/runtime/openworkflow.js +37 -11
  33. package/dist/runtime/state.d.ts +1 -1
  34. package/dist/runtime/state.js +2 -6
  35. package/dist/runtime/vercel-vite.d.ts +1 -1
  36. package/dist/runtime/vercel-vite.js +2 -2
  37. package/dist/{types-CnKVDnEp.d.ts → types-Dsmwsdlv.d.ts} +67 -26
  38. package/dist/{vercel-BZU_O6ay.js → vercel-DTvm61iY.js} +4 -4
  39. package/dist/vite.d.ts +17 -11
  40. package/dist/vite.js +1116 -529
  41. package/package.json +4 -4
package/dist/vite.js CHANGED
@@ -1,24 +1,24 @@
1
- import { r as __toESM } from "./rolldown-runtime-CMFfr-1z.js";
2
- import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
3
- import { workflowDurabilityUrl } from "./durability.js";
4
- import { i as getLegacyCloudflareWorkflowClassName, r as getCloudflareWorkflowClassName, t as createCloudflareWorkflowBindings } from "./cloudflare-BfFnNWB0.js";
5
- import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
6
- import { n as getHostingProvider, r as normalizeHosting, t as normalizeWorkflowOptions } from "./config-DCvRDlxA.js";
1
+ import { i as __toESM, n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
7
2
  import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
8
- import { a as workflowStartAtKey, n as generatedNativeEntryKey } from "./delay--ESDybVT.js";
9
- import { toStepPropertyName } from "./runtime/execute.js";
3
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
4
+ import { workflowDurabilityUrl } from "./durability.js";
5
+ import { i as getLegacyCloudflareWorkflowClassName, r as getCloudflareWorkflowClassName, t as createCloudflareWorkflowBindings } from "./cloudflare-BHfClPvT.js";
6
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
7
+ import { n as getHostingProvider, r as normalizeHosting, t as normalizeWorkflowOptions } from "./config-C3DvtjfJ.js";
8
+ import { a as workflowStartAtKey, n as generatedNativeEntryKey } from "./delay-D1-nq_VE.js";
9
+ import { resolveWorkflowStepOptions, toStepPropertyName } from "./runtime/execute.js";
10
10
  import { n as invariant, r as invariantError, t as defaultOpenWorkflowSqlitePath } from "./openworkflow-defaults-DDig2M4s.js";
11
11
  import { r as relativeDefinitionFile } from "./inspect-B72iFyj-.js";
12
- import { builtinModules, createRequire } from "node:module";
12
+ import { builtinModules, createRequire, isBuiltin } from "node:module";
13
13
  import { dirname, normalize, relative, resolve } from "pathe";
14
14
  import { fileURLToPath, pathToFileURL } from "node:url";
15
15
  import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
16
16
  import { createHash, randomUUID } from "node:crypto";
17
17
  import { basename, dirname as dirname$1, extname, isAbsolute, join, parse, relative as relative$1, resolve as resolve$1, sep } from "node:path";
18
- import { access, copyFile, cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
18
+ import { access, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
19
19
  import { tmpdir } from "node:os";
20
20
  import { parseSync } from "vite";
21
- import { buildSync, transform } from "esbuild";
21
+ import { build, buildSync, transform } from "esbuild";
22
22
  //#region ../internal/src/durability.ts
23
23
  /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
24
24
  function durabilityModuleFile(importMetaUrl) {
@@ -324,20 +324,76 @@ async function writeCloudflareWranglerConfig(options) {
324
324
  });
325
325
  }
326
326
  //#endregion
327
- //#region ../internal/src/build/esbuild.ts
328
- const viteRawNamespace = "vitehub-vite-raw";
329
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
330
- const markdownTemplateFileSuffix = ".template.md";
331
- const markdownTemplateModuleQuery = "markdown-template";
332
- const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
327
+ //#region ../internal/src/build/ast-walk.ts
328
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
329
+ function moduleLanguage(file) {
330
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
331
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
332
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
333
+ return "ts";
334
+ }
335
+ function isNode(value) {
336
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
337
+ }
338
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
339
+ function walk(node, visit, parent) {
340
+ if (visit(node, parent) === false) return;
341
+ const fields = node;
342
+ for (const key in fields) {
343
+ const child = fields[key];
344
+ if (typeof child !== "object" || child === null || key === "parent") continue;
345
+ if (Array.isArray(child)) {
346
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
347
+ } else if (isNode(child)) walk(child, visit, node);
348
+ }
349
+ }
350
+ //#endregion
351
+ //#region ../internal/src/build/rolldown.ts
352
+ const viteRawPrefix = "\0vitehub-vite-raw:";
353
+ const markdownTemplatePrefix = "\0vitehub-markdown-template:";
354
+ const markdownTemplateFileSuffix$1 = ".template.md";
355
+ const markdownTemplateModuleQuery$1 = "markdown-template";
356
+ const skipMarkdownTemplateResolve$1 = "vitehubSkipMarkdownTemplateResolve";
333
357
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
334
- const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
358
+ const resolvingViteAlias = "vitehubResolvingAlias";
359
+ const markdownTemplateRuntimeSpecifier$1 = "@vite-hub/markdown-template";
360
+ /**
361
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
362
+ * Vite+, instead of installing a second bundler.
363
+ */
364
+ async function importRolldown() {
365
+ let entry;
366
+ try {
367
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
368
+ } catch (error) {
369
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
370
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
371
+ }
372
+ return await import(pathToFileURL(entry).href);
373
+ }
335
374
  function normalizePathSeparators(path) {
336
375
  return path.replaceAll("\\", "/");
337
376
  }
338
377
  function escapeRegExp$1(value) {
339
378
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
340
379
  }
380
+ function isRelativeSpecifier(path) {
381
+ return /^\.\.?[\\/]/.test(path);
382
+ }
383
+ function isBareSpecifier(id) {
384
+ return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
385
+ }
386
+ /** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
387
+ function importerDir(importer, workingDir) {
388
+ return importer && isAbsolute(importer) ? dirname$1(importer) : workingDir;
389
+ }
390
+ /** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
391
+ function importerFor(importer, workingDir) {
392
+ return importer ?? join(workingDir, "__vitehub_entry__.js");
393
+ }
394
+ function isFileResolution(resolved) {
395
+ return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
396
+ }
341
397
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
342
398
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
343
399
  if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
@@ -364,7 +420,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
364
420
  }
365
421
  return candidates;
366
422
  }
367
- function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
423
+ /**
424
+ * Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
425
+ * resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
426
+ * same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
427
+ */
428
+ function resolveFrom(context, specifier, request, workingDir, flag) {
429
+ return context.resolve(specifier, importerFor(request.importer, workingDir), {
430
+ custom: {
431
+ ...request.custom,
432
+ [flag]: true
433
+ },
434
+ isEntry: request.isEntry,
435
+ kind: request.kind,
436
+ skipSelf: true
437
+ });
438
+ }
439
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
368
440
  const entries = Object.entries(aliases || {});
369
441
  if (!entries.length) return;
370
442
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -384,200 +456,189 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
384
456
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
385
457
  };
386
458
  }));
459
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
387
460
  return {
388
461
  name: "vitehub-resolved-alias",
389
- setup(build) {
390
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
391
- build.onResolve({ filter: /.*/ }, async (args) => {
392
- if (args.pluginData?.[skipResolvedAlias]) return;
393
- const resolveWithContext = (specifier) => build.resolve(specifier, {
394
- importer: args.importer,
395
- kind: args.kind,
396
- namespace: args.namespace,
397
- pluginData: {
398
- ...args.pluginData,
399
- [skipResolvedAlias]: true
400
- },
401
- resolveDir: args.resolveDir,
402
- with: args.with
403
- });
404
- const aliases = await resolvedEntries;
405
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
406
- let matchedAlias = match?.specifier;
407
- let matchedSpecifier = match ? args.path : void 0;
408
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve$1(args.resolveDir, args.path) : args.path;
409
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve$1(specifier)) : specifier;
410
- let canonicalSpecifier = normalizedSpecifier;
411
- const canonicalizeSpecifier = async () => {
412
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
413
- return canonicalSpecifier;
414
- };
415
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
416
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
417
- await canonicalizeSpecifier();
418
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
419
- }
420
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
421
- const candidates = [];
422
- for (const alias of aliases) {
423
- if (isAbsolute(alias.specifier)) continue;
424
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
425
- const aliasSegments = packageAlias.split("/");
426
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
427
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
428
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
429
- const scopeMarker = `/node_modules/${packageAlias}/`;
430
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
431
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
432
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
433
- }
434
- const packageMarker = `/node_modules/${packageName}/`;
435
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
436
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
437
- const cacheKey = [
438
- alias.specifier,
439
- alias.prefix,
440
- resolutionScope,
441
- normalizedSpecifier,
442
- args.importer,
443
- args.resolveDir,
444
- args.kind,
445
- args.namespace,
446
- JSON.stringify(args.with)
447
- ].join("\0");
448
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
449
- if (!resolution) {
450
- resolution = (async () => {
451
- let resolvedAliasPath;
452
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve$1(aliasResolveDir, alias.specifier));
453
- else if (resolutionScope) {
454
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
455
- const parsedPackageJson = JSON.parse(await readFile(resolve$1(resolutionScope, "package.json"), "utf8"));
456
- if (!isRecord(parsedPackageJson)) return;
457
- const packageJson = parsedPackageJson;
458
- if (packageJson.exports === void 0 && !alias.prefix) {
459
- const resolvedCandidate = await resolveWithContext(alias.specifier);
460
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve$1(resolvedCandidate.path)) === normalizedSpecifier) return {
461
- canonical: alias.specifier,
462
- normalized: alias.specifier,
463
- publicSpecifier: alias.specifier
464
- };
465
- return;
466
- }
467
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
468
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
469
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
470
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
471
- if (normalizePathSeparators(resolve$1(resolvedCandidate.path)) !== normalizedSpecifier) continue;
472
- matchingPublicSpecifiers.add(publicSpecifier);
473
- }
474
- if (matchingPublicSpecifiers.size === 1) {
475
- const publicSpecifier = [...matchingPublicSpecifiers][0];
476
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
477
- canonical: publicSpecifier,
478
- normalized: publicSpecifier,
479
- publicSpecifier
480
- };
481
- }
462
+ async resolveId(source, importer, extra) {
463
+ if (extra.custom?.[skipResolvedAlias]) return;
464
+ const request = {
465
+ custom: extra.custom,
466
+ importer,
467
+ isEntry: extra.isEntry,
468
+ kind: extra.kind
469
+ };
470
+ const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
471
+ const resolveDir = importerDir(importer, workingDir);
472
+ const aliases = await resolvedEntries;
473
+ let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
474
+ let matchedAlias = match?.specifier;
475
+ let matchedSpecifier = match ? source : void 0;
476
+ const specifier = isRelativeSpecifier(source) ? resolve$1(resolveDir, source) : source;
477
+ const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve$1(specifier)) : specifier;
478
+ let canonicalSpecifier = normalizedSpecifier;
479
+ const canonicalizeSpecifier = async () => {
480
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
481
+ return canonicalSpecifier;
482
+ };
483
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
484
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
485
+ await canonicalizeSpecifier();
486
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
487
+ }
488
+ if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
489
+ const candidates = [];
490
+ for (const alias of aliases) {
491
+ if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
492
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
493
+ const aliasSegments = packageAlias.split("/");
494
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
495
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
496
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
497
+ const scopeMarker = `/node_modules/${packageAlias}/`;
498
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
499
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
500
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
501
+ }
502
+ const packageMarker = `/node_modules/${packageName}/`;
503
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
504
+ if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
505
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
506
+ const cacheKey = [
507
+ alias.specifier,
508
+ alias.prefix,
509
+ resolutionScope,
510
+ normalizedSpecifier,
511
+ importer,
512
+ extra.kind,
513
+ extra.isEntry
514
+ ].join("\0");
515
+ const cacheable = !extra.custom || !Object.keys(extra.custom).length;
516
+ let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
517
+ if (!resolution) {
518
+ resolution = (async () => {
519
+ let resolvedAliasPath;
520
+ if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve$1(aliasResolveDir, alias.specifier));
521
+ else if (resolutionScope) {
522
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
523
+ const parsedPackageJson = JSON.parse(await readFile(resolve$1(resolutionScope, "package.json"), "utf8"));
524
+ if (!isRecord(parsedPackageJson)) return;
525
+ const packageJson = parsedPackageJson;
526
+ if (packageJson.exports === void 0 && !alias.prefix) {
527
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
528
+ if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve$1(resolvedCandidate.id)) === normalizedSpecifier) return {
529
+ canonical: alias.specifier,
530
+ normalized: alias.specifier,
531
+ publicSpecifier: alias.specifier
532
+ };
482
533
  return;
483
- } else {
484
- const resolvedAlias = await resolveWithContext(alias.specifier);
485
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
486
- resolvedAliasPath = normalizePathSeparators(resolve$1(resolvedAlias.path));
487
534
  }
488
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
489
- return {
490
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
491
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
492
- };
493
- })();
494
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
495
- }
496
- candidates.push({
497
- alias,
498
- resolution
499
- });
535
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
536
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
537
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
538
+ if (!isFileResolution(resolvedCandidate)) continue;
539
+ if (normalizePathSeparators(resolve$1(resolvedCandidate.id)) !== normalizedSpecifier) continue;
540
+ matchingPublicSpecifiers.add(publicSpecifier);
541
+ }
542
+ if (matchingPublicSpecifiers.size === 1) {
543
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
544
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
545
+ canonical: publicSpecifier,
546
+ normalized: publicSpecifier,
547
+ publicSpecifier
548
+ };
549
+ }
550
+ return;
551
+ } else {
552
+ const resolvedAlias = await resolveWithContext(alias.specifier);
553
+ if (!isFileResolution(resolvedAlias)) return;
554
+ resolvedAliasPath = normalizePathSeparators(resolve$1(resolvedAlias.id));
555
+ }
556
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
557
+ return {
558
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
559
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
560
+ };
561
+ })();
562
+ if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
500
563
  }
501
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
502
- for (const { alias, resolution } of candidates) {
503
- const paths = await resolution;
504
- if (!paths) continue;
505
- if (paths.publicSpecifier) {
506
- match = alias;
507
- matchedAlias = alias.specifier;
508
- matchedSpecifier = paths.publicSpecifier;
509
- break;
510
- }
511
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
512
- let canonicalMatch = false;
513
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
514
- await canonicalizeSpecifier();
515
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
516
- }
517
- if (normalizedMatch || canonicalMatch) {
518
- match = alias;
519
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
520
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
521
- break;
522
- }
564
+ candidates.push({
565
+ alias,
566
+ resolution
567
+ });
568
+ }
569
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
570
+ for (const { alias, resolution } of candidates) {
571
+ const paths = await resolution;
572
+ if (!paths) continue;
573
+ if (paths.publicSpecifier) {
574
+ match = alias;
575
+ matchedAlias = alias.specifier;
576
+ matchedSpecifier = paths.publicSpecifier;
577
+ break;
578
+ }
579
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
580
+ let canonicalMatch = false;
581
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
582
+ await canonicalizeSpecifier();
583
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
584
+ }
585
+ if (normalizedMatch || canonicalMatch) {
586
+ match = alias;
587
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
588
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
589
+ break;
523
590
  }
524
591
  }
525
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
526
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
527
- if (!match) return;
528
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
529
- if (!target) return;
530
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve$1(aliasResolveDir, target) : target);
531
- });
592
+ }
593
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
594
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
595
+ if (!match) return;
596
+ const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
597
+ if (!target) return;
598
+ const resolvedTarget = isRelativeSpecifier(target) ? resolve$1(aliasResolveDir, target) : target;
599
+ const resolved = await resolveWithContext(resolvedTarget);
600
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
601
+ return resolved;
532
602
  }
533
603
  };
534
604
  }
535
- function createViteAliasPlugin(aliases) {
605
+ function createViteAliasPlugin(aliases, workingDir) {
536
606
  if (!Array.isArray(aliases)) return;
537
- const resolvingAlias = "vitehubResolvingAlias";
538
607
  return {
539
608
  name: "vitehub-vite-alias",
540
- setup(build) {
541
- build.onResolve({ filter: /.*/ }, async (args) => {
542
- if (args.pluginData?.[resolvingAlias]) return;
543
- const alias = aliases.find(({ find }) => {
544
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
545
- find.lastIndex = 0;
546
- return find.test(args.path);
547
- });
548
- if (!alias) return;
549
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
550
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
551
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
552
- const result = await build.resolve(replacement, {
553
- importer: args.importer,
554
- kind: args.kind,
555
- namespace: args.namespace,
556
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
557
- resolveDir: args.resolveDir,
558
- with: args.with
559
- });
560
- const pluginData = Object.assign({}, result.pluginData);
561
- Reflect.deleteProperty(pluginData, resolvingAlias);
562
- return {
563
- ...result,
564
- pluginData
565
- };
609
+ async resolveId(source, importer, extra) {
610
+ if (extra.custom?.[resolvingViteAlias]) return;
611
+ const alias = aliases.find(({ find }) => {
612
+ if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
613
+ find.lastIndex = 0;
614
+ return find.test(source);
566
615
  });
616
+ if (!alias) return;
617
+ if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
618
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
619
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
620
+ const resolved = await resolveFrom(this, replacement, {
621
+ custom: extra.custom,
622
+ importer,
623
+ isEntry: extra.isEntry,
624
+ kind: extra.kind
625
+ }, workingDir, resolvingViteAlias);
626
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
627
+ return resolved;
567
628
  }
568
629
  };
569
630
  }
570
- function parseMarkdownTemplateRequest(id) {
631
+ function parseMarkdownTemplateRequest$1(id) {
571
632
  if (id.includes("#")) return;
572
633
  const queryIndex = id.indexOf("?");
573
634
  const path = id.split("?", 1)[0];
574
- if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
575
- if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
635
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix$1) ? { path } : void 0;
636
+ if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery$1) return;
576
637
  return { path };
577
638
  }
578
- function renderMarkdownTemplateModule(template) {
639
+ function renderMarkdownTemplateModule$1(template) {
579
640
  return [
580
- `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
641
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier$1)}`,
581
642
  `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
582
643
  "export default function render(data = {}) {",
583
644
  " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
@@ -585,11 +646,11 @@ function renderMarkdownTemplateModule(template) {
585
646
  ""
586
647
  ].join("\n");
587
648
  }
588
- function hasViteRawQuery(path) {
649
+ function hasViteRawQuery$1(path) {
589
650
  const queryIndex = path.indexOf("?");
590
651
  return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
591
652
  }
592
- async function resolveViteRawSpecifier(path, rootDir) {
653
+ async function resolveViteRawSpecifier$1(path, rootDir) {
593
654
  if (path.startsWith("/@fs/")) return path.slice(5);
594
655
  if (!rootDir || !path.startsWith("/")) return path;
595
656
  const rootRelativePath = path.slice(1);
@@ -602,174 +663,255 @@ async function resolveViteRawSpecifier(path, rootDir) {
602
663
  return resolve$1(rootDir, rootRelativePath);
603
664
  }
604
665
  }
605
- function createViteRawPlugin(rootDir, frameworkRuntime) {
666
+ function createViteRawPlugin$1(rootDir, frameworkRuntime, workingDir) {
606
667
  return {
607
668
  name: "vitehub-vite-raw",
608
- setup(build) {
609
- build.onResolve({
610
- filter: /^@vite-hub\/markdown-template$/,
611
- namespace: viteMarkdownTemplateNamespace
612
- }, async (args) => {
613
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
614
- return build.resolve("vite-hub/markdown-template", {
615
- importer: args.importer,
616
- kind: args.kind,
617
- resolveDir: args.resolveDir
618
- });
619
- });
620
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
621
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
622
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
623
- const raw = hasViteRawQuery(args.path);
624
- if (!markdownTemplate && !raw) return;
625
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
626
- let pluginData = args.pluginData;
627
- if (markdownTemplate) pluginData = {
628
- ...args.pluginData,
629
- [skipMarkdownTemplateResolve]: true
630
- };
631
- const resolved = await build.resolve(specifier, {
632
- importer: args.importer,
633
- kind: args.kind,
634
- namespace: args.namespace,
635
- pluginData,
636
- resolveDir: args.resolveDir,
637
- with: args.with
669
+ async resolveId(source, importer, extra) {
670
+ if (source === markdownTemplateRuntimeSpecifier$1 && importer?.startsWith(markdownTemplatePrefix)) {
671
+ if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier$1));
672
+ return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
673
+ custom: extra.custom,
674
+ kind: extra.kind
638
675
  });
639
- if (resolved.errors.length) return {
640
- errors: resolved.errors,
641
- warnings: resolved.warnings
642
- };
643
- if (resolved.external) return {
644
- external: true,
645
- namespace: resolved.namespace,
646
- path: resolved.path,
647
- pluginData: resolved.pluginData,
648
- sideEffects: resolved.sideEffects,
649
- suffix: resolved.suffix,
650
- warnings: resolved.warnings
651
- };
652
- if (resolved.namespace !== "file") return {
653
- 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.` }],
654
- warnings: resolved.warnings
655
- };
656
- return {
657
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
658
- path: resolved.path,
659
- pluginData: resolved.pluginData,
660
- sideEffects: resolved.sideEffects,
661
- suffix: resolved.suffix,
662
- warnings: resolved.warnings
663
- };
664
- });
665
- build.onLoad({
666
- filter: /.*/,
667
- namespace: viteRawNamespace
668
- }, async (args) => ({
669
- contents: await readFile(args.path),
670
- loader: "text"
671
- }));
672
- build.onLoad({
673
- filter: /.*/,
674
- namespace: viteMarkdownTemplateNamespace
675
- }, async (args) => ({
676
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
677
- loader: "js",
678
- resolveDir: dirname$1(args.path)
679
- }));
676
+ }
677
+ if (extra.custom?.[skipMarkdownTemplateResolve$1]) return;
678
+ const markdownTemplate = parseMarkdownTemplateRequest$1(source);
679
+ const raw = hasViteRawQuery$1(source);
680
+ if (!markdownTemplate && !raw) return;
681
+ const specifier = await resolveViteRawSpecifier$1(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
682
+ const resolved = await resolveFrom(this, specifier, {
683
+ custom: extra.custom,
684
+ importer,
685
+ isEntry: extra.isEntry,
686
+ kind: extra.kind
687
+ }, workingDir, skipMarkdownTemplateResolve$1);
688
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
689
+ if (resolved.external) return {
690
+ id: resolved.id,
691
+ external: resolved.external
692
+ };
693
+ const resolvedId = resolved.id;
694
+ 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.`);
695
+ return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
696
+ },
697
+ async load(id) {
698
+ if (id.startsWith(viteRawPrefix)) return {
699
+ code: await readFile(id.slice(18), "utf8"),
700
+ moduleType: "text"
701
+ };
702
+ if (id.startsWith(markdownTemplatePrefix)) return {
703
+ code: renderMarkdownTemplateModule$1(await readFile(id.slice(27), "utf8")),
704
+ moduleType: "js"
705
+ };
680
706
  }
681
707
  };
682
708
  }
683
- function createFileUrlPlugin() {
709
+ function createFileUrlPlugin$1() {
684
710
  return {
685
711
  name: "vitehub-file-url",
686
- setup(build) {
687
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
712
+ resolveId(source) {
713
+ if (source.startsWith("file:")) return fileURLToPath(source);
688
714
  }
689
715
  };
690
716
  }
691
717
  /**
692
718
  * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
693
719
  * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
720
+ * Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
694
721
  */
695
- function createWasmModulePlugin(outdir) {
722
+ function createWasmModulePlugin(outdir, workingDir, copy) {
696
723
  return {
697
724
  name: "vitehub-wasm-module",
698
- setup(build) {
699
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
700
- const resolved = await build.resolve(args.path.slice(0, -7), {
701
- importer: args.importer,
702
- kind: args.kind,
703
- resolveDir: args.resolveDir
704
- });
705
- if (resolved.errors.length) return { errors: resolved.errors };
706
- const bytes = await readFile(resolved.path);
707
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
708
- await mkdir(outdir, { recursive: true });
709
- await copyFile(resolved.path, join(outdir, name));
710
- return {
711
- external: true,
712
- path: `./${name}`
713
- };
725
+ async resolveId(source, importer, extra) {
726
+ if (!source.endsWith(".wasm?module")) return;
727
+ const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
728
+ custom: extra.custom,
729
+ kind: extra.kind
714
730
  });
731
+ if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
732
+ if (!copy) return resolved.id;
733
+ const bytes = await readFile(resolved.id);
734
+ const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
735
+ await mkdir(outdir, { recursive: true });
736
+ await copyFile(resolved.id, join(outdir, name));
737
+ return {
738
+ id: `./${name}`,
739
+ external: true
740
+ };
741
+ }
742
+ };
743
+ }
744
+ /**
745
+ * Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
746
+ */
747
+ function createExternalPackagesPlugin() {
748
+ return {
749
+ name: "vitehub-external-packages",
750
+ async resolveId(source, importer, extra) {
751
+ if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
752
+ id: source,
753
+ external: true
754
+ };
755
+ if (source.startsWith("#")) return await this.resolve(source, importer, {
756
+ custom: extra.custom,
757
+ kind: extra.kind
758
+ }) ?? {
759
+ id: source,
760
+ external: true
761
+ };
762
+ if (isBareSpecifier(source) && !isBuiltin(source)) return {
763
+ id: source,
764
+ external: true
765
+ };
766
+ }
767
+ };
768
+ }
769
+ function hasImportRejectionHandler(importNode, parents) {
770
+ let expression = importNode;
771
+ let parent = parents.get(expression);
772
+ while (parent?.type === "MemberExpression" && parent.object === expression) {
773
+ const call = parents.get(parent);
774
+ if (call?.type !== "CallExpression" || call.callee !== parent) break;
775
+ const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
776
+ const handler = call.arguments[method === "then" ? 1 : 0];
777
+ if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
778
+ if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
779
+ }
780
+ if (method !== "then" && method !== "finally") break;
781
+ expression = call;
782
+ parent = parents.get(expression);
783
+ }
784
+ if (parent?.type !== "AwaitExpression") return false;
785
+ for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
786
+ if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
787
+ if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
788
+ child = ancestor;
789
+ }
790
+ return false;
791
+ }
792
+ function createOptionalImportPlugin() {
793
+ const prefix = "\0vitehub-optional-import:";
794
+ return {
795
+ name: "vitehub-optional-import",
796
+ resolveId(source) {
797
+ if (source.startsWith(prefix)) return {
798
+ id: source.slice(25),
799
+ external: "absolute"
800
+ };
801
+ },
802
+ transform: {
803
+ order: "post",
804
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
805
+ async handler(code, id) {
806
+ const { parseSync } = await import("vite");
807
+ const module = parseSync(id, code, {
808
+ lang: moduleLanguage(id),
809
+ preserveParens: false,
810
+ sourceType: "module"
811
+ });
812
+ if (module.errors.length) return;
813
+ const parents = /* @__PURE__ */ new WeakMap();
814
+ const handled = [];
815
+ walk(module.program, (node, parent) => {
816
+ if (parent) parents.set(node, parent);
817
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
818
+ if (hasImportRejectionHandler(node, parents)) handled.push({
819
+ source: node.source.value,
820
+ start: node.source.start,
821
+ end: node.source.end
822
+ });
823
+ });
824
+ if (!handled.length) return;
825
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
826
+ 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);
827
+ return code;
828
+ }
715
829
  }
716
830
  };
717
831
  }
832
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
833
+ function createExternalMatcher(patterns) {
834
+ if (!patterns?.length) return;
835
+ const matchers = patterns.map((pattern) => {
836
+ if (pattern.includes("*")) {
837
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp$1).join(".*")}$`);
838
+ return (id) => expression.test(id);
839
+ }
840
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
841
+ });
842
+ return (id) => matchers.some((matches) => matches(id));
843
+ }
718
844
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
719
- const { build: bundle } = await import("esbuild");
845
+ const { rolldown } = await importRolldown();
720
846
  options.signal?.throwIfAborted();
721
847
  const format = options.format || "esm";
722
848
  const platform = options.platform || "neutral";
723
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
849
+ const workingDir = options.workingDir ?? process.cwd();
724
850
  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/"));
725
851
  const plugins = [];
726
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
852
+ plugins.push(createWasmModulePlugin(dirname$1(outfile), workingDir, platform !== "node"));
853
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
727
854
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
728
- plugins.push(...options.plugins ?? [], createFileUrlPlugin());
855
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin$1());
856
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
729
857
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
730
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
731
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname$1(outfile)));
732
- const result = await bundle({
733
- absWorkingDir: options.workingDir,
734
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
735
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
736
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
737
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
738
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
739
- "}"
740
- ] : []].filter(Boolean).join("\n") } : void 0,
741
- bundle: true,
742
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
743
- define: options.define,
744
- entryPoints: [entryFile],
745
- external: options.external,
746
- format,
747
- keepNames: options.minifySyntax || options.minifyIdentifiers,
748
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
749
- logLevel: "silent",
750
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
751
- resolveExtensions: options.extensions,
752
- minifyIdentifiers: options.minifyIdentifiers,
753
- minifySyntax: options.minifySyntax,
754
- minifyWhitespace: options.minifyWhitespace,
755
- outfile,
756
- packages: options.packages,
858
+ plugins.push(createViteRawPlugin$1(options.rootDir, frameworkRuntime, workingDir));
859
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
860
+ plugins.push(createOptionalImportPlugin());
861
+ const isExternal = createExternalMatcher(options.external);
862
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
863
+ compress: options.minifySyntax ?? false,
864
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
865
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
866
+ } : false;
867
+ const banner = [options.banner, ...format === "esm" && platform === "node" ? [
868
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
869
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
870
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
871
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
872
+ "}"
873
+ ] : []].filter(Boolean).join("\n");
874
+ const bundle = await rolldown({
875
+ cwd: workingDir,
876
+ external: isExternal ? (id) => isExternal(id) : void 0,
877
+ input: entryFile,
878
+ onLog(level, log) {
879
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
880
+ },
881
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
757
882
  platform,
758
- preserveSymlinks: options.preserveSymlinks,
759
883
  plugins,
760
- sourcemap: false,
761
- target: "es2022",
762
- write: options.signal ? false : true
884
+ resolve: {
885
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
886
+ extensions: options.extensions,
887
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
888
+ symlinks: !options.preserveSymlinks
889
+ },
890
+ transform: {
891
+ define: options.define,
892
+ target: "es2022"
893
+ },
894
+ tsconfig: options.tsconfig ?? true
763
895
  });
764
- options.signal?.throwIfAborted();
765
- if (options.signal) {
766
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
767
- await mkdir(dirname$1(output.path), { recursive: true });
768
- options.signal.throwIfAborted();
769
- await writeFile(output.path, output.contents, { signal: options.signal });
770
- }));
771
- options.signal.throwIfAborted();
896
+ let output;
897
+ try {
898
+ output = (await bundle.generate({
899
+ banner: banner || void 0,
900
+ codeSplitting: false,
901
+ format,
902
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
903
+ minify,
904
+ polyfillRequire: !(format === "esm" && platform === "node"),
905
+ sourcemap: false
906
+ })).output;
907
+ } finally {
908
+ await bundle.close();
772
909
  }
910
+ options.signal?.throwIfAborted();
911
+ const chunk = output.find((file) => file.type === "chunk");
912
+ await mkdir(dirname$1(outfile), { recursive: true });
913
+ await writeFile(outfile, chunk.code, { signal: options.signal });
914
+ options.signal?.throwIfAborted();
773
915
  }
774
916
  //#endregion
775
917
  //#region ../internal/src/build/scan-module.ts
@@ -778,16 +920,22 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
778
920
  * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
779
921
  * `dynamic`, so callers can report their own diagnostics.
780
922
  */
781
- function languageOf(file) {
782
- if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
783
- if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
784
- if (/\.(?:c|m)?js$/i.test(file)) return "js";
785
- return "ts";
786
- }
923
+ var scan_module_exports = /* @__PURE__ */ __exportAll({
924
+ dynamic: () => dynamic,
925
+ exportNames: () => exportNames,
926
+ maskLiterals: () => maskLiterals,
927
+ objectProperties: () => objectProperties,
928
+ scanModule: () => scanModule,
929
+ staticValue: () => staticValue,
930
+ unwrapExpression: () => unwrapExpression,
931
+ walk: () => walk
932
+ });
933
+ /** The value of an expression that the scanner cannot read without running the module. */
934
+ const dynamic = Symbol("dynamic");
787
935
  /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
788
936
  function scanModule(source, file = "module.ts") {
789
937
  const result = parseSync(file, source, {
790
- lang: languageOf(file),
938
+ lang: moduleLanguage(file),
791
939
  preserveParens: false,
792
940
  sourceType: "module"
793
941
  });
@@ -799,19 +947,109 @@ function scanModule(source, file = "module.ts") {
799
947
  source
800
948
  };
801
949
  }
802
- function isNode(value) {
803
- return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
950
+ /** Lists the names that a module exports. A default export reads as `default`. Type-only exports are left out. */
951
+ function exportNames(source, file = "module.ts") {
952
+ const { module } = parseSync(file, source, {
953
+ lang: moduleLanguage(file),
954
+ sourceType: "module"
955
+ });
956
+ return module.staticExports.flatMap((statement) => statement.entries).flatMap((entry) => {
957
+ if (entry.isType) return [];
958
+ if (entry.exportName.kind === "Default") return ["default"];
959
+ return entry.exportName.name === null ? [] : [entry.exportName.name];
960
+ });
804
961
  }
805
- /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
806
- function walk(node, visit, parent) {
807
- if (visit(node, parent) === false) return;
808
- const fields = node;
809
- for (const key in fields) {
810
- const child = fields[key];
811
- if (typeof child !== "object" || child === null || key === "parent") continue;
812
- if (Array.isArray(child)) {
813
- for (const item of child) if (isNode(item)) walk(item, visit, node);
814
- } else if (isNode(child)) walk(child, visit, node);
962
+ /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
963
+ function unwrapExpression(node) {
964
+ while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
965
+ return node;
966
+ }
967
+ function staticKey(property) {
968
+ const key = property.key;
969
+ if (key.type === "Identifier" && !property.computed) return key.name;
970
+ if (key.type === "PrivateIdentifier") return;
971
+ const value = staticValue(key);
972
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
973
+ }
974
+ /** The members of an object literal in source order. */
975
+ function objectProperties(object) {
976
+ return object.properties.map((node) => node.type === "SpreadElement" ? {
977
+ computed: false,
978
+ key: void 0,
979
+ node,
980
+ value: void 0
981
+ } : {
982
+ computed: node.computed,
983
+ key: staticKey(node),
984
+ node,
985
+ value: unwrapExpression(node.value)
986
+ });
987
+ }
988
+ /** The value of a template literal without substitutions. */
989
+ function staticTemplate(node) {
990
+ if (node.expressions.length) return dynamic;
991
+ return node.quasis[0]?.value.cooked ?? dynamic;
992
+ }
993
+ const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
994
+ /**
995
+ * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
996
+ * and accepts legacy octal escapes, so the scanner checks them again.
997
+ */
998
+ function hasInvalidEscape(raw) {
999
+ for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
1000
+ const code = escape.slice(2, -1);
1001
+ if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
1002
+ } else if (escape.startsWith("u")) {
1003
+ if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
1004
+ } else if (escape.startsWith("x")) {
1005
+ if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
1006
+ } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
1007
+ return false;
1008
+ }
1009
+ /**
1010
+ * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
1011
+ * and arrays and objects of these. Any other expression gives `dynamic`.
1012
+ */
1013
+ function staticValue(node) {
1014
+ node = unwrapExpression(node);
1015
+ switch (node.type) {
1016
+ case "Literal":
1017
+ if ("regex" in node) return dynamic;
1018
+ return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic : node.value;
1019
+ case "TemplateLiteral": return staticTemplate(node);
1020
+ case "Identifier": return node.name === "undefined" ? void 0 : dynamic;
1021
+ case "UnaryExpression": {
1022
+ if (node.operator === "void") return staticValue(node.argument) === dynamic ? dynamic : void 0;
1023
+ const value = staticValue(node.argument);
1024
+ if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
1025
+ return dynamic;
1026
+ }
1027
+ case "ArrayExpression": {
1028
+ const values = [];
1029
+ for (const element of node.elements) {
1030
+ if (element === null || element.type === "SpreadElement") return dynamic;
1031
+ const value = staticValue(element);
1032
+ if (value === dynamic) return dynamic;
1033
+ values.push(value);
1034
+ }
1035
+ return values;
1036
+ }
1037
+ case "ObjectExpression": {
1038
+ const values = {};
1039
+ for (const property of objectProperties(node)) {
1040
+ if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic;
1041
+ const value = staticValue(property.value);
1042
+ if (value === dynamic) return dynamic;
1043
+ Object.defineProperty(values, property.key, {
1044
+ configurable: true,
1045
+ enumerable: true,
1046
+ value,
1047
+ writable: true
1048
+ });
1049
+ }
1050
+ return values;
1051
+ }
1052
+ default: return dynamic;
815
1053
  }
816
1054
  }
817
1055
  function isLineTerminator(char) {
@@ -1387,7 +1625,8 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1387
1625
  async function traceImportedSources(paths, root, configuredRoots) {
1388
1626
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
1389
1627
  if (!entries.length) return /* @__PURE__ */ new Set();
1390
- const { build } = await import("esbuild");
1628
+ const { rolldown } = await importRolldown();
1629
+ const resolvingTraceHint = "vitehubResolvingTraceHint";
1391
1630
  const physicalRoot = realpathSync(root);
1392
1631
  const traceBuildVariants = [
1393
1632
  { platform: "node" },
@@ -1445,113 +1684,99 @@ async function traceImportedSources(paths, root, configuredRoots) {
1445
1684
  const queriedResourceSources = /* @__PURE__ */ new Set();
1446
1685
  const importedSourceHints = /* @__PURE__ */ new Set();
1447
1686
  const results = [];
1687
+ const toRootSource = (path) => pathContains$1(root, path) ? path : pathContains$1(physicalRoot, path) ? resolve$1(root, relative$1(physicalRoot, path)) : void 0;
1688
+ const isProjectSource = (path) => Boolean(path && existsSync(path) && !relative$1(root, path).split(sep).includes("node_modules"));
1448
1689
  for (const variant of traceBuildVariants) {
1449
- const [result] = await Promise.allSettled([build({
1450
- absWorkingDir: root,
1451
- bundle: true,
1452
- entryPoints: tracedBatch,
1453
- format: "esm",
1454
- logLevel: "silent",
1455
- metafile: true,
1456
- outdir: resolve$1(root, ".vitehub-provider-trace"),
1457
- packages: "bundle",
1458
- ...variant,
1459
- plugins: [{
1460
- name: "vitehub-provider-vite-resource-query",
1461
- setup(traceBuild) {
1462
- const resolvingPackageImportHint = "vitehubResolvingPackageImportHint";
1463
- traceBuild.onResolve({ filter: /^\.\.?\// }, (request) => {
1464
- const source = request.resolveDir && resolve$1(request.resolveDir, request.path.split(/[?#]/, 1)[0]);
1465
- if (source && existsSync(source)) importedSourceHints.add(source);
1466
- });
1467
- traceBuild.onResolve({ filter: /^#/ }, async (request) => {
1468
- if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1469
- if (!request.importer) return void 0;
1470
- const suffixOffset = request.path.slice(1).search(/[?#]/);
1471
- const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset + 1);
1472
- const resolution = await traceBuild.resolve(packageImport, {
1473
- importer: request.importer,
1474
- kind: request.kind,
1475
- namespace: request.namespace,
1476
- pluginData: {
1477
- ...request.pluginData,
1478
- [resolvingPackageImportHint]: true
1479
- },
1480
- resolveDir: request.resolveDir,
1481
- with: request.with
1482
- });
1483
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && existsSync(resolution.path)) importedSourceHints.add(resolution.path);
1484
- });
1485
- const resolvingBarePackageHint = "vitehubResolvingBarePackageHint";
1486
- traceBuild.onResolve({ filter: /^[^./#]/ }, async (request) => {
1487
- if (request.pluginData?.[resolvingBarePackageHint]) return void 0;
1488
- if (!request.importer) return void 0;
1489
- const suffixOffset = request.path.search(/[?#]/);
1490
- const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset);
1491
- const resolution = await traceBuild.resolve(packageImport, {
1492
- importer: request.importer,
1493
- kind: request.kind,
1494
- namespace: request.namespace,
1495
- pluginData: {
1496
- ...request.pluginData,
1497
- [resolvingBarePackageHint]: true
1498
- },
1499
- resolveDir: request.resolveDir,
1500
- with: request.with
1501
- });
1502
- const source = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve$1(root, relative$1(physicalRoot, resolution.path)) : void 0;
1503
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && source && existsSync(source) && !relative$1(root, source).split(sep).includes("node_modules")) importedSourceHints.add(source);
1504
- return {
1505
- external: true,
1506
- path: request.path
1507
- };
1508
- });
1509
- traceBuild.onResolve({ filter: /[?#]/ }, (request) => {
1510
- if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1511
- const resourcePath = request.path.split(/[?#]/, 1)[0];
1512
- let resourceSource;
1513
- if (request.resolveDir && (resourcePath.startsWith("./") || resourcePath.startsWith("../"))) resourceSource = resolve$1(request.resolveDir, resourcePath);
1514
- else if (request.resolveDir && resourcePath.startsWith("/")) {
1515
- const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, request.resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1516
- const rootRelativePath = resourcePath.slice(1);
1517
- const publicSource = resolve$1(projectRoot, "public", rootRelativePath);
1518
- resourceSource = existsSync(publicSource) ? publicSource : resolve$1(projectRoot, rootRelativePath);
1519
- }
1520
- if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1521
- return {
1522
- external: true,
1523
- path: request.path
1524
- };
1525
- });
1526
- traceBuild.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
1527
- const sourcePath = pathContains$1(root, request.path) ? request.path : pathContains$1(physicalRoot, request.path) ? resolve$1(root, relative$1(physicalRoot, request.path)) : void 0;
1528
- if (!sourcePath || relative$1(root, sourcePath).split(sep).includes("node_modules")) return void 0;
1529
- const source = await readFile(request.path, "utf8").catch(() => void 0);
1530
- if (!source) return void 0;
1531
- const runtimeRequests = /* @__PURE__ */ new Map();
1532
- for (const runtimeRequest of traceComputedModuleSourcesOnce(request.path, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1533
- await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1534
- const resolveFrom = runtimeRequest.resolveFrom ?? request.path;
1535
- const resolution = await traceBuild.resolve(runtimeRequest.specifier, {
1536
- importer: resolveFrom,
1537
- kind: runtimeRequest.kind,
1538
- namespace: request.namespace,
1539
- resolveDir: dirname$1(resolveFrom)
1540
- });
1541
- const resolvedSource = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve$1(root, relative$1(physicalRoot, resolution.path)) : void 0;
1542
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && resolvedSource && existsSync(resolvedSource) && !relative$1(root, resolvedSource).split(sep).includes("node_modules")) importedSourceHints.add(resolvedSource);
1543
- }));
1544
- });
1690
+ const inputs = /* @__PURE__ */ new Set();
1691
+ const tracePlugin = {
1692
+ name: "vitehub-provider-vite-resource-query",
1693
+ async resolveId(source, importer, extra) {
1694
+ if (!importer || extra.custom?.[resolvingTraceHint]) return;
1695
+ const resolveDir = isAbsolute(importer) ? dirname$1(importer) : root;
1696
+ const hintOptions = {
1697
+ custom: {
1698
+ ...extra.custom,
1699
+ [resolvingTraceHint]: true
1700
+ },
1701
+ kind: extra.kind
1702
+ };
1703
+ if (/^\.\.?\//.test(source)) {
1704
+ const relativeSource = resolve$1(resolveDir, source.split(/[?#]/, 1)[0]);
1705
+ if (existsSync(relativeSource)) importedSourceHints.add(relativeSource);
1706
+ } else if (source.startsWith("#")) {
1707
+ const suffixOffset = source.slice(1).search(/[?#]/);
1708
+ const packageImport = suffixOffset === -1 ? source : source.slice(0, suffixOffset + 1);
1709
+ const resolution = await this.resolve(packageImport, importer, hintOptions);
1710
+ if (resolution && !resolution.external && isAbsolute(resolution.id) && existsSync(resolution.id)) importedSourceHints.add(resolution.id);
1711
+ } else if (/^[^./#]/.test(source)) {
1712
+ const suffixOffset = source.search(/[?#]/);
1713
+ const packageImport = suffixOffset === -1 ? source : source.slice(0, suffixOffset);
1714
+ const resolution = await this.resolve(packageImport, importer, hintOptions);
1715
+ const resolvedSource = resolution && !resolution.external && isAbsolute(resolution.id) ? toRootSource(resolution.id) : void 0;
1716
+ if (isProjectSource(resolvedSource)) importedSourceHints.add(resolvedSource);
1717
+ return {
1718
+ id: source,
1719
+ external: true
1720
+ };
1545
1721
  }
1546
- }],
1547
- write: false
1548
- })]);
1549
- if (result?.status === "fulfilled") results.push(result.value);
1722
+ if (!/[?#]/.test(source)) return;
1723
+ const resourcePath = source.split(/[?#]/, 1)[0];
1724
+ let resourceSource;
1725
+ if (resourcePath.startsWith("./") || resourcePath.startsWith("../")) resourceSource = resolve$1(resolveDir, resourcePath);
1726
+ else if (resourcePath.startsWith("/")) {
1727
+ const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1728
+ const rootRelativePath = resourcePath.slice(1);
1729
+ const publicSource = resolve$1(projectRoot, "public", rootRelativePath);
1730
+ resourceSource = existsSync(publicSource) ? publicSource : resolve$1(projectRoot, rootRelativePath);
1731
+ }
1732
+ if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1733
+ return {
1734
+ id: source,
1735
+ external: true
1736
+ };
1737
+ },
1738
+ async load(id) {
1739
+ if (!isAbsolute(id)) return;
1740
+ inputs.add(id);
1741
+ if (!/\.[cm]?[jt]sx?$/.test(id)) return;
1742
+ const sourcePath = toRootSource(id);
1743
+ if (!sourcePath || relative$1(root, sourcePath).split(sep).includes("node_modules")) return;
1744
+ const source = await readFile(id, "utf8").catch(() => void 0);
1745
+ if (!source) return;
1746
+ const runtimeRequests = /* @__PURE__ */ new Map();
1747
+ for (const runtimeRequest of traceComputedModuleSourcesOnce(id, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1748
+ await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1749
+ const resolution = await this.resolve(runtimeRequest.specifier, runtimeRequest.resolveFrom ?? id, {
1750
+ kind: runtimeRequest.kind === "dynamic-import" ? "dynamic-import" : "require-call",
1751
+ skipSelf: false
1752
+ });
1753
+ const resolvedSource = resolution && !resolution.external && isAbsolute(resolution.id) ? toRootSource(resolution.id) : void 0;
1754
+ if (isProjectSource(resolvedSource)) importedSourceHints.add(resolvedSource);
1755
+ }));
1756
+ }
1757
+ };
1758
+ try {
1759
+ const bundle = await rolldown({
1760
+ cwd: root,
1761
+ input: tracedBatch,
1762
+ onLog(_level, log) {
1763
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
1764
+ },
1765
+ platform: variant.platform,
1766
+ plugins: [tracePlugin],
1767
+ resolve: { conditionNames: variant.conditions }
1768
+ });
1769
+ try {
1770
+ await bundle.generate({ format: "esm" });
1771
+ } finally {
1772
+ await bundle.close();
1773
+ }
1774
+ results.push(inputs);
1775
+ } catch {}
1550
1776
  }
1551
- for (const result of results) for (const path of Object.keys(result.metafile.inputs)) {
1552
- const source = resolve$1(root, path);
1777
+ for (const inputs of results) for (const source of inputs) {
1553
1778
  importedSources.add(source);
1554
- if (results.length === traceBuildVariants.length && results.every((variant) => Object.hasOwn(variant.metafile.inputs, path))) tracedEntries.add(source);
1779
+ if (results.length === traceBuildVariants.length && results.every((variant) => variant.has(source))) tracedEntries.add(source);
1555
1780
  }
1556
1781
  for (const path of importedSourceHints) {
1557
1782
  importedSources.add(path);
@@ -1765,6 +1990,12 @@ async function retainProviderOutputSources(options) {
1765
1990
  ])];
1766
1991
  for (const source of materializedSources.filter((source) => !pathContains$1(root, source))) retainedPaths.set(source, resolve$1(retainedContainer, relative$1(captureRoot, source)));
1767
1992
  const requestedSymlinks = [...new Set([root, ...materializedSources].flatMap((path) => symlinkSourcesForRequestedPath(root, path)))].sort((left, right) => relative$1(root, left).split(sep).length - relative$1(root, right).split(sep).length);
1993
+ const physicalRoot = realpathSync(root);
1994
+ materializedSources.push(...requestedSymlinks.flatMap((link) => {
1995
+ const physicalTarget = realpathSync(link);
1996
+ const target = pathContains$1(physicalRoot, physicalTarget) ? resolve$1(root, relative$1(physicalRoot, physicalTarget)) : physicalTarget;
1997
+ return materializedSources.filter((source) => source !== target && pathContains$1(target, source)).map((source) => resolve$1(link, relative$1(target, source)));
1998
+ }));
1768
1999
  const configuredOutputClosures = nestedConfiguredRoots.flatMap((configuredRoot) => {
1769
2000
  const segments = relative$1(root, configuredRoot).split(sep);
1770
2001
  const ignoredIndex = segments.findIndex((segment) => ignoredGeneratedDirectories.has(segment));
@@ -1956,7 +2187,7 @@ function createNodeFunctionConfig(extra = {}) {
1956
2187
  return {
1957
2188
  handler: "index.mjs",
1958
2189
  launcherType: "Nodejs",
1959
- runtime: "nodejs22.x",
2190
+ runtime: "nodejs24.x",
1960
2191
  shouldAddHelpers: false,
1961
2192
  supportsResponseStreaming: true,
1962
2193
  ...extra
@@ -2440,10 +2671,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2440
2671
  assertNetlifyFunctionName(functionName);
2441
2672
  return resolve$1(functionsRoot, `${functionName}.mjs`);
2442
2673
  }
2674
+ async function declaresTopLevelBinding(code, name) {
2675
+ const { parseSync } = await import("vite");
2676
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
2677
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
2678
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
2679
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
2680
+ });
2681
+ }
2443
2682
  async function appendNetlifyFunctionConfig(outfile, config) {
2444
2683
  if (!config) return;
2445
2684
  const bundled = await readFile(outfile, "utf8");
2446
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2685
+ const literal = stringifyProviderOutputConfig(config);
2686
+ let exported = `export const config = ${literal}`;
2687
+ if (await declaresTopLevelBinding(bundled, "config")) {
2688
+ const baseName = "vitehubNetlifyFunctionConfig";
2689
+ let name = baseName;
2690
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
2691
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
2692
+ }
2693
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
2447
2694
  }
2448
2695
  async function writeCloudflareDeploymentOutput(options, signal) {
2449
2696
  signal?.throwIfAborted();
@@ -3403,7 +3650,7 @@ function workflowDeploymentEnv(workflow) {
3403
3650
  }
3404
3651
  //#endregion
3405
3652
  //#region ../internal/src/definition-catalog.ts
3406
- const sourceFilePattern$1 = /\.(?:c|m)?[jt]sx?$/i;
3653
+ const sourceFilePattern$2 = /\.(?:c|m)?[jt]sx?$/i;
3407
3654
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
3408
3655
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
3409
3656
  const ignoredDirs = /* @__PURE__ */ new Set([
@@ -3466,13 +3713,13 @@ function listMatchingFiles(root, predicate, options = {}) {
3466
3713
  }
3467
3714
  /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
3468
3715
  function isDefinitionSourceFile(name) {
3469
- return sourceFilePattern$1.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
3716
+ return sourceFilePattern$2.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
3470
3717
  }
3471
3718
  function listSourceFiles(root, options = {}) {
3472
3719
  return listMatchingFiles(root, isDefinitionSourceFile, options);
3473
3720
  }
3474
3721
  function normalizePathDefinitionName(rootDir, file) {
3475
- return relative(rootDir, file).replace(sourceFilePattern$1, "").replace(/\/index$/i, "");
3722
+ return relative(rootDir, file).replace(sourceFilePattern$2, "").replace(/\/index$/i, "");
3476
3723
  }
3477
3724
  function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
3478
3725
  const normalized = relative(rootDir, file).replace(pattern, "");
@@ -3541,7 +3788,7 @@ function discoverDefinitions(feature, sources) {
3541
3788
  //#region src/discovery.ts
3542
3789
  const workflowSuffixPattern = /\.workflow\.(?:c|m)?[jt]s$/i;
3543
3790
  const agentSuffixPattern = /\.agent\.(?:c|m)?[jt]s$/i;
3544
- const sourceFilePattern = /\.(?:c|m)?[jt]s$/i;
3791
+ const sourceFilePattern$1 = /\.(?:c|m)?[jt]s$/i;
3545
3792
  const stepFilePattern = /^\d+[.-].*\.(?:c|m)?[jt]s$/i;
3546
3793
  const folderAgentFilePattern = /^agent\.(?:c|m)?[jt]s$/i;
3547
3794
  const folderAgentIndexFilePattern = /^index\.(?:c|m)?[jt]s$/i;
@@ -3562,7 +3809,7 @@ function readDirEntries(root) {
3562
3809
  }
3563
3810
  }
3564
3811
  function isSourceFile(file) {
3565
- return sourceFilePattern.test(file) && isDefinitionSourceFile(file);
3812
+ return sourceFilePattern$1.test(file) && isDefinitionSourceFile(file);
3566
3813
  }
3567
3814
  function findDefineAgentObjectStart(masked, start) {
3568
3815
  let index = start;
@@ -3953,6 +4200,170 @@ function readColocatedAgentFiles(handler, directoryName) {
3953
4200
  return Object.keys(files).length ? files : void 0;
3954
4201
  }
3955
4202
  //#endregion
4203
+ //#region ../internal/src/build/esbuild.ts
4204
+ const viteRawNamespace = "vitehub-vite-raw";
4205
+ const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
4206
+ const markdownTemplateFileSuffix = ".template.md";
4207
+ const markdownTemplateModuleQuery = "markdown-template";
4208
+ const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
4209
+ const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
4210
+ function parseMarkdownTemplateRequest(id) {
4211
+ if (id.includes("#")) return;
4212
+ const queryIndex = id.indexOf("?");
4213
+ const path = id.split("?", 1)[0];
4214
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
4215
+ if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
4216
+ return { path };
4217
+ }
4218
+ function renderMarkdownTemplateModule(template) {
4219
+ return [
4220
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
4221
+ `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
4222
+ "export default function render(data = {}) {",
4223
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
4224
+ "}",
4225
+ ""
4226
+ ].join("\n");
4227
+ }
4228
+ function hasViteRawQuery(path) {
4229
+ const queryIndex = path.indexOf("?");
4230
+ return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
4231
+ }
4232
+ async function resolveViteRawSpecifier(path, rootDir) {
4233
+ if (path.startsWith("/@fs/")) return path.slice(5);
4234
+ if (!rootDir || !path.startsWith("/")) return path;
4235
+ const rootRelativePath = path.slice(1);
4236
+ const publicPath = resolve$1(rootDir, "public", rootRelativePath);
4237
+ try {
4238
+ await stat(publicPath);
4239
+ return publicPath;
4240
+ } catch (error) {
4241
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
4242
+ return resolve$1(rootDir, rootRelativePath);
4243
+ }
4244
+ }
4245
+ function createViteRawPlugin(rootDir) {
4246
+ return {
4247
+ name: "vitehub-vite-raw",
4248
+ setup(build) {
4249
+ build.onResolve({
4250
+ filter: /^@vite-hub\/markdown-template$/,
4251
+ namespace: viteMarkdownTemplateNamespace
4252
+ }, () => {
4253
+ return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
4254
+ });
4255
+ build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
4256
+ if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
4257
+ const markdownTemplate = parseMarkdownTemplateRequest(args.path);
4258
+ const raw = hasViteRawQuery(args.path);
4259
+ if (!markdownTemplate && !raw) return;
4260
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
4261
+ let pluginData = args.pluginData;
4262
+ if (markdownTemplate) pluginData = {
4263
+ ...args.pluginData,
4264
+ [skipMarkdownTemplateResolve]: true
4265
+ };
4266
+ const resolved = await build.resolve(specifier, {
4267
+ importer: args.importer,
4268
+ kind: args.kind,
4269
+ namespace: args.namespace,
4270
+ pluginData,
4271
+ resolveDir: args.resolveDir,
4272
+ with: args.with
4273
+ });
4274
+ if (resolved.errors.length) return {
4275
+ errors: resolved.errors,
4276
+ warnings: resolved.warnings
4277
+ };
4278
+ if (resolved.external) return {
4279
+ external: true,
4280
+ namespace: resolved.namespace,
4281
+ path: resolved.path,
4282
+ pluginData: resolved.pluginData,
4283
+ sideEffects: resolved.sideEffects,
4284
+ suffix: resolved.suffix,
4285
+ warnings: resolved.warnings
4286
+ };
4287
+ if (resolved.namespace !== "file") return {
4288
+ 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.` }],
4289
+ warnings: resolved.warnings
4290
+ };
4291
+ return {
4292
+ namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
4293
+ path: resolved.path,
4294
+ pluginData: resolved.pluginData,
4295
+ sideEffects: resolved.sideEffects,
4296
+ suffix: resolved.suffix,
4297
+ warnings: resolved.warnings
4298
+ };
4299
+ });
4300
+ build.onLoad({
4301
+ filter: /.*/,
4302
+ namespace: viteRawNamespace
4303
+ }, async (args) => ({
4304
+ contents: await readFile(args.path),
4305
+ loader: "text"
4306
+ }));
4307
+ build.onLoad({
4308
+ filter: /.*/,
4309
+ namespace: viteMarkdownTemplateNamespace
4310
+ }, async (args) => ({
4311
+ contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
4312
+ loader: "js",
4313
+ resolveDir: dirname$1(args.path)
4314
+ }));
4315
+ }
4316
+ };
4317
+ }
4318
+ function createFileUrlPlugin() {
4319
+ return {
4320
+ name: "vitehub-file-url",
4321
+ setup(build) {
4322
+ build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
4323
+ }
4324
+ };
4325
+ }
4326
+ /**
4327
+ * Bundles with esbuild. Only the Workflow DevKit steps bundle uses it: Workflow DevKit ships its transforms as esbuild
4328
+ * plugins and installs esbuild itself. Every other bundle goes through `bundleEsmEntry` of `./rolldown.ts`.
4329
+ */
4330
+ async function bundleEsbuildEntry(bundle, entryFile, outfile, options = {}) {
4331
+ const format = options.format || "esm";
4332
+ const platform = options.platform || "neutral";
4333
+ await bundle({
4334
+ absWorkingDir: options.workingDir,
4335
+ banner: format === "esm" && platform === "node" ? { js: [
4336
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
4337
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
4338
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
4339
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
4340
+ "}"
4341
+ ].join("\n") } : void 0,
4342
+ bundle: true,
4343
+ conditions: platform === "node" ? ["node"] : void 0,
4344
+ define: options.define,
4345
+ entryPoints: [entryFile],
4346
+ external: options.external,
4347
+ format,
4348
+ keepNames: options.keepNames,
4349
+ loader: platform === "node" ? { ".wasm": "binary" } : void 0,
4350
+ logLevel: "silent",
4351
+ mainFields: platform === "neutral" ? ["module", "main"] : void 0,
4352
+ resolveExtensions: options.extensions,
4353
+ outfile,
4354
+ platform,
4355
+ plugins: [
4356
+ ...options.plugins ?? [],
4357
+ createFileUrlPlugin(),
4358
+ createViteRawPlugin(options.rootDir)
4359
+ ],
4360
+ sourcemap: false,
4361
+ target: "es2022",
4362
+ tsconfig: options.tsconfig,
4363
+ tsconfigRaw: options.tsconfigRaw
4364
+ });
4365
+ }
4366
+ //#endregion
3956
4367
  //#region ../internal/src/build/runtime-package-resolution.ts
3957
4368
  /** Locates package metadata through exports, an entry's ancestors, or the project's dependency roots. */
3958
4369
  function createRuntimePackageResolver(readPackageName) {
@@ -4154,7 +4565,7 @@ async function copyPackageDirectory(packageDir, targetDir) {
4154
4565
  });
4155
4566
  }
4156
4567
  async function loadNodeFileTrace() {
4157
- nodeFileTracePromise ??= import("./out-fRNaVslw.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).then(({ nodeFileTrace }) => nodeFileTrace);
4568
+ nodeFileTracePromise ??= import("./out-DxLKolA0.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).then(({ nodeFileTrace }) => nodeFileTrace);
4158
4569
  return nodeFileTracePromise;
4159
4570
  }
4160
4571
  async function resolvePackageTraceEntries(name, resolver, packageDir, packageJson) {
@@ -4221,6 +4632,39 @@ function parsePackageJson(value, path) {
4221
4632
  return value;
4222
4633
  }
4223
4634
  //#endregion
4635
+ //#region src/internal/step-options.ts
4636
+ const optionNames = ["retries", "timeout"];
4637
+ /**
4638
+ * Reads the `retries` and `timeout` exports of a step file from its source, without running it. The build checks them,
4639
+ * and writes them into the Vercel step, which cannot import the step file in the Workflow VM.
4640
+ */
4641
+ async function readWorkflowStepOptions(file) {
4642
+ const source = await readFile(file, "utf8");
4643
+ if (!/\b(?:retries|timeout)\b/.test(source)) return {};
4644
+ const { dynamic, exportNames, scanModule, staticValue } = await Promise.resolve().then(() => scan_module_exports);
4645
+ const exported = optionNames.filter((name) => exportNames(source, file).includes(name));
4646
+ if (!exported.length) return {};
4647
+ const values = {};
4648
+ for (const statement of scanModule(source, file).program.body) {
4649
+ if (statement.type !== "ExportNamedDeclaration" || statement.declaration?.type !== "VariableDeclaration") continue;
4650
+ for (const declarator of statement.declaration.declarations) {
4651
+ if (declarator.id.type !== "Identifier" || !declarator.init) continue;
4652
+ const value = staticValue(declarator.init);
4653
+ if (value !== dynamic) values[declarator.id.name] = value;
4654
+ }
4655
+ }
4656
+ const options = {};
4657
+ for (const name of exported) {
4658
+ if (!Object.hasOwn(values, name)) throw workflowErrorDiagnostics.WORKFLOW_STEP_OPTIONS_NOT_STATIC({
4659
+ file,
4660
+ option: name
4661
+ });
4662
+ Object.assign(options, { [name]: values[name] });
4663
+ }
4664
+ resolveWorkflowStepOptions(file, options);
4665
+ return options;
4666
+ }
4667
+ //#endregion
4224
4668
  //#region src/internal/vite-build.ts
4225
4669
  function resolveVercelWorkflowWorld(workflowApi) {
4226
4670
  const workflowCore = createRequire(workflowApi).resolve("@workflow/core");
@@ -4290,52 +4734,106 @@ const nodeBuiltinExternals = [.../* @__PURE__ */ new Set([
4290
4734
  ])];
4291
4735
  const optionalAgentRuntimeExternals = ["@vite-hub/workspace", "@vite-hub/workspace/*"];
4292
4736
  const optionalViteDevtoolsPattern = /^@vitejs\/devtools-(?:oxc|rolldown|vite|vitest)(?:\/.*)?$/;
4737
+ function packageNameOf(specifier) {
4738
+ const [scope, name] = specifier.split("/");
4739
+ return scope.startsWith("@") && name ? `${scope}/${name}` : scope;
4740
+ }
4741
+ /** Reads the optional peers that the package of `file` declares, from the nearest `package.json` that has a name. */
4742
+ function createOptionalPeerReader() {
4743
+ const peersByDirectory = /* @__PURE__ */ new Map();
4744
+ const read = (directory) => {
4745
+ const cached = peersByDirectory.get(directory);
4746
+ if (cached) return cached;
4747
+ let peers = /* @__PURE__ */ new Set();
4748
+ const manifest = join(directory, "package.json");
4749
+ const metadata = existsSync(manifest) ? JSON.parse(readFileSync(manifest, "utf8").replace(/^\uFEFF/, "")) : void 0;
4750
+ if (isRuntimeRecord(metadata) && typeof metadata.name === "string") {
4751
+ const meta = isRuntimeRecord(metadata.peerDependenciesMeta) ? metadata.peerDependenciesMeta : {};
4752
+ peers = new Set(Object.entries(meta).filter(([, value]) => isRuntimeRecord(value) && value.optional === true).map(([name]) => name));
4753
+ } else if (dirname$1(directory) !== directory) peers = read(dirname$1(directory));
4754
+ peersByDirectory.set(directory, peers);
4755
+ return peers;
4756
+ };
4757
+ return (file) => read(dirname$1(file));
4758
+ }
4759
+ /** Tells whether a `node_modules` folder on the way up from `directory` holds the package, as Node looks it up. */
4760
+ function packageInstalledFrom(directory, name) {
4761
+ for (let current = directory;; current = dirname$1(current)) {
4762
+ if (existsSync(join(current, "node_modules", name))) return true;
4763
+ if (dirname$1(current) === current) return false;
4764
+ }
4765
+ }
4293
4766
  /**
4294
4767
  * Lets a Workflow bundle import optional packages that the app did not install. Vite DevTools becomes an empty
4295
- * module. `@vite-hub/kv`, an optional peer that Agents load only when a Chat connector runs, becomes a module that
4296
- * fails on import, as the missing package would.
4768
+ * module. `@vite-hub/kv`, an optional peer that Agents load only when a Chat connector runs, and any optional peer
4769
+ * that a package loads with `import()`, such as `@modelcontextprotocol/sdk` in `@vite-hub/source/mcp`, become a
4770
+ * module that fails on import, as the missing package would.
4297
4771
  */
4298
4772
  function createOptionalPackagesPlugin(rootDir) {
4299
- const require = createRequire(join(rootDir, "package.json"));
4773
+ const missing = createMissingOptionalPackageResolver(rootDir);
4774
+ const prefix = "\0vitehub-optional-package:";
4775
+ return {
4776
+ name: "vitehub-optional-package",
4777
+ async resolveId(source, importer, extra) {
4778
+ return await missing(source, extra.kind, importer, async () => Boolean(await this.resolve(source, importer, { kind: extra.kind }))) ? `${prefix}${source}` : void 0;
4779
+ },
4780
+ load(id) {
4781
+ if (id.startsWith(prefix)) return missingOptionalPackageModule(id.slice(26));
4782
+ }
4783
+ };
4784
+ }
4785
+ /** {@link createOptionalPackagesPlugin} for the Workflow DevKit steps bundle, which Workflow DevKit builds with esbuild plugins. */
4786
+ function createOptionalPackagesEsbuildPlugin(rootDir) {
4787
+ const missing = createMissingOptionalPackageResolver(rootDir);
4300
4788
  const namespace = "vitehub-optional-package";
4301
4789
  return {
4302
4790
  name: namespace,
4303
4791
  setup(build) {
4304
- build.onResolve({ filter: optionalViteDevtoolsPattern }, (args) => {
4305
- try {
4306
- require.resolve(args.path);
4307
- return;
4308
- } catch (error) {
4309
- if (error.code !== "MODULE_NOT_FOUND") throw error;
4310
- return {
4311
- namespace,
4312
- path: args.path
4313
- };
4314
- }
4315
- });
4316
- build.onResolve({ filter: /^@vite-hub\/kv$/ }, async (args) => {
4792
+ build.onResolve({ filter: /^[^./#]/ }, async (args) => {
4317
4793
  if (args.pluginData === namespace) return;
4318
- const resolved = await build.resolve(args.path, {
4794
+ const resolves = async () => !(await build.resolve(args.path, {
4319
4795
  importer: args.importer,
4320
4796
  kind: args.kind,
4321
4797
  pluginData: namespace,
4322
4798
  resolveDir: args.resolveDir
4323
- });
4324
- return resolved.errors.length ? {
4799
+ })).errors.length;
4800
+ return await missing(args.path, args.kind, args.importer, resolves) ? {
4325
4801
  namespace,
4326
4802
  path: args.path
4327
- } : resolved;
4803
+ } : void 0;
4328
4804
  });
4329
4805
  build.onLoad({
4330
4806
  filter: /.*/,
4331
4807
  namespace
4332
4808
  }, (args) => ({
4333
- contents: optionalViteDevtoolsPattern.test(args.path) ? "export {}" : `const error = new globalThis.Error(${JSON.stringify(`Cannot find package "${args.path}". Install it to use it in a Workflow.`)}); error.code = "ERR_MODULE_NOT_FOUND"; throw error`,
4809
+ contents: missingOptionalPackageModule(args.path),
4334
4810
  loader: "js"
4335
4811
  }));
4336
4812
  }
4337
4813
  };
4338
4814
  }
4815
+ /** Tells whether an import names an optional package that the app did not install. */
4816
+ function createMissingOptionalPackageResolver(rootDir) {
4817
+ const require = createRequire(join(rootDir, "package.json"));
4818
+ const optionalPeersOf = createOptionalPeerReader();
4819
+ return async (specifier, kind, importer, resolves) => {
4820
+ if (optionalViteDevtoolsPattern.test(specifier)) try {
4821
+ require.resolve(specifier);
4822
+ return false;
4823
+ } catch (error) {
4824
+ if (error.code !== "MODULE_NOT_FOUND") throw error;
4825
+ return true;
4826
+ }
4827
+ if (specifier === "@vite-hub/kv") return !await resolves();
4828
+ if (kind !== "dynamic-import" || !importer || !isAbsolute(importer) || !/^[^./#]/.test(specifier)) return false;
4829
+ const name = packageNameOf(specifier);
4830
+ if (!optionalPeersOf(importer).has(name)) return false;
4831
+ return !packageInstalledFrom(dirname$1(importer), name);
4832
+ };
4833
+ }
4834
+ function missingOptionalPackageModule(specifier) {
4835
+ return optionalViteDevtoolsPattern.test(specifier) ? "export {}" : `const error = new globalThis.Error(${JSON.stringify(`Cannot find package "${specifier}". Install it to use it in a Workflow.`)}); error.code = "ERR_MODULE_NOT_FOUND"; throw error`;
4836
+ }
4339
4837
  /** The Workflow DevKit packages that a native Vercel Workflow needs. They are optional peers of this package. */
4340
4838
  const vercelWorkflowDevKitPackages = ["workflow", "@workflow/builders"];
4341
4839
  function missingVercelWorkflowDevKitError() {
@@ -4372,23 +4870,21 @@ async function loadVercelWorkflowBuilders() {
4372
4870
  async function createVercelWorkflowTransformPlugin(rootDir, idRoot = rootDir) {
4373
4871
  const builders = await loadVercelWorkflowBuilders();
4374
4872
  if (!builders) return void 0;
4375
- const plugin = builders.createSwcPlugin({
4376
- mode: "workflow",
4377
- projectRoot: rootDir
4378
- });
4873
+ const workingDir = idRoot.replace(/\\/g, "/").replace(/\/$/, "");
4379
4874
  return {
4380
- ...plugin,
4381
- setup: (build) => plugin.setup({
4382
- ...build,
4383
- initialOptions: {
4384
- ...build.initialOptions,
4385
- absWorkingDir: idRoot
4386
- },
4387
- onLoad: (options, callback) => build.onLoad(options, async (args) => {
4388
- const source = await readFile(args.path, "utf8");
4389
- return builders.shouldTransformFile(args.path, builders.detectWorkflowPatterns(source)) ? await callback(args) : void 0;
4390
- })
4391
- })
4875
+ name: "vitehub-vercel-workflow-transform",
4876
+ async load(id) {
4877
+ if (!/\.[cm]?[jt]sx?$/.test(id) || !isAbsolute(id)) return;
4878
+ const source = await readFile(id, "utf8");
4879
+ if (!builders.shouldTransformFile(id, builders.detectWorkflowPatterns(source))) return;
4880
+ const file = id.replace(/\\/g, "/");
4881
+ const filename = relative$1(workingDir, file).replace(/\\/g, "/").split("/").filter((segment) => segment !== "..").join("/");
4882
+ const code = source.replace(/require\(\s*(['"])(?:server|client)-only\1\s*\)/g, "void 0");
4883
+ return {
4884
+ code: (await builders.applySwcTransform(filename, code, "workflow", id, rootDir)).code,
4885
+ moduleType: id.endsWith(".tsx") ? "tsx" : id.endsWith(".jsx") ? "jsx" : "js"
4886
+ };
4887
+ }
4392
4888
  };
4393
4889
  }
4394
4890
  /**
@@ -4721,18 +5217,77 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
4721
5217
  }, null, 2)}\n`);
4722
5218
  const externalWorkflowRoutes = new Set(preservedRoutes.filter((route) => JSON.stringify(route).includes("/.well-known/workflow/v1/")).map((route) => JSON.stringify(route)));
4723
5219
  const definitionDirs = [.../* @__PURE__ */ new Set([...definitions.map((definition) => dirname$1(definition.handler)), ...nativeFiles.map((file) => dirname$1(file))])];
4724
- class ConfiguredWorkflowBuilder extends builders.VercelBuildOutputAPIBuilder {
5220
+ const { createPseudoPackagePlugin, createSwcPlugin, VercelBuildOutputAPIBuilder } = builders;
5221
+ class ConfiguredWorkflowBuilder extends VercelBuildOutputAPIBuilder {
5222
+ /**
5223
+ * Workflow DevKit bundles steps with its own esbuild plugins only. Steps import app code, so ViteHub bundles them:
5224
+ * Workflow DevKit writes the step registration imports, and ViteHub bundles them with its own resolution, as the
5225
+ * server bundle does. A step can import a `?markdown-template` file or a package that loads an optional peer the app
5226
+ * did not install, such as `@vite-hub/kv` in `@vite-hub/agent`.
5227
+ */
4725
5228
  async createStepsBundle(options) {
4726
- const result = await super.createStepsBundle(options);
4727
- if (!Object.keys(bundleDefines).length) return result;
4728
- const source = await readFile(options.outfile, "utf8");
4729
- const output = await transform(source, {
4730
- define: bundleDefines,
4731
- sourcefile: options.outfile,
4732
- sourcemap: "inline"
5229
+ const discoveredEntries = options.discoveredEntries ?? await this.discoverEntries(options.inputFiles, dirname$1(options.outfile), options.tsconfigPath);
5230
+ const entryFile = `${options.outfile}.entry.mjs`;
5231
+ const manifest = {};
5232
+ const registeredFiles = [...discoveredEntries.discoveredSteps, ...discoveredEntries.discoveredSerdeFiles];
5233
+ const swcPlugin = createSwcPlugin({
5234
+ mode: "step",
5235
+ moduleSpecifierRoot: this.moduleSpecifierRoot,
5236
+ projectRoot: this.transformProjectRoot,
5237
+ sideEffectEntries: await Promise.all(registeredFiles.map((file) => realpath(file).catch(() => file))),
5238
+ workflowManifest: manifest
4733
5239
  });
4734
- await writeFile(options.outfile, output.code);
4735
- return result;
5240
+ try {
5241
+ await this.createStepSourceRegistrationFile({
5242
+ discoveredEntries,
5243
+ inputFiles: options.inputFiles,
5244
+ outfile: entryFile,
5245
+ tsconfigPath: options.tsconfigPath
5246
+ });
5247
+ const tsconfigPath = options.tsconfigPath;
5248
+ const tsconfigOptions = tsconfigPath && (await lstat(tsconfigPath)).isSymbolicLink() ? { tsconfigRaw: await readFile(tsconfigPath, "utf8") } : { tsconfig: tsconfigPath };
5249
+ await bundleEsbuildEntry(build, entryFile, options.outfile, {
5250
+ ...tsconfigOptions,
5251
+ define: bundleDefines,
5252
+ extensions: [
5253
+ ".ts",
5254
+ ".tsx",
5255
+ ".mts",
5256
+ ".cts",
5257
+ ".js",
5258
+ ".jsx",
5259
+ ".mjs",
5260
+ ".cjs"
5261
+ ],
5262
+ external: [
5263
+ "bun",
5264
+ "bun:*",
5265
+ ...this.config.externalPackages ?? []
5266
+ ],
5267
+ format: "esm",
5268
+ keepNames: true,
5269
+ platform: "node",
5270
+ plugins: [
5271
+ createPseudoPackagePlugin(),
5272
+ createOptionalPackagesEsbuildPlugin(rootDir),
5273
+ {
5274
+ ...swcPlugin,
5275
+ setup: (build) => swcPlugin.setup({
5276
+ ...build,
5277
+ onLoad: (onLoadOptions, callback) => build.onLoad(onLoadOptions, (args) => args.path === entryFile ? void 0 : callback(args))
5278
+ })
5279
+ }
5280
+ ],
5281
+ rootDir,
5282
+ workingDir: this.config.workingDir
5283
+ });
5284
+ } finally {
5285
+ await rm(entryFile, { force: true });
5286
+ }
5287
+ return {
5288
+ context: void 0,
5289
+ manifest
5290
+ };
4736
5291
  }
4737
5292
  async createWorkflowsBundle(options) {
4738
5293
  const result = await super.createWorkflowsBundle(options);
@@ -4989,7 +5544,7 @@ function renderAgentWorkflowRegistryEntry(registryFile, definition, retainedAgen
4989
5544
  " if (cached) return cached",
4990
5545
  ` const loaded = await ${renderRegistryImport(registryFile, definition.handler)}`,
4991
5546
  ` const agent = workspaceAgentWithSourceRoot(agentWithColocatedSkills(agentWithColocatedInstructions("default" in loaded ? loaded.default : loaded, ${JSON.stringify(instructions)}), ${JSON.stringify(readAgentSkills(definition.handler))}), ${JSON.stringify(resolveAgentWorkspaceSourceRoot(definition.handler))}, ${JSON.stringify(instructions)})`,
4992
- ` const entry = { options: { rootStep: false }, handler: async (_payload, context) => await runAgentWorkflowDefinition(agent, { ...context, payload: { ...context.payload, agentIdentity: context.payload?.agentIdentity || { name: ${JSON.stringify(definition.agentIdentity || definition.name)} } } }, runAgentInline)${definition.source === "agent-workflow-recovery" ? ", internalAgentInvocationRecovery: true" : ""} }`,
5547
+ ` const entry = { rootStep: false, handler: async (context) => await runAgentWorkflowDefinition(agent, { ...context, payload: { ...context.payload, agentIdentity: context.payload?.agentIdentity || { name: ${JSON.stringify(definition.agentIdentity || definition.name)} } } }, runAgentInline)${definition.source === "agent-workflow-recovery" ? ", internalAgentInvocationRecovery: true" : ""} }`,
4993
5548
  ` registryEntryCache.set(${JSON.stringify(definition.name)}, entry)`,
4994
5549
  " return entry",
4995
5550
  ` }, ${definition.source === "agent-workflow-recovery" ? "{ internalAgentInvocationRecovery: true }" : "{}"}),`
@@ -5001,17 +5556,26 @@ function getGeneratedVercelWorkflowExport(definition) {
5001
5556
  }
5002
5557
  /** `@workflow/core` keeps the `sleep()` implementation of the Workflow VM on `globalThis` under this registered symbol. */
5003
5558
  const vercelWorkflowSleepSymbol = "WORKFLOW_SLEEP";
5004
- function createVercelNativeWorkflowContents(definition) {
5559
+ /**
5560
+ * The Workflow VM does not load the step files, so the step options are literals here. Workflow DevKit reads
5561
+ * `maxRetries` from the step function. It has no step timeout, so the step body runs each attempt with the ViteHub
5562
+ * timer, which it imports only inside the step.
5563
+ */
5564
+ function renderVercelNativeStep(name, implementation, step, options) {
5565
+ return [`async function ${name}(input) {\n "use step"\n${options.timeout === void 0 ? ` return await ${implementation}(input, { signal: new AbortController().signal })` : [` const { runWorkflowStepAttempt } = await import(${JSON.stringify(workflowRuntimeModule("execute"))})`, ` return await runWorkflowStepAttempt(${JSON.stringify(step)}, ${JSON.stringify(options.timeout)}, context => ${implementation}(input, context))`].join("\n")}\n}`, ...options.retries?.limit === void 0 ? [] : [`${name}.maxRetries = ${options.retries.limit}`]].join("\n");
5566
+ }
5567
+ async function createVercelNativeWorkflowContents(definition) {
5005
5568
  const imports = [];
5006
5569
  const workflows = [];
5007
5570
  const workflowExport = getGeneratedVercelWorkflowExport(definition);
5008
5571
  const steps = definition.steps;
5009
5572
  if (!workflowExport || !steps) return "";
5573
+ const stepOptions = await Promise.all(steps.map(readWorkflowStepOptions));
5010
5574
  const stepNames = steps.map((step, index) => {
5011
5575
  const implementation = `${workflowExport}Step${index}Implementation`;
5012
5576
  const name = `${workflowExport}Step${index}`;
5013
5577
  imports.push(`import ${implementation} from ${JSON.stringify(step)}`);
5014
- workflows.push(`async function ${name}(input) {\n "use step"\n return await ${implementation}(input)\n}`);
5578
+ workflows.push(renderVercelNativeStep(name, implementation, `${definition.name}/${relative$1(definition.handler, step)}`, stepOptions[index]));
5015
5579
  return name;
5016
5580
  });
5017
5581
  const startAt = `context[${JSON.stringify(workflowStartAtKey)}]`;
@@ -5029,14 +5593,14 @@ function renderWorkflowRegistryEntry(registryFile, definition, vercelNativeFiles
5029
5593
  const workflowDirectory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname$1(definition.handler) : definition.handler;
5030
5594
  const stepImports = definition.steps.map((step) => {
5031
5595
  const stepName = relative$1(workflowDirectory, step);
5032
- return `{ name: ${JSON.stringify(stepName)}, run: (await ${renderRegistryImport(registryFile, step)}).default }`;
5596
+ return `{ name: ${JSON.stringify(stepName)}, ...await ${renderRegistryImport(registryFile, step)}.then(step => ({ options: { retries: step.retries, timeout: step.timeout }, run: step.default })) }`;
5033
5597
  });
5034
5598
  const hasIndex = /\.(?:c|m)?[jt]s$/i.test(definition.handler);
5035
5599
  const indexImport = hasIndex ? `const index = await ${renderRegistryImport(registryFile, definition.handler)}` : "";
5036
5600
  const nativeExport = getGeneratedVercelWorkflowExport(definition);
5037
5601
  const vercelNativeFile = vercelNativeFiles[definition.name];
5038
5602
  const nativeImport = nativeExport && vercelNativeFile ? `const native = (await import(${JSON.stringify(createImportPath(registryFile, vercelNativeFile))})).${nativeExport}\n native.workflowId ||= ${JSON.stringify(`workflow//./.vitehub/workflow/vercel-native//${nativeExport}`)}\n native[${JSON.stringify(generatedNativeEntryKey)}] = true` : "";
5039
- const handler = hasIndex ? `index.default?.handler ? index.default : takeInlineWorkflowDefinitionForModule(${JSON.stringify(definition.name)}, index) || { handler: index.default }` : "{ handler: async (payload, context) => { let value = payload; for (const step of Object.values(context.steps)) value = await step(value); return value } }";
5603
+ const handler = hasIndex ? `index.default?.handler ? index.default : takeInlineWorkflowDefinitionForModule(${JSON.stringify(definition.name)}, index) || { handler: index.default }` : "{ handler: async ({ payload, steps }) => { let value = payload; for (const step of Object.values(steps)) value = await step(value); return value } }";
5040
5604
  return [
5041
5605
  ` [${JSON.stringify(definition.name)}]: async () => {`,
5042
5606
  ` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
@@ -5047,10 +5611,10 @@ function renderWorkflowRegistryEntry(registryFile, definition, vercelNativeFiles
5047
5611
  ` const definition = ${handler}`,
5048
5612
  " const entry = {",
5049
5613
  " ...definition,",
5050
- ` options: { ...definition.options, rootStep: false${nativeImport ? ", native" : ""} },`,
5051
- " handler: async (payload, context) => {",
5614
+ ` rootStep: false,${nativeImport ? " native," : ""}`,
5615
+ " handler: async (context) => {",
5052
5616
  " const workflowSteps = createWorkflowSteps(context, steps)",
5053
- " return await definition.handler(payload, { ...context, steps: workflowSteps })",
5617
+ " return await definition.handler({ ...context, steps: workflowSteps })",
5054
5618
  " },",
5055
5619
  " }",
5056
5620
  ` registryEntryCache.set(${JSON.stringify(definition.name)}, entry)`,
@@ -5096,7 +5660,7 @@ function createWorkflowRegistryContents(registryFile, definitions, importBases =
5096
5660
  const needsAgentRuntime = definitions.some((definition) => definition.source === "agent-workflow" || definition.source === "agent-workflow-recovery");
5097
5661
  const needsRegistryEntryCache = needsWorkflowRuntime || needsAgentRuntime;
5098
5662
  const installAgentWorkflowRuntime = needsAgentRuntime && importBases.workflow;
5099
- const workspaceDependencyRuntimeImports = importBases.workspaceRuntime && Object.values(importBases.workspaceDependencies ?? {}).some(Boolean) ? importBases.workspaceDependencies : void 0;
5663
+ const workspaceDependencyRuntimeImports = importBases.workspaceRuntime && importBases.workspaceDependencies?.shellWorkspace ? importBases.workspaceDependencies : void 0;
5100
5664
  const agent = importBases.agent;
5101
5665
  if (needsAgentRuntime && !agent) throw workflowErrorDiagnostics.WORKFLOW_B0003();
5102
5666
  const imports = [
@@ -5122,8 +5686,6 @@ function createWorkflowRegistryContents(registryFile, definitions, importBases =
5122
5686
  ] : [],
5123
5687
  ...workspaceDependencyRuntimeImports ? [
5124
5688
  "setWorkspaceDependencyRuntimeLoaders({",
5125
- ...workspaceDependencyRuntimeImports.sandboxTask ? [` sandboxTask: () => import(${JSON.stringify(workspaceDependencyRuntimeImports.sandboxTask)}),`] : [],
5126
- ...workspaceDependencyRuntimeImports.sandboxTaskRuntimeState ? [` sandboxTaskRuntimeState: () => import(${JSON.stringify(workspaceDependencyRuntimeImports.sandboxTaskRuntimeState)}),`] : [],
5127
5689
  ...workspaceDependencyRuntimeImports.shellWorkspace ? [` shellWorkspace: () => import(${JSON.stringify(workspaceDependencyRuntimeImports.shellWorkspace)}),`] : [],
5128
5690
  "})",
5129
5691
  ""
@@ -5230,8 +5792,9 @@ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverD
5230
5792
  if (nativeDefinitions.length) await mkdir(vercelNativeDir, { recursive: true });
5231
5793
  await Promise.all(nativeDefinitions.map(async (definition) => {
5232
5794
  const nativeFile = vercelNativeFiles[definition.name];
5233
- await writeFile(nativeFile, createVercelNativeWorkflowContents(definition), "utf8");
5795
+ await writeFile(nativeFile, await createVercelNativeWorkflowContents(definition), "utf8");
5234
5796
  }));
5797
+ await Promise.all(definitions.filter((definition) => !getGeneratedVercelWorkflowExport(definition)).flatMap((definition) => definition.steps ?? []).map(async (step) => await readWorkflowStepOptions(step)));
5235
5798
  const registryRuntimeFile = resolve$1(generatedDir, generatedRegistryRuntimeFileName);
5236
5799
  const agentModules = importBases.agent ?? (providerDefinitions.some((definition) => definition.source === "agent-workflow") ? await installedAgentWorkflowModules(rootDir) : void 0);
5237
5800
  const registryContents = createWorkflowRegistryContents(registryRuntimeFile, providerDefinitions, {
@@ -5496,6 +6059,16 @@ async function updateVercelWorkflowFunctionOwnership(rootDir, activeServerFuncti
5496
6059
  recursive: true
5497
6060
  })));
5498
6061
  }
6062
+ /** Workflow DevKit retries a step after about one second, so a Vercel native step cannot set `delay` or `backoff`. */
6063
+ async function assertVercelStepRetries(definitions) {
6064
+ for (const definition of definitions) {
6065
+ if (!getGeneratedVercelWorkflowExport(definition)) continue;
6066
+ for (const step of definition.steps ?? []) {
6067
+ const { retries } = await readWorkflowStepOptions(step);
6068
+ if (retries?.delay !== void 0 || retries?.backoff !== void 0) throw workflowErrorDiagnostics.WORKFLOW_STEP_RETRY_DELAY_UNSUPPORTED({ file: step });
6069
+ }
6070
+ }
6071
+ }
5499
6072
  async function generateProviderOutputsWithinLock(options, writeProviderDeploymentOutputs) {
5500
6073
  let artifacts = options.artifacts ?? await writeProviderEntries(options.rootDir, options.workflow, {
5501
6074
  agent: options.agentModules,
@@ -5505,6 +6078,7 @@ async function generateProviderOutputsWithinLock(options, writeProviderDeploymen
5505
6078
  }, options.serverDirs, options.includeUserAppEntry, options.transformRegistry, options.definitionRootDir);
5506
6079
  const { cloudflare: cloudflareWorkflowConfig, vercel: vercelWorkflowConfig } = resolveWorkflowProviderOutputs(options.workflow, options.hosting, options.inline);
5507
6080
  const vercelWorkflow = Boolean(vercelWorkflowConfig && vercelWorkflowConfig.driver === "vercel");
6081
+ if (vercelWorkflow) await assertVercelStepRetries(artifacts.providerDefinitions);
5508
6082
  const workflowTransformPlugin = vercelWorkflow && !options.nitroServer ? await createVercelWorkflowTransformPlugin(options.rootDir) : void 0;
5509
6083
  let commitGeneratedArtifacts = async () => {};
5510
6084
  let rollbackGeneratedArtifacts = async () => {};
@@ -5805,25 +6379,39 @@ async function writeWorkflowDevRegistryFiles(options) {
5805
6379
  //#endregion
5806
6380
  //#region src/internal/registry-types.ts
5807
6381
  const workflowTypesFile = ".vitehub/workflow.d.ts";
5808
- /** Types `steps` in `defineWorkflow(name, handler)` with the step files of each folder Workflow. */
6382
+ const sourceFilePattern = /\.(?:c|m)?[jt]s$/i;
6383
+ const javaScriptFilePattern = /\.(?:c|m)?js$/i;
6384
+ const ignoreJavaScriptTypes = "// @ts-ignore JavaScript files may have no declarations when allowJs is disabled.";
6385
+ function importSpecifier(file, target) {
6386
+ const path = relative(dirname(file), target);
6387
+ return path.startsWith(".") ? path : `./${path}`;
6388
+ }
6389
+ /**
6390
+ * Types `startWorkflow()` with the name and payload of each Workflow Definition (`WorkflowRegistry`), and `steps` with
6391
+ * the step files of each folder Workflow (`WorkflowStepRegistry`).
6392
+ */
5809
6393
  function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow") {
5810
- const entries = definitions.filter((definition) => definition.steps?.length).flatMap((definition) => {
5811
- const directory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname(definition.handler) : definition.handler;
6394
+ const registryEntries = definitions.flatMap((definition) => {
6395
+ if (!sourceFilePattern.test(definition.handler)) return [` ${JSON.stringify(definition.name)}: import(${JSON.stringify(importBase)}).WorkflowDefinition<unknown>`];
6396
+ const moduleType = `typeof import(${JSON.stringify(importSpecifier(file, definition.handler))})`;
6397
+ return [...javaScriptFilePattern.test(definition.handler) ? [` ${ignoreJavaScriptTypes}`] : [], ` ${JSON.stringify(definition.name)}: ${moduleType} extends { default: infer TDefault } ? TDefault : unknown`];
6398
+ });
6399
+ const stepEntries = definitions.filter((definition) => definition.steps?.length).flatMap((definition) => {
6400
+ const directory = sourceFilePattern.test(definition.handler) ? dirname(definition.handler) : definition.handler;
5812
6401
  return [
5813
6402
  ` ${JSON.stringify(definition.name)}: {`,
5814
- ...definition.steps.flatMap((step) => {
5815
- const path = relative(dirname(file), step);
5816
- const specifier = path.startsWith(".") ? path : `./${path}`;
5817
- return [.../\.(?:c|m)?js$/i.test(step) ? [" // @ts-ignore JavaScript steps may have no declarations when allowJs is disabled."] : [], ` ${JSON.stringify(toStepPropertyName(relative(directory, step)))}: typeof import(${JSON.stringify(specifier)}).default`];
5818
- }),
6403
+ ...definition.steps.flatMap((step) => [...javaScriptFilePattern.test(step) ? [` ${ignoreJavaScriptTypes}`] : [], ` ${JSON.stringify(toStepPropertyName(relative(directory, step)))}: typeof import(${JSON.stringify(importSpecifier(file, step))}).default`]),
5819
6404
  " }"
5820
6405
  ];
5821
6406
  });
5822
6407
  return [
5823
6408
  `import ${JSON.stringify(importBase)}`,
5824
6409
  `declare module ${JSON.stringify(importBase)} {`,
6410
+ " interface WorkflowRegistry {",
6411
+ ...registryEntries,
6412
+ " }",
5825
6413
  " interface WorkflowStepRegistry {",
5826
- ...entries,
6414
+ ...stepEntries,
5827
6415
  " }",
5828
6416
  "}",
5829
6417
  ""
@@ -5878,14 +6466,13 @@ function readPostgresDefaultDatabase(plugin) {
5878
6466
  const config = plugin.api?.getConfig?.();
5879
6467
  return config ? config.databases.default?.dialect === "postgresql" : void 0;
5880
6468
  }
5881
- function hubWorkflow(options, internalOptions = {}) {
6469
+ function hubWorkflow(workflow, internalOptions = {}) {
5882
6470
  let providerOutput;
5883
6471
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
5884
6472
  const providerOutputEnvironment = createProviderOutputEnvironmentOwner("@vite-hub/workflow/vite");
5885
6473
  let resolved;
5886
- const workflow = internalOptions.implicitlyEnabled && normalizeHosting(internalOptions.hosting).includes("netlify") ? false : options;
5887
6474
  let startupBuild = false;
5888
- const allowsInline = () => !startupBuild || internalOptions.implicitlyEnabled === true;
6475
+ const allowsInline = () => !startupBuild;
5889
6476
  const resolveWorkflow = (workflowOptions) => normalizeWorkflowOptions(workflowOptions, {
5890
6477
  hosting: internalOptions.hosting,
5891
6478
  inline: allowsInline()