@workflow/nitro 5.0.0-beta.6 → 5.0.0-beta.7

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.
@@ -1 +1 @@
1
- {"version":3,"file":"builders.d.ts","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EAEX,2BAA2B,EAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAezC,qBAAa,aAAc,SAAQ,2BAA2B;gBAChD,KAAK,EAAE,KAAK;IAYT,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAWtC;AAED,qBAAa,YAAa,SAAQ,WAAW;;gBAE/B,KAAK,EAAE,KAAK;IAmBf,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAkDhC"}
1
+ {"version":3,"file":"builders.d.ts","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EAEX,2BAA2B,EAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAuBzC,qBAAa,aAAc,SAAQ,2BAA2B;gBAChD,KAAK,EAAE,KAAK;IAYT,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAWtC;AAED,qBAAa,YAAa,SAAQ,WAAW;;gBAE/B,KAAK,EAAE,KAAK;IAmBf,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAkDhC"}
package/dist/builders.js CHANGED
@@ -1,14 +1,11 @@
1
1
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import { BaseBuilder, createBaseBuilderConfig, VercelBuildOutputAPIBuilder, } from '@workflow/builders';
3
3
  import { join } from 'pathe';
4
- /**
5
- * Forward string entries from Nitro's `externals.external` config to the
6
- * workflow builder's esbuild `external` option. RegExp and function entries
7
- * are skipped since esbuild's `external` only supports literal strings.
8
- */
9
4
  function getNitroStringExternals(nitro) {
10
- const externals = nitro.options.externals?.external?.filter((entry) => typeof entry === 'string');
11
- return externals && externals.length > 0 ? externals : undefined;
5
+ const external = nitro.options.externals
6
+ ?.external;
7
+ const strings = external?.filter((entry) => typeof entry === 'string');
8
+ return strings && strings.length > 0 ? strings : undefined;
12
9
  }
