@workflow/next 5.0.0-beta.5 → 5.0.0-beta.51

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 (44) hide show
  1. package/dist/builder-eager.d.ts +2 -1
  2. package/dist/builder-eager.d.ts.map +1 -1
  3. package/dist/builder-eager.js +421 -169
  4. package/dist/builder.d.ts +1 -4
  5. package/dist/builder.d.ts.map +1 -1
  6. package/dist/builder.js +2 -28
  7. package/dist/index.d.ts +0 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +171 -69
  10. package/dist/loader.d.ts +5 -0
  11. package/dist/loader.d.ts.map +1 -1
  12. package/dist/loader.js +15 -341
  13. package/dist/runtime.d.ts +1 -1
  14. package/dist/runtime.d.ts.map +1 -1
  15. package/dist/runtime.js +2 -2
  16. package/dist/swc-plugin-cache.d.ts +7 -0
  17. package/dist/swc-plugin-cache.d.ts.map +1 -0
  18. package/dist/swc-plugin-cache.js +23 -0
  19. package/dist/watch-ignore.d.ts +51 -0
  20. package/dist/watch-ignore.d.ts.map +1 -0
  21. package/dist/watch-ignore.js +264 -0
  22. package/dist/watch-rebuild.d.ts +110 -0
  23. package/dist/watch-rebuild.d.ts.map +1 -0
  24. package/dist/watch-rebuild.js +476 -0
  25. package/docs/api-reference/with-workflow.mdx +39 -17
  26. package/docs/next.mdx +22 -16
  27. package/package.json +12 -9
  28. package/dist/builder-deferred.d.ts +0 -2
  29. package/dist/builder-deferred.d.ts.map +0 -1
  30. package/dist/builder-deferred.js +0 -1326
  31. package/dist/builder-deferred.js.map +0 -1
  32. package/dist/builder-eager.js.map +0 -1
  33. package/dist/builder.js.map +0 -1
  34. package/dist/environment-flag.d.ts +0 -2
  35. package/dist/environment-flag.d.ts.map +0 -1
  36. package/dist/environment-flag.js +0 -15
  37. package/dist/environment-flag.js.map +0 -1
  38. package/dist/index.js.map +0 -1
  39. package/dist/loader.js.map +0 -1
  40. package/dist/runtime.js.map +0 -1
  41. package/dist/socket-server.d.ts +0 -48
  42. package/dist/socket-server.d.ts.map +0 -1
  43. package/dist/socket-server.js +0 -154
  44. package/dist/socket-server.js.map +0 -1
