@wix/ditto-codegen-public 1.0.524 → 1.0.526

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.
@@ -0,0 +1,1834 @@
1
+ // Runs the project's SDK calls and reports the ones the service rejects, which typecheck cannot
2
+ // see. A standalone script the validation-state plugin runs after a passing full validate; not a
3
+ // tool (only top-level `opencode-tools/` files are). Node builtins and erasable TypeScript only:
4
+ // node strips the types. Trouble running the check skips it; it never fails the run itself.
5
+
6
+ import { execFile, fork } from "node:child_process";
7
+ import { createRequire } from "node:module";
8
+ import { readFileSync, realpathSync } from "node:fs";
9
+ import {
10
+ mkdir,
11
+ mkdtemp,
12
+ readdir,
13
+ readFile,
14
+ rm,
15
+ stat,
16
+ writeFile,
17
+ } from "node:fs/promises";
18
+ import { tmpdir } from "node:os";
19
+ import { dirname, join, posix, resolve } from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { promisify } from "node:util";
22
+
23
+ const execFileAsync = promisify(execFile);
24
+
25
+ export type TypeScript = typeof import("typescript");
26
+
27
+ // The project's own TypeScript (the one its tsc step uses), else ours.
28
+ function loadTypeScript(cwd: string): TypeScript | undefined {
29
+ for (const base of [cwd, process.cwd()]) {
30
+ try {
31
+ return createRequire(join(base, "package.json"))(
32
+ "typescript",
33
+ ) as TypeScript;
34
+ } catch {
35
+ continue;
36
+ }
37
+ }
38
+ return undefined;
39
+ }
40
+
41
+ const SDK_RUNTIME_MAX_TARGETS = 20;
42
+ const SDK_RUNTIME_TARGET_TIMEOUT_MS = 8_000;
43
+ const SDK_RUNTIME_REQUEST_TIMEOUT_MS = 10_000;
44
+ const SDK_RUNTIME_MARKER = "__SDK_RUNTIME__";
45
+ const WIX_API_ORIGIN = "https://www.wixapis.com/";
46
+ // Tests serve canned answers from localhost; nothing else may replace the origin.
47
+ const LOCAL_API_ORIGIN = /^http:\/\/127\.0\.0\.1:\d+\/$/;
48
+ // Stand-ins for arguments the runner makes up. A rejected request that carries
49
+ // one of them may have been caused by it, not by the code.
50
+ const ARG_STRING = "synthetic-arg";
51
+ const ARG_ID = "00000000-0000-4000-8000-00000007311a";
52
+ const ARG_NUMBER = 2718;
53
+ const ARG_MARKERS = [ARG_STRING, ARG_ID, String(ARG_NUMBER)];
54
+ // `@wix/*` packages that are not data SDKs: UI, host and tooling.
55
+ const NON_DATA_PACKAGES =
56
+ /^@wix\/(?:design-system|patterns|dashboard|custom-extensions|astro|sdk|sdk-[\w-]+|services-[\w-]+|site-[\w-]+|react-[\w-]+|essentials|image-kit|ui-[\w-]+)$/;
57
+ // Rejections about the shape of a query: always the code's, even when the
58
+ // request carries made-up dates.
59
+ const QUERY_SHAPE_CODE =
60
+ /^(?:INVALID|UNSUPPORTED)_(?:QUERY|SORT|FILTER)|^MISSING_NAMESPACE_FILTER$/;
61
+ // The site does not have the app the code calls: the code compiles and then
62
+ // does nothing. Stores answers 401, others 428 or APP_NOT_INSTALLED.
63
+ const APP_NOT_INSTALLED =
64
+ /APP_NOT_INSTALLED|is not installed|app with id not installed/i;
65
+ // eCommerce (orders, checkout, cart) answers a bare 401 when no app provides it. Elsewhere a
66
+ // bare 401 more likely means the call needs a member or visitor, which the site token is not.
67
+ const BARE_401_MISSING_APP = /^\/ecom\//;
68
+ // A 404 that says the thing the code points at does not exist (a collection, a
69
+ // route), as opposed to one entity a made-up id did not find.
70
+ const MISSING_TARGET_404 =
71
+ /(?:collection|namespace|route|endpoint|method|schema|dataset|table|resource type).{0,40}(?:does not exist|not found|unknown)|no route|unknown method/i;
72
+ // Host modules call `window.clientSdk`, which Studio 2 pages do not have.
73
+ const VIEWER_HOST_MODULE = /^@wix\/site-(?!service-)[\w-]+$/;
74
+
75
+ export interface SdkParam {
76
+ name: string;
77
+ kind: string;
78
+ }
79
+ export interface SdkTarget {
80
+ file: string;
81
+ name: string;
82
+ args: SdkParam[];
83
+ // A call taken out of a component to be run: the wrapper module that holds it, relative to
84
+ // the project, and the source written there.
85
+ module?: string;
86
+ wrapper?: string;
87
+ inline?: boolean;
88
+ }
89
+ type TsNode = import("typescript").Node;
90
+ type TsCall = import("typescript").CallExpression;
91
+ type TsStatement = import("typescript").Statement;
92
+ type TsSourceFile = import("typescript").SourceFile;
93
+
94
+ function parseSource(
95
+ ts: TypeScript,
96
+ file: string,
97
+ source: string,
98
+ ): TsSourceFile {
99
+ return ts.createSourceFile(
100
+ file,
101
+ source,
102
+ ts.ScriptTarget.Latest,
103
+ true,
104
+ file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
105
+ );
106
+ }
107
+
108
+ function hasModifier(ts: TypeScript, node: TsNode, kind: number): boolean {
109
+ return (
110
+ ts.canHaveModifiers(node) &&
111
+ (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind)
112
+ );
113
+ }
114
+
115
+ function isFunctionValue(
116
+ ts: TypeScript,
117
+ node: TsNode | undefined,
118
+ ): node is
119
+ | import("typescript").ArrowFunction
120
+ | import("typescript").FunctionExpression {
121
+ return !!node && (ts.isArrowFunction(node) || ts.isFunctionExpression(node));
122
+ }
123
+
124
+ function lineOf(sourceFile: TsSourceFile, node: TsNode): number {
125
+ return (
126
+ sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1
127
+ );
128
+ }
129
+
130
+ function kindOfType(
131
+ ts: TypeScript,
132
+ type: import("typescript").TypeNode,
133
+ ): string {
134
+ const isOptional =
135
+ ts.isUnionTypeNode(type) &&
136
+ type.types.some(
137
+ (member) =>
138
+ member.kind === ts.SyntaxKind.UndefinedKeyword ||
139
+ (ts.isLiteralTypeNode(member) &&
140
+ member.literal.kind === ts.SyntaxKind.NullKeyword),
141
+ );
142
+ if (isOptional) return "undefined";
143
+ if (type.kind === ts.SyntaxKind.NumberKeyword) return "number";
144
+ if (type.kind === ts.SyntaxKind.StringKeyword) return "string";
145
+ if (type.kind === ts.SyntaxKind.BooleanKeyword) return "boolean";
146
+ if (ts.isArrayTypeNode(type)) return "array";
147
+ if (ts.isTypeReferenceNode(type) && type.typeName.getText() === "Date")
148
+ return "date";
149
+ return "object";
150
+ }
151
+
152
+ function sdkParamKind(
153
+ ts: TypeScript,
154
+ param: import("typescript").ParameterDeclaration,
155
+ ): string {
156
+ if (param.questionToken || param.initializer) return "undefined";
157
+ return param.type ? kindOfType(ts, param.type) : "object";
158
+ }
159
+
160
+ function sdkBindingsOf(ts: TypeScript, sourceFile: TsSourceFile): Set<string> {
161
+ const sdkBindings = new Set<string>();
162
+ for (const statement of sourceFile.statements) {
163
+ if (
164
+ !ts.isImportDeclaration(statement) ||
165
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
166
+ statement.importClause?.isTypeOnly
167
+ )
168
+ continue;
169
+ const specifier = statement.moduleSpecifier.text;
170
+ const packageName = specifier.split("/").slice(0, 2).join("/");
171
+ if (!specifier.startsWith("@wix/") || NON_DATA_PACKAGES.test(packageName))
172
+ continue;
173
+ const bindings = statement.importClause?.namedBindings;
174
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
175
+ for (const element of bindings.elements)
176
+ if (!element.isTypeOnly) sdkBindings.add(element.name.text);
177
+ }
178
+ return sdkBindings;
179
+ }
180
+
181
+ function isSdkBindingCall(
182
+ ts: TypeScript,
183
+ node: TsNode,
184
+ bindings: Set<string>,
185
+ ): node is TsCall {
186
+ if (!ts.isCallExpression(node)) return false;
187
+ // Walk to the root of the call chain, through casts, parentheses, optional
188
+ // chains, element access and await.
189
+ let callee: import("typescript").Expression = node.expression;
190
+ while (
191
+ ts.isPropertyAccessExpression(callee) ||
192
+ ts.isElementAccessExpression(callee) ||
193
+ ts.isCallExpression(callee) ||
194
+ ts.isNonNullExpression(callee) ||
195
+ ts.isParenthesizedExpression(callee) ||
196
+ ts.isAsExpression(callee) ||
197
+ ts.isTypeAssertionExpression(callee) ||
198
+ ts.isAwaitExpression(callee)
199
+ )
200
+ callee = callee.expression;
201
+ return ts.isIdentifier(callee) && bindings.has(callee.text);
202
+ }
203
+
204
+ // The method called on the SDK binding: `query` in `things.query({}).eq(...).find()`, also
205
+ // through casts and parentheses such as `(things as any).query(...)`.
206
+ function sdkMethodName(ts: TypeScript, call: TsCall): string {
207
+ let callee: import("typescript").Expression = call.expression;
208
+ let name = "";
209
+ for (;;) {
210
+ if (ts.isIdentifier(callee)) return name;
211
+ if (ts.isPropertyAccessExpression(callee)) name = callee.name.text;
212
+ else if (
213
+ !ts.isCallExpression(callee) &&
214
+ !ts.isNonNullExpression(callee) &&
215
+ !ts.isParenthesizedExpression(callee) &&
216
+ !ts.isAsExpression(callee) &&
217
+ !ts.isTypeAssertionExpression(callee) &&
218
+ !ts.isAwaitExpression(callee) &&
219
+ !ts.isElementAccessExpression(callee)
220
+ )
221
+ return "";
222
+ callee = callee.expression;
223
+ }
224
+ }
225
+
226
+ function containsSdkCall(
227
+ ts: TypeScript,
228
+ root: TsNode,
229
+ bindings: Set<string>,
230
+ ): boolean {
231
+ return (
232
+ isSdkBindingCall(ts, root, bindings) ||
233
+ (ts.forEachChild(
234
+ root,
235
+ (child) => containsSdkCall(ts, child, bindings) || undefined,
236
+ ) ??
237
+ false)
238
+ );
239
+ }
240
+
241
+ // The exported async functions of a file: the only code the check can call from outside.
242
+ function exportedAsyncFunctions(
243
+ ts: TypeScript,
244
+ statement: TsStatement,
245
+ ): {
246
+ name: string;
247
+ fn: import("typescript").SignatureDeclaration;
248
+ body: TsNode;
249
+ }[] {
250
+ // `export default async () => ...`: reached as the module's `default` export.
251
+ if (
252
+ ts.isExportAssignment(statement) &&
253
+ !statement.isExportEquals &&
254
+ isFunctionValue(ts, statement.expression) &&
255
+ hasModifier(ts, statement.expression, ts.SyntaxKind.AsyncKeyword)
256
+ )
257
+ return [
258
+ {
259
+ name: "default",
260
+ fn: statement.expression,
261
+ body: statement.expression.body,
262
+ },
263
+ ];
264
+ if (!hasModifier(ts, statement, ts.SyntaxKind.ExportKeyword)) return [];
265
+ if (ts.isFunctionDeclaration(statement)) {
266
+ // `export default async function load()` is reached as `default`, not as `load`.
267
+ const name = hasModifier(ts, statement, ts.SyntaxKind.DefaultKeyword)
268
+ ? "default"
269
+ : statement.name?.text;
270
+ return name &&
271
+ statement.body &&
272
+ hasModifier(ts, statement, ts.SyntaxKind.AsyncKeyword)
273
+ ? [{ name, fn: statement, body: statement.body }]
274
+ : [];
275
+ }
276
+ if (!ts.isVariableStatement(statement)) return [];
277
+ return statement.declarationList.declarations.flatMap((declaration) => {
278
+ const init = declaration.initializer;
279
+ return ts.isIdentifier(declaration.name) &&
280
+ isFunctionValue(ts, init) &&
281
+ hasModifier(ts, init, ts.SyntaxKind.AsyncKeyword)
282
+ ? [{ name: declaration.name.text, fn: init, body: init.body }]
283
+ : [];
284
+ });
285
+ }
286
+
287
+ // An exported function with a lowercase name that is not async: a helper the agent wrote on
288
+ // purpose, whose calls are left alone.
289
+ function isExportedHelper(ts: TypeScript, statement: TsStatement): boolean {
290
+ if (!hasModifier(ts, statement, ts.SyntaxKind.ExportKeyword)) return false;
291
+ if (ts.isFunctionDeclaration(statement))
292
+ return !!statement.name && /^[a-z]/.test(statement.name.text);
293
+ return (
294
+ ts.isVariableStatement(statement) &&
295
+ statement.declarationList.declarations.some(
296
+ (declaration) =>
297
+ ts.isIdentifier(declaration.name) &&
298
+ /^[a-z]/.test(declaration.name.text) &&
299
+ isFunctionValue(ts, declaration.initializer),
300
+ )
301
+ );
302
+ }
303
+
304
+ export function findSdkTargets(
305
+ ts: TypeScript,
306
+ file: string,
307
+ source: string,
308
+ ): SdkTarget[] {
309
+ const sourceFile = parseSource(ts, file, source);
310
+ const bindings = sdkBindingsOf(ts, sourceFile);
311
+ if (bindings.size === 0) return [];
312
+ return sourceFile.statements.flatMap((statement) =>
313
+ exportedAsyncFunctions(ts, statement)
314
+ .filter(({ body }) => containsSdkCall(ts, body, bindings))
315
+ .map(({ name, fn }) => ({
316
+ file,
317
+ name,
318
+ args: fn.parameters.map((param) => ({
319
+ name: param.name.getText(),
320
+ kind: sdkParamKind(ts, param),
321
+ })),
322
+ })),
323
+ );
324
+ }
325
+
326
+ export interface SdkCallSites {
327
+ // The file registers an event handler or service plugin.
328
+ handlerFile: boolean;
329
+ // Lines of SDK calls validate cannot run: only an exported async function is.
330
+ unrunLines: number[];
331
+ }
332
+
333
+ // A method that reads: the check sends these for real, so one taken out of a component can be
334
+ // checked. A write is never sent, so taking it out would change nothing.
335
+ const READ_METHOD = /^(?:get|list|query|search|count|find|fetch|retrieve)/i;
336
+ // The registration itself (`things.onThingCreated(handler)`, `provideHandlers({ ... })`) is
337
+ // not a call to run; its handler is.
338
+ const REGISTRATION = /^(?:on[A-Z]|provideHandlers$)/;
339
+
340
+ function calleeName(ts: TypeScript, call: TsCall): string {
341
+ if (ts.isPropertyAccessExpression(call.expression))
342
+ return call.expression.name.text;
343
+ return ts.isIdentifier(call.expression) ? call.expression.text : "";
344
+ }
345
+
346
+ // Event handlers (`export default contacts.onContactCreated(...)`) and service plugins
347
+ // (`provideHandlers({ ... })`) run without a visitor or member session, so a bare SDK call
348
+ // there throws; calls go through auth.elevate.
349
+ function isHandlerFile(ts: TypeScript, sourceFile: TsSourceFile): boolean {
350
+ return sourceFile.statements.some(
351
+ (statement) =>
352
+ (ts.isExportAssignment(statement) &&
353
+ ts.isCallExpression(statement.expression) &&
354
+ /^on[A-Z]/.test(calleeName(ts, statement.expression))) ||
355
+ /\bprovideHandlers\s*\(/.test(statement.getText(sourceFile)),
356
+ );
357
+ }
358
+
359
+ export function findSdkCallSites(
360
+ ts: TypeScript,
361
+ file: string,
362
+ source: string,
363
+ ): SdkCallSites {
364
+ const sourceFile = parseSource(ts, file, source);
365
+ const bindings = sdkBindingsOf(ts, sourceFile);
366
+ if (bindings.size === 0) return { handlerFile: false, unrunLines: [] };
367
+ const unrunLines = new Set<number>();
368
+ const visit = (node: TsNode): void => {
369
+ if (
370
+ isSdkBindingCall(ts, node, bindings) &&
371
+ !REGISTRATION.test(calleeName(ts, node))
372
+ )
373
+ unrunLines.add(lineOf(sourceFile, node));
374
+ ts.forEachChild(node, visit);
375
+ };
376
+ for (const statement of sourceFile.statements)
377
+ if (exportedAsyncFunctions(ts, statement).length === 0) visit(statement);
378
+ return {
379
+ handlerFile: isHandlerFile(ts, sourceFile),
380
+ unrunLines: [...unrunLines].sort((a, b) => a - b),
381
+ };
382
+ }
383
+
384
+ // An SDK read inside a component, an effect or a handler cannot be called from outside, so it
385
+ // is taken out into a small exported async function, with the imports it uses and a parameter
386
+ // for each value it takes from the code around it. A call that cannot be carried over safely
387
+ // (one that uses a local function or an import alias) is left out and gets a note saying it was not checked.
388
+ export interface InlineRead {
389
+ line: number;
390
+ params: SdkParam[];
391
+ wrapper: string;
392
+ }
393
+
394
+ const PROMISE_METHODS = new Set(["then", "catch", "finally"]);
395
+ // Page and component code: backend code has its own rules.
396
+ const INLINE_SCOPE = /^src\/extensions\/(?:dashboard|site)\//;
397
+
398
+ function kindOfExpression(
399
+ ts: TypeScript,
400
+ expression: import("typescript").Expression | undefined,
401
+ ): string | undefined {
402
+ if (!expression) return undefined;
403
+ const text = expression.getText();
404
+ if (
405
+ ts.isNewExpression(expression) &&
406
+ expression.expression.getText() === "Date"
407
+ )
408
+ return "date";
409
+ if (
410
+ ts.isNumericLiteral(expression) ||
411
+ (ts.isPrefixUnaryExpression(expression) &&
412
+ ts.isNumericLiteral(expression.operand)) ||
413
+ text === "Date.now()"
414
+ )
415
+ return "number";
416
+ if (
417
+ ts.isStringLiteral(expression) ||
418
+ ts.isNoSubstitutionTemplateLiteral(expression) ||
419
+ ts.isTemplateExpression(expression)
420
+ )
421
+ return "string";
422
+ if (text === "true" || text === "false") return "boolean";
423
+ if (ts.isArrayLiteralExpression(expression)) return "array";
424
+ if (ts.isObjectLiteralExpression(expression)) return "object";
425
+ return undefined;
426
+ }
427
+
428
+ // `const [from, setFrom] = useState(new Date())`: the state's initial value.
429
+ function stateInitializer(
430
+ ts: TypeScript,
431
+ declaration: TsNode,
432
+ ): import("typescript").Expression | undefined {
433
+ if (
434
+ !ts.isBindingElement(declaration) ||
435
+ !ts.isArrayBindingPattern(declaration.parent)
436
+ )
437
+ return undefined;
438
+ const pattern = declaration.parent;
439
+ const variable = pattern.parent;
440
+ return pattern.elements[0] === declaration &&
441
+ ts.isVariableDeclaration(variable) &&
442
+ variable.initializer &&
443
+ ts.isCallExpression(variable.initializer)
444
+ ? variable.initializer.arguments[0]
445
+ : undefined;
446
+ }
447
+
448
+ // What to pass for a value the call takes from the code around it, from how it is declared.
449
+ function kindOfDeclaration(
450
+ ts: TypeScript,
451
+ name: string,
452
+ declaration: TsNode,
453
+ ): string {
454
+ const isTyped =
455
+ (ts.isParameter(declaration) || ts.isVariableDeclaration(declaration)) &&
456
+ declaration.type;
457
+ if (isTyped) return kindOfType(ts, declaration.type);
458
+ const found =
459
+ (ts.isVariableDeclaration(declaration) &&
460
+ kindOfExpression(ts, declaration.initializer)) ||
461
+ kindOfExpression(ts, stateInitializer(ts, declaration));
462
+ if (found) return found;
463
+ if (/^(?:from|to|start|end|since|until)$|Date$|At$/.test(name)) return "date";
464
+ if (/^(?:limit|offset|page|size|skip|count)$/i.test(name)) return "number";
465
+ return "object";
466
+ }
467
+
468
+ type ImportBinding = { specifier: string; text: string };
469
+
470
+ // Each name the file imports at runtime, with the import clause that brings it in.
471
+ function importBindings(
472
+ ts: TypeScript,
473
+ sourceFile: TsSourceFile,
474
+ ): Map<string, ImportBinding> {
475
+ const imports = new Map<string, ImportBinding>();
476
+ for (const statement of sourceFile.statements) {
477
+ if (
478
+ !ts.isImportDeclaration(statement) ||
479
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
480
+ !statement.importClause ||
481
+ statement.importClause.isTypeOnly
482
+ )
483
+ continue;
484
+ const specifier = statement.moduleSpecifier.text;
485
+ const { name, namedBindings } = statement.importClause;
486
+ if (name) imports.set(name.text, { specifier, text: name.text });
487
+ if (namedBindings && ts.isNamespaceImport(namedBindings))
488
+ imports.set(namedBindings.name.text, {
489
+ specifier,
490
+ text: `* as ${namedBindings.name.text}`,
491
+ });
492
+ else if (namedBindings)
493
+ for (const element of namedBindings.elements)
494
+ if (!element.isTypeOnly)
495
+ imports.set(element.name.text, {
496
+ specifier,
497
+ text: `{ ${element.propertyName ? `${element.propertyName.text} as ` : ""}${element.name.text} }`,
498
+ });
499
+ }
500
+ return imports;
501
+ }
502
+
503
+ function isDeclaration(
504
+ ts: TypeScript,
505
+ node: TsNode,
506
+ ): node is
507
+ | import("typescript").VariableDeclaration
508
+ | import("typescript").ParameterDeclaration
509
+ | import("typescript").BindingElement {
510
+ return (
511
+ ts.isVariableDeclaration(node) ||
512
+ ts.isParameter(node) ||
513
+ ts.isBindingElement(node)
514
+ );
515
+ }
516
+
517
+ // Every name declared anywhere in the file, and what declares it.
518
+ function declarationsOf(
519
+ ts: TypeScript,
520
+ sourceFile: TsSourceFile,
521
+ ): Map<string, TsNode> {
522
+ const declared = new Map<string, TsNode>();
523
+ const collect = (node: TsNode): void => {
524
+ const isNamed =
525
+ isDeclaration(ts, node) ||
526
+ ts.isFunctionDeclaration(node) ||
527
+ ts.isClassDeclaration(node);
528
+ if (
529
+ isNamed &&
530
+ node.name &&
531
+ ts.isIdentifier(node.name) &&
532
+ !declared.has(node.name.text)
533
+ )
534
+ declared.set(node.name.text, node);
535
+ ts.forEachChild(node, collect);
536
+ };
537
+ collect(sourceFile);
538
+ return declared;
539
+ }
540
+
541
+ // The names a call uses that it does not declare itself, each marked if it is called.
542
+ function freeNames(ts: TypeScript, call: TsCall): Map<string, boolean> {
543
+ const inside = new Set<string>();
544
+ const used = new Map<string, boolean>();
545
+ const walk = (node: TsNode): void => {
546
+ if (ts.isTypeNode(node)) return;
547
+ if (isDeclaration(ts, node) && ts.isIdentifier(node.name))
548
+ inside.add(node.name.text);
549
+ if (ts.isIdentifier(node)) {
550
+ const parent = node.parent;
551
+ const isName =
552
+ ((ts.isPropertyAccessExpression(parent) ||
553
+ ts.isPropertyAssignment(parent)) &&
554
+ parent.name === node) ||
555
+ (isDeclaration(ts, parent) && parent.name === node);
556
+ const isCalled =
557
+ ts.isCallExpression(parent) && parent.expression === node;
558
+ if (!isName)
559
+ used.set(node.text, (used.get(node.text) ?? false) || isCalled);
560
+ }
561
+ ts.forEachChild(node, walk);
562
+ };
563
+ walk(call);
564
+ for (const name of [...inside, "undefined"]) used.delete(name);
565
+ return used;
566
+ }
567
+
568
+ // The SDK reads to take out: not the promise handling after a call, and only the outermost
569
+ // call of a builder chain, which carries the whole chain.
570
+ function inlineCandidates(
571
+ ts: TypeScript,
572
+ sourceFile: TsSourceFile,
573
+ bindings: Set<string>,
574
+ ): TsCall[] {
575
+ const calls: TsCall[] = [];
576
+ const visit = (node: TsNode): void => {
577
+ if (isSdkBindingCall(ts, node, bindings)) {
578
+ const { expression: callee, parent } = node;
579
+ const isPromiseStep =
580
+ ts.isPropertyAccessExpression(callee) &&
581
+ PROMISE_METHODS.has(callee.name.text);
582
+ const continues =
583
+ ts.isPropertyAccessExpression(parent) &&
584
+ parent.expression === node &&
585
+ !PROMISE_METHODS.has(parent.name.text) &&
586
+ ts.isCallExpression(parent.parent);
587
+ if (
588
+ !isPromiseStep &&
589
+ !continues &&
590
+ READ_METHOD.test(sdkMethodName(ts, node))
591
+ )
592
+ calls.push(node);
593
+ }
594
+ ts.forEachChild(node, visit);
595
+ };
596
+ for (const statement of sourceFile.statements)
597
+ if (
598
+ exportedAsyncFunctions(ts, statement).length === 0 &&
599
+ !isExportedHelper(ts, statement)
600
+ )
601
+ visit(statement);
602
+ return calls;
603
+ }
604
+
605
+ interface InlineContext {
606
+ ts: TypeScript;
607
+ cwd: string;
608
+ file: string;
609
+ sourceFile: TsSourceFile;
610
+ imports: Map<string, ImportBinding>;
611
+ declared: Map<string, TsNode>;
612
+ aliases: readonly PathAlias[];
613
+ }
614
+
615
+ // The wrapper for one call, or undefined when the call cannot be carried over.
616
+ function inlineRead(
617
+ context: InlineContext,
618
+ call: TsCall,
619
+ ): InlineRead | undefined {
620
+ const { ts, cwd, file, sourceFile, imports, declared, aliases } = context;
621
+ const params: SdkParam[] = [];
622
+ const importLines: string[] = [];
623
+ for (const [name, isCalled] of freeNames(ts, call)) {
624
+ const imported = imports.get(name);
625
+ if (imported) {
626
+ // The runner resolves the tsconfig's aliases, so such an import is carried over as is.
627
+ const isAliased = aliases.some((alias) =>
628
+ imported.specifier.startsWith(alias.prefix),
629
+ );
630
+ if (ALIAS_SPECIFIER.test(imported.specifier) && !isAliased)
631
+ return undefined;
632
+ const specifier = imported.specifier.startsWith(".")
633
+ ? posix.join(
634
+ cwd.replaceAll("\\", "/"),
635
+ posix.dirname(file),
636
+ imported.specifier,
637
+ )
638
+ : imported.specifier;
639
+ importLines.push(
640
+ `import ${imported.text} from ${JSON.stringify(specifier)};`,
641
+ );
642
+ continue;
643
+ }
644
+ const declaration = declared.get(name);
645
+ if (!declaration) continue; // a global: Date, Math, JSON
646
+ // A local function or class cannot be stood in for.
647
+ if (
648
+ isCalled ||
649
+ ts.isFunctionDeclaration(declaration) ||
650
+ ts.isClassDeclaration(declaration)
651
+ )
652
+ return undefined;
653
+ params.push({ name, kind: kindOfDeclaration(ts, name, declaration) });
654
+ }
655
+ const wrapper = [
656
+ ...importLines,
657
+ `export async function inline(${params.map((param) => param.name).join(", ")}) {`,
658
+ ` return ${call.getText(sourceFile)};`,
659
+ "}",
660
+ ].join("\n");
661
+ return { line: lineOf(sourceFile, call), params, wrapper };
662
+ }
663
+
664
+ export function extractInlineReads(
665
+ ts: TypeScript,
666
+ cwd: string,
667
+ file: string,
668
+ source: string,
669
+ aliases: readonly PathAlias[] = [],
670
+ ): InlineRead[] {
671
+ const sourceFile = parseSource(ts, file, source);
672
+ const bindings = sdkBindingsOf(ts, sourceFile);
673
+ if (bindings.size === 0 || isHandlerFile(ts, sourceFile)) return [];
674
+ const context: InlineContext = {
675
+ ts,
676
+ cwd,
677
+ file,
678
+ sourceFile,
679
+ imports: importBindings(ts, sourceFile),
680
+ declared: declarationsOf(ts, sourceFile),
681
+ aliases,
682
+ };
683
+ return inlineCandidates(ts, sourceFile, bindings).flatMap(
684
+ (call) => inlineRead(context, call) ?? [],
685
+ );
686
+ }
687
+
688
+ // Runs in `node` inside the project: requires each target with the project's own typescript
689
+ // and SDK and prints one marker line with what each call did. It never holds the site token:
690
+ // every fetch goes to the parent over IPC (brokerRequest), which decides what is sent, adds
691
+ // the token there and records the request, so project code cannot reach the token.
692
+ export const SDK_RUNTIME_RUNNER = [
693
+ 'const fs = require("fs"), path = require("path"), Module = require("module");',
694
+ // Each request is tagged with the target whose call sent it, even when it is sent after
695
+ // that target timed out and the next one started.
696
+ 'const { AsyncLocalStorage } = require("async_hooks"); const caller = new AsyncLocalStorage();',
697
+ "const [cwd, targetsPath] = process.argv.slice(2);",
698
+ 'const targets = JSON.parse(fs.readFileSync(targetsPath, "utf8"));',
699
+ 'const req = Module.createRequire(path.join(cwd, "package.json"));',
700
+ // tsconfig `paths` (readPathAliases): project code imports through them, plain require does not know them.
701
+ 'const aliases = JSON.parse(process.env.SDK_RUNTIME_PATH_ALIASES || "[]"); const resolveFilename = Module._resolveFilename;',
702
+ "Module._resolveFilename = function (request, ...rest) {",
703
+ " for (const a of aliases) if (request.startsWith(a.prefix) && request.endsWith(a.suffix) && request.length >= a.prefix.length + a.suffix.length) {",
704
+ " const star = request.slice(a.prefix.length, request.length - a.suffix.length);",
705
+ ' for (const t of a.targets) { try { return resolveFilename.call(this, path.join(cwd, t.replace("*", star)), ...rest); } catch {} }',
706
+ " }",
707
+ " return resolveFilename.call(this, request, ...rest);",
708
+ "};",
709
+ "const send = process.send.bind(process); const pending = new Map(); let seq = 0; const sentBy = new Map();",
710
+ 'process.on("message", (m) => { const done = pending.get(m && m.id); if (done) { pending.delete(m.id); done(m); } });',
711
+ // Exits only once the marker line has been written: a pipe write is asynchronous.
712
+ `const out = (value) => new Promise((done) => process.stdout.write("\\n${SDK_RUNTIME_MARKER}" + JSON.stringify(value) + "\\n", done)).then(() => process.exit(0));`,
713
+ // Stopped at the total limit: report the targets that finished, so they still count.
714
+ 'const results = []; process.on("SIGTERM", () => { out({ results, partial: true }); });',
715
+ "globalThis.fetch = async (input, init) => {",
716
+ ' const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;',
717
+ ' const method = (init && init.method) || "GET";',
718
+ " const target = caller.getStore() ?? null; sentBy.set(target, (sentBy.get(target) || 0) + 1);",
719
+ " const headers = []; new Headers(init && init.headers).forEach((value, name) => headers.push([name, value]));",
720
+ ' const body = init && typeof init.body === "string" ? init.body : undefined;',
721
+ " const id = ++seq;",
722
+ " const answer = await new Promise((done) => { pending.set(id, done); send({ id, target, url, method, headers, body }); });",
723
+ " return new Response(answer.text, { status: answer.status, headers: answer.headers });",
724
+ "};",
725
+ "const synth = (a) => {",
726
+ " switch (a.kind) {",
727
+ ` case "number": return /offset|skip|page|index/i.test(a.name) ? 0 : /limit|size|count|take|top|first/i.test(a.name) ? 20 : ${ARG_NUMBER};`,
728
+ ` case "string": return /cursor/i.test(a.name) ? undefined : /id$/i.test(a.name) ? "${ARG_ID}" : "${ARG_STRING}";`,
729
+ ' case "boolean": return false;',
730
+ ' case "date": return new Date();',
731
+ ' case "array": return [];',
732
+ ' case "undefined": return undefined;',
733
+ " default: return {};",
734
+ " }",
735
+ "};",
736
+ "const runTarget = async (t) => {",
737
+ ' const id = t.file + "#" + t.name;',
738
+ " try {",
739
+ ' const fn = req(path.join(cwd, t.module || t.file))[t.module ? "inline" : t.name];',
740
+ ' if (typeof fn !== "function") throw new Error("export is not a function");',
741
+ ` await Promise.race([caller.run(id, () => Promise.resolve(fn(...t.args.map(synth)))), new Promise((_, reject) => setTimeout(() => reject(new Error("timed out")), Number(process.env.SDK_RUNTIME_TARGET_TIMEOUT_MS) || ${SDK_RUNTIME_TARGET_TIMEOUT_MS}))]);`,
742
+ " return { file: t.file, name: t.name, inline: t.inline };",
743
+ " } catch (e) {",
744
+ ' const stack = String(e && e.stack || "").split("\\n").slice(0, 4).join(" ");',
745
+ ' const thrown = { message: String(e && e.message || e).slice(0, 200), fromSdk: stack.includes("node_modules/@wix"), afterRequests: sentBy.get(id) || 0 };',
746
+ " return { file: t.file, name: t.name, inline: t.inline, thrown };",
747
+ " }",
748
+ "};",
749
+ "(async () => {",
750
+ ' let ts, sdk; try { ts = req("typescript"); } catch (e) { return out({ skipped: "typescript is not installed" }); }',
751
+ ' try { sdk = req("@wix/sdk"); } catch (e) { return out({ skipped: "@wix/sdk is not installed" }); }',
752
+ ' for (const ext of [".ts", ".tsx"]) Module._extensions[ext] = (m, f) => {',
753
+ ' const js = ts.transpileModule(fs.readFileSync(f, "utf8"), { fileName: f, compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true } }).outputText;',
754
+ " m._compile(js, f);",
755
+ " };",
756
+ ' for (const ext of [".css", ".scss", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".woff", ".woff2"]) Module._extensions[ext] = (m) => { m.exports = {}; };',
757
+ // Also the elevated client: auth.elevate from @wix/essentials throws without one. Its requests
758
+ // reach the same broker, which sends them with the same site token.
759
+ ' try { const client = sdk.createClient({ modules: {}, auth: { getAuthHeaders: async () => ({ headers: { Authorization: "stub" } }) } }); client.enableContext("global"); client.enableContext("global", { elevated: true }); } catch (e) { return out({ skipped: "could not enable the SDK context: " + String(e && e.message || e).slice(0, 120) }); }',
760
+ " for (const t of targets) results.push(await runTarget(t));",
761
+ " return out({ results });",
762
+ "})();",
763
+ ].join("\n");
764
+
765
+ // What the runner asks the parent to fetch for a call in project code.
766
+ interface BrokeredRequest {
767
+ id: number;
768
+ target: string | null;
769
+ url: string;
770
+ method: string;
771
+ headers: [string, string][];
772
+ body?: string;
773
+ }
774
+
775
+ const READ_VERBS = new Set(["query", "search", "count", "list", "get"]);
776
+
777
+ function isReadRequest(url: string, method: string): boolean {
778
+ if (method.toUpperCase() === "GET") return true;
779
+ try {
780
+ return READ_VERBS.has(
781
+ new URL(url).pathname.split("/").filter(Boolean).pop() ?? "",
782
+ );
783
+ } catch {
784
+ return false;
785
+ }
786
+ }
787
+
788
+ // Opt-in: an update or delete aimed at the made-up id finds no entity, and the service checks
789
+ // the payload before it looks the entity up, so it is safe to send. PUT is never sent: it can
790
+ // be an upsert and would create the entity.
791
+ function isProbeWrite(
792
+ url: string,
793
+ method: string,
794
+ probeWrites: boolean,
795
+ ): boolean {
796
+ const verb = method.toUpperCase();
797
+ if (!probeWrites || (verb !== "PATCH" && verb !== "DELETE")) return false;
798
+ try {
799
+ return new URL(url).pathname.includes(ARG_ID);
800
+ } catch {
801
+ return false;
802
+ }
803
+ }
804
+
805
+ const LOCAL_ANSWER = {
806
+ status: 200,
807
+ text: "{}",
808
+ headers: [["content-type", "application/json"]],
809
+ };
810
+
811
+ // Sends a read the runner asked for, with the site token, to the Wix service only; answers
812
+ // everything else locally. Records every request it is asked for.
813
+ async function brokerRequest(
814
+ message: BrokeredRequest,
815
+ broker: { token: string; origin: string; probeWrites: boolean },
816
+ requests: SdkRecordedRequest[],
817
+ ): Promise<{ status: number; text: string; headers: string[][] }> {
818
+ const { target, url, method, body } = message;
819
+ const record: SdkRecordedRequest = { target, url, method, body };
820
+ const probe = isProbeWrite(url, method, broker.probeWrites);
821
+ if (probe) record.probe = true;
822
+ requests.push(record);
823
+ const isSent =
824
+ url.startsWith(broker.origin) && (isReadRequest(url, method) || probe);
825
+ if (!isSent) return LOCAL_ANSWER;
826
+ try {
827
+ const headers = new Headers(message.headers);
828
+ headers.set("Authorization", broker.token);
829
+ if (!headers.has("Content-Type"))
830
+ headers.set("Content-Type", "application/json");
831
+ const response = await fetch(url, {
832
+ method,
833
+ body,
834
+ headers,
835
+ signal: AbortSignal.timeout(SDK_RUNTIME_REQUEST_TIMEOUT_MS),
836
+ });
837
+ const text = await response.text();
838
+ record.status = response.status;
839
+ record.response = text.slice(0, 1500);
840
+ return { status: response.status, text, headers: [...response.headers] };
841
+ } catch (error) {
842
+ record.networkError = String(
843
+ error instanceof Error ? error.message : error,
844
+ ).slice(0, 120);
845
+ return LOCAL_ANSWER;
846
+ }
847
+ }
848
+
849
+ export interface SdkRecordedRequest {
850
+ target: string | null;
851
+ url: string;
852
+ method: string;
853
+ body?: string;
854
+ status?: number;
855
+ response?: string;
856
+ networkError?: string;
857
+ probe?: boolean;
858
+ }
859
+ export interface SdkTargetResult {
860
+ file: string;
861
+ name: string;
862
+ thrown?: { message: string; fromSdk: boolean; afterRequests: number };
863
+ inline?: boolean;
864
+ }
865
+
866
+ export function readApplicationError(response: string | undefined): {
867
+ code?: string;
868
+ message?: string;
869
+ } {
870
+ try {
871
+ const parsed = JSON.parse(response ?? "") as {
872
+ message?: string;
873
+ details?: {
874
+ applicationError?: { code?: string; description?: string };
875
+ validationError?: {
876
+ fieldViolations?: { field?: string; description?: string }[];
877
+ };
878
+ };
879
+ };
880
+ const violations = (parsed.details?.validationError?.fieldViolations ?? [])
881
+ .slice(0, 3)
882
+ .map((violation) => `${violation.field}: ${violation.description}`)
883
+ .join("; ");
884
+ return {
885
+ code: parsed.details?.applicationError?.code,
886
+ message:
887
+ violations ||
888
+ parsed.details?.applicationError?.description ||
889
+ parsed.message,
890
+ };
891
+ } catch {
892
+ return {};
893
+ }
894
+ }
895
+
896
+ // Placeholders the runner passes that carry no marker (`{}`, `[]`, `false`, a date, 0 or 20):
897
+ // a rejection of a request built from them cannot be pinned on the code.
898
+ export function passesUnmarkedPlaceholders(args: readonly SdkParam[]): boolean {
899
+ return args.some(
900
+ (arg) =>
901
+ ["object", "array", "boolean", "date"].includes(arg.kind) ||
902
+ (arg.kind === "number" &&
903
+ /offset|skip|page|index|limit|size|count|take|top|first/i.test(
904
+ arg.name,
905
+ )),
906
+ );
907
+ }
908
+
909
+ export type SdkVerdict =
910
+ | { kind: "fail"; reason?: string; missingApp?: boolean }
911
+ | { kind: "note"; reason: string }
912
+ | { kind: "ignore" };
913
+
914
+ function carriesMadeUpArgument(
915
+ request: SdkRecordedRequest,
916
+ markers: string[],
917
+ ): boolean {
918
+ return markers.some(
919
+ (marker) => request.url.includes(marker) || request.body?.includes(marker),
920
+ );
921
+ }
922
+
923
+ // A 401, 403 or 428: the site lacks the app, the token was refused, or permission is missing.
924
+ // eCommerce answers a bare 401 UNAUTHENTICATED when no app provides it, so there a 401 the token
925
+ // should not get is told apart from a refused token by the token probe.
926
+ function judgeAccess(
927
+ url: string,
928
+ status: number,
929
+ answer: string,
930
+ tokenValid: boolean | undefined,
931
+ ): SdkVerdict | undefined {
932
+ const missingApp = {
933
+ kind: "fail",
934
+ reason: "the site does not have the app this call needs",
935
+ missingApp: true,
936
+ } as const;
937
+ if (APP_NOT_INSTALLED.test(answer) && [401, 403, 428].includes(status))
938
+ return missingApp;
939
+ if (status === 401) {
940
+ if (!tokenValid)
941
+ return { kind: "note", reason: "the site token was refused" };
942
+ return BARE_401_MISSING_APP.test(pathOf(url))
943
+ ? {
944
+ ...missingApp,
945
+ reason: `${missingApp.reason}: its token works for other calls, but not this one`,
946
+ }
947
+ : {
948
+ kind: "note",
949
+ reason:
950
+ "refused for the site token, which works for other calls: the call may need a signed-in member or visitor",
951
+ };
952
+ }
953
+ if (status === 403)
954
+ return { kind: "note", reason: "permission denied for the site token" };
955
+ return undefined;
956
+ }
957
+
958
+ // What one rejected answer means. The runner passes made-up arguments, so a rejection fails
959
+ // only when it is about the shape of a query, about an app the site lacks, about a missing
960
+ // collection or route, or when nothing made up went into the request.
961
+ export function judgeRejection(
962
+ request: SdkRecordedRequest,
963
+ status: number,
964
+ code: string | undefined,
965
+ answer: string,
966
+ tokenValid?: boolean,
967
+ unmarkedPlaceholders = false,
968
+ ): SdkVerdict {
969
+ const access = judgeAccess(request.url, status, answer, tokenValid);
970
+ if (access) return access;
971
+ if (status >= 500)
972
+ return { kind: "note", reason: "service error, not the code's" };
973
+ if (status === 429) return { kind: "note", reason: "rate limited" };
974
+ if (code && QUERY_SHAPE_CODE.test(code)) return { kind: "fail" };
975
+ if (status === 404) {
976
+ if (MISSING_TARGET_404.test(answer)) return { kind: "fail" };
977
+ // A made-up id finds nothing, as expected.
978
+ return carriesMadeUpArgument(request, ARG_MARKERS)
979
+ ? { kind: "ignore" }
980
+ : { kind: "note", reason: "an entity the code names was not found" };
981
+ }
982
+ // A probed write is aimed at the made-up id on purpose, so the id says
983
+ // nothing about who is to blame for a rejected payload.
984
+ const markers = request.probe
985
+ ? ARG_MARKERS.filter((marker) => marker !== ARG_ID)
986
+ : ARG_MARKERS;
987
+ if (carriesMadeUpArgument(request, markers))
988
+ return { kind: "note", reason: "the request carries a made-up argument" };
989
+ return unmarkedPlaceholders
990
+ ? {
991
+ kind: "note",
992
+ reason: "the request was built from placeholder arguments",
993
+ }
994
+ : { kind: "fail" };
995
+ }
996
+
997
+ export interface SdkFinding {
998
+ // Stable across runs, so the plugin can count how often one finding blocked.
999
+ key: string;
1000
+ text: string;
1001
+ // The site lacks the app the call needs: no code change fixes it.
1002
+ missingApp?: boolean;
1003
+ }
1004
+
1005
+ const INLINE_TARGET_LINE = / at line \d+$/;
1006
+
1007
+ function pathOf(url: string): string {
1008
+ try {
1009
+ return new URL(url).pathname;
1010
+ } catch {
1011
+ return url; // a relative URL the code fetched itself
1012
+ }
1013
+ }
1014
+
1015
+ type Classified = { failing: SdkFinding[]; notes: string[] };
1016
+
1017
+ // One rejected answer, as a finding or a note; nothing for an answer that says nothing.
1018
+ function classifyRejection(
1019
+ request: SdkRecordedRequest & { status: number },
1020
+ tokenValid: boolean | undefined,
1021
+ unmarkedTargets: ReadonlySet<string>,
1022
+ into: Classified,
1023
+ ): void {
1024
+ const { status } = request;
1025
+ const target = request.target ?? "unknown";
1026
+ const { code, message } = readApplicationError(request.response);
1027
+ const text =
1028
+ `- ${target}: ${request.method} ${pathOf(request.url)} ` +
1029
+ `was rejected (${status}) ${[code, message].filter(Boolean).join(": ")}\n` +
1030
+ ` request body: ${request.body ?? "(none)"}`;
1031
+ const answer = `${code ?? ""} ${message ?? ""} ${request.response ?? ""}`;
1032
+ const verdict = judgeRejection(
1033
+ request,
1034
+ status,
1035
+ code,
1036
+ answer,
1037
+ tokenValid,
1038
+ unmarkedTargets.has(target),
1039
+ );
1040
+ // An inline read's name ends with its line, which moves as the file is edited; the key counts
1041
+ // how often a finding blocked, so it keeps only the read's number within the file.
1042
+ const keyTarget = target.replace(INLINE_TARGET_LINE, "");
1043
+ if (verdict.kind === "fail")
1044
+ into.failing.push({
1045
+ key: `${keyTarget}|${request.method}|${pathOf(request.url)}|${code ?? status}`,
1046
+ text: verdict.reason ? `${text}\n (${verdict.reason})` : text,
1047
+ ...(verdict.missingApp ? { missingApp: true } : {}),
1048
+ });
1049
+ else if (verdict.kind === "note")
1050
+ into.notes.push(`${text}\n (${verdict.reason})`);
1051
+ }
1052
+
1053
+ // A target that threw before sending anything.
1054
+ function classifyThrow(result: SdkTargetResult, into: Classified): void {
1055
+ const { file, name, thrown, inline } = result;
1056
+ if (!thrown || thrown.afterRequests > 0) return;
1057
+ const text = `- ${file}#${name}: threw before sending a request: ${thrown.message}`;
1058
+ // A call taken out of its component runs without the component around it, so a throw
1059
+ // before any request may come from that rather than from the code.
1060
+ if (inline)
1061
+ into.notes.push(
1062
+ `${text}\n (the call was taken out of its component to be run, so this may come from that)`,
1063
+ );
1064
+ else if (thrown.fromSdk && thrown.message !== "timed out")
1065
+ into.failing.push({ key: `${file}#${name}|threw`, text });
1066
+ else into.notes.push(`${text}\n (may come from a made-up argument)`);
1067
+ }
1068
+
1069
+ // Sorts what the runner saw into what fails validate and what is only worth a look. Every
1070
+ // answer that is not a success is a failure or a note, except a made-up id that finds nothing.
1071
+ export function classifySdkRuntime(
1072
+ output: {
1073
+ results?: SdkTargetResult[];
1074
+ requests?: SdkRecordedRequest[];
1075
+ },
1076
+ tokenValid?: boolean,
1077
+ unmarkedTargets: ReadonlySet<string> = new Set(),
1078
+ ): { failing: SdkFinding[]; notes: string[]; replayed: number } {
1079
+ const classified: Classified = { failing: [], notes: [] };
1080
+ const seen = new Set<string>();
1081
+ let replayed = 0;
1082
+ for (const request of output.requests ?? []) {
1083
+ if (request.networkError) {
1084
+ classified.notes.push(
1085
+ `- ${request.target ?? "unknown"}: ${request.method} ${pathOf(request.url)} could not be sent: ${request.networkError}`,
1086
+ );
1087
+ continue;
1088
+ }
1089
+ const { status } = request;
1090
+ if (status === undefined) continue;
1091
+ replayed += 1;
1092
+ const code = readApplicationError(request.response).code;
1093
+ const key = `${request.target}|${request.method}|${pathOf(request.url)}|${code ?? status}`;
1094
+ if (status < 400 || seen.has(key)) continue;
1095
+ seen.add(key);
1096
+ classifyRejection(
1097
+ { ...request, status },
1098
+ tokenValid,
1099
+ unmarkedTargets,
1100
+ classified,
1101
+ );
1102
+ }
1103
+ for (const result of output.results ?? []) classifyThrow(result, classified);
1104
+ return { ...classified, replayed };
1105
+ }
1106
+
1107
+ export async function listSdkSourceFiles(
1108
+ cwd: string,
1109
+ subdirectory = "",
1110
+ ): Promise<string[]> {
1111
+ const root = join(cwd, "src/extensions", subdirectory);
1112
+ let entries: string[];
1113
+ try {
1114
+ entries = await readdir(root, { recursive: true });
1115
+ } catch {
1116
+ return [];
1117
+ }
1118
+ return entries
1119
+ .filter(
1120
+ (entry) =>
1121
+ /\.tsx?$/.test(entry) &&
1122
+ !/\.d\.ts$|\.extension\.ts$|node_modules/.test(entry),
1123
+ )
1124
+ .map((entry) => join("src/extensions", subdirectory, entry))
1125
+ .sort();
1126
+ }
1127
+
1128
+ // Viewer code (components, contexts, page code) must not import `@wix/site-*`
1129
+ // host modules: they call `window.clientSdk`, which Studio 2 pages lack, so
1130
+ // every call rejects at runtime and nothing happens. Embedded scripts are the
1131
+ // exception, so they are not scanned.
1132
+ export async function findViewerHostModuleImports(
1133
+ ts: TypeScript,
1134
+ cwd: string,
1135
+ only?: ReadonlySet<string>,
1136
+ ): Promise<SdkFinding[]> {
1137
+ const violations: SdkFinding[] = [];
1138
+ for (const file of await listSdkSourceFiles(cwd, "site")) {
1139
+ // Embedded scripts get their client from the host modules. Site plugins are custom elements
1140
+ // the wix-app skill tells to read `viewMode()` from `@wix/site-window`, so failing them
1141
+ // would block code written as the skill says.
1142
+ if (file.includes("/embedded-scripts/") || file.includes("/site/plugins/"))
1143
+ continue;
1144
+ if (only && !only.has(file)) continue;
1145
+ const source = await readFile(join(cwd, file), "utf8").catch(() => "");
1146
+ const sourceFile = parseSource(ts, file, source);
1147
+ for (const statement of sourceFile.statements) {
1148
+ if (
1149
+ ts.isImportDeclaration(statement) &&
1150
+ ts.isStringLiteral(statement.moduleSpecifier) &&
1151
+ !statement.importClause?.isTypeOnly &&
1152
+ VIEWER_HOST_MODULE.test(statement.moduleSpecifier.text)
1153
+ )
1154
+ violations.push({
1155
+ key: `${file}|${statement.moduleSpecifier.text}`,
1156
+ text: `- ${file}: imports ${statement.moduleSpecifier.text}; host modules need window.clientSdk, which Studio 2 pages do not have, so every call rejects at runtime`,
1157
+ });
1158
+ }
1159
+ }
1160
+ return violations;
1161
+ }
1162
+
1163
+ const SDK_RUNTIME_TOTAL_TIMEOUT_MS = 90_000;
1164
+ // Time the runner gets, once told to stop, to report the targets that finished.
1165
+ const RUNNER_STOP_GRACE_MS = 2_000;
1166
+ const RUNNER_STDOUT_LIMIT = 16 * 1024 * 1024;
1167
+ // `wix token` can wait for a login or the network: it must not hold up validate.
1168
+ const SDK_RUNTIME_TOKEN_TIMEOUT_MS = 15_000;
1169
+
1170
+ export interface SdkRuntimeLimits {
1171
+ targetMs: number;
1172
+ totalMs: number;
1173
+ tokenMs?: number;
1174
+ }
1175
+ const DEFAULT_LIMITS: SdkRuntimeLimits = {
1176
+ targetMs: SDK_RUNTIME_TARGET_TIMEOUT_MS,
1177
+ totalMs: SDK_RUNTIME_TOTAL_TIMEOUT_MS,
1178
+ tokenMs: SDK_RUNTIME_TOKEN_TIMEOUT_MS,
1179
+ };
1180
+
1181
+ type Env = Record<string, string | undefined>;
1182
+
1183
+ // Studio 2 only (Studio 2 and Harmony sites).
1184
+ export function isSdkRuntimeCheckEnabled(env: Env): boolean {
1185
+ return env.CODEGEN_ENVIRONMENT === "STUDIO_2";
1186
+ }
1187
+
1188
+ async function run(
1189
+ file: string,
1190
+ args: string[],
1191
+ options: { cwd: string; env?: Env; timeout?: number },
1192
+ ): Promise<{ exitCode: number; stdout: string }> {
1193
+ try {
1194
+ const { stdout } = await execFileAsync(file, args, {
1195
+ ...options,
1196
+ maxBuffer: 16 * 1024 * 1024,
1197
+ });
1198
+ return { exitCode: 0, stdout };
1199
+ } catch (error) {
1200
+ const failed = error as { code?: unknown; stdout?: unknown };
1201
+ return {
1202
+ exitCode: typeof failed.code === "number" ? failed.code : 1,
1203
+ stdout: typeof failed.stdout === "string" ? failed.stdout : "",
1204
+ };
1205
+ }
1206
+ }
1207
+
1208
+ // The service to ask: the real one, or a local stand-in that tests serve.
1209
+ function apiOrigin(env: Env): string {
1210
+ const override = env.CODEGEN_SDK_RUNTIME_API_ORIGIN ?? "";
1211
+ return LOCAL_API_ORIGIN.test(override) ? override : WIX_API_ORIGIN;
1212
+ }
1213
+
1214
+ // A read every site can answer, to tell a refused token from a site that cannot serve one call.
1215
+ const TOKEN_PROBE_PATH = "site-properties/v4/properties";
1216
+
1217
+ async function tokenWorks(token: string, origin: string): Promise<boolean> {
1218
+ try {
1219
+ const response = await fetch(origin + TOKEN_PROBE_PATH, {
1220
+ headers: { Authorization: token },
1221
+ signal: AbortSignal.timeout(SDK_RUNTIME_REQUEST_TIMEOUT_MS),
1222
+ });
1223
+ return response.ok;
1224
+ } catch {
1225
+ return false;
1226
+ }
1227
+ }
1228
+
1229
+ async function getSdkRuntimeToken(
1230
+ cwd: string,
1231
+ env: Env,
1232
+ timeout: number,
1233
+ ): Promise<string | undefined> {
1234
+ const site = env.CODEGEN_METASITE_ID;
1235
+ const result = await run(
1236
+ "wix",
1237
+ ["token", ...(site ? ["--site", site] : []), "--json"],
1238
+ { cwd, env, timeout },
1239
+ );
1240
+ if (result.exitCode !== 0) return undefined;
1241
+ try {
1242
+ const { accessToken } = JSON.parse(result.stdout) as {
1243
+ accessToken?: string;
1244
+ };
1245
+ return accessToken || undefined;
1246
+ } catch {
1247
+ return undefined;
1248
+ }
1249
+ }
1250
+
1251
+ // With a list of changed files, only code a change can have affected is checked: the changed
1252
+ // files for what the source text shows, and also the files that import them, however far up,
1253
+ // for what running shows (a changed helper can break a function whose own file did not change).
1254
+ const LOCAL_EXTENSIONS = [".ts", ".tsx", "/index.ts", "/index.tsx"];
1255
+ // Specifiers that point into the project without a leading dot (tsconfig paths).
1256
+ const ALIAS_SPECIFIER = /^(?:@\/|~\/|#|src\/)/;
1257
+
1258
+ // Inputs every file depends on: a change to one can break calls in files that did not change.
1259
+ const GLOBAL_INPUT =
1260
+ /^(?:package\.json|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|tsconfig[\w.-]*\.json)$/;
1261
+
1262
+ export function normalizeChangedPaths(paths: readonly string[]): Set<string> {
1263
+ return new Set(
1264
+ paths
1265
+ .map((path) => posix.normalize(path.replaceAll("\\", "/")))
1266
+ .filter((path) => path && path !== "."),
1267
+ );
1268
+ }
1269
+
1270
+ function localSpecifiers(
1271
+ ts: TypeScript,
1272
+ file: string,
1273
+ source: string,
1274
+ aliases: readonly PathAlias[] = [],
1275
+ ): string[] {
1276
+ const specifiers: string[] = [];
1277
+ const visit = (node: import("typescript").Node): void => {
1278
+ if (
1279
+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
1280
+ node.moduleSpecifier &&
1281
+ ts.isStringLiteral(node.moduleSpecifier)
1282
+ )
1283
+ specifiers.push(node.moduleSpecifier.text);
1284
+ else if (
1285
+ ts.isCallExpression(node) &&
1286
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
1287
+ (ts.isIdentifier(node.expression) &&
1288
+ node.expression.text === "require")) &&
1289
+ node.arguments[0] &&
1290
+ ts.isStringLiteral(node.arguments[0])
1291
+ )
1292
+ specifiers.push(node.arguments[0].text);
1293
+ ts.forEachChild(node, visit);
1294
+ };
1295
+ visit(parseSource(ts, file, source));
1296
+ return specifiers.filter(
1297
+ (specifier) =>
1298
+ isSurelyLocal(specifier) ||
1299
+ aliases.some((alias) => specifier.startsWith(alias.prefix)),
1300
+ );
1301
+ }
1302
+
1303
+ // Relative, or one of the usual alias prefixes: never a package.
1304
+ const isSurelyLocal = (specifier: string): boolean =>
1305
+ specifier.startsWith(".") || ALIAS_SPECIFIER.test(specifier);
1306
+
1307
+ // `./helper` may name a folder: only a file counts, so `helper/index.ts` is found next.
1308
+ const isFile = (path: string): Promise<boolean> =>
1309
+ stat(path).then(
1310
+ (found) => found.isFile(),
1311
+ () => false,
1312
+ );
1313
+
1314
+ // One `compilerOptions.paths` entry of the project's tsconfig: `@/*` → `src/*`.
1315
+ interface PathAlias {
1316
+ prefix: string;
1317
+ suffix: string;
1318
+ targets: string[];
1319
+ }
1320
+
1321
+ // The project's own tsconfig `paths`, relative to the project; none when there is no
1322
+ // tsconfig or it cannot be read.
1323
+ function readPathAliases(ts: TypeScript, cwd: string): PathAlias[] {
1324
+ const { config } = ts.readConfigFile(
1325
+ join(cwd, "tsconfig.json"),
1326
+ ts.sys.readFile,
1327
+ );
1328
+ if (!config) return [];
1329
+ // Resolves `extends`, so `paths` set in a base config count too.
1330
+ const { options } = ts.parseJsonConfigFileContent(config, ts.sys, cwd);
1331
+ // `paths` are relative to `baseUrl`, or without one to the config that set them.
1332
+ const base =
1333
+ options.baseUrl ??
1334
+ (options as { pathsBasePath?: string }).pathsBasePath ??
1335
+ cwd;
1336
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => {
1337
+ const [prefix = "", suffix = ""] = pattern.split("*");
1338
+ return {
1339
+ prefix,
1340
+ suffix,
1341
+ targets: targets.map((target) =>
1342
+ posix.relative(
1343
+ cwd.replaceAll("\\", "/"),
1344
+ posix.join(base.replaceAll("\\", "/"), target),
1345
+ ),
1346
+ ),
1347
+ };
1348
+ });
1349
+ }
1350
+
1351
+ // The project file a local specifier points to: undefined when nothing is there.
1352
+ async function resolveLocal(
1353
+ cwd: string,
1354
+ from: string,
1355
+ specifier: string,
1356
+ aliases: readonly PathAlias[] = [],
1357
+ ): Promise<string | undefined> {
1358
+ const bases = specifier.startsWith(".")
1359
+ ? [posix.join(posix.dirname(from), specifier)]
1360
+ : aliases
1361
+ .filter(
1362
+ (alias) =>
1363
+ specifier.startsWith(alias.prefix) &&
1364
+ specifier.endsWith(alias.suffix),
1365
+ )
1366
+ .flatMap((alias) => {
1367
+ const star = specifier.slice(
1368
+ alias.prefix.length,
1369
+ specifier.length - alias.suffix.length,
1370
+ );
1371
+ return alias.targets.map((target) => target.replace("*", star));
1372
+ });
1373
+ for (const base of bases.map((path) => posix.normalize(path))) {
1374
+ const bare = base.replace(/\.(?:[cm]?js|jsx)$/, "");
1375
+ for (const candidate of [
1376
+ base,
1377
+ ...LOCAL_EXTENSIONS.map((extension) => bare + extension),
1378
+ ])
1379
+ if (await isFile(join(cwd, candidate))) return candidate;
1380
+ }
1381
+ return undefined;
1382
+ }
1383
+
1384
+ // Whether `file` is, or imports (directly or not), a changed file. An import that cannot
1385
+ // be followed counts as changed: it is safer to run the importer than to skip it.
1386
+ async function dependsOnChanged(
1387
+ ts: TypeScript,
1388
+ cwd: string,
1389
+ file: string,
1390
+ changed: ReadonlySet<string>,
1391
+ known: Map<string, boolean>,
1392
+ aliases: readonly PathAlias[] = [],
1393
+ ): Promise<boolean> {
1394
+ const seen = new Set<string>();
1395
+ const walk = async (current: string): Promise<boolean> => {
1396
+ if (changed.has(current)) return true;
1397
+ if (known.get(current)) return true;
1398
+ if (seen.has(current) || !/\.[cm]?[jt]sx?$/.test(current)) return false;
1399
+ seen.add(current);
1400
+ const source = await readFile(join(cwd, current), "utf8").catch(() => "");
1401
+ for (const specifier of localSpecifiers(ts, current, source, aliases)) {
1402
+ const target = await resolveLocal(cwd, current, specifier, aliases);
1403
+ // Nothing there: a deleted file or an alias it cannot follow. Matched only by a configured
1404
+ // alias (`*` matches everything), it is a package.
1405
+ if (target === undefined) {
1406
+ if (isSurelyLocal(specifier)) return true;
1407
+ continue;
1408
+ }
1409
+ if (await walk(target)) return true;
1410
+ }
1411
+ return false;
1412
+ };
1413
+ const result = await walk(file);
1414
+ if (result) known.set(file, true);
1415
+ return result;
1416
+ }
1417
+
1418
+ // What the source text of one changed file shows about calls the check cannot run.
1419
+ function callSiteFinding(
1420
+ ts: TypeScript,
1421
+ file: string,
1422
+ source: string,
1423
+ extractedLines: ReadonlySet<number>,
1424
+ into: Classified,
1425
+ ): void {
1426
+ const { handlerFile, unrunLines } = findSdkCallSites(ts, file, source);
1427
+ const rest = unrunLines.filter((line) => !extractedLines.has(line));
1428
+ if (rest.length === 0) return;
1429
+ const where = `${file}:${rest.slice(0, 5).join(", ")}`;
1430
+ if (handlerFile)
1431
+ into.failing.push({
1432
+ key: `${file}|bare-call`,
1433
+ text: `- ${where}: a bare SDK call in an event handler or service plugin. There is no visitor or member session there, so it throws; wrap the call in auth.elevate from @wix/essentials`,
1434
+ });
1435
+ else
1436
+ into.notes.push(
1437
+ `- ${where}: an SDK call this check cannot run (for example a write, or a call that uses a local function), so it was not checked. Nothing needs to change because of this note`,
1438
+ );
1439
+ }
1440
+
1441
+ // The exported async functions of one file, and the reads it takes out of its components.
1442
+ function targetsOfFile(
1443
+ ts: TypeScript,
1444
+ cwd: string,
1445
+ file: string,
1446
+ source: string,
1447
+ aliases: readonly PathAlias[] = [],
1448
+ ): { targets: SdkTarget[]; extractedLines: Set<number> } {
1449
+ const inline =
1450
+ INLINE_SCOPE.test(file) && !file.includes("/embedded-scripts/")
1451
+ ? extractInlineReads(ts, cwd, file, source, aliases)
1452
+ : [];
1453
+ return {
1454
+ targets: [
1455
+ ...findSdkTargets(ts, file, source),
1456
+ ...inline.map((read, index) => ({
1457
+ file,
1458
+ // Numbered within the file, so each read has its own name (the plugin counts targets by
1459
+ // name) and its finding key survives edits that move its line.
1460
+ name: `inline call ${index + 1} at line ${read.line}`,
1461
+ args: read.params,
1462
+ wrapper: read.wrapper,
1463
+ inline: true,
1464
+ })),
1465
+ ],
1466
+ extractedLines: new Set(inline.map((read) => read.line)),
1467
+ };
1468
+ }
1469
+
1470
+ // The targets to run, and what the source text alone already tells: viewer host modules,
1471
+ // bare calls in event handlers and service plugins, calls that cannot be run from outside.
1472
+ async function scanSdkSources(
1473
+ ts: TypeScript,
1474
+ cwd: string,
1475
+ changed?: ReadonlySet<string>,
1476
+ ): Promise<
1477
+ Classified & {
1478
+ targets: SdkTarget[];
1479
+ targetsTotal: number;
1480
+ aliases: PathAlias[];
1481
+ }
1482
+ > {
1483
+ // What the source text alone shows is about one file, so only changed files are read for it.
1484
+ const found: Classified = {
1485
+ failing: await findViewerHostModuleImports(ts, cwd, changed),
1486
+ notes: [],
1487
+ };
1488
+ const targets: SdkTarget[] = [];
1489
+ let targetsTotal = 0;
1490
+ const known = new Map<string, boolean>();
1491
+ const aliases = readPathAliases(ts, cwd);
1492
+ for (const file of await listSdkSourceFiles(cwd)) {
1493
+ const source = await readFile(join(cwd, file), "utf8").catch(() => "");
1494
+ const ofFile = targetsOfFile(ts, cwd, file, source, aliases);
1495
+ targetsTotal += ofFile.targets.length;
1496
+ const affected =
1497
+ ofFile.targets.length > 0 &&
1498
+ (!changed ||
1499
+ (await dependsOnChanged(ts, cwd, file, changed, known, aliases)));
1500
+ if (affected) targets.push(...ofFile.targets);
1501
+ if (!changed || changed.has(file))
1502
+ callSiteFinding(ts, file, source, ofFile.extractedLines, found);
1503
+ }
1504
+ return { ...found, targets, targetsTotal, aliases };
1505
+ }
1506
+
1507
+ type RunnerOutput = {
1508
+ skipped?: string;
1509
+ results?: SdkTargetResult[];
1510
+ // Stopped at the total limit: `results` holds only the targets that finished.
1511
+ partial?: boolean;
1512
+ requests?: SdkRecordedRequest[];
1513
+ };
1514
+
1515
+ // The project code the runner loads sees only what it needs to run, not the secrets of the
1516
+ // process that runs the check.
1517
+ const RUNNER_ENV =
1518
+ /^(?:PATH|HOME|TMPDIR|TMP|TEMP|LANG|LC_\w+|TZ|NODE_\w+|SystemRoot)$/;
1519
+
1520
+ function runnerEnv(env: Env): Env {
1521
+ return Object.fromEntries(
1522
+ Object.entries(env).filter(([name]) => RUNNER_ENV.test(name)),
1523
+ );
1524
+ }
1525
+
1526
+ // Wrappers go under the project's node_modules, so their package imports resolve the way the
1527
+ // page's do and git does not see them; the caller removes the folder when the run ends.
1528
+ async function writeWrappers(
1529
+ cwd: string,
1530
+ targets: SdkTarget[],
1531
+ wrapperDir: string,
1532
+ ): Promise<void> {
1533
+ const wrapped = targets.filter((target) => target.wrapper);
1534
+ if (wrapped.length === 0) return;
1535
+ await mkdir(join(cwd, wrapperDir), { recursive: true });
1536
+ for (const [index, target] of wrapped.entries()) {
1537
+ target.module = `${wrapperDir}/inline-${index}.tsx`;
1538
+ await writeFile(join(cwd, target.module), target.wrapper ?? "");
1539
+ }
1540
+ }
1541
+
1542
+ function readRunnerOutput(stdout: string): RunnerOutput | undefined {
1543
+ const marked = stdout
1544
+ .split("\n")
1545
+ .reverse()
1546
+ .find((entry) => entry.startsWith(SDK_RUNTIME_MARKER));
1547
+ // The runner prints this line itself, from JSON.stringify of this shape.
1548
+ return marked
1549
+ ? (JSON.parse(marked.slice(SDK_RUNTIME_MARKER.length)) as RunnerOutput)
1550
+ : undefined;
1551
+ }
1552
+
1553
+ // Runs the runner with an IPC channel and brokers its requests until it exits or the limit
1554
+ // passes; resolves with what it printed.
1555
+ function forkRunner(
1556
+ runnerPath: string,
1557
+ args: string[],
1558
+ options: { cwd: string; env: Env; timeout: number },
1559
+ broker: { token: string; origin: string; probeWrites: boolean },
1560
+ requests: SdkRecordedRequest[],
1561
+ ): Promise<string> {
1562
+ return new Promise((done) => {
1563
+ const child = fork(runnerPath, args, {
1564
+ cwd: options.cwd,
1565
+ env: options.env,
1566
+ execArgv: [],
1567
+ stdio: ["ignore", "pipe", "ignore", "ipc"],
1568
+ });
1569
+ let stdout = "";
1570
+ // Project code may print without end: past the limit the runner is stopped, and with no
1571
+ // report the check is skipped.
1572
+ child.stdout?.on("data", (chunk: Buffer) => {
1573
+ stdout += chunk.toString();
1574
+ if (stdout.length > RUNNER_STDOUT_LIMIT) {
1575
+ stdout = "";
1576
+ child.kill("SIGKILL");
1577
+ }
1578
+ });
1579
+ child.on("message", (message: BrokeredRequest) => {
1580
+ brokerRequest(message, broker, requests).then(
1581
+ (answer) =>
1582
+ child.connected && child.send({ id: message.id, ...answer }),
1583
+ () => undefined,
1584
+ );
1585
+ });
1586
+ // At the limit the runner is asked to report what finished, then stopped.
1587
+ let kill: NodeJS.Timeout | undefined;
1588
+ const timer = setTimeout(() => {
1589
+ child.kill("SIGTERM");
1590
+ kill = setTimeout(() => child.kill("SIGKILL"), RUNNER_STOP_GRACE_MS);
1591
+ }, options.timeout);
1592
+ const finish = () => {
1593
+ clearTimeout(timer);
1594
+ clearTimeout(kill);
1595
+ done(stdout);
1596
+ };
1597
+ // `close`, not `exit`: the last output can still be on its way when the process exits.
1598
+ child.on("close", finish);
1599
+ child.on("error", finish);
1600
+ });
1601
+ }
1602
+
1603
+ // Runs the targets in a child node inside the project; undefined when the runner printed
1604
+ // no report.
1605
+ async function runSdkRunner(
1606
+ cwd: string,
1607
+ targets: SdkTarget[],
1608
+ token: string,
1609
+ env: Env,
1610
+ limits: SdkRuntimeLimits,
1611
+ aliases: readonly PathAlias[] = [],
1612
+ ): Promise<RunnerOutput | undefined> {
1613
+ const scratch = await mkdtemp(join(tmpdir(), "sdk-runtime-"));
1614
+ const wrapperDir = `node_modules/.sdk-runtime-inline-${process.pid}-${Date.now()}`;
1615
+ try {
1616
+ await writeWrappers(cwd, targets, wrapperDir);
1617
+ const runnerPath = join(scratch, "runner.cjs");
1618
+ const targetsPath = join(scratch, "targets.json");
1619
+ await writeFile(runnerPath, SDK_RUNTIME_RUNNER);
1620
+ await writeFile(targetsPath, JSON.stringify(targets));
1621
+ const requests: SdkRecordedRequest[] = [];
1622
+ const stdout = await forkRunner(
1623
+ runnerPath,
1624
+ [cwd, targetsPath],
1625
+ {
1626
+ cwd,
1627
+ timeout: limits.totalMs,
1628
+ env: {
1629
+ ...runnerEnv(env),
1630
+ SDK_RUNTIME_TARGET_TIMEOUT_MS: String(limits.targetMs),
1631
+ SDK_RUNTIME_PATH_ALIASES: JSON.stringify(aliases),
1632
+ // Not a secret: the service the runner's requests go to (a local stand-in in tests).
1633
+ SDK_RUNTIME_API_ORIGIN: apiOrigin(env),
1634
+ },
1635
+ },
1636
+ {
1637
+ token,
1638
+ origin: apiOrigin(env),
1639
+ probeWrites: env.CODEGEN_SDK_RUNTIME_PROBE_WRITES === "1",
1640
+ },
1641
+ requests,
1642
+ );
1643
+ const output = readRunnerOutput(stdout);
1644
+ return output && { ...output, requests };
1645
+ } finally {
1646
+ await rm(scratch, { recursive: true, force: true });
1647
+ await rm(join(cwd, wrapperDir), { recursive: true, force: true });
1648
+ }
1649
+ }
1650
+
1651
+ export interface SdkRuntimeReport {
1652
+ // One line for the validate output; empty when the check is switched off.
1653
+ line: string;
1654
+ failing: SdkFinding[];
1655
+ notes: string[];
1656
+ // Some targets were left out over the limit: the plugin must not count this check as clean,
1657
+ // and passes `ran` back so the next check runs the ones left out.
1658
+ capped?: boolean;
1659
+ ran?: string[];
1660
+ }
1661
+
1662
+ function skippedReport(reason: string, found?: Classified): SdkRuntimeReport {
1663
+ const failing = found?.failing ?? [];
1664
+ return {
1665
+ line: failing.length
1666
+ ? `SDK runtime check: FAILED (${failing.length} issue(s))`
1667
+ : `SDK runtime check: skipped (${reason})`,
1668
+ failing,
1669
+ notes: found?.notes ?? [],
1670
+ };
1671
+ }
1672
+
1673
+ function reportLine(
1674
+ isFailing: boolean,
1675
+ replayed: number,
1676
+ counts: { run: number; affected: number; total: number; ranBefore: number },
1677
+ ): string {
1678
+ const { run, affected, total, ranBefore } = counts;
1679
+ const scope =
1680
+ run + ranBefore < affected
1681
+ ? `, ${run} of ${affected} changed targets run, the rest over the limit of ${SDK_RUNTIME_MAX_TARGETS} targets or ${SDK_RUNTIME_TOTAL_TIMEOUT_MS / 1000} s run next time`
1682
+ : ranBefore > 0
1683
+ ? `, ${run} of ${affected} changed targets run, the rest in the checks before`
1684
+ : run < total
1685
+ ? `, ${run} of ${total} targets run, the rest unchanged`
1686
+ : "";
1687
+ return `SDK runtime check: ${isFailing ? "FAILED" : "OK"} (${replayed} request(s) sent${scope})`;
1688
+ }
1689
+
1690
+ // Runs the targets and sorts what came back, added to what the source scan already found.
1691
+ async function runAndClassify(
1692
+ cwd: string,
1693
+ scan: Awaited<ReturnType<typeof scanSdkSources>>,
1694
+ token: string,
1695
+ env: Env,
1696
+ limits: SdkRuntimeLimits,
1697
+ alreadyRan: ReadonlySet<string>,
1698
+ ): Promise<SdkRuntimeReport> {
1699
+ const idOf = (target: SdkTarget) => `${target.file}#${target.name}`;
1700
+ // Over the limit, the targets earlier checks ran cleanly wait their turn.
1701
+ const pool = scan.targets.filter((target) => !alreadyRan.has(idOf(target)));
1702
+ const targets = pool.slice(0, SDK_RUNTIME_MAX_TARGETS);
1703
+ const output = await runSdkRunner(
1704
+ cwd,
1705
+ targets,
1706
+ token,
1707
+ env,
1708
+ limits,
1709
+ scan.aliases,
1710
+ );
1711
+ if (!output) return skippedReport("runner failed", scan);
1712
+ if (output.skipped) return skippedReport(output.skipped, scan);
1713
+ const refused = output.requests?.some((request) => request.status === 401);
1714
+ const unmarked = new Set(
1715
+ targets
1716
+ .filter((target) => passesUnmarkedPlaceholders(target.args))
1717
+ .map(idOf),
1718
+ );
1719
+ const tokenValid = refused
1720
+ ? await tokenWorks(token, apiOrigin(env))
1721
+ : undefined;
1722
+ const classified = classifySdkRuntime(output, tokenValid, unmarked);
1723
+ const failing = [...scan.failing, ...classified.failing];
1724
+ // Stopped at the total limit, the targets that did not finish wait like those over the cap.
1725
+ const finished = new Set(
1726
+ (output.results ?? []).map((result) => `${result.file}#${result.name}`),
1727
+ );
1728
+ const ran = output.partial
1729
+ ? targets.filter((target) => finished.has(idOf(target)))
1730
+ : targets;
1731
+ const capped = pool.length > ran.length;
1732
+ return {
1733
+ line: reportLine(failing.length > 0, classified.replayed, {
1734
+ run: ran.length,
1735
+ affected: scan.targets.length,
1736
+ total: scan.targetsTotal,
1737
+ ranBefore: scan.targets.length - pool.length,
1738
+ }),
1739
+ failing,
1740
+ notes: [...scan.notes, ...classified.notes],
1741
+ ...(capped ? { capped: true, ran: ran.map(idOf) } : {}),
1742
+ };
1743
+ }
1744
+
1745
+ export async function checkSdkRuntime(
1746
+ cwd: string,
1747
+ env: Env = process.env,
1748
+ limits: SdkRuntimeLimits = DEFAULT_LIMITS,
1749
+ changedPaths?: readonly string[],
1750
+ alreadyRan: readonly string[] = [],
1751
+ ): Promise<SdkRuntimeReport> {
1752
+ if (!isSdkRuntimeCheckEnabled(env))
1753
+ return { line: "", failing: [], notes: [] };
1754
+ try {
1755
+ const ts = loadTypeScript(cwd);
1756
+ if (!ts) return skippedReport("no typescript");
1757
+ const normalized = changedPaths && normalizeChangedPaths(changedPaths);
1758
+ const changed =
1759
+ normalized && [...normalized].some((path) => GLOBAL_INPUT.test(path))
1760
+ ? undefined
1761
+ : normalized;
1762
+ const scan = await scanSdkSources(ts, cwd, changed);
1763
+ if (scan.targetsTotal === 0)
1764
+ return skippedReport("no SDK calls it can run", scan);
1765
+ if (scan.targets.length === 0)
1766
+ return skippedReport("no changed SDK code", scan);
1767
+ const tokenMs = limits.tokenMs ?? SDK_RUNTIME_TOKEN_TIMEOUT_MS;
1768
+ const token = await getSdkRuntimeToken(cwd, env, tokenMs);
1769
+ if (!token) return skippedReport("no site token", scan);
1770
+ return await runAndClassify(
1771
+ cwd,
1772
+ scan,
1773
+ token,
1774
+ env,
1775
+ limits,
1776
+ new Set(alreadyRan),
1777
+ );
1778
+ } catch {
1779
+ return skippedReport("could not run");
1780
+ }
1781
+ }
1782
+
1783
+ // Compared by real path: the script may be reached through a symlink (/var on macOS).
1784
+ function isRunDirectly(): boolean {
1785
+ if (!process.argv[1]) return false;
1786
+ try {
1787
+ return (
1788
+ realpathSync(fileURLToPath(import.meta.url)) ===
1789
+ realpathSync(resolve(process.argv[1]))
1790
+ );
1791
+ } catch {
1792
+ return false;
1793
+ }
1794
+ }
1795
+
1796
+ // `node sdk-runtime-check.ts <project dir> [--changed <path>...] [--ran-file <file>]` prints
1797
+ // the report as one JSON line. Without `--changed` everything is checked; with it, only what
1798
+ // those files affect.
1799
+ // `--ran-file` names a file listing, one per line, the targets (`file#name`) earlier capped
1800
+ // checks ran cleanly. A file that cannot be read lists none.
1801
+ function parseArgs(args: readonly string[]): {
1802
+ dir: string;
1803
+ changed?: string[];
1804
+ ran: string[];
1805
+ } {
1806
+ const lists: Record<string, string[]> = {};
1807
+ let list: string[] | undefined;
1808
+ for (const arg of args.slice(1)) {
1809
+ if (arg === "--changed" || arg === "--ran-file") list = lists[arg] = [];
1810
+ else list?.push(arg);
1811
+ }
1812
+ return {
1813
+ dir: args[0] ?? process.cwd(),
1814
+ changed: lists["--changed"],
1815
+ ran: readRanFile(lists["--ran-file"]?.[0]),
1816
+ };
1817
+ }
1818
+
1819
+ function readRanFile(path: string | undefined): string[] {
1820
+ if (!path) return [];
1821
+ try {
1822
+ return readFileSync(path, "utf8").split("\n").filter(Boolean);
1823
+ } catch {
1824
+ return [];
1825
+ }
1826
+ }
1827
+
1828
+ if (isRunDirectly()) {
1829
+ const { dir, changed, ran } = parseArgs(process.argv.slice(2));
1830
+ checkSdkRuntime(resolve(dir), process.env, DEFAULT_LIMITS, changed, ran).then(
1831
+ (report) => process.stdout.write(`${JSON.stringify(report)}\n`),
1832
+ () => process.exit(2),
1833
+ );
1834
+ }