@soda-gql/tools 0.13.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.
Files changed (49) hide show
  1. package/README.md +72 -0
  2. package/codegen.d.ts +2 -0
  3. package/codegen.js +1 -0
  4. package/dist/bin.cjs +15509 -0
  5. package/dist/bin.cjs.map +1 -0
  6. package/dist/bin.d.cts +839 -0
  7. package/dist/bin.d.cts.map +1 -0
  8. package/dist/chunk-BrXtsOCC.cjs +41 -0
  9. package/dist/codegen.cjs +4704 -0
  10. package/dist/codegen.cjs.map +1 -0
  11. package/dist/codegen.d.cts +416 -0
  12. package/dist/codegen.d.cts.map +1 -0
  13. package/dist/codegen.d.mts +416 -0
  14. package/dist/codegen.d.mts.map +1 -0
  15. package/dist/codegen.mjs +4712 -0
  16. package/dist/codegen.mjs.map +1 -0
  17. package/dist/formatter-Glj5a663.cjs +510 -0
  18. package/dist/formatter-Glj5a663.cjs.map +1 -0
  19. package/dist/formatter.cjs +509 -0
  20. package/dist/formatter.cjs.map +1 -0
  21. package/dist/formatter.d.cts +33 -0
  22. package/dist/formatter.d.cts.map +1 -0
  23. package/dist/formatter.d.mts +33 -0
  24. package/dist/formatter.d.mts.map +1 -0
  25. package/dist/formatter.mjs +507 -0
  26. package/dist/formatter.mjs.map +1 -0
  27. package/dist/index.cjs +13 -0
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.cts +11 -0
  30. package/dist/index.d.cts.map +1 -0
  31. package/dist/index.d.mts +11 -0
  32. package/dist/index.d.mts.map +1 -0
  33. package/dist/index.mjs +12 -0
  34. package/dist/index.mjs.map +1 -0
  35. package/dist/typegen.cjs +864 -0
  36. package/dist/typegen.cjs.map +1 -0
  37. package/dist/typegen.d.cts +205 -0
  38. package/dist/typegen.d.cts.map +1 -0
  39. package/dist/typegen.d.mts +205 -0
  40. package/dist/typegen.d.mts.map +1 -0
  41. package/dist/typegen.mjs +859 -0
  42. package/dist/typegen.mjs.map +1 -0
  43. package/formatter.d.ts +2 -0
  44. package/formatter.js +1 -0
  45. package/index.d.ts +2 -0
  46. package/index.js +1 -0
  47. package/package.json +102 -0
  48. package/typegen.d.ts +2 -0
  49. package/typegen.js +1 -0
