@graphql-mesh/json-selection 0.0.0-stage → 0.0.0

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,1084 @@
1
+ /**
2
+ * Pure JSONSelection evaluator shared by Connect transport, stitch resolveTo,
3
+ * and string-interpolation arrow helpers.
4
+ */
5
+ export function evalConnectorsVarExpr(expr, vars) {
6
+ const trimmed = expr.trim();
7
+ if (trimmed.startsWith('$(') && trimmed.endsWith(')')) {
8
+ try {
9
+ return JSON.parse(trimmed.slice(2, -1));
10
+ }
11
+ catch {
12
+ return trimmed.slice(2, -1);
13
+ }
14
+ }
15
+ // Linear method split (not nested-quantifier regex) - CodeQL js/polynomial-redos.
16
+ // Only `->method(...)` with parentheses (same as the previous regex).
17
+ const methodCall = splitConnectorsMethodCall(trimmed);
18
+ if (methodCall) {
19
+ const afterMethod = trimmed.slice(methodCall.left.length + 2 + methodCall.method.length);
20
+ if (afterMethod.startsWith('(') && afterMethod.endsWith(')')) {
21
+ const left = evalConnectorsVarExpr(methodCall.left.trim(), vars);
22
+ const method = methodCall.method;
23
+ const rawArgs = methodCall.args.trim();
24
+ if (method === 'match') {
25
+ // Prefer `$args`/`$this` lookup for match-arm values (e.g. `[@, $args.agent]`).
26
+ // Do not use `thisValue || args` - an empty `{}` thisValue is truthy and hides args.
27
+ return evalMatchMethod(left, rawArgs, vars.thisValue ?? {}, {}, vars);
28
+ }
29
+ if (method === 'get') {
30
+ return evalGetMethod(left, rawArgs);
31
+ }
32
+ if (method === 'joinNotNull') {
33
+ if (!Array.isArray(left))
34
+ return left;
35
+ const sepMatch = rawArgs.match(/^["'](.*)["']$/);
36
+ const sep = sepMatch ? sepMatch[1] : ',';
37
+ return left.filter(v => v != null).join(sep);
38
+ }
39
+ if (method === 'jsonStringify') {
40
+ return JSON.stringify(left);
41
+ }
42
+ if (method === 'toString') {
43
+ return left == null ? '' : String(left);
44
+ }
45
+ }
46
+ }
47
+ if (trimmed.startsWith('$')) {
48
+ return lookupVar(trimmed, vars);
49
+ }
50
+ return trimmed;
51
+ }
52
+ export function lookupVar(path, vars) {
53
+ const rootMatch = path.match(/^(\$[A-Za-z_][\w]*)([\s\S]*)$/);
54
+ if (!rootMatch) {
55
+ return undefined;
56
+ }
57
+ const root = rootMatch[1];
58
+ let cur;
59
+ switch (root) {
60
+ case '$args':
61
+ cur = vars.args;
62
+ break;
63
+ case '$this':
64
+ cur = vars.thisValue;
65
+ break;
66
+ case '$batch':
67
+ // Entity batch keys (Apollo `$batch.id`) - prefer explicit batch, else parent/root.
68
+ cur = vars.batch ?? vars.thisValue;
69
+ break;
70
+ case '$env':
71
+ cur = vars.env;
72
+ break;
73
+ case '$context':
74
+ cur = vars.context;
75
+ break;
76
+ case '$config':
77
+ cur = vars.config || {};
78
+ break;
79
+ default:
80
+ return undefined;
81
+ }
82
+ for (const segment of tokenizeVarPath(rootMatch[2])) {
83
+ if (cur == null)
84
+ return undefined;
85
+ cur = cur[segment];
86
+ }
87
+ return cur;
88
+ }
89
+ /** `.foo`, `["a.b"]`, `['x']` path segments after `$args` / `$this`. */
90
+ export function tokenizeVarPath(rest) {
91
+ const segments = [];
92
+ let i = 0;
93
+ while (i < rest.length) {
94
+ if (rest[i] === '.') {
95
+ i++;
96
+ let ident = '';
97
+ while (i < rest.length && /[A-Za-z0-9_]/.test(rest[i])) {
98
+ ident += rest[i];
99
+ i++;
100
+ }
101
+ if (ident)
102
+ segments.push(ident);
103
+ continue;
104
+ }
105
+ if (rest[i] === '[') {
106
+ i++;
107
+ const quote = rest[i] === '"' || rest[i] === "'" ? rest[i] : null;
108
+ if (quote) {
109
+ i++;
110
+ let key = '';
111
+ while (i < rest.length && rest[i] !== quote) {
112
+ if (rest[i] === '\\' && i + 1 < rest.length) {
113
+ key += rest[i + 1];
114
+ i += 2;
115
+ continue;
116
+ }
117
+ key += rest[i];
118
+ i++;
119
+ }
120
+ if (rest[i] === quote)
121
+ i++;
122
+ if (rest[i] === ']')
123
+ i++;
124
+ segments.push(key);
125
+ }
126
+ else {
127
+ let key = '';
128
+ while (i < rest.length && rest[i] !== ']') {
129
+ key += rest[i];
130
+ i++;
131
+ }
132
+ if (rest[i] === ']')
133
+ i++;
134
+ segments.push(key);
135
+ }
136
+ continue;
137
+ }
138
+ break;
139
+ }
140
+ return segments;
141
+ }
142
+ /**
143
+ * Minimal selection evaluator:
144
+ * - `id name` field picks
145
+ * - `alias: path` aliases
146
+ * - nested `field { a b }`
147
+ * - `$` / `$root` for root
148
+ * - `$status`
149
+ * - `$response.headers.x` (Apollo multi-value array; use `->first`)
150
+ * - `$ <fields>` - merge root with mapped fields (Mesh `exposeResponseMetadata`)
151
+ *
152
+ * Mesh-only `_response` fields (url / statusText / full headers map) are filled after
153
+ * selection - Apollo has no `$request.url` / `$statusText` / whole-headers var.
154
+ */
155
+ export function applySelection(selection, root, extras) {
156
+ const trimmed = selection.trim();
157
+ if (!trimmed) {
158
+ return root;
159
+ }
160
+ if (trimmed === '$' || trimmed === '$root') {
161
+ return root;
162
+ }
163
+ // `$()` expressions (incl. multiline `$({ … })` / `$(null)`) evaluate as a whole so
164
+ // JSON array envelopes (TJSON) are not mistaken for GraphQL list roots.
165
+ // Trailing NamedSelection (`$($args.user) { id }`) stays on evalSubSelection.
166
+ if (trimmed.startsWith('$(')) {
167
+ const closed = findBalancedParenClose(trimmed, 1);
168
+ if (closed > 0) {
169
+ const after = trimmed.slice(closed + 1).trim();
170
+ if (after.startsWith('{')) {
171
+ return evalSubSelection(trimmed, root, extras);
172
+ }
173
+ }
174
+ return evalPath(trimmed, root, extras);
175
+ }
176
+ // Mesh: `$ _response: { … }` - keep JSON body fields and overlay mapped keys.
177
+ // Only when `$` is followed by whitespace (not `$status` / `$.x` / `$->…`).
178
+ if (/^\$\s+\S/.test(trimmed)) {
179
+ const rest = trimmed.replace(/^\$\s+/, '').trim();
180
+ const mapped = rest ? evalSubSelection(rest, root, extras) : {};
181
+ if (root != null && typeof root === 'object' && !Array.isArray(root)) {
182
+ return { ...root, ...mapped };
183
+ }
184
+ return mapped;
185
+ }
186
+ // Connectors literals / single path expressions (not multi-field selections).
187
+ // `$status->match(...)` may contain spaces inside the argument list.
188
+ // Single-line `$.value { a b }` / `$.foo { alias: x }` must still run as a
189
+ // subselection - otherwise aliases like `_odataId: $->get("@odata.id")` are dropped.
190
+ if (trimmed.startsWith('$') &&
191
+ !trimmed.includes('\n') &&
192
+ !/^[A-Za-z_][\w]*\s*:/.test(trimmed) &&
193
+ !hasNonEmptyBraceBlock(trimmed)) {
194
+ return evalPath(trimmed, root, extras);
195
+ }
196
+ return evalSubSelection(trimmed, root, extras);
197
+ }
198
+ /** True when `s` contains `{` … `}` with at least one character between (linear scan). */
199
+ function hasNonEmptyBraceBlock(s) {
200
+ const open = s.indexOf('{');
201
+ if (open < 0) {
202
+ return false;
203
+ }
204
+ const close = s.indexOf('}', open + 1);
205
+ return close > open + 1;
206
+ }
207
+ export function evalPath(path, root, extras) {
208
+ if (path === '$' || path === '$root')
209
+ return root;
210
+ if (path === '$status')
211
+ return extras.status;
212
+ // Bare `$args.x` / `$this.y` (no `->method`) - look up via vars. Method chains like
213
+ // `$args.ids->first` fall through so `first`/`map`/`filter` handlers below still run;
214
+ // their left operand then hits this branch.
215
+ if (extras.vars &&
216
+ !path.includes('->') &&
217
+ /^\$args\b|^\$this\b|^\$env\b|^\$context\b|^\$batch\b|^\$config\b/.test(path)) {
218
+ return evalConnectorsVarExpr(path, extras.vars);
219
+ }
220
+ if (path.startsWith('$response.headers.')) {
221
+ const name = path.slice('$response.headers.'.length).replace(/^['"]|['"]$/g, '');
222
+ const value = extras.responseHeaders?.get(name);
223
+ // Apollo: header vars are always arrays (fetch Headers.get → single joined string).
224
+ return value == null ? undefined : [value];
225
+ }
226
+ // `$("lit")` / `$(123)` / `$($->get("k") ?? "default")` - expression wrapper.
227
+ // Method chains after `$()` (e.g. `…->match`) are handled via split below.
228
+ if (path.startsWith('$(')) {
229
+ const closed = findBalancedParenClose(path, 1);
230
+ if (closed === path.length - 1) {
231
+ return evalConnectorsDollarParen(path.slice(2, closed), root, extras);
232
+ }
233
+ }
234
+ // Method calls: `$status->match(...)`, `$->map(@->match(...))`, `$->entries`,
235
+ // `$->entries->filter(@.key->ne("x"))`. Split on the last `->` at paren-depth 0 so
236
+ // nested `->` inside args (and chained filters) stay intact.
237
+ const methodCall = splitConnectorsMethodCall(path);
238
+ if (methodCall) {
239
+ const left = evalPath(methodCall.left.trim(), root, extras);
240
+ const method = methodCall.method;
241
+ const rawArgs = methodCall.args.trim();
242
+ if (method === 'first') {
243
+ return Array.isArray(left) ? left[0] : left;
244
+ }
245
+ if (method === 'size') {
246
+ if (Array.isArray(left))
247
+ return left.length;
248
+ if (left && typeof left === 'object')
249
+ return Object.keys(left).length;
250
+ if (typeof left === 'string')
251
+ return left.length;
252
+ return 0;
253
+ }
254
+ if (method === 'slice') {
255
+ if (!Array.isArray(left) && typeof left !== 'string')
256
+ return left;
257
+ const parts = rawArgs.split(',').map(s => s.trim());
258
+ const start = parts[0] ? Number(parts[0]) : 0;
259
+ const end = parts[1] != null && parts[1] !== '' ? Number(parts[1]) : undefined;
260
+ return left.slice(start, end);
261
+ }
262
+ // Apollo Connectors string `->split(sep, limit?)` (Router 2.15+ / connect mapping).
263
+ if (method === 'split') {
264
+ if (typeof left !== 'string')
265
+ return left;
266
+ // Keep quoted commas inside the separator (`","`) via lit-aware split.
267
+ const parts = splitConnectorsLitItems(rawArgs);
268
+ const sep = String(parseConnectorsLiteralArg(parts[0] ?? '""'));
269
+ const limit = parts[1] != null && parts[1] !== ''
270
+ ? Number(parseConnectorsLiteralArg(parts[1]))
271
+ : undefined;
272
+ return Number.isFinite(limit) ? left.split(sep, limit) : left.split(sep);
273
+ }
274
+ if (method === 'match') {
275
+ return evalMatchMethod(left, rawArgs, root, extras);
276
+ }
277
+ if (method === 'get') {
278
+ return evalGetMethod(left, rawArgs);
279
+ }
280
+ // Object → `[{ key, value }, …]` (Apollo Connectors; replaces Mesh `@dictionary`).
281
+ if (method === 'entries') {
282
+ if (left == null || typeof left !== 'object' || Array.isArray(left))
283
+ return [];
284
+ return Object.keys(left).map(key => ({ key, value: left[key] }));
285
+ }
286
+ // Keep list elements for which `expr` is truthy (`@.key->ne("fixed")`).
287
+ if (method === 'filter') {
288
+ if (!Array.isArray(left))
289
+ return left;
290
+ const elementExpr = rawArgs.trim();
291
+ return left.filter(item => {
292
+ if (elementExpr === '@')
293
+ return Boolean(item);
294
+ if (elementExpr.startsWith('@')) {
295
+ return Boolean(evalPath(rewriteAtToDollar(elementExpr), item, extras));
296
+ }
297
+ return Boolean(evalPath(elementExpr, item, extras));
298
+ });
299
+ }
300
+ if (method === 'ne') {
301
+ const right = parseConnectorsLiteralArg(rawArgs);
302
+ // Connectors None/null: treat null and undefined as equal for `ne(null)`.
303
+ if (right === null)
304
+ return left != null;
305
+ return left !== right;
306
+ }
307
+ if (method === 'eq') {
308
+ const right = parseConnectorsLiteralArg(rawArgs);
309
+ if (right === null)
310
+ return left == null;
311
+ return left === right;
312
+ }
313
+ // `$obj->has("0")` - Mesh helper (Apollo `has` is still future/non-public).
314
+ if (method === 'has') {
315
+ if (left == null || typeof left !== 'object')
316
+ return false;
317
+ const key = String(parseConnectorsLiteralArg(rawArgs));
318
+ return Object.prototype.hasOwnProperty.call(left, key) || key in left;
319
+ }
320
+ // `$->eq(2)->and($->get(4)->get("0")->ne(null))` - combine booleans; arg eval against root.
321
+ if (method === 'and') {
322
+ let arg = rawArgs.trim();
323
+ if (arg.startsWith('(') && arg.endsWith(')')) {
324
+ arg = arg.slice(1, -1).trim();
325
+ }
326
+ return Boolean(left) && Boolean(evalPath(arg, root, extras));
327
+ }
328
+ // `$arr->contains("0")` - Apollo-public membership check.
329
+ if (method === 'contains') {
330
+ if (!Array.isArray(left))
331
+ return false;
332
+ return left.includes(parseConnectorsLiteralArg(rawArgs));
333
+ }
334
+ // `$->map(@->match(...))` / `$->map(@.id)` / `$->map(@->{ ... })` - element transform.
335
+ // Nested maps: outer `rewriteAtToDollar` turns inner `@->{…}` into `$->{…}`; accept both.
336
+ if (method === 'map') {
337
+ if (!Array.isArray(left))
338
+ return left;
339
+ const elementExpr = rawArgs.trim();
340
+ return left.map(item => {
341
+ if (elementExpr === '@' || elementExpr === '$')
342
+ return item;
343
+ if (elementExpr.startsWith('@') ||
344
+ elementExpr.startsWith('$->{') ||
345
+ elementExpr.startsWith('$->[')) {
346
+ const afterSigil = elementExpr.slice(1);
347
+ // `@->{ ... }` / `$->{ ... }` / `@->[ ... ]` - lit with element as root.
348
+ if (afterSigil.startsWith('->{') || afterSigil.startsWith('->[')) {
349
+ const lit = afterSigil.slice(2);
350
+ return evalConnectorsLitExpr(rewriteAtToDollar(lit), item, extras);
351
+ }
352
+ if (afterSigil.startsWith('{') || afterSigil.startsWith('[')) {
353
+ return evalConnectorsLitExpr(rewriteAtToDollar(afterSigil), item, extras);
354
+ }
355
+ // `@->match(...)` / `@.id` - treat `@` as the element root.
356
+ return evalPath(rewriteAtToDollar(elementExpr), item, extras);
357
+ }
358
+ return evalPath(elementExpr, item, extras);
359
+ });
360
+ }
361
+ if (method === 'joinNotNull') {
362
+ if (!Array.isArray(left))
363
+ return left;
364
+ const sepMatch = rawArgs.match(/^["'](.*)["']$/);
365
+ const sep = sepMatch ? sepMatch[1] : ',';
366
+ return left.filter(v => v != null).join(sep);
367
+ }
368
+ // `$([a, b])->concat($args.ids)` - append array elements (TJSON list/set envelopes).
369
+ // Prefer over LitArray `...` spreads (Apollo LitArray grammar has no spread).
370
+ if (method === 'concat') {
371
+ const right = evalConnectorsLitExpr(rawArgs.trim(), root, extras);
372
+ const leftArr = Array.isArray(left) ? left : left == null ? [] : [left];
373
+ const rightArr = Array.isArray(right) ? right : right == null ? [] : [right];
374
+ return leftArr.concat(rightArr);
375
+ }
376
+ if (method === 'jsonStringify') {
377
+ return JSON.stringify(left);
378
+ }
379
+ if (method === 'toString') {
380
+ return left == null ? '' : String(left);
381
+ }
382
+ }
383
+ // `$["TLSv1.3"]` / `$.foo["bar"]` - bracket keys (dots / reserved chars in JSON names).
384
+ if (/^\$(\.|\[)/.test(path) || path === '$') {
385
+ let rest = path === '$' || path === '$root' ? '' : path.replace(/^\$\.?/, '');
386
+ if (path.startsWith('$[') || path.startsWith('$["') || path.startsWith("$['")) {
387
+ rest = path.slice(1); // keep leading `[...]`
388
+ }
389
+ let cur = root;
390
+ if (!rest)
391
+ return cur;
392
+ // Normalize `.a["b"]` / `["a"].b` into tokenizeVarPath shape
393
+ const normalized = rest.startsWith('[') ? rest : `.${rest}`;
394
+ for (const segment of tokenizeVarPath(normalized)) {
395
+ if (cur == null)
396
+ return undefined;
397
+ cur = cur[segment];
398
+ }
399
+ return cur;
400
+ }
401
+ const parts = path.replace(/^\$\.?/, '').split('.');
402
+ let cur = root;
403
+ for (const part of parts) {
404
+ if (cur == null)
405
+ return undefined;
406
+ cur = cur[part];
407
+ }
408
+ return cur;
409
+ }
410
+ /**
411
+ * Rewrite `@` / `@.x` element aliases to `$` / `$.x` for lit/path eval against the item.
412
+ * Leaves `@` inside quoted strings alone (e.g. emails).
413
+ * Preserves bare `@` match / pass-through wildcards in list arms (`[@, "other"]`, `[@, @]`).
414
+ */
415
+ function rewriteAtToDollar(expr) {
416
+ let out = '';
417
+ let i = 0;
418
+ while (i < expr.length) {
419
+ const c = expr[i];
420
+ if (c === '"' || c === "'") {
421
+ const q = c;
422
+ out += c;
423
+ i++;
424
+ while (i < expr.length && expr[i] !== q) {
425
+ if (expr[i] === '\\') {
426
+ out += expr[i++];
427
+ if (i < expr.length)
428
+ out += expr[i++];
429
+ continue;
430
+ }
431
+ out += expr[i++];
432
+ }
433
+ if (i < expr.length)
434
+ out += expr[i++];
435
+ continue;
436
+ }
437
+ if (c === '@' && expr[i + 1] === '.') {
438
+ out += '$.';
439
+ i += 2;
440
+ continue;
441
+ }
442
+ if (c === '@' && expr[i + 1] === '-' && expr[i + 2] === '>') {
443
+ out += '$->';
444
+ i += 3;
445
+ continue;
446
+ }
447
+ if (c === '@') {
448
+ // Preserve bare `@` only in real match arms (`[@, "other"]`, `[@, @]`), not
449
+ // ordinary lit arrays like `[@]` / `@->[@]` where `@` is the element root.
450
+ let prev = out.length - 1;
451
+ while (prev >= 0 && /\s/.test(out[prev]))
452
+ prev--;
453
+ let next = i + 1;
454
+ while (next < expr.length && /\s/.test(expr[next]))
455
+ next++;
456
+ const prevCh = prev >= 0 ? out[prev] : '';
457
+ const nextCh = next < expr.length ? expr[next] : '';
458
+ const matchArmFirst = prevCh === '[' && nextCh === ',';
459
+ const matchArmRest = prevCh === ',' && (nextCh === ',' || nextCh === ']' || nextCh === '');
460
+ if (matchArmFirst || matchArmRest) {
461
+ out += '@';
462
+ i++;
463
+ continue;
464
+ }
465
+ out += '$';
466
+ i++;
467
+ continue;
468
+ }
469
+ out += c;
470
+ i++;
471
+ }
472
+ return out;
473
+ }
474
+ /** Index of the `)` that closes `s[openIdx]` (`(`), or -1. */
475
+ export function findBalancedParenClose(s, openIdx) {
476
+ let depth = 0;
477
+ for (let i = openIdx; i < s.length; i++) {
478
+ const c = s[i];
479
+ if (c === '"' || c === "'") {
480
+ const q = c;
481
+ i++;
482
+ while (i < s.length && s[i] !== q) {
483
+ if (s[i] === '\\')
484
+ i++;
485
+ i++;
486
+ }
487
+ continue;
488
+ }
489
+ if (c === '(')
490
+ depth++;
491
+ else if (c === ')') {
492
+ depth--;
493
+ if (depth === 0)
494
+ return i;
495
+ }
496
+ }
497
+ return -1;
498
+ }
499
+ /**
500
+ * Connectors `$()` body: JSON literal, path/`->` expr, or `a ?? b` / `a ?! b`
501
+ * (Apollo nullish coalescing - required before `->match` when `get` may be None).
502
+ */
503
+ function evalConnectorsDollarParen(inner, root, extras) {
504
+ const trimmed = inner.trim();
505
+ if (!trimmed)
506
+ return undefined;
507
+ try {
508
+ return JSON.parse(trimmed);
509
+ }
510
+ catch {
511
+ // not a JSON literal
512
+ }
513
+ // Top-level `??` / `?!` (Apollo: `??` coalesces null|None; `?!` only None).
514
+ let depth = 0;
515
+ for (let i = 0; i < trimmed.length; i++) {
516
+ const c = trimmed[i];
517
+ if (c === '"' || c === "'") {
518
+ const q = c;
519
+ i++;
520
+ while (i < trimmed.length && trimmed[i] !== q) {
521
+ if (trimmed[i] === '\\')
522
+ i++;
523
+ i++;
524
+ }
525
+ continue;
526
+ }
527
+ if (c === '(' || c === '[' || c === '{')
528
+ depth++;
529
+ else if (c === ')' || c === ']' || c === '}')
530
+ depth--;
531
+ else if (depth === 0 && c === '?') {
532
+ const op = trimmed.slice(i, i + 2);
533
+ if (op === '??' || op === '?!') {
534
+ const left = evalPath(trimmed.slice(0, i).trim(), root, extras);
535
+ const rightRaw = trimmed.slice(i + 2).trim();
536
+ const right = evalConnectorsDollarParen(rightRaw, root, extras);
537
+ if (op === '??') {
538
+ return left == null ? right : left;
539
+ }
540
+ // `?!` - only missing/None (undefined), not JSON null.
541
+ return left === undefined ? right : left;
542
+ }
543
+ }
544
+ }
545
+ // Apollo LitArray / LitObject with embedded `$args` / paths (e.g. TJSON envelopes).
546
+ if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
547
+ try {
548
+ return evalConnectorsLitExpr(trimmed, root, extras);
549
+ }
550
+ catch {
551
+ /* fall through */
552
+ }
553
+ }
554
+ if (trimmed.startsWith('$') || trimmed.includes('->') || /^[A-Za-z_]/.test(trimmed)) {
555
+ return evalPath(trimmed, root, extras);
556
+ }
557
+ return trimmed;
558
+ }
559
+ /**
560
+ * Evaluate Apollo Connectors LitExpr fragments used inside `$()`:
561
+ * arrays/objects that mix JSON literals with `$args` / path selections / spreads.
562
+ */
563
+ function evalConnectorsLitExpr(expr, root, extras) {
564
+ const trimmed = expr.trim();
565
+ if (!trimmed)
566
+ return undefined;
567
+ try {
568
+ return JSON.parse(trimmed);
569
+ }
570
+ catch {
571
+ /* continue */
572
+ }
573
+ // Parse containers before path/`->` so `$([$args.ids->size])` does not send
574
+ // the whole array fragment through evalPath (which rejects `size]`).
575
+ if (trimmed.startsWith('[')) {
576
+ return evalConnectorsLitArray(trimmed, root, extras);
577
+ }
578
+ if (trimmed.startsWith('{')) {
579
+ return evalConnectorsLitObject(trimmed, root, extras);
580
+ }
581
+ if (trimmed.startsWith('$(')) {
582
+ const closed = findBalancedParenClose(trimmed, 1);
583
+ if (closed > 0) {
584
+ // Only unwrap `$()` when it is the whole fragment; otherwise keep chains
585
+ // like `$([$args.ids]->size)` for evalPath.
586
+ if (closed === trimmed.length - 1) {
587
+ return evalConnectorsDollarParen(trimmed.slice(2, closed), root, extras);
588
+ }
589
+ return evalPath(trimmed, root, extras);
590
+ }
591
+ }
592
+ if (trimmed.startsWith('$') || trimmed.includes('->')) {
593
+ return evalPath(trimmed, root, extras);
594
+ }
595
+ if (/^-?\d+(\.\d+)?$/.test(trimmed))
596
+ return Number(trimmed);
597
+ if (trimmed === 'true')
598
+ return true;
599
+ if (trimmed === 'false')
600
+ return false;
601
+ if (trimmed === 'null')
602
+ return null;
603
+ return trimmed;
604
+ }
605
+ function splitConnectorsLitItems(inner) {
606
+ const items = [];
607
+ let depth = 0;
608
+ let start = 0;
609
+ for (let i = 0; i < inner.length; i++) {
610
+ const c = inner[i];
611
+ if (c === '"' || c === "'") {
612
+ const q = c;
613
+ i++;
614
+ while (i < inner.length && inner[i] !== q) {
615
+ if (inner[i] === '\\')
616
+ i++;
617
+ i++;
618
+ }
619
+ continue;
620
+ }
621
+ if (c === '(' || c === '[' || c === '{')
622
+ depth++;
623
+ else if (c === ')' || c === ']' || c === '}')
624
+ depth--;
625
+ else if (c === ',' && depth === 0) {
626
+ items.push(inner.slice(start, i).trim());
627
+ start = i + 1;
628
+ }
629
+ }
630
+ const last = inner.slice(start).trim();
631
+ if (last)
632
+ items.push(last);
633
+ return items;
634
+ }
635
+ function evalConnectorsLitArray(expr, root, extras) {
636
+ const inner = expr.trim().slice(1, -1);
637
+ const out = [];
638
+ for (const item of splitConnectorsLitItems(inner)) {
639
+ if (!item)
640
+ continue;
641
+ if (item.startsWith('...')) {
642
+ const spread = evalConnectorsLitExpr(item.slice(3).trim(), root, extras);
643
+ if (Array.isArray(spread))
644
+ out.push(...spread);
645
+ else if (spread != null)
646
+ out.push(spread);
647
+ continue;
648
+ }
649
+ out.push(evalConnectorsLitExpr(item, root, extras));
650
+ }
651
+ return out;
652
+ }
653
+ function evalConnectorsLitObject(expr, root, extras) {
654
+ const inner = expr.trim().slice(1, -1);
655
+ const out = {};
656
+ for (const item of splitConnectorsLitItems(inner)) {
657
+ if (!item)
658
+ continue;
659
+ if (item.startsWith('...')) {
660
+ const spread = evalConnectorsLitExpr(item.slice(3).trim(), root, extras);
661
+ if (spread && typeof spread === 'object' && !Array.isArray(spread)) {
662
+ Object.assign(out, spread);
663
+ }
664
+ continue;
665
+ }
666
+ const colon = findTopLevelColon(item);
667
+ if (colon < 0)
668
+ continue;
669
+ const rawKey = item.slice(0, colon).trim();
670
+ const rawVal = item.slice(colon + 1).trim();
671
+ let key = rawKey;
672
+ try {
673
+ if ((rawKey.startsWith('"') && rawKey.endsWith('"')) ||
674
+ (rawKey.startsWith("'") && rawKey.endsWith("'"))) {
675
+ key = JSON.parse(rawKey.includes("'") ? `"${rawKey.slice(1, -1)}"` : rawKey);
676
+ }
677
+ }
678
+ catch {
679
+ /* keep key */
680
+ }
681
+ out[key] = evalConnectorsLitExpr(rawVal, root, extras);
682
+ }
683
+ return out;
684
+ }
685
+ function findTopLevelColon(item) {
686
+ let depth = 0;
687
+ for (let i = 0; i < item.length; i++) {
688
+ const c = item[i];
689
+ if (c === '"' || c === "'") {
690
+ const q = c;
691
+ i++;
692
+ while (i < item.length && item[i] !== q) {
693
+ if (item[i] === '\\')
694
+ i++;
695
+ i++;
696
+ }
697
+ continue;
698
+ }
699
+ if (c === '(' || c === '[' || c === '{')
700
+ depth++;
701
+ else if (c === ')' || c === ']' || c === '}')
702
+ depth--;
703
+ else if (c === ':' && depth === 0)
704
+ return i;
705
+ }
706
+ return -1;
707
+ }
708
+ /**
709
+ * Split `left->method` / `left->method(args)` on the last `->` outside parentheses.
710
+ */
711
+ export function splitConnectorsMethodCall(path) {
712
+ let depth = 0;
713
+ let lastArrow = -1;
714
+ for (let i = 0; i < path.length; i++) {
715
+ const c = path[i];
716
+ if (c === '(')
717
+ depth++;
718
+ else if (c === ')')
719
+ depth--;
720
+ else if (depth === 0 && c === '-' && path[i + 1] === '>') {
721
+ lastArrow = i;
722
+ }
723
+ }
724
+ if (lastArrow < 0)
725
+ return null;
726
+ const after = path.slice(lastArrow + 2);
727
+ const nameMatch = after.match(/^([A-Za-z_][\w]*)/);
728
+ if (!nameMatch)
729
+ return null;
730
+ const method = nameMatch[1];
731
+ const rest = after.slice(method.length);
732
+ if (rest === '') {
733
+ return { left: path.slice(0, lastArrow), method, args: '' };
734
+ }
735
+ if (rest.startsWith('(') && rest.endsWith(')')) {
736
+ return { left: path.slice(0, lastArrow), method, args: rest.slice(1, -1) };
737
+ }
738
+ return null;
739
+ }
740
+ /**
741
+ * Federation Connectors `$->get("key")` / `$args->get("special-key")` / `arr->get(0)`.
742
+ * Preferred over `$["key"]` which Apollo Router's selection parser rejects with Eof.
743
+ */
744
+ export function evalGetMethod(left, rawArgs) {
745
+ if (left == null)
746
+ return undefined;
747
+ return left[parseConnectorsLiteralArg(rawArgs)];
748
+ }
749
+ /** Parse a Connectors method arg literal (`"x"`, `'x'`, `0`, `true`) or raw string. */
750
+ export function parseConnectorsLiteralArg(rawArgs) {
751
+ const trimmed = rawArgs.trim();
752
+ try {
753
+ return JSON.parse(trimmed);
754
+ }
755
+ catch {
756
+ const quoted = trimmed.match(/^["'](.*)["']$/);
757
+ if (quoted)
758
+ return quoted[1];
759
+ if (/^-?\d+$/.test(trimmed))
760
+ return Number(trimmed);
761
+ if (trimmed === 'true')
762
+ return true;
763
+ if (trimmed === 'false')
764
+ return false;
765
+ if (trimmed === 'null')
766
+ return null;
767
+ return trimmed;
768
+ }
769
+ }
770
+ /**
771
+ * Federation Connectors `$x->match([key, value], …, [@, default])`.
772
+ * Values may be nested exprs (e.g. `$.petType->match(...)`) for discriminator defaults.
773
+ */
774
+ export function evalMatchMethod(left, rawArgs, root = {}, extras = {}, vars) {
775
+ // Split top-level `[...]` groups (ignore brackets inside nested match args).
776
+ const groups = [];
777
+ let depth = 0;
778
+ let start = -1;
779
+ for (let i = 0; i < rawArgs.length; i++) {
780
+ const ch = rawArgs[i];
781
+ if (ch === '[') {
782
+ if (depth === 0)
783
+ start = i;
784
+ depth++;
785
+ }
786
+ else if (ch === ']') {
787
+ depth--;
788
+ if (depth === 0 && start >= 0) {
789
+ groups.push(rawArgs.slice(start, i + 1));
790
+ start = -1;
791
+ }
792
+ }
793
+ }
794
+ let fallback;
795
+ for (const group of groups) {
796
+ const inner = group.slice(1, -1).trim();
797
+ // [@, value] default arm - `[@, @]` means pass through the unmatched left value.
798
+ if (inner.startsWith('@')) {
799
+ const comma = findTopLevelComma(inner);
800
+ const valueRaw = comma >= 0 ? inner.slice(comma + 1).trim() : 'null';
801
+ fallback = valueRaw === '@' ? left : parseMatchValue(valueRaw, root, extras, vars);
802
+ continue;
803
+ }
804
+ const comma = findTopLevelComma(inner);
805
+ if (comma < 0)
806
+ continue;
807
+ const key = parseMatchValue(inner.slice(0, comma).trim(), root, extras, vars);
808
+ const value = parseMatchValue(inner.slice(comma + 1).trim(), root, extras, vars);
809
+ if (Object.is(key, left) || key === left || String(key) === String(left)) {
810
+ return value;
811
+ }
812
+ }
813
+ return fallback;
814
+ }
815
+ function findTopLevelComma(inner) {
816
+ let depth = 0;
817
+ for (let i = 0; i < inner.length; i++) {
818
+ const ch = inner[i];
819
+ if (ch === '"' || ch === "'") {
820
+ const quote = ch;
821
+ i++;
822
+ while (i < inner.length) {
823
+ if (inner[i] === '\\') {
824
+ i += 2;
825
+ continue;
826
+ }
827
+ if (inner[i] === quote)
828
+ break;
829
+ i++;
830
+ }
831
+ continue;
832
+ }
833
+ if (ch === '[' || ch === '(' || ch === '{')
834
+ depth++;
835
+ else if (ch === ']' || ch === ')' || ch === '}')
836
+ depth--;
837
+ else if (ch === ',' && depth === 0)
838
+ return i;
839
+ }
840
+ return -1;
841
+ }
842
+ function parseMatchValue(raw, root = {}, extras = {}, vars) {
843
+ if (raw === '@')
844
+ return undefined;
845
+ // Abstract-type branch objects: `{ __typename: "Electronics", warranty }`
846
+ // Rewrite string literals to `$("…")` so selection eval can resolve them.
847
+ if (raw.startsWith('{') && raw.endsWith('}')) {
848
+ const inner = raw.slice(1, -1).trim();
849
+ const rewritten = inner.replace(/:(\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g, (_m, sp, lit) => `:${sp}$(${lit})`);
850
+ return evalSubSelection(rewritten, root, extras);
851
+ }
852
+ // Path/arg templates: `$args.x` / `$this.y` need the Connectors var map, not the
853
+ // selection root (which is often `{}` for request-path matches).
854
+ if (vars && /^\$args\b|^\$this\b|^\$env\b|^\$context\b|^\$batch\b|^\$config\b/.test(raw)) {
855
+ return evalConnectorsVarExpr(raw, vars);
856
+ }
857
+ if (raw.startsWith('$') || raw.includes('->')) {
858
+ return evalPath(raw, root, extras);
859
+ }
860
+ try {
861
+ return JSON.parse(raw);
862
+ }
863
+ catch {
864
+ return raw.replace(/^["']|["']$/g, '');
865
+ }
866
+ }
867
+ function evalSubSelection(selection, root, extras) {
868
+ if (Array.isArray(root)) {
869
+ return root.map(item => evalSubSelection(selection, item, extras));
870
+ }
871
+ const tokens = tokenizeSelection(selection);
872
+ // Apollo: a lone path root like `$.products { id }` is the field value itself,
873
+ // not `{ "$.products": [...] }`. Explicit aliases (`products: $.products { id }`) wrap.
874
+ if (tokens.length === 1 &&
875
+ tokens[0].source.startsWith('$') &&
876
+ tokens[0].alias === tokens[0].source) {
877
+ const source = tokens[0].source === '$' || tokens[0].source === '$root'
878
+ ? root
879
+ : evalPath(tokens[0].source, root, extras);
880
+ if (tokens[0].sub) {
881
+ return evalSubSelection(tokens[0].sub, source, extras);
882
+ }
883
+ return source;
884
+ }
885
+ const result = {};
886
+ for (const token of tokens) {
887
+ if (token.spread) {
888
+ const spreadValue = evalPath(token.source, root, extras);
889
+ if (spreadValue && typeof spreadValue === 'object' && !Array.isArray(spreadValue)) {
890
+ Object.assign(result, spreadValue);
891
+ }
892
+ continue;
893
+ }
894
+ if (token.sub) {
895
+ const source = token.source === '$' ? root : evalPath(token.source, root, extras);
896
+ result[token.alias] = evalSubSelection(token.sub, source, extras);
897
+ }
898
+ else {
899
+ result[token.alias] = evalPath(token.source, root, extras);
900
+ }
901
+ }
902
+ return result;
903
+ }
904
+ function readSelectionIdent(s, start) {
905
+ let i = start;
906
+ if (s[i] === '"' || s[i] === "'") {
907
+ const quote = s[i];
908
+ i++;
909
+ let value = '';
910
+ while (i < s.length && s[i] !== quote) {
911
+ if (s[i] === '\\' && i + 1 < s.length) {
912
+ value += s[i + 1];
913
+ i += 2;
914
+ continue;
915
+ }
916
+ value += s[i];
917
+ i++;
918
+ }
919
+ if (s[i] === quote)
920
+ i++;
921
+ return { value, end: i };
922
+ }
923
+ // `$status->match([200, "User"], …)`, `$["patent-id"]`, `$.foo["bar"]->match(...)`,
924
+ // `$("literal")` / `$($->get("k") ?? "default")->match(...)` (balanced `$()` + chains).
925
+ if (s[i] === '$') {
926
+ i++;
927
+ // `$()` - balanced (nested get/match / `??` inside).
928
+ if (s[i] === '(') {
929
+ const close = findBalancedParenClose(s, i);
930
+ if (close < 0) {
931
+ return { value: s.slice(start), end: s.length };
932
+ }
933
+ i = close + 1;
934
+ }
935
+ else {
936
+ // Don't consume the `-` of `->` into the path segment.
937
+ while (i < s.length && /[A-Za-z0-9_.]/.test(s[i]))
938
+ i++;
939
+ // Bracket accessors: `["key"]` / `['key']` / `[0]`
940
+ while (s[i] === '[') {
941
+ i++;
942
+ if (s[i] === '"' || s[i] === "'") {
943
+ const quote = s[i++];
944
+ while (i < s.length && s[i] !== quote) {
945
+ if (s[i] === '\\' && i + 1 < s.length)
946
+ i += 2;
947
+ else
948
+ i++;
949
+ }
950
+ if (s[i] === quote)
951
+ i++;
952
+ }
953
+ else {
954
+ while (i < s.length && s[i] !== ']')
955
+ i++;
956
+ }
957
+ if (s[i] === ']')
958
+ i++;
959
+ while (i < s.length && /[A-Za-z0-9_.]/.test(s[i]))
960
+ i++;
961
+ }
962
+ }
963
+ while (s.slice(i, i + 2) === '->') {
964
+ i += 2;
965
+ while (i < s.length && /[A-Za-z0-9_]/.test(s[i]))
966
+ i++;
967
+ if (s[i] === '(') {
968
+ const close = findBalancedParenClose(s, i);
969
+ if (close < 0) {
970
+ i = s.length;
971
+ break;
972
+ }
973
+ i = close + 1;
974
+ }
975
+ }
976
+ return { value: s.slice(start, i), end: i };
977
+ }
978
+ // Plain field / path, optionally with `->method(...)` (e.g. `test->match([0, "_0"], …)`).
979
+ while (i < s.length && /[A-Za-z0-9_$.]/.test(s[i]))
980
+ i++;
981
+ while (s.slice(i, i + 2) === '->') {
982
+ i += 2;
983
+ while (i < s.length && /[A-Za-z0-9_]/.test(s[i]))
984
+ i++;
985
+ if (s[i] === '(') {
986
+ let depth = 0;
987
+ for (; i < s.length; i++) {
988
+ if (s[i] === '(')
989
+ depth++;
990
+ else if (s[i] === ')') {
991
+ depth--;
992
+ if (depth === 0) {
993
+ i++;
994
+ break;
995
+ }
996
+ }
997
+ }
998
+ }
999
+ }
1000
+ return { value: s.slice(start, i), end: i };
1001
+ }
1002
+ function tokenizeSelection(selection) {
1003
+ const tokens = [];
1004
+ let i = 0;
1005
+ const s = selection.trim();
1006
+ while (i < s.length) {
1007
+ while (i < s.length && /\s/.test(s[i]))
1008
+ i++;
1009
+ if (i >= s.length)
1010
+ break;
1011
+ const start = i;
1012
+ // Abstract-type spread: `... $_type->match([...])` merges into the parent object.
1013
+ if (s.slice(i, i + 3) === '...') {
1014
+ i += 3;
1015
+ while (i < s.length && /\s/.test(s[i]))
1016
+ i++;
1017
+ const readSpread = readSelectionIdent(s, i);
1018
+ if (!readSpread.value) {
1019
+ i = Math.max(i, start + 1);
1020
+ continue;
1021
+ }
1022
+ i = readSpread.end;
1023
+ tokens.push({ alias: '', source: readSpread.value, spread: true });
1024
+ continue;
1025
+ }
1026
+ // alias or field
1027
+ let read = readSelectionIdent(s, i);
1028
+ if (!read.value) {
1029
+ // Avoid infinite loops on unexpected characters
1030
+ i++;
1031
+ continue;
1032
+ }
1033
+ const name = read.value;
1034
+ i = read.end;
1035
+ while (i < s.length && /\s/.test(s[i]))
1036
+ i++;
1037
+ let alias = name;
1038
+ let source = name;
1039
+ if (s[i] === ':') {
1040
+ i++;
1041
+ while (i < s.length && /\s/.test(s[i]))
1042
+ i++;
1043
+ // Apollo entity-ref / object literal: `supplier: { id: supplierId }` -
1044
+ // fields are relative to the *parent* root, not `$.supplier`.
1045
+ if (s[i] === '{') {
1046
+ source = '$';
1047
+ alias = name;
1048
+ }
1049
+ else {
1050
+ read = readSelectionIdent(s, i);
1051
+ source = read.value;
1052
+ i = read.end;
1053
+ alias = name;
1054
+ while (i < s.length && /\s/.test(s[i]))
1055
+ i++;
1056
+ }
1057
+ }
1058
+ let sub;
1059
+ if (s[i] === '{') {
1060
+ let depth = 0;
1061
+ const subStart = i + 1;
1062
+ for (; i < s.length; i++) {
1063
+ if (s[i] === '{')
1064
+ depth++;
1065
+ else if (s[i] === '}') {
1066
+ depth--;
1067
+ if (depth === 0) {
1068
+ sub = s.slice(subStart, i).trim();
1069
+ i++;
1070
+ break;
1071
+ }
1072
+ }
1073
+ }
1074
+ if (!source)
1075
+ source = alias;
1076
+ }
1077
+ if (i === start) {
1078
+ i++;
1079
+ continue;
1080
+ }
1081
+ tokens.push({ alias, source: source || alias, sub });
1082
+ }
1083
+ return tokens;
1084
+ }