astronomical 2.0.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs ADDED
@@ -0,0 +1,1325 @@
1
+ /**
2
+ * ASTronomical - AST query language for JavaScript
3
+ * @license Apache-2.0
4
+ * Copyright (c) Erlend Oftedal
5
+ */
6
+
7
+ // src/nodeutils.ts
8
+ var isNode = (candidate) => {
9
+ return typeof candidate === "object" && candidate != null && "type" in candidate;
10
+ };
11
+ var isNodePath = (candidate) => {
12
+ return typeof candidate === "object" && candidate != null && "node" in candidate;
13
+ };
14
+ var isPrimitive = (value) => {
15
+ return typeof value == "string" || typeof value == "number" || typeof value == "boolean";
16
+ };
17
+ var isUpdateExpression = (value) => {
18
+ return isNode(value) && value.type === "UpdateExpression";
19
+ };
20
+ var isAssignmentExpression = (node) => {
21
+ return node.type === "AssignmentExpression";
22
+ };
23
+ var isMemberExpression = (node) => {
24
+ return node.type === "MemberExpression";
25
+ };
26
+ var isIdentifier = (node) => {
27
+ return node.type === "Identifier";
28
+ };
29
+ var isFunctionDeclaration = (node) => {
30
+ return node.type === "FunctionDeclaration";
31
+ };
32
+ var isFunctionExpression = (node) => {
33
+ return node.type === "FunctionExpression";
34
+ };
35
+ var isVariableDeclarator = (node) => {
36
+ return node.type === "VariableDeclarator";
37
+ };
38
+ var isVariableDeclaration = (node) => {
39
+ return node.type === "VariableDeclaration";
40
+ };
41
+ var isBinding = (node, parentNode, grandParentNode) => {
42
+ if (grandParentNode && node.type === "Identifier" && parentNode.type === "Property" && grandParentNode.type === "ObjectExpression") {
43
+ return false;
44
+ }
45
+ const keys = bindingIdentifiersKeys[parentNode.type] ?? [];
46
+ for (let i = 0; i < keys.length; i++) {
47
+ const key = keys[i];
48
+ const val = (
49
+ // @ts-expect-error key must present in parent
50
+ parentNode[key]
51
+ );
52
+ if (Array.isArray(val)) {
53
+ if (val.indexOf(node) >= 0) return true;
54
+ } else {
55
+ if (val === node) return true;
56
+ }
57
+ }
58
+ return false;
59
+ };
60
+ var bindingIdentifiersKeys = {
61
+ DeclareClass: ["id"],
62
+ DeclareFunction: ["id"],
63
+ DeclareModule: ["id"],
64
+ DeclareVariable: ["id"],
65
+ DeclareInterface: ["id"],
66
+ DeclareTypeAlias: ["id"],
67
+ DeclareOpaqueType: ["id"],
68
+ InterfaceDeclaration: ["id"],
69
+ TypeAlias: ["id"],
70
+ OpaqueType: ["id"],
71
+ CatchClause: ["param"],
72
+ LabeledStatement: ["label"],
73
+ UnaryExpression: ["argument"],
74
+ AssignmentExpression: ["left"],
75
+ ImportSpecifier: ["local"],
76
+ ImportNamespaceSpecifier: ["local"],
77
+ ImportDefaultSpecifier: ["local"],
78
+ ImportDeclaration: ["specifiers"],
79
+ ExportSpecifier: ["exported"],
80
+ ExportNamespaceSpecifier: ["exported"],
81
+ ExportDefaultSpecifier: ["exported"],
82
+ FunctionDeclaration: ["id", "params"],
83
+ FunctionExpression: ["id", "params"],
84
+ ArrowFunctionExpression: ["params"],
85
+ ObjectMethod: ["params"],
86
+ ClassMethod: ["params"],
87
+ ClassPrivateMethod: ["params"],
88
+ ForInStatement: ["left"],
89
+ ForOfStatement: ["left"],
90
+ ClassDeclaration: ["id"],
91
+ ClassExpression: ["id"],
92
+ RestElement: ["argument"],
93
+ UpdateExpression: ["argument"],
94
+ ObjectProperty: ["value"],
95
+ AssignmentPattern: ["left"],
96
+ ArrayPattern: ["elements"],
97
+ ObjectPattern: ["properties"],
98
+ VariableDeclaration: ["declarations"],
99
+ VariableDeclarator: ["id"]
100
+ };
101
+ var VISITOR_KEYS = {
102
+ ArrayExpression: ["elements"],
103
+ ArrayPattern: ["elements"],
104
+ ArrowFunctionExpression: ["params", "body"],
105
+ AssignmentExpression: ["left", "right"],
106
+ AssignmentPattern: ["left", "right"],
107
+ AwaitExpression: ["argument"],
108
+ BinaryExpression: ["left", "right"],
109
+ BlockStatement: ["body"],
110
+ BreakStatement: [],
111
+ CallExpression: ["callee", "arguments"],
112
+ CatchClause: ["param", "body"],
113
+ ChainExpression: ["expression"],
114
+ ClassBody: ["body"],
115
+ ClassDeclaration: ["id", "superClass", "body"],
116
+ ClassExpression: ["id", "superClass", "body"],
117
+ ConditionalExpression: ["test", "consequent", "alternate"],
118
+ ContinueStatement: [],
119
+ DebuggerStatement: [],
120
+ DoWhileStatement: ["body", "test"],
121
+ EmptyStatement: [],
122
+ ExportAllDeclaration: ["source"],
123
+ ExportDefaultDeclaration: ["declaration"],
124
+ ExportNamedDeclaration: ["declaration", "specifiers", "source"],
125
+ ExportSpecifier: ["local", "exported"],
126
+ ExpressionStatement: ["expression"],
127
+ ForInStatement: ["left", "right", "body"],
128
+ ForOfStatement: ["left", "right", "body"],
129
+ ForStatement: ["init", "test", "update", "body"],
130
+ FunctionDeclaration: ["id", "params", "body"],
131
+ FunctionExpression: ["id", "params", "body"],
132
+ Identifier: [],
133
+ IfStatement: ["test", "consequent", "alternate"],
134
+ ImportAttribute: ["key", "value"],
135
+ ImportDeclaration: ["specifiers", "source"],
136
+ ImportDefaultSpecifier: ["local"],
137
+ ImportNamespaceSpecifier: ["local"],
138
+ ImportSpecifier: ["local", "imported"],
139
+ LabeledStatement: ["label", "body"],
140
+ Literal: [],
141
+ LogicalExpression: ["left", "right"],
142
+ MemberExpression: ["object", "property"],
143
+ MetaProperty: ["meta", "property"],
144
+ MethodDefinition: ["key", "value"],
145
+ NewExpression: ["callee", "arguments"],
146
+ ObjectExpression: ["properties"],
147
+ ObjectPattern: ["properties"],
148
+ Program: ["body"],
149
+ Property: ["key", "value"],
150
+ RestElement: ["argument"],
151
+ ReturnStatement: ["argument"],
152
+ SequenceExpression: ["expressions"],
153
+ SpreadElement: ["argument"],
154
+ Super: [],
155
+ SwitchCase: ["test", "consequent"],
156
+ SwitchStatement: ["discriminant", "cases"],
157
+ TaggedTemplateExpression: ["tag", "quasi"],
158
+ TemplateElement: [],
159
+ TemplateLiteral: ["quasis", "expressions"],
160
+ ThisExpression: [],
161
+ ThrowStatement: ["argument"],
162
+ TryStatement: ["block", "handler", "finalizer"],
163
+ UnaryExpression: ["argument"],
164
+ UpdateExpression: ["argument"],
165
+ VariableDeclaration: ["declarations"],
166
+ VariableDeclarator: ["id", "init"],
167
+ WhileStatement: ["test", "body"],
168
+ WithStatement: ["object", "body"],
169
+ YieldExpression: ["argument"],
170
+ ImportExpression: ["source"],
171
+ Decorator: ["expression"],
172
+ PropertyDefinition: ["key", "value"],
173
+ Import: ["source"],
174
+ JSXAttribute: ["name", "value"],
175
+ JSXNamespacedName: ["namespace", "name"],
176
+ JSXElement: ["openingElement", "closingElement", "children"],
177
+ JSXClosingElement: ["name"],
178
+ JSXOpeningElement: ["name", "attributes"],
179
+ JSXFragment: ["openingFragment", "closingFragment", "children"],
180
+ JSXOpeningFragment: [],
181
+ JSXClosingFragment: [],
182
+ JSXText: [],
183
+ JSXExpressionContainer: ["expression"],
184
+ JSXSpreadChild: ["expression"],
185
+ JSXEmptyExpression: [],
186
+ JSXSpreadAttribute: ["argument"],
187
+ JSXIdentifier: [],
188
+ PrivateIdentifier: [],
189
+ JSXMemberExpression: ["object", "property"],
190
+ ParenthesizedExpression: ["expression"],
191
+ StaticBlock: ["body"]
192
+ };
193
+ function isBlockStatement(node) {
194
+ return node.type === "BlockStatement";
195
+ }
196
+ function isFunction(node) {
197
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression";
198
+ }
199
+ function isCatchClause(node) {
200
+ return node.type === "CatchClause";
201
+ }
202
+ function isPattern(node) {
203
+ switch (node.type) {
204
+ case "AssignmentPattern":
205
+ case "ArrayPattern":
206
+ case "ObjectPattern":
207
+ return true;
208
+ }
209
+ return false;
210
+ }
211
+ function isScope(node, parentNode) {
212
+ if (isBlockStatement(node) && (isFunction(parentNode) || isCatchClause(parentNode))) {
213
+ return false;
214
+ }
215
+ if (isPattern(node) && (isFunction(parentNode) || isCatchClause(parentNode))) {
216
+ return true;
217
+ }
218
+ return isFunctionDeclaration(parentNode) || isFunctionExpression(parentNode) || isScopable(node);
219
+ }
220
+ function isScopable(node) {
221
+ switch (node.type) {
222
+ case "BlockStatement":
223
+ case "CatchClause":
224
+ case "DoWhileStatement":
225
+ case "ForInStatement":
226
+ case "ForStatement":
227
+ case "FunctionDeclaration":
228
+ case "FunctionExpression":
229
+ case "Program":
230
+ case "MethodDefinition":
231
+ case "SwitchStatement":
232
+ case "WhileStatement":
233
+ case "ArrowFunctionExpression":
234
+ case "ClassExpression":
235
+ case "ClassDeclaration":
236
+ case "ForOfStatement":
237
+ case "StaticBlock":
238
+ return true;
239
+ }
240
+ return false;
241
+ }
242
+ function isExportSpecifier(node) {
243
+ return node.type === "ExportSpecifier";
244
+ }
245
+
246
+ // src/parseQuery.ts
247
+ var debugLogEnabled = false;
248
+ var log = debugLogEnabled ? {
249
+ debug: (...args) => {
250
+ console.debug(...args);
251
+ }
252
+ } : void 0;
253
+ var visitorKeys = Object.keys(VISITOR_KEYS);
254
+ var supportedIdentifiers = {};
255
+ for (let i = 0; i < visitorKeys.length; i++) {
256
+ const k = visitorKeys[i];
257
+ supportedIdentifiers[k] = k;
258
+ }
259
+ var NodeType = {
260
+ PARENT: 241,
261
+ CHILD: 242,
262
+ DESCENDANT: 243,
263
+ AND: 244,
264
+ OR: 245,
265
+ EQUALS: 246,
266
+ LITERAL: 247,
267
+ FUNCTION: 248
268
+ };
269
+ function isIdentifierToken(token) {
270
+ if (token == void 0) return false;
271
+ if (token.tokenType != 0 /* IDENTIFIER */ && token.tokenType != 1 /* WILDCARD */) return false;
272
+ if (!token.value) return false;
273
+ if (!(token.value in supportedIdentifiers) && token.value != "*") {
274
+ throw new Error("Unsupported identifier: " + token.value);
275
+ }
276
+ ;
277
+ return true;
278
+ }
279
+ var whitespace = " \n\r ";
280
+ function isCharacter(charcode) {
281
+ return charcode >= 65 && charcode <= 90 || charcode >= 97 && charcode <= 122;
282
+ }
283
+ function isInteger(charcode) {
284
+ return charcode >= 48 && charcode <= 57;
285
+ }
286
+ function tokenize(input) {
287
+ let s = 0;
288
+ const result = [];
289
+ while (s < input.length) {
290
+ while (whitespace.includes(input[s])) s++;
291
+ if (s >= input.length) break;
292
+ if (input[s] == "/") {
293
+ if (input[s + 1] == "/") {
294
+ result.push({ tokenType: 2 /* DESCENDANT */ });
295
+ s += 2;
296
+ continue;
297
+ }
298
+ result.push({ tokenType: 3 /* CHILD */ });
299
+ s++;
300
+ continue;
301
+ }
302
+ if (input[s] == ":") {
303
+ result.push({ tokenType: 9 /* ATTRIBUTESELECTOR */ });
304
+ s++;
305
+ continue;
306
+ }
307
+ if (input[s] == "$" && input[s + 1] == "$") {
308
+ result.push({ tokenType: 10 /* RESOLVESELECTOR */ });
309
+ s += 2;
310
+ continue;
311
+ }
312
+ if (input[s] == "$") {
313
+ result.push({ tokenType: 11 /* BINDINGSELECTOR */ });
314
+ s++;
315
+ continue;
316
+ }
317
+ if (input[s] == "[") {
318
+ result.push({ tokenType: 12 /* FILTERBEGIN */ });
319
+ s++;
320
+ continue;
321
+ }
322
+ if (input[s] == "]") {
323
+ result.push({ tokenType: 13 /* FILTEREND */ });
324
+ s++;
325
+ continue;
326
+ }
327
+ if (input[s] == ",") {
328
+ result.push({ tokenType: 14 /* SEPARATOR */ });
329
+ s++;
330
+ continue;
331
+ }
332
+ if (input[s] == "(") {
333
+ result.push({ tokenType: 15 /* PARAMETERSBEGIN */ });
334
+ s++;
335
+ continue;
336
+ }
337
+ if (input[s] == "f" && input[s + 1] == "n" && input[s + 2] == ":") {
338
+ result.push({ tokenType: 17 /* FUNCTION */ });
339
+ s += 3;
340
+ continue;
341
+ }
342
+ if (input[s] == ")") {
343
+ result.push({ tokenType: 16 /* PARAMETERSEND */ });
344
+ s++;
345
+ continue;
346
+ }
347
+ if (input[s] == "&" && input[s + 1] == "&") {
348
+ result.push({ tokenType: 5 /* AND */ });
349
+ s += 2;
350
+ continue;
351
+ }
352
+ if (input[s] == "|" && input[s + 1] == "|") {
353
+ result.push({ tokenType: 6 /* OR */ });
354
+ s += 2;
355
+ continue;
356
+ }
357
+ if (input[s] == "=" && input[s + 1] == "=") {
358
+ result.push({ tokenType: 7 /* EQUALS */ });
359
+ s += 2;
360
+ continue;
361
+ }
362
+ if (input[s] == "'" || input[s] == '"') {
363
+ const begin = input[s];
364
+ const start = s;
365
+ s++;
366
+ while (s < input.length && input[s] != begin) s++;
367
+ result.push({ tokenType: 8 /* LITERAL */, value: input.slice(start + 1, s) });
368
+ s++;
369
+ continue;
370
+ }
371
+ if (input[s] == "." && input[s + 1] == ".") {
372
+ result.push({ tokenType: 4 /* PARENT */ });
373
+ s += 2;
374
+ continue;
375
+ }
376
+ if (input[s] == "*") {
377
+ result.push({ tokenType: 1 /* WILDCARD */, value: "*" });
378
+ s++;
379
+ continue;
380
+ }
381
+ const charCode = input.charCodeAt(s);
382
+ if (isCharacter(charCode)) {
383
+ const start = s;
384
+ while (s < input.length && isCharacter(input.charCodeAt(s))) s++;
385
+ result.push({ tokenType: 0 /* IDENTIFIER */, value: input.slice(start, s) });
386
+ continue;
387
+ }
388
+ if (isInteger(charCode)) {
389
+ const start = s;
390
+ while (s < input.length && isInteger(input.charCodeAt(s))) s++;
391
+ result.push({ tokenType: 8 /* LITERAL */, value: input.slice(start, s) });
392
+ continue;
393
+ }
394
+ throw new Error("Unexpected token: " + input[s]);
395
+ }
396
+ return result;
397
+ }
398
+ function buildFilter(tokens) {
399
+ log?.debug("BUILD FILTER", tokens);
400
+ tokens.shift();
401
+ const p = buildTree(tokens);
402
+ const next = tokens[0];
403
+ if (next.tokenType == 5 /* AND */) {
404
+ return {
405
+ type: NodeType.AND,
406
+ left: p,
407
+ right: buildFilter(tokens)
408
+ };
409
+ }
410
+ if (next.tokenType == 6 /* OR */) {
411
+ return {
412
+ type: NodeType.OR,
413
+ left: p,
414
+ right: buildFilter(tokens)
415
+ };
416
+ }
417
+ if (next.tokenType == 7 /* EQUALS */) {
418
+ const right = buildFilter(tokens);
419
+ if (right.type == NodeType.OR || right.type == NodeType.AND) {
420
+ return {
421
+ type: right.type,
422
+ left: {
423
+ type: NodeType.EQUALS,
424
+ left: p,
425
+ right: right.left
426
+ },
427
+ right: right.right
428
+ };
429
+ }
430
+ if (right.type == NodeType.EQUALS) throw new Error("Unexpected equals in equals");
431
+ return {
432
+ type: NodeType.EQUALS,
433
+ left: p,
434
+ right
435
+ };
436
+ }
437
+ if (next.tokenType == 13 /* FILTEREND */) {
438
+ tokens.shift();
439
+ return p;
440
+ }
441
+ throw new Error("Unexpected token in filter: " + next?.tokenType);
442
+ }
443
+ var subNodes = [3 /* CHILD */, 2 /* DESCENDANT */];
444
+ function buildTree(tokens) {
445
+ log?.debug("BUILD TREE", tokens);
446
+ if (tokens.length == 0) throw new Error("Unexpected end of input");
447
+ const token = tokens.shift();
448
+ if (token == void 0) throw new Error("Unexpected end of input");
449
+ if (token.tokenType == 4 /* PARENT */) {
450
+ return {
451
+ type: NodeType.PARENT,
452
+ child: buildTree(tokens)
453
+ };
454
+ }
455
+ if (subNodes.includes(token.tokenType)) {
456
+ let next = tokens.shift();
457
+ if (next?.tokenType == 17 /* FUNCTION */) {
458
+ const name = tokens.shift();
459
+ if (name == void 0 || name.tokenType != 0 /* IDENTIFIER */ || name.value == void 0 || typeof name.value != "string") throw new Error("Unexpected token: " + name?.tokenType + ". Expecting function name");
460
+ const value = name.value;
461
+ if (!isAvailableFunction(value)) {
462
+ throw new Error("Unsupported function: " + name.value);
463
+ }
464
+ return buildFunctionCall(value, tokens);
465
+ }
466
+ if (next?.tokenType == 4 /* PARENT */) {
467
+ return { type: NodeType.PARENT, child: buildTree(tokens) };
468
+ }
469
+ const modifiers = [];
470
+ while (next && (next?.tokenType == 9 /* ATTRIBUTESELECTOR */ || next?.tokenType == 11 /* BINDINGSELECTOR */ || next?.tokenType == 10 /* RESOLVESELECTOR */)) {
471
+ modifiers.push(next);
472
+ next = tokens.shift();
473
+ }
474
+ const isAttribute = modifiers.some((m) => m.tokenType == 9 /* ATTRIBUTESELECTOR */);
475
+ const isBinding2 = modifiers.some((m) => m.tokenType == 11 /* BINDINGSELECTOR */);
476
+ const isResolve = modifiers.some((m) => m.tokenType == 10 /* RESOLVESELECTOR */);
477
+ if (isResolve && isBinding2) throw new Error("Cannot have both resolve and binding");
478
+ if (!next || !next.value || !isAttribute && !isIdentifierToken(next)) throw new Error("Unexpected or missing token: " + next?.tokenType);
479
+ const identifer = next.value;
480
+ let filter = void 0;
481
+ if (tokens.length > 0 && tokens[0].tokenType == 12 /* FILTERBEGIN */) {
482
+ filter = buildFilter(tokens);
483
+ log?.debug("FILTER", filter, tokens);
484
+ }
485
+ let child = void 0;
486
+ if (tokens.length > 0 && subNodes.includes(tokens[0].tokenType)) {
487
+ child = buildTree(tokens);
488
+ }
489
+ if (typeof identifer != "string") throw new Error("Identifier must be a string");
490
+ let nodeType = NodeType.CHILD;
491
+ if (token.tokenType == 2 /* DESCENDANT */) {
492
+ nodeType = NodeType.DESCENDANT;
493
+ } else if (token.tokenType != 3 /* CHILD */) {
494
+ throw new Error("Unexpected token:" + token.tokenType);
495
+ }
496
+ return {
497
+ type: nodeType,
498
+ value: identifer,
499
+ attribute: isAttribute,
500
+ binding: isBinding2,
501
+ resolve: isResolve,
502
+ filter,
503
+ child
504
+ };
505
+ }
506
+ if (token.tokenType == 8 /* LITERAL */) {
507
+ return {
508
+ type: NodeType.LITERAL,
509
+ value: token.value
510
+ };
511
+ }
512
+ throw new Error("Unexpected token: " + token.tokenType);
513
+ }
514
+ function buildFunctionCall(name, tokens) {
515
+ log?.debug("BUILD FUNCTION", name, tokens);
516
+ const parameters = [];
517
+ const next = tokens.shift();
518
+ if (next?.tokenType != 15 /* PARAMETERSBEGIN */) throw new Error("Unexpected token: " + next?.tokenType);
519
+ while (tokens.length > 0 && tokens[0].tokenType != 16 /* PARAMETERSEND */) {
520
+ parameters.push(buildTree(tokens));
521
+ if (tokens[0].tokenType == 14 /* SEPARATOR */) tokens.shift();
522
+ }
523
+ if (tokens.length == 0) throw new Error("Unexpected end of input");
524
+ tokens.shift();
525
+ return {
526
+ type: NodeType.FUNCTION,
527
+ function: name,
528
+ parameters
529
+ };
530
+ }
531
+ function parse(input) {
532
+ const tokens = tokenize(input);
533
+ const result = buildTree(tokens);
534
+ log?.debug("RESULT", result);
535
+ if (!result) throw new Error("No root element found");
536
+ return result;
537
+ }
538
+
539
+ // src/index.ts
540
+ import { parseScript } from "meriyah";
541
+
542
+ // src/utils.ts
543
+ function toArray(value) {
544
+ return Array.isArray(value) ? value : [value];
545
+ }
546
+ function isDefined(value) {
547
+ return value != void 0 && value != null;
548
+ }
549
+
550
+ // src/index.ts
551
+ var debugLogEnabled2 = false;
552
+ var log2 = debugLogEnabled2 ? {
553
+ debug: (...args) => {
554
+ console.debug(...args);
555
+ }
556
+ } : void 0;
557
+ var functions = {
558
+ "join": {
559
+ fn: (result) => {
560
+ if (result.length != 2) throw new Error("Invalid number of arugments for join");
561
+ const [values, separators] = result;
562
+ if (separators.length != 1) throw new Error("Invalid number of separators for join");
563
+ const separator = separators[0];
564
+ if (typeof separator != "string") throw new Error("Separator must be a string");
565
+ if (values.length == 0) return [];
566
+ return [values.join(separator)];
567
+ }
568
+ },
569
+ "concat": {
570
+ fn: (result) => {
571
+ const flattened = [];
572
+ for (let i = 0; i < result.length; i++) {
573
+ if (result[i].length === 0) return [];
574
+ for (let j = 0; j < result[i].length; j++) {
575
+ flattened.push(result[i][j]);
576
+ }
577
+ }
578
+ return [flattened.join("")];
579
+ }
580
+ },
581
+ "first": {
582
+ fn: (result) => {
583
+ if (result.length != 1) throw new Error("Invalid number of arugments for first");
584
+ if (result[0].length == 0) return [];
585
+ return [result[0][0]];
586
+ }
587
+ },
588
+ "nthchild": {
589
+ fn: (result) => {
590
+ if (result.length != 2) throw new Error("Invalid number of arguments for nthchild");
591
+ if (result[1].length != 1) throw new Error("Invalid number of arguments for nthchild");
592
+ const x = result[1][0];
593
+ const number = typeof x == "number" ? x : parseInt(x);
594
+ return [result[0][number]];
595
+ }
596
+ }
597
+ };
598
+ var functionNames = new Set(Object.keys(functions));
599
+ function isAvailableFunction(name) {
600
+ return functionNames.has(name);
601
+ }
602
+ function breadCrumb(path) {
603
+ if (!debugLogEnabled2) return "";
604
+ return {
605
+ //Using the toString trick here to avoid calculating the breadcrumb if debug logging is off
606
+ valueOf() {
607
+ if (path.parentPath == void 0) return "@" + path.node.type;
608
+ return breadCrumb(path.parentPath) + "." + (path.parentKey == path.key ? path.key : path.parentKey + "[" + path.key + "]") + "@" + path.node.type;
609
+ }
610
+ };
611
+ }
612
+ function createQuerier() {
613
+ const traverser = createTraverser();
614
+ const { getChildren, getPrimitiveChildren, getPrimitiveChildrenOrNodePaths, getBinding, createNodePath, traverse } = traverser;
615
+ function createFilter(filter, filterResult) {
616
+ if (filter.type == NodeType.AND || filter.type == NodeType.OR || filter.type == NodeType.EQUALS) {
617
+ return {
618
+ type: filter.type,
619
+ left: createFilter(filter.left, []),
620
+ right: createFilter(filter.right, [])
621
+ };
622
+ } else if (filter.type == NodeType.LITERAL) {
623
+ const r = [filter.value];
624
+ return {
625
+ node: filter,
626
+ result: r
627
+ };
628
+ }
629
+ return createFNode(filter, filterResult);
630
+ }
631
+ function createFNode(token, result) {
632
+ return {
633
+ node: token,
634
+ result
635
+ };
636
+ }
637
+ function addFilterChildrenToState(filter, state) {
638
+ if ("type" in filter && (filter.type == NodeType.AND || filter.type == NodeType.OR || filter.type == NodeType.EQUALS)) {
639
+ addFilterChildrenToState(filter.left, state);
640
+ addFilterChildrenToState(filter.right, state);
641
+ } else if ("node" in filter) {
642
+ if (filter.node.type == NodeType.CHILD) {
643
+ log2?.debug("ADDING FILTER CHILD", filter.node);
644
+ state.child[state.depth + 1].push(filter);
645
+ }
646
+ if (filter.node.type == NodeType.DESCENDANT) {
647
+ log2?.debug("ADDING FILTER DESCENDANT", filter.node);
648
+ state.descendant[state.depth + 1].push(filter);
649
+ }
650
+ }
651
+ }
652
+ function createFNodeAndAddToState(token, result, state) {
653
+ log2?.debug("ADDING FNODE", token);
654
+ const fnode = createFNode(token, result);
655
+ if (token.type == NodeType.CHILD) {
656
+ state.child[state.depth + 1].push(fnode);
657
+ } else if (token.type == NodeType.DESCENDANT) {
658
+ state.descendant[state.depth + 1].push(fnode);
659
+ }
660
+ return fnode;
661
+ }
662
+ function isMatch(fnode, path) {
663
+ if (fnode.node.attribute) {
664
+ const m2 = fnode.node.value == path.parentKey || fnode.node.value == path.key;
665
+ if (m2) log2?.debug("ATTR MATCH", fnode.node.value, breadCrumb(path));
666
+ return m2;
667
+ }
668
+ if (fnode.node.value == "*") {
669
+ return true;
670
+ }
671
+ const m = fnode.node.value == path.node.type;
672
+ if (m) log2?.debug("NODE MATCH", fnode.node.value, breadCrumb(path));
673
+ return m;
674
+ }
675
+ function addIfTokenMatch(fnode, path, state) {
676
+ if (!isMatch(fnode, path)) return;
677
+ state.matches[state.depth].push([fnode, path]);
678
+ if (fnode.node.filter) {
679
+ const filter = createFilter(fnode.node.filter, []);
680
+ const filteredResult = [];
681
+ const f = { filter, qNode: fnode.node, node: path.node, result: filteredResult };
682
+ state.filters[state.depth].push(f);
683
+ let fmap = state.filtersMap[state.depth].get(fnode.node);
684
+ if (!fmap) {
685
+ fmap = [];
686
+ state.filtersMap[state.depth].set(fnode.node, fmap);
687
+ }
688
+ fmap.push(f);
689
+ addFilterChildrenToState(filter, state);
690
+ const child = fnode.node.child;
691
+ if (child) {
692
+ if (child.type == NodeType.FUNCTION) {
693
+ const fr = addFunction(fnode, child, path, state);
694
+ state.functionCalls[state.depth].push(fr);
695
+ } else {
696
+ createFNodeAndAddToState(child, filteredResult, state);
697
+ }
698
+ }
699
+ } else {
700
+ const child = fnode.node.child;
701
+ if (child?.type == NodeType.FUNCTION) {
702
+ const fr = addFunction(fnode, child, path, state);
703
+ state.functionCalls[state.depth].push(fr);
704
+ } else if (child && !fnode.node.binding && !fnode.node.resolve) {
705
+ createFNodeAndAddToState(child, fnode.result, state);
706
+ }
707
+ }
708
+ }
709
+ function addFunction(rootNode, functionCall, path, state) {
710
+ const functionNode = { node: rootNode.node, functionCall, parameters: [], result: [] };
711
+ for (const param of functionCall.parameters) {
712
+ if (param.type == NodeType.LITERAL) {
713
+ functionNode.parameters.push({ node: param, result: [param.value] });
714
+ } else {
715
+ if (param.type == NodeType.FUNCTION) {
716
+ functionNode.parameters.push(addFunction(functionNode, param, path, state));
717
+ } else {
718
+ functionNode.parameters.push(createFNodeAndAddToState(param, [], state));
719
+ }
720
+ }
721
+ }
722
+ return functionNode;
723
+ }
724
+ function addPrimitiveAttributeIfMatch(fnode, path) {
725
+ if (!fnode.node.attribute || fnode.node.value == void 0) return;
726
+ if (fnode.node.child || fnode.node.filter) return;
727
+ if (!Object.hasOwn(path.node, fnode.node.value)) return;
728
+ const nodes = getPrimitiveChildren(fnode.node.value, path);
729
+ if (nodes.length == 0) return;
730
+ log2?.debug("PRIMITIVE", fnode.node.value, nodes);
731
+ fnode.result.push(...nodes);
732
+ }
733
+ function evaluateFilter(filter, path) {
734
+ log2?.debug("EVALUATING FILTER", filter, breadCrumb(path));
735
+ if ("type" in filter) {
736
+ if (filter.type == NodeType.AND) {
737
+ const left = evaluateFilter(filter.left, path);
738
+ if (left.length == 0) {
739
+ return [];
740
+ }
741
+ const r = evaluateFilter(filter.right, path);
742
+ return r;
743
+ }
744
+ if (filter.type == NodeType.OR) {
745
+ const left = evaluateFilter(filter.left, path);
746
+ if (left.length > 0) {
747
+ return left;
748
+ }
749
+ const r = evaluateFilter(filter.right, path);
750
+ return r;
751
+ }
752
+ if (filter.type == NodeType.EQUALS) {
753
+ const left = evaluateFilter(filter.left, path);
754
+ const right = evaluateFilter(filter.right, path);
755
+ if (right.length > 3) {
756
+ const rightSet = new Set(right);
757
+ const r2 = [];
758
+ for (let i = 0; i < left.length; i++) {
759
+ if (rightSet.has(left[i])) r2.push(left[i]);
760
+ }
761
+ return r2;
762
+ }
763
+ const r = [];
764
+ for (let i = 0; i < left.length; i++) {
765
+ if (right.includes(left[i])) r.push(left[i]);
766
+ }
767
+ return r;
768
+ }
769
+ throw new Error("Unknown filter type: " + filter.type);
770
+ }
771
+ if (filter.node.type == NodeType.PARENT) {
772
+ const r = resolveFilterWithParent(filter.node, path);
773
+ return r;
774
+ }
775
+ return filter.result;
776
+ }
777
+ function resolveBinding(path) {
778
+ if (!isIdentifier(path.node)) return void 0;
779
+ log2?.debug("RESOLVING BINDING FOR ", path.node);
780
+ const name = path.node.name;
781
+ if (name == void 0 || typeof name != "string") return void 0;
782
+ const binding = getBinding(path.scopeId, name);
783
+ if (!binding) return void 0;
784
+ log2?.debug("THIS IS THE BINDING", binding);
785
+ return binding.path;
786
+ }
787
+ function resolveFilterWithParent(node, path) {
788
+ let startNode = node;
789
+ let startPath = path;
790
+ while (startNode.type == NodeType.PARENT) {
791
+ if (!startNode.child) throw new Error("Parent filter must have child");
792
+ if (!startPath.parentPath) return [];
793
+ log2?.debug("STEP OUT", startNode, breadCrumb(startPath));
794
+ startNode = startNode.child;
795
+ startPath = startPath.parentPath;
796
+ }
797
+ return resolveDirectly(startNode, startPath);
798
+ }
799
+ let subQueryCounter = 0;
800
+ const memo = /* @__PURE__ */ new Map();
801
+ function resolveDirectly(node, path) {
802
+ let startNode = node;
803
+ const startPath = path;
804
+ let paths = [startPath];
805
+ while (startNode.attribute && startNode.type == NodeType.CHILD) {
806
+ const lookup = startNode.value;
807
+ if (!lookup) throw new Error("Selector must have a value");
808
+ const nodes = [];
809
+ for (let i = 0; i < paths.length; i++) {
810
+ const p = paths[i];
811
+ if (!isNodePath(p)) continue;
812
+ const arr = getPrimitiveChildrenOrNodePaths(lookup, p);
813
+ for (let j = 0; j < arr.length; j++) {
814
+ nodes.push(arr[j]);
815
+ }
816
+ }
817
+ if (nodes.length == 0) return [];
818
+ paths = nodes;
819
+ if (startNode.resolve) {
820
+ const resolved = [];
821
+ for (let i = 0; i < paths.length; i++) {
822
+ const p = paths[i];
823
+ if (!isNodePath(p)) continue;
824
+ const binding = resolveBinding(p);
825
+ if (!binding) continue;
826
+ const children = getChildren("init", binding);
827
+ for (let j = 0; j < children.length; j++) {
828
+ resolved.push(children[j]);
829
+ }
830
+ }
831
+ if (resolved.length > 0) paths = resolved;
832
+ } else if (startNode.binding) {
833
+ const bindings = [];
834
+ for (let i = 0; i < paths.length; i++) {
835
+ const p = paths[i];
836
+ if (!isNodePath(p)) continue;
837
+ const binding = resolveBinding(p);
838
+ if (binding) bindings.push(binding);
839
+ }
840
+ paths = bindings;
841
+ }
842
+ const filter = startNode.filter;
843
+ if (filter) {
844
+ const filtered = [];
845
+ for (let i = 0; i < paths.length; i++) {
846
+ const p = paths[i];
847
+ if (!isNodePath(p)) continue;
848
+ if (travHandle({ subquery: filter }, p).subquery.length > 0) {
849
+ filtered.push(p);
850
+ }
851
+ }
852
+ paths = filtered;
853
+ }
854
+ if (!startNode.child) {
855
+ const results = new Array(paths.length);
856
+ for (let i = 0; i < paths.length; i++) {
857
+ const p = paths[i];
858
+ results[i] = isPrimitive(p) ? p : p.node;
859
+ }
860
+ return results;
861
+ }
862
+ startNode = startNode.child;
863
+ }
864
+ const result = [];
865
+ for (const path2 of paths) {
866
+ if (isNodePath(path2)) {
867
+ if (memo.has(startNode) && memo.get(startNode).has(path2)) {
868
+ const cached = memo.get(startNode).get(path2);
869
+ for (let i = 0; i < cached.length; i++) {
870
+ result.push(cached[i]);
871
+ }
872
+ } else {
873
+ const subQueryKey = "subquery-" + subQueryCounter++;
874
+ const subQueryResult = travHandle({ [subQueryKey]: startNode }, path2)[subQueryKey];
875
+ if (!memo.has(startNode)) memo.set(startNode, /* @__PURE__ */ new Map());
876
+ memo.get(startNode)?.set(path2, subQueryResult);
877
+ for (let i = 0; i < subQueryResult.length; i++) {
878
+ result.push(subQueryResult[i]);
879
+ }
880
+ }
881
+ }
882
+ }
883
+ log2?.debug("DIRECT TRAV RESOLVE RESULT", result);
884
+ return result;
885
+ }
886
+ function addResultIfTokenMatch(fnode, path, state) {
887
+ const matchingFilters = [];
888
+ const filters = [];
889
+ const nodeFilters = state.filtersMap[state.depth].get(fnode.node);
890
+ if (nodeFilters) {
891
+ for (let i = 0; i < nodeFilters.length; i++) {
892
+ const f = nodeFilters[i];
893
+ if (f.qNode !== fnode.node) continue;
894
+ if (f.node !== path.node) continue;
895
+ filters.push(f);
896
+ }
897
+ for (let i = 0; i < filters.length; i++) {
898
+ const f = filters[i];
899
+ if (evaluateFilter(f.filter, path).length > 0) {
900
+ matchingFilters.push(f);
901
+ }
902
+ }
903
+ if (filters.length > 0 && matchingFilters.length == 0) return;
904
+ }
905
+ if (fnode.node.resolve) {
906
+ const binding = resolveBinding(path);
907
+ const resolved = binding ? getChildren("init", binding)[0] : void 0;
908
+ if (fnode.node.child) {
909
+ const result = resolveDirectly(fnode.node.child, resolved ?? path);
910
+ for (let i = 0; i < result.length; i++) {
911
+ fnode.result.push(result[i]);
912
+ }
913
+ } else {
914
+ fnode.result.push(path.node);
915
+ }
916
+ } else if (fnode.node.binding) {
917
+ const binding = resolveBinding(path);
918
+ if (binding) {
919
+ if (fnode.node.child) {
920
+ const result = resolveDirectly(fnode.node.child, binding);
921
+ for (let i = 0; i < result.length; i++) {
922
+ fnode.result.push(result[i]);
923
+ }
924
+ } else {
925
+ fnode.result.push(binding.node);
926
+ }
927
+ }
928
+ } else if (!fnode.node.child) {
929
+ fnode.result.push(path.node);
930
+ } else if (fnode.node.child.type == NodeType.FUNCTION) {
931
+ const functionCallResult = state.functionCalls[state.depth].find((f) => f.node == fnode.node);
932
+ if (!functionCallResult) throw new Error("Did not find expected function call for " + fnode.node.child.function);
933
+ resolveFunctionCalls(fnode, functionCallResult, path, state);
934
+ } else if (matchingFilters.length > 0) {
935
+ log2?.debug("HAS MATCHING FILTER", fnode.result.length, matchingFilters.length, breadCrumb(path));
936
+ for (let i = 0; i < matchingFilters.length; i++) {
937
+ const filterResult = matchingFilters[i].result;
938
+ for (let j = 0; j < filterResult.length; j++) {
939
+ fnode.result.push(filterResult[j]);
940
+ }
941
+ }
942
+ }
943
+ }
944
+ function resolveFunctionCalls(fnode, functionCallResult, path, state) {
945
+ const parameterResults = [];
946
+ for (let i = 0; i < functionCallResult.parameters.length; i++) {
947
+ const p = functionCallResult.parameters[i];
948
+ if ("parameters" in p) {
949
+ resolveFunctionCalls(p, p, path, state);
950
+ parameterResults.push(p.result);
951
+ } else {
952
+ parameterResults.push(p.result);
953
+ }
954
+ }
955
+ const functionResult = functions[functionCallResult.functionCall.function].fn(parameterResults);
956
+ log2?.debug("PARAMETER RESULTS", functionCallResult.functionCall.function, parameterResults, functionResult);
957
+ for (let i = 0; i < functionResult.length; i++) {
958
+ fnode.result.push(functionResult[i]);
959
+ }
960
+ }
961
+ function travHandle(queries, root) {
962
+ const results = {};
963
+ const queryKeys = Object.keys(queries);
964
+ for (let i = 0; i < queryKeys.length; i++) {
965
+ results[queryKeys[i]] = [];
966
+ }
967
+ const state = {
968
+ depth: 0,
969
+ child: [[], []],
970
+ descendant: [[], []],
971
+ filters: [[], []],
972
+ filtersMap: [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()],
973
+ matches: [[]],
974
+ functionCalls: [[]]
975
+ };
976
+ for (const [name, node] of Object.entries(queries)) {
977
+ createFNodeAndAddToState(node, results[name], state);
978
+ }
979
+ const childAtDepth = state.child[state.depth + 1];
980
+ for (let i = 0; i < childAtDepth.length; i++) {
981
+ addPrimitiveAttributeIfMatch(childAtDepth[i], root);
982
+ }
983
+ const descendantSlice = state.descendant.slice(0, state.depth + 1);
984
+ for (let i = 0; i < descendantSlice.length; i++) {
985
+ const fnodes = descendantSlice[i];
986
+ for (let j = 0; j < fnodes.length; j++) {
987
+ addPrimitiveAttributeIfMatch(fnodes[j], root);
988
+ }
989
+ }
990
+ traverse(root.node, {
991
+ enter(path, state2) {
992
+ state2.depth++;
993
+ state2.child.push([]);
994
+ state2.descendant.push([]);
995
+ state2.filters.push([]);
996
+ state2.filtersMap.push(/* @__PURE__ */ new Map());
997
+ state2.matches.push([]);
998
+ state2.functionCalls.push([]);
999
+ for (const fnode of state2.child[state2.depth]) {
1000
+ addIfTokenMatch(fnode, path, state2);
1001
+ }
1002
+ for (const fnodes of state2.descendant.slice(0, state2.depth + 1)) {
1003
+ for (const fnode of fnodes) {
1004
+ addIfTokenMatch(fnode, path, state2);
1005
+ }
1006
+ }
1007
+ },
1008
+ exit(path, state2) {
1009
+ log2?.debug("EXIT", breadCrumb(path));
1010
+ const childAtDepthPlusOne = state2.child[state2.depth + 1];
1011
+ for (let i = 0; i < childAtDepthPlusOne.length; i++) {
1012
+ addPrimitiveAttributeIfMatch(childAtDepthPlusOne[i], path);
1013
+ }
1014
+ for (let i = 0; i < state2.descendant.length; i++) {
1015
+ const fnodes = state2.descendant[i];
1016
+ for (let j = 0; j < fnodes.length; j++) {
1017
+ addPrimitiveAttributeIfMatch(fnodes[j], path);
1018
+ }
1019
+ }
1020
+ const matchesAtDepth = state2.matches[state2.depth];
1021
+ for (let i = 0; i < matchesAtDepth.length; i++) {
1022
+ addResultIfTokenMatch(matchesAtDepth[i][0], matchesAtDepth[i][1], state2);
1023
+ }
1024
+ state2.depth--;
1025
+ state2.child.pop();
1026
+ state2.descendant.pop();
1027
+ state2.filters.pop();
1028
+ state2.filtersMap.pop();
1029
+ state2.matches.pop();
1030
+ state2.functionCalls.pop();
1031
+ }
1032
+ }, root.scopeId, state, root);
1033
+ return results;
1034
+ }
1035
+ function beginHandle(queries, path) {
1036
+ const rootPath = createNodePath(path, void 0, void 0, void 0, void 0);
1037
+ const r = travHandle(queries, rootPath);
1038
+ memo.clear();
1039
+ return r;
1040
+ }
1041
+ return {
1042
+ beginHandle
1043
+ };
1044
+ }
1045
+ var defaultKey = "__default__";
1046
+ function query(code, query2, returnAST) {
1047
+ const result = multiQuery(code, { [defaultKey]: query2 }, returnAST);
1048
+ if (returnAST) {
1049
+ const r = result[defaultKey];
1050
+ r.__AST = result.__AST;
1051
+ return r;
1052
+ }
1053
+ return result[defaultKey];
1054
+ }
1055
+ function multiQuery(code, namedQueries, returnAST) {
1056
+ const start = Date.now();
1057
+ const ast = typeof code == "string" ? parseSource(code) : code;
1058
+ if (ast == null) throw new Error("Could not pase code");
1059
+ const queries = {};
1060
+ const entries = Object.entries(namedQueries);
1061
+ for (let i = 0; i < entries.length; i++) {
1062
+ const [name, queryStr] = entries[i];
1063
+ queries[name] = parse(queryStr);
1064
+ }
1065
+ const querier = createQuerier();
1066
+ const result = querier.beginHandle(queries, ast);
1067
+ log2?.debug("Query time: ", Date.now() - start);
1068
+ if (returnAST) {
1069
+ return { ...result, __AST: ast };
1070
+ }
1071
+ return result;
1072
+ }
1073
+ function parseSource(source, optimize = true) {
1074
+ const parsingOptions = optimize ? { loc: false, ranges: false } : { loc: true, ranges: true };
1075
+ try {
1076
+ return parseScript(source, { module: true, next: true, ...parsingOptions });
1077
+ } catch (e) {
1078
+ return parseScript(source, { module: false, next: true, ...parsingOptions, webcompat: true });
1079
+ }
1080
+ }
1081
+ function createTraverser() {
1082
+ let scopeIdCounter = 0;
1083
+ const scopes = /* @__PURE__ */ new Map();
1084
+ let removedScopes = 0;
1085
+ const nodePathsCreated = {};
1086
+ function createScope(parentScopeId) {
1087
+ const id = scopeIdCounter++;
1088
+ if (parentScopeId != void 0) {
1089
+ scopes.set(id, parentScopeId ?? -1);
1090
+ }
1091
+ return id;
1092
+ }
1093
+ function getBinding(scopeId, name) {
1094
+ let currentScope = scopes.get(scopeId);
1095
+ while (currentScope !== void 0) {
1096
+ if (typeof currentScope !== "number") {
1097
+ if (currentScope.bindings[name]) {
1098
+ return currentScope.bindings[name];
1099
+ }
1100
+ if (currentScope.parentScopeId === -1) break;
1101
+ currentScope = scopes.get(currentScope.parentScopeId);
1102
+ } else {
1103
+ if (currentScope === -1 || currentScope == void 0) break;
1104
+ currentScope = scopes.get(currentScope);
1105
+ }
1106
+ }
1107
+ return void 0;
1108
+ }
1109
+ function setBinding(scopeId, name, binding) {
1110
+ let scope = scopes.get(scopeId);
1111
+ if (typeof scope === "number" || scope === void 0) {
1112
+ scope = { bindings: {}, id: scopeId, parentScopeId: scope };
1113
+ scopes.set(scopeId, scope);
1114
+ }
1115
+ if (scope && typeof scope !== "number") {
1116
+ scope.bindings[name] = binding;
1117
+ }
1118
+ }
1119
+ let pathsCreated = 0;
1120
+ function getChildren(key, path) {
1121
+ if (key in path.node) {
1122
+ const r = path.node[key];
1123
+ if (Array.isArray(r)) {
1124
+ const len = r.length;
1125
+ const result = new Array(len);
1126
+ for (let i = 0; i < len; i++) {
1127
+ result[i] = createNodePath(r[i], i, key, path.scopeId, path.functionScopeId, path);
1128
+ }
1129
+ return result;
1130
+ } else if (r != void 0) {
1131
+ return [createNodePath(r, key, key, path.scopeId, path.functionScopeId, path)];
1132
+ }
1133
+ }
1134
+ return [];
1135
+ }
1136
+ function getPrimitiveChildren(key, path) {
1137
+ if (key in path.node) {
1138
+ const r = path.node[key];
1139
+ const arr = toArray(r);
1140
+ const result = [];
1141
+ for (let i = 0; i < arr.length; i++) {
1142
+ const item = arr[i];
1143
+ if (isDefined(item) && isPrimitive(item)) {
1144
+ result.push(item);
1145
+ }
1146
+ }
1147
+ return result;
1148
+ }
1149
+ return [];
1150
+ }
1151
+ function getPrimitiveChildrenOrNodePaths(key, path) {
1152
+ if (key in path.node) {
1153
+ const r = path.node[key];
1154
+ if (Array.isArray(r)) {
1155
+ const len = r.length;
1156
+ const result = new Array(len);
1157
+ for (let i = 0; i < len; i++) {
1158
+ const n = r[i];
1159
+ result[i] = isPrimitive(n) ? n : createNodePath(n, i, key, path.scopeId, path.functionScopeId, path);
1160
+ }
1161
+ return result;
1162
+ } else if (r != void 0) {
1163
+ return [
1164
+ isPrimitive(r) ? r : createNodePath(r, key, key, path.scopeId, path.functionScopeId, path)
1165
+ ];
1166
+ }
1167
+ }
1168
+ return [];
1169
+ }
1170
+ const nodePathMap = /* @__PURE__ */ new WeakMap();
1171
+ function createNodePath(node, key, parentKey, scopeId, functionScopeId, nodePath) {
1172
+ if (nodePathMap.has(node)) {
1173
+ const path2 = nodePathMap.get(node);
1174
+ if (nodePath && isExportSpecifier(nodePath.node) && key == "exported" && path2.key == "local") {
1175
+ path2.key = "exported";
1176
+ path2.parentPath = nodePath;
1177
+ return path2;
1178
+ }
1179
+ if (key != void 0) path2.key = typeof key == "number" ? key.toString() : key;
1180
+ if (parentKey != void 0) path2.parentKey = parentKey;
1181
+ if (nodePath != void 0) path2.parentPath = nodePath;
1182
+ return path2;
1183
+ }
1184
+ const finalScope = (node.extra && node.extra.scopeId != void 0 ? node.extra.scopeId : scopeId) ?? createScope();
1185
+ const finalFScope = (node.extra && node.extra.functionScopeId != void 0 ? node.extra.functionScopeId : functionScopeId) ?? finalScope;
1186
+ const path = {
1187
+ node,
1188
+ scopeId: finalScope,
1189
+ functionScopeId: finalFScope,
1190
+ parentPath: nodePath,
1191
+ key: typeof key == "number" ? key.toString() : key,
1192
+ parentKey
1193
+ };
1194
+ if (isNode(node)) {
1195
+ nodePathMap.set(node, path);
1196
+ }
1197
+ nodePathsCreated[node.type] = (nodePathsCreated[node.type] ?? 0) + 1;
1198
+ pathsCreated++;
1199
+ return path;
1200
+ }
1201
+ function registerBinding(stack, scopeId, functionScopeId, key, parentKey) {
1202
+ const node = stack[stack.length - 1];
1203
+ if (!isIdentifier(node)) return;
1204
+ const parentNode = stack[stack.length - 2];
1205
+ if (isAssignmentExpression(parentNode) || isMemberExpression(parentNode) || isUpdateExpression(parentNode) || isExportSpecifier(parentNode)) return;
1206
+ const grandParentNode = stack[stack.length - 3];
1207
+ if (!isBinding(node, parentNode, grandParentNode)) return;
1208
+ if (key == "id" && !isVariableDeclarator(parentNode)) {
1209
+ setBinding(functionScopeId, node.name, { path: createNodePath(node, void 0, void 0, scopeId, functionScopeId) });
1210
+ return;
1211
+ }
1212
+ if (isVariableDeclarator(parentNode) && isVariableDeclaration(grandParentNode)) {
1213
+ if (grandParentNode.kind == "var") {
1214
+ setBinding(functionScopeId, node.name, { path: createNodePath(parentNode, void 0, void 0, scopeId, functionScopeId) });
1215
+ return;
1216
+ } else {
1217
+ setBinding(scopeId, node.name, { path: createNodePath(parentNode, void 0, void 0, scopeId, functionScopeId) });
1218
+ return;
1219
+ }
1220
+ }
1221
+ if (isScope(node, parentNode)) {
1222
+ setBinding(scopeId, node.name, { path: createNodePath(node, key, parentKey, scopeId, functionScopeId) });
1223
+ }
1224
+ }
1225
+ let bindingNodesVisited = 0;
1226
+ function registerBindings(stack, scopeId, functionScopeId) {
1227
+ const node = stack[stack.length - 1];
1228
+ if (!isNode(node)) return;
1229
+ if (node.extra?.scopeId != void 0) return;
1230
+ node.extra = node.extra ?? {};
1231
+ node.extra.scopeId = scopeId;
1232
+ bindingNodesVisited++;
1233
+ const keys = VISITOR_KEYS[node.type];
1234
+ if (keys.length == 0) return;
1235
+ let childScopeId = scopeId;
1236
+ if (isScopable(node)) {
1237
+ childScopeId = createScope(scopeId);
1238
+ }
1239
+ for (let keyIdx = 0; keyIdx < keys.length; keyIdx++) {
1240
+ const key = keys[keyIdx];
1241
+ const childNodes = node[key];
1242
+ const children = toArray(childNodes);
1243
+ for (let i = 0; i < children.length; i++) {
1244
+ const child = children[i];
1245
+ if (!isDefined(child) || !isNode(child)) continue;
1246
+ const f = key === "body" && (isFunctionDeclaration(node) || isFunctionExpression(node)) ? childScopeId : functionScopeId;
1247
+ stack.push(child);
1248
+ if (isIdentifier(child)) {
1249
+ const k = Array.isArray(childNodes) ? i : key;
1250
+ registerBinding(stack, childScopeId, f, k, key);
1251
+ } else {
1252
+ registerBindings(stack, childScopeId, f);
1253
+ }
1254
+ stack.pop();
1255
+ }
1256
+ }
1257
+ if (childScopeId != scopeId && typeof scopes.get(childScopeId) == "number") {
1258
+ scopes.set(childScopeId, scopes.get(scopeId));
1259
+ removedScopes++;
1260
+ }
1261
+ }
1262
+ function traverseInner(node, visitor, scopeId, functionScopeId, state, path) {
1263
+ const nodePath = path ?? createNodePath(node, void 0, void 0, scopeId, functionScopeId);
1264
+ const keys = VISITOR_KEYS[node.type];
1265
+ if (nodePath.parentPath) {
1266
+ const stack = [];
1267
+ if (nodePath.parentPath.parentPath?.node) stack.push(nodePath.parentPath.parentPath.node);
1268
+ stack.push(nodePath.parentPath.node, nodePath.node);
1269
+ registerBindings(stack, nodePath.scopeId, nodePath.functionScopeId);
1270
+ }
1271
+ const stateTyped = state;
1272
+ const hasDescendantQueries = stateTyped.descendant && stateTyped.descendant.some((arr) => arr.length > 0);
1273
+ const hasChildQueriesAtNextDepth = stateTyped.child && stateTyped.child[stateTyped.depth + 1] && stateTyped.child[stateTyped.depth + 1].length > 0;
1274
+ if (!hasDescendantQueries && !hasChildQueriesAtNextDepth) {
1275
+ return;
1276
+ }
1277
+ for (let keyIdx = 0; keyIdx < keys.length; keyIdx++) {
1278
+ const key = keys[keyIdx];
1279
+ const childNodes = node[key];
1280
+ const children = Array.isArray(childNodes) ? childNodes : childNodes ? [childNodes] : [];
1281
+ const nodePaths = [];
1282
+ for (let i = 0; i < children.length; i++) {
1283
+ const child = children[i];
1284
+ if (isNode(child)) {
1285
+ const childPath = createNodePath(child, Array.isArray(childNodes) ? i : key, key, nodePath.scopeId, nodePath.functionScopeId, nodePath);
1286
+ nodePaths.push(childPath);
1287
+ }
1288
+ }
1289
+ for (let i = 0; i < nodePaths.length; i++) {
1290
+ const childPath = nodePaths[i];
1291
+ visitor.enter(childPath, state);
1292
+ traverseInner(childPath.node, visitor, nodePath.scopeId, nodePath.functionScopeId, state, childPath);
1293
+ visitor.exit(childPath, state);
1294
+ }
1295
+ }
1296
+ }
1297
+ const sOut = [];
1298
+ function traverse(node, visitor, scopeId, state, path) {
1299
+ const fscope = path?.functionScopeId ?? node.extra?.functionScopeId ?? scopeId;
1300
+ traverseInner(node, visitor, scopeId, fscope, state, path);
1301
+ if (!sOut.includes(scopeIdCounter)) {
1302
+ log2?.debug("Scopes created", scopeIdCounter, " Scopes removed", removedScopes, "Paths created", pathsCreated, bindingNodesVisited);
1303
+ sOut.push(scopeIdCounter);
1304
+ const k = Object.fromEntries(Object.entries(nodePathsCreated).sort((a, b) => a[1] - b[1]));
1305
+ log2?.debug("Node paths created", k);
1306
+ }
1307
+ }
1308
+ return {
1309
+ traverse,
1310
+ createNodePath,
1311
+ getChildren,
1312
+ getPrimitiveChildren,
1313
+ getPrimitiveChildrenOrNodePaths,
1314
+ getBinding
1315
+ };
1316
+ }
1317
+ export {
1318
+ createTraverser as default,
1319
+ functions,
1320
+ isAvailableFunction,
1321
+ multiQuery,
1322
+ parseSource,
1323
+ query
1324
+ };
1325
+ //# sourceMappingURL=index.mjs.map