@zaly/agent 0.0.5 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/{agent-BaD2kax9.mjs → agent-B7cQOuMZ.mjs} +2 -2
  2. package/dist/agent-B7cQOuMZ.mjs.map +1 -0
  3. package/dist/{agent-EkPynZRJ.mjs → agent-D3wVIibN.mjs} +4 -3
  4. package/dist/agent-D3wVIibN.mjs.map +1 -0
  5. package/dist/{compactions-3AjPqjeZ.mjs → compactions-B8VdZJoU.mjs} +2 -2
  6. package/dist/{compactions-3AjPqjeZ.mjs.map → compactions-B8VdZJoU.mjs.map} +1 -1
  7. package/dist/{edit-Qxl4w1C2.mjs → edit-D4yaBK1K.mjs} +9 -17
  8. package/dist/edit-D4yaBK1K.mjs.map +1 -0
  9. package/dist/{fetch-DknuSrSX.mjs → fetch-VKhSWdEh.mjs} +2 -2
  10. package/dist/{fetch-DknuSrSX.mjs.map → fetch-VKhSWdEh.mjs.map} +1 -1
  11. package/dist/{find-Bah9SKWX.mjs → find-CimUGn-L.mjs} +6 -20
  12. package/dist/find-CimUGn-L.mjs.map +1 -0
  13. package/dist/{grep-B4GF0svc.mjs → grep-6O3mjSvV.mjs} +10 -78
  14. package/dist/grep-6O3mjSvV.mjs.map +1 -0
  15. package/dist/index-node-esm-CJsN8G51.mjs +2116 -0
  16. package/dist/index-node-esm-CJsN8G51.mjs.map +1 -0
  17. package/dist/index.d.mts +25 -37
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +3 -953
  20. package/dist/{manager-f-WjFTMX.mjs → manager-BqlbCGYV.mjs} +12 -2
  21. package/dist/{manager-f-WjFTMX.mjs.map → manager-BqlbCGYV.mjs.map} +1 -1
  22. package/dist/{masker-Bv9KjkDF.mjs → masker-DRFztUwc.mjs} +2 -2
  23. package/dist/{masker-Bv9KjkDF.mjs.map → masker-DRFztUwc.mjs.map} +1 -1
  24. package/dist/{read-Djsx2NZl.mjs → read-CSL_8nAk.mjs} +47 -63
  25. package/dist/read-CSL_8nAk.mjs.map +1 -0
  26. package/dist/{registry-BVf0aZEA.mjs → registry-L9GDccS0.mjs} +89 -43
  27. package/dist/registry-L9GDccS0.mjs.map +1 -0
  28. package/dist/{session-Bv8JiT8P.mjs → session-BSvUrr12.mjs} +2 -2
  29. package/dist/{session-Bv8JiT8P.mjs.map → session-BSvUrr12.mjs.map} +1 -1
  30. package/dist/session.mjs +1 -1
  31. package/dist/src-fK6DL2bg.mjs +953 -0
  32. package/dist/src-fK6DL2bg.mjs.map +1 -0
  33. package/dist/{subagent-CX7Zjcws.mjs → subagent-C8XCEecM.mjs} +2 -2
  34. package/dist/{subagent-CX7Zjcws.mjs.map → subagent-C8XCEecM.mjs.map} +1 -1
  35. package/dist/{tools-Bl-YI890.mjs → tools-wvkkuXWH.mjs} +76 -20
  36. package/dist/tools-wvkkuXWH.mjs.map +1 -0
  37. package/dist/{write-D3L-92vj.mjs → write-DwGiDNeG.mjs} +3 -11
  38. package/dist/write-DwGiDNeG.mjs.map +1 -0
  39. package/package.json +12 -12
  40. package/dist/agent-BaD2kax9.mjs.map +0 -1
  41. package/dist/agent-EkPynZRJ.mjs.map +0 -1
  42. package/dist/edit-Qxl4w1C2.mjs.map +0 -1
  43. package/dist/find-Bah9SKWX.mjs.map +0 -1
  44. package/dist/grep-B4GF0svc.mjs.map +0 -1
  45. package/dist/index-node-esm-D6YQRKEz.mjs +0 -1537
  46. package/dist/index-node-esm-D6YQRKEz.mjs.map +0 -1
  47. package/dist/index.mjs.map +0 -1
  48. package/dist/read-Djsx2NZl.mjs.map +0 -1
  49. package/dist/registry-BVf0aZEA.mjs.map +0 -1
  50. package/dist/tools-Bl-YI890.mjs.map +0 -1
  51. package/dist/write-D3L-92vj.mjs.map +0 -1