@@ -1,1326 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getNextBuilderDeferred = getNextBuilderDeferred;
7
- const node_crypto_1 = require("node:crypto");
8
- const node_fs_1 = require("node:fs");
9
- const promises_1 = require("node:fs/promises");
10
- const node_module_1 = require("node:module");
11
- const node_os_1 = __importDefault(require("node:os"));
12
- const node_path_1 = require("node:path");
13
- const socket_server_js_1 = require("./socket-server.js");
14
- const ROUTE_STUB_FILE_MARKER = 'WORKFLOW_ROUTE_STUB_FILE';
15
- const ROUTE_STUB_MARKER_SCAN_BYTES = 4 * 1024;
16
- let CachedNextBuilderDeferred;
17
- // Create the deferred Next builder dynamically by extending the ESM BaseBuilder.
18
- // Exported as getNextBuilderDeferred() to allow CommonJS modules to import from
19
- // the ESM @workflow/builders package via dynamic import at runtime.
20
- async function getNextBuilderDeferred() {
21
- if (CachedNextBuilderDeferred) {
22
- return CachedNextBuilderDeferred;
23
- }
24
- // V2: STEP_QUEUE_TRIGGER, getImportPath, and enhanced-resolve infrastructure
25
- // were removed because the V2 combined handler eliminates the separate step
26
- // route/topic. The step copy import rewriting (getRelativeImportSpecifier,
27
- // getStepCopyFileName, rewriteRelativeImportsForCopiedStep) from main was also
28
- // removed — V2 doesn't use step copies. If step copy support is needed, it
29
- // should land as a complete feature set.
30
- const { BaseBuilder: BaseBuilderClass, WORKFLOW_QUEUE_TRIGGER, detectWorkflowPatterns, applySwcTransform, resolveWorkflowAliasRelativePath,
31
- // biome-ignore lint/security/noGlobalEval: Need to use eval here to avoid TypeScript from transpiling the import statement into `require()`
32
- } = (await eval('import("@workflow/builders")'));
33
- class NextDeferredBuilder extends BaseBuilderClass {
34
- socketIO;
35
- discoveredWorkflowFiles = new Set();
36
- discoveredStepFiles = new Set();
37
- discoveredSerdeFiles = new Set();
38
- trackedDependencyFiles = new Set();
39
- deferredBuildQueue = Promise.resolve();
40
- cacheInitialized = false;
41
- cacheWriteTimer = null;
42
- deferredRebuildTimer = null;
43
- lastDeferredBuildSignature = null;
44
- async build() {
45
- const outputDir = await this.findAppDirectory();
46
- await this.initializeDiscoveryState();
47
- await this.cleanupGeneratedArtifactsOnBoot(outputDir);
48
- await this.writeStubFiles(outputDir);
49
- await this.createDiscoverySocketServer();
50
- }
51
- async onBeforeDeferredEntries() {
52
- await this.initializeDiscoveryState();
53
- await this.validateDiscoveredEntryFiles();
54
- const implicitStepFiles = await this.resolveImplicitStepFiles();
55
- const pendingBuild = this.deferredBuildQueue.then(() => this.buildDeferredEntriesUntilStable(implicitStepFiles));
56
- // Keep the queue chain alive even when the current build fails so future
57
- // callbacks can enqueue another attempt without triggering unhandled
58
- // rejection warnings.
59
- this.deferredBuildQueue = pendingBuild.catch(() => {
60
- // Error is surfaced through `pendingBuild` below.
61
- });
62
- await pendingBuild;
63
- }
64
- getCurrentInputFiles(implicitStepFiles) {
65
- return Array.from(new Set([
66
- ...this.discoveredWorkflowFiles,
67
- ...this.discoveredStepFiles,
68
- ...this.discoveredSerdeFiles,
69
- ...implicitStepFiles,
70
- ])).sort();
71
- }
72
- async buildDeferredEntriesUntilStable(implicitStepFiles) {
73
- // A successful build can discover additional transitive dependency files
74
- // (via source maps), which changes the signature and may require one more
75
- // build pass to include newly discovered serde files.
76
- const maxBuildPasses = 3;
77
- for (let buildPass = 0; buildPass < maxBuildPasses; buildPass++) {
78
- const inputFiles = this.getCurrentInputFiles(implicitStepFiles);
79
- const buildSignature = await this.createDeferredBuildSignature(inputFiles);
80
- const shouldForceBuildForGeneratedRoutes = await this.shouldForceBuildForGeneratedRoutes();
81
- if (buildSignature === this.lastDeferredBuildSignature &&
82
- !shouldForceBuildForGeneratedRoutes) {
83
- return;
84
- }
85
- try {
86
- await this.buildDiscoveredFiles(inputFiles, implicitStepFiles);
87
- }
88
- catch (error) {
89
- if (this.config.watch) {
90
- await this.validateDiscoveredEntryFiles();
91
- const recoveredInputFiles = this.getCurrentInputFiles(implicitStepFiles);
92
- const recoveredSignature = await this.createDeferredBuildSignature(recoveredInputFiles);
93
- if (recoveredSignature !== buildSignature) {
94
- // A file was added/removed while this build was running; retry
95
- // immediately with the refreshed discovered-entry state.
96
- continue;
97
- }
98
- console.warn('[workflow] Deferred entries build failed. Will retry only after inputs change.', error);
99
- this.lastDeferredBuildSignature = buildSignature;
100
- return;
101
- }
102
- else {
103
- throw error;
104
- }
105
- }
106
- this.lastDeferredBuildSignature = buildSignature;
107
- if (!this.config.watch) {
108
- // Production builds can persist newly discovered deferred-entry files to
109
- // the cache after the first pass completes. Reload that cache before we
110
- // decide whether the input signature stabilized so staged tarball builds
111
- // can immediately replay with the expanded step set.
112
- await new Promise((resolve) => setTimeout(resolve, 250));
113
- await this.loadWorkflowsCache();
114
- }
115
- const postBuildInputFiles = this.getCurrentInputFiles(implicitStepFiles);
116
- const postBuildSignature = await this.createDeferredBuildSignature(postBuildInputFiles);
117
- if (postBuildSignature === buildSignature) {
118
- return;
119
- }
120
- }
121
- console.warn('[workflow] Deferred entries build signature did not stabilize after 3 passes.');
122
- }
123
- async resolveImplicitStepFiles() {
124
- const workflowStdlibPath = this.resolveWorkflowStdlibStepFilePath();
125
- return workflowStdlibPath ? [workflowStdlibPath] : [];
126
- }
127
- async shouldForceBuildForGeneratedRoutes() {
128
- const outputDir = await this.findAppDirectory();
129
- const generatedRouteFiles = [
130
- (0, node_path_1.join)(outputDir, '.well-known/workflow/v1/flow/route.js'),
131
- (0, node_path_1.join)(outputDir, '.well-known/workflow/v1/webhook/[token]/route.js'),
132
- ];
133
- for (const routeFilePath of generatedRouteFiles) {
134
- const routeState = await this.getGeneratedRouteState(routeFilePath);
135
- if (routeState === 'missing' || routeState === 'stub') {
136
- return true;
137
- }
138
- }
139
- return false;
140
- }
141
- async getGeneratedRouteState(routeFilePath) {
142
- let routeStats;
143
- try {
144
- routeStats = await (0, promises_1.stat)(routeFilePath);
145
- }
146
- catch {
147
- return 'missing';
148
- }
149
- if (!routeStats.isFile()) {
150
- return 'missing';
151
- }
152
- try {
153
- const routeFileHandle = await (0, promises_1.open)(routeFilePath, 'r');
154
- try {
155
- const markerScanBuffer = Buffer.alloc(ROUTE_STUB_MARKER_SCAN_BYTES);
156
- const { bytesRead } = await routeFileHandle.read(markerScanBuffer, 0, ROUTE_STUB_MARKER_SCAN_BYTES, 0);
157
- const markerScanSource = markerScanBuffer.toString('utf8', 0, bytesRead);
158
- return markerScanSource.includes(ROUTE_STUB_FILE_MARKER)
159
- ? 'stub'
160
- : 'generated';
161
- }
162
- finally {
163
- await routeFileHandle.close();
164
- }
165
- }
166
- catch {
167
- return 'missing';
168
- }
169
- }
170
- resolveWorkflowStdlibStepFilePath() {
171
- let workflowCjsEntry;
172
- try {
173
- workflowCjsEntry = require.resolve('workflow', {
174
- paths: [this.config.workingDir],
175
- });
176
- }
177
- catch {
178
- return null;
179
- }
180
- const workflowDistDir = (0, node_path_1.dirname)(workflowCjsEntry);
181
- const workflowStdlibPath = this.normalizeDiscoveredFilePath((0, node_path_1.join)(workflowDistDir, 'stdlib.js'));
182
- return (0, node_fs_1.existsSync)(workflowStdlibPath) ? workflowStdlibPath : null;
183
- }
184
- async reconcileDiscoveredEntries({ workflowCandidates, stepCandidates, serdeCandidates, validatePatterns, }) {
185
- const candidatesByFile = new Map();
186
- for (const filePath of workflowCandidates) {
187
- const normalizedPath = this.normalizeDiscoveredFilePath(filePath);
188
- const existing = candidatesByFile.get(normalizedPath);
189
- if (existing) {
190
- existing.hasWorkflowCandidate = true;
191
- }
192
- else {
193
- candidatesByFile.set(normalizedPath, {
194
- hasWorkflowCandidate: true,
195
- hasStepCandidate: false,
196
- hasSerdeCandidate: false,
197
- });
198
- }
199
- }
200
- for (const filePath of stepCandidates) {
201
- const normalizedPath = this.normalizeDiscoveredFilePath(filePath);
202
- const existing = candidatesByFile.get(normalizedPath);
203
- if (existing) {
204
- existing.hasStepCandidate = true;
205
- }
206
- else {
207
- candidatesByFile.set(normalizedPath, {
208
- hasWorkflowCandidate: false,
209
- hasStepCandidate: true,
210
- hasSerdeCandidate: false,
211
- });
212
- }
213
- }
214
- if (serdeCandidates) {
215
- for (const filePath of serdeCandidates) {
216
- const normalizedPath = this.normalizeDiscoveredFilePath(filePath);
217
- const existing = candidatesByFile.get(normalizedPath);
218
- if (existing) {
219
- existing.hasSerdeCandidate = true;
220
- }
221
- else {
222
- candidatesByFile.set(normalizedPath, {
223
- hasWorkflowCandidate: false,
224
- hasStepCandidate: false,
225
- hasSerdeCandidate: true,
226
- });
227
- }
228
- }
229
- }
230
- const fileEntries = Array.from(candidatesByFile.entries()).sort(([a], [b]) => a.localeCompare(b));
231
- const validatedEntries = await Promise.all(fileEntries.map(async ([filePath, candidates]) => {
232
- try {
233
- const fileStats = await (0, promises_1.stat)(filePath);
234
- if (!fileStats.isFile()) {
235
- return null;
236
- }
237
- if (!validatePatterns) {
238
- return {
239
- filePath,
240
- hasUseWorkflow: candidates.hasWorkflowCandidate,
241
- hasUseStep: candidates.hasStepCandidate,
242
- hasSerde: candidates.hasSerdeCandidate,
243
- };
244
- }
245
- const source = await (0, promises_1.readFile)(filePath, 'utf-8');
246
- const patterns = detectWorkflowPatterns(source);
247
- return {
248
- filePath,
249
- hasUseWorkflow: patterns.hasUseWorkflow,
250
- hasUseStep: patterns.hasUseStep,
251
- hasSerde: patterns.hasSerde,
252
- };
253
- }
254
- catch {
255
- return null;
256
- }
257
- }));
258
- const workflowFiles = new Set();
259
- const stepFiles = new Set();
260
- const serdeFiles = new Set();
261
- for (const entry of validatedEntries) {
262
- if (!entry) {
263
- continue;
264
- }
265
- if (entry.hasUseWorkflow) {
266
- workflowFiles.add(entry.filePath);
267
- }
268
- if (entry.hasUseStep) {
269
- stepFiles.add(entry.filePath);
270
- }
271
- if (entry.hasSerde) {
272
- serdeFiles.add(entry.filePath);
273
- }
274
- }
275
- return { workflowFiles, stepFiles, serdeFiles };
276
- }
277
- async validateDiscoveredEntryFiles() {
278
- const workflowCandidates = new Set(this.discoveredWorkflowFiles);
279
- const stepCandidates = new Set(this.discoveredStepFiles);
280
- const serdeCandidates = new Set(this.discoveredSerdeFiles);
281
- const { workflowFiles, stepFiles, serdeFiles } = await this.reconcileDiscoveredEntries({
282
- workflowCandidates,
283
- stepCandidates,
284
- serdeCandidates,
285
- validatePatterns: true,
286
- });
287
- // Reconcile validated entries against the snapshot we started with so
288
- // file discoveries that arrive during validation are preserved.
289
- let workflowsChanged = false;
290
- let stepsChanged = false;
291
- let serdeChanged = false;
292
- for (const filePath of workflowCandidates) {
293
- if (!workflowFiles.has(filePath)) {
294
- workflowsChanged =
295
- this.discoveredWorkflowFiles.delete(filePath) || workflowsChanged;
296
- }
297
- }
298
- for (const filePath of workflowFiles) {
299
- if (!this.discoveredWorkflowFiles.has(filePath)) {
300
- this.discoveredWorkflowFiles.add(filePath);
301
- workflowsChanged = true;
302
- }
303
- }
304
- for (const filePath of stepCandidates) {
305
- if (!stepFiles.has(filePath)) {
306
- stepsChanged =
307
- this.discoveredStepFiles.delete(filePath) || stepsChanged;
308
- }
309
- }
310
- for (const filePath of stepFiles) {
311
- if (!this.discoveredStepFiles.has(filePath)) {
312
- this.discoveredStepFiles.add(filePath);
313
- stepsChanged = true;
314
- }
315
- }
316
- for (const filePath of serdeCandidates) {
317
- if (!serdeFiles.has(filePath)) {
318
- serdeChanged =
319
- this.discoveredSerdeFiles.delete(filePath) || serdeChanged;
320
- }
321
- }
322
- for (const filePath of serdeFiles) {
323
- if (!this.discoveredSerdeFiles.has(filePath)) {
324
- this.discoveredSerdeFiles.add(filePath);
325
- serdeChanged = true;
326
- }
327
- }
328
- if (workflowsChanged || stepsChanged) {
329
- this.scheduleWorkflowsCacheWrite();
330
- }
331
- }
332
- async buildDiscoveredFiles(inputFiles, implicitStepFiles) {
333
- const outputDir = await this.findAppDirectory();
334
- const workflowGeneratedDir = (0, node_path_1.join)(outputDir, '.well-known/workflow/v1');
335
- const cacheDir = (0, node_path_1.join)(this.config.workingDir, this.getDistDir(), 'cache');
336
- await (0, promises_1.mkdir)(cacheDir, { recursive: true });
337
- const manifestBuildDir = (0, node_path_1.join)(cacheDir, 'workflow-generated-manifest');
338
- const tempRouteFileName = 'route.js.temp';
339
- const trackedDiscoveredEntries = await this.collectTrackedDiscoveredEntries();
340
- const discoveredStepFileCandidates = Array.from(new Set([
341
- ...this.discoveredStepFiles,
342
- ...trackedDiscoveredEntries.discoveredSteps,
343
- ...implicitStepFiles,
344
- ])).sort();
345
- const discoveredWorkflowFileCandidates = Array.from(new Set([
346
- ...this.discoveredWorkflowFiles,
347
- ...trackedDiscoveredEntries.discoveredWorkflows,
348
- ])).sort();
349
- const discoveredSerdeFileCandidates = Array.from(new Set([
350
- ...this.discoveredSerdeFiles,
351
- ...trackedDiscoveredEntries.discoveredSerdeFiles,
352
- ])).sort();
353
- const discoveredWorkflowFiles = await this.filterExistingFiles(discoveredWorkflowFileCandidates);
354
- const existingStepFileCandidates = await this.filterExistingFiles(discoveredStepFileCandidates);
355
- const discoveredStepFiles = await this.collectTransitiveStepFiles({
356
- entryFiles: [...existingStepFileCandidates, ...discoveredWorkflowFiles],
357
- stepFiles: existingStepFileCandidates,
358
- });
359
- const existingSerdeFileCandidates = await this.filterExistingFiles(discoveredSerdeFileCandidates);
360
- const discoveredSerdeFiles = await this.collectTransitiveSerdeFiles({
361
- entryFiles: [...discoveredStepFiles, ...discoveredWorkflowFiles],
362
- serdeFiles: existingSerdeFileCandidates,
363
- });
364
- const existingInputFiles = await this.filterExistingFiles(inputFiles);
365
- const buildInputFiles = Array.from(new Set([
366
- ...existingInputFiles,
367
- ...discoveredStepFiles,
368
- ...discoveredWorkflowFiles,
369
- ...discoveredSerdeFiles,
370
- ])).sort();
371
- const discoveredEntries = {
372
- discoveredSteps: new Set(discoveredStepFiles),
373
- discoveredWorkflows: new Set(discoveredWorkflowFiles),
374
- discoveredSerdeFiles: new Set(discoveredSerdeFiles),
375
- };
376
- // Ensure output directories exist
377
- await (0, promises_1.mkdir)(workflowGeneratedDir, { recursive: true });
378
- await this.writeFileIfChanged((0, node_path_1.join)(workflowGeneratedDir, '.gitignore'), '*');
379
- const tsconfigPath = await this.findTsConfigPath();
380
- // V2: Build combined route (replaces separate step + flow routes)
381
- const flowRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'flow');
382
- await (0, promises_1.mkdir)(flowRouteDir, { recursive: true });
383
- // Write step registrations to final name directly (not temp) so the
384
- // import path in the flow route is correct. The flow route uses temp
385
- // naming to avoid HMR churn via copyFileIfChanged, but the step
386
- // registrations file is a side-effect import and doesn't need that.
387
- const stepsOutfile = (0, node_path_1.join)(flowRouteDir, '__step_registrations.js');
388
- const combinedResult = await this.createCombinedBundle({
389
- format: 'esm',
390
- inputFiles: buildInputFiles,
391
- stepsOutfile,
392
- flowOutfile: (0, node_path_1.join)(flowRouteDir, tempRouteFileName),
393
- bundleFinalOutput: false,
394
- externalizeNonSteps: true,
395
- tsconfigPath,
396
- discoveredEntries,
397
- });
398
- await this.buildWebhookRoute({
399
- workflowGeneratedDir,
400
- routeFileName: tempRouteFileName,
401
- });
402
- await this.refreshTrackedDependencyFiles(workflowGeneratedDir, tempRouteFileName);
403
- const manifest = {
404
- steps: { ...combinedResult?.manifest?.steps },
405
- workflows: { ...combinedResult?.manifest?.workflows },
406
- classes: { ...combinedResult?.manifest?.classes },
407
- };
408
- const manifestFilePath = (0, node_path_1.join)(workflowGeneratedDir, 'manifest.json');
409
- const manifestBuildPath = (0, node_path_1.join)(manifestBuildDir, 'manifest.json');
410
- const workflowBundlePath = (0, node_path_1.join)(workflowGeneratedDir, `flow/${tempRouteFileName}`);
411
- const manifestJson = await this.createManifest({
412
- workflowBundlePath,
413
- manifestDir: manifestBuildDir,
414
- manifest,
415
- });
416
- if (manifestJson) {
417
- await this.rewriteJsonFileWithStableKeyOrder(manifestBuildPath);
418
- await this.copyFileIfChanged(manifestBuildPath, manifestFilePath);
419
- }
420
- else {
421
- await (0, promises_1.rm)(manifestBuildPath, { force: true });
422
- await (0, promises_1.rm)(manifestFilePath, { force: true });
423
- }
424
- await this.writeFunctionsConfig(outputDir);
425
- // V2: Combined route (flow) — step registrations already at final path
426
- await this.copyFileIfChanged((0, node_path_1.join)(workflowGeneratedDir, `flow/${tempRouteFileName}`), (0, node_path_1.join)(workflowGeneratedDir, 'flow/route.js'));
427
- await this.copyFileIfChanged((0, node_path_1.join)(workflowGeneratedDir, `webhook/[token]/${tempRouteFileName}`), (0, node_path_1.join)(workflowGeneratedDir, 'webhook/[token]/route.js'));
428
- // Expose manifest as a static file when WORKFLOW_PUBLIC_MANIFEST=1.
429
- // Next.js serves files from public/ at the root URL.
430
- if (this.shouldExposePublicManifest && manifestJson) {
431
- const publicManifestDir = (0, node_path_1.join)(this.config.workingDir, 'public/.well-known/workflow/v1');
432
- await (0, promises_1.mkdir)(publicManifestDir, { recursive: true });
433
- await this.copyFileIfChanged(manifestFilePath, (0, node_path_1.join)(publicManifestDir, 'manifest.json'));
434
- }
435
- // Notify deferred entry loaders waiting on route.js stubs.
436
- this.socketIO?.emit('build-complete');
437
- }
438
- async cleanupGeneratedArtifactsOnBoot(outputDir) {
439
- const workflowGeneratedDir = (0, node_path_1.join)(outputDir, '.well-known/workflow/v1');
440
- const flowRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'flow');
441
- const stepRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'step');
442
- const webhookRouteDir = (0, node_path_1.join)(workflowGeneratedDir, 'webhook/[token]');
443
- const staleArtifactPaths = [
444
- (0, node_path_1.join)(flowRouteDir, 'route.js.temp'),
445
- (0, node_path_1.join)(flowRouteDir, 'route.js.temp.debug.json'),
446
- (0, node_path_1.join)(flowRouteDir, 'route.js.debug.json'),
447
- (0, node_path_1.join)(flowRouteDir, '__step_registrations.route.js.temp'),
448
- (0, node_path_1.join)(flowRouteDir, '__step_registrations.route.js.temp.debug.json'),
449
- // V2: clean up stale V1 step route directory
450
- stepRouteDir,
451
- (0, node_path_1.join)(webhookRouteDir, 'route.js.temp'),
452
- (0, node_path_1.join)(workflowGeneratedDir, 'manifest.json'),
453
- ];
454
- await Promise.all(staleArtifactPaths.map((stalePath) => (0, promises_1.rm)(stalePath, { recursive: true, force: true })));
455
- await Promise.all([
456
- this.removeStaleDeferredTempFiles(flowRouteDir),
457
- this.removeStaleDeferredTempFiles(webhookRouteDir),
458
- ]);
459
- }
460
- async removeStaleDeferredTempFiles(routeDir) {
461
- const routeEntries = await (0, promises_1.readdir)(routeDir, {
462
- withFileTypes: true,
463
- }).catch(() => []);
464
- await Promise.all(routeEntries
465
- .filter((entry) => entry.isFile() &&
466
- entry.name.startsWith('route.js.') &&
467
- entry.name.endsWith('.tmp'))
468
- .map((entry) => (0, promises_1.rm)((0, node_path_1.join)(routeDir, entry.name), {
469
- force: true,
470
- })));
471
- }
472
- async createDiscoverySocketServer() {
473
- if (this.socketIO || process.env.WORKFLOW_SOCKET_PORT) {
474
- return;
475
- }
476
- process.env.WORKFLOW_SOCKET_INFO_PATH = this.getSocketInfoFilePath();
477
- const config = {
478
- isDevServer: Boolean(this.config.watch),
479
- socketInfoFilePath: this.getSocketInfoFilePath(),
480
- onFileDiscovered: (filePath, hasWorkflow, hasStep, hasSerde) => {
481
- const normalizedFilePath = this.normalizeDiscoveredFilePath(filePath);
482
- let hasCacheTrackingChange = false;
483
- const wasTrackedDependency = this.trackedDependencyFiles.has(normalizedFilePath);
484
- if (hasWorkflow) {
485
- if (!this.discoveredWorkflowFiles.has(normalizedFilePath)) {
486
- this.discoveredWorkflowFiles.add(normalizedFilePath);
487
- hasCacheTrackingChange = true;
488
- }
489
- }
490
- else {
491
- const wasDeleted = this.discoveredWorkflowFiles.delete(normalizedFilePath);
492
- hasCacheTrackingChange = wasDeleted || hasCacheTrackingChange;
493
- }
494
- if (hasStep) {
495
- if (!this.discoveredStepFiles.has(normalizedFilePath)) {
496
- this.discoveredStepFiles.add(normalizedFilePath);
497
- hasCacheTrackingChange = true;
498
- }
499
- }
500
- else {
501
- const wasDeleted = this.discoveredStepFiles.delete(normalizedFilePath);
502
- hasCacheTrackingChange = wasDeleted || hasCacheTrackingChange;
503
- }
504
- if (hasSerde) {
505
- if (!this.discoveredSerdeFiles.has(normalizedFilePath)) {
506
- hasCacheTrackingChange = true;
507
- }
508
- this.discoveredSerdeFiles.add(normalizedFilePath);
509
- }
510
- else {
511
- const wasDeleted = this.discoveredSerdeFiles.delete(normalizedFilePath);
512
- hasCacheTrackingChange = wasDeleted || hasCacheTrackingChange;
513
- }
514
- if (hasCacheTrackingChange) {
515
- this.scheduleWorkflowsCacheWrite();
516
- }
517
- if (hasWorkflow ||
518
- hasStep ||
519
- hasSerde ||
520
- hasCacheTrackingChange ||
521
- wasTrackedDependency) {
522
- this.scheduleDeferredRebuild();
523
- }
524
- },
525
- onTriggerBuild: () => {
526
- this.scheduleDeferredRebuild();
527
- },
528
- };
529
- this.socketIO = await (0, socket_server_js_1.createSocketServer)(config);
530
- }
531
- async initializeDiscoveryState() {
532
- if (this.cacheInitialized) {
533
- return;
534
- }
535
- await this.loadWorkflowsCache();
536
- // Deferred mode must not run eager input-graph discovery; entries are
537
- // discovered via loader->socket notifications during Next's build.
538
- this.cacheInitialized = true;
539
- }
540
- getDistDir() {
541
- return this.config.distDir || '.next';
542
- }
543
- getWorkflowsCacheFilePath() {
544
- return (0, node_path_1.join)(this.config.workingDir, this.getDistDir(), 'cache', 'workflows.json');
545
- }
546
- getSocketInfoFilePath() {
547
- return (0, node_path_1.join)(this.config.workingDir, this.getDistDir(), 'cache', 'workflow-socket.json');
548
- }
549
- findPackageJsonPath(filePath) {
550
- let currentDir = (0, node_path_1.dirname)(filePath);
551
- let previousDir = '';
552
- while (currentDir !== previousDir) {
553
- const packageJsonPath = (0, node_path_1.join)(currentDir, 'package.json');
554
- if ((0, node_fs_1.existsSync)(packageJsonPath)) {
555
- return packageJsonPath;
556
- }
557
- previousDir = currentDir;
558
- currentDir = (0, node_path_1.dirname)(currentDir);
559
- }
560
- return null;
561
- }
562
- shouldPreferSourceBackedPackagePath(filePath) {
563
- const normalizedPath = filePath.replace(/\\/g, '/');
564
- // Only prefer source for workspace packages (not in node_modules).
565
- // For tarball-installed packages, using source-backed paths causes
566
- // esbuild to bundle the full source tree (including world.ts with
567
- // process.cwd()) instead of externalizing properly.
568
- if (normalizedPath.includes('/packages/') &&
569
- !normalizedPath.includes('/node_modules/')) {
570
- return true;
571
- }
572
- if (!normalizedPath.includes('/node_modules/')) {
573
- return false;
574
- }
575
- const packageJsonPath = this.findPackageJsonPath(filePath);
576
- if (!packageJsonPath) {
577
- return false;
578
- }
579
- try {
580
- const packageJson = JSON.parse((0, node_fs_1.readFileSync)(packageJsonPath, 'utf-8'));
581
- return (packageJson.name === 'workflow' ||
582
- (typeof packageJson.name === 'string' &&
583
- packageJson.name.startsWith('@workflow/')));
584
- }
585
- catch {
586
- return false;
587
- }
588
- }
589
- resolveSourceBackedPackagePath(filePath) {
590
- const normalizedPath = filePath.replace(/\\/g, '/');
591
- if (!normalizedPath.includes('/dist/')) {
592
- return filePath;
593
- }
594
- const sourceCandidate = normalizedPath.replace('/dist/', '/src/');
595
- const resolvedSourceCandidate = this.resolveCopiedStepImportTargetPath(sourceCandidate);
596
- if (!(0, node_fs_1.existsSync)(resolvedSourceCandidate) ||
597
- !this.shouldPreferSourceBackedPackagePath(filePath)) {
598
- return filePath;
599
- }
600
- return (0, node_fs_1.existsSync)(resolvedSourceCandidate)
601
- ? resolvedSourceCandidate
602
- : filePath;
603
- }
604
- normalizeDiscoveredFilePath(filePath) {
605
- const absolutePath = (0, node_path_1.isAbsolute)(filePath)
606
- ? filePath
607
- : (0, node_path_1.resolve)(this.config.workingDir, filePath);
608
- return this.resolveSourceBackedPackagePath(absolutePath);
609
- }
610
- async filterExistingFiles(filePaths) {
611
- const normalizedFilePaths = Array.from(new Set(filePaths.map((filePath) => this.normalizeDiscoveredFilePath(filePath)))).sort();
612
- const existingFiles = await Promise.all(normalizedFilePaths.map(async (filePath) => {
613
- try {
614
- const fileStats = await (0, promises_1.stat)(filePath);
615
- return fileStats.isFile() ? filePath : null;
616
- }
617
- catch {
618
- return null;
619
- }
620
- }));
621
- return existingFiles.filter((filePath) => Boolean(filePath));
622
- }
623
- async createDeferredBuildSignature(inputFiles) {
624
- const normalizedFiles = Array.from(new Set([
625
- ...inputFiles.map((filePath) => this.normalizeDiscoveredFilePath(filePath)),
626
- ...this.trackedDependencyFiles,
627
- ])).sort();
628
- const signatureParts = await Promise.all(normalizedFiles.map(async (filePath) => {
629
- try {
630
- const fileStats = await (0, promises_1.stat)(filePath);
631
- return `${filePath}:${fileStats.size}:${Math.trunc(fileStats.mtimeMs)}`;
632
- }
633
- catch {
634
- return `${filePath}:missing`;
635
- }
636
- }));
637
- const signatureHash = (0, node_crypto_1.createHash)('sha256');
638
- for (const signaturePart of signatureParts) {
639
- signatureHash.update(signaturePart);
640
- signatureHash.update('\n');
641
- }
642
- return signatureHash.digest('hex');
643
- }
644
- async collectTrackedDiscoveredEntries() {
645
- if (this.trackedDependencyFiles.size === 0) {
646
- return {
647
- discoveredSteps: [],
648
- discoveredWorkflows: [],
649
- discoveredSerdeFiles: [],
650
- };
651
- }
652
- const { workflowFiles, stepFiles, serdeFiles } = await this.reconcileDiscoveredEntries({
653
- workflowCandidates: this.trackedDependencyFiles,
654
- stepCandidates: this.trackedDependencyFiles,
655
- serdeCandidates: this.trackedDependencyFiles,
656
- validatePatterns: true,
657
- });
658
- return {
659
- discoveredSteps: Array.from(stepFiles).sort(),
660
- discoveredWorkflows: Array.from(workflowFiles).sort(),
661
- discoveredSerdeFiles: Array.from(serdeFiles).sort(),
662
- };
663
- }
664
- async refreshTrackedDependencyFiles(workflowGeneratedDir, routeFileName) {
665
- const bundleFiles = [
666
- (0, node_path_1.join)(workflowGeneratedDir, `step/${routeFileName}`),
667
- (0, node_path_1.join)(workflowGeneratedDir, `flow/${routeFileName}`),
668
- ];
669
- const trackedFiles = new Set();
670
- for (const bundleFile of bundleFiles) {
671
- const bundleSources = await this.extractBundleSourceFiles(bundleFile);
672
- for (const sourceFile of bundleSources) {
673
- trackedFiles.add(sourceFile);
674
- }
675
- }
676
- if (trackedFiles.size > 0) {
677
- this.trackedDependencyFiles = trackedFiles;
678
- }
679
- }
680
- async extractBundleSourceFiles(bundleFilePath) {
681
- let bundleContents;
682
- try {
683
- bundleContents = await (0, promises_1.readFile)(bundleFilePath, 'utf-8');
684
- }
685
- catch {
686
- return [];
687
- }
688
- const baseDirectory = (0, node_path_1.dirname)(bundleFilePath);
689
- const localSourceFiles = new Set();
690
- const sourceMapMatches = bundleContents.matchAll(/\/\/# sourceMappingURL=data:application\/json[^,]*;base64,([A-Za-z0-9+/=]+)/g);
691
- for (const match of sourceMapMatches) {
692
- const base64Value = match[1];
693
- if (!base64Value) {
694
- continue;
695
- }
696
- let sourceMap;
697
- try {
698
- sourceMap = JSON.parse(Buffer.from(base64Value, 'base64').toString('utf-8'));
699
- }
700
- catch {
701
- continue;
702
- }
703
- const sourceRoot = typeof sourceMap.sourceRoot === 'string' ? sourceMap.sourceRoot : '';
704
- const sources = Array.isArray(sourceMap.sources)
705
- ? sourceMap.sources.filter((source) => typeof source === 'string')
706
- : [];
707
- for (const source of sources) {
708
- if (source.startsWith('webpack://') || source.startsWith('<')) {
709
- continue;
710
- }
711
- let resolvedSourcePath;
712
- if (source.startsWith('file://')) {
713
- try {
714
- resolvedSourcePath = decodeURIComponent(new URL(source).pathname);
715
- }
716
- catch {
717
- continue;
718
- }
719
- }
720
- else if ((0, node_path_1.isAbsolute)(source)) {
721
- resolvedSourcePath = source;
722
- }
723
- else {
724
- resolvedSourcePath = (0, node_path_1.resolve)(baseDirectory, sourceRoot, source);
725
- }
726
- const normalizedSourcePath = this.normalizeDiscoveredFilePath(resolvedSourcePath);
727
- const normalizedSourcePathForCheck = normalizedSourcePath.replace(/\\/g, '/');
728
- const isSourceBackedPackagePath = this.shouldPreferSourceBackedPackagePath(normalizedSourcePath);
729
- if (normalizedSourcePathForCheck.includes('/.well-known/workflow/') ||
730
- (!isSourceBackedPackagePath &&
731
- normalizedSourcePathForCheck.includes('/node_modules/')) ||
732
- (!isSourceBackedPackagePath &&
733
- normalizedSourcePathForCheck.includes('/.pnpm/')) ||
734
- normalizedSourcePathForCheck.includes('/.next/') ||
735
- normalizedSourcePathForCheck.endsWith('/virtual-entry.js')) {
736
- continue;
737
- }
738
- localSourceFiles.add(normalizedSourcePath);
739
- }
740
- }
741
- return Array.from(localSourceFiles);
742
- }
743
- scheduleWorkflowsCacheWrite() {
744
- if (this.cacheWriteTimer) {
745
- clearTimeout(this.cacheWriteTimer);
746
- }
747
- this.cacheWriteTimer = setTimeout(() => {
748
- this.cacheWriteTimer = null;
749
- void this.writeWorkflowsCache().catch((error) => {
750
- console.warn('Failed to write workflow discovery cache', error);
751
- });
752
- }, 50);
753
- }
754
- scheduleDeferredRebuild() {
755
- if (this.deferredRebuildTimer) {
756
- clearTimeout(this.deferredRebuildTimer);
757
- }
758
- this.deferredRebuildTimer = setTimeout(() => {
759
- this.deferredRebuildTimer = null;
760
- void this.onBeforeDeferredEntries().catch((error) => {
761
- console.warn('[workflow] Deferred rebuild after source update failed.', error);
762
- });
763
- }, 75);
764
- }
765
- async readWorkflowsCache() {
766
- const cacheFilePath = this.getWorkflowsCacheFilePath();
767
- try {
768
- const cacheContents = await (0, promises_1.readFile)(cacheFilePath, 'utf-8');
769
- const parsed = JSON.parse(cacheContents);
770
- const workflowFiles = Array.isArray(parsed.workflowFiles)
771
- ? parsed.workflowFiles.filter((item) => typeof item === 'string')
772
- : [];
773
- const stepFiles = Array.isArray(parsed.stepFiles)
774
- ? parsed.stepFiles.filter((item) => typeof item === 'string')
775
- : [];
776
- return { workflowFiles, stepFiles };
777
- }
778
- catch {
779
- return null;
780
- }
781
- }
782
- async loadWorkflowsCache() {
783
- const cachedData = await this.readWorkflowsCache();
784
- if (!cachedData) {
785
- return;
786
- }
787
- const { workflowFiles, stepFiles, serdeFiles } = await this.reconcileDiscoveredEntries({
788
- workflowCandidates: cachedData.workflowFiles,
789
- stepCandidates: cachedData.stepFiles,
790
- serdeCandidates: this.discoveredSerdeFiles,
791
- validatePatterns: true,
792
- });
793
- this.discoveredWorkflowFiles.clear();
794
- this.discoveredStepFiles.clear();
795
- this.discoveredSerdeFiles.clear();
796
- for (const filePath of workflowFiles) {
797
- this.discoveredWorkflowFiles.add(filePath);
798
- }
799
- for (const filePath of stepFiles) {
800
- this.discoveredStepFiles.add(filePath);
801
- }
802
- for (const filePath of serdeFiles) {
803
- this.discoveredSerdeFiles.add(filePath);
804
- }
805
- }
806
- async writeWorkflowsCache() {
807
- const cacheFilePath = this.getWorkflowsCacheFilePath();
808
- const cacheDir = (0, node_path_1.join)(this.config.workingDir, this.getDistDir(), 'cache');
809
- await (0, promises_1.mkdir)(cacheDir, { recursive: true });
810
- const cacheData = {
811
- workflowFiles: Array.from(this.discoveredWorkflowFiles).sort(),
812
- stepFiles: Array.from(this.discoveredStepFiles).sort(),
813
- };
814
- await (0, promises_1.writeFile)(cacheFilePath, JSON.stringify(cacheData, null, 2));
815
- }
816
- async writeStubFiles(outputDir) {
817
- // Turbopack currently has a worker-concurrency limitation for pending
818
- // virtual entries. Warn if parallelism is too low to reliably discover.
819
- const parallelismCount = node_os_1.default.availableParallelism();
820
- if (process.env.TURBOPACK && parallelismCount < 4) {
821
- console.warn(`Available parallelism of ${parallelismCount} is less than needed 4. This can cause workflows/steps to fail to discover properly in turbopack`);
822
- }
823
- const routeStubContent = [
824
- `// ${ROUTE_STUB_FILE_MARKER}`,
825
- 'export const __workflowRouteStub = true;',
826
- ].join('\n');
827
- const workflowGeneratedDir = (0, node_path_1.join)(outputDir, '.well-known/workflow/v1');
828
- await (0, promises_1.mkdir)((0, node_path_1.join)(workflowGeneratedDir, 'flow'), { recursive: true });
829
- await (0, promises_1.mkdir)((0, node_path_1.join)(workflowGeneratedDir, 'webhook/[token]'), {
830
- recursive: true,
831
- });
832
- await this.writeFileIfChanged((0, node_path_1.join)(workflowGeneratedDir, '.gitignore'), '*');
833
- // V2: Only flow + webhook stubs needed (no separate step route).
834
- // Stubs are replaced by generated output once discovery finishes.
835
- await this.writeFileIfChanged((0, node_path_1.join)(workflowGeneratedDir, 'flow/route.js'), routeStubContent);
836
- await this.writeFileIfChanged((0, node_path_1.join)(workflowGeneratedDir, 'webhook/[token]/route.js'), routeStubContent);
837
- }
838
- async getInputFiles() {
839
- // Read Next.js's app-paths-manifest.json from a previous build to
840
- // determine which files are actual route entrypoints. This avoids
841
- // predicting Next.js conventions with regexes and instead reads
842
- // from Next.js's own output.
843
- const nextDir = (0, node_path_1.join)(this.config.workingDir, '.next');
844
- const manifestPath = (0, node_path_1.join)(nextDir, 'app-paths-manifest.json');
845
- try {
846
- const manifestContent = (0, node_fs_1.readFileSync)(manifestPath, 'utf-8');
847
- const manifest = JSON.parse(manifestContent);
848
- // The manifest maps route paths to their source files.
849
- // Extract the source file paths and resolve them.
850
- const manifestFiles = new Set();
851
- for (const sourcePath of Object.values(manifest)) {
852
- const resolved = (0, node_path_1.resolve)(nextDir, 'server', sourcePath);
853
- // The manifest points to built output; find the source file
854
- // by matching against the base builder's full file list.
855
- manifestFiles.add(resolved);
856
- }
857
- // Use the manifest route paths to filter the input files.
858
- // A file is included if it matches a known route segment from
859
- // the manifest (e.g., app/api/route contains 'app/api/route').
860
- const inputFiles = await super.getInputFiles();
861
- const routeSegments = Object.keys(manifest).map((route) => route.replace(/^\//, '').replace(/\/route$/, ''));
862
- return inputFiles.filter((item) => routeSegments.some((segment) => item.includes(segment)));
863
- }
864
- catch {
865
- // No manifest from a previous build — fall back to the base
866
- // builder's full file scan. This is safe but slower; subsequent
867
- // builds will use the manifest.
868
- return super.getInputFiles();
869
- }
870
- }
871
- async writeFunctionsConfig(outputDir) {
872
- // we don't run this in development mode as it's not needed
873
- if (process.env.NODE_ENV === 'development') {
874
- return;
875
- }
876
- // V2: Single combined trigger handles both workflow and step execution
877
- const generatedConfig = {
878
- version: '0',
879
- workflows: {
880
- maxDuration: 'max',
881
- experimentalTriggers: [WORKFLOW_QUEUE_TRIGGER],
882
- },
883
- };
884
- await this.writeFileIfChanged((0, node_path_1.join)(outputDir, '.well-known/workflow/v1/config.json'), JSON.stringify(generatedConfig, null, 2));
885
- }
886
- async writeFileIfChanged(filePath, contents) {
887
- const nextBuffer = Buffer.isBuffer(contents)
888
- ? contents
889
- : Buffer.from(contents);
890
- try {
891
- const currentBuffer = await (0, promises_1.readFile)(filePath);
892
- if (currentBuffer.equals(nextBuffer)) {
893
- return false;
894
- }
895
- }
896
- catch {
897
- // File does not exist yet or cannot be read; write a fresh copy.
898
- }
899
- await (0, promises_1.mkdir)((0, node_path_1.dirname)(filePath), { recursive: true });
900
- await (0, promises_1.writeFile)(filePath, nextBuffer);
901
- return true;
902
- }
903
- async copyFileIfChanged(sourcePath, destinationPath) {
904
- const sourceContents = await (0, promises_1.readFile)(sourcePath);
905
- return this.writeFileIfChanged(destinationPath, sourceContents);
906
- }
907
- sortJsonValue(value) {
908
- if (Array.isArray(value)) {
909
- return value.map((item) => this.sortJsonValue(item));
910
- }
911
- if (value && typeof value === 'object') {
912
- const sortedEntries = Object.entries(value)
913
- .sort(([a], [b]) => a.localeCompare(b))
914
- .map(([key, entryValue]) => [key, this.sortJsonValue(entryValue)]);
915
- return Object.fromEntries(sortedEntries);
916
- }
917
- return value;
918
- }
919
- async rewriteJsonFileWithStableKeyOrder(filePath) {
920
- try {
921
- const contents = await (0, promises_1.readFile)(filePath, 'utf-8');
922
- const parsed = JSON.parse(contents);
923
- const normalized = this.sortJsonValue(parsed);
924
- await this.writeFileIfChanged(filePath, `${JSON.stringify(normalized, null, 2)}\n`);
925
- }
926
- catch {
927
- // Manifest may not exist (e.g. manifest generation failed); ignore.
928
- }
929
- }
930
- resolveCopiedStepImportTargetPath(targetPath) {
931
- if ((0, node_fs_1.existsSync)(targetPath)) {
932
- return targetPath;
933
- }
934
- const extensionMatch = targetPath.match(/(\.[^./\\]+)$/);
935
- const extension = extensionMatch?.[1]?.toLowerCase();
936
- if (!extension) {
937
- return targetPath;
938
- }
939
- const extensionFallbacks = extension === '.js'
940
- ? ['.ts', '.tsx', '.mts', '.cts']
941
- : extension === '.mjs'
942
- ? ['.mts']
943
- : extension === '.cjs'
944
- ? ['.cts']
945
- : extension === '.jsx'
946
- ? ['.tsx']
947
- : [];
948
- if (extensionFallbacks.length === 0) {
949
- return targetPath;
950
- }
951
- const targetWithoutExtension = targetPath.slice(0, -extension.length);
952
- for (const fallbackExtension of extensionFallbacks) {
953
- const fallbackPath = `${targetWithoutExtension}${fallbackExtension}`;
954
- if ((0, node_fs_1.existsSync)(fallbackPath)) {
955
- return fallbackPath;
956
- }
957
- }
958
- return targetPath;
959
- }
960
- extractRelativeImportSpecifiers(source) {
961
- return this.extractImportSpecifiers(source).filter((specifier) => specifier.startsWith('.'));
962
- }
963
- extractImportSpecifiers(source) {
964
- const relativeSpecifiers = new Set();
965
- const importPatterns = [
966
- /from\s+['"]([^'"]+)['"]/g,
967
- /import\s+['"]([^'"]+)['"]/g,
968
- /import\(\s*['"]([^'"]+)['"]\s*\)/g,
969
- /require\(\s*['"]([^'"]+)['"]\s*\)/g,
970
- ];
971
- for (const importPattern of importPatterns) {
972
- for (const match of source.matchAll(importPattern)) {
973
- const specifier = match[1];
974
- if (specifier) {
975
- relativeSpecifiers.add(specifier);
976
- }
977
- }
978
- }
979
- return Array.from(relativeSpecifiers);
980
- }
981
- async getRelativeFilenameForSwc(filePath) {
982
- const workingDir = this.config.workingDir;
983
- const normalizedWorkingDir = workingDir
984
- .replace(/\\/g, '/')
985
- .replace(/\/$/, '');
986
- const normalizedFilepath = filePath.replace(/\\/g, '/');
987
- // Windows fix: Use case-insensitive comparison to work around drive letter casing issues.
988
- const lowerWd = normalizedWorkingDir.toLowerCase();
989
- const lowerPath = normalizedFilepath.toLowerCase();
990
- let relativeFilename;
991
- if (lowerPath.startsWith(`${lowerWd}/`)) {
992
- relativeFilename = normalizedFilepath.substring(normalizedWorkingDir.length + 1);
993
- }
994
- else if (lowerPath === lowerWd) {
995
- relativeFilename = '.';
996
- }
997
- else {
998
- relativeFilename = (0, node_path_1.relative)(workingDir, filePath).replace(/\\/g, '/');
999
- if (relativeFilename.startsWith('../')) {
1000
- const aliasedRelativePath = await resolveWorkflowAliasRelativePath(filePath, workingDir);
1001
- if (aliasedRelativePath) {
1002
- relativeFilename = aliasedRelativePath;
1003
- }
1004
- else {
1005
- relativeFilename = relativeFilename
1006
- .split('/')
1007
- .filter((part) => part !== '..')
1008
- .join('/');
1009
- }
1010
- }
1011
- }
1012
- if (relativeFilename.includes(':') || relativeFilename.startsWith('/')) {
1013
- relativeFilename = (0, node_path_1.basename)(normalizedFilepath);
1014
- }
1015
- return relativeFilename;
1016
- }
1017
- resolveImportTargetWithExtensionFallbacks(targetPath) {
1018
- if ((0, node_fs_1.existsSync)(targetPath)) {
1019
- return targetPath;
1020
- }
1021
- const extensionMatch = targetPath.match(/(\.[^./\\]+)$/);
1022
- const extension = extensionMatch?.[1]?.toLowerCase();
1023
- if (!extension) {
1024
- return targetPath;
1025
- }
1026
- const extensionFallbacks = extension === '.js'
1027
- ? ['.ts', '.tsx', '.mts', '.cts']
1028
- : extension === '.mjs'
1029
- ? ['.mts']
1030
- : extension === '.cjs'
1031
- ? ['.cts']
1032
- : extension === '.jsx'
1033
- ? ['.tsx']
1034
- : [];
1035
- if (extensionFallbacks.length === 0) {
1036
- return targetPath;
1037
- }
1038
- const targetWithoutExtension = targetPath.slice(0, -extension.length);
1039
- for (const fallbackExtension of extensionFallbacks) {
1040
- const fallbackPath = `${targetWithoutExtension}${fallbackExtension}`;
1041
- if ((0, node_fs_1.existsSync)(fallbackPath)) {
1042
- return fallbackPath;
1043
- }
1044
- }
1045
- return targetPath;
1046
- }
1047
- shouldSkipTransitiveStepFile(filePath) {
1048
- const normalizedPath = filePath.replace(/\\/g, '/');
1049
- const isSourceBackedPackagePath = this.shouldPreferSourceBackedPackagePath(filePath);
1050
- return (normalizedPath.includes('/.well-known/workflow/') ||
1051
- normalizedPath.includes('/.next/') ||
1052
- (!isSourceBackedPackagePath &&
1053
- (normalizedPath.includes('/node_modules/') ||
1054
- normalizedPath.includes('/.pnpm/'))));
1055
- }
1056
- async resolveTransitiveStepImportTargetPath(sourceFilePath, specifier) {
1057
- const specifierMatch = specifier.match(/^([^?#]+)(.*)$/);
1058
- const importPath = specifierMatch?.[1] ?? specifier;
1059
- if (!importPath.startsWith('.')) {
1060
- if (importPath !== 'workflow' && !importPath.startsWith('@workflow/')) {
1061
- return null;
1062
- }
1063
- try {
1064
- const resolvedPath = (0, node_module_1.createRequire)(sourceFilePath).resolve(importPath);
1065
- const normalizedResolvedPath = this.normalizeDiscoveredFilePath(resolvedPath);
1066
- if (this.shouldSkipTransitiveStepFile(normalizedResolvedPath)) {
1067
- return null;
1068
- }
1069
- const fileStats = await (0, promises_1.stat)(normalizedResolvedPath);
1070
- return fileStats.isFile() ? normalizedResolvedPath : null;
1071
- }
1072
- catch {
1073
- return null;
1074
- }
1075
- }
1076
- const absoluteTargetPath = (0, node_path_1.resolve)((0, node_path_1.dirname)(sourceFilePath), importPath);
1077
- const candidatePaths = new Set([
1078
- this.resolveImportTargetWithExtensionFallbacks(absoluteTargetPath),
1079
- ]);
1080
- if (!(0, node_path_1.extname)(absoluteTargetPath)) {
1081
- const extensionCandidates = [
1082
- '.ts',
1083
- '.tsx',
1084
- '.mts',
1085
- '.cts',
1086
- '.js',
1087
- '.jsx',
1088
- '.mjs',
1089
- '.cjs',
1090
- ];
1091
- for (const extensionCandidate of extensionCandidates) {
1092
- candidatePaths.add(`${absoluteTargetPath}${extensionCandidate}`);
1093
- candidatePaths.add((0, node_path_1.join)(absoluteTargetPath, `index${extensionCandidate}`));
1094
- }
1095
- }
1096
- for (const candidatePath of candidatePaths) {
1097
- const resolvedPath = this.resolveImportTargetWithExtensionFallbacks(candidatePath);
1098
- const normalizedResolvedPath = this.normalizeDiscoveredFilePath(resolvedPath);
1099
- if (this.shouldSkipTransitiveStepFile(normalizedResolvedPath)) {
1100
- continue;
1101
- }
1102
- try {
1103
- const fileStats = await (0, promises_1.stat)(normalizedResolvedPath);
1104
- if (fileStats.isFile()) {
1105
- return normalizedResolvedPath;
1106
- }
1107
- }
1108
- catch {
1109
- // Try the next candidate path.
1110
- }
1111
- }
1112
- return null;
1113
- }
1114
- async collectTransitiveStepFiles({ entryFiles, stepFiles, }) {
1115
- const normalizedEntryFiles = Array.from(new Set(entryFiles.map((entryFile) => this.normalizeDiscoveredFilePath(entryFile)))).sort();
1116
- const normalizedStepSeedFiles = Array.from(new Set(stepFiles.map((stepFile) => this.normalizeDiscoveredFilePath(stepFile)))).sort();
1117
- const discoveredStepFiles = new Set(normalizedStepSeedFiles);
1118
- const queuedFiles = Array.from(new Set([...normalizedEntryFiles, ...normalizedStepSeedFiles]));
1119
- const visitedFiles = new Set();
1120
- const sourceCache = new Map();
1121
- const patternCache = new Map();
1122
- const getSource = async (filePath) => {
1123
- if (sourceCache.has(filePath)) {
1124
- return sourceCache.get(filePath) ?? null;
1125
- }
1126
- try {
1127
- const source = await (0, promises_1.readFile)(filePath, 'utf-8');
1128
- sourceCache.set(filePath, source);
1129
- return source;
1130
- }
1131
- catch {
1132
- sourceCache.set(filePath, null);
1133
- return null;
1134
- }
1135
- };
1136
- const getPatterns = async (filePath) => {
1137
- if (patternCache.has(filePath)) {
1138
- return patternCache.get(filePath) ?? null;
1139
- }
1140
- const source = await getSource(filePath);
1141
- if (source === null) {
1142
- patternCache.set(filePath, null);
1143
- return null;
1144
- }
1145
- const patterns = detectWorkflowPatterns(source);
1146
- patternCache.set(filePath, patterns);
1147
- return patterns;
1148
- };
1149
- while (queuedFiles.length > 0) {
1150
- const currentFile = queuedFiles.pop();
1151
- if (!currentFile || visitedFiles.has(currentFile)) {
1152
- continue;
1153
- }
1154
- visitedFiles.add(currentFile);
1155
- const currentSource = await getSource(currentFile);
1156
- if (currentSource === null) {
1157
- continue;
1158
- }
1159
- const importSpecifiers = this.extractImportSpecifiers(currentSource);
1160
- for (const specifier of importSpecifiers) {
1161
- const resolvedImportPath = await this.resolveTransitiveStepImportTargetPath(currentFile, specifier);
1162
- if (!resolvedImportPath) {
1163
- continue;
1164
- }
1165
- if (!visitedFiles.has(resolvedImportPath)) {
1166
- queuedFiles.push(resolvedImportPath);
1167
- }
1168
- const importPatterns = await getPatterns(resolvedImportPath);
1169
- if (importPatterns?.hasUseStep) {
1170
- discoveredStepFiles.add(resolvedImportPath);
1171
- }
1172
- }
1173
- }
1174
- return Array.from(discoveredStepFiles).sort();
1175
- }
1176
- async collectTransitiveSerdeFiles({ entryFiles, serdeFiles, }) {
1177
- const normalizedEntryFiles = Array.from(new Set(entryFiles.map((entryFile) => this.normalizeDiscoveredFilePath(entryFile)))).sort();
1178
- const normalizedSerdeSeedFiles = Array.from(new Set(serdeFiles.map((serdeFile) => this.normalizeDiscoveredFilePath(serdeFile)))).sort();
1179
- // Intentionally re-validate serde seeds against source patterns.
1180
- // This keeps previously discovered/manual seed entries from sticking when
1181
- // files no longer match serde patterns.
1182
- const discoveredSerdeFiles = new Set();
1183
- const queuedFiles = Array.from(new Set([...normalizedEntryFiles, ...normalizedSerdeSeedFiles]));
1184
- const visitedFiles = new Set();
1185
- const sourceCache = new Map();
1186
- const patternCache = new Map();
1187
- const getSource = async (filePath) => {
1188
- if (sourceCache.has(filePath)) {
1189
- return sourceCache.get(filePath) ?? null;
1190
- }
1191
- try {
1192
- const source = await (0, promises_1.readFile)(filePath, 'utf-8');
1193
- sourceCache.set(filePath, source);
1194
- return source;
1195
- }
1196
- catch {
1197
- sourceCache.set(filePath, null);
1198
- return null;
1199
- }
1200
- };
1201
- const getPatterns = async (filePath) => {
1202
- if (patternCache.has(filePath)) {
1203
- return patternCache.get(filePath) ?? null;
1204
- }
1205
- const source = await getSource(filePath);
1206
- if (source === null) {
1207
- patternCache.set(filePath, null);
1208
- return null;
1209
- }
1210
- const patterns = detectWorkflowPatterns(source);
1211
- patternCache.set(filePath, patterns);
1212
- return patterns;
1213
- };
1214
- for (const serdeSeedFile of normalizedSerdeSeedFiles) {
1215
- const seedPatterns = await getPatterns(serdeSeedFile);
1216
- if (seedPatterns?.hasSerde) {
1217
- discoveredSerdeFiles.add(serdeSeedFile);
1218
- }
1219
- }
1220
- while (queuedFiles.length > 0) {
1221
- const currentFile = queuedFiles.pop();
1222
- if (!currentFile || visitedFiles.has(currentFile)) {
1223
- continue;
1224
- }
1225
- visitedFiles.add(currentFile);
1226
- const currentSource = await getSource(currentFile);
1227
- if (currentSource === null) {
1228
- continue;
1229
- }
1230
- const relativeImportSpecifiers = this.extractRelativeImportSpecifiers(currentSource);
1231
- for (const specifier of relativeImportSpecifiers) {
1232
- const resolvedImportPath = await this.resolveTransitiveStepImportTargetPath(currentFile, specifier);
1233
- if (!resolvedImportPath) {
1234
- continue;
1235
- }
1236
- if (!visitedFiles.has(resolvedImportPath)) {
1237
- queuedFiles.push(resolvedImportPath);
1238
- }
1239
- const importPatterns = await getPatterns(resolvedImportPath);
1240
- if (importPatterns?.hasSerde) {
1241
- discoveredSerdeFiles.add(resolvedImportPath);
1242
- }
1243
- }
1244
- }
1245
- // AST-level verification: run SWC detect mode on regex-matched candidates
1246
- // to confirm they actually define serde classes. This prevents SDK internal
1247
- // files (which match serde regex patterns but define no classes) from being
1248
- // bundled into the workflow sandbox.
1249
- const projectRoot = this.config.projectRoot || this.config.workingDir;
1250
- const verifiedSerdeFiles = [];
1251
- await Promise.all(Array.from(discoveredSerdeFiles).map(async (filePath) => {
1252
- const source = await getSource(filePath);
1253
- if (!source)
1254
- return;
1255
- try {
1256
- const relativeFilename = await this.getRelativeFilenameForSwc(filePath);
1257
- const { workflowManifest } = await applySwcTransform(relativeFilename, source, 'detect', filePath, projectRoot);
1258
- // Only include files that actually define serde classes
1259
- const hasClasses = workflowManifest.classes &&
1260
- Object.values(workflowManifest.classes).some((entries) => Object.keys(entries).length > 0);
1261
- if (hasClasses) {
1262
- verifiedSerdeFiles.push(filePath);
1263
- }
1264
- }
1265
- catch {
1266
- // If detect fails, include the file to be safe
1267
- verifiedSerdeFiles.push(filePath);
1268
- }
1269
- }));
1270
- return verifiedSerdeFiles.sort();
1271
- }
1272
- async buildWebhookRoute({ workflowGeneratedDir, routeFileName = 'route.js', }) {
1273
- const webhookRouteFile = (0, node_path_1.join)(workflowGeneratedDir, `webhook/[token]/${routeFileName}`);
1274
- await this.createWebhookBundle({
1275
- outfile: webhookRouteFile,
1276
- bundle: false, // Next.js doesn't need bundling
1277
- });
1278
- }
1279
- async findAppDirectory() {
1280
- const appDir = (0, node_path_1.resolve)(this.config.workingDir, 'app');
1281
- const srcAppDir = (0, node_path_1.resolve)(this.config.workingDir, 'src/app');
1282
- const pagesDir = (0, node_path_1.resolve)(this.config.workingDir, 'pages');
1283
- const srcPagesDir = (0, node_path_1.resolve)(this.config.workingDir, 'src/pages');
1284
- // Helper to check if a path exists and is a directory
1285
- const isDirectory = async (path) => {
1286
- try {
1287
- await (0, promises_1.access)(path, node_fs_1.constants.F_OK);
1288
- const stats = await (0, promises_1.stat)(path);
1289
- if (!stats.isDirectory()) {
1290
- throw new Error(`Path exists but is not a directory: ${path}`);
1291
- }
1292
- return true;
1293
- }
1294
- catch (e) {
1295
- if (e instanceof Error && e.message.includes('not a directory')) {
1296
- throw e;
1297
- }
1298
- return false;
1299
- }
1300
- };
1301
- // Check if app directory exists
1302
- if (await isDirectory(appDir)) {
1303
- return appDir;
1304
- }
1305
- // Check if src/app directory exists
1306
- if (await isDirectory(srcAppDir)) {
1307
- return srcAppDir;
1308
- }
1309
- // If no app directory exists, check for pages directory and create app next to it
1310
- if (await isDirectory(pagesDir)) {
1311
- // Create app directory next to pages directory
1312
- await (0, promises_1.mkdir)(appDir, { recursive: true });
1313
- return appDir;
1314
- }
1315
- if (await isDirectory(srcPagesDir)) {
1316
- // Create src/app directory next to src/pages directory
1317
- await (0, promises_1.mkdir)(srcAppDir, { recursive: true });
1318
- return srcAppDir;
1319
- }
1320
- throw new Error('Could not find Next.js app or pages directory. Expected one of: "app", "src/app", "pages", or "src/pages" to exist.');
1321
- }
1322
- }
1323
- CachedNextBuilderDeferred = NextDeferredBuilder;
1324
- return NextDeferredBuilder;
1325
- }
1326
- //# sourceMappingURL=builder-deferred.js.map