@@ -0,0 +1,4712 @@
1
+ import { createRequire } from "node:module";
2
+ import { err, ok } from "neverthrow";
3
+ import { createSchemaIndex } from "@soda-gql/core";
4
+ import { Kind, concatAST, parse, print } from "graphql";
5
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
7
+ import { build } from "esbuild";
8
+ import { createHash } from "node:crypto";
9
+
10
+ //#region rolldown:runtime
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
21
+ key = keys[i];
22
+ if (!__hasOwnProp.call(to, key) && key !== except) {
23
+ __defProp(to, key, {
24
+ get: ((k) => from[k]).bind(null, key),
25
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
26
+ });
27
+ }
28
+ }
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
33
+ value: mod,
34
+ enumerable: true
35
+ }) : target, mod));
36
+
37
+ //#endregion
38
+ //#region node_modules/picomatch/lib/constants.js
39
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
40
+ const WIN_SLASH = "\\\\/";
41
+ const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
42
+ /**
43
+ * Posix glob regex
44
+ */
45
+ const DOT_LITERAL = "\\.";
46
+ const PLUS_LITERAL = "\\+";
47
+ const QMARK_LITERAL = "\\?";
48
+ const SLASH_LITERAL = "\\/";
49
+ const ONE_CHAR = "(?=.)";
50
+ const QMARK = "[^/]";
51
+ const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
52
+ const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
53
+ const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
54
+ const NO_DOT = `(?!${DOT_LITERAL})`;
55
+ const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
56
+ const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
57
+ const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
58
+ const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
59
+ const STAR = `${QMARK}*?`;
60
+ const SEP = "/";
61
+ const POSIX_CHARS = {
62
+ DOT_LITERAL,
63
+ PLUS_LITERAL,
64
+ QMARK_LITERAL,
65
+ SLASH_LITERAL,
66
+ ONE_CHAR,
67
+ QMARK,
68
+ END_ANCHOR,
69
+ DOTS_SLASH,
70
+ NO_DOT,
71
+ NO_DOTS,
72
+ NO_DOT_SLASH,
73
+ NO_DOTS_SLASH,
74
+ QMARK_NO_DOT,
75
+ STAR,
76
+ START_ANCHOR,
77
+ SEP
78
+ };
79
+ /**
80
+ * Windows glob regex
81
+ */
82
+ const WINDOWS_CHARS = {
83
+ ...POSIX_CHARS,
84
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
85
+ QMARK: WIN_NO_SLASH,
86
+ STAR: `${WIN_NO_SLASH}*?`,
87
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
88
+ NO_DOT: `(?!${DOT_LITERAL})`,
89
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
90
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
91
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
92
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
93
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
94
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
95
+ SEP: "\\"
96
+ };
97
+ /**
98
+ * POSIX Bracket Regex
99
+ */
100
+ const POSIX_REGEX_SOURCE$1 = {
101
+ alnum: "a-zA-Z0-9",
102
+ alpha: "a-zA-Z",
103
+ ascii: "\\x00-\\x7F",
104
+ blank: " \\t",
105
+ cntrl: "\\x00-\\x1F\\x7F",
106
+ digit: "0-9",
107
+ graph: "\\x21-\\x7E",
108
+ lower: "a-z",
109
+ print: "\\x20-\\x7E ",
110
+ punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
111
+ space: " \\t\\r\\n\\v\\f",
112
+ upper: "A-Z",
113
+ word: "A-Za-z0-9_",
114
+ xdigit: "A-Fa-f0-9"
115
+ };
116
+ module.exports = {
117
+ MAX_LENGTH: 1024 * 64,
118
+ POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
119
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
120
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
121
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
122
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
123
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
124
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
125
+ REPLACEMENTS: {
126
+ __proto__: null,
127
+ "***": "*",
128
+ "**/**": "**",
129
+ "**/**/**": "**"
130
+ },
131
+ CHAR_0: 48,
132
+ CHAR_9: 57,
133
+ CHAR_UPPERCASE_A: 65,
134
+ CHAR_LOWERCASE_A: 97,
135
+ CHAR_UPPERCASE_Z: 90,
136
+ CHAR_LOWERCASE_Z: 122,
137
+ CHAR_LEFT_PARENTHESES: 40,
138
+ CHAR_RIGHT_PARENTHESES: 41,
139
+ CHAR_ASTERISK: 42,
140
+ CHAR_AMPERSAND: 38,
141
+ CHAR_AT: 64,
142
+ CHAR_BACKWARD_SLASH: 92,
143
+ CHAR_CARRIAGE_RETURN: 13,
144
+ CHAR_CIRCUMFLEX_ACCENT: 94,
145
+ CHAR_COLON: 58,
146
+ CHAR_COMMA: 44,
147
+ CHAR_DOT: 46,
148
+ CHAR_DOUBLE_QUOTE: 34,
149
+ CHAR_EQUAL: 61,
150
+ CHAR_EXCLAMATION_MARK: 33,
151
+ CHAR_FORM_FEED: 12,
152
+ CHAR_FORWARD_SLASH: 47,
153
+ CHAR_GRAVE_ACCENT: 96,
154
+ CHAR_HASH: 35,
155
+ CHAR_HYPHEN_MINUS: 45,
156
+ CHAR_LEFT_ANGLE_BRACKET: 60,
157
+ CHAR_LEFT_CURLY_BRACE: 123,
158
+ CHAR_LEFT_SQUARE_BRACKET: 91,
159
+ CHAR_LINE_FEED: 10,
160
+ CHAR_NO_BREAK_SPACE: 160,
161
+ CHAR_PERCENT: 37,
162
+ CHAR_PLUS: 43,
163
+ CHAR_QUESTION_MARK: 63,
164
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
165
+ CHAR_RIGHT_CURLY_BRACE: 125,
166
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
167
+ CHAR_SEMICOLON: 59,
168
+ CHAR_SINGLE_QUOTE: 39,
169
+ CHAR_SPACE: 32,
170
+ CHAR_TAB: 9,
171
+ CHAR_UNDERSCORE: 95,
172
+ CHAR_VERTICAL_LINE: 124,
173
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
174
+ extglobChars(chars) {
175
+ return {
176
+ "!": {
177
+ type: "negate",
178
+ open: "(?:(?!(?:",
179
+ close: `))${chars.STAR})`
180
+ },
181
+ "?": {
182
+ type: "qmark",
183
+ open: "(?:",
184
+ close: ")?"
185
+ },
186
+ "+": {
187
+ type: "plus",
188
+ open: "(?:",
189
+ close: ")+"
190
+ },
191
+ "*": {
192
+ type: "star",
193
+ open: "(?:",
194
+ close: ")*"
195
+ },
196
+ "@": {
197
+ type: "at",
198
+ open: "(?:",
199
+ close: ")"
200
+ }
201
+ };
202
+ },
203
+ globChars(win32) {
204
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
205
+ }
206
+ };
207
+ }));
208
+
209
+ //#endregion
210
+ //#region node_modules/picomatch/lib/utils.js
211
+ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
212
+ const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
213
+ exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
214
+ exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
215
+ exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
216
+ exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
217
+ exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
218
+ exports.isWindows = () => {
219
+ if (typeof navigator !== "undefined" && navigator.platform) {
220
+ const platform = navigator.platform.toLowerCase();
221
+ return platform === "win32" || platform === "windows";
222
+ }
223
+ if (typeof process !== "undefined" && process.platform) {
224
+ return process.platform === "win32";
225
+ }
226
+ return false;
227
+ };
228
+ exports.removeBackslashes = (str) => {
229
+ return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
230
+ return match === "\\" ? "" : match;
231
+ });
232
+ };
233
+ exports.escapeLast = (input, char, lastIdx) => {
234
+ const idx = input.lastIndexOf(char, lastIdx);
235
+ if (idx === -1) return input;
236
+ if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
237
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
238
+ };
239
+ exports.removePrefix = (input, state = {}) => {
240
+ let output = input;
241
+ if (output.startsWith("./")) {
242
+ output = output.slice(2);
243
+ state.prefix = "./";
244
+ }
245
+ return output;
246
+ };
247
+ exports.wrapOutput = (input, state = {}, options = {}) => {
248
+ const prepend = options.contains ? "" : "^";
249
+ const append = options.contains ? "" : "$";
250
+ let output = `${prepend}(?:${input})${append}`;
251
+ if (state.negated === true) {
252
+ output = `(?:^(?!${output}).*$)`;
253
+ }
254
+ return output;
255
+ };
256
+ exports.basename = (path, { windows } = {}) => {
257
+ const segs = path.split(windows ? /[\\/]/ : "/");
258
+ const last = segs[segs.length - 1];
259
+ if (last === "") {
260
+ return segs[segs.length - 2];
261
+ }
262
+ return last;
263
+ };
264
+ }));
265
+
266
+ //#endregion
267
+ //#region node_modules/picomatch/lib/scan.js
268
+ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
269
+ const utils$3 = require_utils();
270
+ const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
271
+ const isPathSeparator = (code) => {
272
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
273
+ };
274
+ const depth = (token) => {
275
+ if (token.isPrefix !== true) {
276
+ token.depth = token.isGlobstar ? Infinity : 1;
277
+ }
278
+ };
279
+ /**
280
+ * Quickly scans a glob pattern and returns an object with a handful of
281
+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
282
+ * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
283
+ * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
284
+ *
285
+ * ```js
286
+ * const pm = require('picomatch');
287
+ * console.log(pm.scan('foo/bar/*.js'));
288
+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
289
+ * ```
290
+ * @param {String} `str`
291
+ * @param {Object} `options`
292
+ * @return {Object} Returns an object with tokens and regex source string.
293
+ * @api public
294
+ */
295
+ const scan$1 = (input, options) => {
296
+ const opts = options || {};
297
+ const length = input.length - 1;
298
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
299
+ const slashes = [];
300
+ const tokens = [];
301
+ const parts = [];
302
+ let str = input;
303
+ let index = -1;
304
+ let start = 0;
305
+ let lastIndex = 0;
306
+ let isBrace = false;
307
+ let isBracket = false;
308
+ let isGlob = false;
309
+ let isExtglob = false;
310
+ let isGlobstar = false;
311
+ let braceEscaped = false;
312
+ let backslashes = false;
313
+ let negated = false;
314
+ let negatedExtglob = false;
315
+ let finished = false;
316
+ let braces = 0;
317
+ let prev;
318
+ let code;
319
+ let token = {
320
+ value: "",
321
+ depth: 0,
322
+ isGlob: false
323
+ };
324
+ const eos = () => index >= length;
325
+ const peek = () => str.charCodeAt(index + 1);
326
+ const advance = () => {
327
+ prev = code;
328
+ return str.charCodeAt(++index);
329
+ };
330
+ while (index < length) {
331
+ code = advance();
332
+ let next;
333
+ if (code === CHAR_BACKWARD_SLASH) {
334
+ backslashes = token.backslashes = true;
335
+ code = advance();
336
+ if (code === CHAR_LEFT_CURLY_BRACE) {
337
+ braceEscaped = true;
338
+ }
339
+ continue;
340
+ }
341
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
342
+ braces++;
343
+ while (eos() !== true && (code = advance())) {
344
+ if (code === CHAR_BACKWARD_SLASH) {
345
+ backslashes = token.backslashes = true;
346
+ advance();
347
+ continue;
348
+ }
349
+ if (code === CHAR_LEFT_CURLY_BRACE) {
350
+ braces++;
351
+ continue;
352
+ }
353
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
354
+ isBrace = token.isBrace = true;
355
+ isGlob = token.isGlob = true;
356
+ finished = true;
357
+ if (scanToEnd === true) {
358
+ continue;
359
+ }
360
+ break;
361
+ }
362
+ if (braceEscaped !== true && code === CHAR_COMMA) {
363
+ isBrace = token.isBrace = true;
364
+ isGlob = token.isGlob = true;
365
+ finished = true;
366
+ if (scanToEnd === true) {
367
+ continue;
368
+ }
369
+ break;
370
+ }
371
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
372
+ braces--;
373
+ if (braces === 0) {
374
+ braceEscaped = false;
375
+ isBrace = token.isBrace = true;
376
+ finished = true;
377
+ break;
378
+ }
379
+ }
380
+ }
381
+ if (scanToEnd === true) {
382
+ continue;
383
+ }
384
+ break;
385
+ }
386
+ if (code === CHAR_FORWARD_SLASH) {
387
+ slashes.push(index);
388
+ tokens.push(token);
389
+ token = {
390
+ value: "",
391
+ depth: 0,
392
+ isGlob: false
393
+ };
394
+ if (finished === true) continue;
395
+ if (prev === CHAR_DOT && index === start + 1) {
396
+ start += 2;
397
+ continue;
398
+ }
399
+ lastIndex = index + 1;
400
+ continue;
401
+ }
402
+ if (opts.noext !== true) {
403
+ const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
404
+ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
405
+ isGlob = token.isGlob = true;
406
+ isExtglob = token.isExtglob = true;
407
+ finished = true;
408
+ if (code === CHAR_EXCLAMATION_MARK && index === start) {
409
+ negatedExtglob = true;
410
+ }
411
+ if (scanToEnd === true) {
412
+ while (eos() !== true && (code = advance())) {
413
+ if (code === CHAR_BACKWARD_SLASH) {
414
+ backslashes = token.backslashes = true;
415
+ code = advance();
416
+ continue;
417
+ }
418
+ if (code === CHAR_RIGHT_PARENTHESES) {
419
+ isGlob = token.isGlob = true;
420
+ finished = true;
421
+ break;
422
+ }
423
+ }
424
+ continue;
425
+ }
426
+ break;
427
+ }
428
+ }
429
+ if (code === CHAR_ASTERISK) {
430
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
431
+ isGlob = token.isGlob = true;
432
+ finished = true;
433
+ if (scanToEnd === true) {
434
+ continue;
435
+ }
436
+ break;
437
+ }
438
+ if (code === CHAR_QUESTION_MARK) {
439
+ isGlob = token.isGlob = true;
440
+ finished = true;
441
+ if (scanToEnd === true) {
442
+ continue;
443
+ }
444
+ break;
445
+ }
446
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
447
+ while (eos() !== true && (next = advance())) {
448
+ if (next === CHAR_BACKWARD_SLASH) {
449
+ backslashes = token.backslashes = true;
450
+ advance();
451
+ continue;
452
+ }
453
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
454
+ isBracket = token.isBracket = true;
455
+ isGlob = token.isGlob = true;
456
+ finished = true;
457
+ break;
458
+ }
459
+ }
460
+ if (scanToEnd === true) {
461
+ continue;
462
+ }
463
+ break;
464
+ }
465
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
466
+ negated = token.negated = true;
467
+ start++;
468
+ continue;
469
+ }
470
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
471
+ isGlob = token.isGlob = true;
472
+ if (scanToEnd === true) {
473
+ while (eos() !== true && (code = advance())) {
474
+ if (code === CHAR_LEFT_PARENTHESES) {
475
+ backslashes = token.backslashes = true;
476
+ code = advance();
477
+ continue;
478
+ }
479
+ if (code === CHAR_RIGHT_PARENTHESES) {
480
+ finished = true;
481
+ break;
482
+ }
483
+ }
484
+ continue;
485
+ }
486
+ break;
487
+ }
488
+ if (isGlob === true) {
489
+ finished = true;
490
+ if (scanToEnd === true) {
491
+ continue;
492
+ }
493
+ break;
494
+ }
495
+ }
496
+ if (opts.noext === true) {
497
+ isExtglob = false;
498
+ isGlob = false;
499
+ }
500
+ let base = str;
501
+ let prefix = "";
502
+ let glob = "";
503
+ if (start > 0) {
504
+ prefix = str.slice(0, start);
505
+ str = str.slice(start);
506
+ lastIndex -= start;
507
+ }
508
+ if (base && isGlob === true && lastIndex > 0) {
509
+ base = str.slice(0, lastIndex);
510
+ glob = str.slice(lastIndex);
511
+ } else if (isGlob === true) {
512
+ base = "";
513
+ glob = str;
514
+ } else {
515
+ base = str;
516
+ }
517
+ if (base && base !== "" && base !== "/" && base !== str) {
518
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
519
+ base = base.slice(0, -1);
520
+ }
521
+ }
522
+ if (opts.unescape === true) {
523
+ if (glob) glob = utils$3.removeBackslashes(glob);
524
+ if (base && backslashes === true) {
525
+ base = utils$3.removeBackslashes(base);
526
+ }
527
+ }
528
+ const state = {
529
+ prefix,
530
+ input,
531
+ start,
532
+ base,
533
+ glob,
534
+ isBrace,
535
+ isBracket,
536
+ isGlob,
537
+ isExtglob,
538
+ isGlobstar,
539
+ negated,
540
+ negatedExtglob
541
+ };
542
+ if (opts.tokens === true) {
543
+ state.maxDepth = 0;
544
+ if (!isPathSeparator(code)) {
545
+ tokens.push(token);
546
+ }
547
+ state.tokens = tokens;
548
+ }
549
+ if (opts.parts === true || opts.tokens === true) {
550
+ let prevIndex;
551
+ for (let idx = 0; idx < slashes.length; idx++) {
552
+ const n = prevIndex ? prevIndex + 1 : start;
553
+ const i = slashes[idx];
554
+ const value = input.slice(n, i);
555
+ if (opts.tokens) {
556
+ if (idx === 0 && start !== 0) {
557
+ tokens[idx].isPrefix = true;
558
+ tokens[idx].value = prefix;
559
+ } else {
560
+ tokens[idx].value = value;
561
+ }
562
+ depth(tokens[idx]);
563
+ state.maxDepth += tokens[idx].depth;
564
+ }
565
+ if (idx !== 0 || value !== "") {
566
+ parts.push(value);
567
+ }
568
+ prevIndex = i;
569
+ }
570
+ if (prevIndex && prevIndex + 1 < input.length) {
571
+ const value = input.slice(prevIndex + 1);
572
+ parts.push(value);
573
+ if (opts.tokens) {
574
+ tokens[tokens.length - 1].value = value;
575
+ depth(tokens[tokens.length - 1]);
576
+ state.maxDepth += tokens[tokens.length - 1].depth;
577
+ }
578
+ }
579
+ state.slashes = slashes;
580
+ state.parts = parts;
581
+ }
582
+ return state;
583
+ };
584
+ module.exports = scan$1;
585
+ }));
586
+
587
+ //#endregion
588
+ //#region node_modules/picomatch/lib/parse.js
589
+ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
590
+ const constants$1 = require_constants();
591
+ const utils$2 = require_utils();
592
+ /**
593
+ * Constants
594
+ */
595
+ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
596
+ /**
597
+ * Helpers
598
+ */
599
+ const expandRange = (args, options) => {
600
+ if (typeof options.expandRange === "function") {
601
+ return options.expandRange(...args, options);
602
+ }
603
+ args.sort();
604
+ const value = `[${args.join("-")}]`;
605
+ try {
606
+ new RegExp(value);
607
+ } catch (ex) {
608
+ return args.map((v) => utils$2.escapeRegex(v)).join("..");
609
+ }
610
+ return value;
611
+ };
612
+ /**
613
+ * Create the message for a syntax error
614
+ */
615
+ const syntaxError = (type, char) => {
616
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
617
+ };
618
+ /**
619
+ * Parse the given input string.
620
+ * @param {String} input
621
+ * @param {Object} options
622
+ * @return {Object}
623
+ */
624
+ const parse$2 = (input, options) => {
625
+ if (typeof input !== "string") {
626
+ throw new TypeError("Expected a string");
627
+ }
628
+ input = REPLACEMENTS[input] || input;
629
+ const opts = { ...options };
630
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
631
+ let len = input.length;
632
+ if (len > max) {
633
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
634
+ }
635
+ const bos = {
636
+ type: "bos",
637
+ value: "",
638
+ output: opts.prepend || ""
639
+ };
640
+ const tokens = [bos];
641
+ const capture = opts.capture ? "" : "?:";
642
+ const PLATFORM_CHARS = constants$1.globChars(opts.windows);
643
+ const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
644
+ const { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOT_SLASH: NO_DOT_SLASH$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, QMARK: QMARK$1, QMARK_NO_DOT: QMARK_NO_DOT$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 } = PLATFORM_CHARS;
645
+ const globstar = (opts$1) => {
646
+ return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
647
+ };
648
+ const nodot = opts.dot ? "" : NO_DOT$1;
649
+ const qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT$1;
650
+ let star = opts.bash === true ? globstar(opts) : STAR$1;
651
+ if (opts.capture) {
652
+ star = `(${star})`;
653
+ }
654
+ if (typeof opts.noext === "boolean") {
655
+ opts.noextglob = opts.noext;
656
+ }
657
+ const state = {
658
+ input,
659
+ index: -1,
660
+ start: 0,
661
+ dot: opts.dot === true,
662
+ consumed: "",
663
+ output: "",
664
+ prefix: "",
665
+ backtrack: false,
666
+ negated: false,
667
+ brackets: 0,
668
+ braces: 0,
669
+ parens: 0,
670
+ quotes: 0,
671
+ globstar: false,
672
+ tokens
673
+ };
674
+ input = utils$2.removePrefix(input, state);
675
+ len = input.length;
676
+ const extglobs = [];
677
+ const braces = [];
678
+ const stack = [];
679
+ let prev = bos;
680
+ let value;
681
+ /**
682
+ * Tokenizing helpers
683
+ */
684
+ const eos = () => state.index === len - 1;
685
+ const peek = state.peek = (n = 1) => input[state.index + n];
686
+ const advance = state.advance = () => input[++state.index] || "";
687
+ const remaining = () => input.slice(state.index + 1);
688
+ const consume = (value$1 = "", num = 0) => {
689
+ state.consumed += value$1;
690
+ state.index += num;
691
+ };
692
+ const append = (token) => {
693
+ state.output += token.output != null ? token.output : token.value;
694
+ consume(token.value);
695
+ };
696
+ const negate = () => {
697
+ let count = 1;
698
+ while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
699
+ advance();
700
+ state.start++;
701
+ count++;
702
+ }
703
+ if (count % 2 === 0) {
704
+ return false;
705
+ }
706
+ state.negated = true;
707
+ state.start++;
708
+ return true;
709
+ };
710
+ const increment = (type) => {
711
+ state[type]++;
712
+ stack.push(type);
713
+ };
714
+ const decrement = (type) => {
715
+ state[type]--;
716
+ stack.pop();
717
+ };
718
+ /**
719
+ * Push tokens onto the tokens array. This helper speeds up
720
+ * tokenizing by 1) helping us avoid backtracking as much as possible,
721
+ * and 2) helping us avoid creating extra tokens when consecutive
722
+ * characters are plain text. This improves performance and simplifies
723
+ * lookbehinds.
724
+ */
725
+ const push = (tok) => {
726
+ if (prev.type === "globstar") {
727
+ const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
728
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
729
+ if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
730
+ state.output = state.output.slice(0, -prev.output.length);
731
+ prev.type = "star";
732
+ prev.value = "*";
733
+ prev.output = star;
734
+ state.output += prev.output;
735
+ }
736
+ }
737
+ if (extglobs.length && tok.type !== "paren") {
738
+ extglobs[extglobs.length - 1].inner += tok.value;
739
+ }
740
+ if (tok.value || tok.output) append(tok);
741
+ if (prev && prev.type === "text" && tok.type === "text") {
742
+ prev.output = (prev.output || prev.value) + tok.value;
743
+ prev.value += tok.value;
744
+ return;
745
+ }
746
+ tok.prev = prev;
747
+ tokens.push(tok);
748
+ prev = tok;
749
+ };
750
+ const extglobOpen = (type, value$1) => {
751
+ const token = {
752
+ ...EXTGLOB_CHARS[value$1],
753
+ conditions: 1,
754
+ inner: ""
755
+ };
756
+ token.prev = prev;
757
+ token.parens = state.parens;
758
+ token.output = state.output;
759
+ const output = (opts.capture ? "(" : "") + token.open;
760
+ increment("parens");
761
+ push({
762
+ type,
763
+ value: value$1,
764
+ output: state.output ? "" : ONE_CHAR$1
765
+ });
766
+ push({
767
+ type: "paren",
768
+ extglob: true,
769
+ value: advance(),
770
+ output
771
+ });
772
+ extglobs.push(token);
773
+ };
774
+ const extglobClose = (token) => {
775
+ let output = token.close + (opts.capture ? ")" : "");
776
+ let rest;
777
+ if (token.type === "negate") {
778
+ let extglobStar = star;
779
+ if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
780
+ extglobStar = globstar(opts);
781
+ }
782
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
783
+ output = token.close = `)$))${extglobStar}`;
784
+ }
785
+ if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
786
+ const expression = parse$2(rest, {
787
+ ...options,
788
+ fastpaths: false
789
+ }).output;
790
+ output = token.close = `)${expression})${extglobStar})`;
791
+ }
792
+ if (token.prev.type === "bos") {
793
+ state.negatedExtglob = true;
794
+ }
795
+ }
796
+ push({
797
+ type: "paren",
798
+ extglob: true,
799
+ value,
800
+ output
801
+ });
802
+ decrement("parens");
803
+ };
804
+ /**
805
+ * Fast paths
806
+ */
807
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
808
+ let backslashes = false;
809
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
810
+ if (first === "\\") {
811
+ backslashes = true;
812
+ return m;
813
+ }
814
+ if (first === "?") {
815
+ if (esc) {
816
+ return esc + first + (rest ? QMARK$1.repeat(rest.length) : "");
817
+ }
818
+ if (index === 0) {
819
+ return qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : "");
820
+ }
821
+ return QMARK$1.repeat(chars.length);
822
+ }
823
+ if (first === ".") {
824
+ return DOT_LITERAL$1.repeat(chars.length);
825
+ }
826
+ if (first === "*") {
827
+ if (esc) {
828
+ return esc + first + (rest ? star : "");
829
+ }
830
+ return star;
831
+ }
832
+ return esc ? m : `\\${m}`;
833
+ });
834
+ if (backslashes === true) {
835
+ if (opts.unescape === true) {
836
+ output = output.replace(/\\/g, "");
837
+ } else {
838
+ output = output.replace(/\\+/g, (m) => {
839
+ return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
840
+ });
841
+ }
842
+ }
843
+ if (output === input && opts.contains === true) {
844
+ state.output = input;
845
+ return state;
846
+ }
847
+ state.output = utils$2.wrapOutput(output, state, options);
848
+ return state;
849
+ }
850
+ /**
851
+ * Tokenize input until we reach end-of-string
852
+ */
853
+ while (!eos()) {
854
+ value = advance();
855
+ if (value === "\0") {
856
+ continue;
857
+ }
858
+ /**
859
+ * Escaped characters
860
+ */
861
+ if (value === "\\") {
862
+ const next = peek();
863
+ if (next === "/" && opts.bash !== true) {
864
+ continue;
865
+ }
866
+ if (next === "." || next === ";") {
867
+ continue;
868
+ }
869
+ if (!next) {
870
+ value += "\\";
871
+ push({
872
+ type: "text",
873
+ value
874
+ });
875
+ continue;
876
+ }
877
+ const match = /^\\+/.exec(remaining());
878
+ let slashes = 0;
879
+ if (match && match[0].length > 2) {
880
+ slashes = match[0].length;
881
+ state.index += slashes;
882
+ if (slashes % 2 !== 0) {
883
+ value += "\\";
884
+ }
885
+ }
886
+ if (opts.unescape === true) {
887
+ value = advance();
888
+ } else {
889
+ value += advance();
890
+ }
891
+ if (state.brackets === 0) {
892
+ push({
893
+ type: "text",
894
+ value
895
+ });
896
+ continue;
897
+ }
898
+ }
899
+ /**
900
+ * If we're inside a regex character class, continue
901
+ * until we reach the closing bracket.
902
+ */
903
+ if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
904
+ if (opts.posix !== false && value === ":") {
905
+ const inner = prev.value.slice(1);
906
+ if (inner.includes("[")) {
907
+ prev.posix = true;
908
+ if (inner.includes(":")) {
909
+ const idx = prev.value.lastIndexOf("[");
910
+ const pre = prev.value.slice(0, idx);
911
+ const rest$1 = prev.value.slice(idx + 2);
912
+ const posix = POSIX_REGEX_SOURCE[rest$1];
913
+ if (posix) {
914
+ prev.value = pre + posix;
915
+ state.backtrack = true;
916
+ advance();
917
+ if (!bos.output && tokens.indexOf(prev) === 1) {
918
+ bos.output = ONE_CHAR$1;
919
+ }
920
+ continue;
921
+ }
922
+ }
923
+ }
924
+ }
925
+ if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
926
+ value = `\\${value}`;
927
+ }
928
+ if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
929
+ value = `\\${value}`;
930
+ }
931
+ if (opts.posix === true && value === "!" && prev.value === "[") {
932
+ value = "^";
933
+ }
934
+ prev.value += value;
935
+ append({ value });
936
+ continue;
937
+ }
938
+ /**
939
+ * If we're inside a quoted string, continue
940
+ * until we reach the closing double quote.
941
+ */
942
+ if (state.quotes === 1 && value !== "\"") {
943
+ value = utils$2.escapeRegex(value);
944
+ prev.value += value;
945
+ append({ value });
946
+ continue;
947
+ }
948
+ /**
949
+ * Double quotes
950
+ */
951
+ if (value === "\"") {
952
+ state.quotes = state.quotes === 1 ? 0 : 1;
953
+ if (opts.keepQuotes === true) {
954
+ push({
955
+ type: "text",
956
+ value
957
+ });
958
+ }
959
+ continue;
960
+ }
961
+ /**
962
+ * Parentheses
963
+ */
964
+ if (value === "(") {
965
+ increment("parens");
966
+ push({
967
+ type: "paren",
968
+ value
969
+ });
970
+ continue;
971
+ }
972
+ if (value === ")") {
973
+ if (state.parens === 0 && opts.strictBrackets === true) {
974
+ throw new SyntaxError(syntaxError("opening", "("));
975
+ }
976
+ const extglob = extglobs[extglobs.length - 1];
977
+ if (extglob && state.parens === extglob.parens + 1) {
978
+ extglobClose(extglobs.pop());
979
+ continue;
980
+ }
981
+ push({
982
+ type: "paren",
983
+ value,
984
+ output: state.parens ? ")" : "\\)"
985
+ });
986
+ decrement("parens");
987
+ continue;
988
+ }
989
+ /**
990
+ * Square brackets
991
+ */
992
+ if (value === "[") {
993
+ if (opts.nobracket === true || !remaining().includes("]")) {
994
+ if (opts.nobracket !== true && opts.strictBrackets === true) {
995
+ throw new SyntaxError(syntaxError("closing", "]"));
996
+ }
997
+ value = `\\${value}`;
998
+ } else {
999
+ increment("brackets");
1000
+ }
1001
+ push({
1002
+ type: "bracket",
1003
+ value
1004
+ });
1005
+ continue;
1006
+ }
1007
+ if (value === "]") {
1008
+ if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
1009
+ push({
1010
+ type: "text",
1011
+ value,
1012
+ output: `\\${value}`
1013
+ });
1014
+ continue;
1015
+ }
1016
+ if (state.brackets === 0) {
1017
+ if (opts.strictBrackets === true) {
1018
+ throw new SyntaxError(syntaxError("opening", "["));
1019
+ }
1020
+ push({
1021
+ type: "text",
1022
+ value,
1023
+ output: `\\${value}`
1024
+ });
1025
+ continue;
1026
+ }
1027
+ decrement("brackets");
1028
+ const prevValue = prev.value.slice(1);
1029
+ if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
1030
+ value = `/${value}`;
1031
+ }
1032
+ prev.value += value;
1033
+ append({ value });
1034
+ if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
1035
+ continue;
1036
+ }
1037
+ const escaped = utils$2.escapeRegex(prev.value);
1038
+ state.output = state.output.slice(0, -prev.value.length);
1039
+ if (opts.literalBrackets === true) {
1040
+ state.output += escaped;
1041
+ prev.value = escaped;
1042
+ continue;
1043
+ }
1044
+ prev.value = `(${capture}${escaped}|${prev.value})`;
1045
+ state.output += prev.value;
1046
+ continue;
1047
+ }
1048
+ /**
1049
+ * Braces
1050
+ */
1051
+ if (value === "{" && opts.nobrace !== true) {
1052
+ increment("braces");
1053
+ const open = {
1054
+ type: "brace",
1055
+ value,
1056
+ output: "(",
1057
+ outputIndex: state.output.length,
1058
+ tokensIndex: state.tokens.length
1059
+ };
1060
+ braces.push(open);
1061
+ push(open);
1062
+ continue;
1063
+ }
1064
+ if (value === "}") {
1065
+ const brace = braces[braces.length - 1];
1066
+ if (opts.nobrace === true || !brace) {
1067
+ push({
1068
+ type: "text",
1069
+ value,
1070
+ output: value
1071
+ });
1072
+ continue;
1073
+ }
1074
+ let output = ")";
1075
+ if (brace.dots === true) {
1076
+ const arr = tokens.slice();
1077
+ const range = [];
1078
+ for (let i = arr.length - 1; i >= 0; i--) {
1079
+ tokens.pop();
1080
+ if (arr[i].type === "brace") {
1081
+ break;
1082
+ }
1083
+ if (arr[i].type !== "dots") {
1084
+ range.unshift(arr[i].value);
1085
+ }
1086
+ }
1087
+ output = expandRange(range, opts);
1088
+ state.backtrack = true;
1089
+ }
1090
+ if (brace.comma !== true && brace.dots !== true) {
1091
+ const out = state.output.slice(0, brace.outputIndex);
1092
+ const toks = state.tokens.slice(brace.tokensIndex);
1093
+ brace.value = brace.output = "\\{";
1094
+ value = output = "\\}";
1095
+ state.output = out;
1096
+ for (const t of toks) {
1097
+ state.output += t.output || t.value;
1098
+ }
1099
+ }
1100
+ push({
1101
+ type: "brace",
1102
+ value,
1103
+ output
1104
+ });
1105
+ decrement("braces");
1106
+ braces.pop();
1107
+ continue;
1108
+ }
1109
+ /**
1110
+ * Pipes
1111
+ */
1112
+ if (value === "|") {
1113
+ if (extglobs.length > 0) {
1114
+ extglobs[extglobs.length - 1].conditions++;
1115
+ }
1116
+ push({
1117
+ type: "text",
1118
+ value
1119
+ });
1120
+ continue;
1121
+ }
1122
+ /**
1123
+ * Commas
1124
+ */
1125
+ if (value === ",") {
1126
+ let output = value;
1127
+ const brace = braces[braces.length - 1];
1128
+ if (brace && stack[stack.length - 1] === "braces") {
1129
+ brace.comma = true;
1130
+ output = "|";
1131
+ }
1132
+ push({
1133
+ type: "comma",
1134
+ value,
1135
+ output
1136
+ });
1137
+ continue;
1138
+ }
1139
+ /**
1140
+ * Slashes
1141
+ */
1142
+ if (value === "/") {
1143
+ if (prev.type === "dot" && state.index === state.start + 1) {
1144
+ state.start = state.index + 1;
1145
+ state.consumed = "";
1146
+ state.output = "";
1147
+ tokens.pop();
1148
+ prev = bos;
1149
+ continue;
1150
+ }
1151
+ push({
1152
+ type: "slash",
1153
+ value,
1154
+ output: SLASH_LITERAL$1
1155
+ });
1156
+ continue;
1157
+ }
1158
+ /**
1159
+ * Dots
1160
+ */
1161
+ if (value === ".") {
1162
+ if (state.braces > 0 && prev.type === "dot") {
1163
+ if (prev.value === ".") prev.output = DOT_LITERAL$1;
1164
+ const brace = braces[braces.length - 1];
1165
+ prev.type = "dots";
1166
+ prev.output += value;
1167
+ prev.value += value;
1168
+ brace.dots = true;
1169
+ continue;
1170
+ }
1171
+ if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
1172
+ push({
1173
+ type: "text",
1174
+ value,
1175
+ output: DOT_LITERAL$1
1176
+ });
1177
+ continue;
1178
+ }
1179
+ push({
1180
+ type: "dot",
1181
+ value,
1182
+ output: DOT_LITERAL$1
1183
+ });
1184
+ continue;
1185
+ }
1186
+ /**
1187
+ * Question marks
1188
+ */
1189
+ if (value === "?") {
1190
+ const isGroup = prev && prev.value === "(";
1191
+ if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1192
+ extglobOpen("qmark", value);
1193
+ continue;
1194
+ }
1195
+ if (prev && prev.type === "paren") {
1196
+ const next = peek();
1197
+ let output = value;
1198
+ if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
1199
+ output = `\\${value}`;
1200
+ }
1201
+ push({
1202
+ type: "text",
1203
+ value,
1204
+ output
1205
+ });
1206
+ continue;
1207
+ }
1208
+ if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
1209
+ push({
1210
+ type: "qmark",
1211
+ value,
1212
+ output: QMARK_NO_DOT$1
1213
+ });
1214
+ continue;
1215
+ }
1216
+ push({
1217
+ type: "qmark",
1218
+ value,
1219
+ output: QMARK$1
1220
+ });
1221
+ continue;
1222
+ }
1223
+ /**
1224
+ * Exclamation
1225
+ */
1226
+ if (value === "!") {
1227
+ if (opts.noextglob !== true && peek() === "(") {
1228
+ if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
1229
+ extglobOpen("negate", value);
1230
+ continue;
1231
+ }
1232
+ }
1233
+ if (opts.nonegate !== true && state.index === 0) {
1234
+ negate();
1235
+ continue;
1236
+ }
1237
+ }
1238
+ /**
1239
+ * Plus
1240
+ */
1241
+ if (value === "+") {
1242
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1243
+ extglobOpen("plus", value);
1244
+ continue;
1245
+ }
1246
+ if (prev && prev.value === "(" || opts.regex === false) {
1247
+ push({
1248
+ type: "plus",
1249
+ value,
1250
+ output: PLUS_LITERAL$1
1251
+ });
1252
+ continue;
1253
+ }
1254
+ if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
1255
+ push({
1256
+ type: "plus",
1257
+ value
1258
+ });
1259
+ continue;
1260
+ }
1261
+ push({
1262
+ type: "plus",
1263
+ value: PLUS_LITERAL$1
1264
+ });
1265
+ continue;
1266
+ }
1267
+ /**
1268
+ * Plain text
1269
+ */
1270
+ if (value === "@") {
1271
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1272
+ push({
1273
+ type: "at",
1274
+ extglob: true,
1275
+ value,
1276
+ output: ""
1277
+ });
1278
+ continue;
1279
+ }
1280
+ push({
1281
+ type: "text",
1282
+ value
1283
+ });
1284
+ continue;
1285
+ }
1286
+ /**
1287
+ * Plain text
1288
+ */
1289
+ if (value !== "*") {
1290
+ if (value === "$" || value === "^") {
1291
+ value = `\\${value}`;
1292
+ }
1293
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1294
+ if (match) {
1295
+ value += match[0];
1296
+ state.index += match[0].length;
1297
+ }
1298
+ push({
1299
+ type: "text",
1300
+ value
1301
+ });
1302
+ continue;
1303
+ }
1304
+ /**
1305
+ * Stars
1306
+ */
1307
+ if (prev && (prev.type === "globstar" || prev.star === true)) {
1308
+ prev.type = "star";
1309
+ prev.star = true;
1310
+ prev.value += value;
1311
+ prev.output = star;
1312
+ state.backtrack = true;
1313
+ state.globstar = true;
1314
+ consume(value);
1315
+ continue;
1316
+ }
1317
+ let rest = remaining();
1318
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1319
+ extglobOpen("star", value);
1320
+ continue;
1321
+ }
1322
+ if (prev.type === "star") {
1323
+ if (opts.noglobstar === true) {
1324
+ consume(value);
1325
+ continue;
1326
+ }
1327
+ const prior = prev.prev;
1328
+ const before = prior.prev;
1329
+ const isStart = prior.type === "slash" || prior.type === "bos";
1330
+ const afterStar = before && (before.type === "star" || before.type === "globstar");
1331
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
1332
+ push({
1333
+ type: "star",
1334
+ value,
1335
+ output: ""
1336
+ });
1337
+ continue;
1338
+ }
1339
+ const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
1340
+ const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
1341
+ if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
1342
+ push({
1343
+ type: "star",
1344
+ value,
1345
+ output: ""
1346
+ });
1347
+ continue;
1348
+ }
1349
+ while (rest.slice(0, 3) === "/**") {
1350
+ const after = input[state.index + 4];
1351
+ if (after && after !== "/") {
1352
+ break;
1353
+ }
1354
+ rest = rest.slice(3);
1355
+ consume("/**", 3);
1356
+ }
1357
+ if (prior.type === "bos" && eos()) {
1358
+ prev.type = "globstar";
1359
+ prev.value += value;
1360
+ prev.output = globstar(opts);
1361
+ state.output = prev.output;
1362
+ state.globstar = true;
1363
+ consume(value);
1364
+ continue;
1365
+ }
1366
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1367
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1368
+ prior.output = `(?:${prior.output}`;
1369
+ prev.type = "globstar";
1370
+ prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
1371
+ prev.value += value;
1372
+ state.globstar = true;
1373
+ state.output += prior.output + prev.output;
1374
+ consume(value);
1375
+ continue;
1376
+ }
1377
+ if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
1378
+ const end = rest[1] !== void 0 ? "|$" : "";
1379
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1380
+ prior.output = `(?:${prior.output}`;
1381
+ prev.type = "globstar";
1382
+ prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`;
1383
+ prev.value += value;
1384
+ state.output += prior.output + prev.output;
1385
+ state.globstar = true;
1386
+ consume(value + advance());
1387
+ push({
1388
+ type: "slash",
1389
+ value: "/",
1390
+ output: ""
1391
+ });
1392
+ continue;
1393
+ }
1394
+ if (prior.type === "bos" && rest[0] === "/") {
1395
+ prev.type = "globstar";
1396
+ prev.value += value;
1397
+ prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`;
1398
+ state.output = prev.output;
1399
+ state.globstar = true;
1400
+ consume(value + advance());
1401
+ push({
1402
+ type: "slash",
1403
+ value: "/",
1404
+ output: ""
1405
+ });
1406
+ continue;
1407
+ }
1408
+ state.output = state.output.slice(0, -prev.output.length);
1409
+ prev.type = "globstar";
1410
+ prev.output = globstar(opts);
1411
+ prev.value += value;
1412
+ state.output += prev.output;
1413
+ state.globstar = true;
1414
+ consume(value);
1415
+ continue;
1416
+ }
1417
+ const token = {
1418
+ type: "star",
1419
+ value,
1420
+ output: star
1421
+ };
1422
+ if (opts.bash === true) {
1423
+ token.output = ".*?";
1424
+ if (prev.type === "bos" || prev.type === "slash") {
1425
+ token.output = nodot + token.output;
1426
+ }
1427
+ push(token);
1428
+ continue;
1429
+ }
1430
+ if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
1431
+ token.output = value;
1432
+ push(token);
1433
+ continue;
1434
+ }
1435
+ if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
1436
+ if (prev.type === "dot") {
1437
+ state.output += NO_DOT_SLASH$1;
1438
+ prev.output += NO_DOT_SLASH$1;
1439
+ } else if (opts.dot === true) {
1440
+ state.output += NO_DOTS_SLASH$1;
1441
+ prev.output += NO_DOTS_SLASH$1;
1442
+ } else {
1443
+ state.output += nodot;
1444
+ prev.output += nodot;
1445
+ }
1446
+ if (peek() !== "*") {
1447
+ state.output += ONE_CHAR$1;
1448
+ prev.output += ONE_CHAR$1;
1449
+ }
1450
+ }
1451
+ push(token);
1452
+ }
1453
+ while (state.brackets > 0) {
1454
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1455
+ state.output = utils$2.escapeLast(state.output, "[");
1456
+ decrement("brackets");
1457
+ }
1458
+ while (state.parens > 0) {
1459
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
1460
+ state.output = utils$2.escapeLast(state.output, "(");
1461
+ decrement("parens");
1462
+ }
1463
+ while (state.braces > 0) {
1464
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
1465
+ state.output = utils$2.escapeLast(state.output, "{");
1466
+ decrement("braces");
1467
+ }
1468
+ if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
1469
+ push({
1470
+ type: "maybe_slash",
1471
+ value: "",
1472
+ output: `${SLASH_LITERAL$1}?`
1473
+ });
1474
+ }
1475
+ if (state.backtrack === true) {
1476
+ state.output = "";
1477
+ for (const token of state.tokens) {
1478
+ state.output += token.output != null ? token.output : token.value;
1479
+ if (token.suffix) {
1480
+ state.output += token.suffix;
1481
+ }
1482
+ }
1483
+ }
1484
+ return state;
1485
+ };
1486
+ /**
1487
+ * Fast paths for creating regular expressions for common glob patterns.
1488
+ * This can significantly speed up processing and has very little downside
1489
+ * impact when none of the fast paths match.
1490
+ */
1491
+ parse$2.fastpaths = (input, options) => {
1492
+ const opts = { ...options };
1493
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1494
+ const len = input.length;
1495
+ if (len > max) {
1496
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1497
+ }
1498
+ input = REPLACEMENTS[input] || input;
1499
+ const { DOT_LITERAL: DOT_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOTS: NO_DOTS$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 } = constants$1.globChars(opts.windows);
1500
+ const nodot = opts.dot ? NO_DOTS$1 : NO_DOT$1;
1501
+ const slashDot = opts.dot ? NO_DOTS_SLASH$1 : NO_DOT$1;
1502
+ const capture = opts.capture ? "" : "?:";
1503
+ const state = {
1504
+ negated: false,
1505
+ prefix: ""
1506
+ };
1507
+ let star = opts.bash === true ? ".*?" : STAR$1;
1508
+ if (opts.capture) {
1509
+ star = `(${star})`;
1510
+ }
1511
+ const globstar = (opts$1) => {
1512
+ if (opts$1.noglobstar === true) return star;
1513
+ return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
1514
+ };
1515
+ const create = (str) => {
1516
+ switch (str) {
1517
+ case "*": return `${nodot}${ONE_CHAR$1}${star}`;
1518
+ case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1519
+ case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1520
+ case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`;
1521
+ case "**": return nodot + globstar(opts);
1522
+ case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`;
1523
+ case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1524
+ case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1525
+ default: {
1526
+ const match = /^(.*?)\.(\w+)$/.exec(str);
1527
+ if (!match) return;
1528
+ const source$1 = create(match[1]);
1529
+ if (!source$1) return;
1530
+ return source$1 + DOT_LITERAL$1 + match[2];
1531
+ }
1532
+ }
1533
+ };
1534
+ const output = utils$2.removePrefix(input, state);
1535
+ let source = create(output);
1536
+ if (source && opts.strictSlashes !== true) {
1537
+ source += `${SLASH_LITERAL$1}?`;
1538
+ }
1539
+ return source;
1540
+ };
1541
+ module.exports = parse$2;
1542
+ }));
1543
+
1544
+ //#endregion
1545
+ //#region node_modules/picomatch/lib/picomatch.js
1546
+ var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1547
+ const scan = require_scan();
1548
+ const parse$1 = require_parse();
1549
+ const utils$1 = require_utils();
1550
+ const constants = require_constants();
1551
+ const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
1552
+ /**
1553
+ * Creates a matcher function from one or more glob patterns. The
1554
+ * returned function takes a string to match as its first argument,
1555
+ * and returns true if the string is a match. The returned matcher
1556
+ * function also takes a boolean as the second argument that, when true,
1557
+ * returns an object with additional information.
1558
+ *
1559
+ * ```js
1560
+ * const picomatch = require('picomatch');
1561
+ * // picomatch(glob[, options]);
1562
+ *
1563
+ * const isMatch = picomatch('*.!(*a)');
1564
+ * console.log(isMatch('a.a')); //=> false
1565
+ * console.log(isMatch('a.b')); //=> true
1566
+ * ```
1567
+ * @name picomatch
1568
+ * @param {String|Array} `globs` One or more glob patterns.
1569
+ * @param {Object=} `options`
1570
+ * @return {Function=} Returns a matcher function.
1571
+ * @api public
1572
+ */
1573
+ const picomatch$2 = (glob, options, returnState = false) => {
1574
+ if (Array.isArray(glob)) {
1575
+ const fns = glob.map((input) => picomatch$2(input, options, returnState));
1576
+ const arrayMatcher = (str) => {
1577
+ for (const isMatch of fns) {
1578
+ const state$1 = isMatch(str);
1579
+ if (state$1) return state$1;
1580
+ }
1581
+ return false;
1582
+ };
1583
+ return arrayMatcher;
1584
+ }
1585
+ const isState = isObject(glob) && glob.tokens && glob.input;
1586
+ if (glob === "" || typeof glob !== "string" && !isState) {
1587
+ throw new TypeError("Expected pattern to be a non-empty string");
1588
+ }
1589
+ const opts = options || {};
1590
+ const posix = opts.windows;
1591
+ const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.makeRe(glob, options, false, true);
1592
+ const state = regex.state;
1593
+ delete regex.state;
1594
+ let isIgnored = () => false;
1595
+ if (opts.ignore) {
1596
+ const ignoreOpts = {
1597
+ ...options,
1598
+ ignore: null,
1599
+ onMatch: null,
1600
+ onResult: null
1601
+ };
1602
+ isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
1603
+ }
1604
+ const matcher = (input, returnObject = false) => {
1605
+ const { isMatch, match, output } = picomatch$2.test(input, regex, options, {
1606
+ glob,
1607
+ posix
1608
+ });
1609
+ const result = {
1610
+ glob,
1611
+ state,
1612
+ regex,
1613
+ posix,
1614
+ input,
1615
+ output,
1616
+ match,
1617
+ isMatch
1618
+ };
1619
+ if (typeof opts.onResult === "function") {
1620
+ opts.onResult(result);
1621
+ }
1622
+ if (isMatch === false) {
1623
+ result.isMatch = false;
1624
+ return returnObject ? result : false;
1625
+ }
1626
+ if (isIgnored(input)) {
1627
+ if (typeof opts.onIgnore === "function") {
1628
+ opts.onIgnore(result);
1629
+ }
1630
+ result.isMatch = false;
1631
+ return returnObject ? result : false;
1632
+ }
1633
+ if (typeof opts.onMatch === "function") {
1634
+ opts.onMatch(result);
1635
+ }
1636
+ return returnObject ? result : true;
1637
+ };
1638
+ if (returnState) {
1639
+ matcher.state = state;
1640
+ }
1641
+ return matcher;
1642
+ };
1643
+ /**
1644
+ * Test `input` with the given `regex`. This is used by the main
1645
+ * `picomatch()` function to test the input string.
1646
+ *
1647
+ * ```js
1648
+ * const picomatch = require('picomatch');
1649
+ * // picomatch.test(input, regex[, options]);
1650
+ *
1651
+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
1652
+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
1653
+ * ```
1654
+ * @param {String} `input` String to test.
1655
+ * @param {RegExp} `regex`
1656
+ * @return {Object} Returns an object with matching info.
1657
+ * @api public
1658
+ */
1659
+ picomatch$2.test = (input, regex, options, { glob, posix } = {}) => {
1660
+ if (typeof input !== "string") {
1661
+ throw new TypeError("Expected input to be a string");
1662
+ }
1663
+ if (input === "") {
1664
+ return {
1665
+ isMatch: false,
1666
+ output: ""
1667
+ };
1668
+ }
1669
+ const opts = options || {};
1670
+ const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
1671
+ let match = input === glob;
1672
+ let output = match && format ? format(input) : input;
1673
+ if (match === false) {
1674
+ output = format ? format(input) : input;
1675
+ match = output === glob;
1676
+ }
1677
+ if (match === false || opts.capture === true) {
1678
+ if (opts.matchBase === true || opts.basename === true) {
1679
+ match = picomatch$2.matchBase(input, regex, options, posix);
1680
+ } else {
1681
+ match = regex.exec(output);
1682
+ }
1683
+ }
1684
+ return {
1685
+ isMatch: Boolean(match),
1686
+ match,
1687
+ output
1688
+ };
1689
+ };
1690
+ /**
1691
+ * Match the basename of a filepath.
1692
+ *
1693
+ * ```js
1694
+ * const picomatch = require('picomatch');
1695
+ * // picomatch.matchBase(input, glob[, options]);
1696
+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
1697
+ * ```
1698
+ * @param {String} `input` String to test.
1699
+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
1700
+ * @return {Boolean}
1701
+ * @api public
1702
+ */
1703
+ picomatch$2.matchBase = (input, glob, options) => {
1704
+ const regex = glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options);
1705
+ return regex.test(utils$1.basename(input));
1706
+ };
1707
+ /**
1708
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
1709
+ *
1710
+ * ```js
1711
+ * const picomatch = require('picomatch');
1712
+ * // picomatch.isMatch(string, patterns[, options]);
1713
+ *
1714
+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
1715
+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
1716
+ * ```
1717
+ * @param {String|Array} str The string to test.
1718
+ * @param {String|Array} patterns One or more glob patterns to use for matching.
1719
+ * @param {Object} [options] See available [options](#options).
1720
+ * @return {Boolean} Returns true if any patterns match `str`
1721
+ * @api public
1722
+ */
1723
+ picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
1724
+ /**
1725
+ * Parse a glob pattern to create the source string for a regular
1726
+ * expression.
1727
+ *
1728
+ * ```js
1729
+ * const picomatch = require('picomatch');
1730
+ * const result = picomatch.parse(pattern[, options]);
1731
+ * ```
1732
+ * @param {String} `pattern`
1733
+ * @param {Object} `options`
1734
+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
1735
+ * @api public
1736
+ */
1737
+ picomatch$2.parse = (pattern, options) => {
1738
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch$2.parse(p, options));
1739
+ return parse$1(pattern, {
1740
+ ...options,
1741
+ fastpaths: false
1742
+ });
1743
+ };
1744
+ /**
1745
+ * Scan a glob pattern to separate the pattern into segments.
1746
+ *
1747
+ * ```js
1748
+ * const picomatch = require('picomatch');
1749
+ * // picomatch.scan(input[, options]);
1750
+ *
1751
+ * const result = picomatch.scan('!./foo/*.js');
1752
+ * console.log(result);
1753
+ * { prefix: '!./',
1754
+ * input: '!./foo/*.js',
1755
+ * start: 3,
1756
+ * base: 'foo',
1757
+ * glob: '*.js',
1758
+ * isBrace: false,
1759
+ * isBracket: false,
1760
+ * isGlob: true,
1761
+ * isExtglob: false,
1762
+ * isGlobstar: false,
1763
+ * negated: true }
1764
+ * ```
1765
+ * @param {String} `input` Glob pattern to scan.
1766
+ * @param {Object} `options`
1767
+ * @return {Object} Returns an object with
1768
+ * @api public
1769
+ */
1770
+ picomatch$2.scan = (input, options) => scan(input, options);
1771
+ /**
1772
+ * Compile a regular expression from the `state` object returned by the
1773
+ * [parse()](#parse) method.
1774
+ *
1775
+ * @param {Object} `state`
1776
+ * @param {Object} `options`
1777
+ * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
1778
+ * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
1779
+ * @return {RegExp}
1780
+ * @api public
1781
+ */
1782
+ picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
1783
+ if (returnOutput === true) {
1784
+ return state.output;
1785
+ }
1786
+ const opts = options || {};
1787
+ const prepend = opts.contains ? "" : "^";
1788
+ const append = opts.contains ? "" : "$";
1789
+ let source = `${prepend}(?:${state.output})${append}`;
1790
+ if (state && state.negated === true) {
1791
+ source = `^(?!${source}).*$`;
1792
+ }
1793
+ const regex = picomatch$2.toRegex(source, options);
1794
+ if (returnState === true) {
1795
+ regex.state = state;
1796
+ }
1797
+ return regex;
1798
+ };
1799
+ /**
1800
+ * Create a regular expression from a parsed glob pattern.
1801
+ *
1802
+ * ```js
1803
+ * const picomatch = require('picomatch');
1804
+ * const state = picomatch.parse('*.js');
1805
+ * // picomatch.compileRe(state[, options]);
1806
+ *
1807
+ * console.log(picomatch.compileRe(state));
1808
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
1809
+ * ```
1810
+ * @param {String} `state` The object returned from the `.parse` method.
1811
+ * @param {Object} `options`
1812
+ * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
1813
+ * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
1814
+ * @return {RegExp} Returns a regex created from the given pattern.
1815
+ * @api public
1816
+ */
1817
+ picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
1818
+ if (!input || typeof input !== "string") {
1819
+ throw new TypeError("Expected a non-empty string");
1820
+ }
1821
+ let parsed = {
1822
+ negated: false,
1823
+ fastpaths: true
1824
+ };
1825
+ if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
1826
+ parsed.output = parse$1.fastpaths(input, options);
1827
+ }
1828
+ if (!parsed.output) {
1829
+ parsed = parse$1(input, options);
1830
+ }
1831
+ return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
1832
+ };
1833
+ /**
1834
+ * Create a regular expression from the given regex source string.
1835
+ *
1836
+ * ```js
1837
+ * const picomatch = require('picomatch');
1838
+ * // picomatch.toRegex(source[, options]);
1839
+ *
1840
+ * const { output } = picomatch.parse('*.js');
1841
+ * console.log(picomatch.toRegex(output));
1842
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
1843
+ * ```
1844
+ * @param {String} `source` Regular expression source string.
1845
+ * @param {Object} `options`
1846
+ * @return {RegExp}
1847
+ * @api public
1848
+ */
1849
+ picomatch$2.toRegex = (source, options) => {
1850
+ try {
1851
+ const opts = options || {};
1852
+ return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
1853
+ } catch (err$1) {
1854
+ if (options && options.debug === true) throw err$1;
1855
+ return /$^/;
1856
+ }
1857
+ };
1858
+ /**
1859
+ * Picomatch constants.
1860
+ * @return {Object}
1861
+ */
1862
+ picomatch$2.constants = constants;
1863
+ /**
1864
+ * Expose "picomatch"
1865
+ */
1866
+ module.exports = picomatch$2;
1867
+ }));
1868
+
1869
+ //#endregion
1870
+ //#region node_modules/picomatch/index.js
1871
+ var require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1872
+ const pico = require_picomatch$1();
1873
+ const utils = require_utils();
1874
+ function picomatch$1(glob, options, returnState = false) {
1875
+ if (options && (options.windows === null || options.windows === undefined)) {
1876
+ options = {
1877
+ ...options,
1878
+ windows: utils.isWindows()
1879
+ };
1880
+ }
1881
+ return pico(glob, options, returnState);
1882
+ }
1883
+ Object.assign(picomatch$1, pico);
1884
+ module.exports = picomatch$1;
1885
+ }));
1886
+
1887
+ //#endregion
1888
+ //#region packages/tools/src/codegen/type-filter.ts
1889
+ var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
1890
+ const compileRule = (rule) => {
1891
+ const matcher = (0, import_picomatch.default)(rule.pattern);
1892
+ const categories = rule.category ? Array.isArray(rule.category) ? rule.category : [rule.category] : null;
1893
+ return (context) => {
1894
+ if (categories && !categories.includes(context.category)) {
1895
+ return true;
1896
+ }
1897
+ return !matcher(context.name);
1898
+ };
1899
+ };
1900
+ const compileTypeFilter = (config) => {
1901
+ if (!config) {
1902
+ return () => true;
1903
+ }
1904
+ if (typeof config === "function") {
1905
+ return config;
1906
+ }
1907
+ const rules = config.exclude.map(compileRule);
1908
+ return (context) => rules.every((rule) => rule(context));
1909
+ };
1910
+ const buildExclusionSet = (filter, typeNames) => {
1911
+ const excluded = new Set();
1912
+ for (const [category, names] of typeNames) {
1913
+ for (const name of names) {
1914
+ if (!filter({
1915
+ name,
1916
+ category
1917
+ })) {
1918
+ excluded.add(name);
1919
+ }
1920
+ }
1921
+ }
1922
+ return excluded;
1923
+ };
1924
+
1925
+ //#endregion
1926
+ //#region packages/tools/src/codegen/generator.ts
1927
+ const builtinScalarTypes$1 = new Map([
1928
+ ["ID", {
1929
+ input: "string",
1930
+ output: "string"
1931
+ }],
1932
+ ["String", {
1933
+ input: "string",
1934
+ output: "string"
1935
+ }],
1936
+ ["Int", {
1937
+ input: "number",
1938
+ output: "number"
1939
+ }],
1940
+ ["Float", {
1941
+ input: "number",
1942
+ output: "number"
1943
+ }],
1944
+ ["Boolean", {
1945
+ input: "boolean",
1946
+ output: "boolean"
1947
+ }]
1948
+ ]);
1949
+ const collectTypeLevels = (type, nonNull = false, levels = []) => {
1950
+ if (type.kind === Kind.NON_NULL_TYPE) {
1951
+ return collectTypeLevels(type.type, true, levels);
1952
+ }
1953
+ if (type.kind === Kind.LIST_TYPE) {
1954
+ levels.push({
1955
+ kind: "list",
1956
+ nonNull
1957
+ });
1958
+ return collectTypeLevels(type.type, false, levels);
1959
+ }
1960
+ levels.push({
1961
+ kind: "named",
1962
+ nonNull
1963
+ });
1964
+ return {
1965
+ name: type.name.value,
1966
+ levels
1967
+ };
1968
+ };
1969
+ const buildTypeModifier = (levels) => {
1970
+ let modifier = "?";
1971
+ for (const level of levels.slice().reverse()) {
1972
+ if (level.kind === "named") {
1973
+ modifier = level.nonNull ? "!" : "?";
1974
+ continue;
1975
+ }
1976
+ const listSuffix = level.nonNull ? "[]!" : "[]?";
1977
+ modifier = `${modifier}${listSuffix}`;
1978
+ }
1979
+ return modifier;
1980
+ };
1981
+ const parseTypeReference = (type) => {
1982
+ const { name, levels } = collectTypeLevels(type);
1983
+ return {
1984
+ name,
1985
+ modifier: buildTypeModifier(levels)
1986
+ };
1987
+ };
1988
+ const isScalarName$1 = (schema, name) => builtinScalarTypes$1.has(name) || schema.scalars.has(name);
1989
+ const isEnumName$1 = (schema, name) => schema.enums.has(name);
1990
+ const _isInputName = (schema, name) => schema.inputs.has(name);
1991
+ const isUnionName = (schema, name) => schema.unions.has(name);
1992
+ const isObjectName = (schema, name) => schema.objects.has(name);
1993
+ /**
1994
+ * Maps type kind to deferred specifier prefix character.
1995
+ */
1996
+ const inputKindToChar = (kind) => {
1997
+ switch (kind) {
1998
+ case "scalar": return "s";
1999
+ case "enum": return "e";
2000
+ case "input": return "i";
2001
+ case "excluded": return "x";
2002
+ }
2003
+ };
2004
+ const renderInputRef = (schema, definition, excluded) => {
2005
+ const { name, modifier } = parseTypeReference(definition.type);
2006
+ const defaultValue = definition.defaultValue;
2007
+ if (excluded.has(name)) {
2008
+ const defaultSuffix$1 = defaultValue ? "|D" : "";
2009
+ return `"x|${name}|${modifier}${defaultSuffix$1}"`;
2010
+ }
2011
+ let kind;
2012
+ if (isScalarName$1(schema, name)) {
2013
+ kind = "scalar";
2014
+ } else if (isEnumName$1(schema, name)) {
2015
+ kind = "enum";
2016
+ } else {
2017
+ kind = "input";
2018
+ }
2019
+ const kindChar = inputKindToChar(kind);
2020
+ const defaultSuffix = defaultValue ? "|D" : "";
2021
+ return `"${kindChar}|${name}|${modifier}${defaultSuffix}"`;
2022
+ };
2023
+ /**
2024
+ * Maps output type kind to deferred specifier prefix character.
2025
+ */
2026
+ const outputKindToChar = (kind) => {
2027
+ switch (kind) {
2028
+ case "scalar": return "s";
2029
+ case "enum": return "e";
2030
+ case "object": return "o";
2031
+ case "union": return "u";
2032
+ case "excluded": return "x";
2033
+ }
2034
+ };
2035
+ /**
2036
+ * Render arguments as object format for DeferredOutputFieldWithArgs.
2037
+ * Returns array of "argName: \"spec\"" entries.
2038
+ */
2039
+ const renderArgumentsObjectEntries = (schema, args, excluded) => {
2040
+ return [...args].sort((left, right) => left.name.value.localeCompare(right.name.value)).map((arg) => {
2041
+ const { name, modifier } = parseTypeReference(arg.type);
2042
+ if (excluded.has(name)) {
2043
+ return null;
2044
+ }
2045
+ let kind;
2046
+ if (isScalarName$1(schema, name)) {
2047
+ kind = "scalar";
2048
+ } else if (isEnumName$1(schema, name)) {
2049
+ kind = "enum";
2050
+ } else {
2051
+ kind = "input";
2052
+ }
2053
+ const kindChar = inputKindToChar(kind);
2054
+ const defaultSuffix = arg.defaultValue ? "|D" : "";
2055
+ return `${arg.name.value}: "${kindChar}|${name}|${modifier}${defaultSuffix}"`;
2056
+ }).filter((spec) => spec !== null);
2057
+ };
2058
+ const renderArgumentMap = (schema, args, excluded) => {
2059
+ const entries = [...args ?? []].sort((left, right) => left.name.value.localeCompare(right.name.value)).map((arg) => `${arg.name.value}: ${renderInputRef(schema, arg, excluded)}`);
2060
+ return renderPropertyLines({
2061
+ entries,
2062
+ indentSize: 8
2063
+ });
2064
+ };
2065
+ const renderOutputRef = (schema, type, args, excluded) => {
2066
+ const { name, modifier } = parseTypeReference(type);
2067
+ if (excluded.has(name)) {
2068
+ const argumentMap = renderArgumentMap(schema, args, excluded);
2069
+ return `{ spec: "x|${name}|${modifier}", arguments: ${argumentMap} }`;
2070
+ }
2071
+ let kind;
2072
+ if (isScalarName$1(schema, name)) {
2073
+ kind = "scalar";
2074
+ } else if (isEnumName$1(schema, name)) {
2075
+ kind = "enum";
2076
+ } else if (isUnionName(schema, name)) {
2077
+ kind = "union";
2078
+ } else if (isObjectName(schema, name)) {
2079
+ kind = "object";
2080
+ } else {
2081
+ kind = "scalar";
2082
+ }
2083
+ const kindChar = outputKindToChar(kind);
2084
+ const spec = `${kindChar}|${name}|${modifier}`;
2085
+ if (args && args.length > 0) {
2086
+ const argEntries = renderArgumentsObjectEntries(schema, args, excluded);
2087
+ if (argEntries.length > 0) {
2088
+ return `{ spec: "${spec}", arguments: { ${argEntries.join(", ")} } }`;
2089
+ }
2090
+ }
2091
+ return `{ spec: "${spec}", arguments: {} }`;
2092
+ };
2093
+ const renderPropertyLines = ({ entries, indentSize }) => {
2094
+ if (entries.length === 0) {
2095
+ return "{}";
2096
+ }
2097
+ const indent = " ".repeat(indentSize);
2098
+ const lastIndent = " ".repeat(indentSize - 2);
2099
+ return [
2100
+ "{",
2101
+ `${indent}${entries.join(`,\n${indent}`)},`,
2102
+ `${lastIndent}}`
2103
+ ].join(`\n`);
2104
+ };
2105
+ const renderObjectFields = (schema, fields, excluded) => {
2106
+ const entries = Array.from(fields.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((field) => `${field.name.value}: ${renderOutputRef(schema, field.type, field.arguments, excluded)}`);
2107
+ return renderPropertyLines({
2108
+ entries,
2109
+ indentSize: 6
2110
+ });
2111
+ };
2112
+ const renderInputFields = (schema, fields, excluded) => {
2113
+ const entries = Array.from(fields.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((field) => `${field.name.value}: ${renderInputRef(schema, field, excluded)}`);
2114
+ return renderPropertyLines({
2115
+ entries,
2116
+ indentSize: 6
2117
+ });
2118
+ };
2119
+ const renderScalarVar = (schemaName, record) => {
2120
+ const typeInfo = builtinScalarTypes$1.get(record.name) ?? {
2121
+ input: "string",
2122
+ output: "string"
2123
+ };
2124
+ return `const scalar_${schemaName}_${record.name} = { name: "${record.name}", $type: {} as { input: ${typeInfo.input}; output: ${typeInfo.output}; inputProfile: { kind: "scalar"; name: "${record.name}"; value: ${typeInfo.input} }; outputProfile: { kind: "scalar"; name: "${record.name}"; value: ${typeInfo.output} } } } as const;`;
2125
+ };
2126
+ const renderEnumVar = (schemaName, record) => {
2127
+ const valueNames = Array.from(record.values.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((value) => value.name.value);
2128
+ const valuesObj = valueNames.length === 0 ? "{}" : `{ ${valueNames.map((v) => `${v}: true`).join(", ")} }`;
2129
+ const valueUnion = valueNames.length === 0 ? "never" : valueNames.map((v) => `"${v}"`).join(" | ");
2130
+ return `const enum_${schemaName}_${record.name} = defineEnum<"${record.name}", ${valueUnion}>("${record.name}", ${valuesObj});`;
2131
+ };
2132
+ const renderInputVar = (schemaName, schema, record, excluded) => {
2133
+ const fields = renderInputFields(schema, record.fields, excluded);
2134
+ return `const input_${schemaName}_${record.name} = { name: "${record.name}", fields: ${fields} } as const;`;
2135
+ };
2136
+ const renderObjectVar = (schemaName, schema, record, excluded) => {
2137
+ const fields = renderObjectFields(schema, record.fields, excluded);
2138
+ return `const object_${schemaName}_${record.name} = { name: "${record.name}", fields: ${fields} } as const;`;
2139
+ };
2140
+ const renderUnionVar = (schemaName, record, excluded) => {
2141
+ const memberNames = Array.from(record.members.values()).filter((member) => !excluded.has(member.name.value)).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((member) => member.name.value);
2142
+ const typesObj = memberNames.length === 0 ? "{}" : `{ ${memberNames.map((m) => `${m}: true`).join(", ")} }`;
2143
+ return `const union_${schemaName}_${record.name} = { name: "${record.name}", types: ${typesObj} } as const;`;
2144
+ };
2145
+ const collectObjectTypeNames = (schema) => Array.from(schema.objects.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
2146
+ const collectInputTypeNames = (schema) => Array.from(schema.inputs.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
2147
+ const collectEnumTypeNames = (schema) => Array.from(schema.enums.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
2148
+ const collectUnionTypeNames = (schema) => Array.from(schema.unions.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
2149
+ const collectScalarNames = (schema) => Array.from(schema.scalars.keys()).filter((name) => !name.startsWith("__")).sort((left, right) => left.localeCompare(right));
2150
+ const collectDirectiveNames = (schema) => Array.from(schema.directives.keys()).sort((left, right) => left.localeCompare(right));
2151
+ const renderInputTypeMethod = (factoryVar, kind, typeName) => `${typeName}: ${factoryVar}("${kind}", "${typeName}")`;
2152
+ const renderInputTypeMethods = (schema, factoryVar, excluded) => {
2153
+ const scalarMethods = Array.from(builtinScalarTypes$1.keys()).concat(collectScalarNames(schema).filter((name) => !builtinScalarTypes$1.has(name))).filter((name) => !excluded.has(name)).map((name) => renderInputTypeMethod(factoryVar, "scalar", name));
2154
+ const enumMethods = collectEnumTypeNames(schema).filter((name) => !excluded.has(name)).map((name) => renderInputTypeMethod(factoryVar, "enum", name));
2155
+ const inputMethods = collectInputTypeNames(schema).filter((name) => !excluded.has(name)).map((name) => renderInputTypeMethod(factoryVar, "input", name));
2156
+ const allMethods = [
2157
+ ...scalarMethods,
2158
+ ...enumMethods,
2159
+ ...inputMethods
2160
+ ].sort((left, right) => {
2161
+ const leftName = left.split(":")[0] ?? "";
2162
+ const rightName = right.split(":")[0] ?? "";
2163
+ return leftName.localeCompare(rightName);
2164
+ });
2165
+ return renderPropertyLines({
2166
+ entries: allMethods,
2167
+ indentSize: 2
2168
+ });
2169
+ };
2170
+ /**
2171
+ * Renders an input reference as a deferred string for directive arguments.
2172
+ * Format: "{kindChar}|{name}|{modifier}"
2173
+ */
2174
+ const renderDeferredDirectiveArgRef = (schema, definition, excluded) => {
2175
+ const { name, modifier } = parseTypeReference(definition.type);
2176
+ if (excluded.has(name)) {
2177
+ return null;
2178
+ }
2179
+ let kind;
2180
+ if (isScalarName$1(schema, name)) {
2181
+ kind = "scalar";
2182
+ } else if (isEnumName$1(schema, name)) {
2183
+ kind = "enum";
2184
+ } else {
2185
+ kind = "input";
2186
+ }
2187
+ const kindChar = inputKindToChar(kind);
2188
+ return `"${kindChar}|${name}|${modifier}"`;
2189
+ };
2190
+ /**
2191
+ * Renders argument specifiers for a directive.
2192
+ * Returns null if the directive has no arguments.
2193
+ * Uses deferred string format for consistency with other type specifiers.
2194
+ */
2195
+ const renderDirectiveArgsSpec = (schema, args, excluded) => {
2196
+ if (args.size === 0) return null;
2197
+ const entries = Array.from(args.values()).sort((left, right) => left.name.value.localeCompare(right.name.value)).map((arg) => {
2198
+ const ref = renderDeferredDirectiveArgRef(schema, arg, excluded);
2199
+ return ref ? `${arg.name.value}: ${ref}` : null;
2200
+ }).filter((entry) => entry !== null);
2201
+ if (entries.length === 0) return null;
2202
+ return renderPropertyLines({
2203
+ entries,
2204
+ indentSize: 4
2205
+ });
2206
+ };
2207
+ const renderDirectiveMethod = (schema, record, excluded) => {
2208
+ const locationsJson = JSON.stringify(record.locations);
2209
+ const argsSpec = renderDirectiveArgsSpec(schema, record.args, excluded);
2210
+ if (argsSpec === null) {
2211
+ return `${record.name}: createDirectiveMethod("${record.name}", ${locationsJson} as const)`;
2212
+ }
2213
+ return `${record.name}: createTypedDirectiveMethod("${record.name}", ${locationsJson} as const, ${argsSpec})`;
2214
+ };
2215
+ const renderDirectiveMethods = (schema, excluded) => {
2216
+ const directiveNames = collectDirectiveNames(schema);
2217
+ if (directiveNames.length === 0) {
2218
+ return "{}";
2219
+ }
2220
+ const methods = directiveNames.map((name) => {
2221
+ const record = schema.directives.get(name);
2222
+ return record ? renderDirectiveMethod(schema, record, excluded) : null;
2223
+ }).filter((method) => method !== null);
2224
+ return renderPropertyLines({
2225
+ entries: methods,
2226
+ indentSize: 2
2227
+ });
2228
+ };
2229
+ /**
2230
+ * Generates the _internal-injects.ts module code.
2231
+ * This file contains only adapter imports (scalar, adapter) to keep it lightweight.
2232
+ * The heavy schema types remain in _internal.ts.
2233
+ */
2234
+ const generateInjectsCode = (injection) => {
2235
+ const imports = [];
2236
+ const exports$1 = [];
2237
+ const typeExports = [];
2238
+ const importsByPath = new Map();
2239
+ for (const [schemaName, config] of injection) {
2240
+ const scalarAlias = `scalar_${schemaName}`;
2241
+ const scalarSpecifiers = importsByPath.get(config.scalarImportPath) ?? [];
2242
+ if (!importsByPath.has(config.scalarImportPath)) {
2243
+ importsByPath.set(config.scalarImportPath, scalarSpecifiers);
2244
+ }
2245
+ scalarSpecifiers.push(`scalar as ${scalarAlias}`);
2246
+ exports$1.push(`export { ${scalarAlias} };`);
2247
+ typeExports.push(`export type Scalar_${schemaName} = typeof ${scalarAlias};`);
2248
+ if (config.adapterImportPath) {
2249
+ const adapterAlias = `adapter_${schemaName}`;
2250
+ const adapterSpecifiers = importsByPath.get(config.adapterImportPath) ?? [];
2251
+ if (!importsByPath.has(config.adapterImportPath)) {
2252
+ importsByPath.set(config.adapterImportPath, adapterSpecifiers);
2253
+ }
2254
+ adapterSpecifiers.push(`adapter as ${adapterAlias}`);
2255
+ exports$1.push(`export { ${adapterAlias} };`);
2256
+ typeExports.push(`export type Adapter_${schemaName} = typeof ${adapterAlias} & { _?: never };`);
2257
+ }
2258
+ }
2259
+ for (const [path, specifiers] of importsByPath) {
2260
+ if (specifiers.length === 1) {
2261
+ imports.push(`import { ${specifiers[0]} } from "${path}";`);
2262
+ } else {
2263
+ imports.push(`import {\n ${specifiers.join(",\n ")},\n} from "${path}";`);
2264
+ }
2265
+ }
2266
+ return `\
2267
+ /**
2268
+ * Adapter injections for schema.
2269
+ * Separated to allow lightweight imports for prebuilt module.
2270
+ * @generated by @soda-gql/tools/codegen
2271
+ */
2272
+
2273
+ ${imports.join("\n")}
2274
+
2275
+ // Value exports
2276
+ ${exports$1.join("\n")}
2277
+
2278
+ // Type exports
2279
+ ${typeExports.join("\n")}
2280
+ `;
2281
+ };
2282
+ const multiRuntimeTemplate = ($$) => {
2283
+ const imports = [];
2284
+ const scalarAliases = new Map();
2285
+ const adapterAliases = new Map();
2286
+ if ($$.injection.mode === "inject") {
2287
+ const injectsImports = [];
2288
+ for (const [schemaName, injection] of $$.injection.perSchema) {
2289
+ const scalarAlias = `scalar_${schemaName}`;
2290
+ scalarAliases.set(schemaName, scalarAlias);
2291
+ injectsImports.push(scalarAlias);
2292
+ if (injection.adapterImportPath) {
2293
+ const adapterAlias = `adapter_${schemaName}`;
2294
+ adapterAliases.set(schemaName, adapterAlias);
2295
+ injectsImports.push(adapterAlias);
2296
+ }
2297
+ }
2298
+ imports.push(`import { ${injectsImports.join(", ")} } from "${$$.injection.injectsModulePath}";`);
2299
+ }
2300
+ {
2301
+ const { importPaths } = $$.splitting;
2302
+ for (const [name, config] of Object.entries($$.schemas)) {
2303
+ if (config.enumNames.length > 0) {
2304
+ const enumImports = config.enumNames.map((n) => `enum_${name}_${n}`).join(", ");
2305
+ imports.push(`import { ${enumImports} } from "${importPaths.enums}";`);
2306
+ }
2307
+ if (config.inputNames.length > 0) {
2308
+ const inputImports = config.inputNames.map((n) => `input_${name}_${n}`).join(", ");
2309
+ imports.push(`import { ${inputImports} } from "${importPaths.inputs}";`);
2310
+ }
2311
+ if (config.objectNames.length > 0) {
2312
+ const objectImports = config.objectNames.map((n) => `object_${name}_${n}`).join(", ");
2313
+ imports.push(`import { ${objectImports} } from "${importPaths.objects}";`);
2314
+ }
2315
+ if (config.unionNames.length > 0) {
2316
+ const unionImports = config.unionNames.map((n) => `union_${name}_${n}`).join(", ");
2317
+ imports.push(`import { ${unionImports} } from "${importPaths.unions}";`);
2318
+ }
2319
+ }
2320
+ }
2321
+ const extraImports = imports.length > 0 ? `${imports.join("\n")}\n` : "";
2322
+ const schemaBlocks = [];
2323
+ const gqlExports = [];
2324
+ for (const [name, config] of Object.entries($$.schemas)) {
2325
+ const schemaVar = `${name}Schema`;
2326
+ const adapterVar = adapterAliases.get(name);
2327
+ const typeExports = [`export type Schema_${name} = typeof ${schemaVar} & { _?: never };`];
2328
+ if (adapterVar) {
2329
+ typeExports.push(`export type Adapter_${name} = typeof ${adapterVar} & { _?: never };`);
2330
+ }
2331
+ const inputTypeMethodsVar = `inputTypeMethods_${name}`;
2332
+ const factoryVar = `createMethod_${name}`;
2333
+ const customDirectivesVar = `customDirectives_${name}`;
2334
+ const defaultDepthBlock = config.defaultInputDepth !== undefined && config.defaultInputDepth !== 3 ? `\n __defaultInputDepth: ${config.defaultInputDepth},` : "";
2335
+ const depthOverridesBlock = config.inputDepthOverrides && Object.keys(config.inputDepthOverrides).length > 0 ? `\n __inputDepthOverrides: ${JSON.stringify(config.inputDepthOverrides)},` : "";
2336
+ const isSplitMode = true;
2337
+ const scalarVarsBlock = config.scalarVars.join("\n");
2338
+ const enumVarsBlock = isSplitMode ? "// (enums imported)" : config.enumVars.length > 0 ? config.enumVars.join("\n") : "// (no enums)";
2339
+ const inputVarsBlock = isSplitMode ? "// (inputs imported)" : config.inputVars.length > 0 ? config.inputVars.join("\n") : "// (no inputs)";
2340
+ const objectVarsBlock = isSplitMode ? "// (objects imported)" : config.objectVars.length > 0 ? config.objectVars.join("\n") : "// (no objects)";
2341
+ const unionVarsBlock = isSplitMode ? "// (unions imported)" : config.unionVars.length > 0 ? config.unionVars.join("\n") : "// (no unions)";
2342
+ const scalarAssembly = $$.injection.mode === "inject" ? scalarAliases.get(name) ?? "{}" : config.scalarNames.length > 0 ? `{ ${config.scalarNames.map((n) => `${n}: scalar_${name}_${n}`).join(", ")} }` : "{}";
2343
+ const enumAssembly = config.enumNames.length > 0 ? `{ ${config.enumNames.map((n) => `${n}: enum_${name}_${n}`).join(", ")} }` : "{}";
2344
+ const inputAssembly = config.inputNames.length > 0 ? `{ ${config.inputNames.map((n) => `${n}: input_${name}_${n}`).join(", ")} }` : "{}";
2345
+ const objectAssembly = config.objectNames.length > 0 ? `{ ${config.objectNames.map((n) => `${n}: object_${name}_${n}`).join(", ")} }` : "{}";
2346
+ const unionAssembly = config.unionNames.length > 0 ? `{ ${config.unionNames.map((n) => `${n}: union_${name}_${n}`).join(", ")} }` : "{}";
2347
+ const scalarVarsSection = $$.injection.mode === "inject" ? "// (scalars imported)" : scalarVarsBlock;
2348
+ const scalarAssemblyLine = $$.injection.mode === "inject" ? `// scalar_${name} is imported directly` : `const scalar_${name} = ${scalarAssembly} as const;`;
2349
+ const scalarRef = $$.injection.mode === "inject" ? scalarAliases.get(name) ?? `scalar_${name}` : `scalar_${name}`;
2350
+ schemaBlocks.push(`
2351
+ // Individual scalar definitions
2352
+ ${scalarVarsSection}
2353
+
2354
+ // Individual enum definitions
2355
+ ${enumVarsBlock}
2356
+
2357
+ // Individual input definitions
2358
+ ${inputVarsBlock}
2359
+
2360
+ // Individual object definitions
2361
+ ${objectVarsBlock}
2362
+
2363
+ // Individual union definitions
2364
+ ${unionVarsBlock}
2365
+
2366
+ // Category assembly
2367
+ ${scalarAssemblyLine}
2368
+ const enum_${name} = ${enumAssembly} as const;
2369
+ const input_${name} = ${inputAssembly} as const;
2370
+ const object_${name} = ${objectAssembly} as const;
2371
+ const union_${name} = ${unionAssembly} as const;
2372
+
2373
+ // Schema assembly
2374
+ const ${schemaVar} = {
2375
+ label: "${name}" as const,
2376
+ operations: { query: "${config.queryType}", mutation: "${config.mutationType}", subscription: "${config.subscriptionType}" } as const,
2377
+ scalar: ${scalarRef},
2378
+ enum: enum_${name},
2379
+ input: input_${name},
2380
+ object: object_${name},
2381
+ union: union_${name},${defaultDepthBlock}${depthOverridesBlock}
2382
+ } as const satisfies AnyGraphqlSchema;
2383
+
2384
+ const ${factoryVar} = createVarMethodFactory<typeof ${schemaVar}>();
2385
+ const ${inputTypeMethodsVar} = ${config.inputTypeMethodsBlock};
2386
+ const ${customDirectivesVar} = { ...createStandardDirectives(), ...${config.directiveMethodsBlock} };
2387
+
2388
+ ${typeExports.join("\n")}`);
2389
+ const gqlVarName = `gql_${name}`;
2390
+ if (adapterVar) {
2391
+ const typeParams = `<Schema_${name}, typeof ${customDirectivesVar}, Adapter_${name}>`;
2392
+ schemaBlocks.push(`const ${gqlVarName} = createGqlElementComposer${typeParams}(${schemaVar}, { adapter: ${adapterVar}, inputTypeMethods: ${inputTypeMethodsVar}, directiveMethods: ${customDirectivesVar} });`);
2393
+ } else {
2394
+ const typeParams = `<Schema_${name}, typeof ${customDirectivesVar}>`;
2395
+ schemaBlocks.push(`const ${gqlVarName} = createGqlElementComposer${typeParams}(${schemaVar}, { inputTypeMethods: ${inputTypeMethodsVar}, directiveMethods: ${customDirectivesVar} });`);
2396
+ }
2397
+ schemaBlocks.push(`export type Context_${name} = Parameters<typeof ${gqlVarName}>[0] extends (ctx: infer C) => unknown ? C : never;`);
2398
+ const prebuiltExports = [
2399
+ `export { ${schemaVar} as __schema_${name} }`,
2400
+ `export { ${inputTypeMethodsVar} as __inputTypeMethods_${name} }`,
2401
+ `export { ${customDirectivesVar} as __directiveMethods_${name} }`
2402
+ ];
2403
+ if (adapterVar) {
2404
+ prebuiltExports.push(`export { ${adapterVar} as __adapter_${name} }`);
2405
+ }
2406
+ schemaBlocks.push(`${prebuiltExports.join(";\n")};`);
2407
+ gqlExports.push(`export { ${gqlVarName} as __gql_${name} }`);
2408
+ }
2409
+ const needsDefineEnum = false;
2410
+ return `\
2411
+ import {${needsDefineEnum ? "\n defineEnum," : ""}
2412
+ type AnyGraphqlSchema,
2413
+ createDirectiveMethod,
2414
+ createTypedDirectiveMethod,
2415
+ createGqlElementComposer,
2416
+ createStandardDirectives,
2417
+ createVarMethodFactory,
2418
+ } from "@soda-gql/core";
2419
+ ${extraImports}
2420
+ ${schemaBlocks.join("\n")}
2421
+
2422
+ ${gqlExports.join(";\n")};
2423
+ `;
2424
+ };
2425
+ const generateMultiSchemaModule = (schemas, options) => {
2426
+ const schemaConfigs = {};
2427
+ const allStats = {
2428
+ objects: 0,
2429
+ enums: 0,
2430
+ inputs: 0,
2431
+ unions: 0
2432
+ };
2433
+ for (const [name, document] of schemas.entries()) {
2434
+ const schema = createSchemaIndex(document);
2435
+ const typeFilterConfig = options?.typeFilters?.get(name);
2436
+ const typeFilter = compileTypeFilter(typeFilterConfig);
2437
+ const allTypeNames = new Map([
2438
+ ["object", Array.from(schema.objects.keys()).filter((n) => !n.startsWith("__"))],
2439
+ ["input", Array.from(schema.inputs.keys()).filter((n) => !n.startsWith("__"))],
2440
+ ["enum", Array.from(schema.enums.keys()).filter((n) => !n.startsWith("__"))],
2441
+ ["union", Array.from(schema.unions.keys()).filter((n) => !n.startsWith("__"))],
2442
+ ["scalar", Array.from(schema.scalars.keys()).filter((n) => !n.startsWith("__"))]
2443
+ ]);
2444
+ const excluded = buildExclusionSet(typeFilter, allTypeNames);
2445
+ const objectTypeNames = collectObjectTypeNames(schema).filter((n) => !excluded.has(n));
2446
+ const enumTypeNames = collectEnumTypeNames(schema).filter((n) => !excluded.has(n));
2447
+ const inputTypeNames = collectInputTypeNames(schema).filter((n) => !excluded.has(n));
2448
+ const unionTypeNames = collectUnionTypeNames(schema).filter((n) => !excluded.has(n));
2449
+ const customScalarNames = collectScalarNames(schema).filter((n) => !builtinScalarTypes$1.has(n) && !excluded.has(n));
2450
+ const scalarVars = [];
2451
+ const enumVars = [];
2452
+ const inputVars = [];
2453
+ const objectVars = [];
2454
+ const unionVars = [];
2455
+ for (const scalarName of builtinScalarTypes$1.keys()) {
2456
+ const record = schema.scalars.get(scalarName) ?? {
2457
+ name: scalarName,
2458
+ directives: []
2459
+ };
2460
+ scalarVars.push(renderScalarVar(name, record));
2461
+ }
2462
+ for (const scalarName of customScalarNames) {
2463
+ const record = schema.scalars.get(scalarName);
2464
+ if (record) {
2465
+ scalarVars.push(renderScalarVar(name, record));
2466
+ }
2467
+ }
2468
+ for (const enumName of enumTypeNames) {
2469
+ const record = schema.enums.get(enumName);
2470
+ if (record) {
2471
+ enumVars.push(renderEnumVar(name, record));
2472
+ }
2473
+ }
2474
+ for (const inputName of inputTypeNames) {
2475
+ const record = schema.inputs.get(inputName);
2476
+ if (record) {
2477
+ inputVars.push(renderInputVar(name, schema, record, excluded));
2478
+ }
2479
+ }
2480
+ for (const objectName of objectTypeNames) {
2481
+ const record = schema.objects.get(objectName);
2482
+ if (record) {
2483
+ objectVars.push(renderObjectVar(name, schema, record, excluded));
2484
+ }
2485
+ }
2486
+ for (const unionName of unionTypeNames) {
2487
+ const record = schema.unions.get(unionName);
2488
+ if (record) {
2489
+ unionVars.push(renderUnionVar(name, record, excluded));
2490
+ }
2491
+ }
2492
+ const allScalarNames = [...builtinScalarTypes$1.keys(), ...customScalarNames];
2493
+ const factoryVar = `createMethod_${name}`;
2494
+ const inputTypeMethodsBlock = renderInputTypeMethods(schema, factoryVar, excluded);
2495
+ const directiveMethodsBlock = renderDirectiveMethods(schema, excluded);
2496
+ const queryType = schema.operationTypes.query ?? "Query";
2497
+ const mutationType = schema.operationTypes.mutation ?? "Mutation";
2498
+ const subscriptionType = schema.operationTypes.subscription ?? "Subscription";
2499
+ schemaConfigs[name] = {
2500
+ queryType,
2501
+ mutationType,
2502
+ subscriptionType,
2503
+ scalarVars,
2504
+ enumVars,
2505
+ inputVars,
2506
+ objectVars,
2507
+ unionVars,
2508
+ scalarNames: allScalarNames,
2509
+ enumNames: enumTypeNames,
2510
+ inputNames: inputTypeNames,
2511
+ objectNames: objectTypeNames,
2512
+ unionNames: unionTypeNames,
2513
+ inputTypeMethodsBlock,
2514
+ directiveMethodsBlock,
2515
+ defaultInputDepth: options?.defaultInputDepth?.get(name),
2516
+ inputDepthOverrides: options?.inputDepthOverrides?.get(name)
2517
+ };
2518
+ allStats.objects += objectVars.length;
2519
+ allStats.enums += enumVars.length;
2520
+ allStats.inputs += inputVars.length;
2521
+ allStats.unions += unionVars.length;
2522
+ }
2523
+ const injection = options?.injection ? {
2524
+ mode: "inject",
2525
+ perSchema: options.injection,
2526
+ injectsModulePath: "./_internal-injects"
2527
+ } : { mode: "inline" };
2528
+ const splitting = { importPaths: {
2529
+ enums: "./_defs/enums",
2530
+ inputs: "./_defs/inputs",
2531
+ objects: "./_defs/objects",
2532
+ unions: "./_defs/unions"
2533
+ } };
2534
+ const code = multiRuntimeTemplate({
2535
+ schemas: schemaConfigs,
2536
+ injection,
2537
+ splitting
2538
+ });
2539
+ const injectsCode = options?.injection ? generateInjectsCode(options.injection) : undefined;
2540
+ const categoryVarsResult = Object.fromEntries(Object.entries(schemaConfigs).map(([schemaName, config]) => {
2541
+ const toDefVar = (code$1, prefix) => {
2542
+ const match = code$1.match(new RegExp(`const (${prefix}_${schemaName}_(\\w+))`));
2543
+ return {
2544
+ name: match?.[1] ?? "",
2545
+ code: code$1
2546
+ };
2547
+ };
2548
+ return [schemaName, {
2549
+ enums: config.enumVars.map((c) => toDefVar(c, "enum")),
2550
+ inputs: config.inputVars.map((c) => toDefVar(c, "input")),
2551
+ objects: config.objectVars.map((c) => toDefVar(c, "object")),
2552
+ unions: config.unionVars.map((c) => toDefVar(c, "union"))
2553
+ }];
2554
+ }));
2555
+ return {
2556
+ code,
2557
+ injectsCode,
2558
+ categoryVars: categoryVarsResult,
2559
+ stats: allStats
2560
+ };
2561
+ };
2562
+ /**
2563
+ * Generate a stub `types.prebuilt.ts` file with empty PrebuiltTypes registries.
2564
+ * This stub is only written when `types.prebuilt.ts` does not already exist.
2565
+ * Typegen will later overwrite it with the real type registry.
2566
+ */
2567
+ const generatePrebuiltStub = (schemaNames) => {
2568
+ const typeDeclarations = schemaNames.map((name) => `export type PrebuiltTypes_${name} = {
2569
+ readonly fragments: {};
2570
+ readonly operations: {};
2571
+ };`).join("\n\n");
2572
+ return `\
2573
+ /**
2574
+ * Prebuilt type registry stub.
2575
+ *
2576
+ * This file was generated by @soda-gql/tools/codegen as an empty stub.
2577
+ * Run 'soda-gql typegen' to populate with real prebuilt types.
2578
+ *
2579
+ * @module
2580
+ * @generated
2581
+ */
2582
+
2583
+ ${typeDeclarations}
2584
+ `;
2585
+ };
2586
+ /**
2587
+ * Generate the `index.ts` module that re-exports from `_internal`
2588
+ * and constructs the `gql` object from individual `__gql_*` exports.
2589
+ *
2590
+ * The `gql` object preserves the original inferred types from schema inference.
2591
+ * PrebuiltContext types will be integrated once the type resolution strategy
2592
+ * is redesigned to match the tagged template runtime API.
2593
+ */
2594
+ const generateIndexModule = (schemaNames, allFieldNames) => {
2595
+ const gqlImports = schemaNames.map((name) => `__gql_${name}`).join(", ");
2596
+ const prebuiltImports = schemaNames.map((name) => `PrebuiltTypes_${name}`).join(", ");
2597
+ const schemaTypeImports = schemaNames.map((name) => `Schema_${name}`).join(", ");
2598
+ const directiveImports = schemaNames.map((name) => `__directiveMethods_${name}`).join(", ");
2599
+ const perSchemaTypes = schemaNames.map((name) => `
2600
+ type ResolveFragmentAtBuilder_${name}<TKey extends string> =
2601
+ TKey extends keyof PrebuiltTypes_${name}["fragments"]
2602
+ ? Fragment<
2603
+ PrebuiltTypes_${name}["fragments"][TKey]["typename"],
2604
+ PrebuiltTypes_${name}["fragments"][TKey]["input"] extends void
2605
+ ? void
2606
+ : Partial<PrebuiltTypes_${name}["fragments"][TKey]["input"] & AnyConstAssignableInput>,
2607
+ Partial<AnyFields>,
2608
+ PrebuiltTypes_${name}["fragments"][TKey]["output"] & object
2609
+ >
2610
+ : Fragment<"(unknown)", PrebuiltEntryNotFound<TKey, "fragment">, Partial<AnyFields>, PrebuiltEntryNotFound<TKey, "fragment">>;
2611
+
2612
+ type ResolveOperationAtBuilder_${name}<TOperationType extends OperationType, TName extends string> =
2613
+ TName extends keyof PrebuiltTypes_${name}["operations"]
2614
+ ? Operation<
2615
+ TOperationType,
2616
+ TName,
2617
+ string[],
2618
+ PrebuiltTypes_${name}["operations"][TName]["input"],
2619
+ Partial<AnyFields>,
2620
+ PrebuiltTypes_${name}["operations"][TName]["output"] & object
2621
+ >
2622
+ : Operation<
2623
+ TOperationType,
2624
+ TName,
2625
+ string[],
2626
+ PrebuiltEntryNotFound<TName, "operation">,
2627
+ Partial<AnyFields>,
2628
+ PrebuiltEntryNotFound<TName, "operation">
2629
+ >;
2630
+
2631
+ type PrebuiltCurriedFragment_${name} = <TKey extends string>(
2632
+ name: TKey,
2633
+ typeName: string,
2634
+ ) => (...args: unknown[]) => (...args: unknown[]) => ResolveFragmentAtBuilder_${name}<TKey>;
2635
+
2636
+ type PrebuiltCurriedOperation_${name}<TOperationType extends OperationType> = <TName extends string>(
2637
+ operationName: TName,
2638
+ ) => (...args: unknown[]) => (...args: unknown[]) => ResolveOperationAtBuilder_${name}<TOperationType, TName>;
2639
+
2640
+ type FieldFactoryFn_${name} = (...args: unknown[]) => Record<string, unknown> & ((callback: (tools: GenericFieldsBuilderTools_${name}) => Record<string, unknown>) => Record<string, unknown>);
2641
+ ${(() => {
2642
+ const fieldNames = allFieldNames?.get(name);
2643
+ if (fieldNames && fieldNames.length > 0) {
2644
+ const union = fieldNames.map((n) => JSON.stringify(n)).join(" | ");
2645
+ return `type AllObjectFieldNames_${name} = ${union};
2646
+ type GenericFieldFactory_${name} = { readonly [K in AllObjectFieldNames_${name}]: FieldFactoryFn_${name} } & Record<string, FieldFactoryFn_${name}>;`;
2647
+ }
2648
+ return `type GenericFieldFactory_${name} = Record<string, FieldFactoryFn_${name}>;`;
2649
+ })()}
2650
+ type GenericFieldsBuilderTools_${name} = { readonly f: GenericFieldFactory_${name}; readonly $: Readonly<Record<string, never>> };
2651
+
2652
+ type PrebuiltCallbackOperation_${name}<TOperationType extends OperationType> = <TName extends string>(
2653
+ options: { name: TName; fields: (tools: GenericFieldsBuilderTools_${name}) => Record<string, unknown>; variables?: Record<string, unknown>; metadata?: (tools: { readonly $: Readonly<Record<string, never>>; readonly fragmentMetadata: unknown[] | undefined }) => Record<string, unknown> },
2654
+ ) => ResolveOperationAtBuilder_${name}<TOperationType, TName>;
2655
+
2656
+ export type PrebuiltContext_${name} = {
2657
+ readonly fragment: PrebuiltCurriedFragment_${name};
2658
+ readonly query: PrebuiltCurriedOperation_${name}<"query"> & {
2659
+ readonly operation: PrebuiltCallbackOperation_${name}<"query">;
2660
+ readonly compat: (operationName: string) => (strings: TemplateStringsArray, ...values: never[]) => GqlDefine<unknown>;
2661
+ };
2662
+ readonly mutation: PrebuiltCurriedOperation_${name}<"mutation"> & {
2663
+ readonly operation: PrebuiltCallbackOperation_${name}<"mutation">;
2664
+ readonly compat: (operationName: string) => (strings: TemplateStringsArray, ...values: never[]) => GqlDefine<unknown>;
2665
+ };
2666
+ readonly subscription: PrebuiltCurriedOperation_${name}<"subscription"> & {
2667
+ readonly operation: PrebuiltCallbackOperation_${name}<"subscription">;
2668
+ readonly compat: (operationName: string) => (strings: TemplateStringsArray, ...values: never[]) => GqlDefine<unknown>;
2669
+ };
2670
+ readonly define: <TValue>(factory: () => TValue | Promise<TValue>) => GqlDefine<TValue>;
2671
+ readonly extend: (...args: unknown[]) => AnyOperation;
2672
+ readonly $var: VarBuilder<Schema_${name}>;
2673
+ readonly $dir: typeof __directiveMethods_${name};
2674
+ readonly $colocate: <T extends Record<string, unknown>>(projections: T) => T;
2675
+ };
2676
+
2677
+ type GqlComposer_${name} = {
2678
+ <TResult>(composeElement: (context: PrebuiltContext_${name}) => TResult): TResult;
2679
+ readonly $schema: AnyGraphqlSchema;
2680
+ };`).join("\n");
2681
+ const gqlEntries = schemaNames.map((name) => ` ${name}: __gql_${name} as unknown as GqlComposer_${name}`).join(",\n");
2682
+ return `\
2683
+ /**
2684
+ * Generated by @soda-gql/tools/codegen
2685
+ * @module
2686
+ * @generated
2687
+ */
2688
+
2689
+ export * from "./_internal";
2690
+ import { ${gqlImports} } from "./_internal";
2691
+ import type { ${schemaTypeImports} } from "./_internal";
2692
+ import type { ${directiveImports} } from "./_internal";
2693
+ import type { ${prebuiltImports} } from "./types.prebuilt";
2694
+ import type { Fragment, Operation, OperationType, PrebuiltEntryNotFound, AnyConstAssignableInput, AnyFields, AnyGraphqlSchema, AnyOperation, VarBuilder, GqlDefine } from "@soda-gql/core";
2695
+ ${perSchemaTypes}
2696
+
2697
+ export const gql = {
2698
+ ${gqlEntries}
2699
+ };
2700
+ `;
2701
+ };
2702
+
2703
+ //#endregion
2704
+ //#region packages/tools/src/codegen/graphql-compat/parser.ts
2705
+ /**
2706
+ * Parser for .graphql operation files.
2707
+ * Extracts operations and fragments from GraphQL documents.
2708
+ * @module
2709
+ */
2710
+ /**
2711
+ * Parse a single .graphql file and extract operations and fragments.
2712
+ */
2713
+ const parseGraphqlFile = (filePath) => {
2714
+ const resolvedPath = resolve(filePath);
2715
+ if (!existsSync(resolvedPath)) {
2716
+ return err({
2717
+ code: "GRAPHQL_FILE_NOT_FOUND",
2718
+ message: `GraphQL file not found at ${resolvedPath}`,
2719
+ filePath: resolvedPath
2720
+ });
2721
+ }
2722
+ try {
2723
+ const source = readFileSync(resolvedPath, "utf8");
2724
+ const document = parse(source);
2725
+ return ok(extractFromDocument(document, resolvedPath));
2726
+ } catch (error) {
2727
+ const message = error instanceof Error ? error.message : String(error);
2728
+ return err({
2729
+ code: "GRAPHQL_PARSE_ERROR",
2730
+ message: `GraphQL parse error: ${message}`,
2731
+ filePath: resolvedPath
2732
+ });
2733
+ }
2734
+ };
2735
+ /**
2736
+ * Parse GraphQL source string directly.
2737
+ */
2738
+ const parseGraphqlSource = (source, sourceFile) => {
2739
+ try {
2740
+ const document = parse(source);
2741
+ return ok(extractFromDocument(document, sourceFile));
2742
+ } catch (error) {
2743
+ const message = error instanceof Error ? error.message : String(error);
2744
+ return err({
2745
+ code: "GRAPHQL_PARSE_ERROR",
2746
+ message: `GraphQL parse error: ${message}`,
2747
+ filePath: sourceFile
2748
+ });
2749
+ }
2750
+ };
2751
+ /**
2752
+ * Extract operations and fragments from a parsed GraphQL document.
2753
+ */
2754
+ const extractFromDocument = (document, sourceFile) => {
2755
+ const operations = [];
2756
+ const fragments = [];
2757
+ for (const definition of document.definitions) {
2758
+ if (definition.kind === Kind.OPERATION_DEFINITION) {
2759
+ const operation = extractOperation(definition, sourceFile);
2760
+ if (operation) {
2761
+ operations.push(operation);
2762
+ }
2763
+ } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {
2764
+ fragments.push(extractFragment(definition, sourceFile));
2765
+ }
2766
+ }
2767
+ return {
2768
+ operations,
2769
+ fragments
2770
+ };
2771
+ };
2772
+ /**
2773
+ * Extract a single operation from an OperationDefinitionNode.
2774
+ */
2775
+ const extractOperation = (node, sourceFile) => {
2776
+ if (!node.name) {
2777
+ return null;
2778
+ }
2779
+ const variables = (node.variableDefinitions ?? []).map(extractVariable);
2780
+ const selections = extractSelections(node.selectionSet.selections);
2781
+ return {
2782
+ kind: node.operation,
2783
+ name: node.name.value,
2784
+ variables,
2785
+ selections,
2786
+ sourceFile
2787
+ };
2788
+ };
2789
+ /**
2790
+ * Extract a fragment from a FragmentDefinitionNode.
2791
+ */
2792
+ const extractFragment = (node, sourceFile) => {
2793
+ const selections = extractSelections(node.selectionSet.selections);
2794
+ return {
2795
+ name: node.name.value,
2796
+ onType: node.typeCondition.name.value,
2797
+ selections,
2798
+ sourceFile
2799
+ };
2800
+ };
2801
+ /**
2802
+ * Extract a variable definition.
2803
+ */
2804
+ const extractVariable = (node) => {
2805
+ const { typeName, modifier } = parseTypeNode(node.type);
2806
+ const defaultValue = node.defaultValue ? extractValue(node.defaultValue) : undefined;
2807
+ return {
2808
+ name: node.variable.name.value,
2809
+ typeName,
2810
+ modifier,
2811
+ typeKind: "scalar",
2812
+ defaultValue
2813
+ };
2814
+ };
2815
+ /**
2816
+ * Parse a GraphQL TypeNode into type name and modifier.
2817
+ *
2818
+ * Format: inner nullability + list modifiers
2819
+ * - Inner: `!` (non-null) or `?` (nullable)
2820
+ * - List: `[]!` (non-null list) or `[]?` (nullable list)
2821
+ */
2822
+ const parseTypeNode = (node) => {
2823
+ const levels = [];
2824
+ const collect = (n, nonNull) => {
2825
+ if (n.kind === Kind.NON_NULL_TYPE) {
2826
+ return collect(n.type, true);
2827
+ }
2828
+ if (n.kind === Kind.LIST_TYPE) {
2829
+ levels.push({
2830
+ kind: "list",
2831
+ nonNull
2832
+ });
2833
+ return collect(n.type, false);
2834
+ }
2835
+ levels.push({
2836
+ kind: "named",
2837
+ nonNull
2838
+ });
2839
+ return n.name.value;
2840
+ };
2841
+ const typeName = collect(node, false);
2842
+ let modifier = "?";
2843
+ for (const level of levels.slice().reverse()) {
2844
+ if (level.kind === "named") {
2845
+ modifier = level.nonNull ? "!" : "?";
2846
+ continue;
2847
+ }
2848
+ const listSuffix = level.nonNull ? "[]!" : "[]?";
2849
+ modifier = `${modifier}${listSuffix}`;
2850
+ }
2851
+ return {
2852
+ typeName,
2853
+ modifier
2854
+ };
2855
+ };
2856
+ /**
2857
+ * Extract selections from a SelectionSet.
2858
+ */
2859
+ const extractSelections = (selections) => {
2860
+ return selections.map(extractSelection);
2861
+ };
2862
+ /**
2863
+ * Extract a single selection.
2864
+ */
2865
+ const extractSelection = (node) => {
2866
+ switch (node.kind) {
2867
+ case Kind.FIELD: return extractFieldSelection(node);
2868
+ case Kind.FRAGMENT_SPREAD: return extractFragmentSpread(node);
2869
+ case Kind.INLINE_FRAGMENT: return extractInlineFragment(node);
2870
+ }
2871
+ };
2872
+ /**
2873
+ * Extract a field selection.
2874
+ */
2875
+ const extractFieldSelection = (node) => {
2876
+ const args = node.arguments?.length ? node.arguments.map(extractArgument) : undefined;
2877
+ const selections = node.selectionSet ? extractSelections(node.selectionSet.selections) : undefined;
2878
+ return {
2879
+ kind: "field",
2880
+ name: node.name.value,
2881
+ alias: node.alias?.value,
2882
+ arguments: args,
2883
+ selections
2884
+ };
2885
+ };
2886
+ /**
2887
+ * Extract a fragment spread.
2888
+ */
2889
+ const extractFragmentSpread = (node) => {
2890
+ return {
2891
+ kind: "fragmentSpread",
2892
+ name: node.name.value
2893
+ };
2894
+ };
2895
+ /**
2896
+ * Extract an inline fragment.
2897
+ */
2898
+ const extractInlineFragment = (node) => {
2899
+ return {
2900
+ kind: "inlineFragment",
2901
+ onType: node.typeCondition?.name.value ?? "",
2902
+ selections: extractSelections(node.selectionSet.selections)
2903
+ };
2904
+ };
2905
+ /**
2906
+ * Extract an argument.
2907
+ */
2908
+ const extractArgument = (node) => {
2909
+ return {
2910
+ name: node.name.value,
2911
+ value: extractValue(node.value)
2912
+ };
2913
+ };
2914
+ /**
2915
+ * Assert unreachable code path (for exhaustiveness checks).
2916
+ */
2917
+ const assertUnreachable = (value) => {
2918
+ throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
2919
+ };
2920
+ /**
2921
+ * Extract a value (literal or variable reference).
2922
+ */
2923
+ const extractValue = (node) => {
2924
+ switch (node.kind) {
2925
+ case Kind.VARIABLE: return {
2926
+ kind: "variable",
2927
+ name: node.name.value
2928
+ };
2929
+ case Kind.INT: return {
2930
+ kind: "int",
2931
+ value: node.value
2932
+ };
2933
+ case Kind.FLOAT: return {
2934
+ kind: "float",
2935
+ value: node.value
2936
+ };
2937
+ case Kind.STRING: return {
2938
+ kind: "string",
2939
+ value: node.value
2940
+ };
2941
+ case Kind.BOOLEAN: return {
2942
+ kind: "boolean",
2943
+ value: node.value
2944
+ };
2945
+ case Kind.NULL: return { kind: "null" };
2946
+ case Kind.ENUM: return {
2947
+ kind: "enum",
2948
+ value: node.value
2949
+ };
2950
+ case Kind.LIST: return {
2951
+ kind: "list",
2952
+ values: node.values.map(extractValue)
2953
+ };
2954
+ case Kind.OBJECT: return {
2955
+ kind: "object",
2956
+ fields: node.fields.map((field) => ({
2957
+ name: field.name.value,
2958
+ value: extractValue(field.value)
2959
+ }))
2960
+ };
2961
+ default: return assertUnreachable(node);
2962
+ }
2963
+ };
2964
+
2965
+ //#endregion
2966
+ //#region packages/tools/src/codegen/graphql-compat/transformer.ts
2967
+ /**
2968
+ * Transformer for enriching parsed GraphQL operations with schema information.
2969
+ * @module
2970
+ */
2971
+ /**
2972
+ * Built-in GraphQL scalar types.
2973
+ */
2974
+ const builtinScalarTypes = new Set([
2975
+ "ID",
2976
+ "String",
2977
+ "Int",
2978
+ "Float",
2979
+ "Boolean"
2980
+ ]);
2981
+ /**
2982
+ * Parse a modifier string into its structural components.
2983
+ * @param modifier - Modifier string like "!", "?", "![]!", "?[]?[]!"
2984
+ * @returns Parsed structure with inner nullability and list modifiers
2985
+ */
2986
+ const parseModifierStructure = (modifier) => {
2987
+ const inner = modifier[0] === "!" ? "!" : "?";
2988
+ const lists = [];
2989
+ const listPattern = /\[\]([!?])/g;
2990
+ let match;
2991
+ while ((match = listPattern.exec(modifier)) !== null) {
2992
+ lists.push(`[]${match[1]}`);
2993
+ }
2994
+ return {
2995
+ inner,
2996
+ lists
2997
+ };
2998
+ };
2999
+ /**
3000
+ * Rebuild modifier string from structure.
3001
+ */
3002
+ const buildModifier = (structure) => {
3003
+ return structure.inner + structure.lists.join("");
3004
+ };
3005
+ /**
3006
+ * Check if source modifier can be assigned to target modifier.
3007
+ * Implements GraphQL List Coercion: depth difference of 0 or 1 is allowed.
3008
+ *
3009
+ * Rules:
3010
+ * - A single value can be coerced into a list (depth diff = 1)
3011
+ * - At each level, non-null can be assigned to nullable (but not vice versa)
3012
+ *
3013
+ * @param source - The modifier of the value being assigned (variable's type)
3014
+ * @param target - The modifier expected by the position (field argument's type)
3015
+ * @returns true if assignment is valid
3016
+ */
3017
+ const isModifierAssignable = (source, target) => {
3018
+ const srcStruct = parseModifierStructure(source);
3019
+ const tgtStruct = parseModifierStructure(target);
3020
+ const depthDiff = tgtStruct.lists.length - srcStruct.lists.length;
3021
+ if (depthDiff < 0 || depthDiff > 1) return false;
3022
+ const tgtListsToCompare = depthDiff === 1 ? tgtStruct.lists.slice(1) : tgtStruct.lists;
3023
+ if (depthDiff === 1 && srcStruct.lists.length === 0 && srcStruct.inner === "?" && tgtStruct.lists[0] === "[]!") {
3024
+ return false;
3025
+ }
3026
+ if (srcStruct.inner === "?" && tgtStruct.inner === "!") return false;
3027
+ for (let i = 0; i < srcStruct.lists.length; i++) {
3028
+ const srcList = srcStruct.lists[i];
3029
+ const tgtList = tgtListsToCompare[i];
3030
+ if (srcList === undefined || tgtList === undefined) break;
3031
+ if (srcList === "[]?" && tgtList === "[]!") return false;
3032
+ }
3033
+ return true;
3034
+ };
3035
+ /**
3036
+ * Derive minimum modifier needed to satisfy expected modifier.
3037
+ * When List Coercion can apply, returns one level shallower.
3038
+ *
3039
+ * @param expectedModifier - The modifier expected by the field argument
3040
+ * @returns The minimum modifier the variable must have
3041
+ */
3042
+ const deriveMinimumModifier = (expectedModifier) => {
3043
+ const struct = parseModifierStructure(expectedModifier);
3044
+ if (struct.lists.length > 0) {
3045
+ return buildModifier({
3046
+ inner: struct.inner,
3047
+ lists: struct.lists.slice(1)
3048
+ });
3049
+ }
3050
+ return expectedModifier;
3051
+ };
3052
+ /**
3053
+ * Merge two modifiers by taking the stricter constraint at each level.
3054
+ * - Non-null (!) is stricter than nullable (?)
3055
+ * - List depths must match
3056
+ *
3057
+ * @param a - First modifier
3058
+ * @param b - Second modifier
3059
+ * @returns Merged modifier or error if incompatible
3060
+ */
3061
+ const mergeModifiers = (a, b) => {
3062
+ const structA = parseModifierStructure(a);
3063
+ const structB = parseModifierStructure(b);
3064
+ if (structA.lists.length !== structB.lists.length) {
3065
+ return {
3066
+ ok: false,
3067
+ reason: `Incompatible list depths: "${a}" has ${structA.lists.length} list level(s), "${b}" has ${structB.lists.length}`
3068
+ };
3069
+ }
3070
+ const mergedInner = structA.inner === "!" || structB.inner === "!" ? "!" : "?";
3071
+ const mergedLists = [];
3072
+ for (let i = 0; i < structA.lists.length; i++) {
3073
+ const listA = structA.lists[i];
3074
+ const listB = structB.lists[i];
3075
+ if (listA === undefined || listB === undefined) break;
3076
+ mergedLists.push(listA === "[]!" || listB === "[]!" ? "[]!" : "[]?");
3077
+ }
3078
+ return {
3079
+ ok: true,
3080
+ value: buildModifier({
3081
+ inner: mergedInner,
3082
+ lists: mergedLists
3083
+ })
3084
+ };
3085
+ };
3086
+ /**
3087
+ * Get the expected type for a field argument from the schema.
3088
+ * Returns null if the field or argument is not found.
3089
+ */
3090
+ const getArgumentType = (schema, parentTypeName, fieldName, argumentName) => {
3091
+ const objectRecord = schema.objects.get(parentTypeName);
3092
+ if (!objectRecord) return null;
3093
+ const fieldDef = objectRecord.fields.get(fieldName);
3094
+ if (!fieldDef) return null;
3095
+ const argDef = fieldDef.arguments?.find((arg) => arg.name.value === argumentName);
3096
+ if (!argDef) return null;
3097
+ return parseTypeNode(argDef.type);
3098
+ };
3099
+ /**
3100
+ * Get the expected type for an input object field from the schema.
3101
+ */
3102
+ const getInputFieldType = (schema, inputTypeName, fieldName) => {
3103
+ const inputRecord = schema.inputs.get(inputTypeName);
3104
+ if (!inputRecord) return null;
3105
+ const fieldDef = inputRecord.fields.get(fieldName);
3106
+ if (!fieldDef) return null;
3107
+ return parseTypeNode(fieldDef.type);
3108
+ };
3109
+ /**
3110
+ * Resolve the type kind for a type name.
3111
+ */
3112
+ const resolveTypeKindFromName = (schema, typeName) => {
3113
+ if (isScalarName(schema, typeName)) return "scalar";
3114
+ if (isEnumName(schema, typeName)) return "enum";
3115
+ if (schema.inputs.has(typeName)) return "input";
3116
+ return null;
3117
+ };
3118
+ /**
3119
+ * Extract variable usages from a parsed value, given the expected type.
3120
+ * Handles nested input objects recursively.
3121
+ */
3122
+ const collectVariablesFromValue = (value, expectedTypeName, expectedModifier, schema, usages) => {
3123
+ if (value.kind === "variable") {
3124
+ const typeKind = resolveTypeKindFromName(schema, expectedTypeName);
3125
+ if (!typeKind) {
3126
+ return {
3127
+ code: "GRAPHQL_UNKNOWN_TYPE",
3128
+ message: `Unknown type "${expectedTypeName}" for variable "$${value.name}"`,
3129
+ typeName: expectedTypeName
3130
+ };
3131
+ }
3132
+ usages.push({
3133
+ name: value.name,
3134
+ typeName: expectedTypeName,
3135
+ expectedModifier,
3136
+ minimumModifier: deriveMinimumModifier(expectedModifier),
3137
+ typeKind
3138
+ });
3139
+ return null;
3140
+ }
3141
+ if (value.kind === "object") {
3142
+ for (const field of value.fields) {
3143
+ const fieldType = getInputFieldType(schema, expectedTypeName, field.name);
3144
+ if (!fieldType) {
3145
+ return {
3146
+ code: "GRAPHQL_UNKNOWN_FIELD",
3147
+ message: `Unknown field "${field.name}" on input type "${expectedTypeName}"`,
3148
+ typeName: expectedTypeName,
3149
+ fieldName: field.name
3150
+ };
3151
+ }
3152
+ const error = collectVariablesFromValue(field.value, fieldType.typeName, fieldType.modifier, schema, usages);
3153
+ if (error) return error;
3154
+ }
3155
+ return null;
3156
+ }
3157
+ if (value.kind === "list") {
3158
+ const struct = parseModifierStructure(expectedModifier);
3159
+ if (struct.lists.length > 0) {
3160
+ const innerModifier = buildModifier({
3161
+ inner: struct.inner,
3162
+ lists: struct.lists.slice(1)
3163
+ });
3164
+ for (const item of value.values) {
3165
+ const error = collectVariablesFromValue(item, expectedTypeName, innerModifier, schema, usages);
3166
+ if (error) return error;
3167
+ }
3168
+ }
3169
+ }
3170
+ return null;
3171
+ };
3172
+ /**
3173
+ * Collect variable usages from field arguments.
3174
+ */
3175
+ const collectVariablesFromArguments = (args, parentTypeName, fieldName, schema, usages) => {
3176
+ for (const arg of args) {
3177
+ const argType = getArgumentType(schema, parentTypeName, fieldName, arg.name);
3178
+ if (!argType) {
3179
+ return {
3180
+ code: "GRAPHQL_UNKNOWN_ARGUMENT",
3181
+ message: `Unknown argument "${arg.name}" on field "${fieldName}"`,
3182
+ fieldName,
3183
+ argumentName: arg.name
3184
+ };
3185
+ }
3186
+ const error = collectVariablesFromValue(arg.value, argType.typeName, argType.modifier, schema, usages);
3187
+ if (error) return error;
3188
+ }
3189
+ return null;
3190
+ };
3191
+ /**
3192
+ * Recursively collect all variable usages from selections.
3193
+ */
3194
+ const collectVariableUsages = (selections, parentTypeName, schema) => {
3195
+ const usages = [];
3196
+ const collect = (sels, parentType) => {
3197
+ for (const sel of sels) {
3198
+ switch (sel.kind) {
3199
+ case "field": {
3200
+ if (sel.arguments && sel.arguments.length > 0) {
3201
+ const error$1 = collectVariablesFromArguments(sel.arguments, parentType, sel.name, schema, usages);
3202
+ if (error$1) return error$1;
3203
+ }
3204
+ if (sel.selections && sel.selections.length > 0) {
3205
+ const fieldReturnType = getFieldReturnType(schema, parentType, sel.name);
3206
+ if (!fieldReturnType) {
3207
+ return {
3208
+ code: "GRAPHQL_UNKNOWN_FIELD",
3209
+ message: `Unknown field "${sel.name}" on type "${parentType}"`,
3210
+ typeName: parentType,
3211
+ fieldName: sel.name
3212
+ };
3213
+ }
3214
+ const error$1 = collect(sel.selections, fieldReturnType);
3215
+ if (error$1) return error$1;
3216
+ }
3217
+ break;
3218
+ }
3219
+ case "inlineFragment": {
3220
+ const error$1 = collect(sel.selections, sel.onType);
3221
+ if (error$1) return error$1;
3222
+ break;
3223
+ }
3224
+ case "fragmentSpread": break;
3225
+ }
3226
+ }
3227
+ return null;
3228
+ };
3229
+ const error = collect(selections, parentTypeName);
3230
+ if (error) return err(error);
3231
+ return ok(usages);
3232
+ };
3233
+ /**
3234
+ * Get the return type of a field (unwrapped from modifiers).
3235
+ */
3236
+ const getFieldReturnType = (schema, parentTypeName, fieldName) => {
3237
+ const objectRecord = schema.objects.get(parentTypeName);
3238
+ if (!objectRecord) return null;
3239
+ const fieldDef = objectRecord.fields.get(fieldName);
3240
+ if (!fieldDef) return null;
3241
+ const { typeName } = parseTypeNode(fieldDef.type);
3242
+ return typeName;
3243
+ };
3244
+ /**
3245
+ * Merge multiple variable usages into a single InferredVariable.
3246
+ * Validates type compatibility and merges modifiers using List Coercion rules.
3247
+ *
3248
+ * The algorithm:
3249
+ * 1. Validate all usages have the same type name
3250
+ * 2. Merge minimumModifiers to find the candidate (shallowest type that could work)
3251
+ * 3. Verify the candidate can satisfy ALL expected modifiers via isModifierAssignable
3252
+ */
3253
+ const mergeVariableUsages = (variableName, usages) => {
3254
+ const first = usages[0];
3255
+ if (!first) {
3256
+ return err({
3257
+ code: "GRAPHQL_UNDECLARED_VARIABLE",
3258
+ message: `No usages found for variable "${variableName}"`,
3259
+ variableName
3260
+ });
3261
+ }
3262
+ for (const usage of usages) {
3263
+ if (usage.typeName !== first.typeName) {
3264
+ return err({
3265
+ code: "GRAPHQL_VARIABLE_TYPE_MISMATCH",
3266
+ message: `Variable "$${variableName}" has conflicting types: "${first.typeName}" and "${usage.typeName}"`,
3267
+ variableName
3268
+ });
3269
+ }
3270
+ }
3271
+ let candidateModifier = first.minimumModifier;
3272
+ for (let i = 1; i < usages.length; i++) {
3273
+ const usage = usages[i];
3274
+ if (!usage) break;
3275
+ const result = mergeModifiers(candidateModifier, usage.minimumModifier);
3276
+ if (!result.ok) {
3277
+ return err({
3278
+ code: "GRAPHQL_VARIABLE_MODIFIER_INCOMPATIBLE",
3279
+ message: `Variable "$${variableName}" has incompatible modifiers: ${result.reason}`,
3280
+ variableName
3281
+ });
3282
+ }
3283
+ candidateModifier = result.value;
3284
+ }
3285
+ for (const usage of usages) {
3286
+ if (!isModifierAssignable(candidateModifier, usage.expectedModifier)) {
3287
+ return err({
3288
+ code: "GRAPHQL_VARIABLE_MODIFIER_INCOMPATIBLE",
3289
+ message: `Variable "$${variableName}" with modifier "${candidateModifier}" cannot satisfy expected "${usage.expectedModifier}"`,
3290
+ variableName
3291
+ });
3292
+ }
3293
+ }
3294
+ return ok({
3295
+ name: variableName,
3296
+ typeName: first.typeName,
3297
+ modifier: candidateModifier,
3298
+ typeKind: first.typeKind
3299
+ });
3300
+ };
3301
+ /**
3302
+ * Infer variables from collected usages.
3303
+ * Groups by variable name and merges each group.
3304
+ */
3305
+ const inferVariablesFromUsages = (usages) => {
3306
+ const byName = new Map();
3307
+ for (const usage of usages) {
3308
+ const existing = byName.get(usage.name);
3309
+ if (existing) {
3310
+ existing.push(usage);
3311
+ } else {
3312
+ byName.set(usage.name, [usage]);
3313
+ }
3314
+ }
3315
+ const variables = [];
3316
+ for (const [name, group] of byName) {
3317
+ const result = mergeVariableUsages(name, group);
3318
+ if (result.isErr()) return err(result.error);
3319
+ variables.push(result.value);
3320
+ }
3321
+ variables.sort((a, b) => a.name.localeCompare(b.name));
3322
+ return ok(variables);
3323
+ };
3324
+ /**
3325
+ * Check if a type name is a scalar type.
3326
+ */
3327
+ const isScalarName = (schema, name) => builtinScalarTypes.has(name) || schema.scalars.has(name);
3328
+ /**
3329
+ * Topologically sort fragments so dependencies come before dependents.
3330
+ * Detects circular dependencies.
3331
+ *
3332
+ * Note: Uses the existing collectFragmentDependencies function defined below.
3333
+ */
3334
+ const sortFragmentsByDependency = (fragments) => {
3335
+ const graph = new Map();
3336
+ for (const fragment of fragments) {
3337
+ const deps = collectFragmentDependenciesSet(fragment.selections);
3338
+ graph.set(fragment.name, deps);
3339
+ }
3340
+ const fragmentByName = new Map();
3341
+ for (const f of fragments) {
3342
+ fragmentByName.set(f.name, f);
3343
+ }
3344
+ const sorted = [];
3345
+ const visited = new Set();
3346
+ const visiting = new Set();
3347
+ const visit = (name, path) => {
3348
+ if (visited.has(name)) return null;
3349
+ if (visiting.has(name)) {
3350
+ const cycleStart = path.indexOf(name);
3351
+ const cycle = path.slice(cycleStart).concat(name);
3352
+ return {
3353
+ code: "GRAPHQL_FRAGMENT_CIRCULAR_DEPENDENCY",
3354
+ message: `Circular dependency detected in fragments: ${cycle.join(" -> ")}`,
3355
+ fragmentNames: cycle
3356
+ };
3357
+ }
3358
+ const fragment = fragmentByName.get(name);
3359
+ if (!fragment) {
3360
+ visited.add(name);
3361
+ return null;
3362
+ }
3363
+ visiting.add(name);
3364
+ const deps = graph.get(name) ?? new Set();
3365
+ for (const dep of deps) {
3366
+ const error = visit(dep, [...path, name]);
3367
+ if (error) return error;
3368
+ }
3369
+ visiting.delete(name);
3370
+ visited.add(name);
3371
+ sorted.push(fragment);
3372
+ return null;
3373
+ };
3374
+ for (const fragment of fragments) {
3375
+ const error = visit(fragment.name, []);
3376
+ if (error) return err(error);
3377
+ }
3378
+ return ok(sorted);
3379
+ };
3380
+ /**
3381
+ * Recursively collect fragment spread names from selections into a Set.
3382
+ * Internal helper for sortFragmentsByDependency.
3383
+ */
3384
+ const collectFragmentDependenciesSet = (selections) => {
3385
+ const deps = new Set();
3386
+ const collect = (sels) => {
3387
+ for (const sel of sels) {
3388
+ switch (sel.kind) {
3389
+ case "fragmentSpread":
3390
+ deps.add(sel.name);
3391
+ break;
3392
+ case "field":
3393
+ if (sel.selections) {
3394
+ collect(sel.selections);
3395
+ }
3396
+ break;
3397
+ case "inlineFragment":
3398
+ collect(sel.selections);
3399
+ break;
3400
+ }
3401
+ }
3402
+ };
3403
+ collect(selections);
3404
+ return deps;
3405
+ };
3406
+ /**
3407
+ * Check if a type name is an enum type.
3408
+ */
3409
+ const isEnumName = (schema, name) => schema.enums.has(name);
3410
+ /**
3411
+ * Transform parsed operations/fragments by enriching them with schema information.
3412
+ *
3413
+ * This resolves variable type kinds (scalar, enum, input), collects
3414
+ * fragment dependencies, and infers variables for fragments.
3415
+ */
3416
+ const transformParsedGraphql = (parsed, options) => {
3417
+ const schema = createSchemaIndex(options.schemaDocument);
3418
+ const sortResult = sortFragmentsByDependency(parsed.fragments);
3419
+ if (sortResult.isErr()) {
3420
+ return err(sortResult.error);
3421
+ }
3422
+ const sortedFragments = sortResult.value;
3423
+ const resolvedFragmentVariables = new Map();
3424
+ const fragments = [];
3425
+ for (const frag of sortedFragments) {
3426
+ const result = transformFragment(frag, schema, resolvedFragmentVariables);
3427
+ if (result.isErr()) {
3428
+ return err(result.error);
3429
+ }
3430
+ resolvedFragmentVariables.set(frag.name, result.value.variables);
3431
+ fragments.push(result.value);
3432
+ }
3433
+ const operations = [];
3434
+ for (const op of parsed.operations) {
3435
+ const result = transformOperation(op, schema);
3436
+ if (result.isErr()) {
3437
+ return err(result.error);
3438
+ }
3439
+ operations.push(result.value);
3440
+ }
3441
+ return ok({
3442
+ operations,
3443
+ fragments
3444
+ });
3445
+ };
3446
+ /**
3447
+ * Transform a single operation.
3448
+ */
3449
+ const transformOperation = (op, schema) => {
3450
+ const variables = [];
3451
+ for (const v of op.variables) {
3452
+ const typeKind = resolveTypeKind(schema, v.typeName);
3453
+ if (typeKind === null) {
3454
+ return err({
3455
+ code: "GRAPHQL_UNKNOWN_TYPE",
3456
+ message: `Unknown type "${v.typeName}" in variable "${v.name}"`,
3457
+ typeName: v.typeName
3458
+ });
3459
+ }
3460
+ variables.push({
3461
+ ...v,
3462
+ typeKind
3463
+ });
3464
+ }
3465
+ const fragmentDependencies = collectFragmentDependencies(op.selections);
3466
+ return ok({
3467
+ ...op,
3468
+ variables,
3469
+ fragmentDependencies
3470
+ });
3471
+ };
3472
+ /**
3473
+ * Transform a single fragment.
3474
+ * Infers variables from field arguments and propagates variables from spread fragments.
3475
+ */
3476
+ const transformFragment = (frag, schema, resolvedFragmentVariables) => {
3477
+ const fragmentDependencies = collectFragmentDependencies(frag.selections);
3478
+ const directUsagesResult = collectVariableUsages(frag.selections, frag.onType, schema);
3479
+ if (directUsagesResult.isErr()) {
3480
+ return err(directUsagesResult.error);
3481
+ }
3482
+ const directUsages = directUsagesResult.value;
3483
+ const spreadVariables = [];
3484
+ for (const depName of fragmentDependencies) {
3485
+ const depVariables = resolvedFragmentVariables.get(depName);
3486
+ if (depVariables) {
3487
+ spreadVariables.push(...depVariables);
3488
+ }
3489
+ }
3490
+ const allUsages = [...directUsages, ...spreadVariables.map((v) => ({
3491
+ name: v.name,
3492
+ typeName: v.typeName,
3493
+ expectedModifier: v.modifier,
3494
+ minimumModifier: v.modifier,
3495
+ typeKind: v.typeKind
3496
+ }))];
3497
+ const variablesResult = inferVariablesFromUsages(allUsages);
3498
+ if (variablesResult.isErr()) {
3499
+ return err(variablesResult.error);
3500
+ }
3501
+ return ok({
3502
+ ...frag,
3503
+ fragmentDependencies,
3504
+ variables: variablesResult.value
3505
+ });
3506
+ };
3507
+ /**
3508
+ * Resolve the type kind for a type name.
3509
+ */
3510
+ const resolveTypeKind = (schema, typeName) => {
3511
+ if (isScalarName(schema, typeName)) {
3512
+ return "scalar";
3513
+ }
3514
+ if (isEnumName(schema, typeName)) {
3515
+ return "enum";
3516
+ }
3517
+ if (schema.inputs.has(typeName)) {
3518
+ return "input";
3519
+ }
3520
+ return null;
3521
+ };
3522
+ /**
3523
+ * Collect fragment names used in selections (recursively).
3524
+ */
3525
+ const collectFragmentDependencies = (selections) => {
3526
+ const fragments = new Set();
3527
+ const collect = (sels) => {
3528
+ for (const sel of sels) {
3529
+ switch (sel.kind) {
3530
+ case "fragmentSpread":
3531
+ fragments.add(sel.name);
3532
+ break;
3533
+ case "field":
3534
+ if (sel.selections) {
3535
+ collect(sel.selections);
3536
+ }
3537
+ break;
3538
+ case "inlineFragment":
3539
+ collect(sel.selections);
3540
+ break;
3541
+ }
3542
+ }
3543
+ };
3544
+ collect(selections);
3545
+ return [...fragments];
3546
+ };
3547
+
3548
+ //#endregion
3549
+ //#region packages/tools/src/codegen/graphql-compat/emitter.ts
3550
+ /**
3551
+ * Map operation kind to root type name.
3552
+ * Uses schema.operationTypes if available, falls back to standard names.
3553
+ */
3554
+ const getRootTypeName = (schema, kind) => {
3555
+ if (schema) {
3556
+ switch (kind) {
3557
+ case "query": return schema.operationTypes.query ?? "Query";
3558
+ case "mutation": return schema.operationTypes.mutation ?? "Mutation";
3559
+ case "subscription": return schema.operationTypes.subscription ?? "Subscription";
3560
+ }
3561
+ }
3562
+ switch (kind) {
3563
+ case "query": return "Query";
3564
+ case "mutation": return "Mutation";
3565
+ case "subscription": return "Subscription";
3566
+ }
3567
+ };
3568
+ /**
3569
+ * Emit TypeScript code for an operation.
3570
+ */
3571
+ const emitOperation = (operation, options) => {
3572
+ const lines = [];
3573
+ const schema = options.schemaDocument ? createSchemaIndex(options.schemaDocument) : null;
3574
+ const exportName = `${operation.name}Compat`;
3575
+ const operationType = operation.kind;
3576
+ lines.push(`export const ${exportName} = gql.${options.schemaName}(({ ${operationType}, $var }) =>`);
3577
+ lines.push(` ${operationType}.compat({`);
3578
+ lines.push(` name: ${JSON.stringify(operation.name)},`);
3579
+ if (operation.variables.length > 0) {
3580
+ lines.push(` variables: { ${emitVariables(operation.variables)} },`);
3581
+ }
3582
+ const rootTypeName = getRootTypeName(schema, operation.kind);
3583
+ lines.push(` fields: ({ f, $ }) => ({`);
3584
+ const fieldLinesResult = emitSelections(operation.selections, 3, operation.variables, schema, rootTypeName);
3585
+ if (fieldLinesResult.isErr()) {
3586
+ return err(fieldLinesResult.error);
3587
+ }
3588
+ lines.push(fieldLinesResult.value);
3589
+ lines.push(` }),`);
3590
+ lines.push(` }),`);
3591
+ lines.push(`);`);
3592
+ return ok(lines.join("\n"));
3593
+ };
3594
+ /**
3595
+ * Emit TypeScript code for a fragment.
3596
+ */
3597
+ const emitFragment = (fragment, options) => {
3598
+ const lines = [];
3599
+ const schema = options.schemaDocument ? createSchemaIndex(options.schemaDocument) : null;
3600
+ const hasVariables = fragment.variables.length > 0;
3601
+ const exportName = `${fragment.name}Fragment`;
3602
+ const destructure = hasVariables ? "fragment, $var" : "fragment";
3603
+ lines.push(`export const ${exportName} = gql.${options.schemaName}(({ ${destructure} }) =>`);
3604
+ lines.push(` fragment.${fragment.onType}({`);
3605
+ if (hasVariables) {
3606
+ lines.push(` variables: { ${emitVariables(fragment.variables)} },`);
3607
+ }
3608
+ const fieldsContext = hasVariables ? "{ f, $ }" : "{ f }";
3609
+ lines.push(` fields: (${fieldsContext}) => ({`);
3610
+ const fieldLinesResult = emitSelections(fragment.selections, 3, fragment.variables, schema, fragment.onType);
3611
+ if (fieldLinesResult.isErr()) {
3612
+ return err(fieldLinesResult.error);
3613
+ }
3614
+ lines.push(fieldLinesResult.value);
3615
+ lines.push(` }),`);
3616
+ lines.push(` }),`);
3617
+ lines.push(`);`);
3618
+ return ok(lines.join("\n"));
3619
+ };
3620
+ /**
3621
+ * Emit variable definitions.
3622
+ */
3623
+ const emitVariables = (variables) => {
3624
+ return variables.map((v) => `...$var(${JSON.stringify(v.name)}).${v.typeName}(${JSON.stringify(v.modifier)})`).join(", ");
3625
+ };
3626
+ /**
3627
+ * Emit field selections (public API).
3628
+ * Converts variable array to Set<string> and delegates to internal implementation.
3629
+ */
3630
+ const emitSelections = (selections, indent, variables, schema, parentTypeName) => {
3631
+ const variableNames = new Set(variables.map((v) => v.name));
3632
+ return emitSelectionsInternal(selections, indent, variableNames, schema, parentTypeName);
3633
+ };
3634
+ /**
3635
+ * Internal implementation for emitting field selections.
3636
+ * Takes variableNames as Set<string> for recursive calls.
3637
+ */
3638
+ const emitSelectionsInternal = (selections, indent, variableNames, schema, parentTypeName) => {
3639
+ const lines = [];
3640
+ const inlineFragments = [];
3641
+ const otherSelections = [];
3642
+ let hasTypenameField = false;
3643
+ for (const sel of selections) {
3644
+ if (sel.kind === "inlineFragment") {
3645
+ inlineFragments.push(sel);
3646
+ } else if (sel.kind === "field" && sel.name === "__typename" && !sel.alias) {
3647
+ hasTypenameField = true;
3648
+ } else {
3649
+ otherSelections.push(sel);
3650
+ }
3651
+ }
3652
+ for (const sel of otherSelections) {
3653
+ const result = emitSingleSelection(sel, indent, variableNames, schema, parentTypeName);
3654
+ if (result.isErr()) {
3655
+ return err(result.error);
3656
+ }
3657
+ lines.push(result.value);
3658
+ }
3659
+ if (inlineFragments.length > 0) {
3660
+ const unionResult = emitInlineFragmentsAsUnion(inlineFragments, indent, variableNames, schema, hasTypenameField);
3661
+ if (unionResult.isErr()) {
3662
+ return err(unionResult.error);
3663
+ }
3664
+ lines.push(unionResult.value);
3665
+ } else if (hasTypenameField) {
3666
+ const padding = " ".repeat(indent);
3667
+ lines.push(`${padding}__typename: true,`);
3668
+ }
3669
+ return ok(lines.join("\n"));
3670
+ };
3671
+ /**
3672
+ * Emit a single selection (field or fragment spread).
3673
+ */
3674
+ const emitSingleSelection = (sel, indent, variableNames, schema, parentTypeName) => {
3675
+ const padding = " ".repeat(indent);
3676
+ switch (sel.kind) {
3677
+ case "field": return emitFieldSelection(sel, indent, variableNames, schema, parentTypeName);
3678
+ case "fragmentSpread": return ok(`${padding}...${sel.name}Fragment.spread(),`);
3679
+ case "inlineFragment": return ok("");
3680
+ }
3681
+ };
3682
+ /**
3683
+ * Emit inline fragments grouped as a union selection.
3684
+ * Format: { TypeA: ({ f }) => ({ ...fields }), TypeB: ({ f }) => ({ ...fields }), __typename: true }
3685
+ */
3686
+ const emitInlineFragmentsAsUnion = (inlineFragments, indent, variableNames, schema, includeTypename) => {
3687
+ const padding = " ".repeat(indent);
3688
+ for (const frag of inlineFragments) {
3689
+ if (frag.onType === "") {
3690
+ return err({
3691
+ code: "GRAPHQL_INLINE_FRAGMENT_WITHOUT_TYPE",
3692
+ message: "Inline fragments without type condition are not supported. Use `... on TypeName { }` syntax."
3693
+ });
3694
+ }
3695
+ }
3696
+ for (const frag of inlineFragments) {
3697
+ if (schema && !schema.objects.has(frag.onType)) {
3698
+ let isUnionMember = false;
3699
+ for (const [, unionDef] of schema.unions) {
3700
+ if (unionDef.members.has(frag.onType)) {
3701
+ isUnionMember = true;
3702
+ break;
3703
+ }
3704
+ }
3705
+ if (!isUnionMember) {
3706
+ return err({
3707
+ code: "GRAPHQL_INLINE_FRAGMENT_ON_INTERFACE",
3708
+ message: `Inline fragments on interface type "${frag.onType}" are not supported. Use union types instead.`,
3709
+ onType: frag.onType
3710
+ });
3711
+ }
3712
+ }
3713
+ }
3714
+ const entries = [];
3715
+ for (const frag of inlineFragments) {
3716
+ const innerPadding = " ".repeat(indent + 1);
3717
+ const fieldsResult = emitSelectionsInternal(frag.selections, indent + 2, variableNames, schema, frag.onType);
3718
+ if (fieldsResult.isErr()) {
3719
+ return err(fieldsResult.error);
3720
+ }
3721
+ entries.push(`${innerPadding}${frag.onType}: ({ f }) => ({
3722
+ ${fieldsResult.value}
3723
+ ${innerPadding}}),`);
3724
+ }
3725
+ if (includeTypename) {
3726
+ const innerPadding = " ".repeat(indent + 1);
3727
+ entries.push(`${innerPadding}__typename: true,`);
3728
+ }
3729
+ return ok(`${padding}...({
3730
+ ${entries.join("\n")}
3731
+ ${padding}}),`);
3732
+ };
3733
+ /**
3734
+ * Emit a single field selection.
3735
+ */
3736
+ const emitFieldSelection = (field, indent, variableNames, schema, parentTypeName) => {
3737
+ const padding = " ".repeat(indent);
3738
+ const args = field.arguments;
3739
+ const selections = field.selections;
3740
+ const hasArgs = args && args.length > 0;
3741
+ const hasSelections = selections && selections.length > 0;
3742
+ if (!hasArgs && !hasSelections && !field.alias) {
3743
+ return ok(`${padding}${field.name}: true,`);
3744
+ }
3745
+ let line = `${padding}...f.${field.name}(`;
3746
+ if (hasArgs) {
3747
+ const argsResult = emitArguments(args, variableNames, schema, parentTypeName, field.name);
3748
+ if (argsResult.isErr()) {
3749
+ return err(argsResult.error);
3750
+ }
3751
+ line += argsResult.value;
3752
+ if (field.alias) {
3753
+ line += `, { alias: ${JSON.stringify(field.alias)} }`;
3754
+ }
3755
+ } else if (field.alias) {
3756
+ line += `null, { alias: ${JSON.stringify(field.alias)} }`;
3757
+ }
3758
+ line += ")";
3759
+ if (hasSelections) {
3760
+ const hasInlineFragments = selections.some((s) => s.kind === "inlineFragment");
3761
+ const nestedParentType = schema && parentTypeName ? getFieldReturnType(schema, parentTypeName, field.name) ?? undefined : undefined;
3762
+ if (hasInlineFragments) {
3763
+ const nestedResult = emitSelectionsInternal(selections, indent + 1, variableNames, schema, nestedParentType);
3764
+ if (nestedResult.isErr()) {
3765
+ return err(nestedResult.error);
3766
+ }
3767
+ line += "({\n";
3768
+ line += `${nestedResult.value}\n`;
3769
+ line += `${padding}})`;
3770
+ } else {
3771
+ line += "(({ f }) => ({\n";
3772
+ const nestedResult = emitSelectionsInternal(selections, indent + 1, variableNames, schema, nestedParentType);
3773
+ if (nestedResult.isErr()) {
3774
+ return err(nestedResult.error);
3775
+ }
3776
+ line += `${nestedResult.value}\n`;
3777
+ line += `${padding}}))`;
3778
+ }
3779
+ }
3780
+ line += ",";
3781
+ return ok(line);
3782
+ };
3783
+ /**
3784
+ * Check if a modifier represents a list type (contains []).
3785
+ */
3786
+ const isListModifier = (modifier) => {
3787
+ return modifier.includes("[]");
3788
+ };
3789
+ /**
3790
+ * Determine if a value needs to be wrapped in an array for list coercion.
3791
+ * Returns true if:
3792
+ * - Expected type is a list
3793
+ * - Value is NOT already a list
3794
+ * - Value is NOT a variable (runtime handles coercion)
3795
+ * - Value is NOT null
3796
+ */
3797
+ const needsListCoercion = (value, expectedModifier) => {
3798
+ if (!expectedModifier) return false;
3799
+ if (!isListModifier(expectedModifier)) return false;
3800
+ if (value.kind === "variable") return false;
3801
+ if (value.kind === "null") return false;
3802
+ if (value.kind === "list") return false;
3803
+ return true;
3804
+ };
3805
+ /**
3806
+ * Extract the element type from a list type by removing the outermost list modifier.
3807
+ * For example: "![]!" (non-null list of non-null) → "!" (non-null element)
3808
+ * "?[]![]!" (nested lists) → "?[]!" (inner list type)
3809
+ * Returns null if the modifier doesn't represent a list type.
3810
+ */
3811
+ const getListElementType = (expectedType) => {
3812
+ const { modifier, typeName } = expectedType;
3813
+ const listMatch = modifier.match(/^(.+?)(\[\][!?])$/);
3814
+ if (!listMatch || !listMatch[1]) return null;
3815
+ return {
3816
+ typeName,
3817
+ modifier: listMatch[1]
3818
+ };
3819
+ };
3820
+ /**
3821
+ * Emit a value with type context for list coercion.
3822
+ */
3823
+ const emitValueWithType = (value, expectedType, variableNames, schema) => {
3824
+ const shouldCoerce = needsListCoercion(value, expectedType?.modifier);
3825
+ if (value.kind === "object" && expectedType && schema) {
3826
+ return emitObjectWithType(value, expectedType.typeName, variableNames, schema, shouldCoerce);
3827
+ }
3828
+ if (value.kind === "list" && expectedType && schema) {
3829
+ const elementType = getListElementType(expectedType);
3830
+ if (elementType) {
3831
+ const values = [];
3832
+ for (const v of value.values) {
3833
+ const result$1 = emitValueWithType(v, elementType, variableNames, schema);
3834
+ if (result$1.isErr()) return result$1;
3835
+ values.push(result$1.value);
3836
+ }
3837
+ return ok(`[${values.join(", ")}]`);
3838
+ }
3839
+ }
3840
+ const result = emitValue(value, variableNames);
3841
+ if (result.isErr()) return result;
3842
+ if (shouldCoerce) {
3843
+ return ok(`[${result.value}]`);
3844
+ }
3845
+ return result;
3846
+ };
3847
+ /**
3848
+ * Emit an object value with type context for recursive list coercion.
3849
+ */
3850
+ const emitObjectWithType = (value, inputTypeName, variableNames, schema, wrapInArray) => {
3851
+ if (value.fields.length === 0) {
3852
+ return ok(wrapInArray ? "[{}]" : "{}");
3853
+ }
3854
+ const entries = [];
3855
+ for (const f of value.fields) {
3856
+ const fieldType = getInputFieldType(schema, inputTypeName, f.name);
3857
+ if (fieldType === null) {
3858
+ return err({
3859
+ code: "GRAPHQL_UNKNOWN_FIELD",
3860
+ message: `Unknown field "${f.name}" on input type "${inputTypeName}"`,
3861
+ typeName: inputTypeName,
3862
+ fieldName: f.name
3863
+ });
3864
+ }
3865
+ const result = emitValueWithType(f.value, fieldType, variableNames, schema);
3866
+ if (result.isErr()) {
3867
+ return err(result.error);
3868
+ }
3869
+ entries.push(`${f.name}: ${result.value}`);
3870
+ }
3871
+ const objectStr = `{ ${entries.join(", ")} }`;
3872
+ return ok(wrapInArray ? `[${objectStr}]` : objectStr);
3873
+ };
3874
+ /**
3875
+ * Emit field arguments with type context for list coercion.
3876
+ */
3877
+ const emitArguments = (args, variableNames, schema, parentTypeName, fieldName) => {
3878
+ if (args.length === 0) {
3879
+ return ok("");
3880
+ }
3881
+ const argEntries = [];
3882
+ for (const arg of args) {
3883
+ const expectedType = schema && parentTypeName && fieldName ? getArgumentType(schema, parentTypeName, fieldName, arg.name) : null;
3884
+ const result = emitValueWithType(arg.value, expectedType, variableNames, schema);
3885
+ if (result.isErr()) {
3886
+ return err(result.error);
3887
+ }
3888
+ argEntries.push(`${arg.name}: ${result.value}`);
3889
+ }
3890
+ return ok(`{ ${argEntries.join(", ")} }`);
3891
+ };
3892
+ /**
3893
+ * Emit a value (literal or variable reference).
3894
+ */
3895
+ const emitValue = (value, variableNames) => {
3896
+ switch (value.kind) {
3897
+ case "variable":
3898
+ if (variableNames.has(value.name)) {
3899
+ return ok(`$.${value.name}`);
3900
+ }
3901
+ return err({
3902
+ code: "GRAPHQL_UNDECLARED_VARIABLE",
3903
+ message: `Variable "$${value.name}" is not declared in the operation`,
3904
+ variableName: value.name
3905
+ });
3906
+ case "int":
3907
+ case "float": return ok(value.value);
3908
+ case "string": return ok(JSON.stringify(value.value));
3909
+ case "boolean": return ok(value.value ? "true" : "false");
3910
+ case "null": return ok("null");
3911
+ case "enum": return ok(JSON.stringify(value.value));
3912
+ case "list": {
3913
+ const values = [];
3914
+ for (const v of value.values) {
3915
+ const result = emitValue(v, variableNames);
3916
+ if (result.isErr()) {
3917
+ return err(result.error);
3918
+ }
3919
+ values.push(result.value);
3920
+ }
3921
+ return ok(`[${values.join(", ")}]`);
3922
+ }
3923
+ case "object": {
3924
+ if (value.fields.length === 0) {
3925
+ return ok("{}");
3926
+ }
3927
+ const entries = [];
3928
+ for (const f of value.fields) {
3929
+ const result = emitValue(f.value, variableNames);
3930
+ if (result.isErr()) {
3931
+ return err(result.error);
3932
+ }
3933
+ entries.push(`${f.name}: ${result.value}`);
3934
+ }
3935
+ return ok(`{ ${entries.join(", ")} }`);
3936
+ }
3937
+ }
3938
+ };
3939
+
3940
+ //#endregion
3941
+ //#region packages/tools/src/codegen/inject-template.ts
3942
+ const templateContents = `\
3943
+ import { defineScalar } from "@soda-gql/core";
3944
+
3945
+ export const scalar = {
3946
+ ...defineScalar<"ID", string, string>("ID"),
3947
+ ...defineScalar<"String", string, string>("String"),
3948
+ ...defineScalar<"Int", number, number>("Int"),
3949
+ ...defineScalar<"Float", number, number>("Float"),
3950
+ ...defineScalar<"Boolean", boolean, boolean>("Boolean"),
3951
+ } as const;
3952
+ `;
3953
+ const writeInjectTemplate = (outPath) => {
3954
+ const targetPath = resolve(outPath);
3955
+ try {
3956
+ if (existsSync(targetPath)) {
3957
+ return err({
3958
+ code: "INJECT_TEMPLATE_EXISTS",
3959
+ message: `Inject module already exists: ${targetPath}`,
3960
+ outPath: targetPath
3961
+ });
3962
+ }
3963
+ mkdirSync(dirname(targetPath), { recursive: true });
3964
+ writeFileSync(targetPath, `${templateContents}\n`);
3965
+ return ok(undefined);
3966
+ } catch (error) {
3967
+ const message = error instanceof Error ? error.message : String(error);
3968
+ return err({
3969
+ code: "INJECT_TEMPLATE_FAILED",
3970
+ message,
3971
+ outPath: targetPath
3972
+ });
3973
+ }
3974
+ };
3975
+ const getInjectTemplate = () => `${templateContents}\n`;
3976
+
3977
+ //#endregion
3978
+ //#region packages/tools/src/codegen/reachability.ts
3979
+ /**
3980
+ * Schema type reachability analysis.
3981
+ *
3982
+ * Determines which types are reachable from root types (Query/Mutation/Subscription)
3983
+ * to specified target types (e.g., fragment onType values from .graphql files).
3984
+ * Produces a CompiledFilter for use with existing buildExclusionSet.
3985
+ *
3986
+ * @module
3987
+ */
3988
+ const extractNamedType = (typeNode) => {
3989
+ switch (typeNode.kind) {
3990
+ case Kind.NAMED_TYPE: return typeNode.name.value;
3991
+ case Kind.LIST_TYPE: return extractNamedType(typeNode.type);
3992
+ case Kind.NON_NULL_TYPE: return extractNamedType(typeNode.type);
3993
+ }
3994
+ };
3995
+ const addEdge = (graph, from, to) => {
3996
+ let edges = graph.get(from);
3997
+ if (!edges) {
3998
+ edges = new Set();
3999
+ graph.set(from, edges);
4000
+ }
4001
+ edges.add(to);
4002
+ };
4003
+ const buildTypeGraph = (document) => {
4004
+ const schema = createSchemaIndex(document);
4005
+ const forward = new Map();
4006
+ const reverse = new Map();
4007
+ const addBidirectional = (from, to) => {
4008
+ addEdge(forward, from, to);
4009
+ addEdge(reverse, to, from);
4010
+ };
4011
+ for (const [typeName, record] of schema.objects) {
4012
+ for (const field of record.fields.values()) {
4013
+ const returnType = extractNamedType(field.type);
4014
+ addBidirectional(typeName, returnType);
4015
+ if (field.arguments) {
4016
+ for (const arg of field.arguments) {
4017
+ const argType = extractNamedType(arg.type);
4018
+ addBidirectional(typeName, argType);
4019
+ }
4020
+ }
4021
+ }
4022
+ }
4023
+ for (const [typeName, record] of schema.inputs) {
4024
+ for (const field of record.fields.values()) {
4025
+ const fieldType = extractNamedType(field.type);
4026
+ addBidirectional(typeName, fieldType);
4027
+ }
4028
+ }
4029
+ for (const [typeName, record] of schema.unions) {
4030
+ for (const memberName of record.members.keys()) {
4031
+ addBidirectional(typeName, memberName);
4032
+ }
4033
+ }
4034
+ return {
4035
+ graph: {
4036
+ forward,
4037
+ reverse
4038
+ },
4039
+ schema
4040
+ };
4041
+ };
4042
+ /**
4043
+ * BFS traversal collecting all reachable nodes from seeds.
4044
+ */
4045
+ const bfs = (adjacency, seeds, constraint) => {
4046
+ const visited = new Set();
4047
+ const queue = [];
4048
+ for (const seed of seeds) {
4049
+ if (!visited.has(seed)) {
4050
+ visited.add(seed);
4051
+ queue.push(seed);
4052
+ }
4053
+ }
4054
+ let head = 0;
4055
+ while (head < queue.length) {
4056
+ const current = queue[head++];
4057
+ if (current === undefined) break;
4058
+ const neighbors = adjacency.get(current);
4059
+ if (!neighbors) continue;
4060
+ for (const neighbor of neighbors) {
4061
+ if (visited.has(neighbor)) continue;
4062
+ if (constraint && !constraint.has(neighbor)) continue;
4063
+ visited.add(neighbor);
4064
+ queue.push(neighbor);
4065
+ }
4066
+ }
4067
+ return visited;
4068
+ };
4069
+ /**
4070
+ * Compute the set of type names reachable on paths from root types to target types.
4071
+ *
4072
+ * Algorithm:
4073
+ * 1. Backward BFS from target types to find all upstream types
4074
+ * 2. Forward BFS from root types, constrained to upstream set, to find actual paths
4075
+ * 3. Collect input/enum/scalar types used as field arguments on reachable object types
4076
+ */
4077
+ const computeReachableTypes = (graph, schema, targetTypes, usedArgumentTypes) => {
4078
+ const upstream = bfs(graph.reverse, targetTypes);
4079
+ const rootTypes = [];
4080
+ if (schema.operationTypes.query) rootTypes.push(schema.operationTypes.query);
4081
+ if (schema.operationTypes.mutation) rootTypes.push(schema.operationTypes.mutation);
4082
+ if (schema.operationTypes.subscription) rootTypes.push(schema.operationTypes.subscription);
4083
+ const validRoots = rootTypes.filter((r) => upstream.has(r));
4084
+ const pathTypes = bfs(graph.forward, validRoots, upstream);
4085
+ const reachable = new Set(pathTypes);
4086
+ const inputQueue = [];
4087
+ for (const typeName of pathTypes) {
4088
+ const objectRecord = schema.objects.get(typeName);
4089
+ if (!objectRecord) continue;
4090
+ for (const field of objectRecord.fields.values()) {
4091
+ const returnType = extractNamedType(field.type);
4092
+ if (!reachable.has(returnType)) {
4093
+ const isKnownComposite = schema.objects.has(returnType) || schema.inputs.has(returnType) || schema.unions.has(returnType);
4094
+ if (!isKnownComposite) {
4095
+ reachable.add(returnType);
4096
+ }
4097
+ }
4098
+ if (!usedArgumentTypes && field.arguments) {
4099
+ for (const arg of field.arguments) {
4100
+ const argType = extractNamedType(arg.type);
4101
+ if (!reachable.has(argType)) {
4102
+ reachable.add(argType);
4103
+ if (schema.inputs.has(argType)) {
4104
+ inputQueue.push(argType);
4105
+ }
4106
+ }
4107
+ }
4108
+ }
4109
+ }
4110
+ }
4111
+ if (usedArgumentTypes) {
4112
+ for (const inputName of usedArgumentTypes) {
4113
+ if (!reachable.has(inputName)) {
4114
+ reachable.add(inputName);
4115
+ inputQueue.push(inputName);
4116
+ }
4117
+ }
4118
+ }
4119
+ let inputHead = 0;
4120
+ while (inputHead < inputQueue.length) {
4121
+ const inputName = inputQueue[inputHead++];
4122
+ if (inputName === undefined) break;
4123
+ const inputRecord = schema.inputs.get(inputName);
4124
+ if (!inputRecord) continue;
4125
+ for (const field of inputRecord.fields.values()) {
4126
+ const fieldType = extractNamedType(field.type);
4127
+ if (!reachable.has(fieldType)) {
4128
+ reachable.add(fieldType);
4129
+ if (schema.inputs.has(fieldType)) {
4130
+ inputQueue.push(fieldType);
4131
+ }
4132
+ }
4133
+ }
4134
+ }
4135
+ return reachable;
4136
+ };
4137
+ /**
4138
+ * Compute a filter function that includes only types reachable from root types
4139
+ * to the specified target types.
4140
+ *
4141
+ * When targetTypes is empty, returns a pass-all filter (no filtering).
4142
+ * Warns when target types are not found in the schema.
4143
+ *
4144
+ * @param document - The parsed GraphQL schema document
4145
+ * @param targetTypes - Set of type names that fragments target (e.g., from ParsedFragment.onType)
4146
+ * @returns Filter function and any warnings
4147
+ */
4148
+ const computeReachabilityFilter = (document, targetTypes, usedArgumentTypes) => {
4149
+ if (targetTypes.size === 0) {
4150
+ return {
4151
+ filter: () => true,
4152
+ warnings: []
4153
+ };
4154
+ }
4155
+ const { graph, schema } = buildTypeGraph(document);
4156
+ const allTypeNames = new Set([
4157
+ ...schema.objects.keys(),
4158
+ ...schema.inputs.keys(),
4159
+ ...schema.enums.keys(),
4160
+ ...schema.unions.keys(),
4161
+ ...schema.scalars.keys()
4162
+ ]);
4163
+ const warnings = [];
4164
+ const validTargets = new Set();
4165
+ for (const target of targetTypes) {
4166
+ if (allTypeNames.has(target)) {
4167
+ validTargets.add(target);
4168
+ } else {
4169
+ warnings.push(`Target type "${target}" not found in schema`);
4170
+ }
4171
+ }
4172
+ if (validTargets.size === 0) {
4173
+ return {
4174
+ filter: () => true,
4175
+ warnings
4176
+ };
4177
+ }
4178
+ const reachable = computeReachableTypes(graph, schema, validTargets, usedArgumentTypes);
4179
+ if (reachable.size === 0) {
4180
+ warnings.push(`No types reachable from root operations to target types: ${[...validTargets].join(", ")}; skipping reachability filter`);
4181
+ return {
4182
+ filter: () => true,
4183
+ warnings
4184
+ };
4185
+ }
4186
+ return {
4187
+ filter: (context) => reachable.has(context.name),
4188
+ warnings
4189
+ };
4190
+ };
4191
+
4192
+ //#endregion
4193
+ //#region packages/tools/src/codegen/bundler/esbuild.ts
4194
+ const esbuildBundler = {
4195
+ name: "esbuild",
4196
+ bundle: async ({ sourcePath, external }) => {
4197
+ try {
4198
+ const sourceExt = extname(sourcePath);
4199
+ const baseName = sourcePath.slice(0, -sourceExt.length);
4200
+ const cjsPath = `${baseName}.cjs`;
4201
+ await build({
4202
+ entryPoints: [sourcePath],
4203
+ outfile: cjsPath,
4204
+ format: "cjs",
4205
+ platform: "node",
4206
+ bundle: true,
4207
+ external: [...external],
4208
+ sourcemap: false,
4209
+ minify: false,
4210
+ treeShaking: false
4211
+ });
4212
+ return ok({ cjsPath });
4213
+ } catch (error) {
4214
+ return err({
4215
+ code: "EMIT_FAILED",
4216
+ message: `[esbuild] Failed to bundle: ${error instanceof Error ? error.message : String(error)}`,
4217
+ outPath: sourcePath
4218
+ });
4219
+ }
4220
+ }
4221
+ };
4222
+
4223
+ //#endregion
4224
+ //#region packages/tools/src/codegen/defs-generator.ts
4225
+ /**
4226
+ * Split an array into chunks of the specified size.
4227
+ */
4228
+ const chunkArray = (array, size) => {
4229
+ if (size <= 0) {
4230
+ return [Array.from(array)];
4231
+ }
4232
+ const result = [];
4233
+ for (let i = 0; i < array.length; i += size) {
4234
+ result.push(array.slice(i, i + size));
4235
+ }
4236
+ return result;
4237
+ };
4238
+ /**
4239
+ * Determine if chunking is needed based on the number of definitions.
4240
+ */
4241
+ const needsChunking = (vars, chunkSize) => {
4242
+ return vars.length > chunkSize;
4243
+ };
4244
+ /**
4245
+ * Generate a single definition file content.
4246
+ */
4247
+ const generateDefinitionFile = (options) => {
4248
+ const { category, vars, needsDefineEnum } = options;
4249
+ if (vars.length === 0) {
4250
+ return `/**
4251
+ * ${category} definitions (empty)
4252
+ * @generated by @soda-gql/tools/codegen
4253
+ */
4254
+ `;
4255
+ }
4256
+ const imports = [];
4257
+ if (needsDefineEnum && category === "enums") {
4258
+ imports.push("import { defineEnum } from \"@soda-gql/core\";");
4259
+ }
4260
+ const importsBlock = imports.length > 0 ? `${imports.join("\n")}\n\n` : "";
4261
+ const exportStatements = vars.map((v) => `export ${v.code}`).join("\n");
4262
+ return `/**
4263
+ * ${category} definitions
4264
+ * @generated by @soda-gql/tools/codegen
4265
+ */
4266
+ ${importsBlock}${exportStatements}
4267
+ `;
4268
+ };
4269
+ /**
4270
+ * Generate a chunk file content.
4271
+ */
4272
+ const generateChunkFile = (options) => {
4273
+ const { category, vars, chunkIndex, needsDefineEnum } = options;
4274
+ if (vars.length === 0) {
4275
+ return `/**
4276
+ * ${category} chunk ${chunkIndex} (empty)
4277
+ * @generated by @soda-gql/tools/codegen
4278
+ */
4279
+ `;
4280
+ }
4281
+ const imports = [];
4282
+ if (needsDefineEnum && category === "enums") {
4283
+ imports.push("import { defineEnum } from \"@soda-gql/core\";");
4284
+ }
4285
+ const importsBlock = imports.length > 0 ? `${imports.join("\n")}\n\n` : "";
4286
+ const exportStatements = vars.map((v) => `export ${v.code}`).join("\n");
4287
+ return `/**
4288
+ * ${category} chunk ${chunkIndex}
4289
+ * @generated by @soda-gql/tools/codegen
4290
+ */
4291
+ ${importsBlock}${exportStatements}
4292
+ `;
4293
+ };
4294
+ /**
4295
+ * Generate the index file that re-exports all chunks.
4296
+ */
4297
+ const generateChunkIndex = (options) => {
4298
+ const { category, chunkCount } = options;
4299
+ const reExports = Array.from({ length: chunkCount }, (_, i) => `export * from "./chunk-${i}";`).join("\n");
4300
+ return `/**
4301
+ * ${category} index (re-exports all chunks)
4302
+ * @generated by @soda-gql/tools/codegen
4303
+ */
4304
+ ${reExports}
4305
+ `;
4306
+ };
4307
+ /**
4308
+ * Generate chunked definition files.
4309
+ */
4310
+ const generateChunkedDefinitionFiles = (category, schemaName, vars, chunkSize) => {
4311
+ const chunks = chunkArray(vars, chunkSize);
4312
+ const needsDefineEnum = category === "enums";
4313
+ const chunkContents = chunks.map((chunkVars, chunkIndex) => ({
4314
+ chunkIndex,
4315
+ content: generateChunkFile({
4316
+ category,
4317
+ schemaName,
4318
+ vars: chunkVars,
4319
+ chunkIndex,
4320
+ needsDefineEnum
4321
+ }),
4322
+ varNames: chunkVars.map((v) => v.name)
4323
+ }));
4324
+ const allVarNames = vars.map((v) => v.name);
4325
+ const indexContent = generateChunkIndex({
4326
+ category,
4327
+ chunkCount: chunks.length,
4328
+ varNames: allVarNames
4329
+ });
4330
+ return {
4331
+ indexContent,
4332
+ chunks: chunkContents
4333
+ };
4334
+ };
4335
+ /**
4336
+ * Generate the complete _defs directory structure.
4337
+ */
4338
+ const generateDefsStructure = (schemaName, categoryVars, chunkSize) => {
4339
+ const files = [];
4340
+ const importPaths = {
4341
+ enums: "./_defs/enums",
4342
+ inputs: "./_defs/inputs",
4343
+ objects: "./_defs/objects",
4344
+ unions: "./_defs/unions"
4345
+ };
4346
+ const categories = [
4347
+ "enums",
4348
+ "inputs",
4349
+ "objects",
4350
+ "unions"
4351
+ ];
4352
+ for (const category of categories) {
4353
+ const vars = categoryVars[category];
4354
+ const needsDefineEnum = category === "enums";
4355
+ if (needsChunking(vars, chunkSize)) {
4356
+ const chunked = generateChunkedDefinitionFiles(category, schemaName, vars, chunkSize);
4357
+ importPaths[category] = `./_defs/${category}`;
4358
+ files.push({
4359
+ relativePath: `_defs/${category}/index.ts`,
4360
+ content: chunked.indexContent
4361
+ });
4362
+ for (const chunk of chunked.chunks) {
4363
+ files.push({
4364
+ relativePath: `_defs/${category}/chunk-${chunk.chunkIndex}.ts`,
4365
+ content: chunk.content
4366
+ });
4367
+ }
4368
+ } else {
4369
+ const content = generateDefinitionFile({
4370
+ category,
4371
+ schemaName,
4372
+ vars,
4373
+ needsDefineEnum
4374
+ });
4375
+ files.push({
4376
+ relativePath: `_defs/${category}.ts`,
4377
+ content
4378
+ });
4379
+ }
4380
+ }
4381
+ return {
4382
+ files,
4383
+ importPaths
4384
+ };
4385
+ };
4386
+
4387
+ //#endregion
4388
+ //#region packages/tools/src/codegen/file.ts
4389
+ const removeDirectory = (dirPath) => {
4390
+ const targetPath = resolve(dirPath);
4391
+ try {
4392
+ rmSync(targetPath, {
4393
+ recursive: true,
4394
+ force: true
4395
+ });
4396
+ return ok(undefined);
4397
+ } catch (error) {
4398
+ const message = error instanceof Error ? error.message : String(error);
4399
+ return err({
4400
+ code: "REMOVE_FAILED",
4401
+ message,
4402
+ outPath: targetPath
4403
+ });
4404
+ }
4405
+ };
4406
+ const readModule = (filePath) => {
4407
+ const targetPath = resolve(filePath);
4408
+ try {
4409
+ const content = readFileSync(targetPath, "utf-8");
4410
+ return ok(content);
4411
+ } catch (error) {
4412
+ const message = error instanceof Error ? error.message : String(error);
4413
+ return err({
4414
+ code: "READ_FAILED",
4415
+ message,
4416
+ outPath: targetPath
4417
+ });
4418
+ }
4419
+ };
4420
+ const writeModule = (outPath, contents) => {
4421
+ const targetPath = resolve(outPath);
4422
+ try {
4423
+ mkdirSync(dirname(targetPath), { recursive: true });
4424
+ writeFileSync(targetPath, contents);
4425
+ return ok(undefined);
4426
+ } catch (error) {
4427
+ const message = error instanceof Error ? error.message : String(error);
4428
+ return err({
4429
+ code: "EMIT_FAILED",
4430
+ message,
4431
+ outPath: targetPath
4432
+ });
4433
+ }
4434
+ };
4435
+
4436
+ //#endregion
4437
+ //#region packages/tools/src/codegen/schema.ts
4438
+ /**
4439
+ * Load a single schema file.
4440
+ * @internal Use loadSchema for public API.
4441
+ */
4442
+ const loadSingleSchema = (schemaPath) => {
4443
+ const resolvedPath = resolve(schemaPath);
4444
+ if (!existsSync(resolvedPath)) {
4445
+ return err({
4446
+ code: "SCHEMA_NOT_FOUND",
4447
+ message: `Schema file not found at ${resolvedPath}`,
4448
+ schemaPath: resolvedPath
4449
+ });
4450
+ }
4451
+ try {
4452
+ const schemaSource = readFileSync(resolvedPath, "utf8");
4453
+ const document = parse(schemaSource);
4454
+ return ok(document);
4455
+ } catch (error) {
4456
+ const message = error instanceof Error ? error.message : String(error);
4457
+ return err({
4458
+ code: "SCHEMA_INVALID",
4459
+ message: `SchemaValidationError: ${message}`,
4460
+ schemaPath: resolvedPath
4461
+ });
4462
+ }
4463
+ };
4464
+ /**
4465
+ * Load and merge multiple schema files into a single DocumentNode.
4466
+ * Uses GraphQL's concatAST to combine definitions from all files.
4467
+ */
4468
+ const loadSchema = (schemaPaths) => {
4469
+ const documents = [];
4470
+ for (const schemaPath of schemaPaths) {
4471
+ const result = loadSingleSchema(schemaPath);
4472
+ if (result.isErr()) {
4473
+ return err(result.error);
4474
+ }
4475
+ documents.push(result.value);
4476
+ }
4477
+ const merged = concatAST(documents);
4478
+ return ok(merged);
4479
+ };
4480
+ const hashSchema = (document) => createHash("sha256").update(print(document)).digest("hex");
4481
+
4482
+ //#endregion
4483
+ //#region packages/tools/src/codegen/runner.ts
4484
+ const extensionMap = {
4485
+ ".ts": ".js",
4486
+ ".tsx": ".js",
4487
+ ".mts": ".mjs",
4488
+ ".cts": ".cjs",
4489
+ ".js": ".js",
4490
+ ".mjs": ".mjs",
4491
+ ".cjs": ".cjs"
4492
+ };
4493
+ const toImportSpecifier = (fromPath, targetPath, options) => {
4494
+ const fromDir = dirname(fromPath);
4495
+ const normalized = relative(fromDir, targetPath).replace(/\\/g, "/");
4496
+ const sourceExt = extname(targetPath);
4497
+ if (!options?.includeExtension) {
4498
+ if (normalized.length === 0) {
4499
+ return `./${basename(targetPath, sourceExt)}`;
4500
+ }
4501
+ const withPrefix$1 = normalized.startsWith(".") ? normalized : `./${normalized}`;
4502
+ const currentExt$1 = extname(withPrefix$1);
4503
+ return currentExt$1 ? withPrefix$1.slice(0, -currentExt$1.length) : withPrefix$1;
4504
+ }
4505
+ const runtimeExt = extensionMap[sourceExt] ?? sourceExt;
4506
+ if (normalized.length === 0) {
4507
+ const base = runtimeExt !== sourceExt ? basename(targetPath, sourceExt) : basename(targetPath);
4508
+ return `./${base}${runtimeExt}`;
4509
+ }
4510
+ const withPrefix = normalized.startsWith(".") ? normalized : `./${normalized}`;
4511
+ if (!runtimeExt) {
4512
+ return withPrefix;
4513
+ }
4514
+ if (withPrefix.endsWith(runtimeExt)) {
4515
+ return withPrefix;
4516
+ }
4517
+ const currentExt = extname(withPrefix);
4518
+ const withoutExt = currentExt ? withPrefix.slice(0, -currentExt.length) : withPrefix;
4519
+ return `${withoutExt}${runtimeExt}`;
4520
+ };
4521
+ const runCodegen = async (options) => {
4522
+ const outPath = resolve(options.outPath);
4523
+ const importSpecifierOptions = { includeExtension: options.importExtension };
4524
+ for (const [schemaName, schemaConfig] of Object.entries(options.schemas)) {
4525
+ const scalarPath = resolve(schemaConfig.inject.scalars);
4526
+ if (!existsSync(scalarPath)) {
4527
+ return err({
4528
+ code: "INJECT_MODULE_NOT_FOUND",
4529
+ message: `Scalar module not found for schema '${schemaName}': ${scalarPath}`,
4530
+ injectPath: scalarPath
4531
+ });
4532
+ }
4533
+ if (schemaConfig.inject.adapter) {
4534
+ const adapterPath = resolve(schemaConfig.inject.adapter);
4535
+ if (!existsSync(adapterPath)) {
4536
+ return err({
4537
+ code: "INJECT_MODULE_NOT_FOUND",
4538
+ message: `Adapter module not found for schema '${schemaName}': ${adapterPath}`,
4539
+ injectPath: adapterPath
4540
+ });
4541
+ }
4542
+ }
4543
+ }
4544
+ const schemas = new Map();
4545
+ const schemaHashes = {};
4546
+ for (const [name, schemaConfig] of Object.entries(options.schemas)) {
4547
+ const preloaded = options.preloadedSchemas?.get(name);
4548
+ if (preloaded) {
4549
+ schemas.set(name, preloaded);
4550
+ } else {
4551
+ const result = await loadSchema(schemaConfig.schema).match((doc) => Promise.resolve(ok(doc)), (error) => Promise.resolve(err(error)));
4552
+ if (result.isErr()) {
4553
+ return err(result.error);
4554
+ }
4555
+ schemas.set(name, result.value);
4556
+ }
4557
+ }
4558
+ const injectionConfig = new Map();
4559
+ for (const [schemaName, schemaConfig] of Object.entries(options.schemas)) {
4560
+ const injectConfig = schemaConfig.inject;
4561
+ injectionConfig.set(schemaName, {
4562
+ scalarImportPath: toImportSpecifier(outPath, resolve(injectConfig.scalars), importSpecifierOptions),
4563
+ ...injectConfig.adapter ? { adapterImportPath: toImportSpecifier(outPath, resolve(injectConfig.adapter), importSpecifierOptions) } : {}
4564
+ });
4565
+ }
4566
+ const defaultInputDepthConfig = new Map();
4567
+ const inputDepthOverridesConfig = new Map();
4568
+ for (const [schemaName, schemaConfig] of Object.entries(options.schemas)) {
4569
+ if (schemaConfig.defaultInputDepth !== undefined && schemaConfig.defaultInputDepth !== 3) {
4570
+ defaultInputDepthConfig.set(schemaName, schemaConfig.defaultInputDepth);
4571
+ }
4572
+ if (schemaConfig.inputDepthOverrides && Object.keys(schemaConfig.inputDepthOverrides).length > 0) {
4573
+ inputDepthOverridesConfig.set(schemaName, schemaConfig.inputDepthOverrides);
4574
+ }
4575
+ }
4576
+ const chunkSize = options.chunkSize ?? 100;
4577
+ const typeFiltersConfig = new Map();
4578
+ for (const [schemaName, schemaConfig] of Object.entries(options.schemas)) {
4579
+ if (schemaConfig.typeFilter) {
4580
+ typeFiltersConfig.set(schemaName, schemaConfig.typeFilter);
4581
+ }
4582
+ }
4583
+ const { code: internalCode, injectsCode, categoryVars } = generateMultiSchemaModule(schemas, {
4584
+ injection: injectionConfig,
4585
+ defaultInputDepth: defaultInputDepthConfig.size > 0 ? defaultInputDepthConfig : undefined,
4586
+ inputDepthOverrides: inputDepthOverridesConfig.size > 0 ? inputDepthOverridesConfig : undefined,
4587
+ chunkSize,
4588
+ typeFilters: typeFiltersConfig.size > 0 ? typeFiltersConfig : undefined
4589
+ });
4590
+ const schemaNames = Object.keys(options.schemas);
4591
+ const allFieldNames = new Map();
4592
+ for (const [name, document] of schemas.entries()) {
4593
+ const schemaIndex = createSchemaIndex(document);
4594
+ const fieldNameSet = new Set();
4595
+ for (const [objectName, record] of schemaIndex.objects.entries()) {
4596
+ if (objectName.startsWith("__")) continue;
4597
+ for (const fieldName of record.fields.keys()) {
4598
+ fieldNameSet.add(fieldName);
4599
+ }
4600
+ }
4601
+ allFieldNames.set(name, Array.from(fieldNameSet).sort());
4602
+ const objects = Array.from(schemaIndex.objects.keys()).filter((n) => !n.startsWith("__")).length;
4603
+ const enums = Array.from(schemaIndex.enums.keys()).filter((n) => !n.startsWith("__")).length;
4604
+ const inputs = Array.from(schemaIndex.inputs.keys()).filter((n) => !n.startsWith("__")).length;
4605
+ const unions = Array.from(schemaIndex.unions.keys()).filter((n) => !n.startsWith("__")).length;
4606
+ schemaHashes[name] = {
4607
+ schemaHash: hashSchema(document),
4608
+ objects,
4609
+ enums,
4610
+ inputs,
4611
+ unions
4612
+ };
4613
+ }
4614
+ const indexCode = generateIndexModule(schemaNames, allFieldNames);
4615
+ const injectsPath = join(dirname(outPath), "_internal-injects.ts");
4616
+ if (injectsCode) {
4617
+ const injectsWriteResult = await writeModule(injectsPath, injectsCode).match(() => Promise.resolve(ok(undefined)), (error) => Promise.resolve(err(error)));
4618
+ if (injectsWriteResult.isErr()) {
4619
+ return err(injectsWriteResult.error);
4620
+ }
4621
+ }
4622
+ const defsPaths = [];
4623
+ if (categoryVars) {
4624
+ const outDir = dirname(outPath);
4625
+ const defsDir = join(outDir, "_defs");
4626
+ if (existsSync(defsDir)) {
4627
+ const removeResult = removeDirectory(defsDir);
4628
+ if (removeResult.isErr()) {
4629
+ return err(removeResult.error);
4630
+ }
4631
+ }
4632
+ const combinedVars = {
4633
+ enums: [],
4634
+ inputs: [],
4635
+ objects: [],
4636
+ unions: []
4637
+ };
4638
+ for (const vars of Object.values(categoryVars)) {
4639
+ combinedVars.enums.push(...vars.enums);
4640
+ combinedVars.inputs.push(...vars.inputs);
4641
+ combinedVars.objects.push(...vars.objects);
4642
+ combinedVars.unions.push(...vars.unions);
4643
+ }
4644
+ const defsStructure = generateDefsStructure("combined", combinedVars, chunkSize);
4645
+ for (const file of defsStructure.files) {
4646
+ const filePath = join(outDir, file.relativePath);
4647
+ const writeResult = await writeModule(filePath, file.content).match(() => Promise.resolve(ok(undefined)), (error) => Promise.resolve(err(error)));
4648
+ if (writeResult.isErr()) {
4649
+ return err(writeResult.error);
4650
+ }
4651
+ defsPaths.push(filePath);
4652
+ }
4653
+ }
4654
+ const internalPath = join(dirname(outPath), "_internal.ts");
4655
+ const internalWriteResult = await writeModule(internalPath, internalCode).match(() => Promise.resolve(ok(undefined)), (error) => Promise.resolve(err(error)));
4656
+ if (internalWriteResult.isErr()) {
4657
+ return err(internalWriteResult.error);
4658
+ }
4659
+ const indexWriteResult = await writeModule(outPath, indexCode).match(() => Promise.resolve(ok(undefined)), (error) => Promise.resolve(err(error)));
4660
+ if (indexWriteResult.isErr()) {
4661
+ return err(indexWriteResult.error);
4662
+ }
4663
+ const prebuiltStubPath = join(dirname(outPath), "types.prebuilt.ts");
4664
+ if (!existsSync(prebuiltStubPath)) {
4665
+ const prebuiltStubCode = generatePrebuiltStub(schemaNames);
4666
+ const prebuiltWriteResult = await writeModule(prebuiltStubPath, prebuiltStubCode).match(() => Promise.resolve(ok(undefined)), (error) => Promise.resolve(err(error)));
4667
+ if (prebuiltWriteResult.isErr()) {
4668
+ return err(prebuiltWriteResult.error);
4669
+ }
4670
+ } else {
4671
+ const readResult = readModule(prebuiltStubPath);
4672
+ if (readResult.isErr()) {
4673
+ return err(readResult.error);
4674
+ }
4675
+ const existingContent = readResult.value;
4676
+ const existingNames = new Set();
4677
+ for (const match of existingContent.matchAll(/export type PrebuiltTypes_(\w+)/g)) {
4678
+ const name = match[1];
4679
+ if (name) existingNames.add(name);
4680
+ }
4681
+ const missingNames = schemaNames.filter((name) => !existingNames.has(name));
4682
+ if (missingNames.length > 0) {
4683
+ const missingStubs = generatePrebuiltStub(missingNames);
4684
+ const stubDeclarations = missingStubs.replace(/^\/\*\*[\s\S]*?\*\/\n\n/, "");
4685
+ const updatedContent = `${existingContent.trimEnd()}\n\n${stubDeclarations}`;
4686
+ const patchResult = writeModule(prebuiltStubPath, updatedContent);
4687
+ if (patchResult.isErr()) {
4688
+ return err(patchResult.error);
4689
+ }
4690
+ }
4691
+ }
4692
+ const bundleOutcome = await esbuildBundler.bundle({
4693
+ sourcePath: outPath,
4694
+ external: ["@soda-gql/core", "@soda-gql/core/runtime"]
4695
+ });
4696
+ const bundleResult = bundleOutcome.match((result) => ok(result), (error) => err(error));
4697
+ if (bundleResult.isErr()) {
4698
+ return err(bundleResult.error);
4699
+ }
4700
+ return ok({
4701
+ schemas: schemaHashes,
4702
+ outPath,
4703
+ internalPath,
4704
+ injectsPath,
4705
+ cjsPath: bundleResult.value.cjsPath,
4706
+ ...defsPaths.length > 0 ? { defsPaths } : {}
4707
+ });
4708
+ };
4709
+
4710
+ //#endregion
4711
+ export { collectVariableUsages, compileTypeFilter, computeReachabilityFilter, emitFragment, emitOperation, getArgumentType, getFieldReturnType, getInputFieldType, hashSchema, inferVariablesFromUsages, isModifierAssignable, loadSchema, mergeModifiers, mergeVariableUsages, parseGraphqlFile, parseGraphqlSource, parseTypeNode, runCodegen, sortFragmentsByDependency, transformParsedGraphql, writeInjectTemplate };
4712
+ //# sourceMappingURL=codegen.mjs.map