@@ -0,0 +1,2116 @@
1
+ import vm from "node:vm";
2
+ //#region ../../node_modules/.bun/jsonpath-plus@11.2.1/node_modules/jsonpath-plus/dist/index-node-esm.js
3
+ /**
4
+ * @implements {IHooks}
5
+ */
6
+ var Hooks = class {
7
+ /**
8
+ * @callback HookCallback
9
+ * @this {*|Jsep} this
10
+ * @param {Jsep} env
11
+ * @returns: void
12
+ */
13
+ /**
14
+ * Adds the given callback to the list of callbacks for the given hook.
15
+ *
16
+ * The callback will be invoked when the hook it is registered for is run.
17
+ *
18
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
19
+ *
20
+ * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
21
+ * @param {HookCallback|boolean} callback The callback function which is given environment variables.
22
+ * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
23
+ * @public
24
+ */
25
+ add(name, callback, first) {
26
+ if (typeof arguments[0] != "string") for (let name in arguments[0]) this.add(name, arguments[0][name], arguments[1]);
27
+ else (Array.isArray(name) ? name : [name]).forEach(function(name) {
28
+ this[name] = this[name] || [];
29
+ if (callback) this[name][first ? "unshift" : "push"](callback);
30
+ }, this);
31
+ }
32
+ /**
33
+ * Runs a hook invoking all registered callbacks with the given environment variables.
34
+ *
35
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
36
+ *
37
+ * @param {string} name The name of the hook.
38
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
39
+ * @public
40
+ */
41
+ run(name, env) {
42
+ this[name] = this[name] || [];
43
+ this[name].forEach(function(callback) {
44
+ callback.call(env && env.context ? env.context : env, env);
45
+ });
46
+ }
47
+ };
48
+ /**
49
+ * @implements {IPlugins}
50
+ */
51
+ var Plugins = class {
52
+ constructor(jsep) {
53
+ this.jsep = jsep;
54
+ this.registered = {};
55
+ }
56
+ /**
57
+ * @callback PluginSetup
58
+ * @this {Jsep} jsep
59
+ * @returns: void
60
+ */
61
+ /**
62
+ * Adds the given plugin(s) to the registry
63
+ *
64
+ * @param {object} plugins
65
+ * @param {string} plugins.name The name of the plugin
66
+ * @param {PluginSetup} plugins.init The init function
67
+ * @public
68
+ */
69
+ register(...plugins) {
70
+ plugins.forEach((plugin) => {
71
+ if (typeof plugin !== "object" || !plugin.name || !plugin.init) throw new Error("Invalid JSEP plugin format");
72
+ if (this.registered[plugin.name]) return;
73
+ plugin.init(this.jsep);
74
+ this.registered[plugin.name] = plugin;
75
+ });
76
+ }
77
+ };
78
+ var Jsep = class Jsep {
79
+ /**
80
+ * @returns {string}
81
+ */
82
+ static get version() {
83
+ return "1.4.0";
84
+ }
85
+ /**
86
+ * @returns {string}
87
+ */
88
+ static toString() {
89
+ return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
90
+ }
91
+ /**
92
+ * @method addUnaryOp
93
+ * @param {string} op_name The name of the unary op to add
94
+ * @returns {Jsep}
95
+ */
96
+ static addUnaryOp(op_name) {
97
+ Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
98
+ Jsep.unary_ops[op_name] = 1;
99
+ return Jsep;
100
+ }
101
+ /**
102
+ * @method jsep.addBinaryOp
103
+ * @param {string} op_name The name of the binary op to add
104
+ * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
105
+ * @param {boolean} [isRightAssociative=false] whether operator is right-associative
106
+ * @returns {Jsep}
107
+ */
108
+ static addBinaryOp(op_name, precedence, isRightAssociative) {
109
+ Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
110
+ Jsep.binary_ops[op_name] = precedence;
111
+ if (isRightAssociative) Jsep.right_associative.add(op_name);
112
+ else Jsep.right_associative.delete(op_name);
113
+ return Jsep;
114
+ }
115
+ /**
116
+ * @method addIdentifierChar
117
+ * @param {string} char The additional character to treat as a valid part of an identifier
118
+ * @returns {Jsep}
119
+ */
120
+ static addIdentifierChar(char) {
121
+ Jsep.additional_identifier_chars.add(char);
122
+ return Jsep;
123
+ }
124
+ /**
125
+ * @method addLiteral
126
+ * @param {string} literal_name The name of the literal to add
127
+ * @param {*} literal_value The value of the literal
128
+ * @returns {Jsep}
129
+ */
130
+ static addLiteral(literal_name, literal_value) {
131
+ Jsep.literals[literal_name] = literal_value;
132
+ return Jsep;
133
+ }
134
+ /**
135
+ * @method removeUnaryOp
136
+ * @param {string} op_name The name of the unary op to remove
137
+ * @returns {Jsep}
138
+ */
139
+ static removeUnaryOp(op_name) {
140
+ delete Jsep.unary_ops[op_name];
141
+ if (op_name.length === Jsep.max_unop_len) Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
142
+ return Jsep;
143
+ }
144
+ /**
145
+ * @method removeAllUnaryOps
146
+ * @returns {Jsep}
147
+ */
148
+ static removeAllUnaryOps() {
149
+ Jsep.unary_ops = {};
150
+ Jsep.max_unop_len = 0;
151
+ return Jsep;
152
+ }
153
+ /**
154
+ * @method removeIdentifierChar
155
+ * @param {string} char The additional character to stop treating as a valid part of an identifier
156
+ * @returns {Jsep}
157
+ */
158
+ static removeIdentifierChar(char) {
159
+ Jsep.additional_identifier_chars.delete(char);
160
+ return Jsep;
161
+ }
162
+ /**
163
+ * @method removeBinaryOp
164
+ * @param {string} op_name The name of the binary op to remove
165
+ * @returns {Jsep}
166
+ */
167
+ static removeBinaryOp(op_name) {
168
+ delete Jsep.binary_ops[op_name];
169
+ if (op_name.length === Jsep.max_binop_len) Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
170
+ Jsep.right_associative.delete(op_name);
171
+ return Jsep;
172
+ }
173
+ /**
174
+ * @method removeAllBinaryOps
175
+ * @returns {Jsep}
176
+ */
177
+ static removeAllBinaryOps() {
178
+ Jsep.binary_ops = {};
179
+ Jsep.max_binop_len = 0;
180
+ return Jsep;
181
+ }
182
+ /**
183
+ * @method removeLiteral
184
+ * @param {string} literal_name The name of the literal to remove
185
+ * @returns {Jsep}
186
+ */
187
+ static removeLiteral(literal_name) {
188
+ delete Jsep.literals[literal_name];
189
+ return Jsep;
190
+ }
191
+ /**
192
+ * @method removeAllLiterals
193
+ * @returns {Jsep}
194
+ */
195
+ static removeAllLiterals() {
196
+ Jsep.literals = {};
197
+ return Jsep;
198
+ }
199
+ /**
200
+ * @returns {string}
201
+ */
202
+ get char() {
203
+ return this.expr.charAt(this.index);
204
+ }
205
+ /**
206
+ * @returns {number}
207
+ */
208
+ get code() {
209
+ return this.expr.charCodeAt(this.index);
210
+ }
211
+ /**
212
+ * @param {string} expr a string with the passed in express
213
+ * @returns Jsep
214
+ */
215
+ constructor(expr) {
216
+ this.expr = expr;
217
+ this.index = 0;
218
+ }
219
+ /**
220
+ * static top-level parser
221
+ * @returns {jsep.Expression}
222
+ */
223
+ static parse(expr) {
224
+ return new Jsep(expr).parse();
225
+ }
226
+ /**
227
+ * Get the longest key length of any object
228
+ * @param {object} obj
229
+ * @returns {number}
230
+ */
231
+ static getMaxKeyLen(obj) {
232
+ return Math.max(0, ...Object.keys(obj).map((k) => k.length));
233
+ }
234
+ /**
235
+ * `ch` is a character code in the next three functions
236
+ * @param {number} ch
237
+ * @returns {boolean}
238
+ */
239
+ static isDecimalDigit(ch) {
240
+ return ch >= 48 && ch <= 57;
241
+ }
242
+ /**
243
+ * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
244
+ * @param {string} op_val
245
+ * @returns {number}
246
+ */
247
+ static binaryPrecedence(op_val) {
248
+ return Jsep.binary_ops[op_val] || 0;
249
+ }
250
+ /**
251
+ * Looks for start of identifier
252
+ * @param {number} ch
253
+ * @returns {boolean}
254
+ */
255
+ static isIdentifierStart(ch) {
256
+ return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] || Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
257
+ }
258
+ /**
259
+ * @param {number} ch
260
+ * @returns {boolean}
261
+ */
262
+ static isIdentifierPart(ch) {
263
+ return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
264
+ }
265
+ /**
266
+ * throw error at index of the expression
267
+ * @param {string} message
268
+ * @throws
269
+ */
270
+ throwError(message) {
271
+ const error = /* @__PURE__ */ new Error(message + " at character " + this.index);
272
+ error.index = this.index;
273
+ error.description = message;
274
+ throw error;
275
+ }
276
+ /**
277
+ * Run a given hook
278
+ * @param {string} name
279
+ * @param {jsep.Expression|false} [node]
280
+ * @returns {?jsep.Expression}
281
+ */
282
+ runHook(name, node) {
283
+ if (Jsep.hooks[name]) {
284
+ const env = {
285
+ context: this,
286
+ node
287
+ };
288
+ Jsep.hooks.run(name, env);
289
+ return env.node;
290
+ }
291
+ return node;
292
+ }
293
+ /**
294
+ * Runs a given hook until one returns a node
295
+ * @param {string} name
296
+ * @returns {?jsep.Expression}
297
+ */
298
+ searchHook(name) {
299
+ if (Jsep.hooks[name]) {
300
+ const env = { context: this };
301
+ Jsep.hooks[name].find(function(callback) {
302
+ callback.call(env.context, env);
303
+ return env.node;
304
+ });
305
+ return env.node;
306
+ }
307
+ }
308
+ /**
309
+ * Push `index` up to the next non-space character
310
+ */
311
+ gobbleSpaces() {
312
+ let ch = this.code;
313
+ while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) ch = this.expr.charCodeAt(++this.index);
314
+ this.runHook("gobble-spaces");
315
+ }
316
+ /**
317
+ * Top-level method to parse all expressions and returns compound or single node
318
+ * @returns {jsep.Expression}
319
+ */
320
+ parse() {
321
+ this.runHook("before-all");
322
+ const nodes = this.gobbleExpressions();
323
+ const node = nodes.length === 1 ? nodes[0] : {
324
+ type: Jsep.COMPOUND,
325
+ body: nodes
326
+ };
327
+ return this.runHook("after-all", node);
328
+ }
329
+ /**
330
+ * top-level parser (but can be reused within as well)
331
+ * @param {number} [untilICode]
332
+ * @returns {jsep.Expression[]}
333
+ */
334
+ gobbleExpressions(untilICode) {
335
+ let nodes = [], ch_i, node;
336
+ while (this.index < this.expr.length) {
337
+ ch_i = this.code;
338
+ if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) this.index++;
339
+ else if (node = this.gobbleExpression()) nodes.push(node);
340
+ else if (this.index < this.expr.length) {
341
+ if (ch_i === untilICode) break;
342
+ this.throwError("Unexpected \"" + this.char + "\"");
343
+ }
344
+ }
345
+ return nodes;
346
+ }
347
+ /**
348
+ * The main parsing function.
349
+ * @returns {?jsep.Expression}
350
+ */
351
+ gobbleExpression() {
352
+ const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
353
+ this.gobbleSpaces();
354
+ return this.runHook("after-expression", node);
355
+ }
356
+ /**
357
+ * Search for the operation portion of the string (e.g. `+`, `===`)
358
+ * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
359
+ * and move down from 3 to 2 to 1 character until a matching binary operation is found
360
+ * then, return that binary operation
361
+ * @returns {string|boolean}
362
+ */
363
+ gobbleBinaryOp() {
364
+ this.gobbleSpaces();
365
+ let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
366
+ let tc_len = to_check.length;
367
+ while (tc_len > 0) {
368
+ if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
369
+ this.index += tc_len;
370
+ return to_check;
371
+ }
372
+ to_check = to_check.substr(0, --tc_len);
373
+ }
374
+ return false;
375
+ }
376
+ /**
377
+ * This function is responsible for gobbling an individual expression,
378
+ * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
379
+ * @returns {?jsep.BinaryExpression}
380
+ */
381
+ gobbleBinaryExpression() {
382
+ let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
383
+ left = this.gobbleToken();
384
+ if (!left) return left;
385
+ biop = this.gobbleBinaryOp();
386
+ if (!biop) return left;
387
+ biop_info = {
388
+ value: biop,
389
+ prec: Jsep.binaryPrecedence(biop),
390
+ right_a: Jsep.right_associative.has(biop)
391
+ };
392
+ right = this.gobbleToken();
393
+ if (!right) this.throwError("Expected expression after " + biop);
394
+ stack = [
395
+ left,
396
+ biop_info,
397
+ right
398
+ ];
399
+ while (biop = this.gobbleBinaryOp()) {
400
+ prec = Jsep.binaryPrecedence(biop);
401
+ if (prec === 0) {
402
+ this.index -= biop.length;
403
+ break;
404
+ }
405
+ biop_info = {
406
+ value: biop,
407
+ prec,
408
+ right_a: Jsep.right_associative.has(biop)
409
+ };
410
+ cur_biop = biop;
411
+ const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
412
+ while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
413
+ right = stack.pop();
414
+ biop = stack.pop().value;
415
+ left = stack.pop();
416
+ node = {
417
+ type: Jsep.BINARY_EXP,
418
+ operator: biop,
419
+ left,
420
+ right
421
+ };
422
+ stack.push(node);
423
+ }
424
+ node = this.gobbleToken();
425
+ if (!node) this.throwError("Expected expression after " + cur_biop);
426
+ stack.push(biop_info, node);
427
+ }
428
+ i = stack.length - 1;
429
+ node = stack[i];
430
+ while (i > 1) {
431
+ node = {
432
+ type: Jsep.BINARY_EXP,
433
+ operator: stack[i - 1].value,
434
+ left: stack[i - 2],
435
+ right: node
436
+ };
437
+ i -= 2;
438
+ }
439
+ return node;
440
+ }
441
+ /**
442
+ * An individual part of a binary expression:
443
+ * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
444
+ * @returns {boolean|jsep.Expression}
445
+ */
446
+ gobbleToken() {
447
+ let ch, to_check, tc_len, node;
448
+ this.gobbleSpaces();
449
+ node = this.searchHook("gobble-token");
450
+ if (node) return this.runHook("after-token", node);
451
+ ch = this.code;
452
+ if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) return this.gobbleNumericLiteral();
453
+ if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) node = this.gobbleStringLiteral();
454
+ else if (ch === Jsep.OBRACK_CODE) node = this.gobbleArray();
455
+ else {
456
+ to_check = this.expr.substr(this.index, Jsep.max_unop_len);
457
+ tc_len = to_check.length;
458
+ while (tc_len > 0) {
459
+ if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
460
+ this.index += tc_len;
461
+ const argument = this.gobbleToken();
462
+ if (!argument) this.throwError("missing unaryOp argument");
463
+ return this.runHook("after-token", {
464
+ type: Jsep.UNARY_EXP,
465
+ operator: to_check,
466
+ argument,
467
+ prefix: true
468
+ });
469
+ }
470
+ to_check = to_check.substr(0, --tc_len);
471
+ }
472
+ if (Jsep.isIdentifierStart(ch)) {
473
+ node = this.gobbleIdentifier();
474
+ if (Jsep.literals.hasOwnProperty(node.name)) node = {
475
+ type: Jsep.LITERAL,
476
+ value: Jsep.literals[node.name],
477
+ raw: node.name
478
+ };
479
+ else if (node.name === Jsep.this_str) node = { type: Jsep.THIS_EXP };
480
+ } else if (ch === Jsep.OPAREN_CODE) node = this.gobbleGroup();
481
+ }
482
+ if (!node) return this.runHook("after-token", false);
483
+ node = this.gobbleTokenProperty(node);
484
+ return this.runHook("after-token", node);
485
+ }
486
+ /**
487
+ * Gobble properties of of identifiers/strings/arrays/groups.
488
+ * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
489
+ * It also gobbles function calls:
490
+ * e.g. `Math.acos(obj.angle)`
491
+ * @param {jsep.Expression} node
492
+ * @returns {jsep.Expression}
493
+ */
494
+ gobbleTokenProperty(node) {
495
+ this.gobbleSpaces();
496
+ let ch = this.code;
497
+ while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
498
+ let optional;
499
+ if (ch === Jsep.QUMARK_CODE) {
500
+ if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) break;
501
+ optional = true;
502
+ this.index += 2;
503
+ this.gobbleSpaces();
504
+ ch = this.code;
505
+ }
506
+ this.index++;
507
+ if (ch === Jsep.OBRACK_CODE) {
508
+ node = {
509
+ type: Jsep.MEMBER_EXP,
510
+ computed: true,
511
+ object: node,
512
+ property: this.gobbleExpression()
513
+ };
514
+ if (!node.property) this.throwError("Unexpected \"" + this.char + "\"");
515
+ this.gobbleSpaces();
516
+ ch = this.code;
517
+ if (ch !== Jsep.CBRACK_CODE) this.throwError("Unclosed [");
518
+ this.index++;
519
+ } else if (ch === Jsep.OPAREN_CODE) node = {
520
+ type: Jsep.CALL_EXP,
521
+ "arguments": this.gobbleArguments(Jsep.CPAREN_CODE),
522
+ callee: node
523
+ };
524
+ else if (ch === Jsep.PERIOD_CODE || optional) {
525
+ if (optional) this.index--;
526
+ this.gobbleSpaces();
527
+ node = {
528
+ type: Jsep.MEMBER_EXP,
529
+ computed: false,
530
+ object: node,
531
+ property: this.gobbleIdentifier()
532
+ };
533
+ }
534
+ if (optional) node.optional = true;
535
+ this.gobbleSpaces();
536
+ ch = this.code;
537
+ }
538
+ return node;
539
+ }
540
+ /**
541
+ * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
542
+ * keep track of everything in the numeric literal and then calling `parseFloat` on that string
543
+ * @returns {jsep.Literal}
544
+ */
545
+ gobbleNumericLiteral() {
546
+ let number = "", ch, chCode;
547
+ while (Jsep.isDecimalDigit(this.code)) number += this.expr.charAt(this.index++);
548
+ if (this.code === Jsep.PERIOD_CODE) {
549
+ number += this.expr.charAt(this.index++);
550
+ while (Jsep.isDecimalDigit(this.code)) number += this.expr.charAt(this.index++);
551
+ }
552
+ ch = this.char;
553
+ if (ch === "e" || ch === "E") {
554
+ number += this.expr.charAt(this.index++);
555
+ ch = this.char;
556
+ if (ch === "+" || ch === "-") number += this.expr.charAt(this.index++);
557
+ while (Jsep.isDecimalDigit(this.code)) number += this.expr.charAt(this.index++);
558
+ if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) this.throwError("Expected exponent (" + number + this.char + ")");
559
+ }
560
+ chCode = this.code;
561
+ if (Jsep.isIdentifierStart(chCode)) this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
562
+ else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) this.throwError("Unexpected period");
563
+ return {
564
+ type: Jsep.LITERAL,
565
+ value: parseFloat(number),
566
+ raw: number
567
+ };
568
+ }
569
+ /**
570
+ * Parses a string literal, staring with single or double quotes with basic support for escape codes
571
+ * e.g. `"hello world"`, `'this is\nJSEP'`
572
+ * @returns {jsep.Literal}
573
+ */
574
+ gobbleStringLiteral() {
575
+ let str = "";
576
+ const startIndex = this.index;
577
+ const quote = this.expr.charAt(this.index++);
578
+ let closed = false;
579
+ while (this.index < this.expr.length) {
580
+ let ch = this.expr.charAt(this.index++);
581
+ if (ch === quote) {
582
+ closed = true;
583
+ break;
584
+ } else if (ch === "\\") {
585
+ ch = this.expr.charAt(this.index++);
586
+ switch (ch) {
587
+ case "n":
588
+ str += "\n";
589
+ break;
590
+ case "r":
591
+ str += "\r";
592
+ break;
593
+ case "t":
594
+ str += " ";
595
+ break;
596
+ case "b":
597
+ str += "\b";
598
+ break;
599
+ case "f":
600
+ str += "\f";
601
+ break;
602
+ case "v":
603
+ str += "\v";
604
+ break;
605
+ default: str += ch;
606
+ }
607
+ } else str += ch;
608
+ }
609
+ if (!closed) this.throwError("Unclosed quote after \"" + str + "\"");
610
+ return {
611
+ type: Jsep.LITERAL,
612
+ value: str,
613
+ raw: this.expr.substring(startIndex, this.index)
614
+ };
615
+ }
616
+ /**
617
+ * Gobbles only identifiers
618
+ * e.g.: `foo`, `_value`, `$x1`
619
+ * Also, this function checks if that identifier is a literal:
620
+ * (e.g. `true`, `false`, `null`) or `this`
621
+ * @returns {jsep.Identifier}
622
+ */
623
+ gobbleIdentifier() {
624
+ let ch = this.code, start = this.index;
625
+ if (Jsep.isIdentifierStart(ch)) this.index++;
626
+ else this.throwError("Unexpected " + this.char);
627
+ while (this.index < this.expr.length) {
628
+ ch = this.code;
629
+ if (Jsep.isIdentifierPart(ch)) this.index++;
630
+ else break;
631
+ }
632
+ return {
633
+ type: Jsep.IDENTIFIER,
634
+ name: this.expr.slice(start, this.index)
635
+ };
636
+ }
637
+ /**
638
+ * Gobbles a list of arguments within the context of a function call
639
+ * or array literal. This function also assumes that the opening character
640
+ * `(` or `[` has already been gobbled, and gobbles expressions and commas
641
+ * until the terminator character `)` or `]` is encountered.
642
+ * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
643
+ * @param {number} termination
644
+ * @returns {jsep.Expression[]}
645
+ */
646
+ gobbleArguments(termination) {
647
+ const args = [];
648
+ let closed = false;
649
+ let separator_count = 0;
650
+ while (this.index < this.expr.length) {
651
+ this.gobbleSpaces();
652
+ let ch_i = this.code;
653
+ if (ch_i === termination) {
654
+ closed = true;
655
+ this.index++;
656
+ if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) this.throwError("Unexpected token " + String.fromCharCode(termination));
657
+ break;
658
+ } else if (ch_i === Jsep.COMMA_CODE) {
659
+ this.index++;
660
+ separator_count++;
661
+ if (separator_count !== args.length) {
662
+ if (termination === Jsep.CPAREN_CODE) this.throwError("Unexpected token ,");
663
+ else if (termination === Jsep.CBRACK_CODE) for (let arg = args.length; arg < separator_count; arg++) args.push(null);
664
+ }
665
+ } else if (args.length !== separator_count && separator_count !== 0) this.throwError("Expected comma");
666
+ else {
667
+ const node = this.gobbleExpression();
668
+ if (!node || node.type === Jsep.COMPOUND) this.throwError("Expected comma");
669
+ args.push(node);
670
+ }
671
+ }
672
+ if (!closed) this.throwError("Expected " + String.fromCharCode(termination));
673
+ return args;
674
+ }
675
+ /**
676
+ * Responsible for parsing a group of things within parentheses `()`
677
+ * that have no identifier in front (so not a function call)
678
+ * This function assumes that it needs to gobble the opening parenthesis
679
+ * and then tries to gobble everything within that parenthesis, assuming
680
+ * that the next thing it should see is the close parenthesis. If not,
681
+ * then the expression probably doesn't have a `)`
682
+ * @returns {boolean|jsep.Expression}
683
+ */
684
+ gobbleGroup() {
685
+ this.index++;
686
+ let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
687
+ if (this.code === Jsep.CPAREN_CODE) {
688
+ this.index++;
689
+ if (nodes.length === 1) return nodes[0];
690
+ else if (!nodes.length) return false;
691
+ else return {
692
+ type: Jsep.SEQUENCE_EXP,
693
+ expressions: nodes
694
+ };
695
+ } else this.throwError("Unclosed (");
696
+ }
697
+ /**
698
+ * Responsible for parsing Array literals `[1, 2, 3]`
699
+ * This function assumes that it needs to gobble the opening bracket
700
+ * and then tries to gobble the expressions as arguments.
701
+ * @returns {jsep.ArrayExpression}
702
+ */
703
+ gobbleArray() {
704
+ this.index++;
705
+ return {
706
+ type: Jsep.ARRAY_EXP,
707
+ elements: this.gobbleArguments(Jsep.CBRACK_CODE)
708
+ };
709
+ }
710
+ };
711
+ const hooks = new Hooks();
712
+ Object.assign(Jsep, {
713
+ hooks,
714
+ plugins: new Plugins(Jsep),
715
+ COMPOUND: "Compound",
716
+ SEQUENCE_EXP: "SequenceExpression",
717
+ IDENTIFIER: "Identifier",
718
+ MEMBER_EXP: "MemberExpression",
719
+ LITERAL: "Literal",
720
+ THIS_EXP: "ThisExpression",
721
+ CALL_EXP: "CallExpression",
722
+ UNARY_EXP: "UnaryExpression",
723
+ BINARY_EXP: "BinaryExpression",
724
+ ARRAY_EXP: "ArrayExpression",
725
+ TAB_CODE: 9,
726
+ LF_CODE: 10,
727
+ CR_CODE: 13,
728
+ SPACE_CODE: 32,
729
+ PERIOD_CODE: 46,
730
+ COMMA_CODE: 44,
731
+ SQUOTE_CODE: 39,
732
+ DQUOTE_CODE: 34,
733
+ OPAREN_CODE: 40,
734
+ CPAREN_CODE: 41,
735
+ OBRACK_CODE: 91,
736
+ CBRACK_CODE: 93,
737
+ QUMARK_CODE: 63,
738
+ SEMCOL_CODE: 59,
739
+ COLON_CODE: 58,
740
+ unary_ops: {
741
+ "-": 1,
742
+ "!": 1,
743
+ "~": 1,
744
+ "+": 1
745
+ },
746
+ binary_ops: {
747
+ "||": 1,
748
+ "??": 1,
749
+ "&&": 2,
750
+ "|": 3,
751
+ "^": 4,
752
+ "&": 5,
753
+ "==": 6,
754
+ "!=": 6,
755
+ "===": 6,
756
+ "!==": 6,
757
+ "<": 7,
758
+ ">": 7,
759
+ "<=": 7,
760
+ ">=": 7,
761
+ "<<": 8,
762
+ ">>": 8,
763
+ ">>>": 8,
764
+ "+": 9,
765
+ "-": 9,
766
+ "*": 10,
767
+ "/": 10,
768
+ "%": 10,
769
+ "**": 11
770
+ },
771
+ right_associative: /* @__PURE__ */ new Set(["**"]),
772
+ additional_identifier_chars: /* @__PURE__ */ new Set(["$", "_"]),
773
+ literals: {
774
+ "true": true,
775
+ "false": false,
776
+ "null": null
777
+ },
778
+ this_str: "this"
779
+ });
780
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
781
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
782
+ const jsep = (expr) => new Jsep(expr).parse();
783
+ const stdClassProps = Object.getOwnPropertyNames(class Test {});
784
+ Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === void 0).forEach((m) => {
785
+ jsep[m] = Jsep[m];
786
+ });
787
+ jsep.Jsep = Jsep;
788
+ const CONDITIONAL_EXP = "ConditionalExpression";
789
+ jsep.plugins.register({
790
+ name: "ternary",
791
+ init(jsep) {
792
+ jsep.hooks.add("after-expression", function gobbleTernary(env) {
793
+ if (env.node && this.code === jsep.QUMARK_CODE) {
794
+ this.index++;
795
+ const test = env.node;
796
+ const consequent = this.gobbleExpression();
797
+ if (!consequent) this.throwError("Expected expression");
798
+ this.gobbleSpaces();
799
+ if (this.code === jsep.COLON_CODE) {
800
+ this.index++;
801
+ const alternate = this.gobbleExpression();
802
+ if (!alternate) this.throwError("Expected expression");
803
+ env.node = {
804
+ type: CONDITIONAL_EXP,
805
+ test,
806
+ consequent,
807
+ alternate
808
+ };
809
+ if (test.operator && jsep.binary_ops[test.operator] <= .9) {
810
+ let newTest = test;
811
+ while (newTest.right.operator && jsep.binary_ops[newTest.right.operator] <= .9) newTest = newTest.right;
812
+ env.node.test = newTest.right;
813
+ newTest.right = env.node;
814
+ env.node = test;
815
+ }
816
+ } else this.throwError("Expected :");
817
+ }
818
+ });
819
+ }
820
+ });
821
+ const FSLASH_CODE = 47;
822
+ const BSLASH_CODE = 92;
823
+ var index = {
824
+ name: "regex",
825
+ init(jsep) {
826
+ jsep.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
827
+ if (this.code === FSLASH_CODE) {
828
+ const patternIndex = ++this.index;
829
+ let inCharSet = false;
830
+ while (this.index < this.expr.length) {
831
+ if (this.code === FSLASH_CODE && !inCharSet) {
832
+ const pattern = this.expr.slice(patternIndex, this.index);
833
+ let flags = "";
834
+ while (++this.index < this.expr.length) {
835
+ const code = this.code;
836
+ if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) flags += this.char;
837
+ else break;
838
+ }
839
+ let value;
840
+ try {
841
+ value = new RegExp(pattern, flags);
842
+ } catch (e) {
843
+ this.throwError(e.message);
844
+ }
845
+ env.node = {
846
+ type: jsep.LITERAL,
847
+ value,
848
+ raw: this.expr.slice(patternIndex - 1, this.index)
849
+ };
850
+ env.node = this.gobbleTokenProperty(env.node);
851
+ return env.node;
852
+ }
853
+ if (this.code === jsep.OBRACK_CODE) inCharSet = true;
854
+ else if (inCharSet && this.code === jsep.CBRACK_CODE) inCharSet = false;
855
+ this.index += this.code === BSLASH_CODE ? 2 : 1;
856
+ }
857
+ this.throwError("Unclosed Regex");
858
+ }
859
+ });
860
+ }
861
+ };
862
+ const PLUS_CODE = 43;
863
+ const plugin = {
864
+ name: "assignment",
865
+ assignmentOperators: /* @__PURE__ */ new Set([
866
+ "=",
867
+ "*=",
868
+ "**=",
869
+ "/=",
870
+ "%=",
871
+ "+=",
872
+ "-=",
873
+ "<<=",
874
+ ">>=",
875
+ ">>>=",
876
+ "&=",
877
+ "^=",
878
+ "|=",
879
+ "||=",
880
+ "&&=",
881
+ "??="
882
+ ]),
883
+ updateOperators: [PLUS_CODE, 45],
884
+ assignmentPrecedence: .9,
885
+ init(jsep) {
886
+ const updateNodeTypes = [jsep.IDENTIFIER, jsep.MEMBER_EXP];
887
+ plugin.assignmentOperators.forEach((op) => jsep.addBinaryOp(op, plugin.assignmentPrecedence, true));
888
+ jsep.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
889
+ const code = this.code;
890
+ if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
891
+ this.index += 2;
892
+ env.node = {
893
+ type: "UpdateExpression",
894
+ operator: code === PLUS_CODE ? "++" : "--",
895
+ argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
896
+ prefix: true
897
+ };
898
+ if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) this.throwError(`Unexpected ${env.node.operator}`);
899
+ }
900
+ });
901
+ jsep.hooks.add("after-token", function gobbleUpdatePostfix(env) {
902
+ if (env.node) {
903
+ const code = this.code;
904
+ if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
905
+ if (!updateNodeTypes.includes(env.node.type)) this.throwError(`Unexpected ${env.node.operator}`);
906
+ this.index += 2;
907
+ env.node = {
908
+ type: "UpdateExpression",
909
+ operator: code === PLUS_CODE ? "++" : "--",
910
+ argument: env.node,
911
+ prefix: false
912
+ };
913
+ }
914
+ }
915
+ });
916
+ jsep.hooks.add("after-expression", function gobbleAssignment(env) {
917
+ if (env.node) updateBinariesToAssignments(env.node);
918
+ });
919
+ function updateBinariesToAssignments(node) {
920
+ if (plugin.assignmentOperators.has(node.operator)) {
921
+ node.type = "AssignmentExpression";
922
+ updateBinariesToAssignments(node.left);
923
+ updateBinariesToAssignments(node.right);
924
+ } else if (!node.operator) Object.values(node).forEach((val) => {
925
+ if (val && typeof val === "object") updateBinariesToAssignments(val);
926
+ });
927
+ }
928
+ }
929
+ };
930
+ /**
931
+ * @import {EvaluatedResult, UnknownResult} from './jsonpath.js';
932
+ */
933
+ /**
934
+ * @typedef {any} AssignmentExpression
935
+ */
936
+ /**
937
+ * @typedef {any} Substitution
938
+ */
939
+ /**
940
+ * @typedef {any} AnyParameter
941
+ */
942
+ /**
943
+ * @typedef {Record<string, Substitution>} Substitutions
944
+ */
945
+ jsep.plugins.register(index, plugin);
946
+ jsep.addUnaryOp("typeof");
947
+ jsep.addUnaryOp("void");
948
+ jsep.addLiteral("null", null);
949
+ jsep.addLiteral("undefined", void 0);
950
+ const BLOCKED_PROTO_PROPERTIES = /* @__PURE__ */ new Set([
951
+ "constructor",
952
+ "__proto__",
953
+ "__defineGetter__",
954
+ "__defineSetter__",
955
+ "__lookupGetter__",
956
+ "__lookupSetter__"
957
+ ]);
958
+ /** @type {WeakSet<object>} */
959
+ const BLOCKED_FUNCTIONS = new WeakSet([
960
+ Function,
961
+ function* () {}.constructor,
962
+ async function() {}.constructor,
963
+ async function* () {}.constructor,
964
+ Function.prototype.call,
965
+ Function.prototype.apply,
966
+ Function.prototype.bind,
967
+ Reflect.apply,
968
+ Reflect.construct,
969
+ ...[...BLOCKED_PROTO_PROPERTIES].map((name) => Reflect.get(Object.prototype, name)).filter((value) => typeof value === "function")
970
+ ]);
971
+ /**
972
+ * @param {UnknownResult} value
973
+ * @returns {boolean}
974
+ */
975
+ const isBlockedFunction = (value) => {
976
+ return typeof value === "function" && BLOCKED_FUNCTIONS.has(value);
977
+ };
978
+ /**
979
+ * Guarded `obj[prop]`, applying the same restrictions as a MemberExpression.
980
+ * @param {UnknownResult} obj
981
+ * @param {string} prop
982
+ * @returns {UnknownResult}
983
+ */
984
+ const getSafeProperty = (obj, prop) => {
985
+ if (obj === void 0 || obj === null) throw new TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
986
+ if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) throw new TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
987
+ const result = obj[prop];
988
+ if (isBlockedFunction(result)) throw new TypeError("Function constructor is disabled");
989
+ return result;
990
+ };
991
+ /**
992
+ * @typedef {Record<
993
+ * string,
994
+ * (a: AnyParameter, b: AnyParameter) => UnknownResult
995
+ * >} OperatorTable
996
+ */
997
+ const BINOPS = Object.assign(
998
+ Object.create(null),
999
+ /** @type {OperatorTable} */
1000
+ {
1001
+ "||": (a, b) => a || b(),
1002
+ "??": (a, b) => a ?? b(),
1003
+ "&&": (a, b) => a && b(),
1004
+ "|": (a, b) => a | b(),
1005
+ "^": (a, b) => a ^ b(),
1006
+ "&": (a, b) => a & b(),
1007
+ "==": (a, b) => a == b(),
1008
+ "!=": (a, b) => a != b(),
1009
+ "===": (a, b) => a === b(),
1010
+ "!==": (a, b) => a !== b(),
1011
+ "<": (a, b) => a < b(),
1012
+ ">": (a, b) => a > b(),
1013
+ "<=": (a, b) => a <= b(),
1014
+ ">=": (a, b) => a >= b(),
1015
+ "<<": (a, b) => a << b(),
1016
+ ">>": (a, b) => a >> b(),
1017
+ ">>>": (a, b) => a >>> b(),
1018
+ "+": (a, b) => a + b(),
1019
+ "-": (a, b) => a - b(),
1020
+ "*": (a, b) => a * b(),
1021
+ "/": (a, b) => a / b(),
1022
+ "%": (a, b) => a % b(),
1023
+ "**": (a, b) => a ** b()
1024
+ }
1025
+ );
1026
+ /**
1027
+ * @typedef {{
1028
+ * [key: string]: (a: AnyParameter) => UnknownResult
1029
+ * }} UnaryOperatorTable
1030
+ */
1031
+ const UNOPS = Object.assign(
1032
+ Object.create(null),
1033
+ /** @type {UnaryOperatorTable} */
1034
+ {
1035
+ "-": (a) => -a,
1036
+ "!": (a) => !a,
1037
+ "~": (a) => ~a,
1038
+ "+": (a) => +a,
1039
+ typeof: (a) => typeof a,
1040
+ void: () => void 0
1041
+ }
1042
+ );
1043
+ const SafeEval = {
1044
+ /**
1045
+ * @param {jsep.Expression} ast
1046
+ * @param {Substitutions} subs
1047
+ * @returns {UnknownResult}
1048
+ */
1049
+ evalAst(ast, subs) {
1050
+ switch (ast.type) {
1051
+ case "BinaryExpression":
1052
+ case "LogicalExpression": return SafeEval.evalBinaryExpression(
1053
+ /** @type {jsep.BinaryExpression} */
1054
+ ast,
1055
+ subs
1056
+ );
1057
+ case "Compound": return SafeEval.evalCompound(
1058
+ /** @type {jsep.Compound} */
1059
+ ast,
1060
+ subs
1061
+ );
1062
+ case "ConditionalExpression": return SafeEval.evalConditionalExpression(
1063
+ /** @type {jsep.ConditionalExpression} */
1064
+ ast,
1065
+ subs
1066
+ );
1067
+ case "Identifier": return SafeEval.evalIdentifier(
1068
+ /** @type {jsep.Identifier} */
1069
+ ast,
1070
+ subs
1071
+ );
1072
+ case "Literal": return SafeEval.evalLiteral(
1073
+ /** @type {jsep.Literal} */
1074
+ ast
1075
+ );
1076
+ case "MemberExpression": return SafeEval.evalMemberExpression(
1077
+ /** @type {jsep.MemberExpression} */
1078
+ ast,
1079
+ subs
1080
+ );
1081
+ case "UnaryExpression": return SafeEval.evalUnaryExpression(
1082
+ /** @type {jsep.UnaryExpression} */
1083
+ ast,
1084
+ subs
1085
+ );
1086
+ case "ArrayExpression": return SafeEval.evalArrayExpression(
1087
+ /** @type {jsep.ArrayExpression} */
1088
+ ast,
1089
+ subs
1090
+ );
1091
+ case "CallExpression": return SafeEval.evalCallExpression(
1092
+ /** @type {jsep.CallExpression} */
1093
+ ast,
1094
+ subs
1095
+ );
1096
+ case "AssignmentExpression": return SafeEval.evalAssignmentExpression(
1097
+ /** @type {AssignmentExpression} */
1098
+ ast,
1099
+ subs
1100
+ );
1101
+ default: throw new SyntaxError("Unexpected expression", { cause: ast });
1102
+ }
1103
+ },
1104
+ /**
1105
+ * @param {jsep.BinaryExpression} ast
1106
+ * @param {Substitutions} subs
1107
+ * @returns {UnknownResult}
1108
+ */
1109
+ evalBinaryExpression(ast, subs) {
1110
+ /* c8 ignore next 3 -- Defensive guard for malformed ASTs */
1111
+ if (!Object.hasOwn(BINOPS, ast.operator)) throw new SyntaxError(`Unknown binary operator: ${ast.operator}`);
1112
+ return BINOPS[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
1113
+ },
1114
+ /**
1115
+ * @param {jsep.Compound} ast
1116
+ * @param {Substitutions} subs
1117
+ * @returns {UnknownResult}
1118
+ */
1119
+ evalCompound(ast, subs) {
1120
+ let last;
1121
+ for (let i = 0; i < ast.body.length; i++) {
1122
+ if (ast.body[i].type === "Identifier" && [
1123
+ "var",
1124
+ "let",
1125
+ "const"
1126
+ ].includes(ast.body[i].name) && Object.hasOwn(ast.body, i + 1) && ast.body[i + 1].type === "AssignmentExpression") i += 1;
1127
+ const expr = ast.body[i];
1128
+ last = SafeEval.evalAst(expr, subs);
1129
+ }
1130
+ return last;
1131
+ },
1132
+ /**
1133
+ * @param {jsep.ConditionalExpression} ast
1134
+ * @param {Substitutions} subs
1135
+ * @returns {UnknownResult}
1136
+ */
1137
+ evalConditionalExpression(ast, subs) {
1138
+ return SafeEval.evalAst(ast.test, subs) ? SafeEval.evalAst(ast.consequent, subs) : SafeEval.evalAst(ast.alternate, subs);
1139
+ },
1140
+ /**
1141
+ * @param {jsep.Identifier} ast
1142
+ * @param {Substitutions} subs
1143
+ * @returns {UnknownResult}
1144
+ */
1145
+ evalIdentifier(ast, subs) {
1146
+ if (Object.hasOwn(subs, ast.name)) return subs[ast.name];
1147
+ throw new ReferenceError(`${ast.name} is not defined`);
1148
+ },
1149
+ /**
1150
+ * @param {jsep.Literal} ast
1151
+ * @returns {UnknownResult}
1152
+ */
1153
+ evalLiteral(ast) {
1154
+ return ast.value;
1155
+ },
1156
+ /**
1157
+ * @param {jsep.MemberExpression} ast
1158
+ * @param {Substitutions} subs
1159
+ * @returns {UnknownResult}
1160
+ */
1161
+ evalMemberExpression(ast, subs) {
1162
+ const prop = String(ast.computed ? SafeEval.evalAst(ast.property, subs) : ast.property.name);
1163
+ const obj = SafeEval.evalAst(ast.object, subs);
1164
+ const result = getSafeProperty(obj, prop);
1165
+ if (typeof result === "function") return result.bind(obj);
1166
+ return result;
1167
+ },
1168
+ /**
1169
+ * @param {jsep.UnaryExpression} ast
1170
+ * @param {Substitutions} subs
1171
+ * @returns {UnknownResult}
1172
+ */
1173
+ evalUnaryExpression(ast, subs) {
1174
+ /* c8 ignore next 3 -- Defensive guard for malformed ASTs */
1175
+ if (!Object.hasOwn(UNOPS, ast.operator)) throw new SyntaxError(`Unknown unary operator: ${ast.operator}`);
1176
+ const operand = SafeEval.evalAst(ast.argument, subs);
1177
+ return UNOPS[ast.operator](operand);
1178
+ },
1179
+ /**
1180
+ * @param {jsep.ArrayExpression} ast
1181
+ * @param {Substitutions} subs
1182
+ * @returns {UnknownResult}
1183
+ */
1184
+ evalArrayExpression(ast, subs) {
1185
+ return ast.elements.map((el) => SafeEval.evalAst(el, subs));
1186
+ },
1187
+ /**
1188
+ * @param {jsep.CallExpression} ast
1189
+ * @param {Substitutions} subs
1190
+ * @returns {UnknownResult}
1191
+ */
1192
+ evalCallExpression(ast, subs) {
1193
+ const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
1194
+ const func = SafeEval.evalAst(ast.callee, subs);
1195
+ if (isBlockedFunction(func) || args.some((arg) => isBlockedFunction(arg))) throw new Error("Function constructor is disabled");
1196
+ return func(...args);
1197
+ },
1198
+ /**
1199
+ * @param {AssignmentExpression} ast
1200
+ * @param {Substitutions} subs
1201
+ * @returns {UnknownResult}
1202
+ */
1203
+ evalAssignmentExpression(ast, subs) {
1204
+ if (ast.left.type !== "Identifier") throw new SyntaxError("Invalid left-hand side in assignment");
1205
+ const id = ast.left.name;
1206
+ subs[id] = SafeEval.evalAst(ast.right, subs);
1207
+ return subs[id];
1208
+ }
1209
+ };
1210
+ /**
1211
+ * A replacement for NodeJS' VM.Script which is also {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | Content Security Policy} friendly.
1212
+ */
1213
+ var SafeScript = class {
1214
+ /**
1215
+ * @param {string} expr Expression to evaluate
1216
+ */
1217
+ constructor(expr) {
1218
+ this.code = expr;
1219
+ this.ast = jsep(this.code);
1220
+ }
1221
+ /**
1222
+ * @param {object} context Object whose items will be added
1223
+ * to evaluation
1224
+ * @returns {EvaluatedResult} Result of evaluated code
1225
+ */
1226
+ runInNewContext(context) {
1227
+ const keyMap = Object.assign(Object.create(null), context);
1228
+ return SafeEval.evalAst(
1229
+ /** @type {jsep.Expression} */
1230
+ this.ast,
1231
+ keyMap
1232
+ );
1233
+ }
1234
+ };
1235
+ /**
1236
+ * @param {unknown} val
1237
+ */
1238
+ const toStringTag = (val) => {
1239
+ return Object.prototype.toString.call(val).slice(8, -1);
1240
+ };
1241
+ const scriptCache = /* @__PURE__ */ new Map();
1242
+ const pathCache = /* @__PURE__ */ new Map();
1243
+ /**
1244
+ * @typedef {any} AnyInput
1245
+ */
1246
+ /**
1247
+ * @typedef {((...args: any[]) => any)} SandboxCallback
1248
+ */
1249
+ /**
1250
+ * @typedef {any|SandboxCallback} SandboxPropertyValue
1251
+ */
1252
+ /**
1253
+ * @typedef {(string|number)[]} ExpressionArray
1254
+ */
1255
+ /**
1256
+ * @typedef {"scalar"|"boolean"|"string"|"undefined"
1257
+ * |"function"|"integer"|"number"|"nonFinite"|"object"
1258
+ * |"array"|"other"|"null"|"symbol"|"Promise"|"BigInt"
1259
+ * |"jsonReference"} ValueType
1260
+ */
1261
+ /**
1262
+ * @typedef {unknown} ParentValue
1263
+ */
1264
+ /**
1265
+ * @typedef {unknown} UnknownResult
1266
+ */
1267
+ /**
1268
+ * @typedef {string|number|null} ParentProperty
1269
+ */
1270
+ /**
1271
+ * @typedef {ReturnObject|string|number|boolean|null|unknown[]
1272
+ * |Record<string, unknown>} PreferredOutput
1273
+ */
1274
+ /**
1275
+ * Copies array and then pushes item into it.
1276
+ * @param {ExpressionArray} arr Array to copy and into which to push
1277
+ * @param {string|number} item Array item to add (to end)
1278
+ * @returns {ExpressionArray} Copy of the original array
1279
+ */
1280
+ function push(arr, item) {
1281
+ arr = arr.slice();
1282
+ arr.push(item);
1283
+ return arr;
1284
+ }
1285
+ /**
1286
+ * Copies array and then unshifts item into it.
1287
+ * @param {string|number} item Array item to add (to beginning)
1288
+ * @param {ExpressionArray} arr Array to copy and into which to unshift
1289
+ * @returns {ExpressionArray} Copy of the original array
1290
+ */
1291
+ function unshift(item, arr) {
1292
+ arr = arr.slice();
1293
+ arr.unshift(item);
1294
+ return arr;
1295
+ }
1296
+ /**
1297
+ * @typedef {object} ReturnObject
1298
+ * @property {ExpressionArray|string} path
1299
+ * @property {unknown} value
1300
+ * @property {ParentValue} parent
1301
+ * @property {ParentProperty} parentProperty
1302
+ * @property {boolean} [isParentSelector]
1303
+ * @property {boolean} [hasArrExpr]
1304
+ * @property {ExpressionArray} [expr]
1305
+ * @property {string} [pointer]
1306
+ */
1307
+ /**
1308
+ * @callback JSONPathCallback
1309
+ * @param {any} preferredOutput Using `any` type instead of `PreferredOutput` so
1310
+ * that user can supply flexible type
1311
+ * @param {"value"|"property"} type
1312
+ * @param {ReturnObject} fullRetObj
1313
+ * @returns {void}
1314
+ */
1315
+ /**
1316
+ * @callback OtherTypeCallback
1317
+ * @param {unknown} val
1318
+ * @param {ExpressionArray} path
1319
+ * @param {ParentValue} parent
1320
+ * @param {string|number|null} parentPropName
1321
+ * @param {string} arg
1322
+ * @returns {boolean|null}
1323
+ */
1324
+ /**
1325
+ * @typedef {any} ContextItem
1326
+ */
1327
+ /**
1328
+ * @typedef {any} EvaluatedResult
1329
+ */
1330
+ /**
1331
+ * @callback EvalCallback
1332
+ * @param {string} code
1333
+ * @param {ContextItem} context
1334
+ * @returns {EvaluatedResult}
1335
+ */
1336
+ /**
1337
+ * @typedef {new (expr: string) => {
1338
+ * runInNewContext: (context: object) => EvaluatedResult
1339
+ * }} ScriptConstructor
1340
+ */
1341
+ /**
1342
+ * @typedef {ScriptConstructor} EvalClass
1343
+ */
1344
+ /**
1345
+ * @typedef {"value"|"path"|"pointer"|"parent"|"parentProperty"
1346
+ * |"all"} ResultType
1347
+ */
1348
+ /**
1349
+ * @typedef {EvalCallback|EvalClass|'safe'|'native'|boolean} EvalValue
1350
+ */
1351
+ /**
1352
+ * @typedef {string|string[]} PathType
1353
+ */
1354
+ /**
1355
+ * @typedef {{Script: ScriptConstructor}} SafeScriptType
1356
+ */
1357
+ /**
1358
+ * @typedef {{Script: ScriptConstructor}} ScriptType
1359
+ */
1360
+ /**
1361
+ * @typedef {{
1362
+ * _$_path?: string,
1363
+ * _$_parentProperty?: ParentProperty,
1364
+ * _$_parent?: ParentValue,
1365
+ * _$_property?: string|number,
1366
+ * _$_root?: AnyInput,
1367
+ * _$_v?: unknown,
1368
+ * [key: string]: SandboxPropertyValue
1369
+ * }} SandboxType
1370
+ */
1371
+ /**
1372
+ * @typedef {object} JSONPathOptions
1373
+ * @property {AnyInput} [json]
1374
+ * @property {PathType} [path]
1375
+ * @property {ResultType} [resultType="value"]
1376
+ * @property {boolean} [flatten=false]
1377
+ * @property {boolean} [wrap=true]
1378
+ * @property {SandboxType} [sandbox={}]
1379
+ * @property {EvalValue} [eval='safe']
1380
+ * @property {any|null} [parent=null]
1381
+ * @property {ParentProperty} [parentProperty=null]
1382
+ * @property {JSONPathCallback} [callback]
1383
+ * @property {OtherTypeCallback} [otherTypeCallback] Defaults to
1384
+ * function which throws on encountering `@other`
1385
+ * @property {Record<string, OtherTypeCallback>} [customTypes] Map of
1386
+ * custom type operator names to their evaluation callbacks
1387
+ * @property {boolean} [autostart=true]
1388
+ * @property {boolean} [ignoreEvalErrors=false]
1389
+ */
1390
+ /**
1391
+ * @overload
1392
+ * @param {string} opts JSON path to evaluate
1393
+ * @param {AnyInput} [expr] JSON object to evaluate against
1394
+ * @param {JSONPathCallback} [obj] Passed 3 arguments: 1) desired
1395
+ * payload per `resultType`, 2) `"value"|"property"`, 3) Full returned
1396
+ * object with all payloads
1397
+ * @param {OtherTypeCallback} [callback] If `@other()` is at the
1398
+ * end of one's query, this will be invoked with the value of the item,
1399
+ * its path, its parent, and its parent's property name, and it should
1400
+ * return a boolean indicating whether the supplied value belongs to the
1401
+ * "other" type or not (or it may handle transformations and return
1402
+ * `false`).
1403
+ * @param {undefined} [otherTypeCallback]
1404
+ * @returns {unknown} The string form always has `autostart` implicitly
1405
+ * `true`, so the result is the evaluated value, not a `JSONPathClass`
1406
+ */
1407
+ /**
1408
+ * @overload
1409
+ * @param {JSONPathOptions & {autostart: false}} opts An options object
1410
+ * with `autostart` explicitly set to `false` defers evaluation and
1411
+ * returns the `JSONPathClass` instance instead
1412
+ * @returns {JSONPathClass}
1413
+ */
1414
+ /**
1415
+ * @overload
1416
+ * @param {JSONPathOptions} opts If a string, will be treated as
1417
+ * `expr`
1418
+ * @returns {unknown}
1419
+ */
1420
+ /**
1421
+ * @param {JSONPathOptions|string} opts If a string, will be treated as `expr`
1422
+ * @param {string|AnyInput} [expr] JSON path to evaluate
1423
+ * @param {AnyInput|JSONPathCallback} [obj] JSON object to evaluate against
1424
+ * @param {JSONPathCallback|OtherTypeCallback} [callback] Passed 3
1425
+ * arguments: 1) desired payload per `resultType`,
1426
+ * 2) `"value"|"property"`, 3) Full returned object with
1427
+ * all payloads
1428
+ * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the end
1429
+ * of one's query, this will be invoked with the value of the item, its
1430
+ * path, its parent, and its parent's property name, and it should return
1431
+ * a boolean indicating whether the supplied value belongs to the "other"
1432
+ * type or not (or it may handle transformations and return `false`).
1433
+ * @throws {Error}
1434
+ * @returns {unknown|JSONPathClass}
1435
+ */
1436
+ function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
1437
+ try {
1438
+ if (opts && typeof opts === "object") return new JSONPathClass(opts);
1439
+ return new JSONPathClass(
1440
+ opts,
1441
+ expr,
1442
+ /** @type {JSONPathCallback|undefined} */
1443
+ obj,
1444
+ /** @type {OtherTypeCallback|undefined} */
1445
+ callback,
1446
+ /** @type {undefined} */
1447
+ otherTypeCallback
1448
+ );
1449
+ } catch (e) {
1450
+ if (new.target) throw e;
1451
+ if (e && typeof e === "object" && "value" in e) return e.value;
1452
+ throw e;
1453
+ }
1454
+ }
1455
+ /**
1456
+ *
1457
+ */
1458
+ var JSONPathClass = class {
1459
+ /**
1460
+ * @overload
1461
+ * @param {string} opts JSON path to evaluate
1462
+ * @param {AnyInput} [expr] JSON object to evaluate against
1463
+ * @param {JSONPathCallback} [obj] Passed 3 arguments: 1) desired
1464
+ * payload per `resultType`, 2) `"value"|"property"`, 3) Full returned
1465
+ * object with all payloads
1466
+ * @param {OtherTypeCallback} [callback] If `@other()` is at the
1467
+ * end of one's query, this will be invoked with the value of the item,
1468
+ * its path, its parent, and its parent's property name, and it should
1469
+ * return a boolean indicating whether the supplied value belongs to the
1470
+ * "other" type or not (or it may handle transformations and return
1471
+ * `false`).
1472
+ * @param {undefined} [otherTypeCallback]
1473
+ */
1474
+ /**
1475
+ * @overload
1476
+ * @param {JSONPathOptions} opts If a string, will be treated as
1477
+ * `expr`
1478
+ */
1479
+ /**
1480
+ * @param {null|string|JSONPathOptions} opts If a string, will be treated as
1481
+ * `expr`
1482
+ * @param {string|AnyInput} [expr] JSON path to evaluate
1483
+ * @param {AnyInput|JSONPathCallback} [obj] JSON object to evaluate against
1484
+ * @param {JSONPathCallback|OtherTypeCallback} [callback] Passed 3
1485
+ * arguments: 1) desired payload per `resultType`,
1486
+ * 2) `"value"|"property"`, 3) Full returned
1487
+ * object with all payloads
1488
+ * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the
1489
+ * end of one's query, this will be invoked with the value of the item,
1490
+ * its path, its parent, and its parent's property name, and it should
1491
+ * return a boolean indicating whether the supplied value belongs to the
1492
+ * "other" type or not (or it may handle transformations and return
1493
+ * `false`).
1494
+ */
1495
+ constructor(opts, expr, obj, callback, otherTypeCallback) {
1496
+ if (typeof opts === "string") {
1497
+ otherTypeCallback = callback;
1498
+ callback = obj;
1499
+ obj = expr;
1500
+ expr = opts;
1501
+ opts = null;
1502
+ }
1503
+ const optObj = opts && typeof opts === "object";
1504
+ opts ||= (/** @type {JSONPathOptions} */ {});
1505
+ /** @type {ResultType|undefined} */
1506
+ this.currResultType = void 0;
1507
+ /** @type {EvalValue|undefined} */
1508
+ this.currEval = void 0;
1509
+ /** @type {OtherTypeCallback|undefined} */
1510
+ this.currOtherTypeCallback = void 0;
1511
+ /** @type {Record<string, OtherTypeCallback>|undefined} */
1512
+ this.currCustomTypes = void 0;
1513
+ /** @type {SandboxType|undefined} */
1514
+ this.currSandbox = void 0;
1515
+ this._hasParentSelector = false;
1516
+ this.json = opts.json || obj;
1517
+ this.path = opts.path || expr;
1518
+ this.resultType = opts.resultType || "value";
1519
+ this.flatten = Object.hasOwn(opts, "flatten") && opts.flatten;
1520
+ this.wrap = !Object.hasOwn(opts, "wrap") || opts.wrap;
1521
+ this.sandbox = opts.sandbox || {};
1522
+ this.eval = opts.eval === void 0 ? "safe" : opts.eval;
1523
+ this.ignoreEvalErrors = typeof opts.ignoreEvalErrors !== "undefined" && opts.ignoreEvalErrors;
1524
+ this.parent = Object.hasOwn(opts, "parent") ? opts.parent : null;
1525
+ this.parentProperty = Object.hasOwn(opts, "parentProperty") ? opts.parentProperty : null;
1526
+ this.callback = opts.callback || callback || null;
1527
+ this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
1528
+ throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.");
1529
+ };
1530
+ this.customTypes = opts.customTypes || {};
1531
+ if (opts.autostart === false) return;
1532
+ const args = (/** @type {JSONPathOptions} */ { path: optObj ? opts.path : expr });
1533
+ if (!optObj && obj !== void 0) args.json = obj;
1534
+ else if ("json" in opts) args.json = opts.json;
1535
+ const ret = this.evaluate(args);
1536
+ if (!ret || typeof ret !== "object") {
1537
+ const err = /* @__PURE__ */ new Error("JSONPath should not be called with \"new\" (it prevents return of (unwrapped) scalar values)");
1538
+ err.value = ret;
1539
+ throw err;
1540
+ }
1541
+ return ret;
1542
+ }
1543
+ /**
1544
+ * @overload
1545
+ * @param {JSONPathOptions} [expr]
1546
+ * @returns {ReturnObject|ReturnObject[]|undefined|unknown}
1547
+ */
1548
+ /**
1549
+ * @overload
1550
+ * @param {PathType|undefined} [expr]
1551
+ * @param {AnyInput} [json]
1552
+ * @param {JSONPathCallback|null} [callback]
1553
+ * @param {OtherTypeCallback} [otherTypeCallback]
1554
+ * @returns {ReturnObject|ReturnObject[]|undefined|unknown}
1555
+ */
1556
+ /**
1557
+ * @param {PathType|JSONPathOptions|undefined} [expr]
1558
+ * @param {AnyInput} [json]
1559
+ * @param {JSONPathCallback|null} [callback]
1560
+ * @param {OtherTypeCallback} [otherTypeCallback]
1561
+ * @returns {ReturnObject|ReturnObject[]|undefined|unknown}
1562
+ */
1563
+ evaluate(expr, json, callback, otherTypeCallback) {
1564
+ let currParent = this.parent, currParentProperty = this.parentProperty;
1565
+ let { flatten, wrap } = this;
1566
+ this.currResultType = this.resultType;
1567
+ this.currEval = this.eval;
1568
+ this.currSandbox = this.sandbox;
1569
+ callback ||= this.callback;
1570
+ this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
1571
+ this.currCustomTypes = this.customTypes;
1572
+ if (expr && typeof expr === "object" && !Array.isArray(expr)) {
1573
+ const exprObj = expr;
1574
+ if (!exprObj.path && exprObj.path !== "") throw new TypeError("You must supply a \"path\" property when providing an object argument to JSONPath.evaluate().");
1575
+ if (!Object.hasOwn(exprObj, "json")) throw new TypeError("You must supply a \"json\" property when providing an object argument to JSONPath.evaluate().");
1576
+ ({json} = exprObj);
1577
+ flatten = Object.hasOwn(exprObj, "flatten") ? exprObj.flatten : flatten;
1578
+ this.currResultType = Object.hasOwn(exprObj, "resultType") ? exprObj.resultType : this.currResultType;
1579
+ this.currSandbox = Object.hasOwn(exprObj, "sandbox") ? exprObj.sandbox : this.currSandbox;
1580
+ wrap = Object.hasOwn(exprObj, "wrap") ? exprObj.wrap : wrap;
1581
+ this.currEval = Object.hasOwn(exprObj, "eval") ? exprObj.eval : this.currEval;
1582
+ callback = Object.hasOwn(exprObj, "callback") ? exprObj.callback : callback;
1583
+ this.currOtherTypeCallback = Object.hasOwn(exprObj, "otherTypeCallback") ? exprObj.otherTypeCallback : this.currOtherTypeCallback;
1584
+ this.currCustomTypes = Object.hasOwn(exprObj, "customTypes") ? exprObj.customTypes : this.currCustomTypes;
1585
+ currParent = Object.hasOwn(exprObj, "parent") ? exprObj.parent : currParent;
1586
+ currParentProperty = Object.hasOwn(exprObj, "parentProperty") ? exprObj.parentProperty : currParentProperty;
1587
+ expr = exprObj.path;
1588
+ } else {
1589
+ json ||= this.json;
1590
+ expr ||= this.path;
1591
+ }
1592
+ currParent ||= null;
1593
+ currParentProperty ||= null;
1594
+ if (Array.isArray(expr)) expr = JSONPath.toPathString(expr);
1595
+ if (!json || !expr && expr !== "") return;
1596
+ const exprList = JSONPath.toPathArray(expr);
1597
+ if (exprList[0] === "$" && exprList.length > 1) exprList.shift();
1598
+ this._hasParentSelector = false;
1599
+ const traceResult = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback ?? void 0, void 0);
1600
+ /* c8 ignore next 2 -- Unreachable: _trace returns array when hasArrExpr set */
1601
+ const result = (Array.isArray(traceResult) ? traceResult : [traceResult]).filter((ea) => {
1602
+ return ea && !ea.isParentSelector;
1603
+ });
1604
+ if (!result.length)
1605
+ /* c8 ignore next -- Unreachable: valid queries always produce results */
1606
+ return wrap ? [] : void 0;
1607
+ if (!wrap && result.length === 1 && !result[0].hasArrExpr) return this._getPreferredOutput(result[0]);
1608
+ return result.reduce((rslt, ea) => {
1609
+ const valOrPath = this._getPreferredOutput(ea);
1610
+ if (flatten && Array.isArray(valOrPath)) rslt = rslt.concat(valOrPath);
1611
+ else rslt.push(valOrPath);
1612
+ return rslt;
1613
+ }, []);
1614
+ }
1615
+ /**
1616
+ * @param {ReturnObject} ea
1617
+ * @returns {PreferredOutput}
1618
+ */
1619
+ _getPreferredOutput(ea) {
1620
+ const resultType = this.currResultType;
1621
+ switch (resultType) {
1622
+ case "all": {
1623
+ const path = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
1624
+ ea.pointer = JSONPath.toPointer(
1625
+ /** @type {string[]} */
1626
+ path
1627
+ );
1628
+ ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(
1629
+ /** @type {string[]} */
1630
+ ea.path
1631
+ );
1632
+ return ea;
1633
+ }
1634
+ case "value":
1635
+ case "parent":
1636
+ case "parentProperty": return ea[resultType];
1637
+ case "path":
1638
+ if (typeof ea.path === "string") return ea.path;
1639
+ return JSONPath.toPathString(
1640
+ /** @type {string[]} */
1641
+ ea.path
1642
+ );
1643
+ case "pointer": {
1644
+ const pathArray = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
1645
+ return JSONPath.toPointer(
1646
+ /** @type {string[]} */
1647
+ pathArray
1648
+ );
1649
+ }
1650
+ default: throw new TypeError("Unknown result type");
1651
+ }
1652
+ }
1653
+ /**
1654
+ * @param {ReturnObject} fullRetObj
1655
+ * @param {JSONPathCallback|undefined} callback
1656
+ * @param {"value"|"property"} type
1657
+ * @returns {void}
1658
+ */
1659
+ _handleCallback(fullRetObj, callback, type) {
1660
+ if (!callback) return;
1661
+ const preferredOutput = this._getPreferredOutput(fullRetObj);
1662
+ if (Array.isArray(fullRetObj.path)) fullRetObj.path = JSONPath.toPathString(
1663
+ /** @type {string[]} */
1664
+ fullRetObj.path
1665
+ );
1666
+ callback(preferredOutput, type, fullRetObj);
1667
+ }
1668
+ /**
1669
+ *
1670
+ * @param {ExpressionArray} expr
1671
+ * @param {unknown} val
1672
+ * @param {ExpressionArray} path
1673
+ * @param {ParentValue} parent
1674
+ * @param {ParentProperty} parentPropName
1675
+ * @param {JSONPathCallback|undefined} callback
1676
+ * @param {boolean|undefined} hasArrExpr
1677
+ * @param {boolean} [literalPriority]
1678
+ * @returns {ReturnObject|ReturnObject[]}
1679
+ */
1680
+ _trace(expr, val, path, parent, parentPropName, callback, hasArrExpr, literalPriority) {
1681
+ let retObj;
1682
+ if (!expr.length) {
1683
+ retObj = {
1684
+ path,
1685
+ value: val,
1686
+ parent,
1687
+ parentProperty: parentPropName,
1688
+ hasArrExpr
1689
+ };
1690
+ this._handleCallback(retObj, callback, "value");
1691
+ return retObj;
1692
+ }
1693
+ const loc = expr[0], x = expr.slice(1);
1694
+ /** @type {ReturnObject[]} */
1695
+ const ret = [];
1696
+ /**
1697
+ *
1698
+ * @param {ReturnObject|ReturnObject[]} elems
1699
+ * @returns {void}
1700
+ */
1701
+ function addRet(elems) {
1702
+ if (Array.isArray(elems)) elems.forEach((t) => {
1703
+ ret.push(t);
1704
+ });
1705
+ else ret.push(elems);
1706
+ }
1707
+ if (val && (typeof loc !== "string" || literalPriority) && Object.hasOwn(
1708
+ val,
1709
+ /** @type {PropertyKey} */
1710
+ loc
1711
+ )) {
1712
+ const valObj = val;
1713
+ addRet(this._trace(
1714
+ x,
1715
+ valObj[loc],
1716
+ push(path, loc),
1717
+ val,
1718
+ /** @type {string|number} */
1719
+ loc,
1720
+ callback,
1721
+ hasArrExpr
1722
+ ));
1723
+ } else if (loc === "*") this._walk(val, (m) => {
1724
+ const valObj = val;
1725
+ addRet(this._trace(x, valObj[m], push(path, m), val, m, callback, true, true));
1726
+ });
1727
+ else if (loc === "..") {
1728
+ addRet(this._trace(x, val, path, parent, parentPropName, callback, hasArrExpr));
1729
+ this._walk(val, (m) => {
1730
+ const valObj = val;
1731
+ if (typeof valObj[m] === "object") addRet(this._trace(expr.slice(), valObj[m], push(path, m), val, m, callback, true));
1732
+ });
1733
+ } else if (loc === "^") {
1734
+ this._hasParentSelector = true;
1735
+ return (/** @type {ReturnObject} */ {
1736
+ path: path.slice(0, -1),
1737
+ expr: x,
1738
+ isParentSelector: true,
1739
+ value: void 0,
1740
+ parent: void 0,
1741
+ parentProperty: null
1742
+ });
1743
+ } else if (loc === "~") {
1744
+ retObj = {
1745
+ path: push(path, loc),
1746
+ value: parentPropName,
1747
+ parent,
1748
+ parentProperty: null
1749
+ };
1750
+ this._handleCallback(retObj, callback, "property");
1751
+ return retObj;
1752
+ } else if (loc === "$") addRet(this._trace(x, val, path, null, null, callback, hasArrExpr));
1753
+ else if (/^(-?\d*):(-?\d*):?(\d*)$/v.test(loc)) {
1754
+ const sliceResult = this._slice(loc, x, val, path, parent, parentPropName, callback);
1755
+ if (sliceResult) addRet(sliceResult);
1756
+ } else if (loc.indexOf("?(") === 0) {
1757
+ if (this.currEval === false) throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
1758
+ const safeLoc = loc.replace(/^\?\((.*?)\)$/v, "$1");
1759
+ const nested = /@.?([^?]*)[\['](\??\(.*?\))(?!.\)\])[\]']/gv.exec(safeLoc);
1760
+ if (nested) this._walk(val, (m) => {
1761
+ const npath = [nested[2]];
1762
+ const valObj2 = val;
1763
+ const nvalue = nested[1] ? getSafeProperty(valObj2[m], nested[1]) : valObj2[m];
1764
+ const filterResults = this._trace(npath, nvalue, path, parent, parentPropName, callback, true);
1765
+ if ((Array.isArray(filterResults) ? filterResults : [filterResults]).length > 0) addRet(this._trace(x, valObj2[m], push(path, m), val, m, callback, true));
1766
+ });
1767
+ else {
1768
+ const valObj3 = val;
1769
+ this._walk(val, (m) => {
1770
+ if (this._eval(safeLoc, valObj3[m], m, path, parent, parentPropName)) addRet(this._trace(x, valObj3[m], push(path, m), val, m, callback, true));
1771
+ });
1772
+ }
1773
+ } else if (loc[0] === "(") {
1774
+ if (this.currEval === false) throw new Error("Eval [(expr)] prevented in JSONPath expression.");
1775
+ const evalResult = this._eval(
1776
+ /** @type {string} */
1777
+ loc,
1778
+ val,
1779
+ /** @type {string|number} */
1780
+ path.at(-1),
1781
+ path.slice(0, -1),
1782
+ parent,
1783
+ parentPropName
1784
+ );
1785
+ const exprToUse = evalResult !== void 0 ? evalResult : "";
1786
+ addRet(this._trace(unshift(exprToUse, x), val, path, parent, parentPropName, callback, hasArrExpr));
1787
+ } else if (loc[0] === "@") {
1788
+ let addType = false;
1789
+ const parenthIndex = loc.indexOf("(");
1790
+ const valueType = loc.slice(1, parenthIndex);
1791
+ const lastParenth = loc.lastIndexOf(")");
1792
+ const argRaw = loc.slice(parenthIndex + 1, lastParenth);
1793
+ const arg = argRaw ? JSON.parse(argRaw) : void 0;
1794
+ switch (valueType) {
1795
+ case "scalar":
1796
+ addType = !val || !["object", "function"].includes(typeof val);
1797
+ break;
1798
+ case "boolean":
1799
+ case "string":
1800
+ case "undefined":
1801
+ case "function":
1802
+ addType = typeof val === valueType;
1803
+ break;
1804
+ case "integer":
1805
+ addType = Number.isFinite(val) && !(val % 1);
1806
+ break;
1807
+ case "number":
1808
+ addType = Number.isFinite(val);
1809
+ break;
1810
+ case "nonFinite":
1811
+ addType = typeof val === "number" && !Number.isFinite(val);
1812
+ break;
1813
+ case "object":
1814
+ addType = Boolean(val) && typeof val === valueType;
1815
+ break;
1816
+ case "array":
1817
+ addType = Array.isArray(val);
1818
+ break;
1819
+ case "other":
1820
+ addType = this.currOtherTypeCallback(val, path, parent, parentPropName, arg) || false;
1821
+ break;
1822
+ case "null":
1823
+ addType = val === null;
1824
+ break;
1825
+ case "symbol":
1826
+ addType = typeof val === "symbol";
1827
+ break;
1828
+ case "BigInt":
1829
+ addType = typeof val === "bigint";
1830
+ break;
1831
+ case "Promise":
1832
+ addType = toStringTag(val) === "Promise";
1833
+ break;
1834
+ case "jsonReference":
1835
+ addType = Boolean(val) && typeof val === "object" && Object.hasOwn(
1836
+ /** @type {object} */
1837
+ val,
1838
+ "$ref"
1839
+ );
1840
+ break;
1841
+ default: if (this.currCustomTypes && Object.hasOwn(this.currCustomTypes, valueType)) addType = this.currCustomTypes[valueType](val, path, parent, parentPropName, arg) || false;
1842
+ else throw new TypeError("Unknown value type " + valueType);
1843
+ }
1844
+ if (addType) {
1845
+ retObj = {
1846
+ path,
1847
+ value: val,
1848
+ parent,
1849
+ parentProperty: parentPropName
1850
+ };
1851
+ this._handleCallback(retObj, callback, "value");
1852
+ return retObj;
1853
+ }
1854
+ } else if (val && loc[0] === "`" && Object.hasOwn(val, loc.slice(1))) {
1855
+ const locProp = loc.slice(1);
1856
+ const valObj = val;
1857
+ addRet(this._trace(x, valObj[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));
1858
+ } else if (loc[0] === "'" || loc[0] === "\"") for (const [, single, double] of loc.matchAll(/'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"/gv)) {
1859
+ const prop = (single ?? double).replaceAll(/\\(['"\\])/gv, "$1");
1860
+ if (!val || !Object.hasOwn(val, prop)) continue;
1861
+ const valObj = val;
1862
+ addRet(this._trace(x, valObj[prop], push(path, prop), val, prop, callback, true));
1863
+ }
1864
+ else if (loc.includes(",")) {
1865
+ const parts = loc.split(",");
1866
+ for (const part of parts) addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback, true));
1867
+ } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
1868
+ const valObj = val;
1869
+ addRet(this._trace(x, valObj[loc], push(path, loc), val, loc, callback, hasArrExpr, true));
1870
+ }
1871
+ if (this._hasParentSelector) for (let t = 0; t < ret.length; t++) {
1872
+ const rett = ret[t];
1873
+ if (!rett || !rett.isParentSelector) continue;
1874
+ const exprToUse = rett.expr;
1875
+ const pathToUse = rett.path;
1876
+ const tmp = this._trace(exprToUse, val, pathToUse, parent, parentPropName, callback, hasArrExpr);
1877
+ if (Array.isArray(tmp)) {
1878
+ ret[t] = tmp[0];
1879
+ const tl = tmp.length;
1880
+ for (let tt = 1; tt < tl; tt++) {
1881
+ t++;
1882
+ ret.splice(t, 0, tmp[tt]);
1883
+ }
1884
+ } else ret[t] = tmp;
1885
+ }
1886
+ return ret;
1887
+ }
1888
+ /**
1889
+ * @param {unknown} val
1890
+ * @param {(prop: string|number) => void} f
1891
+ * @returns {void}
1892
+ */
1893
+ _walk(val, f) {
1894
+ if (Array.isArray(val)) {
1895
+ const n = val.length;
1896
+ for (let i = 0; i < n; i++) f(i);
1897
+ } else if (val && typeof val === "object") Object.keys(val).forEach((m) => {
1898
+ f(m);
1899
+ });
1900
+ }
1901
+ /**
1902
+ * @param {string} loc
1903
+ * @param {ExpressionArray} expr
1904
+ * @param {unknown} val
1905
+ * @param {ExpressionArray} path
1906
+ * @param {ParentValue} parent
1907
+ * @param {ParentProperty} parentPropName
1908
+ * @param {JSONPathCallback|undefined} callback
1909
+ * @returns {ReturnObject[]|undefined}
1910
+ */
1911
+ _slice(loc, expr, val, path, parent, parentPropName, callback) {
1912
+ if (!Array.isArray(val)) return;
1913
+ const len = val.length, parts = loc.split(":"), step = parts[2] && Number(parts[2]) || 1;
1914
+ let start = parts[0] && Number(parts[0]) || 0, end = parts[1] ? Number(parts[1]) : len;
1915
+ start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
1916
+ end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
1917
+ /** @type {ReturnObject[]} */
1918
+ const ret = [];
1919
+ for (let i = start; i < end; i += step) {
1920
+ const tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback, true);
1921
+ (Array.isArray(tmp) ? tmp : [tmp]).forEach((t) => {
1922
+ ret.push(t);
1923
+ });
1924
+ }
1925
+ return ret;
1926
+ }
1927
+ /**
1928
+ * @param {string} code
1929
+ * @param {unknown} _v
1930
+ * @param {string|number} _vname
1931
+ * @param {ExpressionArray} path
1932
+ * @param {ParentValue} parent
1933
+ * @param {ParentProperty} parentPropName
1934
+ * @returns {UnknownResult}
1935
+ */
1936
+ _eval(code, _v, _vname, path, parent, parentPropName) {
1937
+ if (this.currSandbox) {
1938
+ this.currSandbox._$_parentProperty = parentPropName;
1939
+ this.currSandbox._$_parent = parent;
1940
+ this.currSandbox._$_property = _vname;
1941
+ this.currSandbox._$_root = this.json;
1942
+ this.currSandbox._$_v = _v;
1943
+ }
1944
+ const containsPath = code.includes("@path");
1945
+ if (containsPath) {
1946
+ /* c8 ignore next -- Unreachable: currSandbox set in evaluate() before _eval */
1947
+ const currSandbox = this.currSandbox ?? {};
1948
+ currSandbox._$_path = JSONPath.toPathString(
1949
+ /** @type {string[]} */
1950
+ path.concat([_vname])
1951
+ );
1952
+ }
1953
+ const scriptCacheKey = this.currEval + "Script:" + code;
1954
+ if (!scriptCache.has(scriptCacheKey)) {
1955
+ let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|(?<=(?:^|[\(,=:\[!\|?\{\};+\-*%<>~^]|&)\s*)\/(?:\\.|\[(?:\\.|[^\]\\])*\]|[^\/\\\[])+\/[dgimsuvy]*)|@(?![\w$])/gv, (_, literal) => literal ?? "_$_v");
1956
+ if (containsPath) script = script.replaceAll("@path", "_$_path");
1957
+ const evalType = this.currEval;
1958
+ if ([
1959
+ "safe",
1960
+ true,
1961
+ void 0
1962
+ ].includes(evalType)) scriptCache.set(scriptCacheKey, new this.safeVm.Script(script));
1963
+ else if (this.currEval === "native") scriptCache.set(scriptCacheKey, new this.vm.Script(script));
1964
+ else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
1965
+ const CurrEval = this.currEval;
1966
+ scriptCache.set(scriptCacheKey, new CurrEval(script));
1967
+ } else if (typeof this.currEval === "function") {
1968
+ const evalFunc = this.currEval;
1969
+ scriptCache.set(scriptCacheKey, { runInNewContext: (context) => evalFunc(script, context) });
1970
+ } else throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
1971
+ }
1972
+ try {
1973
+ /**
1974
+ * @typedef {{
1975
+ * runInNewContext: (
1976
+ * ctx: SandboxType|undefined
1977
+ * ) => EvaluatedResult
1978
+ * }} RunInNewContext
1979
+ */
1980
+ return scriptCache.get(scriptCacheKey).runInNewContext(this.currSandbox);
1981
+ } catch (e) {
1982
+ if (this.ignoreEvalErrors) return false;
1983
+ throw new Error("jsonPath: " + e.message + ": " + code, { cause: e });
1984
+ }
1985
+ }
1986
+ };
1987
+ /** @type {{safeVm: SafeScriptType}} */
1988
+ JSONPathClass.prototype.safeVm = { Script: SafeScript };
1989
+ JSONPath.prototype = JSONPathClass.prototype;
1990
+ /**
1991
+ * Clears cached parsed paths and compiled scripts.
1992
+ * @returns {void}
1993
+ */
1994
+ JSONPath.clearCache = function() {
1995
+ pathCache.clear();
1996
+ scriptCache.clear();
1997
+ };
1998
+ /**
1999
+ * @param {string[]} pathArr Array to convert
2000
+ * @returns {string} The path string
2001
+ */
2002
+ JSONPath.toPathString = function(pathArr) {
2003
+ const x = pathArr, n = x.length;
2004
+ let p = "$";
2005
+ for (let i = 1; i < n; i++) if (!/^(~|\^|@.*?\(\))$/v.test(x[i])) p += /^[0-9*]+$/v.test(x[i]) ? "[" + x[i] + "]" : "['" + String(x[i]).replaceAll(/['\\]/gv, String.raw`\$&`) + "']";
2006
+ return p;
2007
+ };
2008
+ /**
2009
+ * @param {string[]} pointer JSON Path array
2010
+ * @returns {string} JSON Pointer
2011
+ */
2012
+ JSONPath.toPointer = function(pointer) {
2013
+ const x = pointer, n = x.length;
2014
+ let p = "";
2015
+ for (let i = 1; i < n; i++) if (!/^(~|\^|@.*?\(\))$/v.test(x[i])) p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
2016
+ return p;
2017
+ };
2018
+ /**
2019
+ * @param {string} expr Expression to convert
2020
+ * @returns {string[]}
2021
+ */
2022
+ JSONPath.toPathArray = function(expr) {
2023
+ if (pathCache.has(expr)) return pathCache.get(expr).concat();
2024
+ /** @type {string[]} */
2025
+ const subx = [];
2026
+ const exprList = expr.replaceAll(/@[\w$\-]+\([^\)]*\)/gv, ";$&;").replaceAll(/[\['](\??\(.*?\))[\]'](?!.\])/gv, function($0, $1) {
2027
+ return "[#" + (subx.push($1) - 1) + "]";
2028
+ }).replaceAll(/\[\s*((?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")(?:\s*,\s*(?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"))*)\s*\]/gv, function($0, $1) {
2029
+ if (!/[,\\]/v.test($1)) return $0;
2030
+ return "[#" + (subx.push($1) - 1) + "]";
2031
+ }).replaceAll(/\[['"]([^'\]]*)['"]\]/gv, function($0, prop) {
2032
+ return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
2033
+ }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^\[]*\])|\[['"]?/gv, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gv, function($0, ups) {
2034
+ return ";" + ups.split("").join(";") + ";";
2035
+ }).replaceAll(/;;;|;;/gv, ";..;").replaceAll(/;$|'?\]|'$/gv, "").split(";").map(function(exp) {
2036
+ const match = exp.match(/#(\d+)/v);
2037
+ return !match || !match[1] ? exp : subx[Number(match[1])];
2038
+ });
2039
+ pathCache.set(expr, exprList);
2040
+ return pathCache.get(expr).concat();
2041
+ };
2042
+ /**
2043
+ * @typedef {import('./jsonpath.js').AnyInput} AnyInput
2044
+ */
2045
+ /**
2046
+ * @typedef {import('./jsonpath.js').SandboxCallback} SandboxCallback
2047
+ */
2048
+ /**
2049
+ * @typedef {import('./jsonpath.js').SandboxPropertyValue} SandboxPropertyValue
2050
+ */
2051
+ /**
2052
+ * @typedef {import('./jsonpath.js').ExpressionArray} ExpressionArray
2053
+ */
2054
+ /**
2055
+ * @typedef {import('./jsonpath.js').ValueType} ValueType
2056
+ */
2057
+ /**
2058
+ * @typedef {import('./jsonpath.js').ParentValue} ParentValue
2059
+ */
2060
+ /**
2061
+ * @typedef {import('./jsonpath.js').UnknownResult} UnknownResult
2062
+ */
2063
+ /**
2064
+ * @typedef {import('./jsonpath.js').ParentProperty} ParentProperty
2065
+ */
2066
+ /**
2067
+ * @typedef {import('./jsonpath.js').PreferredOutput} PreferredOutput
2068
+ */
2069
+ /**
2070
+ * @typedef {import('./jsonpath.js').ReturnObject} ReturnObject
2071
+ */
2072
+ /**
2073
+ * @typedef {import('./jsonpath.js').JSONPathCallback} JSONPathCallback
2074
+ */
2075
+ /**
2076
+ * @typedef {import('./jsonpath.js').OtherTypeCallback} OtherTypeCallback
2077
+ */
2078
+ /**
2079
+ * @typedef {import('./jsonpath.js').ContextItem} ContextItem
2080
+ */
2081
+ /**
2082
+ * @typedef {import('./jsonpath.js').EvaluatedResult} EvaluatedResult
2083
+ */
2084
+ /**
2085
+ * @typedef {import('./jsonpath.js').EvalCallback} EvalCallback
2086
+ */
2087
+ /**
2088
+ * @typedef {import('./jsonpath.js').EvalClass} EvalClass
2089
+ */
2090
+ /**
2091
+ * @typedef {import('./jsonpath.js').ResultType} ResultType
2092
+ */
2093
+ /**
2094
+ * @typedef {import('./jsonpath.js').EvalValue} EvalValue
2095
+ */
2096
+ /**
2097
+ * @typedef {import('./jsonpath.js').PathType} PathType
2098
+ */
2099
+ /**
2100
+ * @typedef {import('./jsonpath.js').SafeScriptType} SafeScriptType
2101
+ */
2102
+ /**
2103
+ * @typedef {import('./jsonpath.js').ScriptType} ScriptType
2104
+ */
2105
+ /**
2106
+ * @typedef {import('./jsonpath.js').SandboxType} SandboxType
2107
+ */
2108
+ /**
2109
+ * @typedef {import('./jsonpath.js').JSONPathOptions} JSONPathOptions
2110
+ */
2111
+ /** @type {{vm: ScriptType}} */
2112
+ JSONPathClass.prototype.vm = vm;
2113
+ //#endregion
2114
+ export { JSONPath };
2115
+
2116
+ //# sourceMappingURL=index-node-esm-CJsN8G51.mjs.map