@soda-gql/babel-transformer 0.2.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1382 @@
1
+ import { formatPluginError, resolveCanonicalId } from "@soda-gql/plugin-common";
2
+ import { err, ok } from "neverthrow";
3
+ import * as t from "@babel/types";
4
+ import { types } from "@babel/core";
5
+ import { createCanonicalTracker } from "@soda-gql/common";
6
+ import _generate from "@babel/generator";
7
+ import { parse } from "@babel/parser";
8
+ import _traverse from "@babel/traverse";
9
+ import { createGraphqlSystemIdentifyHelper } from "@soda-gql/builder";
10
+
11
+ //#region packages/babel-transformer/src/ast/analysis.ts
12
+ const extractGqlCall = ({ nodePath, filename, metadata, getArtifact }) => {
13
+ const callExpression = nodePath.node;
14
+ const meta = metadata.get(callExpression);
15
+ if (!meta) return err(createMetadataMissingError({ filename }));
16
+ const canonicalId = resolveCanonicalId(filename, meta.astPath);
17
+ const artifact = getArtifact(canonicalId);
18
+ if (!artifact) return err(createArtifactMissingError({
19
+ filename,
20
+ canonicalId
21
+ }));
22
+ if (artifact.type === "fragment") return ok({
23
+ nodePath,
24
+ canonicalId,
25
+ type: "fragment",
26
+ artifact
27
+ });
28
+ if (artifact.type === "operation") return ok({
29
+ nodePath,
30
+ canonicalId,
31
+ type: "operation",
32
+ artifact
33
+ });
34
+ return err(createUnsupportedArtifactTypeError({
35
+ filename,
36
+ canonicalId,
37
+ artifactType: artifact.type
38
+ }));
39
+ };
40
+ const createMetadataMissingError = ({ filename }) => ({
41
+ type: "PluginError",
42
+ stage: "analysis",
43
+ code: "SODA_GQL_METADATA_NOT_FOUND",
44
+ message: `No GraphQL metadata found for ${filename}`,
45
+ cause: { filename },
46
+ filename
47
+ });
48
+ const createArtifactMissingError = ({ filename, canonicalId }) => ({
49
+ type: "PluginError",
50
+ stage: "analysis",
51
+ code: "SODA_GQL_ANALYSIS_ARTIFACT_NOT_FOUND",
52
+ message: `No builder artifact found for canonical ID ${canonicalId}`,
53
+ cause: {
54
+ filename,
55
+ canonicalId
56
+ },
57
+ filename,
58
+ canonicalId
59
+ });
60
+ const createUnsupportedArtifactTypeError = ({ filename, canonicalId, artifactType }) => ({
61
+ type: "PluginError",
62
+ stage: "analysis",
63
+ code: "SODA_GQL_UNSUPPORTED_ARTIFACT_TYPE",
64
+ message: `Unsupported builder artifact type "${artifactType}" for canonical ID ${canonicalId}`,
65
+ cause: {
66
+ filename,
67
+ canonicalId,
68
+ artifactType
69
+ },
70
+ filename,
71
+ canonicalId,
72
+ artifactType
73
+ });
74
+
75
+ //#endregion
76
+ //#region packages/babel-transformer/src/ast/ast.ts
77
+ const createUnsupportedValueTypeError = (valueType) => ({
78
+ type: "PluginError",
79
+ stage: "transform",
80
+ code: "SODA_GQL_TRANSFORM_UNSUPPORTED_VALUE_TYPE",
81
+ message: `Unsupported value type: ${valueType}`,
82
+ cause: { valueType },
83
+ valueType
84
+ });
85
+ const buildLiteralFromValue = (value) => {
86
+ if (value === null) return ok(t.nullLiteral());
87
+ if (typeof value === "string") return ok(t.stringLiteral(value));
88
+ if (typeof value === "number") return ok(t.numericLiteral(value));
89
+ if (typeof value === "boolean") return ok(t.booleanLiteral(value));
90
+ if (Array.isArray(value)) {
91
+ const elements = [];
92
+ for (const item of value) {
93
+ const result = buildLiteralFromValue(item);
94
+ if (result.isErr()) return result;
95
+ elements.push(result.value);
96
+ }
97
+ return ok(t.arrayExpression(elements));
98
+ }
99
+ if (typeof value === "object") {
100
+ const properties = [];
101
+ for (const [key, val] of Object.entries(value)) {
102
+ const result = buildLiteralFromValue(val);
103
+ if (result.isErr()) return result;
104
+ properties.push(t.objectProperty(t.identifier(key), result.value));
105
+ }
106
+ return ok(t.objectExpression(properties));
107
+ }
108
+ return err(createUnsupportedValueTypeError(typeof value));
109
+ };
110
+ const clone = (node) => t.cloneNode(node, true);
111
+ const cloneCallExpression = (node) => t.callExpression(clone(node.callee), node.arguments.map(clone));
112
+ const stripTypeAnnotations = (node) => {
113
+ if ("typeParameters" in node) delete node.typeParameters;
114
+ if ("typeAnnotation" in node) delete node.typeAnnotation;
115
+ if ("returnType" in node) delete node.returnType;
116
+ };
117
+ const buildObjectExpression = (properties) => t.objectExpression(Object.entries(properties).map(([key, value]) => t.objectProperty(t.identifier(key), value)));
118
+
119
+ //#endregion
120
+ //#region packages/babel-transformer/src/ast/imports.ts
121
+ const RUNTIME_MODULE = "@soda-gql/runtime";
122
+ /**
123
+ * Ensure that the gqlRuntime require exists in the program for CJS output.
124
+ * Injects: const __soda_gql_runtime = require("@soda-gql/runtime");
125
+ */
126
+ const ensureGqlRuntimeRequire = (programPath) => {
127
+ if (programPath.node.body.find((statement) => types.isVariableDeclaration(statement) && statement.declarations.some((decl) => {
128
+ if (!types.isIdentifier(decl.id) || decl.id.name !== "__soda_gql_runtime") return false;
129
+ if (!decl.init || !types.isCallExpression(decl.init)) return false;
130
+ const callExpr = decl.init;
131
+ if (!types.isIdentifier(callExpr.callee) || callExpr.callee.name !== "require") return false;
132
+ const arg = callExpr.arguments[0];
133
+ return arg && types.isStringLiteral(arg) && arg.value === RUNTIME_MODULE;
134
+ }))) return;
135
+ const requireCall = types.callExpression(types.identifier("require"), [types.stringLiteral(RUNTIME_MODULE)]);
136
+ const variableDeclaration = types.variableDeclaration("const", [types.variableDeclarator(types.identifier("__soda_gql_runtime"), requireCall)]);
137
+ programPath.node.body.unshift(variableDeclaration);
138
+ };
139
+ /**
140
+ * Ensure that the gqlRuntime import exists in the program.
141
+ * gqlRuntime is always imported from @soda-gql/runtime.
142
+ */
143
+ const ensureGqlRuntimeImport = (programPath) => {
144
+ const existing = programPath.node.body.find((statement) => statement.type === "ImportDeclaration" && statement.source.value === RUNTIME_MODULE);
145
+ if (existing && types.isImportDeclaration(existing)) {
146
+ if (!existing.specifiers.some((specifier) => specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "gqlRuntime")) existing.specifiers = [...existing.specifiers, types.importSpecifier(types.identifier("gqlRuntime"), types.identifier("gqlRuntime"))];
147
+ return;
148
+ }
149
+ programPath.node.body.unshift(types.importDeclaration([types.importSpecifier(types.identifier("gqlRuntime"), types.identifier("gqlRuntime"))], types.stringLiteral(RUNTIME_MODULE)));
150
+ };
151
+ /**
152
+ * Remove the graphql-system import (runtimeModule) and gql-related exports from the program.
153
+ * After transformation, gqlRuntime is imported from @soda-gql/runtime instead,
154
+ * so the original graphql-system import should be completely removed.
155
+ *
156
+ * This handles both ESM imports and CommonJS require() statements.
157
+ */
158
+ const removeGraphqlSystemImports = (programPath, graphqlSystemIdentifyHelper, filename) => {
159
+ const toRemove = [];
160
+ programPath.traverse({
161
+ ImportDeclaration(path) {
162
+ if (types.isStringLiteral(path.node.source)) {
163
+ if (graphqlSystemIdentifyHelper.isGraphqlSystemImportSpecifier({
164
+ filePath: filename,
165
+ specifier: path.node.source.value
166
+ })) toRemove.push(path);
167
+ }
168
+ },
169
+ VariableDeclaration(path) {
170
+ if (path.node.declarations.every((decl) => {
171
+ const specifier = extractRequireTargetSpecifier(decl.init);
172
+ if (!specifier) return false;
173
+ return graphqlSystemIdentifyHelper.isGraphqlSystemImportSpecifier({
174
+ filePath: filename,
175
+ specifier
176
+ });
177
+ })) toRemove.push(path);
178
+ }
179
+ });
180
+ for (const path of toRemove) path.remove();
181
+ };
182
+ /**
183
+ * Check if an expression is a require() call and extract its target specifier.
184
+ * Handles multiple patterns:
185
+ * - require("@/graphql-system")
186
+ * - Object(require("@/graphql-system")) (interop helper pattern)
187
+ */
188
+ const extractRequireTargetSpecifier = (expr) => {
189
+ if (!expr) return;
190
+ if (types.isCallExpression(expr)) {
191
+ if (types.isIdentifier(expr.callee) && expr.callee.name === "require") {
192
+ const arg = expr.arguments[0];
193
+ if (arg && types.isStringLiteral(arg)) return arg.value;
194
+ }
195
+ if (types.isIdentifier(expr.callee) && (expr.callee.name === "Object" || expr.callee.name.startsWith("__import"))) {
196
+ const arg = expr.arguments[0];
197
+ if (arg && types.isCallExpression(arg)) {
198
+ if (types.isIdentifier(arg.callee) && arg.callee.name === "require") {
199
+ const requireArg = arg.arguments[0];
200
+ if (requireArg && types.isStringLiteral(requireArg)) return requireArg.value;
201
+ }
202
+ }
203
+ }
204
+ }
205
+ };
206
+
207
+ //#endregion
208
+ //#region packages/babel-transformer/src/ast/metadata.ts
209
+ const collectGqlDefinitionMetadata = ({ programPath, filename, createTracker }) => {
210
+ const exportBindings = collectExportBindings(programPath.node);
211
+ const tracker = (createTracker ?? createCanonicalTracker)({
212
+ filePath: filename,
213
+ getExportName: (localName) => exportBindings.get(localName)
214
+ });
215
+ const getAnonymousName = createAnonymousNameFactory();
216
+ const scopeHandles = /* @__PURE__ */ new WeakMap();
217
+ const metadata = /* @__PURE__ */ new WeakMap();
218
+ programPath.traverse({
219
+ enter(path) {
220
+ if (path.isCallExpression() && isGqlDefinitionCall(path.node)) {
221
+ const depthBeforeRegister = tracker.currentDepth();
222
+ const { astPath } = tracker.registerDefinition();
223
+ const isTopLevel = depthBeforeRegister <= 1;
224
+ const exportInfo = isTopLevel ? resolveTopLevelExport(path, exportBindings) : null;
225
+ metadata.set(path.node, {
226
+ astPath,
227
+ isTopLevel,
228
+ isExported: exportInfo?.isExported ?? false,
229
+ exportBinding: exportInfo?.exportBinding
230
+ });
231
+ path.skip();
232
+ return;
233
+ }
234
+ const handle = maybeEnterScope(path, tracker, getAnonymousName);
235
+ if (handle) scopeHandles.set(path, handle);
236
+ },
237
+ exit(path) {
238
+ const handle = scopeHandles.get(path);
239
+ if (handle) {
240
+ tracker.exitScope(handle);
241
+ scopeHandles.delete(path);
242
+ }
243
+ }
244
+ });
245
+ return metadata;
246
+ };
247
+ const collectExportBindings = (program) => {
248
+ const bindings = /* @__PURE__ */ new Map();
249
+ for (const statement of program.body) {
250
+ if (types.isExportNamedDeclaration(statement) && statement.declaration) {
251
+ const { declaration } = statement;
252
+ if (types.isVariableDeclaration(declaration)) {
253
+ for (const declarator of declaration.declarations) if (types.isIdentifier(declarator.id)) bindings.set(declarator.id.name, declarator.id.name);
254
+ continue;
255
+ }
256
+ if ((types.isFunctionDeclaration(declaration) || types.isClassDeclaration(declaration)) && declaration.id) bindings.set(declaration.id.name, declaration.id.name);
257
+ continue;
258
+ }
259
+ if (types.isExpressionStatement(statement) && types.isAssignmentExpression(statement.expression)) {
260
+ const exportName = getCommonJsExportName(statement.expression.left);
261
+ if (exportName) bindings.set(exportName, exportName);
262
+ }
263
+ }
264
+ return bindings;
265
+ };
266
+ const getCommonJsExportName = (node) => {
267
+ if (!types.isMemberExpression(node) || node.computed) return null;
268
+ const isExports = types.isIdentifier(node.object, { name: "exports" });
269
+ const isModuleExports = types.isMemberExpression(node.object) && types.isIdentifier(node.object.object, { name: "module" }) && types.isIdentifier(node.object.property, { name: "exports" });
270
+ if (!isExports && !isModuleExports) return null;
271
+ if (types.isIdentifier(node.property)) return node.property.name;
272
+ if (types.isStringLiteral(node.property)) return node.property.value;
273
+ return null;
274
+ };
275
+ const createAnonymousNameFactory = () => {
276
+ const counters = /* @__PURE__ */ new Map();
277
+ return (kind) => {
278
+ const count = counters.get(kind) ?? 0;
279
+ counters.set(kind, count + 1);
280
+ return `${kind}#${count}`;
281
+ };
282
+ };
283
+ const isGqlDefinitionCall = (node) => types.isCallExpression(node) && types.isMemberExpression(node.callee) && isGqlReference(node.callee.object) && node.arguments.length > 0 && types.isArrowFunctionExpression(node.arguments[0]);
284
+ const isGqlReference = (expr) => {
285
+ if (types.isIdentifier(expr, { name: "gql" })) return true;
286
+ if (!types.isMemberExpression(expr) || expr.computed) return false;
287
+ if (types.isIdentifier(expr.property) && expr.property.name === "gql" || types.isStringLiteral(expr.property) && expr.property.value === "gql") return true;
288
+ return isGqlReference(expr.object);
289
+ };
290
+ const resolveTopLevelExport = (callPath, exportBindings) => {
291
+ const declarator = callPath.parentPath;
292
+ if (declarator?.isVariableDeclarator()) {
293
+ const { id } = declarator.node;
294
+ if (types.isIdentifier(id)) {
295
+ const exportBinding = exportBindings.get(id.name);
296
+ if (exportBinding) return {
297
+ isExported: true,
298
+ exportBinding
299
+ };
300
+ }
301
+ }
302
+ const assignment = callPath.parentPath;
303
+ if (assignment?.isAssignmentExpression()) {
304
+ const exportName = getCommonJsExportName(assignment.node.left);
305
+ if (exportName && exportBindings.has(exportName)) return {
306
+ isExported: true,
307
+ exportBinding: exportName
308
+ };
309
+ }
310
+ return null;
311
+ };
312
+ const maybeEnterScope = (path, tracker, getAnonymousName) => {
313
+ if (path.isAssignmentExpression()) {
314
+ const exportName = getCommonJsExportName(path.node.left);
315
+ if (exportName) return tracker.enterScope({
316
+ segment: exportName,
317
+ kind: "variable",
318
+ stableKey: `var:${exportName}`
319
+ });
320
+ }
321
+ if (path.isVariableDeclarator() && types.isIdentifier(path.node.id)) {
322
+ const name = path.node.id.name;
323
+ return tracker.enterScope({
324
+ segment: name,
325
+ kind: "variable",
326
+ stableKey: `var:${name}`
327
+ });
328
+ }
329
+ if (path.isArrowFunctionExpression()) {
330
+ const name = getAnonymousName("arrow");
331
+ return tracker.enterScope({
332
+ segment: name,
333
+ kind: "function",
334
+ stableKey: "arrow"
335
+ });
336
+ }
337
+ if (path.isFunctionDeclaration() || path.isFunctionExpression()) {
338
+ const name = path.node.id?.name ?? getAnonymousName("function");
339
+ return tracker.enterScope({
340
+ segment: name,
341
+ kind: "function",
342
+ stableKey: `func:${name}`
343
+ });
344
+ }
345
+ if (path.isClassDeclaration()) {
346
+ const name = path.node.id?.name ?? getAnonymousName("class");
347
+ return tracker.enterScope({
348
+ segment: name,
349
+ kind: "class",
350
+ stableKey: `class:${name}`
351
+ });
352
+ }
353
+ if (path.isClassMethod() && types.isIdentifier(path.node.key)) {
354
+ const name = path.node.key.name;
355
+ return tracker.enterScope({
356
+ segment: name,
357
+ kind: "method",
358
+ stableKey: `member:${name}`
359
+ });
360
+ }
361
+ if (path.isClassProperty() && types.isIdentifier(path.node.key)) {
362
+ const name = path.node.key.name;
363
+ return tracker.enterScope({
364
+ segment: name,
365
+ kind: "property",
366
+ stableKey: `member:${name}`
367
+ });
368
+ }
369
+ if (path.isObjectProperty()) {
370
+ const key = path.node.key;
371
+ const name = types.isIdentifier(key) ? key.name : types.isStringLiteral(key) ? key.value : null;
372
+ if (name) return tracker.enterScope({
373
+ segment: name,
374
+ kind: "property",
375
+ stableKey: `prop:${name}`
376
+ });
377
+ }
378
+ return null;
379
+ };
380
+
381
+ //#endregion
382
+ //#region packages/babel-transformer/src/ast/runtime.ts
383
+ const buildFragmentRuntimeCall = ({ artifact }) => {
384
+ return ok(types.callExpression(types.memberExpression(types.identifier("gqlRuntime"), types.identifier("fragment")), [buildObjectExpression({ prebuild: buildObjectExpression({ typename: types.stringLiteral(artifact.prebuild.typename) }) })]));
385
+ };
386
+ const buildOperationRuntimeComponents = ({ artifact }) => {
387
+ const runtimeCall = types.callExpression(types.memberExpression(types.identifier("gqlRuntime"), types.identifier("operation")), [buildObjectExpression({
388
+ prebuild: types.callExpression(types.memberExpression(types.identifier("JSON"), types.identifier("parse")), [types.stringLiteral(JSON.stringify(artifact.prebuild))]),
389
+ runtime: buildObjectExpression({})
390
+ })]);
391
+ return ok({
392
+ referenceCall: types.callExpression(types.memberExpression(types.identifier("gqlRuntime"), types.identifier("getOperation")), [types.stringLiteral(artifact.prebuild.operationName)]),
393
+ runtimeCall
394
+ });
395
+ };
396
+
397
+ //#endregion
398
+ //#region packages/babel-transformer/src/ast/transformer.ts
399
+ const transformCallExpression = ({ callPath, filename, metadata, getArtifact }) => {
400
+ if (!metadata.has(callPath.node)) return ok({ transformed: false });
401
+ const gqlCallResult = extractGqlCall({
402
+ nodePath: callPath,
403
+ filename,
404
+ metadata,
405
+ getArtifact
406
+ });
407
+ if (gqlCallResult.isErr()) return err(gqlCallResult.error);
408
+ const gqlCall = gqlCallResult.value;
409
+ return replaceWithRuntimeCall(callPath, gqlCall, filename);
410
+ };
411
+ const replaceWithRuntimeCall = (callPath, gqlCall, filename) => {
412
+ if (gqlCall.type === "fragment") {
413
+ const result = buildFragmentRuntimeCall({
414
+ ...gqlCall,
415
+ filename
416
+ });
417
+ if (result.isErr()) return err(result.error);
418
+ callPath.replaceWith(result.value);
419
+ return ok({ transformed: true });
420
+ }
421
+ if (gqlCall.type === "operation") {
422
+ const result = buildOperationRuntimeComponents({
423
+ ...gqlCall,
424
+ filename
425
+ });
426
+ if (result.isErr()) return err(result.error);
427
+ const { referenceCall, runtimeCall } = result.value;
428
+ callPath.replaceWith(referenceCall);
429
+ return ok({
430
+ transformed: true,
431
+ runtimeCall
432
+ });
433
+ }
434
+ return ok({ transformed: false });
435
+ };
436
+ const insertRuntimeCalls = (programPath, runtimeCalls) => {
437
+ if (runtimeCalls.length === 0) return;
438
+ programPath.traverse({ ImportDeclaration(importDeclPath) {
439
+ if (importDeclPath.node.source.value === "@soda-gql/runtime") importDeclPath.insertAfter([...runtimeCalls]);
440
+ } });
441
+ };
442
+
443
+ //#endregion
444
+ //#region node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
445
+ var comma = ",".charCodeAt(0);
446
+ var semicolon = ";".charCodeAt(0);
447
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
448
+ var intToChar = new Uint8Array(64);
449
+ var charToInt = new Uint8Array(128);
450
+ for (let i = 0; i < chars.length; i++) {
451
+ const c = chars.charCodeAt(i);
452
+ intToChar[i] = c;
453
+ charToInt[c] = i;
454
+ }
455
+ function decodeInteger(reader, relative) {
456
+ let value = 0;
457
+ let shift = 0;
458
+ let integer = 0;
459
+ do {
460
+ integer = charToInt[reader.next()];
461
+ value |= (integer & 31) << shift;
462
+ shift += 5;
463
+ } while (integer & 32);
464
+ const shouldNegate = value & 1;
465
+ value >>>= 1;
466
+ if (shouldNegate) value = -2147483648 | -value;
467
+ return relative + value;
468
+ }
469
+ function encodeInteger(builder, num, relative) {
470
+ let delta = num - relative;
471
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
472
+ do {
473
+ let clamped = delta & 31;
474
+ delta >>>= 5;
475
+ if (delta > 0) clamped |= 32;
476
+ builder.write(intToChar[clamped]);
477
+ } while (delta > 0);
478
+ return num;
479
+ }
480
+ function hasMoreVlq(reader, max) {
481
+ if (reader.pos >= max) return false;
482
+ return reader.peek() !== comma;
483
+ }
484
+ var bufLength = 1024 * 16;
485
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
486
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
487
+ } } : { decode(buf) {
488
+ let out = "";
489
+ for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
490
+ return out;
491
+ } };
492
+ var StringWriter = class {
493
+ constructor() {
494
+ this.pos = 0;
495
+ this.out = "";
496
+ this.buffer = new Uint8Array(bufLength);
497
+ }
498
+ write(v) {
499
+ const { buffer } = this;
500
+ buffer[this.pos++] = v;
501
+ if (this.pos === bufLength) {
502
+ this.out += td.decode(buffer);
503
+ this.pos = 0;
504
+ }
505
+ }
506
+ flush() {
507
+ const { buffer, out, pos } = this;
508
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
509
+ }
510
+ };
511
+ var StringReader = class {
512
+ constructor(buffer) {
513
+ this.pos = 0;
514
+ this.buffer = buffer;
515
+ }
516
+ next() {
517
+ return this.buffer.charCodeAt(this.pos++);
518
+ }
519
+ peek() {
520
+ return this.buffer.charCodeAt(this.pos);
521
+ }
522
+ indexOf(char) {
523
+ const { buffer, pos } = this;
524
+ const idx = buffer.indexOf(char, pos);
525
+ return idx === -1 ? buffer.length : idx;
526
+ }
527
+ };
528
+ function decode(mappings) {
529
+ const { length } = mappings;
530
+ const reader = new StringReader(mappings);
531
+ const decoded = [];
532
+ let genColumn = 0;
533
+ let sourcesIndex = 0;
534
+ let sourceLine = 0;
535
+ let sourceColumn = 0;
536
+ let namesIndex = 0;
537
+ do {
538
+ const semi = reader.indexOf(";");
539
+ const line = [];
540
+ let sorted = true;
541
+ let lastCol = 0;
542
+ genColumn = 0;
543
+ while (reader.pos < semi) {
544
+ let seg;
545
+ genColumn = decodeInteger(reader, genColumn);
546
+ if (genColumn < lastCol) sorted = false;
547
+ lastCol = genColumn;
548
+ if (hasMoreVlq(reader, semi)) {
549
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
550
+ sourceLine = decodeInteger(reader, sourceLine);
551
+ sourceColumn = decodeInteger(reader, sourceColumn);
552
+ if (hasMoreVlq(reader, semi)) {
553
+ namesIndex = decodeInteger(reader, namesIndex);
554
+ seg = [
555
+ genColumn,
556
+ sourcesIndex,
557
+ sourceLine,
558
+ sourceColumn,
559
+ namesIndex
560
+ ];
561
+ } else seg = [
562
+ genColumn,
563
+ sourcesIndex,
564
+ sourceLine,
565
+ sourceColumn
566
+ ];
567
+ } else seg = [genColumn];
568
+ line.push(seg);
569
+ reader.pos++;
570
+ }
571
+ if (!sorted) sort(line);
572
+ decoded.push(line);
573
+ reader.pos = semi + 1;
574
+ } while (reader.pos <= length);
575
+ return decoded;
576
+ }
577
+ function sort(line) {
578
+ line.sort(sortComparator$1);
579
+ }
580
+ function sortComparator$1(a, b) {
581
+ return a[0] - b[0];
582
+ }
583
+ function encode(decoded) {
584
+ const writer = new StringWriter();
585
+ let sourcesIndex = 0;
586
+ let sourceLine = 0;
587
+ let sourceColumn = 0;
588
+ let namesIndex = 0;
589
+ for (let i = 0; i < decoded.length; i++) {
590
+ const line = decoded[i];
591
+ if (i > 0) writer.write(semicolon);
592
+ if (line.length === 0) continue;
593
+ let genColumn = 0;
594
+ for (let j = 0; j < line.length; j++) {
595
+ const segment = line[j];
596
+ if (j > 0) writer.write(comma);
597
+ genColumn = encodeInteger(writer, segment[0], genColumn);
598
+ if (segment.length === 1) continue;
599
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
600
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
601
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
602
+ if (segment.length === 4) continue;
603
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
604
+ }
605
+ }
606
+ return writer.flush();
607
+ }
608
+
609
+ //#endregion
610
+ //#region node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
611
+ const schemeRegex = /^[\w+.-]+:\/\//;
612
+ /**
613
+ * Matches the parts of a URL:
614
+ * 1. Scheme, including ":", guaranteed.
615
+ * 2. User/password, including "@", optional.
616
+ * 3. Host, guaranteed.
617
+ * 4. Port, including ":", optional.
618
+ * 5. Path, including "/", optional.
619
+ * 6. Query, including "?", optional.
620
+ * 7. Hash, including "#", optional.
621
+ */
622
+ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
623
+ /**
624
+ * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
625
+ * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
626
+ *
627
+ * 1. Host, optional.
628
+ * 2. Path, which may include "/", guaranteed.
629
+ * 3. Query, including "?", optional.
630
+ * 4. Hash, including "#", optional.
631
+ */
632
+ const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
633
+ function isAbsoluteUrl(input) {
634
+ return schemeRegex.test(input);
635
+ }
636
+ function isSchemeRelativeUrl(input) {
637
+ return input.startsWith("//");
638
+ }
639
+ function isAbsolutePath(input) {
640
+ return input.startsWith("/");
641
+ }
642
+ function isFileUrl(input) {
643
+ return input.startsWith("file:");
644
+ }
645
+ function isRelative(input) {
646
+ return /^[.?#]/.test(input);
647
+ }
648
+ function parseAbsoluteUrl(input) {
649
+ const match = urlRegex.exec(input);
650
+ return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
651
+ }
652
+ function parseFileUrl(input) {
653
+ const match = fileRegex.exec(input);
654
+ const path = match[2];
655
+ return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
656
+ }
657
+ function makeUrl(scheme, user, host, port, path, query, hash) {
658
+ return {
659
+ scheme,
660
+ user,
661
+ host,
662
+ port,
663
+ path,
664
+ query,
665
+ hash,
666
+ type: 7
667
+ };
668
+ }
669
+ function parseUrl(input) {
670
+ if (isSchemeRelativeUrl(input)) {
671
+ const url$1 = parseAbsoluteUrl("http:" + input);
672
+ url$1.scheme = "";
673
+ url$1.type = 6;
674
+ return url$1;
675
+ }
676
+ if (isAbsolutePath(input)) {
677
+ const url$1 = parseAbsoluteUrl("http://foo.com" + input);
678
+ url$1.scheme = "";
679
+ url$1.host = "";
680
+ url$1.type = 5;
681
+ return url$1;
682
+ }
683
+ if (isFileUrl(input)) return parseFileUrl(input);
684
+ if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
685
+ const url = parseAbsoluteUrl("http://foo.com/" + input);
686
+ url.scheme = "";
687
+ url.host = "";
688
+ url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
689
+ return url;
690
+ }
691
+ function stripPathFilename(path) {
692
+ if (path.endsWith("/..")) return path;
693
+ const index = path.lastIndexOf("/");
694
+ return path.slice(0, index + 1);
695
+ }
696
+ function mergePaths(url, base) {
697
+ normalizePath(base, base.type);
698
+ if (url.path === "/") url.path = base.path;
699
+ else url.path = stripPathFilename(base.path) + url.path;
700
+ }
701
+ /**
702
+ * The path can have empty directories "//", unneeded parents "foo/..", or current directory
703
+ * "foo/.". We need to normalize to a standard representation.
704
+ */
705
+ function normalizePath(url, type) {
706
+ const rel = type <= 4;
707
+ const pieces = url.path.split("/");
708
+ let pointer = 1;
709
+ let positive = 0;
710
+ let addTrailingSlash = false;
711
+ for (let i = 1; i < pieces.length; i++) {
712
+ const piece = pieces[i];
713
+ if (!piece) {
714
+ addTrailingSlash = true;
715
+ continue;
716
+ }
717
+ addTrailingSlash = false;
718
+ if (piece === ".") continue;
719
+ if (piece === "..") {
720
+ if (positive) {
721
+ addTrailingSlash = true;
722
+ positive--;
723
+ pointer--;
724
+ } else if (rel) pieces[pointer++] = piece;
725
+ continue;
726
+ }
727
+ pieces[pointer++] = piece;
728
+ positive++;
729
+ }
730
+ let path = "";
731
+ for (let i = 1; i < pointer; i++) path += "/" + pieces[i];
732
+ if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/";
733
+ url.path = path;
734
+ }
735
+ /**
736
+ * Attempts to resolve `input` URL/path relative to `base`.
737
+ */
738
+ function resolve(input, base) {
739
+ if (!input && !base) return "";
740
+ const url = parseUrl(input);
741
+ let inputType = url.type;
742
+ if (base && inputType !== 7) {
743
+ const baseUrl = parseUrl(base);
744
+ const baseType = baseUrl.type;
745
+ switch (inputType) {
746
+ case 1: url.hash = baseUrl.hash;
747
+ case 2: url.query = baseUrl.query;
748
+ case 3:
749
+ case 4: mergePaths(url, baseUrl);
750
+ case 5:
751
+ url.user = baseUrl.user;
752
+ url.host = baseUrl.host;
753
+ url.port = baseUrl.port;
754
+ case 6: url.scheme = baseUrl.scheme;
755
+ }
756
+ if (baseType > inputType) inputType = baseType;
757
+ }
758
+ normalizePath(url, inputType);
759
+ const queryHash = url.query + url.hash;
760
+ switch (inputType) {
761
+ case 2:
762
+ case 3: return queryHash;
763
+ case 4: {
764
+ const path = url.path.slice(1);
765
+ if (!path) return queryHash || ".";
766
+ if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash;
767
+ return path + queryHash;
768
+ }
769
+ case 5: return url.path + queryHash;
770
+ default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
771
+ }
772
+ }
773
+
774
+ //#endregion
775
+ //#region node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
776
+ function stripFilename(path) {
777
+ if (!path) return "";
778
+ const index = path.lastIndexOf("/");
779
+ return path.slice(0, index + 1);
780
+ }
781
+ function resolver(mapUrl, sourceRoot) {
782
+ const from = stripFilename(mapUrl);
783
+ const prefix = sourceRoot ? sourceRoot + "/" : "";
784
+ return (source) => resolve(prefix + (source || ""), from);
785
+ }
786
+ var COLUMN$1 = 0;
787
+ function maybeSort(mappings, owned) {
788
+ const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
789
+ if (unsortedIndex === mappings.length) return mappings;
790
+ if (!owned) mappings = mappings.slice();
791
+ for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
792
+ return mappings;
793
+ }
794
+ function nextUnsortedSegmentLine(mappings, start) {
795
+ for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
796
+ return mappings.length;
797
+ }
798
+ function isSorted(line) {
799
+ for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false;
800
+ return true;
801
+ }
802
+ function sortSegments(line, owned) {
803
+ if (!owned) line = line.slice();
804
+ return line.sort(sortComparator);
805
+ }
806
+ function sortComparator(a, b) {
807
+ return a[COLUMN$1] - b[COLUMN$1];
808
+ }
809
+ var found = false;
810
+ function binarySearch(haystack, needle, low, high) {
811
+ while (low <= high) {
812
+ const mid = low + (high - low >> 1);
813
+ const cmp = haystack[mid][COLUMN$1] - needle;
814
+ if (cmp === 0) {
815
+ found = true;
816
+ return mid;
817
+ }
818
+ if (cmp < 0) low = mid + 1;
819
+ else high = mid - 1;
820
+ }
821
+ found = false;
822
+ return low - 1;
823
+ }
824
+ function upperBound(haystack, needle, index) {
825
+ for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$1] !== needle) break;
826
+ return index;
827
+ }
828
+ function lowerBound(haystack, needle, index) {
829
+ for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$1] !== needle) break;
830
+ return index;
831
+ }
832
+ function memoizedState() {
833
+ return {
834
+ lastKey: -1,
835
+ lastNeedle: -1,
836
+ lastIndex: -1
837
+ };
838
+ }
839
+ function memoizedBinarySearch(haystack, needle, state, key) {
840
+ const { lastKey, lastNeedle, lastIndex } = state;
841
+ let low = 0;
842
+ let high = haystack.length - 1;
843
+ if (key === lastKey) {
844
+ if (needle === lastNeedle) {
845
+ found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
846
+ return lastIndex;
847
+ }
848
+ if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
849
+ else high = lastIndex;
850
+ }
851
+ state.lastKey = key;
852
+ state.lastNeedle = needle;
853
+ return state.lastIndex = binarySearch(haystack, needle, low, high);
854
+ }
855
+ function parse$1(map) {
856
+ return typeof map === "string" ? JSON.parse(map) : map;
857
+ }
858
+ var LEAST_UPPER_BOUND = -1;
859
+ var GREATEST_LOWER_BOUND = 1;
860
+ var TraceMap = class {
861
+ constructor(map, mapUrl) {
862
+ const isString = typeof map === "string";
863
+ if (!isString && map._decodedMemo) return map;
864
+ const parsed = parse$1(map);
865
+ const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
866
+ this.version = version;
867
+ this.file = file;
868
+ this.names = names || [];
869
+ this.sourceRoot = sourceRoot;
870
+ this.sources = sources;
871
+ this.sourcesContent = sourcesContent;
872
+ this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
873
+ const resolve$1 = resolver(mapUrl, sourceRoot);
874
+ this.resolvedSources = sources.map(resolve$1);
875
+ const { mappings } = parsed;
876
+ if (typeof mappings === "string") {
877
+ this._encoded = mappings;
878
+ this._decoded = void 0;
879
+ } else if (Array.isArray(mappings)) {
880
+ this._encoded = void 0;
881
+ this._decoded = maybeSort(mappings, isString);
882
+ } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
883
+ else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
884
+ this._decodedMemo = memoizedState();
885
+ this._bySources = void 0;
886
+ this._bySourceMemos = void 0;
887
+ }
888
+ };
889
+ function cast$1(map) {
890
+ return map;
891
+ }
892
+ function decodedMappings(map) {
893
+ var _a;
894
+ return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded));
895
+ }
896
+ function traceSegment(map, line, column) {
897
+ const decoded = decodedMappings(map);
898
+ if (line >= decoded.length) return null;
899
+ const segments = decoded[line];
900
+ const index = traceSegmentInternal(segments, cast$1(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
901
+ return index === -1 ? null : segments[index];
902
+ }
903
+ function traceSegmentInternal(segments, memo, line, column, bias) {
904
+ let index = memoizedBinarySearch(segments, column, memo, line);
905
+ if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
906
+ else if (bias === LEAST_UPPER_BOUND) index++;
907
+ if (index === -1 || index === segments.length) return -1;
908
+ return index;
909
+ }
910
+
911
+ //#endregion
912
+ //#region node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
913
+ var SetArray = class {
914
+ constructor() {
915
+ this._indexes = { __proto__: null };
916
+ this.array = [];
917
+ }
918
+ };
919
+ function cast(set) {
920
+ return set;
921
+ }
922
+ function get(setarr, key) {
923
+ return cast(setarr)._indexes[key];
924
+ }
925
+ function put(setarr, key) {
926
+ const index = get(setarr, key);
927
+ if (index !== void 0) return index;
928
+ const { array, _indexes: indexes } = cast(setarr);
929
+ return indexes[key] = array.push(key) - 1;
930
+ }
931
+ function remove(setarr, key) {
932
+ const index = get(setarr, key);
933
+ if (index === void 0) return;
934
+ const { array, _indexes: indexes } = cast(setarr);
935
+ for (let i = index + 1; i < array.length; i++) {
936
+ const k = array[i];
937
+ array[i - 1] = k;
938
+ indexes[k]--;
939
+ }
940
+ indexes[key] = void 0;
941
+ array.pop();
942
+ }
943
+ var COLUMN = 0;
944
+ var SOURCES_INDEX = 1;
945
+ var SOURCE_LINE = 2;
946
+ var SOURCE_COLUMN = 3;
947
+ var NAMES_INDEX = 4;
948
+ var NO_NAME = -1;
949
+ var GenMapping = class {
950
+ constructor({ file, sourceRoot } = {}) {
951
+ this._names = new SetArray();
952
+ this._sources = new SetArray();
953
+ this._sourcesContent = [];
954
+ this._mappings = [];
955
+ this.file = file;
956
+ this.sourceRoot = sourceRoot;
957
+ this._ignoreList = new SetArray();
958
+ }
959
+ };
960
+ function cast2(map) {
961
+ return map;
962
+ }
963
+ var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
964
+ return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
965
+ };
966
+ function setSourceContent(map, source, content) {
967
+ const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map);
968
+ const index = put(sources, source);
969
+ sourcesContent[index] = content;
970
+ }
971
+ function setIgnore(map, source, ignore = true) {
972
+ const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map);
973
+ const index = put(sources, source);
974
+ if (index === sourcesContent.length) sourcesContent[index] = null;
975
+ if (ignore) put(ignoreList, index);
976
+ else remove(ignoreList, index);
977
+ }
978
+ function toDecodedMap(map) {
979
+ const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map);
980
+ removeEmptyFinalLines(mappings);
981
+ return {
982
+ version: 3,
983
+ file: map.file || void 0,
984
+ names: names.array,
985
+ sourceRoot: map.sourceRoot || void 0,
986
+ sources: sources.array,
987
+ sourcesContent,
988
+ mappings,
989
+ ignoreList: ignoreList.array
990
+ };
991
+ }
992
+ function toEncodedMap(map) {
993
+ const decoded = toDecodedMap(map);
994
+ return Object.assign({}, decoded, { mappings: encode(decoded.mappings) });
995
+ }
996
+ function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
997
+ const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map);
998
+ const line = getIndex(mappings, genLine);
999
+ const index = getColumnIndex(line, genColumn);
1000
+ if (!source) {
1001
+ if (skipable && skipSourceless(line, index)) return;
1002
+ return insert(line, index, [genColumn]);
1003
+ }
1004
+ assert(sourceLine);
1005
+ assert(sourceColumn);
1006
+ const sourcesIndex = put(sources, source);
1007
+ const namesIndex = name ? put(names, name) : NO_NAME;
1008
+ if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
1009
+ if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
1010
+ return insert(line, index, name ? [
1011
+ genColumn,
1012
+ sourcesIndex,
1013
+ sourceLine,
1014
+ sourceColumn,
1015
+ namesIndex
1016
+ ] : [
1017
+ genColumn,
1018
+ sourcesIndex,
1019
+ sourceLine,
1020
+ sourceColumn
1021
+ ]);
1022
+ }
1023
+ function assert(_val) {}
1024
+ function getIndex(arr, index) {
1025
+ for (let i = arr.length; i <= index; i++) arr[i] = [];
1026
+ return arr[index];
1027
+ }
1028
+ function getColumnIndex(line, genColumn) {
1029
+ let index = line.length;
1030
+ for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN]) break;
1031
+ return index;
1032
+ }
1033
+ function insert(array, index, value) {
1034
+ for (let i = array.length; i > index; i--) array[i] = array[i - 1];
1035
+ array[index] = value;
1036
+ }
1037
+ function removeEmptyFinalLines(mappings) {
1038
+ const { length } = mappings;
1039
+ let len = length;
1040
+ for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break;
1041
+ if (len < length) mappings.length = len;
1042
+ }
1043
+ function skipSourceless(line, index) {
1044
+ if (index === 0) return true;
1045
+ return line[index - 1].length === 1;
1046
+ }
1047
+ function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
1048
+ if (index === 0) return false;
1049
+ const prev = line[index - 1];
1050
+ if (prev.length === 1) return false;
1051
+ return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
1052
+ }
1053
+
1054
+ //#endregion
1055
+ //#region node_modules/@ampproject/remapping/dist/remapping.mjs
1056
+ const SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
1057
+ const EMPTY_SOURCES = [];
1058
+ function SegmentObject(source, line, column, name, content, ignore) {
1059
+ return {
1060
+ source,
1061
+ line,
1062
+ column,
1063
+ name,
1064
+ content,
1065
+ ignore
1066
+ };
1067
+ }
1068
+ function Source(map, sources, source, content, ignore) {
1069
+ return {
1070
+ map,
1071
+ sources,
1072
+ source,
1073
+ content,
1074
+ ignore
1075
+ };
1076
+ }
1077
+ /**
1078
+ * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
1079
+ * (which may themselves be SourceMapTrees).
1080
+ */
1081
+ function MapSource(map, sources) {
1082
+ return Source(map, sources, "", null, false);
1083
+ }
1084
+ /**
1085
+ * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
1086
+ * segment tracing ends at the `OriginalSource`.
1087
+ */
1088
+ function OriginalSource(source, content, ignore) {
1089
+ return Source(null, EMPTY_SOURCES, source, content, ignore);
1090
+ }
1091
+ /**
1092
+ * traceMappings is only called on the root level SourceMapTree, and begins the process of
1093
+ * resolving each mapping in terms of the original source files.
1094
+ */
1095
+ function traceMappings(tree) {
1096
+ const gen = new GenMapping({ file: tree.map.file });
1097
+ const { sources: rootSources, map } = tree;
1098
+ const rootNames = map.names;
1099
+ const rootMappings = decodedMappings(map);
1100
+ for (let i = 0; i < rootMappings.length; i++) {
1101
+ const segments = rootMappings[i];
1102
+ for (let j = 0; j < segments.length; j++) {
1103
+ const segment = segments[j];
1104
+ const genCol = segment[0];
1105
+ let traced = SOURCELESS_MAPPING;
1106
+ if (segment.length !== 1) {
1107
+ const source$1 = rootSources[segment[1]];
1108
+ traced = originalPositionFor(source$1, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
1109
+ if (traced == null) continue;
1110
+ }
1111
+ const { column, line, name, content, source, ignore } = traced;
1112
+ maybeAddSegment(gen, i, genCol, source, line, column, name);
1113
+ if (source && content != null) setSourceContent(gen, source, content);
1114
+ if (ignore) setIgnore(gen, source, true);
1115
+ }
1116
+ }
1117
+ return gen;
1118
+ }
1119
+ /**
1120
+ * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
1121
+ * child SourceMapTrees, until we find the original source map.
1122
+ */
1123
+ function originalPositionFor(source, line, column, name) {
1124
+ if (!source.map) return SegmentObject(source.source, line, column, name, source.content, source.ignore);
1125
+ const segment = traceSegment(source.map, line, column);
1126
+ if (segment == null) return null;
1127
+ if (segment.length === 1) return SOURCELESS_MAPPING;
1128
+ return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
1129
+ }
1130
+ function asArray(value) {
1131
+ if (Array.isArray(value)) return value;
1132
+ return [value];
1133
+ }
1134
+ /**
1135
+ * Recursively builds a tree structure out of sourcemap files, with each node
1136
+ * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
1137
+ * `OriginalSource`s and `SourceMapTree`s.
1138
+ *
1139
+ * Every sourcemap is composed of a collection of source files and mappings
1140
+ * into locations of those source files. When we generate a `SourceMapTree` for
1141
+ * the sourcemap, we attempt to load each source file's own sourcemap. If it
1142
+ * does not have an associated sourcemap, it is considered an original,
1143
+ * unmodified source file.
1144
+ */
1145
+ function buildSourceMapTree(input, loader) {
1146
+ const maps = asArray(input).map((m) => new TraceMap(m, ""));
1147
+ const map = maps.pop();
1148
+ for (let i = 0; i < maps.length; i++) if (maps[i].sources.length > 1) throw new Error(`Transformation map ${i} must have exactly one source file.\nDid you specify these with the most recent transformation maps first?`);
1149
+ let tree = build(map, loader, "", 0);
1150
+ for (let i = maps.length - 1; i >= 0; i--) tree = MapSource(maps[i], [tree]);
1151
+ return tree;
1152
+ }
1153
+ function build(map, loader, importer, importerDepth) {
1154
+ const { resolvedSources, sourcesContent, ignoreList } = map;
1155
+ const depth = importerDepth + 1;
1156
+ return MapSource(map, resolvedSources.map((sourceFile, i) => {
1157
+ const ctx = {
1158
+ importer,
1159
+ depth,
1160
+ source: sourceFile || "",
1161
+ content: void 0,
1162
+ ignore: void 0
1163
+ };
1164
+ const sourceMap = loader(ctx.source, ctx);
1165
+ const { source, content, ignore } = ctx;
1166
+ if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);
1167
+ return OriginalSource(source, content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null, ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false);
1168
+ }));
1169
+ }
1170
+ /**
1171
+ * A SourceMap v3 compatible sourcemap, which only includes fields that were
1172
+ * provided to it.
1173
+ */
1174
+ var SourceMap = class {
1175
+ constructor(map, options) {
1176
+ const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
1177
+ this.version = out.version;
1178
+ this.file = out.file;
1179
+ this.mappings = out.mappings;
1180
+ this.names = out.names;
1181
+ this.ignoreList = out.ignoreList;
1182
+ this.sourceRoot = out.sourceRoot;
1183
+ this.sources = out.sources;
1184
+ if (!options.excludeContent) this.sourcesContent = out.sourcesContent;
1185
+ }
1186
+ toString() {
1187
+ return JSON.stringify(this);
1188
+ }
1189
+ };
1190
+ /**
1191
+ * Traces through all the mappings in the root sourcemap, through the sources
1192
+ * (and their sourcemaps), all the way back to the original source location.
1193
+ *
1194
+ * `loader` will be called every time we encounter a source file. If it returns
1195
+ * a sourcemap, we will recurse into that sourcemap to continue the trace. If
1196
+ * it returns a falsey value, that source file is treated as an original,
1197
+ * unmodified source file.
1198
+ *
1199
+ * Pass `excludeContent` to exclude any self-containing source file content
1200
+ * from the output sourcemap.
1201
+ *
1202
+ * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
1203
+ * VLQ encoded) mappings.
1204
+ */
1205
+ function remapping(input, loader, options) {
1206
+ const opts = typeof options === "object" ? options : {
1207
+ excludeContent: !!options,
1208
+ decodedMappings: false
1209
+ };
1210
+ return new SourceMap(traceMappings(buildSourceMapTree(input, loader)), opts);
1211
+ }
1212
+
1213
+ //#endregion
1214
+ //#region packages/babel-transformer/src/transformer.ts
1215
+ /**
1216
+ * Creates a Babel transformer with a single transform() method.
1217
+ * This matches the pattern used in the TypeScript plugin.
1218
+ */
1219
+ const createTransformer = ({ programPath, types: types$1, config }) => {
1220
+ const graphqlSystemIdentifyHelper = createGraphqlSystemIdentifyHelper(config);
1221
+ /**
1222
+ * Check if a node is a require() or __webpack_require__() call.
1223
+ */
1224
+ const isRequireCall = (node) => {
1225
+ if (!types$1.isCallExpression(node)) return false;
1226
+ const callee = node.callee;
1227
+ return types$1.isIdentifier(callee) && (callee.name === "require" || callee.name === "__webpack_require__");
1228
+ };
1229
+ /**
1230
+ * Find the last statement that loads a module (import or require).
1231
+ * Handles both ESM imports and CommonJS require() calls.
1232
+ */
1233
+ const findLastModuleLoader = () => {
1234
+ const bodyPaths = programPath.get("body");
1235
+ let lastLoader = null;
1236
+ for (const path of bodyPaths) {
1237
+ if (path.isImportDeclaration()) {
1238
+ lastLoader = path;
1239
+ continue;
1240
+ }
1241
+ if (path.isVariableDeclaration()) {
1242
+ for (const declarator of path.node.declarations) if (declarator.init && isRequireCall(declarator.init)) {
1243
+ lastLoader = path;
1244
+ break;
1245
+ }
1246
+ continue;
1247
+ }
1248
+ if (path.isExpressionStatement()) {
1249
+ if (isRequireCall(path.node.expression)) lastLoader = path;
1250
+ }
1251
+ }
1252
+ return lastLoader;
1253
+ };
1254
+ return { transform: (context) => {
1255
+ const metadata = collectGqlDefinitionMetadata({
1256
+ programPath,
1257
+ filename: context.filename
1258
+ });
1259
+ const runtimeCalls = [];
1260
+ let transformed = false;
1261
+ programPath.traverse({ CallExpression: (callPath) => {
1262
+ const result = transformCallExpression({
1263
+ callPath,
1264
+ filename: context.filename,
1265
+ metadata,
1266
+ getArtifact: context.artifactLookup
1267
+ });
1268
+ if (result.isErr()) {
1269
+ console.error(`[@soda-gql/babel-transformer] ${formatPluginError(result.error)}`);
1270
+ return;
1271
+ }
1272
+ const transformResult = result.value;
1273
+ if (transformResult.transformed) {
1274
+ transformed = true;
1275
+ if (transformResult.runtimeCall) runtimeCalls.push(transformResult.runtimeCall);
1276
+ }
1277
+ } });
1278
+ if (!transformed) return {
1279
+ transformed: false,
1280
+ runtimeArtifacts: void 0
1281
+ };
1282
+ ensureGqlRuntimeImport(programPath);
1283
+ if (runtimeCalls.length > 0) {
1284
+ const statements = runtimeCalls.map((expr) => types$1.expressionStatement(expr));
1285
+ const lastLoaderPath = findLastModuleLoader();
1286
+ if (lastLoaderPath) lastLoaderPath.insertAfter(statements);
1287
+ else programPath.unshiftContainer("body", statements);
1288
+ }
1289
+ programPath.scope.crawl();
1290
+ removeGraphqlSystemImports(programPath, graphqlSystemIdentifyHelper, context.filename);
1291
+ return {
1292
+ transformed: true,
1293
+ runtimeArtifacts: void 0
1294
+ };
1295
+ } };
1296
+ };
1297
+
1298
+ //#endregion
1299
+ //#region packages/babel-transformer/src/transform.ts
1300
+ /**
1301
+ * Source-code based transform function for babel-transformer.
1302
+ *
1303
+ * This provides a similar interface to swc-transformer, taking source code
1304
+ * as input and returning transformed source code.
1305
+ */
1306
+ const traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
1307
+ const generate = typeof _generate === "function" ? _generate : _generate.default;
1308
+ /**
1309
+ * Create a transformer instance.
1310
+ *
1311
+ * @param options - Transform options including config and artifact
1312
+ * @returns A transformer that can transform source files
1313
+ */
1314
+ const createBabelTransformer = (options) => {
1315
+ const { config, artifact, sourceMap = false } = options;
1316
+ return { transform: ({ sourceCode, sourcePath, inputSourceMap }) => {
1317
+ const ast = parse(sourceCode, {
1318
+ sourceType: "module",
1319
+ plugins: ["typescript", "jsx"],
1320
+ sourceFilename: sourcePath
1321
+ });
1322
+ let programPath = null;
1323
+ traverse(ast, { Program(path) {
1324
+ programPath = path;
1325
+ path.stop();
1326
+ } });
1327
+ if (!programPath) return {
1328
+ transformed: false,
1329
+ sourceCode,
1330
+ sourceMap: void 0
1331
+ };
1332
+ if (!createTransformer({
1333
+ programPath,
1334
+ types,
1335
+ config
1336
+ }).transform({
1337
+ filename: sourcePath,
1338
+ artifactLookup: (canonicalId) => artifact.elements[canonicalId]
1339
+ }).transformed) return {
1340
+ transformed: false,
1341
+ sourceCode,
1342
+ sourceMap: void 0
1343
+ };
1344
+ const output = generate(ast, {
1345
+ sourceMaps: sourceMap,
1346
+ sourceFileName: sourcePath
1347
+ }, sourceCode);
1348
+ let finalSourceMap;
1349
+ if (sourceMap && output.map) if (inputSourceMap) {
1350
+ const merged = remapping([output.map, JSON.parse(inputSourceMap)], () => null);
1351
+ finalSourceMap = JSON.stringify(merged);
1352
+ } else finalSourceMap = JSON.stringify(output.map);
1353
+ return {
1354
+ transformed: true,
1355
+ sourceCode: output.code,
1356
+ sourceMap: finalSourceMap
1357
+ };
1358
+ } };
1359
+ };
1360
+ /**
1361
+ * Transform a single source file (one-shot).
1362
+ *
1363
+ * For transforming multiple files, use createBabelTransformer() to reuse the artifact.
1364
+ *
1365
+ * @param input - Transform input including source, path, artifact, and config
1366
+ * @returns Transform output
1367
+ */
1368
+ const transform = (input) => {
1369
+ return createBabelTransformer({
1370
+ config: input.config,
1371
+ artifact: input.artifact,
1372
+ sourceMap: input.sourceMap
1373
+ }).transform({
1374
+ sourceCode: input.sourceCode,
1375
+ sourcePath: input.sourcePath,
1376
+ inputSourceMap: input.inputSourceMap
1377
+ });
1378
+ };
1379
+
1380
+ //#endregion
1381
+ export { buildFragmentRuntimeCall, buildLiteralFromValue, buildObjectExpression, buildOperationRuntimeComponents, clone, cloneCallExpression, collectGqlDefinitionMetadata, createBabelTransformer, createTransformer, ensureGqlRuntimeImport, ensureGqlRuntimeRequire, extractGqlCall, insertRuntimeCalls, removeGraphqlSystemImports, stripTypeAnnotations, transform, transformCallExpression };
1382
+ //# sourceMappingURL=index.mjs.map