Repository navigation
Expand file tree
/
Copy pathjavascriptSemanticDataEffects.ts
More file actions
733 lines (711 loc) · 28 KB
/
Copy pathjavascriptSemanticDataEffects.ts
File metadata and controls
733 lines (711 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
import * as t from "@babel/types";
import type {
JavaScriptSemanticBoundaryOperation,
JavaScriptSemanticCallable,
JavaScriptSemanticConfigurationOperation,
JavaScriptSemanticRequestOperation,
} from "./javascriptSemanticIr.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import {
javaScriptExpressionWrapperTarget,
readExactJavaScriptLiteral,
semanticStaticPropertyKey,
staticObjectProperty,
semanticStaticPropertyName,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import {
recordSemanticValueLimit,
resolveSemanticBindingState,
semanticResolutionBlocked,
semanticStableInitializer,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticBindingState,
} from "./javascriptSemanticState.js";
import {
semanticBindingAtRead,
semanticEffectTiming,
} from "./javascriptSemanticMutationInitializers.js";
import {
builtinDataEffectIdentity,
dataEffectArgumentBindingId as argumentBindingId,
dataEffectLiteralString as literalString,
dataEffectMemberCallee as memberCallee,
semanticProcessObjectIdentity,
outerDataEffectBinding as outerAssignedBinding,
assignedSemanticResultBindings,
semanticProjectedBindingFacts,
traverseDataEffects as traverseWithContext,
type DataEffectTraversalContext as TraversalContext,
} from "./javascriptSemanticDataEffectHelpers.js";
import { isUnmodifiedGlobalReference } from "./javascriptSemanticAmbientWrites.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import { semanticPrimitiveSet } from "./javascriptSemanticPrimitives.js";
import type { JavaScriptSemanticValue } from "./javascriptSemanticValueTypes.js";
interface DataEffectAnalysis {
readonly configurationOperations: readonly JavaScriptSemanticConfigurationOperation[];
readonly requestOperations: readonly JavaScriptSemanticRequestOperation[];
readonly boundaryOperations: readonly JavaScriptSemanticBoundaryOperation[];
}
interface ConfigurationCandidate {
readonly node: t.Node;
readonly operation: JavaScriptSemanticConfigurationOperation;
}
interface RequestCandidate {
readonly node: t.CallExpression | t.OptionalCallExpression | t.NewExpression;
readonly operation: JavaScriptSemanticRequestOperation;
}
/** Recover configuration, request, and boundary candidates from inert syntax. */
export const collectJavaScriptSemanticDataEffects = (
program: t.Program,
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
): DataEffectAnalysis => {
const context: TraversalContext = {
state,
callableIds: new Set(callables.map(({ callableId }) => callableId)),
callableStack: [],
ancestors: [],
};
const configuration = collectConfigurations(program, context);
const requests = collectRequests(program, context);
return {
configurationOperations: [
...configuration.map(({ operation }) => operation),
...collectDefaults(program, context, configuration),
],
requestOperations: [
...requests.map(({ operation }) => operation),
...collectResponseConsumers(program, context, requests),
],
boundaryOperations: collectBoundaries(program, context),
};
};
const collectConfigurations = (
program: t.Program,
context: TraversalContext,
): ConfigurationCandidate[] => {
const output: ConfigurationCandidate[] = [];
traverseWithContext(program, context, (node) => {
const details = configurationDetails(node, context);
if (details === null) return;
const operation: JavaScriptSemanticConfigurationOperation = {
configId: `config:${details.kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
kind: details.kind,
location: range(node),
ownerCallableId: context.callableStack.at(-1) ?? null,
resultBindingId: outerAssignedBinding(node, context),
key: details.key,
sourceConfigId: null,
value: null,
...(details.builtinAuthority === undefined
? {}
: { builtinAuthority: details.builtinAuthority }),
resolution: details.resolution,
};
output.push({ node, operation });
});
return output;
};
const configurationDetails = (
node: t.Node,
context: TraversalContext,
): {
readonly kind: "environment" | "argv" | "file";
readonly key: string | null;
readonly builtinAuthority?: "candidate";
readonly resolution: "complete" | "partial";
} | null => {
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
const processMember = processConfigurationMember(node, context.state);
if (processMember !== null) return processMember;
}
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node))
return null;
const fs = builtinDataEffectIdentity(node.callee, context.state, [
"fs",
"node:fs",
]);
const fsMethod = fs?.path.length === 1 ? fs.path[0] : null;
const promises =
fsMethod === null
? builtinDataEffectIdentity(node.callee, context.state, [
"fs/promises",
"node:fs/promises",
])
: null;
const isFileRead =
fsMethod === "readFile" ||
fsMethod === "readFileSync" ||
(fsMethod === null &&
promises?.path.length === 1 &&
promises.path[0] === "readFile");
return isFileRead
? {
kind: "file",
key: literalString(node.arguments[0]),
...((fsMethod === null ? promises : fs)?.builtinAuthority ===
"candidate"
? { builtinAuthority: "candidate" as const }
: {}),
resolution:
literalString(node.arguments[0]) === null ? "partial" : "complete",
}
: null;
};
const processConfigurationMember = (
node: t.MemberExpression | t.OptionalMemberExpression,
state: JavaScriptSemanticAnalysisState,
): {
readonly kind: "environment" | "argv";
readonly key: string | null;
readonly builtinAuthority?: "candidate";
readonly resolution: "complete" | "partial";
} | null => {
const object = node.object;
if (!t.isMemberExpression(object) && !t.isOptionalMemberExpression(object))
return null;
const family = semanticStaticPropertyName(object.property, object.computed);
if (family !== "env" && family !== "argv") return null;
// `process.env[""]` names an exact (empty) key; only a dynamic key is unknown.
const key = semanticStaticPropertyKey(node.property, node.computed);
if (family === "argv" && key !== null && !isArrayIndexKey(key)) return null;
const processIdentity = semanticProcessObjectIdentity(
object.object,
state,
family,
key,
);
if (processIdentity === null) return null;
return {
kind: family === "env" ? "environment" : "argv",
key,
...(processIdentity.builtinAuthority === undefined
? {}
: { builtinAuthority: processIdentity.builtinAuthority }),
resolution: key === null ? "partial" : "complete",
};
};
const isArrayIndexKey = (key: string): boolean => {
if (!/^(?:0|[1-9][0-9]*)$/u.test(key)) return false;
const index = Number(key);
return Number.isSafeInteger(index) && index < 2 ** 32 - 1;
};
const collectDefaults = (
program: t.Program,
context: TraversalContext,
configurations: readonly ConfigurationCandidate[],
): JavaScriptSemanticConfigurationOperation[] => {
const output: JavaScriptSemanticConfigurationOperation[] = [];
const configurationsByNode = new Map(
configurations.map((candidate) => [candidate.node, candidate]),
);
traverseWithContext(program, context, (node) => {
if (
!t.isLogicalExpression(node) ||
(node.operator !== "??" && node.operator !== "||")
)
return;
const source = unwrapJavaScriptExpression(node.left).node;
const candidate = configurationsByNode.get(source);
if (candidate === undefined) return;
const literal = readExactJavaScriptLiteral(node.right);
const value: JavaScriptSemanticValue = literal.found
? semanticPrimitiveSet([literal.value])
: { status: "unknown", reason: "Default is not an exact primitive." };
recordSemanticValueLimit(context.state, value);
output.push({
configId: `config:default:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
kind: "default",
location: range(node.right),
ownerCallableId: context.callableStack.at(-1) ?? null,
resultBindingId: outerAssignedBinding(node, context),
key: candidate.operation.key,
...(candidate.operation.builtinAuthority === undefined
? {}
: { builtinAuthority: candidate.operation.builtinAuthority }),
sourceConfigId: candidate.operation.configId,
value: value.status === "literal" ? value.value : null,
...(value.status === "unknown" && value.resourceLimit !== undefined
? { valueResourceLimit: value.resourceLimit }
: {}),
resolution: value.status === "literal" ? "complete" : "partial",
});
});
return output;
};
const collectRequests = (
program: t.Program,
context: TraversalContext,
): RequestCandidate[] => {
const output: RequestCandidate[] = [];
traverseWithContext(program, context, (node) => {
if (
!t.isCallExpression(node) &&
!t.isOptionalCallExpression(node) &&
!t.isNewExpression(node)
)
return;
const identity = requestMethod(node, context.state);
if (identity === null) return;
const method = identity.method;
const endpoint = requestEndpoint(node);
// `http.get`/`http.request` parse a string target with `new URL` before the
// request exists, so a literal that is not an absolute URL throws
// `ERR_INVALID_URL` synchronously — an options object cannot rescue it.
// `fetch` and `WebSocket` are host globals a browser resolves against the
// document URL, so their spellings stay as reported.
if (
endpoint !== null &&
(method === "get" || method === "request") &&
!URL.canParse(endpoint)
)
return;
// `http`/`https` validate `options.method` with `checkIsHttpToken` before the request
// exists, so a literal outside the token set throws from the call itself.
if (rejectsHttpMethodLiteral(node, method)) return;
output.push({
node,
operation: {
requestId: `request:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
kind: "request",
method,
...(identity.builtinAuthority === undefined
? {}
: { builtinAuthority: identity.builtinAuthority }),
location: range(node),
ownerCallableId: context.callableStack.at(-1) ?? null,
resultBindingId: outerAssignedBinding(node, context),
projectedResultBindings: semanticProjectedBindingFacts(
assignedSemanticResultBindings(
node,
context.ancestors,
context.state,
).filter(({ projectionPath }) => projectionPath.length > 0),
),
linkedRequestIds: [],
endpoint,
fields: requestFields(node, method, context.state),
resolution: endpoint === null ? "partial" : "complete",
},
});
});
return output;
};
/**
* Any other write (assignment, update, loop or destructuring target) can
* replace the response before this read. A sole write that can be skipped or
* runs after the read leaves an incoming value possible.
*/
const soleWriteReachesRead = (
binding: JavaScriptSemanticBindingState | undefined,
read: t.Node,
context: TraversalContext,
request: t.Node | undefined,
): boolean => {
if (binding === undefined || request === undefined) return false;
const snapshot = semanticBindingAtRead(binding, read, context.state);
const initializers = snapshot.binding.initializers.filter(
({ node }) => semanticEffectTiming(read, node, context.state) !== "after",
);
const [initializer] = initializers;
if (initializers.length !== 1 || initializer === undefined) return false;
// The result itself must be this request. Containing a request in a branch
// or child allocation does not prove the entire initializer is its response.
let source = unwrapJavaScriptExpression(initializer.node).node;
while (t.isAwaitExpression(source))
source = unwrapJavaScriptExpression(source.argument).node;
return (
source === request &&
!snapshot.binding.referenceInitializers.some(
({ assignment, node }) =>
assignment &&
semanticEffectTiming(read, node, context.state) !== "after",
) &&
(semanticStableInitializer(binding, context.state) !== undefined ||
snapshot.hasDefiniteInitializer)
);
};
/**
* Only `fetch` resolves to a `Response`, and only once its promise settles.
* `http.request`/`http.get` return a `ClientRequest` and `new WebSocket` a
* socket, neither of which has `json`/`text`/`arrayBuffer`; an un-awaited
* `fetch` returns a `Promise`. In all of those the call throws at the call site
* instead of reading a body, so it is not a response consumer at all.
*/
const settlesToResponse = (
request: RequestCandidate,
context: TraversalContext,
): boolean => {
if (request.operation.method !== "fetch") return false;
let node: t.Node = request.node;
for (;;) {
const parent = context.state.parentsByNode.get(node);
if (parent === undefined) return false;
if (t.isAwaitExpression(parent)) return true;
if (javaScriptExpressionWrapperTarget(parent) !== node) return false;
node = parent;
}
};
const collectResponseConsumers = (
program: t.Program,
context: TraversalContext,
requests: readonly RequestCandidate[],
): JavaScriptSemanticRequestOperation[] => {
const requestsByBinding = new Map<string, RequestCandidate[]>();
for (const request of requests) {
const bindingIds = [
...(request.operation.resultBindingId === null
? []
: [request.operation.resultBindingId]),
...request.operation.projectedResultBindings.map(
({ bindingId }) => bindingId,
),
];
for (const bindingId of bindingIds) {
const existing = requestsByBinding.get(bindingId) ?? [];
existing.push(request);
requestsByBinding.set(bindingId, existing);
}
}
const output: JavaScriptSemanticRequestOperation[] = [];
traverseWithContext(program, context, (node) => {
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) return;
const member = memberCallee(node);
if (member === null || !t.isIdentifier(member.object)) return;
const method = semanticStaticPropertyName(member.property, member.computed);
if (method !== "json" && method !== "text" && method !== "arrayBuffer")
return;
const binding = resolveSemanticBindingState(
context.state,
member.object,
member.object.name,
);
const candidates =
binding === undefined
? []
: (requestsByBinding.get(binding.bindingId) ?? []);
// A body reader only exists on a settled fetch Response. Requests of any
// other kind throw at this call site instead, so they link nothing; if no
// candidate survives, the call is not a response consumer at all.
const linked = candidates.filter((request) =>
settlesToResponse(request, context),
);
if (linked.length === 0) return;
// A binding that also receives a request kind without a body reader leaves
// this reader a candidate, not a proven consumer of the fetch response.
const otherKinds = candidates.length !== linked.length;
// A consumer of exactly one request through its own result binding
// reads that request's response, so it keeps the request's endpoint.
const uniqueRequest =
linked.length === 1 &&
!linked[0]?.operation.projectedResultBindings.some(
({ bindingId }) => bindingId === binding?.bindingId,
)
? linked[0]
: undefined;
const soleWrite = soleWriteReachesRead(
binding,
member.object,
context,
uniqueRequest?.node,
);
output.push({
requestId: `response:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
kind: "response-consumer",
method,
location: range(node),
ownerCallableId: context.callableStack.at(-1) ?? null,
resultBindingId: outerAssignedBinding(node, context),
projectedResultBindings: semanticProjectedBindingFacts(
assignedSemanticResultBindings(
node,
context.ancestors,
context.state,
).filter(({ projectionPath }) => projectionPath.length > 0),
),
linkedRequestIds: linked
.map(({ operation }) => operation.requestId)
.sort(compareUnicodeCodePoints),
endpoint: soleWrite ? (uniqueRequest?.operation.endpoint ?? null) : null,
fields: [],
resolution:
uniqueRequest === undefined || otherKinds ? "partial" : "complete",
});
});
return output;
};
const collectBoundaries = (
program: t.Program,
context: TraversalContext,
): JavaScriptSemanticBoundaryOperation[] => {
const output: JavaScriptSemanticBoundaryOperation[] = [];
traverseWithContext(program, context, (node) => {
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) return;
const details = boundaryDetails(node, context.state);
if (details === null) return;
output.push({
boundaryId: `boundary:${details.kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
kind: details.kind,
method: details.method,
location: range(node),
ownerCallableId: context.callableStack.at(-1) ?? null,
sourceBindingId: argumentBindingId(node.arguments[0], context.state),
resultBindingId: outerAssignedBinding(node, context),
resolution: details.resolution,
});
});
return output;
};
const boundaryDetails = (
node: t.CallExpression | t.OptionalCallExpression,
state: JavaScriptSemanticAnalysisState,
): {
readonly kind: JavaScriptSemanticBoundaryOperation["kind"];
readonly method: string;
readonly resolution: "complete" | "partial";
} | null => {
if (t.isIdentifier(node.callee)) {
const name = node.callee.name;
const unbound =
resolveSemanticBindingState(state, node.callee, name) === undefined &&
!semanticResolutionBlocked(state, node.callee, name);
if (
unbound &&
["String", "Number", "Boolean", "parseInt", "parseFloat"].includes(
name,
) &&
isUnmodifiedGlobalReference(node.callee, state, name)
)
return { kind: "coerce", method: name, resolution: "complete" };
}
const member = memberCallee(node);
if (member === null) return null;
const method = semanticStaticPropertyName(member.property, member.computed);
if (
method === "parse" &&
t.isIdentifier(member.object, { name: "JSON" }) &&
resolveSemanticBindingState(state, member.object, "JSON") === undefined &&
!semanticResolutionBlocked(state, member.object, "JSON") &&
isUnmodifiedGlobalReference(node.callee, state, ["JSON", "parse"])
)
return { kind: "parse", method: "JSON.parse", resolution: "complete" };
if (method === "parse" || method === "safeParse")
return { kind: "parse", method, resolution: "partial" };
if (method === "validate" || method === "assert" || method === "is")
return { kind: "validate", method, resolution: "partial" };
return null;
};
const requestMethod = (
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
state: JavaScriptSemanticAnalysisState,
): {
readonly method: JavaScriptSemanticRequestOperation["method"];
readonly builtinAuthority?: "candidate";
} | null => {
if (t.isIdentifier(node.callee)) {
const name = node.callee.name;
const unbound =
resolveSemanticBindingState(state, node.callee, name) === undefined &&
!semanticResolutionBlocked(state, node.callee, name);
const global = t.isNewExpression(node) ? "WebSocket" : "fetch";
if (
unbound &&
name === global &&
isUnmodifiedGlobalReference(node.callee, state, name)
)
return { method: global };
}
const identity = builtinDataEffectIdentity(node.callee, state, [
"http",
"https",
"node:http",
"node:https",
]);
const method = identity?.path.length === 1 ? identity.path[0] : null;
return method === "request" || method === "get"
? {
method,
...(identity?.builtinAuthority === undefined
? {}
: { builtinAuthority: identity.builtinAuthority }),
}
: null;
};
const requestFields = (
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
method: JavaScriptSemanticRequestOperation["method"],
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticRequestOperation["fields"] => {
const candidate =
method === "fetch" || method === "WebSocket"
? node.arguments[1]
: t.isObjectExpression(node.arguments[0])
? node.arguments[0]
: node.arguments[1];
if (!t.isObjectExpression(candidate)) return [];
return candidate.properties.flatMap((property) => {
if (!t.isObjectProperty(property)) return [];
// `{[key]: 1}` sends no knowable field name; reporting `key` would invent
// a request field that may not exist.
const name = semanticStaticPropertyKey(property.key, property.computed);
if (name === null) return [];
return [
{
name,
sourceBindingId: t.isIdentifier(property.value)
? (resolveSemanticBindingState(
state,
property.value,
property.value.name,
)?.bindingId ?? null)
: null,
},
];
});
};
/**
* The characters RFC 9110 allows in a method token, which is what Node's
* `checkIsHttpToken` accepts.
*
* Measured on Node 24.22.1, `method: "M-SEARCH"`, `"X"` and the punctuation set
* `"!#$%&'*+-.^_` | "~"` all construct a request, while `"G/ET"`, `"G:ET"`, `"G(ET"`,
* `"G,ET"`, `"G"ET"`, `"GéT"`, `" "` and `"\\t"` throw `ERR_INVALID_HTTP_TOKEN`. The set is
* a closed character class rather than a list of verbs, so `"GET "` fails on the trailing
* space and `"get"` is accepted.
*/
const HTTP_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]*$/u;
/**
* Whether a literal `options.method` makes `http.request` throw before any request exists.
*
* `http` and `https` validate the method with `checkIsHttpToken` before they build the
* request, so a literal outside `HTTP_TOKEN` throws `ERR_INVALID_HTTP_TOKEN` from the call
* itself. Measured on Node 24.22.1, an empty string is accepted: Node treats `""` as "not
* given" and falls back to `GET`. A non-string value throws `ERR_INVALID_ARG_TYPE` too, but
* it is left undecided here because the reported fields do not describe the type check.
*/
/**
* Whether a getter is copied before the last write of `member`.
*
* `Object.assign` walks the source in **enumeration** order, which is neither source order nor
* AST order. Two rules decide it, each measured on Node 24.22.1:
*
* - An ECMAScript array index (a canonical integer below `2 ** 32 - 1`) enumerates first,
* ascending. `4294967295` is *not* an array index, so it enumerates with the string keys.
* - A redefined key keeps its **first** insertion position: `{x: 0, method: "BAD METHOD",
* get x() {...}}` enumerates the final `x` getter before `method`, so it returns a GET,
* while the same getter on a fresh key `y` comes after and the call throws
* `ERR_INVALID_HTTP_TOKEN`.
*/
const METHOD_GETTER_ARRAY_INDEX_LIMIT = 2 ** 32 - 1;
const methodGetterPrecedesMember = (
options: t.ObjectExpression,
member: string,
): boolean => {
// A key's position comes from its first insertion; its descriptor comes from the last.
const firstIndex = new Map<string, number>();
const lastDescriptor = new Map<
string,
{ readonly node: t.ObjectProperty | t.ObjectMethod; readonly index: number }
>();
for (const [index, property] of options.properties.entries()) {
if (t.isSpreadElement(property)) continue;
const name = semanticStaticPropertyKey(property.key, property.computed);
if (name === null) continue;
if (!firstIndex.has(name)) firstIndex.set(name, index);
lastDescriptor.set(name, { node: property, index });
}
const orderOf = (name: string): readonly [number, number] => {
const position = firstIndex.get(name) ?? Number.MAX_SAFE_INTEGER;
const key = Number(name);
return Number.isInteger(key) &&
String(key) === name &&
key >= 0 &&
key < METHOD_GETTER_ARRAY_INDEX_LIMIT
? [0, key]
: [1, position];
};
const before = (
left: readonly [number, number],
right: readonly [number, number],
): boolean =>
left[0] !== right[0] ? left[0] < right[0] : left[1] < right[1];
let memberOrder: readonly [number, number] | undefined;
let getterOrder: readonly [number, number] | undefined;
for (const [name, { node }] of lastDescriptor) {
const order = orderOf(name);
if (
t.isObjectMethod(node) &&
node.kind === "get" &&
(getterOrder === undefined || before(order, getterOrder))
)
getterOrder = order;
if (name === member) memberOrder = order;
}
return (
getterOrder !== undefined &&
(memberOrder === undefined || before(getterOrder, memberOrder))
);
};
const rejectsHttpMethodLiteral = (
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
method: JavaScriptSemanticRequestOperation["method"],
): boolean => {
// `fetch` and `WebSocket` read a different member and do not validate a token.
if (method !== "get" && method !== "request") return false;
// A spread before the options slot can supply several runtime arguments, so a later
// syntactic object is not necessarily the options Node reads. Measured on Node
// 24.22.1, `http.request(...[{host, path}, () => {}], {method: "BAD METHOD"})` returns
// a GET request, so the trailing object is ignored and the call must be kept. A spread
// *after* the options cannot move it: `http.request({method: "BAD METHOD"}, ...[])`
// still throws ERR_INVALID_HTTP_TOKEN.
const firstArgument = node.arguments[0];
if (firstArgument !== undefined && t.isSpreadElement(firstArgument))
return false;
// A callable in slot 0 is the callback, so Node replaces the options with defaults and
// never reads a later object. Measured on Node 24.22.1,
// `http.request(() => {}, {method: "BAD METHOD"})` returns a GET ClientRequest, while
// `http.request({method: "BAD METHOD"}, () => {})` throws ERR_INVALID_HTTP_TOKEN
// because the method in slot 0 is validated before the callback is registered.
const head = node.arguments[0];
// The value is unwrapped first, because an erased TypeScript assertion leaves the same
// function at runtime. Measured on Node 24.22.1,
// `http.request((() => {}) as any, {method: "BAD METHOD"})` returns a default GET.
const headValue =
head === undefined ? undefined : unwrapJavaScriptExpression(head).node;
if (
headValue !== undefined &&
(t.isArrowFunctionExpression(headValue) ||
t.isFunctionExpression(headValue))
)
return false;
// The value is unwrapped before the slot is chosen, because an erased TypeScript
// assertion is the same object at runtime: measured on Node 24.22.1,
// `http.request({method: "BAD METHOD"} as any)` throws ERR_INVALID_HTTP_TOKEN.
const first = node.arguments[0];
const firstValue =
first === undefined ? undefined : unwrapJavaScriptExpression(first).node;
const options =
firstValue !== undefined && t.isObjectExpression(firstValue)
? firstValue
: unwrapJavaScriptExpression(node.arguments[1] ?? first!).node;
if (!t.isObjectExpression(options)) return false;
// `ClientRequest` copies the options with `Object.assign` in property order, so a getter
// can only rewrite a member that comes after it. Measured on Node 24.22.1,
// `http.request({get x() { this.method = "GET"; }, method: "BAD METHOD"})` returns a GET
// request while `{method: "BAD METHOD", get x() {...}}` throws ERR_INVALID_HTTP_TOKEN,
// because the invalid value was copied first.
if (methodGetterPrecedesMember(options, "method")) return false;
const expression = options;
const lookup = staticObjectProperty(expression, "method");
if (lookup.status !== "explicit") return false;
const literal = readExactJavaScriptLiteral(lookup.value);
if (!literal.found || typeof literal.value !== "string") return false;
return literal.value !== "" && !HTTP_TOKEN.test(literal.value);
};
const requestEndpoint = (
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
): string | null =>
t.isObjectExpression(node.arguments[0])
? null
: literalString(node.arguments[0]);