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