13
10
  export class VercelBuilder extends VercelBuildOutputAPIBuilder {
14
11
  constructor(nitro) {
@@ -1 +1 @@
1
- {"version":3,"file":"builders.js","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EACL,WAAW,EACX,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAE7B;;;;GAIG;AACH,SAAS,uBAAuB,CAAC,KAAY;IAC3C,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,EAAE,MAAM,CACzD,CAAC,KAAK,EAAmB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CACtD,CAAC;IACF,OAAO,SAAS,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;AACnE,CAAC;AAED,MAAM,OAAO,aAAc,SAAQ,2BAA2B;IAC5D,YAAY,KAAY;QACtB,KAAK,CAAC;YACJ,GAAG,uBAAuB,CAAC;gBACzB,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO;gBACjC,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,2DAA2D;gBACxE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO;gBACxC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,SAAS;gBAC5C,gBAAgB,EAAE,uBAAuB,CA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YAC1C,MAAM,EAAE,KAAK;SACd,CAAC,CAAC;QAEH,oBAAoB;QACpB,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAC/D,MAAM,IAAI,CAAC,cAAc,CAAC;YACxB,kBAAkB;YAClB,WAAW,EAAE,IAAI,CAAC,OAAO;YACzB,QAAQ;SACT,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport {\n BaseBuilder,\n createBaseBuilderConfig,\n VercelBuildOutputAPIBuilder,\n} from '@workflow/builders';\nimport type { Nitro } from 'nitro/types';\nimport { join } from 'pathe';\n\n/**\n * Forward string entries from Nitro's `externals.external` config to the\n * workflow builder's esbuild `external` option. RegExp and function entries\n * are skipped since esbuild's `external` only supports literal strings.\n */\nfunction getNitroStringExternals(nitro: Nitro): string[] | undefined {\n const externals = nitro.options.externals?.external?.filter(\n (entry): entry is string => typeof entry === 'string'\n );\n return externals && externals.length > 0 ? externals : undefined;\n}\n\nexport class VercelBuilder extends VercelBuildOutputAPIBuilder {\n constructor(nitro: Nitro) {\n super({\n ...createBaseBuilderConfig({\n workingDir: nitro.options.rootDir,\n dirs: ['.'], // Different apps that use nitro have different directories\n runtime: nitro.options.workflow?.runtime,\n sourcemap: nitro.options.workflow?.sourcemap,\n externalPackages: getNitroStringExternals(nitro),\n }),\n buildTarget: 'vercel-build-output-api',\n });\n }\n override async build(): Promise<void> {\n const configPath = join(\n this.config.workingDir,\n '.vercel/output/config.json'\n );\n const originalConfig = JSON.parse(await readFile(configPath, 'utf-8'));\n await super.build();\n const newConfig = JSON.parse(await readFile(configPath, 'utf-8'));\n originalConfig.routes.unshift(...newConfig.routes);\n await writeFile(configPath, JSON.stringify(originalConfig, null, 2));\n }\n}\n\nexport class LocalBuilder extends BaseBuilder {\n #outDir: string;\n constructor(nitro: Nitro) {\n const outDir = join(nitro.options.buildDir, 'workflow');\n super({\n ...createBaseBuilderConfig({\n workingDir: nitro.options.rootDir,\n watch: nitro.options.dev,\n dirs: ['.'], // Different apps that use nitro have different directories\n sourcemap: nitro.options.workflow?.sourcemap,\n externalPackages: getNitroStringExternals(nitro),\n }),\n buildTarget: 'next', // Placeholder, not actually used\n });\n this.#outDir = outDir;\n }\n\n // Serialize concurrent build() calls so overlapping dev rebuilds don't\n // stomp on each other's temp files or partially overwrite output.\n #buildQueue: Promise<void> = Promise.resolve();\n\n override build(): Promise<void> {\n const next = this.#buildQueue.then(\n () => this.#buildOnce(),\n () => this.#buildOnce()\n );\n // Swallow rejections on the queue itself so a failed build doesn't\n // permanently reject all subsequent builds; each caller still sees\n // its own rejection via the returned promise.\n this.#buildQueue = next.catch(() => {});\n return next;\n }\n\n async #buildOnce(): Promise<void> {\n const inputFiles = await this.getInputFiles();\n await mkdir(this.#outDir, { recursive: true });\n\n // V2: The combined bundle's flow route references the steps file by\n // name in its import statement, so we build directly to final names.\n // (The V1 atomic tmp-file pattern doesn't work here because renaming\n // the steps file would leave the flow route's import stale.)\n const { manifest } = await this.createCombinedBundle({\n inputFiles,\n stepsOutfile: join(this.#outDir, 'steps.mjs'),\n flowOutfile: join(this.#outDir, 'workflows.mjs'),\n format: 'esm',\n // bundleFinalOutput: false — Nitro externalizes the workflow build dir\n // during dev, and its own rollup pipeline handles bundling for prod.\n // Using true causes \"Dynamic require of X is not supported\" errors\n // because esbuild wraps CJS require() calls in ESM output.\n bundleFinalOutput: false,\n externalizeNonSteps: true,\n // In dev, Nitro dynamically imports the generated workflow files from\n // disk, so there is no later Rollup pass to resolve externalized local\n // TypeScript imports. In prod, Nitro/Rollup handles those imports.\n bundleTransitiveLocalStepDependencies: this.config.watch,\n });\n\n await this.createWebhookBundle({\n outfile: join(this.#outDir, 'webhook.mjs'),\n bundle: false,\n });\n\n // Generate manifest\n const workflowBundlePath = join(this.#outDir, 'workflows.mjs');\n await this.createManifest({\n workflowBundlePath,\n manifestDir: this.#outDir,\n manifest,\n });\n }\n}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ACT,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport {\n BaseBuilder,\n createBaseBuilderConfig,\n VercelBuildOutputAPIBuilder,\n} from '@workflow/builders';\nimport type { Nitro } from 'nitro/types';\nimport { join } from 'pathe';\n\n/**\n * Forward string entries from Nitro's `externals.external` config to the\n * workflow builder's esbuild `external` option. RegExp and function entries\n * are skipped since esbuild's `external` only supports literal strings.\n *\n * Note: `externals.external` is on Nitro v2's options shape — v3 dropped it\n * in favour of `noExternals`. Reading it through a v2-shaped view lets us\n * still pick it up on v2 setups; on v3 the chained optional access just\n * returns undefined.\n */\ntype NitroV2ExternalsOptions = { externals?: { external?: unknown[] } };\nfunction getNitroStringExternals(nitro: Nitro): string[] | undefined {\n const external = (nitro.options as NitroV2ExternalsOptions).externals\n ?.external;\n const strings = external?.filter(\n (entry): entry is string => typeof entry === 'string'\n );\n return strings && strings.length > 0 ? strings : undefined;\n}\n\nexport class VercelBuilder extends VercelBuildOutputAPIBuilder {\n constructor(nitro: Nitro) {\n super({\n ...createBaseBuilderConfig({\n workingDir: nitro.options.rootDir,\n dirs: ['.'], // Different apps that use nitro have different directories\n runtime: nitro.options.workflow?.runtime,\n sourcemap: nitro.options.workflow?.sourcemap,\n externalPackages: getNitroStringExternals(nitro),\n }),\n buildTarget: 'vercel-build-output-api',\n });\n }\n override async build(): Promise<void> {\n const configPath = join(\n this.config.workingDir,\n '.vercel/output/config.json'\n );\n const originalConfig = JSON.parse(await readFile(configPath, 'utf-8'));\n await super.build();\n const newConfig = JSON.parse(await readFile(configPath, 'utf-8'));\n originalConfig.routes.unshift(...newConfig.routes);\n await writeFile(configPath, JSON.stringify(originalConfig, null, 2));\n }\n}\n\nexport class LocalBuilder extends BaseBuilder {\n #outDir: string;\n constructor(nitro: Nitro) {\n const outDir = join(nitro.options.buildDir, 'workflow');\n super({\n ...createBaseBuilderConfig({\n workingDir: nitro.options.rootDir,\n watch: nitro.options.dev,\n dirs: ['.'], // Different apps that use nitro have different directories\n sourcemap: nitro.options.workflow?.sourcemap,\n externalPackages: getNitroStringExternals(nitro),\n }),\n buildTarget: 'next', // Placeholder, not actually used\n });\n this.#outDir = outDir;\n }\n\n // Serialize concurrent build() calls so overlapping dev rebuilds don't\n // stomp on each other's temp files or partially overwrite output.\n #buildQueue: Promise<void> = Promise.resolve();\n\n override build(): Promise<void> {\n const next = this.#buildQueue.then(\n () => this.#buildOnce(),\n () => this.#buildOnce()\n );\n // Swallow rejections on the queue itself so a failed build doesn't\n // permanently reject all subsequent builds; each caller still sees\n // its own rejection via the returned promise.\n this.#buildQueue = next.catch(() => {});\n return next;\n }\n\n async #buildOnce(): Promise<void> {\n const inputFiles = await this.getInputFiles();\n await mkdir(this.#outDir, { recursive: true });\n\n // V2: The combined bundle's flow route references the steps file by\n // name in its import statement, so we build directly to final names.\n // (The V1 atomic tmp-file pattern doesn't work here because renaming\n // the steps file would leave the flow route's import stale.)\n const { manifest } = await this.createCombinedBundle({\n inputFiles,\n stepsOutfile: join(this.#outDir, 'steps.mjs'),\n flowOutfile: join(this.#outDir, 'workflows.mjs'),\n format: 'esm',\n // bundleFinalOutput: false — Nitro externalizes the workflow build dir\n // during dev, and its own rollup pipeline handles bundling for prod.\n // Using true causes \"Dynamic require of X is not supported\" errors\n // because esbuild wraps CJS require() calls in ESM output.\n bundleFinalOutput: false,\n externalizeNonSteps: true,\n // In dev, Nitro dynamically imports the generated workflow files from\n // disk, so there is no later Rollup pass to resolve externalized local\n // TypeScript imports. In prod, Nitro/Rollup handles those imports.\n bundleTransitiveLocalStepDependencies: this.config.watch,\n });\n\n await this.createWebhookBundle({\n outfile: join(this.#outDir, 'webhook.mjs'),\n bundle: false,\n });\n\n // Generate manifest\n const workflowBundlePath = join(this.#outDir, 'workflows.mjs');\n await this.createManifest({\n workflowBundlePath,\n manifestDir: this.#outDir,\n manifest,\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,KAAK,EAA6B,MAAM,aAAa,CAAC;AAGpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,YAAY,EAAE,aAAa,EAAE,CAAC;;;6BAIT,KAAK;;AAF1B,wBAqMwB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAA6B,MAAM,aAAa,CAAC;AAGpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,YAAY,EAAE,aAAa,EAAE,CAAC;;;6BAoBT,KAAK;;AAF1B,wBAoQwB"}
package/dist/index.js CHANGED
@@ -1,8 +1,24 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { fileURLToPath } from 'node:url';
3
+ import { WORKFLOW_QUEUE_TRIGGER } from '@workflow/builders';
3
4
  import { workflowTransformPlugin } from '@workflow/rollup';
4
5
  import { join } from 'pathe';
5
6
  import { LocalBuilder, VercelBuilder } from './builders.js';
7
+ /**
8
+ * Detect whether the Nitro instance is v2.
9
+ * Newer Nitro releases (both v2 and v3) expose `nitro.meta.majorVersion`.
10
+ * Fall back to `!nitro.routing` (only present in v3+) for older Nitro v2
11
+ * versions that don't have `majorVersion` yet (e.g. Nuxt users on an older
12
+ * nitropack).
13
+ */
14
+ function isNitroV2(nitro) {
15
+ const majorVersion = nitro.meta
16
+ ?.majorVersion;
17
+ if (majorVersion != null) {
18
+ return majorVersion === 2;
19
+ }
20
+ return !nitro.routing;
21
+ }
6
22
  export default {
7
23
  name: 'workflow/nitro',
8
24
  async setup(nitro) {
@@ -61,36 +77,48 @@ export default {
61
77
  nitro.hooks.hook('rollup:before', (_nitro, config) => {
62
78
  config.plugins.unshift({
63
79
  name: 'workflow:force-inline',
64
- async resolveId(source, importer, options) {
65
- if (!importer)
66
- return null;
67
- // Let other plugins resolve first to get the file path
68
- const resolved = await this.resolve(source, importer, {
69
- ...options,
70
- skipSelf: true,
71
- });
72
- if (!resolved)
73
- return null;
74
- if (!resolved.external)
75
- return null;
76
- // Force workflow packages and their internal imports
77
- // to be bundled (not external). We match both the
78
- // package specifier (e.g., `@workflow/core/runtime`)
79
- // and resolved file paths within workflow packages.
80
- const isWorkflowPkg = /^@?workflow(\/|$)/.test(source) ||
81
- /[\\/]packages[\\/](workflow|core|serde|errors|utils|builders|rollup|ai|world|world-local|world-vercel|world-postgres|world-testing|cli|next|nitro|nuxt|vite|vitest|web|web-shared|astro|sveltekit|nest)[\\/]/.test(resolved.id);
82
- if (isWorkflowPkg) {
83
- // Strip file:// protocol if present — Rollup needs
84
- // a plain filesystem path to load the module.
85
- // `fileURLToPath` correctly handles Windows paths
86
- // (e.g., file:///C:/... -> C:\...) and percent-decoding.
80
+ // `order: 'pre'` is required: Nitro's `nitro:externals` plugin
81
+ // uses `order: 'pre'` for its resolveId hook and spreads our
82
+ // resolution result while forcing `external: true`. Without
83
+ // `pre` here, our `external: false` decision gets overwritten
84
+ // and `@workflow/*` imports end up externalized in the dev
85
+ // bundle — which means the SWC-injected `static classId` IIFE
86
+ // in (e.g.) `@workflow/core/dist/runtime/run.js` is never
87
+ // applied, and step return values that include `Run`
88
+ // instances fail to serialize at runtime.
89
+ resolveId: {
90
+ order: 'pre',
91
+ async handler(source, importer, options) {
92
+ if (!importer)
93
+ return null;
94
+ // Match workflow package specifiers OR direct paths into
95
+ // packages/<name>/. Bail out early on non-workflow imports
96
+ // so we don't intercept the rest of the resolution chain.
97
+ const isWorkflowPkg = /^@?workflow(\/|$)/.test(source) ||
98
+ /[\\/]packages[\\/](workflow|core|serde|errors|utils|builders|rollup|ai|world|world-local|world-vercel|world-postgres|world-testing|cli|next|nitro|nuxt|vite|vitest|web|web-shared|astro|sveltekit|nest)[\\/]/.test(source);
99
+ if (!isWorkflowPkg)
100
+ return null;
101
+ // Resolve via other resolvers, skipping ourselves so we
102
+ // get a path. We don't gate on `resolved.external` because
103
+ // `nitro:externals` spreads our result and overrides
104
+ // `external: true` regardless of what we return — we want
105
+ // to win that race by returning first under `order: 'pre'`.
106
+ const resolved = await this.resolve(source, importer, {
107
+ ...options,
108
+ skipSelf: true,
109
+ });
110
+ if (!resolved)
111
+ return null;
87
112
  let resolvedId = resolved.id;
113
+ // Strip file:// protocol if present — Rollup needs a plain
114
+ // filesystem path to load the module. `fileURLToPath`
115
+ // correctly handles Windows paths (e.g., file:///C:/...
116
+ // -> C:\...) and percent-decoding.
88
117
  if (resolvedId.startsWith('file://')) {
89
118
  resolvedId = fileURLToPath(resolvedId);
90
119
  }
91
120
  return { id: resolvedId, external: false };
92
- }
93
- return null;
121
+ },
94
122
  },
95
123
  });
96
124
  });
@@ -104,14 +132,23 @@ export default {
104
132
  name: 'workflow',
105
133
  });
106
134
  }
107
- // Generate functions for vercel build
108
- if (isVercelDeploy) {
135
+ // Nitro v2 Vercel deploy: keep the legacy Build Output API path that
136
+ // builds the workflow functions standalone and stitches the routes into
137
+ // `.vercel/output/config.json`. This path is independent of nitro's own
138
+ // bundle and is only used for nitropack v2 (e.g. Nuxt 4 still uses it).
139
+ const useLegacyVercelBuild = isVercelDeploy && isNitroV2(nitro);
140
+ if (useLegacyVercelBuild) {
109
141
  nitro.hooks.hook('compiled', async () => {
110
142
  await new VercelBuilder(nitro).build();
111
143
  });
112
144
  }
113
- // Generate local bundles for dev and local prod
114
- if (!isVercelDeploy) {
145
+ // Local dev/prod and Nitro v3 Vercel deploy share the same path:
146
+ // bundle the workflow routes into nitro itself via virtual handlers.
147
+ // For Vercel v3 we additionally configure `functionRules` so the
148
+ // routes get queue triggers + extended maxDuration via the nitro
149
+ // vercel preset. This lets workflow handlers use nitro features
150
+ // (storage, database, runtime config, virtual imports, etc.).
151
+ if (!useLegacyVercelBuild) {
115
152
  const builder = new LocalBuilder(nitro);
116
153
  let isInitialBuild = true;
117
154
  nitro.hooks.hook('build:before', async () => {
@@ -148,6 +185,42 @@ export default {
148
185
  // The step registrations are imported as side effects by the combined
149
186
  // handler — no separate step route needed.
150
187
  addVirtualHandler(nitro, '/.well-known/workflow/v1/flow', 'workflow/workflows.mjs');
188
+ // Nitro v3+ Vercel deploy: configure function rules for the combined
189
+ // flow handler so it gets the queue triggers + max duration that the
190
+ // workflow runtime needs. Workflow-required fields (`maxDuration`,
191
+ // `experimentalTriggers`, `runtime` when set) take precedence over
192
+ // user-provided values for these routes; unrelated fields the user
193
+ // sets (e.g. `memory`) pass through untouched.
194
+ //
195
+ // Pattern keys must match the route patterns the handlers are
196
+ // registered with so nitro reuses the same function directory.
197
+ // Using a `webhook/**` catch-all here would create a second
198
+ // `webhook/[...].func` next to the `webhook/[token].func` that
199
+ // `addVirtualHandler` produces.
200
+ if (isVercelDeploy) {
201
+ nitro.options.vercel ??= {};
202
+ nitro.options.vercel.functionRules ??= {};
203
+ const runtime = nitro.options.workflow?.runtime;
204
+ const rules = nitro.options.vercel.functionRules;
205
+ const flowPath = '/.well-known/workflow/v1/flow';
206
+ rules[flowPath] = {
207
+ ...rules[flowPath],
208
+ ...(runtime && { runtime }),
209
+ maxDuration: 'max',
210
+ // V2 combined: a single trigger covers both `__wkf_workflow_*`
211
+ // (workflow orchestration) and `__wkf_step_*` (step execution),
212
+ // since the same handler dispatches both.
213
+ experimentalTriggers: [WORKFLOW_QUEUE_TRIGGER],
214
+ };
215
+ if (runtime) {
216
+ const webhookPath = '/.well-known/workflow/v1/webhook/:token';
217
+ rules[webhookPath] = { ...rules[webhookPath], runtime };
218
+ if (process.env.WORKFLOW_PUBLIC_MANIFEST === '1') {
219
+ const manifestPath = '/.well-known/workflow/v1/manifest.json';
220
+ rules[manifestPath] = { ...rules[manifestPath], runtime };
221
+ }
222
+ }
223
+ }
151
224
  // Expose manifest as a public HTTP route when WORKFLOW_PUBLIC_MANIFEST=1
152
225
  if (process.env.WORKFLOW_PUBLIC_MANIFEST === '1') {
153
226
  // Write a placeholder manifest-data.mjs so rollup can resolve the
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAK5D,eAAe;IACb,IAAI,EAAE,gBAAgB;IACtB,KAAK,CAAC,KAAK,CAAC,KAAY;QACtB,MAAM,cAAc,GAClB,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC;QAE1D,iFAAiF;QACjF,MAAM,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;QAElE,uEAAuE;QACvE,oFAAoF;QACpF,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,MAAa,EAAE,MAAoB,EAAE,EAAE;YACvE,MAAM,CAAC,OAA0B,CAAC,OAAO,CACxC,uBAAuB,CAAC;gBACtB,4DAA4D;gBAC5D,mEAAmE;gBACnE,oEAAoE;gBACpE,OAAO,EAAE,CAAC,gBAAgB,CAAC;aAC5B,CAAC,CACH,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,kDAAkD;QAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC;YACnC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC;QAC3C,CAAC;QAED,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,EAA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C,MAAM,WAAW,GAAG,CAAC,KAAK,CAAC,OAAO;YAChC,CAAC,CAAC;mBACW,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC;;;;CAIjD;YACK,CAAC,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC;;;;CAI1D,CAAC;QACE,aAAa,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QACP,+BAA+B;QAC/B,MAAM,QAAQ,GAAG,CAAC,KAAK,CAAC,OAAO;YAC7B,CAAC,CAAC;;CAEP;YACK,CAAC,CAAC;CACP,CAAC;QACE,aAAa,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;IACvC,CAAC;AACH,CAAC","sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { workflowTransformPlugin } from '@workflow/rollup';\nimport type { Nitro, NitroModule, RollupConfig } from 'nitro/types';\nimport { join } from 'pathe';\nimport { LocalBuilder, VercelBuilder } from './builders.js';\nimport type { ModuleOptions } from './types';\n\nexport type { ModuleOptions };\n\nexport default {\n name: 'workflow/nitro',\n async setup(nitro: Nitro) {\n const isVercelDeploy =\n !nitro.options.dev && nitro.options.preset === 'vercel';\n\n // Pre-built workflow bundles directory - must be excluded from re-transformation\n const workflowBuildDir = join(nitro.options.buildDir, 'workflow');\n\n // Add transform plugin at the BEGINNING to run before other transforms\n // (especially before class property transforms that rename classes like _ClassName)\n nitro.hooks.hook('rollup:before', (_nitro: Nitro, config: RollupConfig) => {\n (config.plugins as Array<unknown>).unshift(\n workflowTransformPlugin({\n // Exclude pre-built workflow bundles from re-transformation\n // These are already processed and re-processing causes issues like\n // undefined class references when Nitro's bundler renames variables\n exclude: [workflowBuildDir],\n })\n );\n });\n\n // NOTE: Temporary workaround for debug unenv mock\n if (!nitro.options.workflow?._vite) {\n nitro.options.alias['debug'] ??= 'debug';\n }\n\n if (nitro.options.dev) {\n const workflowBuildGlob = `${join(nitro.options.buildDir, 'workflow')}/**`;\n nitro.options.watchOptions ||= {};\n const existingIgnored = nitro.options.watchOptions.ignored;\n if (!existingIgnored) {\n nitro.options.watchOptions.ignored = [workflowBuildGlob];\n } else if (Array.isArray(existingIgnored)) {\n nitro.options.watchOptions.ignored = [\n ...existingIgnored,\n workflowBuildGlob,\n ];\n } else {\n nitro.options.watchOptions.ignored = [\n existingIgnored,\n workflowBuildGlob,\n ];\n }\n }\n\n // In dev mode, force workflow SDK packages to be bundled by Nitro's\n // Rollup rather than externalized. This ensures the SWC transform\n // plugin processes files containing workflow patterns (like\n // @workflow/core/dist/runtime/run.js) and adds the classId\n // registration IIFEs needed for serialization. Without this, serde\n // classes from npm packages (like `Run`) would be externalized, the\n // SWC transform would never fire on them, and serialization would\n // fail with \"must have a static classId property\".\n //\n // We use a Rollup resolveId hook (added BEFORE the externalization\n // plugin) that intercepts workflow package imports and marks them\n // as non-external. This is more targeted than `noExternals = true`\n // which would bundle ALL dependencies and cause TDZ errors from\n // circular imports in packages like vue-bundle-renderer/h3.\n if (nitro.options.dev) {\n nitro.hooks.hook(\n 'rollup:before',\n (_nitro: Nitro, config: RollupConfig) => {\n (config.plugins as Array<unknown>).unshift({\n name: 'workflow:force-inline',\n async resolveId(\n this: { resolve: Function },\n source: string,\n importer: string | undefined,\n options: { skipSelf?: boolean }\n ) {\n if (!importer) return null;\n // Let other plugins resolve first to get the file path\n const resolved = await this.resolve(source, importer, {\n ...options,\n skipSelf: true,\n });\n if (!resolved) return null;\n if (!resolved.external) return null;\n // Force workflow packages and their internal imports\n // to be bundled (not external). We match both the\n // package specifier (e.g., `@workflow/core/runtime`)\n // and resolved file paths within workflow packages.\n const isWorkflowPkg =\n /^@?workflow(\\/|$)/.test(source) ||\n /[\\\\/]packages[\\\\/](workflow|core|serde|errors|utils|builders|rollup|ai|world|world-local|world-vercel|world-postgres|world-testing|cli|next|nitro|nuxt|vite|vitest|web|web-shared|astro|sveltekit|nest)[\\\\/]/.test(\n resolved.id\n );\n if (isWorkflowPkg) {\n // Strip file:// protocol if present — Rollup needs\n // a plain filesystem path to load the module.\n // `fileURLToPath` correctly handles Windows paths\n // (e.g., file:///C:/... -> C:\\...) and percent-decoding.\n let resolvedId = resolved.id;\n if (resolvedId.startsWith('file://')) {\n resolvedId = fileURLToPath(resolvedId);\n }\n return { id: resolvedId, external: false };\n }\n return null;\n },\n });\n }\n );\n }\n\n // Add tsConfig plugin\n if (nitro.options.workflow?.typescriptPlugin) {\n nitro.options.typescript.tsConfig ||= {};\n nitro.options.typescript.tsConfig.compilerOptions ||= {};\n nitro.options.typescript.tsConfig.compilerOptions.plugins ||= [];\n nitro.options.typescript.tsConfig.compilerOptions.plugins.push({\n name: 'workflow',\n });\n }\n\n // Generate functions for vercel build\n if (isVercelDeploy) {\n nitro.hooks.hook('compiled', async () => {\n await new VercelBuilder(nitro).build();\n });\n }\n\n // Generate local bundles for dev and local prod\n if (!isVercelDeploy) {\n const builder = new LocalBuilder(nitro);\n let isInitialBuild = true;\n\n nitro.hooks.hook('build:before', async () => {\n await builder.build();\n\n // For prod: write the manifest handler file with inlined content\n // now that the builder has generated the manifest. Rollup will\n // bundle this file into the compiled output.\n if (\n !nitro.options.dev &&\n process.env.WORKFLOW_PUBLIC_MANIFEST === '1'\n ) {\n writeManifestHandler(nitro);\n }\n });\n\n // Allows for HMR - but skip the first dev:reload since build:before already ran\n if (nitro.options.dev) {\n nitro.hooks.hook('dev:reload', async () => {\n if (isInitialBuild) {\n isInitialBuild = false;\n return;\n }\n try {\n await builder.build();\n } catch (error) {\n // During dev, files may be added/removed while the builder\n // is rebuilding (e.g., during test cleanup). Log the error\n // but don't crash — the next file change will trigger\n // another rebuild with the correct file list.\n console.warn('Warning: Workflow rebuild failed:', error);\n }\n });\n }\n\n addVirtualHandler(\n nitro,\n '/.well-known/workflow/v1/webhook/:token',\n 'workflow/webhook.mjs'\n );\n\n // V2: single combined handler for both workflow and step execution.\n // The step registrations are imported as side effects by the combined\n // handler — no separate step route needed.\n addVirtualHandler(\n nitro,\n '/.well-known/workflow/v1/flow',\n 'workflow/workflows.mjs'\n );\n\n // Expose manifest as a public HTTP route when WORKFLOW_PUBLIC_MANIFEST=1\n if (process.env.WORKFLOW_PUBLIC_MANIFEST === '1') {\n // Write a placeholder manifest-data.mjs so rollup can resolve the\n // import. It will be overwritten with the real manifest in build:before.\n // Write a placeholder handler file so rollup can resolve the path\n // during prod compilation. It will be overwritten with the real\n // manifest content by writeManifestHandler() in build:before.\n if (!nitro.options.dev) {\n const dir = join(nitro.options.buildDir, 'workflow');\n mkdirSync(dir, { recursive: true });\n const handlerPath = join(dir, 'manifest-handler.mjs');\n writeFileSync(\n handlerPath,\n 'export default async () => new Response(\"Manifest not found\", { status: 404 });\\n'\n );\n }\n addManifestHandler(nitro);\n }\n }\n },\n} satisfies NitroModule;\n\nfunction addVirtualHandler(nitro: Nitro, route: string, buildPath: string) {\n nitro.options.handlers.push({\n route,\n handler: `#${buildPath}`,\n });\n const handlerImportPath = JSON.stringify(\n join(nitro.options.buildDir, buildPath)\n );\n\n if (nitro.options.dev) {\n // Dev mode: load generated workflow bundles from disk at request time.\n // This keeps `.nitro/workflow/*.mjs` out of Nitro's own bundle graph,\n // which avoids rebuild loops and stale dependency graphs during HMR.\n // Cache-bust by file mtime so each successful rebuild loads fresh code.\n if (!nitro.routing) {\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import { fromWebHandler } from \"h3\";\n import { statSync } from \"node:fs\";\n import { pathToFileURL } from \"node:url\";\n\n const handlerPath = ${handlerImportPath};\n let currentVersion = \"\";\n let currentImportPath = \"\";\n\n async function loadPOST() {\n const version = String(statSync(handlerPath).mtimeMs);\n if (version !== currentVersion) {\n currentVersion = version;\n currentImportPath = pathToFileURL(handlerPath).href + \"?t=\" + version;\n }\n return (await import(currentImportPath)).POST;\n }\n\n export default fromWebHandler(async (request, context) => {\n const POST = await loadPOST();\n return POST(request, context);\n });\n `;\n } else {\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import { statSync } from \"node:fs\";\n import { pathToFileURL } from \"node:url\";\n\n const handlerPath = ${handlerImportPath};\n let currentVersion = \"\";\n let currentImportPath = \"\";\n\n async function loadPOST() {\n const version = String(statSync(handlerPath).mtimeMs);\n if (version !== currentVersion) {\n currentVersion = version;\n currentImportPath = pathToFileURL(handlerPath).href + \"?t=\" + version;\n }\n return (await import(currentImportPath)).POST;\n }\n\n export default async ({ req }) => {\n try {\n const POST = await loadPOST();\n return await POST(req);\n } catch (error) {\n console.error('Handler error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n `;\n }\n return;\n }\n\n // Keep a bare import alongside `POST`: in Nuxt + Nitro production builds\n // using `@workflow/nuxt`, importing only `POST` could drop the generated\n // step bundle's top-level registrations, so the handler loaded but steps\n // were missing at runtime.\n\n if (!nitro.routing) {\n // Nitro v2 (legacy)\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import ${handlerImportPath};\n import { fromWebHandler } from \"h3\";\n import { POST } from ${handlerImportPath};\n export default fromWebHandler(POST);\n `;\n } else {\n // Nitro v3+ (native web handlers)\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import ${handlerImportPath};\n import { POST } from ${handlerImportPath};\n export default async ({ req }) => {\n try {\n return await POST(req);\n } catch (error) {\n console.error('Handler error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n `;\n }\n}\n\nconst MANIFEST_VIRTUAL_ID = '#workflow/manifest-handler';\n\nfunction addManifestHandler(nitro: Nitro) {\n const route = '/.well-known/workflow/v1/manifest.json';\n const manifestPath = join(nitro.options.buildDir, 'workflow/manifest.json');\n const handlerPath = join(\n nitro.options.buildDir,\n 'workflow/manifest-handler.mjs'\n );\n\n if (nitro.options.dev) {\n // Dev mode: use a virtual handler that reads the manifest from disk at\n // request time. The absolute path is valid because we're on the build machine.\n nitro.options.handlers.push({ route, handler: MANIFEST_VIRTUAL_ID });\n nitro.options.virtual[MANIFEST_VIRTUAL_ID] = !nitro.routing\n ? /* js */ `\n import { fromWebHandler } from \"h3\";\n import { readFileSync } from \"node:fs\";\n function GET() {\n try {\n const manifest = readFileSync(${JSON.stringify(manifestPath)}, \"utf-8\");\n return new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n });\n } catch {\n return new Response(\"Manifest not found\", { status: 404 });\n }\n }\n export default fromWebHandler(GET);\n `\n : /* js */ `\n import { readFileSync } from \"node:fs\";\n export default async () => {\n try {\n const manifest = readFileSync(${JSON.stringify(manifestPath)}, \"utf-8\");\n return new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n });\n } catch {\n return new Response(\"Manifest not found\", { status: 404 });\n }\n };\n `;\n } else {\n // Prod mode: register a physical handler file that will be written by\n // writeManifestHandler() after the builder generates the manifest.\n // This file is bundled by rollup into the compiled output.\n nitro.options.handlers.push({ route, handler: handlerPath });\n }\n}\n\n/**\n * Writes a physical manifest handler file with the manifest content inlined.\n * Must be called after the builder generates the manifest (during build:before)\n * and before Nitro compiles the bundle with rollup.\n */\nfunction writeManifestHandler(nitro: Nitro) {\n const manifestPath = join(nitro.options.buildDir, 'workflow/manifest.json');\n const handlerPath = join(\n nitro.options.buildDir,\n 'workflow/manifest-handler.mjs'\n );\n const dir = join(nitro.options.buildDir, 'workflow');\n mkdirSync(dir, { recursive: true });\n\n try {\n const manifestContent = readFileSync(manifestPath, 'utf-8');\n JSON.parse(manifestContent); // validate\n\n const handlerCode = !nitro.routing\n ? `import { fromWebHandler } from \"h3\";\nconst manifest = ${JSON.stringify(manifestContent)};\nexport default fromWebHandler(() => new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n}));\n`\n : `const manifest = ${JSON.stringify(manifestContent)};\nexport default async () => new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n});\n`;\n writeFileSync(handlerPath, handlerCode);\n } catch {\n // Write a 404 fallback handler\n const fallback = !nitro.routing\n ? `import { fromWebHandler } from \"h3\";\nexport default fromWebHandler(() => new Response(\"Manifest not found\", { status: 404 }));\n`\n : `export default async () => new Response(\"Manifest not found\", { status: 404 });\n`;\n writeFileSync(handlerPath, fallback);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAK5D;;;;;;GAMG;AACH,SAAS,SAAS,CAAC,KAAY;IAC7B,MAAM,YAAY,GAAI,KAA8C,CAAC,IAAI;QACvE,EAAE,YAAY,CAAC;IACjB,IAAI,YAAY,IAAI,IAAI,EAAE,CAAC;QACzB,OAAO,YAAY,KAAK,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;AACxB,CAAC;AAED,eAAe;IACb,IAAI,EAAE,gBAAgB;IACtB,KAAK,CAAC,KAAK,CAAC,KAAY;QACtB,MAAM,cAAc,GAClB,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC;QAE1D,iFAAiF;QACjF,MAAM,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;QAElE,uEAAuE;QACvE,oFAAoF;QACpF,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,MAAa,EAAE,MAAoB,EAAE,EAAE;YACvE,MAAM,CAAC,OAA0B,CAAC,OAAO,CACxC,uBAAuB,CAAC;gBACt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flow/builders';\nimport { workflowTransformPlugin } from '@workflow/rollup';\nimport type { Nitro, NitroModule, RollupConfig } from 'nitro/types';\nimport { join } from 'pathe';\nimport { LocalBuilder, VercelBuilder } from './builders.js';\nimport type { ModuleOptions } from './types';\n\nexport type { ModuleOptions };\n\n/**\n * Detect whether the Nitro instance is v2.\n * Newer Nitro releases (both v2 and v3) expose `nitro.meta.majorVersion`.\n * Fall back to `!nitro.routing` (only present in v3+) for older Nitro v2\n * versions that don't have `majorVersion` yet (e.g. Nuxt users on an older\n * nitropack).\n */\nfunction isNitroV2(nitro: Nitro): boolean {\n const majorVersion = (nitro as { meta?: { majorVersion?: number } }).meta\n ?.majorVersion;\n if (majorVersion != null) {\n return majorVersion === 2;\n }\n return !nitro.routing;\n}\n\nexport default {\n name: 'workflow/nitro',\n async setup(nitro: Nitro) {\n const isVercelDeploy =\n !nitro.options.dev && nitro.options.preset === 'vercel';\n\n // Pre-built workflow bundles directory - must be excluded from re-transformation\n const workflowBuildDir = join(nitro.options.buildDir, 'workflow');\n\n // Add transform plugin at the BEGINNING to run before other transforms\n // (especially before class property transforms that rename classes like _ClassName)\n nitro.hooks.hook('rollup:before', (_nitro: Nitro, config: RollupConfig) => {\n (config.plugins as Array<unknown>).unshift(\n workflowTransformPlugin({\n // Exclude pre-built workflow bundles from re-transformation\n // These are already processed and re-processing causes issues like\n // undefined class references when Nitro's bundler renames variables\n exclude: [workflowBuildDir],\n })\n );\n });\n\n // NOTE: Temporary workaround for debug unenv mock\n if (!nitro.options.workflow?._vite) {\n nitro.options.alias['debug'] ??= 'debug';\n }\n\n if (nitro.options.dev) {\n const workflowBuildGlob = `${join(nitro.options.buildDir, 'workflow')}/**`;\n nitro.options.watchOptions ||= {};\n const existingIgnored = nitro.options.watchOptions.ignored;\n if (!existingIgnored) {\n nitro.options.watchOptions.ignored = [workflowBuildGlob];\n } else if (Array.isArray(existingIgnored)) {\n nitro.options.watchOptions.ignored = [\n ...existingIgnored,\n workflowBuildGlob,\n ];\n } else {\n nitro.options.watchOptions.ignored = [\n existingIgnored,\n workflowBuildGlob,\n ];\n }\n }\n\n // In dev mode, force workflow SDK packages to be bundled by Nitro's\n // Rollup rather than externalized. This ensures the SWC transform\n // plugin processes files containing workflow patterns (like\n // @workflow/core/dist/runtime/run.js) and adds the classId\n // registration IIFEs needed for serialization. Without this, serde\n // classes from npm packages (like `Run`) would be externalized, the\n // SWC transform would never fire on them, and serialization would\n // fail with \"must have a static classId property\".\n //\n // We use a Rollup resolveId hook (added BEFORE the externalization\n // plugin) that intercepts workflow package imports and marks them\n // as non-external. This is more targeted than `noExternals = true`\n // which would bundle ALL dependencies and cause TDZ errors from\n // circular imports in packages like vue-bundle-renderer/h3.\n if (nitro.options.dev) {\n nitro.hooks.hook(\n 'rollup:before',\n (_nitro: Nitro, config: RollupConfig) => {\n (config.plugins as Array<unknown>).unshift({\n name: 'workflow:force-inline',\n // `order: 'pre'` is required: Nitro's `nitro:externals` plugin\n // uses `order: 'pre'` for its resolveId hook and spreads our\n // resolution result while forcing `external: true`. Without\n // `pre` here, our `external: false` decision gets overwritten\n // and `@workflow/*` imports end up externalized in the dev\n // bundle — which means the SWC-injected `static classId` IIFE\n // in (e.g.) `@workflow/core/dist/runtime/run.js` is never\n // applied, and step return values that include `Run`\n // instances fail to serialize at runtime.\n resolveId: {\n order: 'pre',\n async handler(\n this: { resolve: Function },\n source: string,\n importer: string | undefined,\n options: { skipSelf?: boolean }\n ) {\n if (!importer) return null;\n // Match workflow package specifiers OR direct paths into\n // packages/<name>/. Bail out early on non-workflow imports\n // so we don't intercept the rest of the resolution chain.\n const isWorkflowPkg =\n /^@?workflow(\\/|$)/.test(source) ||\n /[\\\\/]packages[\\\\/](workflow|core|serde|errors|utils|builders|rollup|ai|world|world-local|world-vercel|world-postgres|world-testing|cli|next|nitro|nuxt|vite|vitest|web|web-shared|astro|sveltekit|nest)[\\\\/]/.test(\n source\n );\n if (!isWorkflowPkg) return null;\n // Resolve via other resolvers, skipping ourselves so we\n // get a path. We don't gate on `resolved.external` because\n // `nitro:externals` spreads our result and overrides\n // `external: true` regardless of what we return — we want\n // to win that race by returning first under `order: 'pre'`.\n const resolved = await this.resolve(source, importer, {\n ...options,\n skipSelf: true,\n });\n if (!resolved) return null;\n let resolvedId = resolved.id;\n // Strip file:// protocol if present — Rollup needs a plain\n // filesystem path to load the module. `fileURLToPath`\n // correctly handles Windows paths (e.g., file:///C:/...\n // -> C:\\...) and percent-decoding.\n if (resolvedId.startsWith('file://')) {\n resolvedId = fileURLToPath(resolvedId);\n }\n return { id: resolvedId, external: false };\n },\n },\n });\n }\n );\n }\n\n // Add tsConfig plugin\n if (nitro.options.workflow?.typescriptPlugin) {\n nitro.options.typescript.tsConfig ||= {};\n nitro.options.typescript.tsConfig.compilerOptions ||= {};\n nitro.options.typescript.tsConfig.compilerOptions.plugins ||= [];\n nitro.options.typescript.tsConfig.compilerOptions.plugins.push({\n name: 'workflow',\n });\n }\n\n // Nitro v2 Vercel deploy: keep the legacy Build Output API path that\n // builds the workflow functions standalone and stitches the routes into\n // `.vercel/output/config.json`. This path is independent of nitro's own\n // bundle and is only used for nitropack v2 (e.g. Nuxt 4 still uses it).\n const useLegacyVercelBuild = isVercelDeploy && isNitroV2(nitro);\n\n if (useLegacyVercelBuild) {\n nitro.hooks.hook('compiled', async () => {\n await new VercelBuilder(nitro).build();\n });\n }\n\n // Local dev/prod and Nitro v3 Vercel deploy share the same path:\n // bundle the workflow routes into nitro itself via virtual handlers.\n // For Vercel v3 we additionally configure `functionRules` so the\n // routes get queue triggers + extended maxDuration via the nitro\n // vercel preset. This lets workflow handlers use nitro features\n // (storage, database, runtime config, virtual imports, etc.).\n if (!useLegacyVercelBuild) {\n const builder = new LocalBuilder(nitro);\n let isInitialBuild = true;\n\n nitro.hooks.hook('build:before', async () => {\n await builder.build();\n\n // For prod: write the manifest handler file with inlined content\n // now that the builder has generated the manifest. Rollup will\n // bundle this file into the compiled output.\n if (\n !nitro.options.dev &&\n process.env.WORKFLOW_PUBLIC_MANIFEST === '1'\n ) {\n writeManifestHandler(nitro);\n }\n });\n\n // Allows for HMR - but skip the first dev:reload since build:before already ran\n if (nitro.options.dev) {\n nitro.hooks.hook('dev:reload', async () => {\n if (isInitialBuild) {\n isInitialBuild = false;\n return;\n }\n try {\n await builder.build();\n } catch (error) {\n // During dev, files may be added/removed while the builder\n // is rebuilding (e.g., during test cleanup). Log the error\n // but don't crash — the next file change will trigger\n // another rebuild with the correct file list.\n console.warn('Warning: Workflow rebuild failed:', error);\n }\n });\n }\n\n addVirtualHandler(\n nitro,\n '/.well-known/workflow/v1/webhook/:token',\n 'workflow/webhook.mjs'\n );\n\n // V2: single combined handler for both workflow and step execution.\n // The step registrations are imported as side effects by the combined\n // handler — no separate step route needed.\n addVirtualHandler(\n nitro,\n '/.well-known/workflow/v1/flow',\n 'workflow/workflows.mjs'\n );\n\n // Nitro v3+ Vercel deploy: configure function rules for the combined\n // flow handler so it gets the queue triggers + max duration that the\n // workflow runtime needs. Workflow-required fields (`maxDuration`,\n // `experimentalTriggers`, `runtime` when set) take precedence over\n // user-provided values for these routes; unrelated fields the user\n // sets (e.g. `memory`) pass through untouched.\n //\n // Pattern keys must match the route patterns the handlers are\n // registered with so nitro reuses the same function directory.\n // Using a `webhook/**` catch-all here would create a second\n // `webhook/[...].func` next to the `webhook/[token].func` that\n // `addVirtualHandler` produces.\n if (isVercelDeploy) {\n nitro.options.vercel ??= {};\n nitro.options.vercel.functionRules ??= {};\n\n const runtime = nitro.options.workflow?.runtime;\n const rules = nitro.options.vercel.functionRules;\n\n const flowPath = '/.well-known/workflow/v1/flow';\n rules[flowPath] = {\n ...rules[flowPath],\n ...(runtime && { runtime }),\n maxDuration: 'max',\n // V2 combined: a single trigger covers both `__wkf_workflow_*`\n // (workflow orchestration) and `__wkf_step_*` (step execution),\n // since the same handler dispatches both.\n experimentalTriggers: [WORKFLOW_QUEUE_TRIGGER],\n };\n\n if (runtime) {\n const webhookPath = '/.well-known/workflow/v1/webhook/:token';\n rules[webhookPath] = { ...rules[webhookPath], runtime };\n\n if (process.env.WORKFLOW_PUBLIC_MANIFEST === '1') {\n const manifestPath = '/.well-known/workflow/v1/manifest.json';\n rules[manifestPath] = { ...rules[manifestPath], runtime };\n }\n }\n }\n\n // Expose manifest as a public HTTP route when WORKFLOW_PUBLIC_MANIFEST=1\n if (process.env.WORKFLOW_PUBLIC_MANIFEST === '1') {\n // Write a placeholder manifest-data.mjs so rollup can resolve the\n // import. It will be overwritten with the real manifest in build:before.\n // Write a placeholder handler file so rollup can resolve the path\n // during prod compilation. It will be overwritten with the real\n // manifest content by writeManifestHandler() in build:before.\n if (!nitro.options.dev) {\n const dir = join(nitro.options.buildDir, 'workflow');\n mkdirSync(dir, { recursive: true });\n const handlerPath = join(dir, 'manifest-handler.mjs');\n writeFileSync(\n handlerPath,\n 'export default async () => new Response(\"Manifest not found\", { status: 404 });\\n'\n );\n }\n addManifestHandler(nitro);\n }\n }\n },\n} satisfies NitroModule;\n\nfunction addVirtualHandler(nitro: Nitro, route: string, buildPath: string) {\n nitro.options.handlers.push({\n route,\n handler: `#${buildPath}`,\n });\n const handlerImportPath = JSON.stringify(\n join(nitro.options.buildDir, buildPath)\n );\n\n if (nitro.options.dev) {\n // Dev mode: load generated workflow bundles from disk at request time.\n // This keeps `.nitro/workflow/*.mjs` out of Nitro's own bundle graph,\n // which avoids rebuild loops and stale dependency graphs during HMR.\n // Cache-bust by file mtime so each successful rebuild loads fresh code.\n if (!nitro.routing) {\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import { fromWebHandler } from \"h3\";\n import { statSync } from \"node:fs\";\n import { pathToFileURL } from \"node:url\";\n\n const handlerPath = ${handlerImportPath};\n let currentVersion = \"\";\n let currentImportPath = \"\";\n\n async function loadPOST() {\n const version = String(statSync(handlerPath).mtimeMs);\n if (version !== currentVersion) {\n currentVersion = version;\n currentImportPath = pathToFileURL(handlerPath).href + \"?t=\" + version;\n }\n return (await import(currentImportPath)).POST;\n }\n\n export default fromWebHandler(async (request, context) => {\n const POST = await loadPOST();\n return POST(request, context);\n });\n `;\n } else {\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import { statSync } from \"node:fs\";\n import { pathToFileURL } from \"node:url\";\n\n const handlerPath = ${handlerImportPath};\n let currentVersion = \"\";\n let currentImportPath = \"\";\n\n async function loadPOST() {\n const version = String(statSync(handlerPath).mtimeMs);\n if (version !== currentVersion) {\n currentVersion = version;\n currentImportPath = pathToFileURL(handlerPath).href + \"?t=\" + version;\n }\n return (await import(currentImportPath)).POST;\n }\n\n export default async ({ req }) => {\n try {\n const POST = await loadPOST();\n return await POST(req);\n } catch (error) {\n console.error('Handler error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n `;\n }\n return;\n }\n\n // Keep a bare import alongside `POST`: in Nuxt + Nitro production builds\n // using `@workflow/nuxt`, importing only `POST` could drop the generated\n // step bundle's top-level registrations, so the handler loaded but steps\n // were missing at runtime.\n\n if (!nitro.routing) {\n // Nitro v2 (legacy)\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import ${handlerImportPath};\n import { fromWebHandler } from \"h3\";\n import { POST } from ${handlerImportPath};\n export default fromWebHandler(POST);\n `;\n } else {\n // Nitro v3+ (native web handlers)\n nitro.options.virtual[`#${buildPath}`] = /* js */ `\n import ${handlerImportPath};\n import { POST } from ${handlerImportPath};\n export default async ({ req }) => {\n try {\n return await POST(req);\n } catch (error) {\n console.error('Handler error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n `;\n }\n}\n\nconst MANIFEST_VIRTUAL_ID = '#workflow/manifest-handler';\n\nfunction addManifestHandler(nitro: Nitro) {\n const route = '/.well-known/workflow/v1/manifest.json';\n const manifestPath = join(nitro.options.buildDir, 'workflow/manifest.json');\n const handlerPath = join(\n nitro.options.buildDir,\n 'workflow/manifest-handler.mjs'\n );\n\n if (nitro.options.dev) {\n // Dev mode: use a virtual handler that reads the manifest from disk at\n // request time. The absolute path is valid because we're on the build machine.\n nitro.options.handlers.push({ route, handler: MANIFEST_VIRTUAL_ID });\n nitro.options.virtual[MANIFEST_VIRTUAL_ID] = !nitro.routing\n ? /* js */ `\n import { fromWebHandler } from \"h3\";\n import { readFileSync } from \"node:fs\";\n function GET() {\n try {\n const manifest = readFileSync(${JSON.stringify(manifestPath)}, \"utf-8\");\n return new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n });\n } catch {\n return new Response(\"Manifest not found\", { status: 404 });\n }\n }\n export default fromWebHandler(GET);\n `\n : /* js */ `\n import { readFileSync } from \"node:fs\";\n export default async () => {\n try {\n const manifest = readFileSync(${JSON.stringify(manifestPath)}, \"utf-8\");\n return new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n });\n } catch {\n return new Response(\"Manifest not found\", { status: 404 });\n }\n };\n `;\n } else {\n // Prod mode: register a physical handler file that will be written by\n // writeManifestHandler() after the builder generates the manifest.\n // This file is bundled by rollup into the compiled output.\n nitro.options.handlers.push({ route, handler: handlerPath });\n }\n}\n\n/**\n * Writes a physical manifest handler file with the manifest content inlined.\n * Must be called after the builder generates the manifest (during build:before)\n * and before Nitro compiles the bundle with rollup.\n */\nfunction writeManifestHandler(nitro: Nitro) {\n const manifestPath = join(nitro.options.buildDir, 'workflow/manifest.json');\n const handlerPath = join(\n nitro.options.buildDir,\n 'workflow/manifest-handler.mjs'\n );\n const dir = join(nitro.options.buildDir, 'workflow');\n mkdirSync(dir, { recursive: true });\n\n try {\n const manifestContent = readFileSync(manifestPath, 'utf-8');\n JSON.parse(manifestContent); // validate\n\n const handlerCode = !nitro.routing\n ? `import { fromWebHandler } from \"h3\";\nconst manifest = ${JSON.stringify(manifestContent)};\nexport default fromWebHandler(() => new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n}));\n`\n : `const manifest = ${JSON.stringify(manifestContent)};\nexport default async () => new Response(manifest, {\n headers: { \"content-type\": \"application/json\" },\n});\n`;\n writeFileSync(handlerPath, handlerCode);\n } catch {\n // Write a 404 fallback handler\n const fallback = !nitro.routing\n ? `import { fromWebHandler } from \"h3\";\nexport default fromWebHandler(() => new Response(\"Manifest not found\", { status: 404 }));\n`\n : `export default async () => new Response(\"Manifest not found\", { status: 404 });\n`;\n writeFileSync(handlerPath, fallback);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workflow/nitro",
3
- "version": "5.0.0-beta.6",
3
+ "version": "5.0.0-beta.7",
4
4
  "description": "Nitro integration for Workflow SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -24,15 +24,15 @@
24
24
  "@swc/core": "1.15.3",
25
25
  "exsolve": "1.0.8",
26
26
  "pathe": "2.0.3",
27
- "@workflow/builders": "5.0.0-beta.6",
28
- "@workflow/core": "5.0.0-beta.6",
29
- "@workflow/rollup": "5.0.0-beta.6",
27
+ "@workflow/builders": "5.0.0-beta.7",
28
+ "@workflow/core": "5.0.0-beta.7",
29
+ "@workflow/rollup": "5.0.0-beta.7",
30
30
  "@workflow/swc-plugin": "5.0.0-beta.4",
31
- "@workflow/vite": "5.0.0-beta.6"
31
+ "@workflow/vite": "5.0.0-beta.7"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/node": "22.19.0",
35
- "nitro": "3.0.1-alpha.1",
35
+ "nitro": "^3.0.260429-beta",
36
36
  "vite": "7.3.2",
37
37
  "@workflow/tsconfig": "5.0.0-beta.0"
38
38
  },