@vuu-ui/vuu-filters 0.8.5-debug → 0.8.5

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/esm/index.js CHANGED
@@ -1,4479 +1,4 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
- var __accessCheck = (obj, member, msg) => {
27
- if (!member.has(obj))
28
- throw TypeError("Cannot " + msg);
29
- };
30
- var __privateGet = (obj, member, getter) => {
31
- __accessCheck(obj, member, "read from private field");
32
- return getter ? getter.call(obj) : member.get(obj);
33
- };
34
- var __privateAdd = (obj, member, value) => {
35
- if (member.has(obj))
36
- throw TypeError("Cannot add the same private member more than once");
37
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
38
- };
39
- var __privateSet = (obj, member, value, setter) => {
40
- __accessCheck(obj, member, "write to private field");
41
- setter ? setter.call(obj, value) : member.set(obj, value);
42
- return value;
43
- };
44
-
45
- // ../../node_modules/classnames/index.js
46
- var require_classnames = __commonJS({
47
- "../../node_modules/classnames/index.js"(exports, module) {
48
- (function() {
49
- "use strict";
50
- var hasOwn = {}.hasOwnProperty;
51
- var nativeCodeString = "[native code]";
52
- function classNames() {
53
- var classes = [];
54
- for (var i = 0; i < arguments.length; i++) {
55
- var arg = arguments[i];
56
- if (!arg)
57
- continue;
58
- var argType = typeof arg;
59
- if (argType === "string" || argType === "number") {
60
- classes.push(arg);
61
- } else if (Array.isArray(arg)) {
62
- if (arg.length) {
63
- var inner = classNames.apply(null, arg);
64
- if (inner) {
65
- classes.push(inner);
66
- }
67
- }
68
- } else if (argType === "object") {
69
- if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) {
70
- classes.push(arg.toString());
71
- continue;
72
- }
73
- for (var key in arg) {
74
- if (hasOwn.call(arg, key) && arg[key]) {
75
- classes.push(key);
76
- }
77
- }
78
- }
79
- }
80
- return classes.join(" ");
81
- }
82
- if (typeof module !== "undefined" && module.exports) {
83
- classNames.default = classNames;
84
- module.exports = classNames;
85
- } else if (typeof define === "function" && typeof define.amd === "object" && define.amd) {
86
- define("classnames", [], function() {
87
- return classNames;
88
- });
89
- } else {
90
- window.classNames = classNames;
91
- }
92
- })();
93
- }
94
- });
95
-
96
- // src/filter-input/FilterInput.tsx
97
- import { Button } from "@salt-ds/core";
98
-
99
- // src/filter-input/useCodeMirrorEditor.ts
100
- import {
101
- autocompletion,
102
- defaultKeymap,
103
- EditorState as EditorState2,
104
- EditorView as EditorView2,
105
- ensureSyntaxTree,
106
- keymap,
107
- minimalSetup,
108
- startCompletion
109
- } from "@vuu-ui/vuu-codemirror";
110
-
111
- // ../../node_modules/@lezer/common/dist/index.js
112
- var DefaultBufferLength = 1024;
113
- var nextPropID = 0;
114
- var Range = class {
115
- constructor(from, to) {
116
- this.from = from;
117
- this.to = to;
118
- }
119
- };
120
- var NodeProp = class {
121
- /// Create a new node prop type.
122
- constructor(config = {}) {
123
- this.id = nextPropID++;
124
- this.perNode = !!config.perNode;
125
- this.deserialize = config.deserialize || (() => {
126
- throw new Error("This node type doesn't define a deserialize function");
127
- });
128
- }
129
- /// This is meant to be used with
130
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
131
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
132
- /// prop values for each node type in the set. Takes a [match
133
- /// object](#common.NodeType^match) or function that returns undefined
134
- /// if the node type doesn't get this prop, and the prop's value if
135
- /// it does.
136
- add(match) {
137
- if (this.perNode)
138
- throw new RangeError("Can't add per-node props to node types");
139
- if (typeof match != "function")
140
- match = NodeType.match(match);
141
- return (type) => {
142
- let result = match(type);
143
- return result === void 0 ? null : [this, result];
144
- };
145
- }
146
- };
147
- NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
148
- NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
149
- NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
150
- NodeProp.contextHash = new NodeProp({ perNode: true });
151
- NodeProp.lookAhead = new NodeProp({ perNode: true });
152
- NodeProp.mounted = new NodeProp({ perNode: true });
153
- var noProps = /* @__PURE__ */ Object.create(null);
154
- var NodeType = class {
155
- /// @internal
156
- constructor(name, props, id, flags = 0) {
157
- this.name = name;
158
- this.props = props;
159
- this.id = id;
160
- this.flags = flags;
161
- }
162
- /// Define a node type.
163
- static define(spec) {
164
- let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
165
- let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
166
- let type = new NodeType(spec.name || "", props, spec.id, flags);
167
- if (spec.props)
168
- for (let src of spec.props) {
169
- if (!Array.isArray(src))
170
- src = src(type);
171
- if (src) {
172
- if (src[0].perNode)
173
- throw new RangeError("Can't store a per-node prop on a node type");
174
- props[src[0].id] = src[1];
175
- }
176
- }
177
- return type;
178
- }
179
- /// Retrieves a node prop for this type. Will return `undefined` if
180
- /// the prop isn't present on this node.
181
- prop(prop) {
182
- return this.props[prop.id];
183
- }
184
- /// True when this is the top node of a grammar.
185
- get isTop() {
186
- return (this.flags & 1) > 0;
187
- }
188
- /// True when this node is produced by a skip rule.
189
- get isSkipped() {
190
- return (this.flags & 2) > 0;
191
- }
192
- /// Indicates whether this is an error node.
193
- get isError() {
194
- return (this.flags & 4) > 0;
195
- }
196
- /// When true, this node type doesn't correspond to a user-declared
197
- /// named node, for example because it is used to cache repetition.
198
- get isAnonymous() {
199
- return (this.flags & 8) > 0;
200
- }
201
- /// Returns true when this node's name or one of its
202
- /// [groups](#common.NodeProp^group) matches the given string.
203
- is(name) {
204
- if (typeof name == "string") {
205
- if (this.name == name)
206
- return true;
207
- let group = this.prop(NodeProp.group);
208
- return group ? group.indexOf(name) > -1 : false;
209
- }
210
- return this.id == name;
211
- }
212
- /// Create a function from node types to arbitrary values by
213
- /// specifying an object whose property names are node or
214
- /// [group](#common.NodeProp^group) names. Often useful with
215
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
216
- /// names, separated by spaces, in a single property name to map
217
- /// multiple node names to a single value.
218
- static match(map) {
219
- let direct = /* @__PURE__ */ Object.create(null);
220
- for (let prop in map)
221
- for (let name of prop.split(" "))
222
- direct[name] = map[prop];
223
- return (node) => {
224
- for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
225
- let found = direct[i < 0 ? node.name : groups[i]];
226
- if (found)
227
- return found;
228
- }
229
- };
230
- }
231
- };
232
- NodeType.none = new NodeType(
233
- "",
234
- /* @__PURE__ */ Object.create(null),
235
- 0,
236
- 8
237
- /* NodeFlag.Anonymous */
238
- );
239
- var NodeSet = class {
240
- /// Create a set with the given types. The `id` property of each
241
- /// type should correspond to its position within the array.
242
- constructor(types) {
243
- this.types = types;
244
- for (let i = 0; i < types.length; i++)
245
- if (types[i].id != i)
246
- throw new RangeError("Node type ids should correspond to array positions when creating a node set");
247
- }
248
- /// Create a copy of this set with some node properties added. The
249
- /// arguments to this method can be created with
250
- /// [`NodeProp.add`](#common.NodeProp.add).
251
- extend(...props) {
252
- let newTypes = [];
253
- for (let type of this.types) {
254
- let newProps = null;
255
- for (let source of props) {
256
- let add = source(type);
257
- if (add) {
258
- if (!newProps)
259
- newProps = Object.assign({}, type.props);
260
- newProps[add[0].id] = add[1];
261
- }
262
- }
263
- newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
264
- }
265
- return new NodeSet(newTypes);
266
- }
267
- };
268
- var CachedNode = /* @__PURE__ */ new WeakMap();
269
- var CachedInnerNode = /* @__PURE__ */ new WeakMap();
270
- var IterMode;
271
- (function(IterMode2) {
272
- IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
273
- IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
274
- IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
275
- IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
276
- })(IterMode || (IterMode = {}));
277
- var Tree = class {
278
- /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
279
- constructor(type, children, positions, length, props) {
280
- this.type = type;
281
- this.children = children;
282
- this.positions = positions;
283
- this.length = length;
284
- this.props = null;
285
- if (props && props.length) {
286
- this.props = /* @__PURE__ */ Object.create(null);
287
- for (let [prop, value] of props)
288
- this.props[typeof prop == "number" ? prop : prop.id] = value;
289
- }
290
- }
291
- /// @internal
292
- toString() {
293
- let mounted = this.prop(NodeProp.mounted);
294
- if (mounted && !mounted.overlay)
295
- return mounted.tree.toString();
296
- let children = "";
297
- for (let ch of this.children) {
298
- let str = ch.toString();
299
- if (str) {
300
- if (children)
301
- children += ",";
302
- children += str;
303
- }
304
- }
305
- return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
306
- }
307
- /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
308
- /// the tree. Mode can be used to [control](#common.IterMode) which
309
- /// nodes the cursor visits.
310
- cursor(mode = 0) {
311
- return new TreeCursor(this.topNode, mode);
312
- }
313
- /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
314
- /// at the given position and side (see
315
- /// [`moveTo`](#common.TreeCursor.moveTo).
316
- cursorAt(pos, side = 0, mode = 0) {
317
- let scope = CachedNode.get(this) || this.topNode;
318
- let cursor = new TreeCursor(scope);
319
- cursor.moveTo(pos, side);
320
- CachedNode.set(this, cursor._tree);
321
- return cursor;
322
- }
323
- /// Get a [syntax node](#common.SyntaxNode) object for the top of the
324
- /// tree.
325
- get topNode() {
326
- return new TreeNode(this, 0, 0, null);
327
- }
328
- /// Get the [syntax node](#common.SyntaxNode) at the given position.
329
- /// If `side` is -1, this will move into nodes that end at the
330
- /// position. If 1, it'll move into nodes that start at the
331
- /// position. With 0, it'll only enter nodes that cover the position
332
- /// from both sides.
333
- ///
334
- /// Note that this will not enter
335
- /// [overlays](#common.MountedTree.overlay), and you often want
336
- /// [`resolveInner`](#common.Tree.resolveInner) instead.
337
- resolve(pos, side = 0) {
338
- let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
339
- CachedNode.set(this, node);
340
- return node;
341
- }
342
- /// Like [`resolve`](#common.Tree.resolve), but will enter
343
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
344
- /// pointing into the innermost overlaid tree at the given position
345
- /// (with parent links going through all parent structure, including
346
- /// the host trees).
347
- resolveInner(pos, side = 0) {
348
- let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
349
- CachedInnerNode.set(this, node);
350
- return node;
351
- }
352
- /// Iterate over the tree and its children, calling `enter` for any
353
- /// node that touches the `from`/`to` region (if given) before
354
- /// running over such a node's children, and `leave` (if given) when
355
- /// leaving the node. When `enter` returns `false`, that node will
356
- /// not have its children iterated over (or `leave` called).
357
- iterate(spec) {
358
- let { enter, leave, from = 0, to = this.length } = spec;
359
- let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
360
- for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
361
- let entered = false;
362
- if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
363
- if (c.firstChild())
364
- continue;
365
- entered = true;
366
- }
367
- for (; ; ) {
368
- if (entered && leave && (anon || !c.type.isAnonymous))
369
- leave(c);
370
- if (c.nextSibling())
371
- break;
372
- if (!c.parent())
373
- return;
374
- entered = true;
375
- }
376
- }
377
- }
378
- /// Get the value of the given [node prop](#common.NodeProp) for this
379
- /// node. Works with both per-node and per-type props.
380
- prop(prop) {
381
- return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
382
- }
383
- /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
384
- /// format that can be passed to the [`Tree`](#common.Tree)
385
- /// constructor.
386
- get propValues() {
387
- let result = [];
388
- if (this.props)
389
- for (let id in this.props)
390
- result.push([+id, this.props[id]]);
391
- return result;
392
- }
393
- /// Balance the direct children of this tree, producing a copy of
394
- /// which may have children grouped into subtrees with type
395
- /// [`NodeType.none`](#common.NodeType^none).
396
- balance(config = {}) {
397
- return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
398
- }
399
- /// Build a tree from a postfix-ordered buffer of node information,
400
- /// or a cursor over such a buffer.
401
- static build(data) {
402
- return buildTree(data);
403
- }
404
- };
405
- Tree.empty = new Tree(NodeType.none, [], [], 0);
406
- var FlatBufferCursor = class {
407
- constructor(buffer, index) {
408
- this.buffer = buffer;
409
- this.index = index;
410
- }
411
- get id() {
412
- return this.buffer[this.index - 4];
413
- }
414
- get start() {
415
- return this.buffer[this.index - 3];
416
- }
417
- get end() {
418
- return this.buffer[this.index - 2];
419
- }
420
- get size() {
421
- return this.buffer[this.index - 1];
422
- }
423
- get pos() {
424
- return this.index;
425
- }
426
- next() {
427
- this.index -= 4;
428
- }
429
- fork() {
430
- return new FlatBufferCursor(this.buffer, this.index);
431
- }
432
- };
433
- var TreeBuffer = class {
434
- /// Create a tree buffer.
435
- constructor(buffer, length, set) {
436
- this.buffer = buffer;
437
- this.length = length;
438
- this.set = set;
439
- }
440
- /// @internal
441
- get type() {
442
- return NodeType.none;
443
- }
444
- /// @internal
445
- toString() {
446
- let result = [];
447
- for (let index = 0; index < this.buffer.length; ) {
448
- result.push(this.childString(index));
449
- index = this.buffer[index + 3];
450
- }
451
- return result.join(",");
452
- }
453
- /// @internal
454
- childString(index) {
455
- let id = this.buffer[index], endIndex = this.buffer[index + 3];
456
- let type = this.set.types[id], result = type.name;
457
- if (/\W/.test(result) && !type.isError)
458
- result = JSON.stringify(result);
459
- index += 4;
460
- if (endIndex == index)
461
- return result;
462
- let children = [];
463
- while (index < endIndex) {
464
- children.push(this.childString(index));
465
- index = this.buffer[index + 3];
466
- }
467
- return result + "(" + children.join(",") + ")";
468
- }
469
- /// @internal
470
- findChild(startIndex, endIndex, dir, pos, side) {
471
- let { buffer } = this, pick = -1;
472
- for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
473
- if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
474
- pick = i;
475
- if (dir > 0)
476
- break;
477
- }
478
- }
479
- return pick;
480
- }
481
- /// @internal
482
- slice(startI, endI, from) {
483
- let b = this.buffer;
484
- let copy = new Uint16Array(endI - startI), len = 0;
485
- for (let i = startI, j = 0; i < endI; ) {
486
- copy[j++] = b[i++];
487
- copy[j++] = b[i++] - from;
488
- let to = copy[j++] = b[i++] - from;
489
- copy[j++] = b[i++] - startI;
490
- len = Math.max(len, to);
491
- }
492
- return new TreeBuffer(copy, len, this.set);
493
- }
494
- };
495
- function checkSide(side, pos, from, to) {
496
- switch (side) {
497
- case -2:
498
- return from < pos;
499
- case -1:
500
- return to >= pos && from < pos;
501
- case 0:
502
- return from < pos && to > pos;
503
- case 1:
504
- return from <= pos && to > pos;
505
- case 2:
506
- return to > pos;
507
- case 4:
508
- return true;
509
- }
510
- }
511
- function enterUnfinishedNodesBefore(node, pos) {
512
- let scan = node.childBefore(pos);
513
- while (scan) {
514
- let last = scan.lastChild;
515
- if (!last || last.to != scan.to)
516
- break;
517
- if (last.type.isError && last.from == last.to) {
518
- node = scan;
519
- scan = last.prevSibling;
520
- } else {
521
- scan = last;
522
- }
523
- }
524
- return node;
525
- }
526
- function resolveNode(node, pos, side, overlays) {
527
- var _a;
528
- while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
529
- let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
530
- if (!parent)
531
- return node;
532
- node = parent;
533
- }
534
- let mode = overlays ? 0 : IterMode.IgnoreOverlays;
535
- if (overlays)
536
- for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
537
- if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
538
- node = parent;
539
- }
540
- for (; ; ) {
541
- let inner = node.enter(pos, side, mode);
542
- if (!inner)
543
- return node;
544
- node = inner;
545
- }
546
- }
547
- var TreeNode = class {
548
- constructor(_tree, from, index, _parent) {
549
- this._tree = _tree;
550
- this.from = from;
551
- this.index = index;
552
- this._parent = _parent;
553
- }
554
- get type() {
555
- return this._tree.type;
556
- }
557
- get name() {
558
- return this._tree.type.name;
559
- }
560
- get to() {
561
- return this.from + this._tree.length;
562
- }
563
- nextChild(i, dir, pos, side, mode = 0) {
564
- for (let parent = this; ; ) {
565
- for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
566
- let next = children[i], start = positions[i] + parent.from;
567
- if (!checkSide(side, pos, start, start + next.length))
568
- continue;
569
- if (next instanceof TreeBuffer) {
570
- if (mode & IterMode.ExcludeBuffers)
571
- continue;
572
- let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
573
- if (index > -1)
574
- return new BufferNode(new BufferContext(parent, next, i, start), null, index);
575
- } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
576
- let mounted;
577
- if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
578
- return new TreeNode(mounted.tree, start, i, parent);
579
- let inner = new TreeNode(next, start, i, parent);
580
- return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
581
- }
582
- }
583
- if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
584
- return null;
585
- if (parent.index >= 0)
586
- i = parent.index + dir;
587
- else
588
- i = dir < 0 ? -1 : parent._parent._tree.children.length;
589
- parent = parent._parent;
590
- if (!parent)
591
- return null;
592
- }
593
- }
594
- get firstChild() {
595
- return this.nextChild(
596
- 0,
597
- 1,
598
- 0,
599
- 4
600
- /* Side.DontCare */
601
- );
602
- }
603
- get lastChild() {
604
- return this.nextChild(
605
- this._tree.children.length - 1,
606
- -1,
607
- 0,
608
- 4
609
- /* Side.DontCare */
610
- );
611
- }
612
- childAfter(pos) {
613
- return this.nextChild(
614
- 0,
615
- 1,
616
- pos,
617
- 2
618
- /* Side.After */
619
- );
620
- }
621
- childBefore(pos) {
622
- return this.nextChild(
623
- this._tree.children.length - 1,
624
- -1,
625
- pos,
626
- -2
627
- /* Side.Before */
628
- );
629
- }
630
- enter(pos, side, mode = 0) {
631
- let mounted;
632
- if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
633
- let rPos = pos - this.from;
634
- for (let { from, to } of mounted.overlay) {
635
- if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
636
- return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
637
- }
638
- }
639
- return this.nextChild(0, 1, pos, side, mode);
640
- }
641
- nextSignificantParent() {
642
- let val = this;
643
- while (val.type.isAnonymous && val._parent)
644
- val = val._parent;
645
- return val;
646
- }
647
- get parent() {
648
- return this._parent ? this._parent.nextSignificantParent() : null;
649
- }
650
- get nextSibling() {
651
- return this._parent && this.index >= 0 ? this._parent.nextChild(
652
- this.index + 1,
653
- 1,
654
- 0,
655
- 4
656
- /* Side.DontCare */
657
- ) : null;
658
- }
659
- get prevSibling() {
660
- return this._parent && this.index >= 0 ? this._parent.nextChild(
661
- this.index - 1,
662
- -1,
663
- 0,
664
- 4
665
- /* Side.DontCare */
666
- ) : null;
667
- }
668
- cursor(mode = 0) {
669
- return new TreeCursor(this, mode);
670
- }
671
- get tree() {
672
- return this._tree;
673
- }
674
- toTree() {
675
- return this._tree;
676
- }
677
- resolve(pos, side = 0) {
678
- return resolveNode(this, pos, side, false);
679
- }
680
- resolveInner(pos, side = 0) {
681
- return resolveNode(this, pos, side, true);
682
- }
683
- enterUnfinishedNodesBefore(pos) {
684
- return enterUnfinishedNodesBefore(this, pos);
685
- }
686
- getChild(type, before = null, after = null) {
687
- let r = getChildren(this, type, before, after);
688
- return r.length ? r[0] : null;
689
- }
690
- getChildren(type, before = null, after = null) {
691
- return getChildren(this, type, before, after);
692
- }
693
- /// @internal
694
- toString() {
695
- return this._tree.toString();
696
- }
697
- get node() {
698
- return this;
699
- }
700
- matchContext(context) {
701
- return matchNodeContext(this, context);
702
- }
703
- };
704
- function getChildren(node, type, before, after) {
705
- let cur = node.cursor(), result = [];
706
- if (!cur.firstChild())
707
- return result;
708
- if (before != null) {
709
- while (!cur.type.is(before))
710
- if (!cur.nextSibling())
711
- return result;
712
- }
713
- for (; ; ) {
714
- if (after != null && cur.type.is(after))
715
- return result;
716
- if (cur.type.is(type))
717
- result.push(cur.node);
718
- if (!cur.nextSibling())
719
- return after == null ? result : [];
720
- }
721
- }
722
- function matchNodeContext(node, context, i = context.length - 1) {
723
- for (let p = node.parent; i >= 0; p = p.parent) {
724
- if (!p)
725
- return false;
726
- if (!p.type.isAnonymous) {
727
- if (context[i] && context[i] != p.name)
728
- return false;
729
- i--;
730
- }
731
- }
732
- return true;
733
- }
734
- var BufferContext = class {
735
- constructor(parent, buffer, index, start) {
736
- this.parent = parent;
737
- this.buffer = buffer;
738
- this.index = index;
739
- this.start = start;
740
- }
741
- };
742
- var BufferNode = class {
743
- get name() {
744
- return this.type.name;
745
- }
746
- get from() {
747
- return this.context.start + this.context.buffer.buffer[this.index + 1];
748
- }
749
- get to() {
750
- return this.context.start + this.context.buffer.buffer[this.index + 2];
751
- }
752
- constructor(context, _parent, index) {
753
- this.context = context;
754
- this._parent = _parent;
755
- this.index = index;
756
- this.type = context.buffer.set.types[context.buffer.buffer[index]];
757
- }
758
- child(dir, pos, side) {
759
- let { buffer } = this.context;
760
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
761
- return index < 0 ? null : new BufferNode(this.context, this, index);
762
- }
763
- get firstChild() {
764
- return this.child(
765
- 1,
766
- 0,
767
- 4
768
- /* Side.DontCare */
769
- );
770
- }
771
- get lastChild() {
772
- return this.child(
773
- -1,
774
- 0,
775
- 4
776
- /* Side.DontCare */
777
- );
778
- }
779
- childAfter(pos) {
780
- return this.child(
781
- 1,
782
- pos,
783
- 2
784
- /* Side.After */
785
- );
786
- }
787
- childBefore(pos) {
788
- return this.child(
789
- -1,
790
- pos,
791
- -2
792
- /* Side.Before */
793
- );
794
- }
795
- enter(pos, side, mode = 0) {
796
- if (mode & IterMode.ExcludeBuffers)
797
- return null;
798
- let { buffer } = this.context;
799
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
800
- return index < 0 ? null : new BufferNode(this.context, this, index);
801
- }
802
- get parent() {
803
- return this._parent || this.context.parent.nextSignificantParent();
804
- }
805
- externalSibling(dir) {
806
- return this._parent ? null : this.context.parent.nextChild(
807
- this.context.index + dir,
808
- dir,
809
- 0,
810
- 4
811
- /* Side.DontCare */
812
- );
813
- }
814
- get nextSibling() {
815
- let { buffer } = this.context;
816
- let after = buffer.buffer[this.index + 3];
817
- if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
818
- return new BufferNode(this.context, this._parent, after);
819
- return this.externalSibling(1);
820
- }
821
- get prevSibling() {
822
- let { buffer } = this.context;
823
- let parentStart = this._parent ? this._parent.index + 4 : 0;
824
- if (this.index == parentStart)
825
- return this.externalSibling(-1);
826
- return new BufferNode(this.context, this._parent, buffer.findChild(
827
- parentStart,
828
- this.index,
829
- -1,
830
- 0,
831
- 4
832
- /* Side.DontCare */
833
- ));
834
- }
835
- cursor(mode = 0) {
836
- return new TreeCursor(this, mode);
837
- }
838
- get tree() {
839
- return null;
840
- }
841
- toTree() {
842
- let children = [], positions = [];
843
- let { buffer } = this.context;
844
- let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
845
- if (endI > startI) {
846
- let from = buffer.buffer[this.index + 1];
847
- children.push(buffer.slice(startI, endI, from));
848
- positions.push(0);
849
- }
850
- return new Tree(this.type, children, positions, this.to - this.from);
851
- }
852
- resolve(pos, side = 0) {
853
- return resolveNode(this, pos, side, false);
854
- }
855
- resolveInner(pos, side = 0) {
856
- return resolveNode(this, pos, side, true);
857
- }
858
- enterUnfinishedNodesBefore(pos) {
859
- return enterUnfinishedNodesBefore(this, pos);
860
- }
861
- /// @internal
862
- toString() {
863
- return this.context.buffer.childString(this.index);
864
- }
865
- getChild(type, before = null, after = null) {
866
- let r = getChildren(this, type, before, after);
867
- return r.length ? r[0] : null;
868
- }
869
- getChildren(type, before = null, after = null) {
870
- return getChildren(this, type, before, after);
871
- }
872
- get node() {
873
- return this;
874
- }
875
- matchContext(context) {
876
- return matchNodeContext(this, context);
877
- }
878
- };
879
- var TreeCursor = class {
880
- /// Shorthand for `.type.name`.
881
- get name() {
882
- return this.type.name;
883
- }
884
- /// @internal
885
- constructor(node, mode = 0) {
886
- this.mode = mode;
887
- this.buffer = null;
888
- this.stack = [];
889
- this.index = 0;
890
- this.bufferNode = null;
891
- if (node instanceof TreeNode) {
892
- this.yieldNode(node);
893
- } else {
894
- this._tree = node.context.parent;
895
- this.buffer = node.context;
896
- for (let n = node._parent; n; n = n._parent)
897
- this.stack.unshift(n.index);
898
- this.bufferNode = node;
899
- this.yieldBuf(node.index);
900
- }
901
- }
902
- yieldNode(node) {
903
- if (!node)
904
- return false;
905
- this._tree = node;
906
- this.type = node.type;
907
- this.from = node.from;
908
- this.to = node.to;
909
- return true;
910
- }
911
- yieldBuf(index, type) {
912
- this.index = index;
913
- let { start, buffer } = this.buffer;
914
- this.type = type || buffer.set.types[buffer.buffer[index]];
915
- this.from = start + buffer.buffer[index + 1];
916
- this.to = start + buffer.buffer[index + 2];
917
- return true;
918
- }
919
- yield(node) {
920
- if (!node)
921
- return false;
922
- if (node instanceof TreeNode) {
923
- this.buffer = null;
924
- return this.yieldNode(node);
925
- }
926
- this.buffer = node.context;
927
- return this.yieldBuf(node.index, node.type);
928
- }
929
- /// @internal
930
- toString() {
931
- return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
932
- }
933
- /// @internal
934
- enterChild(dir, pos, side) {
935
- if (!this.buffer)
936
- return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
937
- let { buffer } = this.buffer;
938
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
939
- if (index < 0)
940
- return false;
941
- this.stack.push(this.index);
942
- return this.yieldBuf(index);
943
- }
944
- /// Move the cursor to this node's first child. When this returns
945
- /// false, the node has no child, and the cursor has not been moved.
946
- firstChild() {
947
- return this.enterChild(
948
- 1,
949
- 0,
950
- 4
951
- /* Side.DontCare */
952
- );
953
- }
954
- /// Move the cursor to this node's last child.
955
- lastChild() {
956
- return this.enterChild(
957
- -1,
958
- 0,
959
- 4
960
- /* Side.DontCare */
961
- );
962
- }
963
- /// Move the cursor to the first child that ends after `pos`.
964
- childAfter(pos) {
965
- return this.enterChild(
966
- 1,
967
- pos,
968
- 2
969
- /* Side.After */
970
- );
971
- }
972
- /// Move to the last child that starts before `pos`.
973
- childBefore(pos) {
974
- return this.enterChild(
975
- -1,
976
- pos,
977
- -2
978
- /* Side.Before */
979
- );
980
- }
981
- /// Move the cursor to the child around `pos`. If side is -1 the
982
- /// child may end at that position, when 1 it may start there. This
983
- /// will also enter [overlaid](#common.MountedTree.overlay)
984
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
985
- /// set to false.
986
- enter(pos, side, mode = this.mode) {
987
- if (!this.buffer)
988
- return this.yield(this._tree.enter(pos, side, mode));
989
- return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
990
- }
991
- /// Move to the node's parent node, if this isn't the top node.
992
- parent() {
993
- if (!this.buffer)
994
- return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
995
- if (this.stack.length)
996
- return this.yieldBuf(this.stack.pop());
997
- let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
998
- this.buffer = null;
999
- return this.yieldNode(parent);
1000
- }
1001
- /// @internal
1002
- sibling(dir) {
1003
- if (!this.buffer)
1004
- return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
1005
- let { buffer } = this.buffer, d = this.stack.length - 1;
1006
- if (dir < 0) {
1007
- let parentStart = d < 0 ? 0 : this.stack[d] + 4;
1008
- if (this.index != parentStart)
1009
- return this.yieldBuf(buffer.findChild(
1010
- parentStart,
1011
- this.index,
1012
- -1,
1013
- 0,
1014
- 4
1015
- /* Side.DontCare */
1016
- ));
1017
- } else {
1018
- let after = buffer.buffer[this.index + 3];
1019
- if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
1020
- return this.yieldBuf(after);
1021
- }
1022
- return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
1023
- }
1024
- /// Move to this node's next sibling, if any.
1025
- nextSibling() {
1026
- return this.sibling(1);
1027
- }
1028
- /// Move to this node's previous sibling, if any.
1029
- prevSibling() {
1030
- return this.sibling(-1);
1031
- }
1032
- atLastNode(dir) {
1033
- let index, parent, { buffer } = this;
1034
- if (buffer) {
1035
- if (dir > 0) {
1036
- if (this.index < buffer.buffer.buffer.length)
1037
- return false;
1038
- } else {
1039
- for (let i = 0; i < this.index; i++)
1040
- if (buffer.buffer.buffer[i + 3] < this.index)
1041
- return false;
1042
- }
1043
- ({ index, parent } = buffer);
1044
- } else {
1045
- ({ index, _parent: parent } = this._tree);
1046
- }
1047
- for (; parent; { index, _parent: parent } = parent) {
1048
- if (index > -1)
1049
- for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
1050
- let child = parent._tree.children[i];
1051
- if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
1052
- return false;
1053
- }
1054
- }
1055
- return true;
1056
- }
1057
- move(dir, enter) {
1058
- if (enter && this.enterChild(
1059
- dir,
1060
- 0,
1061
- 4
1062
- /* Side.DontCare */
1063
- ))
1064
- return true;
1065
- for (; ; ) {
1066
- if (this.sibling(dir))
1067
- return true;
1068
- if (this.atLastNode(dir) || !this.parent())
1069
- return false;
1070
- }
1071
- }
1072
- /// Move to the next node in a
1073
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
1074
- /// traversal, going from a node to its first child or, if the
1075
- /// current node is empty or `enter` is false, its next sibling or
1076
- /// the next sibling of the first parent node that has one.
1077
- next(enter = true) {
1078
- return this.move(1, enter);
1079
- }
1080
- /// Move to the next node in a last-to-first pre-order traveral. A
1081
- /// node is followed by its last child or, if it has none, its
1082
- /// previous sibling or the previous sibling of the first parent
1083
- /// node that has one.
1084
- prev(enter = true) {
1085
- return this.move(-1, enter);
1086
- }
1087
- /// Move the cursor to the innermost node that covers `pos`. If
1088
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
1089
- /// it will enter nodes that start at `pos`.
1090
- moveTo(pos, side = 0) {
1091
- while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
1092
- if (!this.parent())
1093
- break;
1094
- while (this.enterChild(1, pos, side)) {
1095
- }
1096
- return this;
1097
- }
1098
- /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
1099
- /// position.
1100
- get node() {
1101
- if (!this.buffer)
1102
- return this._tree;
1103
- let cache = this.bufferNode, result = null, depth = 0;
1104
- if (cache && cache.context == this.buffer) {
1105
- scan:
1106
- for (let index = this.index, d = this.stack.length; d >= 0; ) {
1107
- for (let c = cache; c; c = c._parent)
1108
- if (c.index == index) {
1109
- if (index == this.index)
1110
- return c;
1111
- result = c;
1112
- depth = d + 1;
1113
- break scan;
1114
- }
1115
- index = this.stack[--d];
1116
- }
1117
- }
1118
- for (let i = depth; i < this.stack.length; i++)
1119
- result = new BufferNode(this.buffer, result, this.stack[i]);
1120
- return this.bufferNode = new BufferNode(this.buffer, result, this.index);
1121
- }
1122
- /// Get the [tree](#common.Tree) that represents the current node, if
1123
- /// any. Will return null when the node is in a [tree
1124
- /// buffer](#common.TreeBuffer).
1125
- get tree() {
1126
- return this.buffer ? null : this._tree._tree;
1127
- }
1128
- /// Iterate over the current node and all its descendants, calling
1129
- /// `enter` when entering a node and `leave`, if given, when leaving
1130
- /// one. When `enter` returns `false`, any children of that node are
1131
- /// skipped, and `leave` isn't called for it.
1132
- iterate(enter, leave) {
1133
- for (let depth = 0; ; ) {
1134
- let mustLeave = false;
1135
- if (this.type.isAnonymous || enter(this) !== false) {
1136
- if (this.firstChild()) {
1137
- depth++;
1138
- continue;
1139
- }
1140
- if (!this.type.isAnonymous)
1141
- mustLeave = true;
1142
- }
1143
- for (; ; ) {
1144
- if (mustLeave && leave)
1145
- leave(this);
1146
- mustLeave = this.type.isAnonymous;
1147
- if (this.nextSibling())
1148
- break;
1149
- if (!depth)
1150
- return;
1151
- this.parent();
1152
- depth--;
1153
- mustLeave = true;
1154
- }
1155
- }
1156
- }
1157
- /// Test whether the current node matches a given context—a sequence
1158
- /// of direct parent node names. Empty strings in the context array
1159
- /// are treated as wildcards.
1160
- matchContext(context) {
1161
- if (!this.buffer)
1162
- return matchNodeContext(this.node, context);
1163
- let { buffer } = this.buffer, { types } = buffer.set;
1164
- for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
1165
- if (d < 0)
1166
- return matchNodeContext(this.node, context, i);
1167
- let type = types[buffer.buffer[this.stack[d]]];
1168
- if (!type.isAnonymous) {
1169
- if (context[i] && context[i] != type.name)
1170
- return false;
1171
- i--;
1172
- }
1173
- }
1174
- return true;
1175
- }
1176
- };
1177
- function hasChild(tree) {
1178
- return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1179
- }
1180
- function buildTree(data) {
1181
- var _a;
1182
- let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1183
- let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1184
- let types = nodeSet.types;
1185
- let contextHash = 0, lookAhead = 0;
1186
- function takeNode(parentStart, minPos, children2, positions2, inRepeat) {
1187
- let { id, start, end, size } = cursor;
1188
- let lookAheadAtStart = lookAhead;
1189
- while (size < 0) {
1190
- cursor.next();
1191
- if (size == -1) {
1192
- let node2 = reused[id];
1193
- children2.push(node2);
1194
- positions2.push(start - parentStart);
1195
- return;
1196
- } else if (size == -3) {
1197
- contextHash = id;
1198
- return;
1199
- } else if (size == -4) {
1200
- lookAhead = id;
1201
- return;
1202
- } else {
1203
- throw new RangeError(`Unrecognized record size: ${size}`);
1204
- }
1205
- }
1206
- let type = types[id], node, buffer2;
1207
- let startPos = start - parentStart;
1208
- if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
1209
- let data2 = new Uint16Array(buffer2.size - buffer2.skip);
1210
- let endPos = cursor.pos - buffer2.size, index = data2.length;
1211
- while (cursor.pos > endPos)
1212
- index = copyToBuffer(buffer2.start, data2, index);
1213
- node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
1214
- startPos = buffer2.start - parentStart;
1215
- } else {
1216
- let endPos = cursor.pos - size;
1217
- cursor.next();
1218
- let localChildren = [], localPositions = [];
1219
- let localInRepeat = id >= minRepeatType ? id : -1;
1220
- let lastGroup = 0, lastEnd = end;
1221
- while (cursor.pos > endPos) {
1222
- if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1223
- if (cursor.end <= lastEnd - maxBufferLength) {
1224
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
1225
- lastGroup = localChildren.length;
1226
- lastEnd = cursor.end;
1227
- }
1228
- cursor.next();
1229
- } else {
1230
- takeNode(start, endPos, localChildren, localPositions, localInRepeat);
1231
- }
1232
- }
1233
- if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1234
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
1235
- localChildren.reverse();
1236
- localPositions.reverse();
1237
- if (localInRepeat > -1 && lastGroup > 0) {
1238
- let make = makeBalanced(type);
1239
- node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1240
- } else {
1241
- node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
1242
- }
1243
- }
1244
- children2.push(node);
1245
- positions2.push(startPos);
1246
- }
1247
- function makeBalanced(type) {
1248
- return (children2, positions2, length2) => {
1249
- let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp;
1250
- if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) {
1251
- if (!lastI && last.type == type && last.length == length2)
1252
- return last;
1253
- if (lookAheadProp = last.prop(NodeProp.lookAhead))
1254
- lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
1255
- }
1256
- return makeTree(type, children2, positions2, length2, lookAhead2);
1257
- };
1258
- }
1259
- function makeRepeatLeaf(children2, positions2, base, i, from, to, type, lookAhead2) {
1260
- let localChildren = [], localPositions = [];
1261
- while (children2.length > i) {
1262
- localChildren.push(children2.pop());
1263
- localPositions.push(positions2.pop() + base - from);
1264
- }
1265
- children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to));
1266
- positions2.push(from - base);
1267
- }
1268
- function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) {
1269
- if (contextHash) {
1270
- let pair2 = [NodeProp.contextHash, contextHash];
1271
- props = props ? [pair2].concat(props) : [pair2];
1272
- }
1273
- if (lookAhead2 > 25) {
1274
- let pair2 = [NodeProp.lookAhead, lookAhead2];
1275
- props = props ? [pair2].concat(props) : [pair2];
1276
- }
1277
- return new Tree(type, children2, positions2, length2, props);
1278
- }
1279
- function findBufferSize(maxSize, inRepeat) {
1280
- let fork = cursor.fork();
1281
- let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1282
- let result = { size: 0, start: 0, skip: 0 };
1283
- scan:
1284
- for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
1285
- let nodeSize2 = fork.size;
1286
- if (fork.id == inRepeat && nodeSize2 >= 0) {
1287
- result.size = size;
1288
- result.start = start;
1289
- result.skip = skip;
1290
- skip += 4;
1291
- size += 4;
1292
- fork.next();
1293
- continue;
1294
- }
1295
- let startPos = fork.pos - nodeSize2;
1296
- if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
1297
- break;
1298
- let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1299
- let nodeStart = fork.start;
1300
- fork.next();
1301
- while (fork.pos > startPos) {
1302
- if (fork.size < 0) {
1303
- if (fork.size == -3)
1304
- localSkipped += 4;
1305
- else
1306
- break scan;
1307
- } else if (fork.id >= minRepeatType) {
1308
- localSkipped += 4;
1309
- }
1310
- fork.next();
1311
- }
1312
- start = nodeStart;
1313
- size += nodeSize2;
1314
- skip += localSkipped;
1315
- }
1316
- if (inRepeat < 0 || size == maxSize) {
1317
- result.size = size;
1318
- result.start = start;
1319
- result.skip = skip;
1320
- }
1321
- return result.size > 4 ? result : void 0;
1322
- }
1323
- function copyToBuffer(bufferStart, buffer2, index) {
1324
- let { id, start, end, size } = cursor;
1325
- cursor.next();
1326
- if (size >= 0 && id < minRepeatType) {
1327
- let startIndex = index;
1328
- if (size > 4) {
1329
- let endPos = cursor.pos - (size - 4);
1330
- while (cursor.pos > endPos)
1331
- index = copyToBuffer(bufferStart, buffer2, index);
1332
- }
1333
- buffer2[--index] = startIndex;
1334
- buffer2[--index] = end - bufferStart;
1335
- buffer2[--index] = start - bufferStart;
1336
- buffer2[--index] = id;
1337
- } else if (size == -3) {
1338
- contextHash = id;
1339
- } else if (size == -4) {
1340
- lookAhead = id;
1341
- }
1342
- return index;
1343
- }
1344
- let children = [], positions = [];
1345
- while (cursor.pos > 0)
1346
- takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1347
- let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
1348
- return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1349
- }
1350
- var nodeSizeCache = /* @__PURE__ */ new WeakMap();
1351
- function nodeSize(balanceType, node) {
1352
- if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1353
- return 1;
1354
- let size = nodeSizeCache.get(node);
1355
- if (size == null) {
1356
- size = 1;
1357
- for (let child of node.children) {
1358
- if (child.type != balanceType || !(child instanceof Tree)) {
1359
- size = 1;
1360
- break;
1361
- }
1362
- size += nodeSize(balanceType, child);
1363
- }
1364
- nodeSizeCache.set(node, size);
1365
- }
1366
- return size;
1367
- }
1368
- function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
1369
- let total = 0;
1370
- for (let i = from; i < to; i++)
1371
- total += nodeSize(balanceType, children[i]);
1372
- let maxChild = Math.ceil(
1373
- total * 1.5 / 8
1374
- /* Balance.BranchFactor */
1375
- );
1376
- let localChildren = [], localPositions = [];
1377
- function divide(children2, positions2, from2, to2, offset) {
1378
- for (let i = from2; i < to2; ) {
1379
- let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children2[i]);
1380
- i++;
1381
- for (; i < to2; i++) {
1382
- let nextSize = nodeSize(balanceType, children2[i]);
1383
- if (groupSize + nextSize >= maxChild)
1384
- break;
1385
- groupSize += nextSize;
1386
- }
1387
- if (i == groupFrom + 1) {
1388
- if (groupSize > maxChild) {
1389
- let only = children2[groupFrom];
1390
- divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
1391
- continue;
1392
- }
1393
- localChildren.push(children2[groupFrom]);
1394
- } else {
1395
- let length2 = positions2[i - 1] + children2[i - 1].length - groupStart;
1396
- localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i, groupStart, length2, null, mkTree));
1397
- }
1398
- localPositions.push(groupStart + offset - start);
1399
- }
1400
- }
1401
- divide(children, positions, from, to, 0);
1402
- return (mkTop || mkTree)(localChildren, localPositions, length);
1403
- }
1404
- var Parser = class {
1405
- /// Start a parse, returning a [partial parse](#common.PartialParse)
1406
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
1407
- /// make the parse incremental.
1408
- ///
1409
- /// By default, the entire input is parsed. You can pass `ranges`,
1410
- /// which should be a sorted array of non-empty, non-overlapping
1411
- /// ranges, to parse only those ranges. The tree returned in that
1412
- /// case will start at `ranges[0].from`.
1413
- startParse(input, fragments, ranges) {
1414
- if (typeof input == "string")
1415
- input = new StringInput(input);
1416
- ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map((r) => new Range(r.from, r.to)) : [new Range(0, 0)];
1417
- return this.createParse(input, fragments || [], ranges);
1418
- }
1419
- /// Run a full parse, returning the resulting tree.
1420
- parse(input, fragments, ranges) {
1421
- let parse = this.startParse(input, fragments, ranges);
1422
- for (; ; ) {
1423
- let done = parse.advance();
1424
- if (done)
1425
- return done;
1426
- }
1427
- }
1428
- };
1429
- var StringInput = class {
1430
- constructor(string) {
1431
- this.string = string;
1432
- }
1433
- get length() {
1434
- return this.string.length;
1435
- }
1436
- chunk(from) {
1437
- return this.string.slice(from);
1438
- }
1439
- get lineChunks() {
1440
- return false;
1441
- }
1442
- read(from, to) {
1443
- return this.string.slice(from, to);
1444
- }
1445
- };
1446
- var stoppedInner = new NodeProp({ perNode: true });
1447
-
1448
- // ../../node_modules/@lezer/lr/dist/index.js
1449
- var Stack = class {
1450
- /// @internal
1451
- constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) {
1452
- this.p = p;
1453
- this.stack = stack;
1454
- this.state = state;
1455
- this.reducePos = reducePos;
1456
- this.pos = pos;
1457
- this.score = score;
1458
- this.buffer = buffer;
1459
- this.bufferBase = bufferBase;
1460
- this.curContext = curContext;
1461
- this.lookAhead = lookAhead;
1462
- this.parent = parent;
1463
- }
1464
- /// @internal
1465
- toString() {
1466
- return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
1467
- }
1468
- // Start an empty stack
1469
- /// @internal
1470
- static start(p, state, pos = 0) {
1471
- let cx3 = p.parser.context;
1472
- return new Stack(p, [], state, pos, pos, 0, [], 0, cx3 ? new StackContext(cx3, cx3.start) : null, 0, null);
1473
- }
1474
- /// The stack's current [context](#lr.ContextTracker) value, if
1475
- /// any. Its type will depend on the context tracker's type
1476
- /// parameter, or it will be `null` if there is no context
1477
- /// tracker.
1478
- get context() {
1479
- return this.curContext ? this.curContext.context : null;
1480
- }
1481
- // Push a state onto the stack, tracking its start position as well
1482
- // as the buffer base at that point.
1483
- /// @internal
1484
- pushState(state, start) {
1485
- this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
1486
- this.state = state;
1487
- }
1488
- // Apply a reduce action
1489
- /// @internal
1490
- reduce(action) {
1491
- var _a;
1492
- let depth = action >> 19, type = action & 65535;
1493
- let { parser: parser2 } = this.p;
1494
- let dPrec = parser2.dynamicPrecedence(type);
1495
- if (dPrec)
1496
- this.score += dPrec;
1497
- if (depth == 0) {
1498
- this.pushState(parser2.getGoto(this.state, type, true), this.reducePos);
1499
- if (type < parser2.minRepeatTerm)
1500
- this.storeNode(type, this.reducePos, this.reducePos, 4, true);
1501
- this.reduceContext(type, this.reducePos);
1502
- return;
1503
- }
1504
- let base = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0);
1505
- let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
1506
- if (size >= 2e3 && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
1507
- if (start == this.p.lastBigReductionStart) {
1508
- this.p.bigReductionCount++;
1509
- this.p.lastBigReductionSize = size;
1510
- } else if (this.p.lastBigReductionSize < size) {
1511
- this.p.bigReductionCount = 1;
1512
- this.p.lastBigReductionStart = start;
1513
- this.p.lastBigReductionSize = size;
1514
- }
1515
- }
1516
- let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
1517
- if (type < parser2.minRepeatTerm || action & 131072) {
1518
- let pos = parser2.stateFlag(
1519
- this.state,
1520
- 1
1521
- /* StateFlag.Skipped */
1522
- ) ? this.pos : this.reducePos;
1523
- this.storeNode(type, start, pos, count + 4, true);
1524
- }
1525
- if (action & 262144) {
1526
- this.state = this.stack[base];
1527
- } else {
1528
- let baseStateID = this.stack[base - 3];
1529
- this.state = parser2.getGoto(baseStateID, type, true);
1530
- }
1531
- while (this.stack.length > base)
1532
- this.stack.pop();
1533
- this.reduceContext(type, start);
1534
- }
1535
- // Shift a value into the buffer
1536
- /// @internal
1537
- storeNode(term, start, end, size = 4, isReduce = false) {
1538
- if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
1539
- let cur = this, top = this.buffer.length;
1540
- if (top == 0 && cur.parent) {
1541
- top = cur.bufferBase - cur.parent.bufferBase;
1542
- cur = cur.parent;
1543
- }
1544
- if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) {
1545
- if (start == end)
1546
- return;
1547
- if (cur.buffer[top - 2] >= start) {
1548
- cur.buffer[top - 2] = end;
1549
- return;
1550
- }
1551
- }
1552
- }
1553
- if (!isReduce || this.pos == end) {
1554
- this.buffer.push(term, start, end, size);
1555
- } else {
1556
- let index = this.buffer.length;
1557
- if (index > 0 && this.buffer[index - 4] != 0)
1558
- while (index > 0 && this.buffer[index - 2] > end) {
1559
- this.buffer[index] = this.buffer[index - 4];
1560
- this.buffer[index + 1] = this.buffer[index - 3];
1561
- this.buffer[index + 2] = this.buffer[index - 2];
1562
- this.buffer[index + 3] = this.buffer[index - 1];
1563
- index -= 4;
1564
- if (size > 4)
1565
- size -= 4;
1566
- }
1567
- this.buffer[index] = term;
1568
- this.buffer[index + 1] = start;
1569
- this.buffer[index + 2] = end;
1570
- this.buffer[index + 3] = size;
1571
- }
1572
- }
1573
- // Apply a shift action
1574
- /// @internal
1575
- shift(action, next, nextEnd) {
1576
- let start = this.pos;
1577
- if (action & 131072) {
1578
- this.pushState(action & 65535, this.pos);
1579
- } else if ((action & 262144) == 0) {
1580
- let nextState = action, { parser: parser2 } = this.p;
1581
- if (nextEnd > this.pos || next <= parser2.maxNode) {
1582
- this.pos = nextEnd;
1583
- if (!parser2.stateFlag(
1584
- nextState,
1585
- 1
1586
- /* StateFlag.Skipped */
1587
- ))
1588
- this.reducePos = nextEnd;
1589
- }
1590
- this.pushState(nextState, start);
1591
- this.shiftContext(next, start);
1592
- if (next <= parser2.maxNode)
1593
- this.buffer.push(next, start, nextEnd, 4);
1594
- } else {
1595
- this.pos = nextEnd;
1596
- this.shiftContext(next, start);
1597
- if (next <= this.p.parser.maxNode)
1598
- this.buffer.push(next, start, nextEnd, 4);
1599
- }
1600
- }
1601
- // Apply an action
1602
- /// @internal
1603
- apply(action, next, nextEnd) {
1604
- if (action & 65536)
1605
- this.reduce(action);
1606
- else
1607
- this.shift(action, next, nextEnd);
1608
- }
1609
- // Add a prebuilt (reused) node into the buffer.
1610
- /// @internal
1611
- useNode(value, next) {
1612
- let index = this.p.reused.length - 1;
1613
- if (index < 0 || this.p.reused[index] != value) {
1614
- this.p.reused.push(value);
1615
- index++;
1616
- }
1617
- let start = this.pos;
1618
- this.reducePos = this.pos = start + value.length;
1619
- this.pushState(next, start);
1620
- this.buffer.push(
1621
- index,
1622
- start,
1623
- this.reducePos,
1624
- -1
1625
- /* size == -1 means this is a reused value */
1626
- );
1627
- if (this.curContext)
1628
- this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
1629
- }
1630
- // Split the stack. Due to the buffer sharing and the fact
1631
- // that `this.stack` tends to stay quite shallow, this isn't very
1632
- // expensive.
1633
- /// @internal
1634
- split() {
1635
- let parent = this;
1636
- let off = parent.buffer.length;
1637
- while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
1638
- off -= 4;
1639
- let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
1640
- while (parent && base == parent.bufferBase)
1641
- parent = parent.parent;
1642
- return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
1643
- }
1644
- // Try to recover from an error by 'deleting' (ignoring) one token.
1645
- /// @internal
1646
- recoverByDelete(next, nextEnd) {
1647
- let isNode = next <= this.p.parser.maxNode;
1648
- if (isNode)
1649
- this.storeNode(next, this.pos, nextEnd, 4);
1650
- this.storeNode(0, this.pos, nextEnd, isNode ? 8 : 4);
1651
- this.pos = this.reducePos = nextEnd;
1652
- this.score -= 190;
1653
- }
1654
- /// Check if the given term would be able to be shifted (optionally
1655
- /// after some reductions) on this stack. This can be useful for
1656
- /// external tokenizers that want to make sure they only provide a
1657
- /// given token when it applies.
1658
- canShift(term) {
1659
- for (let sim = new SimulatedStack(this); ; ) {
1660
- let action = this.p.parser.stateSlot(
1661
- sim.state,
1662
- 4
1663
- /* ParseState.DefaultReduce */
1664
- ) || this.p.parser.hasAction(sim.state, term);
1665
- if (action == 0)
1666
- return false;
1667
- if ((action & 65536) == 0)
1668
- return true;
1669
- sim.reduce(action);
1670
- }
1671
- }
1672
- // Apply up to Recover.MaxNext recovery actions that conceptually
1673
- // inserts some missing token or rule.
1674
- /// @internal
1675
- recoverByInsert(next) {
1676
- if (this.stack.length >= 300)
1677
- return [];
1678
- let nextStates = this.p.parser.nextStates(this.state);
1679
- if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
1680
- let best = [];
1681
- for (let i = 0, s; i < nextStates.length; i += 2) {
1682
- if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
1683
- best.push(nextStates[i], s);
1684
- }
1685
- if (this.stack.length < 120)
1686
- for (let i = 0; best.length < 4 << 1 && i < nextStates.length; i += 2) {
1687
- let s = nextStates[i + 1];
1688
- if (!best.some((v, i2) => i2 & 1 && v == s))
1689
- best.push(nextStates[i], s);
1690
- }
1691
- nextStates = best;
1692
- }
1693
- let result = [];
1694
- for (let i = 0; i < nextStates.length && result.length < 4; i += 2) {
1695
- let s = nextStates[i + 1];
1696
- if (s == this.state)
1697
- continue;
1698
- let stack = this.split();
1699
- stack.pushState(s, this.pos);
1700
- stack.storeNode(0, stack.pos, stack.pos, 4, true);
1701
- stack.shiftContext(nextStates[i], this.pos);
1702
- stack.score -= 200;
1703
- result.push(stack);
1704
- }
1705
- return result;
1706
- }
1707
- // Force a reduce, if possible. Return false if that can't
1708
- // be done.
1709
- /// @internal
1710
- forceReduce() {
1711
- let { parser: parser2 } = this.p;
1712
- let reduce = parser2.stateSlot(
1713
- this.state,
1714
- 5
1715
- /* ParseState.ForcedReduce */
1716
- );
1717
- if ((reduce & 65536) == 0)
1718
- return false;
1719
- if (!parser2.validAction(this.state, reduce)) {
1720
- let depth = reduce >> 19, term = reduce & 65535;
1721
- let target = this.stack.length - depth * 3;
1722
- if (target < 0 || parser2.getGoto(this.stack[target], term, false) < 0) {
1723
- let backup = this.findForcedReduction();
1724
- if (backup == null)
1725
- return false;
1726
- reduce = backup;
1727
- }
1728
- this.storeNode(0, this.pos, this.pos, 4, true);
1729
- this.score -= 100;
1730
- }
1731
- this.reducePos = this.pos;
1732
- this.reduce(reduce);
1733
- return true;
1734
- }
1735
- /// Try to scan through the automaton to find some kind of reduction
1736
- /// that can be applied. Used when the regular ForcedReduce field
1737
- /// isn't a valid action. @internal
1738
- findForcedReduction() {
1739
- let { parser: parser2 } = this.p, seen = [];
1740
- let explore = (state, depth) => {
1741
- if (seen.includes(state))
1742
- return;
1743
- seen.push(state);
1744
- return parser2.allActions(state, (action) => {
1745
- if (action & (262144 | 131072))
1746
- ;
1747
- else if (action & 65536) {
1748
- let rDepth = (action >> 19) - depth;
1749
- if (rDepth > 1) {
1750
- let term = action & 65535, target = this.stack.length - rDepth * 3;
1751
- if (target >= 0 && parser2.getGoto(this.stack[target], term, false) >= 0)
1752
- return rDepth << 19 | 65536 | term;
1753
- }
1754
- } else {
1755
- let found = explore(action, depth + 1);
1756
- if (found != null)
1757
- return found;
1758
- }
1759
- });
1760
- };
1761
- return explore(this.state, 0);
1762
- }
1763
- /// @internal
1764
- forceAll() {
1765
- while (!this.p.parser.stateFlag(
1766
- this.state,
1767
- 2
1768
- /* StateFlag.Accepting */
1769
- )) {
1770
- if (!this.forceReduce()) {
1771
- this.storeNode(0, this.pos, this.pos, 4, true);
1772
- break;
1773
- }
1774
- }
1775
- return this;
1776
- }
1777
- /// Check whether this state has no further actions (assumed to be a direct descendant of the
1778
- /// top state, since any other states must be able to continue
1779
- /// somehow). @internal
1780
- get deadEnd() {
1781
- if (this.stack.length != 3)
1782
- return false;
1783
- let { parser: parser2 } = this.p;
1784
- return parser2.data[parser2.stateSlot(
1785
- this.state,
1786
- 1
1787
- /* ParseState.Actions */
1788
- )] == 65535 && !parser2.stateSlot(
1789
- this.state,
1790
- 4
1791
- /* ParseState.DefaultReduce */
1792
- );
1793
- }
1794
- /// Restart the stack (put it back in its start state). Only safe
1795
- /// when this.stack.length == 3 (state is directly below the top
1796
- /// state). @internal
1797
- restart() {
1798
- this.state = this.stack[0];
1799
- this.stack.length = 0;
1800
- }
1801
- /// @internal
1802
- sameState(other) {
1803
- if (this.state != other.state || this.stack.length != other.stack.length)
1804
- return false;
1805
- for (let i = 0; i < this.stack.length; i += 3)
1806
- if (this.stack[i] != other.stack[i])
1807
- return false;
1808
- return true;
1809
- }
1810
- /// Get the parser used by this stack.
1811
- get parser() {
1812
- return this.p.parser;
1813
- }
1814
- /// Test whether a given dialect (by numeric ID, as exported from
1815
- /// the terms file) is enabled.
1816
- dialectEnabled(dialectID) {
1817
- return this.p.parser.dialect.flags[dialectID];
1818
- }
1819
- shiftContext(term, start) {
1820
- if (this.curContext)
1821
- this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
1822
- }
1823
- reduceContext(term, start) {
1824
- if (this.curContext)
1825
- this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
1826
- }
1827
- /// @internal
1828
- emitContext() {
1829
- let last = this.buffer.length - 1;
1830
- if (last < 0 || this.buffer[last] != -3)
1831
- this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
1832
- }
1833
- /// @internal
1834
- emitLookAhead() {
1835
- let last = this.buffer.length - 1;
1836
- if (last < 0 || this.buffer[last] != -4)
1837
- this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
1838
- }
1839
- updateContext(context) {
1840
- if (context != this.curContext.context) {
1841
- let newCx = new StackContext(this.curContext.tracker, context);
1842
- if (newCx.hash != this.curContext.hash)
1843
- this.emitContext();
1844
- this.curContext = newCx;
1845
- }
1846
- }
1847
- /// @internal
1848
- setLookAhead(lookAhead) {
1849
- if (lookAhead > this.lookAhead) {
1850
- this.emitLookAhead();
1851
- this.lookAhead = lookAhead;
1852
- }
1853
- }
1854
- /// @internal
1855
- close() {
1856
- if (this.curContext && this.curContext.tracker.strict)
1857
- this.emitContext();
1858
- if (this.lookAhead > 0)
1859
- this.emitLookAhead();
1860
- }
1861
- };
1862
- var StackContext = class {
1863
- constructor(tracker, context) {
1864
- this.tracker = tracker;
1865
- this.context = context;
1866
- this.hash = tracker.strict ? tracker.hash(context) : 0;
1867
- }
1868
- };
1869
- var Recover;
1870
- (function(Recover2) {
1871
- Recover2[Recover2["Insert"] = 200] = "Insert";
1872
- Recover2[Recover2["Delete"] = 190] = "Delete";
1873
- Recover2[Recover2["Reduce"] = 100] = "Reduce";
1874
- Recover2[Recover2["MaxNext"] = 4] = "MaxNext";
1875
- Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
1876
- Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
1877
- Recover2[Recover2["MinBigReduction"] = 2e3] = "MinBigReduction";
1878
- })(Recover || (Recover = {}));
1879
- var SimulatedStack = class {
1880
- constructor(start) {
1881
- this.start = start;
1882
- this.state = start.state;
1883
- this.stack = start.stack;
1884
- this.base = this.stack.length;
1885
- }
1886
- reduce(action) {
1887
- let term = action & 65535, depth = action >> 19;
1888
- if (depth == 0) {
1889
- if (this.stack == this.start.stack)
1890
- this.stack = this.stack.slice();
1891
- this.stack.push(this.state, 0, 0);
1892
- this.base += 3;
1893
- } else {
1894
- this.base -= (depth - 1) * 3;
1895
- }
1896
- let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
1897
- this.state = goto;
1898
- }
1899
- };
1900
- var StackBufferCursor = class {
1901
- constructor(stack, pos, index) {
1902
- this.stack = stack;
1903
- this.pos = pos;
1904
- this.index = index;
1905
- this.buffer = stack.buffer;
1906
- if (this.index == 0)
1907
- this.maybeNext();
1908
- }
1909
- static create(stack, pos = stack.bufferBase + stack.buffer.length) {
1910
- return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
1911
- }
1912
- maybeNext() {
1913
- let next = this.stack.parent;
1914
- if (next != null) {
1915
- this.index = this.stack.bufferBase - next.bufferBase;
1916
- this.stack = next;
1917
- this.buffer = next.buffer;
1918
- }
1919
- }
1920
- get id() {
1921
- return this.buffer[this.index - 4];
1922
- }
1923
- get start() {
1924
- return this.buffer[this.index - 3];
1925
- }
1926
- get end() {
1927
- return this.buffer[this.index - 2];
1928
- }
1929
- get size() {
1930
- return this.buffer[this.index - 1];
1931
- }
1932
- next() {
1933
- this.index -= 4;
1934
- this.pos -= 4;
1935
- if (this.index == 0)
1936
- this.maybeNext();
1937
- }
1938
- fork() {
1939
- return new StackBufferCursor(this.stack, this.pos, this.index);
1940
- }
1941
- };
1942
- function decodeArray(input, Type = Uint16Array) {
1943
- if (typeof input != "string")
1944
- return input;
1945
- let array = null;
1946
- for (let pos = 0, out = 0; pos < input.length; ) {
1947
- let value = 0;
1948
- for (; ; ) {
1949
- let next = input.charCodeAt(pos++), stop = false;
1950
- if (next == 126) {
1951
- value = 65535;
1952
- break;
1953
- }
1954
- if (next >= 92)
1955
- next--;
1956
- if (next >= 34)
1957
- next--;
1958
- let digit = next - 32;
1959
- if (digit >= 46) {
1960
- digit -= 46;
1961
- stop = true;
1962
- }
1963
- value += digit;
1964
- if (stop)
1965
- break;
1966
- value *= 46;
1967
- }
1968
- if (array)
1969
- array[out++] = value;
1970
- else
1971
- array = new Type(value);
1972
- }
1973
- return array;
1974
- }
1975
- var CachedToken = class {
1976
- constructor() {
1977
- this.start = -1;
1978
- this.value = -1;
1979
- this.end = -1;
1980
- this.extended = -1;
1981
- this.lookAhead = 0;
1982
- this.mask = 0;
1983
- this.context = 0;
1984
- }
1985
- };
1986
- var nullToken = new CachedToken();
1987
- var InputStream = class {
1988
- /// @internal
1989
- constructor(input, ranges) {
1990
- this.input = input;
1991
- this.ranges = ranges;
1992
- this.chunk = "";
1993
- this.chunkOff = 0;
1994
- this.chunk2 = "";
1995
- this.chunk2Pos = 0;
1996
- this.next = -1;
1997
- this.token = nullToken;
1998
- this.rangeIndex = 0;
1999
- this.pos = this.chunkPos = ranges[0].from;
2000
- this.range = ranges[0];
2001
- this.end = ranges[ranges.length - 1].to;
2002
- this.readNext();
2003
- }
2004
- /// @internal
2005
- resolveOffset(offset, assoc) {
2006
- let range = this.range, index = this.rangeIndex;
2007
- let pos = this.pos + offset;
2008
- while (pos < range.from) {
2009
- if (!index)
2010
- return null;
2011
- let next = this.ranges[--index];
2012
- pos -= range.from - next.to;
2013
- range = next;
2014
- }
2015
- while (assoc < 0 ? pos > range.to : pos >= range.to) {
2016
- if (index == this.ranges.length - 1)
2017
- return null;
2018
- let next = this.ranges[++index];
2019
- pos += next.from - range.to;
2020
- range = next;
2021
- }
2022
- return pos;
2023
- }
2024
- /// @internal
2025
- clipPos(pos) {
2026
- if (pos >= this.range.from && pos < this.range.to)
2027
- return pos;
2028
- for (let range of this.ranges)
2029
- if (range.to > pos)
2030
- return Math.max(pos, range.from);
2031
- return this.end;
2032
- }
2033
- /// Look at a code unit near the stream position. `.peek(0)` equals
2034
- /// `.next`, `.peek(-1)` gives you the previous character, and so
2035
- /// on.
2036
- ///
2037
- /// Note that looking around during tokenizing creates dependencies
2038
- /// on potentially far-away content, which may reduce the
2039
- /// effectiveness incremental parsing—when looking forward—or even
2040
- /// cause invalid reparses when looking backward more than 25 code
2041
- /// units, since the library does not track lookbehind.
2042
- peek(offset) {
2043
- let idx = this.chunkOff + offset, pos, result;
2044
- if (idx >= 0 && idx < this.chunk.length) {
2045
- pos = this.pos + offset;
2046
- result = this.chunk.charCodeAt(idx);
2047
- } else {
2048
- let resolved = this.resolveOffset(offset, 1);
2049
- if (resolved == null)
2050
- return -1;
2051
- pos = resolved;
2052
- if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
2053
- result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
2054
- } else {
2055
- let i = this.rangeIndex, range = this.range;
2056
- while (range.to <= pos)
2057
- range = this.ranges[++i];
2058
- this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
2059
- if (pos + this.chunk2.length > range.to)
2060
- this.chunk2 = this.chunk2.slice(0, range.to - pos);
2061
- result = this.chunk2.charCodeAt(0);
2062
- }
2063
- }
2064
- if (pos >= this.token.lookAhead)
2065
- this.token.lookAhead = pos + 1;
2066
- return result;
2067
- }
2068
- /// Accept a token. By default, the end of the token is set to the
2069
- /// current stream position, but you can pass an offset (relative to
2070
- /// the stream position) to change that.
2071
- acceptToken(token, endOffset = 0) {
2072
- let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
2073
- if (end == null || end < this.token.start)
2074
- throw new RangeError("Token end out of bounds");
2075
- this.token.value = token;
2076
- this.token.end = end;
2077
- }
2078
- getChunk() {
2079
- if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
2080
- let { chunk, chunkPos } = this;
2081
- this.chunk = this.chunk2;
2082
- this.chunkPos = this.chunk2Pos;
2083
- this.chunk2 = chunk;
2084
- this.chunk2Pos = chunkPos;
2085
- this.chunkOff = this.pos - this.chunkPos;
2086
- } else {
2087
- this.chunk2 = this.chunk;
2088
- this.chunk2Pos = this.chunkPos;
2089
- let nextChunk = this.input.chunk(this.pos);
2090
- let end = this.pos + nextChunk.length;
2091
- this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
2092
- this.chunkPos = this.pos;
2093
- this.chunkOff = 0;
2094
- }
2095
- }
2096
- readNext() {
2097
- if (this.chunkOff >= this.chunk.length) {
2098
- this.getChunk();
2099
- if (this.chunkOff == this.chunk.length)
2100
- return this.next = -1;
2101
- }
2102
- return this.next = this.chunk.charCodeAt(this.chunkOff);
2103
- }
2104
- /// Move the stream forward N (defaults to 1) code units. Returns
2105
- /// the new value of [`next`](#lr.InputStream.next).
2106
- advance(n = 1) {
2107
- this.chunkOff += n;
2108
- while (this.pos + n >= this.range.to) {
2109
- if (this.rangeIndex == this.ranges.length - 1)
2110
- return this.setDone();
2111
- n -= this.range.to - this.pos;
2112
- this.range = this.ranges[++this.rangeIndex];
2113
- this.pos = this.range.from;
2114
- }
2115
- this.pos += n;
2116
- if (this.pos >= this.token.lookAhead)
2117
- this.token.lookAhead = this.pos + 1;
2118
- return this.readNext();
2119
- }
2120
- setDone() {
2121
- this.pos = this.chunkPos = this.end;
2122
- this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
2123
- this.chunk = "";
2124
- return this.next = -1;
2125
- }
2126
- /// @internal
2127
- reset(pos, token) {
2128
- if (token) {
2129
- this.token = token;
2130
- token.start = pos;
2131
- token.lookAhead = pos + 1;
2132
- token.value = token.extended = -1;
2133
- } else {
2134
- this.token = nullToken;
2135
- }
2136
- if (this.pos != pos) {
2137
- this.pos = pos;
2138
- if (pos == this.end) {
2139
- this.setDone();
2140
- return this;
2141
- }
2142
- while (pos < this.range.from)
2143
- this.range = this.ranges[--this.rangeIndex];
2144
- while (pos >= this.range.to)
2145
- this.range = this.ranges[++this.rangeIndex];
2146
- if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
2147
- this.chunkOff = pos - this.chunkPos;
2148
- } else {
2149
- this.chunk = "";
2150
- this.chunkOff = 0;
2151
- }
2152
- this.readNext();
2153
- }
2154
- return this;
2155
- }
2156
- /// @internal
2157
- read(from, to) {
2158
- if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
2159
- return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
2160
- if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
2161
- return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
2162
- if (from >= this.range.from && to <= this.range.to)
2163
- return this.input.read(from, to);
2164
- let result = "";
2165
- for (let r of this.ranges) {
2166
- if (r.from >= to)
2167
- break;
2168
- if (r.to > from)
2169
- result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
2170
- }
2171
- return result;
2172
- }
2173
- };
2174
- var TokenGroup = class {
2175
- constructor(data, id) {
2176
- this.data = data;
2177
- this.id = id;
2178
- }
2179
- token(input, stack) {
2180
- let { parser: parser2 } = stack.p;
2181
- readToken(this.data, input, stack, this.id, parser2.data, parser2.tokenPrecTable);
2182
- }
2183
- };
2184
- TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2185
- var LocalTokenGroup = class {
2186
- constructor(data, precTable, elseToken) {
2187
- this.precTable = precTable;
2188
- this.elseToken = elseToken;
2189
- this.data = typeof data == "string" ? decodeArray(data) : data;
2190
- }
2191
- token(input, stack) {
2192
- let start = input.pos, skipped = 0;
2193
- for (; ; ) {
2194
- let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
2195
- readToken(this.data, input, stack, 0, this.data, this.precTable);
2196
- if (input.token.value > -1)
2197
- break;
2198
- if (this.elseToken == null)
2199
- return;
2200
- if (!atEof)
2201
- skipped++;
2202
- if (nextPos == null)
2203
- break;
2204
- input.reset(nextPos, input.token);
2205
- }
2206
- if (skipped) {
2207
- input.reset(start, input.token);
2208
- input.acceptToken(this.elseToken, skipped);
2209
- }
2210
- }
2211
- };
2212
- LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2213
- function readToken(data, input, stack, group, precTable, precOffset) {
2214
- let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
2215
- scan:
2216
- for (; ; ) {
2217
- if ((groupMask & data[state]) == 0)
2218
- break;
2219
- let accEnd = data[state + 1];
2220
- for (let i = state + 3; i < accEnd; i += 2)
2221
- if ((data[i + 1] & groupMask) > 0) {
2222
- let term = data[i];
2223
- if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
2224
- input.acceptToken(term);
2225
- break;
2226
- }
2227
- }
2228
- let next = input.next, low = 0, high = data[state + 2];
2229
- if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 && data[accEnd + high * 3 - 3] == 65535) {
2230
- state = data[accEnd + high * 3 - 1];
2231
- continue scan;
2232
- }
2233
- for (; low < high; ) {
2234
- let mid = low + high >> 1;
2235
- let index = accEnd + mid + (mid << 1);
2236
- let from = data[index], to = data[index + 1] || 65536;
2237
- if (next < from)
2238
- high = mid;
2239
- else if (next >= to)
2240
- low = mid + 1;
2241
- else {
2242
- state = data[index + 2];
2243
- input.advance();
2244
- continue scan;
2245
- }
2246
- }
2247
- break;
2248
- }
2249
- }
2250
- function findOffset(data, start, term) {
2251
- for (let i = start, next; (next = data[i]) != 65535; i++)
2252
- if (next == term)
2253
- return i - start;
2254
- return -1;
2255
- }
2256
- function overrides(token, prev, tableData, tableOffset) {
2257
- let iPrev = findOffset(tableData, tableOffset, prev);
2258
- return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
2259
- }
2260
- var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
2261
- var stackIDs = null;
2262
- var Safety;
2263
- (function(Safety2) {
2264
- Safety2[Safety2["Margin"] = 25] = "Margin";
2265
- })(Safety || (Safety = {}));
2266
- function cutAt(tree, pos, side) {
2267
- let cursor = tree.cursor(IterMode.IncludeAnonymous);
2268
- cursor.moveTo(pos);
2269
- for (; ; ) {
2270
- if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
2271
- for (; ; ) {
2272
- if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
2273
- return side < 0 ? Math.max(0, Math.min(
2274
- cursor.to - 1,
2275
- pos - 25
2276
- /* Safety.Margin */
2277
- )) : Math.min(tree.length, Math.max(
2278
- cursor.from + 1,
2279
- pos + 25
2280
- /* Safety.Margin */
2281
- ));
2282
- if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
2283
- break;
2284
- if (!cursor.parent())
2285
- return side < 0 ? 0 : tree.length;
2286
- }
2287
- }
2288
- }
2289
- var FragmentCursor = class {
2290
- constructor(fragments, nodeSet) {
2291
- this.fragments = fragments;
2292
- this.nodeSet = nodeSet;
2293
- this.i = 0;
2294
- this.fragment = null;
2295
- this.safeFrom = -1;
2296
- this.safeTo = -1;
2297
- this.trees = [];
2298
- this.start = [];
2299
- this.index = [];
2300
- this.nextFragment();
2301
- }
2302
- nextFragment() {
2303
- let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
2304
- if (fr) {
2305
- this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
2306
- this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
2307
- while (this.trees.length) {
2308
- this.trees.pop();
2309
- this.start.pop();
2310
- this.index.pop();
2311
- }
2312
- this.trees.push(fr.tree);
2313
- this.start.push(-fr.offset);
2314
- this.index.push(0);
2315
- this.nextStart = this.safeFrom;
2316
- } else {
2317
- this.nextStart = 1e9;
2318
- }
2319
- }
2320
- // `pos` must be >= any previously given `pos` for this cursor
2321
- nodeAt(pos) {
2322
- if (pos < this.nextStart)
2323
- return null;
2324
- while (this.fragment && this.safeTo <= pos)
2325
- this.nextFragment();
2326
- if (!this.fragment)
2327
- return null;
2328
- for (; ; ) {
2329
- let last = this.trees.length - 1;
2330
- if (last < 0) {
2331
- this.nextFragment();
2332
- return null;
2333
- }
2334
- let top = this.trees[last], index = this.index[last];
2335
- if (index == top.children.length) {
2336
- this.trees.pop();
2337
- this.start.pop();
2338
- this.index.pop();
2339
- continue;
2340
- }
2341
- let next = top.children[index];
2342
- let start = this.start[last] + top.positions[index];
2343
- if (start > pos) {
2344
- this.nextStart = start;
2345
- return null;
2346
- }
2347
- if (next instanceof Tree) {
2348
- if (start == pos) {
2349
- if (start < this.safeFrom)
2350
- return null;
2351
- let end = start + next.length;
2352
- if (end <= this.safeTo) {
2353
- let lookAhead = next.prop(NodeProp.lookAhead);
2354
- if (!lookAhead || end + lookAhead < this.fragment.to)
2355
- return next;
2356
- }
2357
- }
2358
- this.index[last]++;
2359
- if (start + next.length >= Math.max(this.safeFrom, pos)) {
2360
- this.trees.push(next);
2361
- this.start.push(start);
2362
- this.index.push(0);
2363
- }
2364
- } else {
2365
- this.index[last]++;
2366
- this.nextStart = start + next.length;
2367
- }
2368
- }
2369
- }
2370
- };
2371
- var TokenCache = class {
2372
- constructor(parser2, stream) {
2373
- this.stream = stream;
2374
- this.tokens = [];
2375
- this.mainToken = null;
2376
- this.actions = [];
2377
- this.tokens = parser2.tokenizers.map((_) => new CachedToken());
2378
- }
2379
- getActions(stack) {
2380
- let actionIndex = 0;
2381
- let main = null;
2382
- let { parser: parser2 } = stack.p, { tokenizers } = parser2;
2383
- let mask = parser2.stateSlot(
2384
- stack.state,
2385
- 3
2386
- /* ParseState.TokenizerMask */
2387
- );
2388
- let context = stack.curContext ? stack.curContext.hash : 0;
2389
- let lookAhead = 0;
2390
- for (let i = 0; i < tokenizers.length; i++) {
2391
- if ((1 << i & mask) == 0)
2392
- continue;
2393
- let tokenizer = tokenizers[i], token = this.tokens[i];
2394
- if (main && !tokenizer.fallback)
2395
- continue;
2396
- if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
2397
- this.updateCachedToken(token, tokenizer, stack);
2398
- token.mask = mask;
2399
- token.context = context;
2400
- }
2401
- if (token.lookAhead > token.end + 25)
2402
- lookAhead = Math.max(token.lookAhead, lookAhead);
2403
- if (token.value != 0) {
2404
- let startIndex = actionIndex;
2405
- if (token.extended > -1)
2406
- actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
2407
- actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
2408
- if (!tokenizer.extend) {
2409
- main = token;
2410
- if (actionIndex > startIndex)
2411
- break;
2412
- }
2413
- }
2414
- }
2415
- while (this.actions.length > actionIndex)
2416
- this.actions.pop();
2417
- if (lookAhead)
2418
- stack.setLookAhead(lookAhead);
2419
- if (!main && stack.pos == this.stream.end) {
2420
- main = new CachedToken();
2421
- main.value = stack.p.parser.eofTerm;
2422
- main.start = main.end = stack.pos;
2423
- actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
2424
- }
2425
- this.mainToken = main;
2426
- return this.actions;
2427
- }
2428
- getMainToken(stack) {
2429
- if (this.mainToken)
2430
- return this.mainToken;
2431
- let main = new CachedToken(), { pos, p } = stack;
2432
- main.start = pos;
2433
- main.end = Math.min(pos + 1, p.stream.end);
2434
- main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
2435
- return main;
2436
- }
2437
- updateCachedToken(token, tokenizer, stack) {
2438
- let start = this.stream.clipPos(stack.pos);
2439
- tokenizer.token(this.stream.reset(start, token), stack);
2440
- if (token.value > -1) {
2441
- let { parser: parser2 } = stack.p;
2442
- for (let i = 0; i < parser2.specialized.length; i++)
2443
- if (parser2.specialized[i] == token.value) {
2444
- let result = parser2.specializers[i](this.stream.read(token.start, token.end), stack);
2445
- if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
2446
- if ((result & 1) == 0)
2447
- token.value = result >> 1;
2448
- else
2449
- token.extended = result >> 1;
2450
- break;
2451
- }
2452
- }
2453
- } else {
2454
- token.value = 0;
2455
- token.end = this.stream.clipPos(start + 1);
2456
- }
2457
- }
2458
- putAction(action, token, end, index) {
2459
- for (let i = 0; i < index; i += 3)
2460
- if (this.actions[i] == action)
2461
- return index;
2462
- this.actions[index++] = action;
2463
- this.actions[index++] = token;
2464
- this.actions[index++] = end;
2465
- return index;
2466
- }
2467
- addActions(stack, token, end, index) {
2468
- let { state } = stack, { parser: parser2 } = stack.p, { data } = parser2;
2469
- for (let set = 0; set < 2; set++) {
2470
- for (let i = parser2.stateSlot(
2471
- state,
2472
- set ? 2 : 1
2473
- /* ParseState.Actions */
2474
- ); ; i += 3) {
2475
- if (data[i] == 65535) {
2476
- if (data[i + 1] == 1) {
2477
- i = pair(data, i + 2);
2478
- } else {
2479
- if (index == 0 && data[i + 1] == 2)
2480
- index = this.putAction(pair(data, i + 2), token, end, index);
2481
- break;
2482
- }
2483
- }
2484
- if (data[i] == token)
2485
- index = this.putAction(pair(data, i + 1), token, end, index);
2486
- }
2487
- }
2488
- return index;
2489
- }
2490
- };
2491
- var Rec;
2492
- (function(Rec2) {
2493
- Rec2[Rec2["Distance"] = 5] = "Distance";
2494
- Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
2495
- Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune";
2496
- Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit";
2497
- Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth";
2498
- Rec2[Rec2["CutTo"] = 9e3] = "CutTo";
2499
- Rec2[Rec2["MaxLeftAssociativeReductionCount"] = 300] = "MaxLeftAssociativeReductionCount";
2500
- Rec2[Rec2["MaxStackCount"] = 12] = "MaxStackCount";
2501
- })(Rec || (Rec = {}));
2502
- var Parse = class {
2503
- constructor(parser2, input, fragments, ranges) {
2504
- this.parser = parser2;
2505
- this.input = input;
2506
- this.ranges = ranges;
2507
- this.recovering = 0;
2508
- this.nextStackID = 9812;
2509
- this.minStackPos = 0;
2510
- this.reused = [];
2511
- this.stoppedAt = null;
2512
- this.lastBigReductionStart = -1;
2513
- this.lastBigReductionSize = 0;
2514
- this.bigReductionCount = 0;
2515
- this.stream = new InputStream(input, ranges);
2516
- this.tokens = new TokenCache(parser2, this.stream);
2517
- this.topTerm = parser2.top[1];
2518
- let { from } = ranges[0];
2519
- this.stacks = [Stack.start(this, parser2.top[0], from)];
2520
- this.fragments = fragments.length && this.stream.end - from > parser2.bufferLength * 4 ? new FragmentCursor(fragments, parser2.nodeSet) : null;
2521
- }
2522
- get parsedPos() {
2523
- return this.minStackPos;
2524
- }
2525
- // Move the parser forward. This will process all parse stacks at
2526
- // `this.pos` and try to advance them to a further position. If no
2527
- // stack for such a position is found, it'll start error-recovery.
2528
- //
2529
- // When the parse is finished, this will return a syntax tree. When
2530
- // not, it returns `null`.
2531
- advance() {
2532
- let stacks = this.stacks, pos = this.minStackPos;
2533
- let newStacks = this.stacks = [];
2534
- let stopped, stoppedTokens;
2535
- if (this.bigReductionCount > 300 && stacks.length == 1) {
2536
- let [s] = stacks;
2537
- while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) {
2538
- }
2539
- this.bigReductionCount = this.lastBigReductionSize = 0;
2540
- }
2541
- for (let i = 0; i < stacks.length; i++) {
2542
- let stack = stacks[i];
2543
- for (; ; ) {
2544
- this.tokens.mainToken = null;
2545
- if (stack.pos > pos) {
2546
- newStacks.push(stack);
2547
- } else if (this.advanceStack(stack, newStacks, stacks)) {
2548
- continue;
2549
- } else {
2550
- if (!stopped) {
2551
- stopped = [];
2552
- stoppedTokens = [];
2553
- }
2554
- stopped.push(stack);
2555
- let tok = this.tokens.getMainToken(stack);
2556
- stoppedTokens.push(tok.value, tok.end);
2557
- }
2558
- break;
2559
- }
2560
- }
2561
- if (!newStacks.length) {
2562
- let finished = stopped && findFinished(stopped);
2563
- if (finished)
2564
- return this.stackToTree(finished);
2565
- if (this.parser.strict) {
2566
- if (verbose && stopped)
2567
- console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
2568
- throw new SyntaxError("No parse at " + pos);
2569
- }
2570
- if (!this.recovering)
2571
- this.recovering = 5;
2572
- }
2573
- if (this.recovering && stopped) {
2574
- let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
2575
- if (finished)
2576
- return this.stackToTree(finished.forceAll());
2577
- }
2578
- if (this.recovering) {
2579
- let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
2580
- if (newStacks.length > maxRemaining) {
2581
- newStacks.sort((a, b) => b.score - a.score);
2582
- while (newStacks.length > maxRemaining)
2583
- newStacks.pop();
2584
- }
2585
- if (newStacks.some((s) => s.reducePos > pos))
2586
- this.recovering--;
2587
- } else if (newStacks.length > 1) {
2588
- outer:
2589
- for (let i = 0; i < newStacks.length - 1; i++) {
2590
- let stack = newStacks[i];
2591
- for (let j = i + 1; j < newStacks.length; j++) {
2592
- let other = newStacks[j];
2593
- if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) {
2594
- if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) {
2595
- newStacks.splice(j--, 1);
2596
- } else {
2597
- newStacks.splice(i--, 1);
2598
- continue outer;
2599
- }
2600
- }
2601
- }
2602
- }
2603
- if (newStacks.length > 12)
2604
- newStacks.splice(
2605
- 12,
2606
- newStacks.length - 12
2607
- /* Rec.MaxStackCount */
2608
- );
2609
- }
2610
- this.minStackPos = newStacks[0].pos;
2611
- for (let i = 1; i < newStacks.length; i++)
2612
- if (newStacks[i].pos < this.minStackPos)
2613
- this.minStackPos = newStacks[i].pos;
2614
- return null;
2615
- }
2616
- stopAt(pos) {
2617
- if (this.stoppedAt != null && this.stoppedAt < pos)
2618
- throw new RangeError("Can't move stoppedAt forward");
2619
- this.stoppedAt = pos;
2620
- }
2621
- // Returns an updated version of the given stack, or null if the
2622
- // stack can't advance normally. When `split` and `stacks` are
2623
- // given, stacks split off by ambiguous operations will be pushed to
2624
- // `split`, or added to `stacks` if they move `pos` forward.
2625
- advanceStack(stack, stacks, split) {
2626
- let start = stack.pos, { parser: parser2 } = this;
2627
- let base = verbose ? this.stackID(stack) + " -> " : "";
2628
- if (this.stoppedAt != null && start > this.stoppedAt)
2629
- return stack.forceReduce() ? stack : null;
2630
- if (this.fragments) {
2631
- let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
2632
- for (let cached = this.fragments.nodeAt(start); cached; ) {
2633
- let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser2.getGoto(stack.state, cached.type.id) : -1;
2634
- if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
2635
- stack.useNode(cached, match);
2636
- if (verbose)
2637
- console.log(base + this.stackID(stack) + ` (via reuse of ${parser2.getName(cached.type.id)})`);
2638
- return true;
2639
- }
2640
- if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
2641
- break;
2642
- let inner = cached.children[0];
2643
- if (inner instanceof Tree && cached.positions[0] == 0)
2644
- cached = inner;
2645
- else
2646
- break;
2647
- }
2648
- }
2649
- let defaultReduce = parser2.stateSlot(
2650
- stack.state,
2651
- 4
2652
- /* ParseState.DefaultReduce */
2653
- );
2654
- if (defaultReduce > 0) {
2655
- stack.reduce(defaultReduce);
2656
- if (verbose)
2657
- console.log(base + this.stackID(stack) + ` (via always-reduce ${parser2.getName(
2658
- defaultReduce & 65535
2659
- /* Action.ValueMask */
2660
- )})`);
2661
- return true;
2662
- }
2663
- if (stack.stack.length >= 15e3) {
2664
- while (stack.stack.length > 9e3 && stack.forceReduce()) {
2665
- }
2666
- }
2667
- let actions = this.tokens.getActions(stack);
2668
- for (let i = 0; i < actions.length; ) {
2669
- let action = actions[i++], term = actions[i++], end = actions[i++];
2670
- let last = i == actions.length || !split;
2671
- let localStack = last ? stack : stack.split();
2672
- localStack.apply(action, term, end);
2673
- if (verbose)
2674
- console.log(base + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser2.getName(
2675
- action & 65535
2676
- /* Action.ValueMask */
2677
- )}`} for ${parser2.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
2678
- if (last)
2679
- return true;
2680
- else if (localStack.pos > start)
2681
- stacks.push(localStack);
2682
- else
2683
- split.push(localStack);
2684
- }
2685
- return false;
2686
- }
2687
- // Advance a given stack forward as far as it will go. Returns the
2688
- // (possibly updated) stack if it got stuck, or null if it moved
2689
- // forward and was given to `pushStackDedup`.
2690
- advanceFully(stack, newStacks) {
2691
- let pos = stack.pos;
2692
- for (; ; ) {
2693
- if (!this.advanceStack(stack, null, null))
2694
- return false;
2695
- if (stack.pos > pos) {
2696
- pushStackDedup(stack, newStacks);
2697
- return true;
2698
- }
2699
- }
2700
- }
2701
- runRecovery(stacks, tokens, newStacks) {
2702
- let finished = null, restarted = false;
2703
- for (let i = 0; i < stacks.length; i++) {
2704
- let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
2705
- let base = verbose ? this.stackID(stack) + " -> " : "";
2706
- if (stack.deadEnd) {
2707
- if (restarted)
2708
- continue;
2709
- restarted = true;
2710
- stack.restart();
2711
- if (verbose)
2712
- console.log(base + this.stackID(stack) + " (restarted)");
2713
- let done = this.advanceFully(stack, newStacks);
2714
- if (done)
2715
- continue;
2716
- }
2717
- let force = stack.split(), forceBase = base;
2718
- for (let j = 0; force.forceReduce() && j < 10; j++) {
2719
- if (verbose)
2720
- console.log(forceBase + this.stackID(force) + " (via force-reduce)");
2721
- let done = this.advanceFully(force, newStacks);
2722
- if (done)
2723
- break;
2724
- if (verbose)
2725
- forceBase = this.stackID(force) + " -> ";
2726
- }
2727
- for (let insert of stack.recoverByInsert(token)) {
2728
- if (verbose)
2729
- console.log(base + this.stackID(insert) + " (via recover-insert)");
2730
- this.advanceFully(insert, newStacks);
2731
- }
2732
- if (this.stream.end > stack.pos) {
2733
- if (tokenEnd == stack.pos) {
2734
- tokenEnd++;
2735
- token = 0;
2736
- }
2737
- stack.recoverByDelete(token, tokenEnd);
2738
- if (verbose)
2739
- console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
2740
- pushStackDedup(stack, newStacks);
2741
- } else if (!finished || finished.score < stack.score) {
2742
- finished = stack;
2743
- }
2744
- }
2745
- return finished;
2746
- }
2747
- // Convert the stack's buffer to a syntax tree.
2748
- stackToTree(stack) {
2749
- stack.close();
2750
- return Tree.build({
2751
- buffer: StackBufferCursor.create(stack),
2752
- nodeSet: this.parser.nodeSet,
2753
- topID: this.topTerm,
2754
- maxBufferLength: this.parser.bufferLength,
2755
- reused: this.reused,
2756
- start: this.ranges[0].from,
2757
- length: stack.pos - this.ranges[0].from,
2758
- minRepeatType: this.parser.minRepeatTerm
2759
- });
2760
- }
2761
- stackID(stack) {
2762
- let id = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack);
2763
- if (!id)
2764
- stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
2765
- return id + stack;
2766
- }
2767
- };
2768
- function pushStackDedup(stack, newStacks) {
2769
- for (let i = 0; i < newStacks.length; i++) {
2770
- let other = newStacks[i];
2771
- if (other.pos == stack.pos && other.sameState(stack)) {
2772
- if (newStacks[i].score < stack.score)
2773
- newStacks[i] = stack;
2774
- return;
2775
- }
2776
- }
2777
- newStacks.push(stack);
2778
- }
2779
- var Dialect = class {
2780
- constructor(source, flags, disabled) {
2781
- this.source = source;
2782
- this.flags = flags;
2783
- this.disabled = disabled;
2784
- }
2785
- allows(term) {
2786
- return !this.disabled || this.disabled[term] == 0;
2787
- }
2788
- };
2789
- var LRParser = class extends Parser {
2790
- /// @internal
2791
- constructor(spec) {
2792
- super();
2793
- this.wrappers = [];
2794
- if (spec.version != 14)
2795
- throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
2796
- let nodeNames = spec.nodeNames.split(" ");
2797
- this.minRepeatTerm = nodeNames.length;
2798
- for (let i = 0; i < spec.repeatNodeCount; i++)
2799
- nodeNames.push("");
2800
- let topTerms = Object.keys(spec.topRules).map((r) => spec.topRules[r][1]);
2801
- let nodeProps = [];
2802
- for (let i = 0; i < nodeNames.length; i++)
2803
- nodeProps.push([]);
2804
- function setProp(nodeID, prop, value) {
2805
- nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
2806
- }
2807
- if (spec.nodeProps)
2808
- for (let propSpec of spec.nodeProps) {
2809
- let prop = propSpec[0];
2810
- if (typeof prop == "string")
2811
- prop = NodeProp[prop];
2812
- for (let i = 1; i < propSpec.length; ) {
2813
- let next = propSpec[i++];
2814
- if (next >= 0) {
2815
- setProp(next, prop, propSpec[i++]);
2816
- } else {
2817
- let value = propSpec[i + -next];
2818
- for (let j = -next; j > 0; j--)
2819
- setProp(propSpec[i++], prop, value);
2820
- i++;
2821
- }
2822
- }
2823
- }
2824
- this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
2825
- name: i >= this.minRepeatTerm ? void 0 : name,
2826
- id: i,
2827
- props: nodeProps[i],
2828
- top: topTerms.indexOf(i) > -1,
2829
- error: i == 0,
2830
- skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
2831
- })));
2832
- if (spec.propSources)
2833
- this.nodeSet = this.nodeSet.extend(...spec.propSources);
2834
- this.strict = false;
2835
- this.bufferLength = DefaultBufferLength;
2836
- let tokenArray = decodeArray(spec.tokenData);
2837
- this.context = spec.context;
2838
- this.specializerSpecs = spec.specialized || [];
2839
- this.specialized = new Uint16Array(this.specializerSpecs.length);
2840
- for (let i = 0; i < this.specializerSpecs.length; i++)
2841
- this.specialized[i] = this.specializerSpecs[i].term;
2842
- this.specializers = this.specializerSpecs.map(getSpecializer);
2843
- this.states = decodeArray(spec.states, Uint32Array);
2844
- this.data = decodeArray(spec.stateData);
2845
- this.goto = decodeArray(spec.goto);
2846
- this.maxTerm = spec.maxTerm;
2847
- this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
2848
- this.topRules = spec.topRules;
2849
- this.dialects = spec.dialects || {};
2850
- this.dynamicPrecedences = spec.dynamicPrecedences || null;
2851
- this.tokenPrecTable = spec.tokenPrec;
2852
- this.termNames = spec.termNames || null;
2853
- this.maxNode = this.nodeSet.types.length - 1;
2854
- this.dialect = this.parseDialect();
2855
- this.top = this.topRules[Object.keys(this.topRules)[0]];
2856
- }
2857
- createParse(input, fragments, ranges) {
2858
- let parse = new Parse(this, input, fragments, ranges);
2859
- for (let w of this.wrappers)
2860
- parse = w(parse, input, fragments, ranges);
2861
- return parse;
2862
- }
2863
- /// Get a goto table entry @internal
2864
- getGoto(state, term, loose = false) {
2865
- let table = this.goto;
2866
- if (term >= table[0])
2867
- return -1;
2868
- for (let pos = table[term + 1]; ; ) {
2869
- let groupTag = table[pos++], last = groupTag & 1;
2870
- let target = table[pos++];
2871
- if (last && loose)
2872
- return target;
2873
- for (let end = pos + (groupTag >> 1); pos < end; pos++)
2874
- if (table[pos] == state)
2875
- return target;
2876
- if (last)
2877
- return -1;
2878
- }
2879
- }
2880
- /// Check if this state has an action for a given terminal @internal
2881
- hasAction(state, terminal) {
2882
- let data = this.data;
2883
- for (let set = 0; set < 2; set++) {
2884
- for (let i = this.stateSlot(
2885
- state,
2886
- set ? 2 : 1
2887
- /* ParseState.Actions */
2888
- ), next; ; i += 3) {
2889
- if ((next = data[i]) == 65535) {
2890
- if (data[i + 1] == 1)
2891
- next = data[i = pair(data, i + 2)];
2892
- else if (data[i + 1] == 2)
2893
- return pair(data, i + 2);
2894
- else
2895
- break;
2896
- }
2897
- if (next == terminal || next == 0)
2898
- return pair(data, i + 1);
2899
- }
2900
- }
2901
- return 0;
2902
- }
2903
- /// @internal
2904
- stateSlot(state, slot) {
2905
- return this.states[state * 6 + slot];
2906
- }
2907
- /// @internal
2908
- stateFlag(state, flag) {
2909
- return (this.stateSlot(
2910
- state,
2911
- 0
2912
- /* ParseState.Flags */
2913
- ) & flag) > 0;
2914
- }
2915
- /// @internal
2916
- validAction(state, action) {
2917
- return !!this.allActions(state, (a) => a == action ? true : null);
2918
- }
2919
- /// @internal
2920
- allActions(state, action) {
2921
- let deflt = this.stateSlot(
2922
- state,
2923
- 4
2924
- /* ParseState.DefaultReduce */
2925
- );
2926
- let result = deflt ? action(deflt) : void 0;
2927
- for (let i = this.stateSlot(
2928
- state,
2929
- 1
2930
- /* ParseState.Actions */
2931
- ); result == null; i += 3) {
2932
- if (this.data[i] == 65535) {
2933
- if (this.data[i + 1] == 1)
2934
- i = pair(this.data, i + 2);
2935
- else
2936
- break;
2937
- }
2938
- result = action(pair(this.data, i + 1));
2939
- }
2940
- return result;
2941
- }
2942
- /// Get the states that can follow this one through shift actions or
2943
- /// goto jumps. @internal
2944
- nextStates(state) {
2945
- let result = [];
2946
- for (let i = this.stateSlot(
2947
- state,
2948
- 1
2949
- /* ParseState.Actions */
2950
- ); ; i += 3) {
2951
- if (this.data[i] == 65535) {
2952
- if (this.data[i + 1] == 1)
2953
- i = pair(this.data, i + 2);
2954
- else
2955
- break;
2956
- }
2957
- if ((this.data[i + 2] & 65536 >> 16) == 0) {
2958
- let value = this.data[i + 1];
2959
- if (!result.some((v, i2) => i2 & 1 && v == value))
2960
- result.push(this.data[i], value);
2961
- }
2962
- }
2963
- return result;
2964
- }
2965
- /// Configure the parser. Returns a new parser instance that has the
2966
- /// given settings modified. Settings not provided in `config` are
2967
- /// kept from the original parser.
2968
- configure(config) {
2969
- let copy = Object.assign(Object.create(LRParser.prototype), this);
2970
- if (config.props)
2971
- copy.nodeSet = this.nodeSet.extend(...config.props);
2972
- if (config.top) {
2973
- let info = this.topRules[config.top];
2974
- if (!info)
2975
- throw new RangeError(`Invalid top rule name ${config.top}`);
2976
- copy.top = info;
2977
- }
2978
- if (config.tokenizers)
2979
- copy.tokenizers = this.tokenizers.map((t) => {
2980
- let found = config.tokenizers.find((r) => r.from == t);
2981
- return found ? found.to : t;
2982
- });
2983
- if (config.specializers) {
2984
- copy.specializers = this.specializers.slice();
2985
- copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
2986
- let found = config.specializers.find((r) => r.from == s.external);
2987
- if (!found)
2988
- return s;
2989
- let spec = Object.assign(Object.assign({}, s), { external: found.to });
2990
- copy.specializers[i] = getSpecializer(spec);
2991
- return spec;
2992
- });
2993
- }
2994
- if (config.contextTracker)
2995
- copy.context = config.contextTracker;
2996
- if (config.dialect)
2997
- copy.dialect = this.parseDialect(config.dialect);
2998
- if (config.strict != null)
2999
- copy.strict = config.strict;
3000
- if (config.wrap)
3001
- copy.wrappers = copy.wrappers.concat(config.wrap);
3002
- if (config.bufferLength != null)
3003
- copy.bufferLength = config.bufferLength;
3004
- return copy;
3005
- }
3006
- /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
3007
- /// are registered for this parser.
3008
- hasWrappers() {
3009
- return this.wrappers.length > 0;
3010
- }
3011
- /// Returns the name associated with a given term. This will only
3012
- /// work for all terms when the parser was generated with the
3013
- /// `--names` option. By default, only the names of tagged terms are
3014
- /// stored.
3015
- getName(term) {
3016
- return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
3017
- }
3018
- /// The eof term id is always allocated directly after the node
3019
- /// types. @internal
3020
- get eofTerm() {
3021
- return this.maxNode + 1;
3022
- }
3023
- /// The type of top node produced by the parser.
3024
- get topNode() {
3025
- return this.nodeSet.types[this.top[1]];
3026
- }
3027
- /// @internal
3028
- dynamicPrecedence(term) {
3029
- let prec = this.dynamicPrecedences;
3030
- return prec == null ? 0 : prec[term] || 0;
3031
- }
3032
- /// @internal
3033
- parseDialect(dialect) {
3034
- let values = Object.keys(this.dialects), flags = values.map(() => false);
3035
- if (dialect)
3036
- for (let part of dialect.split(" ")) {
3037
- let id = values.indexOf(part);
3038
- if (id >= 0)
3039
- flags[id] = true;
3040
- }
3041
- let disabled = null;
3042
- for (let i = 0; i < values.length; i++)
3043
- if (!flags[i]) {
3044
- for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535; )
3045
- (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
3046
- }
3047
- return new Dialect(dialect, flags, disabled);
3048
- }
3049
- /// Used by the output of the parser generator. Not available to
3050
- /// user code. @hide
3051
- static deserialize(spec) {
3052
- return new LRParser(spec);
3053
- }
3054
- };
3055
- function pair(data, off) {
3056
- return data[off] | data[off + 1] << 16;
3057
- }
3058
- function findFinished(stacks) {
3059
- let best = null;
3060
- for (let stack of stacks) {
3061
- let stopped = stack.p.stoppedAt;
3062
- if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(
3063
- stack.state,
3064
- 2
3065
- /* StateFlag.Accepting */
3066
- ) && (!best || best.score < stack.score))
3067
- best = stack;
3068
- }
3069
- return best;
3070
- }
3071
- function getSpecializer(spec) {
3072
- if (spec.external) {
3073
- let mask = spec.extend ? 1 : 0;
3074
- return (value, stack) => spec.external(value, stack) << 1 | mask;
3075
- }
3076
- return spec.get;
3077
- }
3078
-
3079
- // ../vuu-filter-parser/src/generated/filter-parser.js
3080
- var parser = LRParser.deserialize({
3081
- version: 14,
3082
- states: "%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",
3083
- stateData: "#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",
3084
- goto: "#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",
3085
- nodeNames: "\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",
3086
- maxTerm: 39,
3087
- skippedNodes: [0],
3088
- repeatNodeCount: 1,
3089
- tokenData: "6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",
3090
- tokenizers: [0, 1],
3091
- topRules: { "Filter": [0, 1] },
3092
- tokenPrec: 0
3093
- });
3094
-
3095
- // ../vuu-filter-parser/src/FilterTreeWalker.ts
3096
- import {
3097
- isMultiClauseFilter,
3098
- isMultiValueFilter,
3099
- isSingleValueFilter
3100
- } from "@vuu-ui/vuu-utils";
3101
- var _filter;
3102
- var FilterExpression = class {
3103
- constructor() {
3104
- __privateAdd(this, _filter, void 0);
3105
- }
3106
- setFilterCombinatorOp(op, filter = __privateGet(this, _filter)) {
3107
- if (isMultiClauseFilter(filter) && filter.op === op) {
3108
- return;
3109
- } else {
3110
- __privateSet(this, _filter, {
3111
- op,
3112
- filters: [__privateGet(this, _filter)]
3113
- });
3114
- }
3115
- }
3116
- add(filter) {
3117
- if (__privateGet(this, _filter) === void 0) {
3118
- __privateSet(this, _filter, filter);
3119
- } else if (isMultiClauseFilter(__privateGet(this, _filter))) {
3120
- __privateGet(this, _filter).filters.push(filter);
3121
- } else {
3122
- throw Error(`Invalid filter passed to FilterExpression`);
3123
- }
3124
- }
3125
- setColumn(column, filter = __privateGet(this, _filter)) {
3126
- if (isMultiClauseFilter(filter)) {
3127
- const target = filter.filters.at(-1);
3128
- if (target) {
3129
- this.setColumn(column, target);
3130
- }
3131
- } else if (filter) {
3132
- filter.column = column;
3133
- }
3134
- }
3135
- setOp(value, filter = __privateGet(this, _filter)) {
3136
- if (isMultiClauseFilter(filter)) {
3137
- const target = filter.filters.at(-1);
3138
- if (target) {
3139
- this.setOp(value, target);
3140
- }
3141
- } else if (filter) {
3142
- filter.op = value;
3143
- }
3144
- }
3145
- setValue(value, filter = __privateGet(this, _filter)) {
3146
- var _a;
3147
- if (isMultiClauseFilter(filter)) {
3148
- const target = filter.filters.at(-1);
3149
- if (target) {
3150
- this.setValue(value, target);
3151
- }
3152
- } else if (isMultiValueFilter(filter)) {
3153
- (_a = filter.values) != null ? _a : filter.values = [];
3154
- filter.values.push(value);
3155
- } else if (isSingleValueFilter(filter)) {
3156
- filter.value = value;
3157
- }
3158
- }
3159
- toJSON(filter = __privateGet(this, _filter)) {
3160
- if (this.name) {
3161
- return {
3162
- ...filter,
3163
- name: this.name
3164
- };
3165
- } else {
3166
- return filter;
3167
- }
3168
- }
3169
- };
3170
- _filter = new WeakMap();
3171
- var walkTree = (tree, source) => {
3172
- const filterExpression = new FilterExpression();
3173
- const cursor = tree.cursor();
3174
- do {
3175
- const { name, from, to } = cursor;
3176
- switch (name) {
3177
- case "ColumnValueExpression":
3178
- filterExpression.add({});
3179
- break;
3180
- case "ColumnSetExpression":
3181
- filterExpression.add({ op: "in" });
3182
- break;
3183
- case "Or":
3184
- case "And":
3185
- filterExpression.setFilterCombinatorOp(source.substring(from, to));
3186
- break;
3187
- case "Column":
3188
- filterExpression.setColumn(source.substring(from, to));
3189
- break;
3190
- case "Operator":
3191
- filterExpression.setOp(source.substring(from, to));
3192
- break;
3193
- case "String":
3194
- filterExpression.setValue(source.substring(from + 1, to - 1));
3195
- break;
3196
- case "Number":
3197
- filterExpression.setValue(parseFloat(source.substring(from, to)));
3198
- break;
3199
- case "True":
3200
- filterExpression.setValue(true);
3201
- break;
3202
- case "False":
3203
- filterExpression.setValue(false);
3204
- break;
3205
- case "FilterName":
3206
- filterExpression.name = source.substring(from, to);
3207
- break;
3208
- default:
3209
- }
3210
- } while (cursor.next());
3211
- return filterExpression.toJSON();
3212
- };
3213
-
3214
- // ../vuu-filter-parser/src/FilterParser.ts
3215
- var strictParser = parser.configure({ strict: true });
3216
-
3217
- // src/filter-input/useCodeMirrorEditor.ts
3218
- var import_classnames = __toESM(require_classnames(), 1);
3219
- import { useEffect, useMemo, useRef } from "react";
3220
-
3221
- // src/filter-input/FilterLanguage.ts
3222
- import {
3223
- LanguageSupport,
3224
- LRLanguage,
3225
- styleTags,
3226
- tags as tag
3227
- } from "@vuu-ui/vuu-codemirror";
3228
- var filterLanguage = LRLanguage.define({
3229
- name: "VuuFilterQuery",
3230
- parser: parser.configure({
3231
- props: [
3232
- styleTags({
3233
- Identifier: tag.variableName,
3234
- String: tag.string,
3235
- Or: tag.emphasis,
3236
- Operator: tag.operator
3237
- })
3238
- ]
3239
- })
3240
- });
3241
- var filterLanguageSupport = () => {
3242
- return new LanguageSupport(filterLanguage);
3243
- };
3244
-
3245
- // src/filter-input/highlighting.ts
3246
- import {
3247
- HighlightStyle,
3248
- syntaxHighlighting,
3249
- tags
3250
- } from "@vuu-ui/vuu-codemirror";
3251
- var myHighlightStyle = HighlightStyle.define([
3252
- { tag: tags.variableName, color: "var(--vuuFilterEditor-variableColor)" },
3253
- { tag: tags.comment, color: "green", fontStyle: "italic" }
3254
- ]);
3255
- var vuuHighlighting = syntaxHighlighting(myHighlightStyle);
3256
-
3257
- // src/filter-input/theme.ts
3258
- import { EditorView } from "@vuu-ui/vuu-codemirror";
3259
- var vuuTheme = EditorView.theme(
3260
- {
3261
- "&": {
3262
- color: "var(--vuuFilterEditor-color)",
3263
- backgroundColor: "var(--vuuFilterEditor-background)",
3264
- fontSize: "var(--vuuFilterEditor-fontSize)"
3265
- },
3266
- ".cm-content": {
3267
- caretColor: "var(--vuuFilterEditor-cursorColor)",
3268
- padding: 0
3269
- },
3270
- ".cm-line": {
3271
- lineHeight: "var(--vuuFilterEditor-lineHeight)"
3272
- },
3273
- "&.cm-focused .cm-cursor": {
3274
- borderLeftColor: "var(--vuuFilterEditor-cursorColor)"
3275
- },
3276
- "&.cm-focused .cm-selectionBackground, ::selection": {
3277
- backgroundColor: "var(--vuuFilterEditor-selectionBackground)"
3278
- },
3279
- ".cm-selectionBackground, ::selection": {
3280
- backgroundColor: "var(--vuuFilterEditor-selectionBackground)"
3281
- },
3282
- ".cm-scroller": {
3283
- fontFamily: "var(--vuuFilterEditor-fontFamily)"
3284
- },
3285
- ".cm-tooltip": {
3286
- background: "var(--vuuFilterEditor-tooltipBackground)",
3287
- border: "var(--vuuFilterEditor-tooltipBorder)",
3288
- boxShadow: "var(--vuuFilterEditor-tooltipElevation)",
3289
- "&.cm-tooltip-autocomplete > ul": {
3290
- fontFamily: "var(--vuuFilterEditor-fontFamily)",
3291
- fontSize: "var(--vuuFilterEditor-fontSize)",
3292
- maxHeight: "240px"
3293
- },
3294
- "&.cm-tooltip-autocomplete > ul > li": {
3295
- alignItems: "center",
3296
- display: "flex",
3297
- height: "var(--vuuFilterEditor-suggestion-height)",
3298
- padding: "0 3px",
3299
- lineHeight: "var(--vuuFilterEditor-suggestion-height)"
3300
- },
3301
- "&.cm-tooltip-autocomplete li[aria-selected]": {
3302
- background: "var(--vuuFilterEditor-suggestion-selectedBackground)",
3303
- color: "var(--vuuFilterEditor-suggestion-selectedColor)"
3304
- }
3305
- },
3306
- ".cm-completionIcon": {
3307
- height: "18px",
3308
- flex: "0 0 16px"
3309
- },
3310
- ".cm-completionLabel": {
3311
- flex: "1 1 auto"
3312
- },
3313
- ".cm-completionIcon-filter": {
3314
- position: "relative",
3315
- "&:after": {
3316
- background: "var(--salt-text-secondary-foreground)",
3317
- content: "''",
3318
- "-webkit-mask": "var(--svg-filter) center center/13px 13px",
3319
- "-webkit-mask-repeat": "no-repeat",
3320
- position: "absolute",
3321
- height: "18px",
3322
- left: "0px",
3323
- top: "0px",
3324
- width: "16px"
3325
- }
3326
- }
3327
- },
3328
- { dark: false }
3329
- );
3330
-
3331
- // src/filter-input/useFilterAutoComplete.ts
3332
- import {
3333
- getNodeByName,
3334
- getValue,
3335
- syntaxTree
3336
- } from "@vuu-ui/vuu-codemirror";
3337
- import { useCallback } from "react";
3338
- var getOperator = (node, state) => {
3339
- let maybeColumnNode = node.prevSibling || node.parent;
3340
- while (maybeColumnNode && !["Column", "Operator", "In"].includes(maybeColumnNode.name)) {
3341
- maybeColumnNode = maybeColumnNode.prevSibling || maybeColumnNode.parent;
3342
- }
3343
- if ((maybeColumnNode == null ? void 0 : maybeColumnNode.name) === "In" || (maybeColumnNode == null ? void 0 : maybeColumnNode.name) === "Operator") {
3344
- return getValue(maybeColumnNode, state);
3345
- } else {
3346
- return void 0;
3347
- }
3348
- };
3349
- var getPartialOperator = (maybeOperatorNode, state, columnName) => {
3350
- const value = getValue(maybeOperatorNode, state);
3351
- if (columnName === void 0 || value === columnName) {
3352
- return;
3353
- }
3354
- if (["contains", "ends", "starts"].some(
3355
- (val) => val.startsWith(value.toLowerCase())
3356
- )) {
3357
- return value;
3358
- } else {
3359
- return void 0;
3360
- }
3361
- };
3362
- var getClauseOperator = (node, state) => {
3363
- let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;
3364
- while (maybeTargetNode && maybeTargetNode.name === "\u26A0")
3365
- maybeTargetNode = maybeTargetNode.prevSibling;
3366
- if (maybeTargetNode && ["As", "Or", "And"].includes(maybeTargetNode.name)) {
3367
- return getValue(maybeTargetNode, state);
3368
- } else {
3369
- return void 0;
3370
- }
3371
- };
3372
- var getFilterName = (node, state) => {
3373
- if (node.name === "FilterName") {
3374
- return getValue(node, state);
3375
- } else {
3376
- let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;
3377
- while (maybeTargetNode && maybeTargetNode.name !== "FilterName")
3378
- maybeTargetNode = maybeTargetNode.prevSibling;
3379
- if (maybeTargetNode && maybeTargetNode.name === "FilterName") {
3380
- return getValue(node, state);
3381
- }
3382
- }
3383
- };
3384
- var getColumnName = (node, state) => {
3385
- const prevNode = node.prevSibling;
3386
- if ((prevNode == null ? void 0 : prevNode.name) === "Column") {
3387
- return getValue(prevNode, state);
3388
- } else if ((prevNode == null ? void 0 : prevNode.name) === "Operator") {
3389
- return getColumnName(prevNode, state);
3390
- }
3391
- };
3392
- var getSetValues = (node, state) => {
3393
- let maybeTargetNode = node.lastChild;
3394
- const values = [];
3395
- while (maybeTargetNode && maybeTargetNode.name !== "In") {
3396
- const value = getValue(maybeTargetNode, state);
3397
- if (value) {
3398
- values.push(value);
3399
- } else {
3400
- break;
3401
- }
3402
- maybeTargetNode = maybeTargetNode.prevSibling;
3403
- }
3404
- return values;
3405
- };
3406
- var useAutoComplete = (suggestionProvider, onSubmit, existingFilter) => {
3407
- const makeSuggestions = useCallback(
3408
- async (context, suggestionType, optionalArgs = {}) => {
3409
- const { startsWith = "" } = optionalArgs;
3410
- const options = await suggestionProvider.getSuggestions(
3411
- suggestionType,
3412
- optionalArgs
3413
- );
3414
- return { from: context.pos - startsWith.length, options };
3415
- },
3416
- [suggestionProvider]
3417
- );
3418
- return useCallback(
3419
- async (context) => {
3420
- var _a, _b;
3421
- const { state, pos } = context;
3422
- const word = (_a = context.matchBefore(/\w*/)) != null ? _a : {
3423
- from: 0,
3424
- to: 0,
3425
- text: void 0
3426
- };
3427
- const tree = syntaxTree(state);
3428
- const nodeBefore = tree.resolveInner(pos, -1);
3429
- console.log({ nodeBeforeName: nodeBefore.name });
3430
- switch (nodeBefore.name) {
3431
- case "Filter":
3432
- if (context.pos === 0) {
3433
- return makeSuggestions(context, "column");
3434
- } else {
3435
- const clauseOperator = getClauseOperator(nodeBefore, state);
3436
- if (clauseOperator === "as") {
3437
- return makeSuggestions(context, "name");
3438
- } else {
3439
- const filterName = getFilterName(nodeBefore, state);
3440
- return makeSuggestions(context, "save", {
3441
- onSubmit: onSubmit.current,
3442
- existingFilter,
3443
- filterName
3444
- });
3445
- }
3446
- }
3447
- case "String":
3448
- {
3449
- const operator = getOperator(nodeBefore, state);
3450
- const columnName = getColumnName(nodeBefore, state);
3451
- const { from, to } = nodeBefore;
3452
- if (to - from === 2 && context.pos === from + 1) {
3453
- if (columnName && operator) {
3454
- return makeSuggestions(context, "columnValue", {
3455
- columnName,
3456
- operator,
3457
- quoted: true,
3458
- startsWith: word.text
3459
- });
3460
- }
3461
- } else {
3462
- console.log(
3463
- `we have a string, column is ${columnName} ${from} ${to}`
3464
- );
3465
- }
3466
- }
3467
- break;
3468
- case "As":
3469
- return makeSuggestions(context, "name");
3470
- case "FilterName":
3471
- return makeSuggestions(context, "save", {
3472
- onSubmit: onSubmit.current,
3473
- existingFilter,
3474
- filterName: getFilterName(nodeBefore, state)
3475
- });
3476
- case "Column": {
3477
- const columnName = getValue(nodeBefore, state);
3478
- const isPartialMatch = await suggestionProvider.isPartialMatch(
3479
- "column",
3480
- void 0,
3481
- columnName
3482
- );
3483
- if (isPartialMatch) {
3484
- return makeSuggestions(context, "column", {
3485
- startsWith: columnName
3486
- });
3487
- } else {
3488
- return makeSuggestions(context, "operator", { columnName });
3489
- }
3490
- }
3491
- case "\u26A0": {
3492
- const columnName = getNodeByName(nodeBefore, state);
3493
- const operator = getOperator(nodeBefore, state);
3494
- const partialOperator = operator ? void 0 : getPartialOperator(nodeBefore, state, columnName);
3495
- if (partialOperator) {
3496
- return makeSuggestions(context, "operator", {
3497
- columnName,
3498
- startsWith: partialOperator
3499
- });
3500
- } else {
3501
- return makeSuggestions(context, "columnValue", {
3502
- columnName,
3503
- operator,
3504
- startsWith: word.text
3505
- });
3506
- }
3507
- }
3508
- case "Identifier":
3509
- {
3510
- const clauseOperator = getClauseOperator(nodeBefore, state);
3511
- if (clauseOperator === "as") {
3512
- return {
3513
- from: context.pos,
3514
- options: [
3515
- {
3516
- label: "press ENTER to apply filter and save",
3517
- apply: () => onSubmit.current(),
3518
- boost: 5
3519
- }
3520
- ]
3521
- };
3522
- }
3523
- }
3524
- break;
3525
- case "ColumnSetExpression":
3526
- case "Values": {
3527
- const columnName = getNodeByName(nodeBefore, state);
3528
- const selection = getSetValues(nodeBefore, state);
3529
- return makeSuggestions(context, "columnValue", {
3530
- columnName,
3531
- selection
3532
- });
3533
- }
3534
- case "Comma":
3535
- case "LBrack": {
3536
- const columnName = getNodeByName(nodeBefore, state);
3537
- return makeSuggestions(context, "columnValue", { columnName });
3538
- }
3539
- case "ColumnValueExpression":
3540
- {
3541
- const lastToken = (_b = nodeBefore.lastChild) == null ? void 0 : _b.prevSibling;
3542
- if ((lastToken == null ? void 0 : lastToken.name) === "Column") {
3543
- return makeSuggestions(context, "operator", {
3544
- columnName: getNodeByName(nodeBefore, state)
3545
- });
3546
- } else if ((lastToken == null ? void 0 : lastToken.name) === "Operator") {
3547
- return makeSuggestions(context, "columnValue", {
3548
- columnName: getNodeByName(lastToken, state),
3549
- operator: getValue(lastToken, state)
3550
- });
3551
- }
3552
- }
3553
- break;
3554
- case "In": {
3555
- return {
3556
- from: context.pos,
3557
- options: [{ label: "[", apply: " [", type: "text" }]
3558
- };
3559
- }
3560
- case "Eq": {
3561
- return makeSuggestions(context, "columnValue", {
3562
- columnName: getNodeByName(nodeBefore, state)
3563
- });
3564
- }
3565
- case "AndExpression":
3566
- case "OrExpression": {
3567
- return makeSuggestions(context, "column");
3568
- }
3569
- default:
3570
- }
3571
- },
3572
- [existingFilter, makeSuggestions, onSubmit, suggestionProvider]
3573
- );
3574
- };
3575
-
3576
- // src/filter-input/useCodeMirrorEditor.ts
3577
- var getView = (ref) => {
3578
- if (ref.current == void 0) {
3579
- throw Error("EditorView not defined");
3580
- }
3581
- return ref.current;
3582
- };
3583
- var getOptionClass = (completion) => {
3584
- return (0, import_classnames.default)("vuuSuggestion", {
3585
- vuuIllustration: completion.isIllustration
3586
- });
3587
- };
3588
- var stripName = (filterQuery) => {
3589
- const pos = filterQuery.lastIndexOf(" as ");
3590
- if (pos !== -1) {
3591
- return filterQuery.slice(0, pos);
3592
- } else {
3593
- return filterQuery;
3594
- }
3595
- };
3596
- var noop = () => console.log("noooop");
3597
- var useCodeMirrorEditor = ({
3598
- existingFilter,
3599
- onSubmitFilter,
3600
- suggestionProvider
3601
- }) => {
3602
- const editorRef = useRef(null);
3603
- const onSubmit = useRef(noop);
3604
- const viewRef = useRef();
3605
- const completionFn = useAutoComplete(
3606
- suggestionProvider,
3607
- onSubmit,
3608
- existingFilter
3609
- );
3610
- const [createState, clearInput] = useMemo(() => {
3611
- const parseFilter2 = () => {
3612
- const view = getView(viewRef);
3613
- const source = view.state.doc.toString();
3614
- const tree = ensureSyntaxTree(view.state, view.state.doc.length, 5e3);
3615
- if (tree) {
3616
- const filter = walkTree(tree, source);
3617
- return [filter, stripName(source), filter.name];
3618
- } else {
3619
- return [void 0, "", void 0];
3620
- }
3621
- };
3622
- const clearInput2 = () => {
3623
- getView(viewRef).setState(createState2());
3624
- };
3625
- const submitFilterAndClearInput = (mode) => {
3626
- const [filter, filterQuery, filterName] = parseFilter2();
3627
- onSubmitFilter == null ? void 0 : onSubmitFilter(filter, filterQuery, mode, filterName);
3628
- clearInput2();
3629
- };
3630
- const submitFilter = (key) => {
3631
- return keymap.of([
3632
- {
3633
- key,
3634
- run() {
3635
- submitFilterAndClearInput();
3636
- return true;
3637
- }
3638
- }
3639
- ]);
3640
- };
3641
- const showSuggestions = (key) => {
3642
- return keymap.of([
3643
- {
3644
- key,
3645
- run() {
3646
- startCompletion(getView(viewRef));
3647
- return true;
3648
- }
3649
- }
3650
- ]);
3651
- };
3652
- const createState2 = () => EditorState2.create({
3653
- doc: "",
3654
- extensions: [
3655
- minimalSetup,
3656
- autocompletion({
3657
- override: [completionFn],
3658
- optionClass: getOptionClass
3659
- }),
3660
- filterLanguageSupport(),
3661
- keymap.of(defaultKeymap),
3662
- submitFilter("Ctrl-Enter"),
3663
- showSuggestions("ArrowDown"),
3664
- EditorView2.updateListener.of((v) => {
3665
- const view = getView(viewRef);
3666
- if (v.docChanged) {
3667
- startCompletion(view);
3668
- }
3669
- }),
3670
- EditorState2.transactionFilter.of(
3671
- (tr) => tr.newDoc.lines > 1 ? [] : tr
3672
- ),
3673
- vuuTheme,
3674
- vuuHighlighting
3675
- ]
3676
- });
3677
- onSubmit.current = (mode) => {
3678
- submitFilterAndClearInput(mode);
3679
- setTimeout(() => {
3680
- getView(viewRef).focus();
3681
- }, 100);
3682
- };
3683
- return [createState2, clearInput2];
3684
- }, [completionFn, onSubmitFilter]);
3685
- useEffect(() => {
3686
- if (!editorRef.current) {
3687
- throw Error("editor not in dom");
3688
- }
3689
- viewRef.current = new EditorView2({
3690
- state: createState(),
3691
- parent: editorRef.current
3692
- });
3693
- return () => {
3694
- var _a;
3695
- (_a = viewRef.current) == null ? void 0 : _a.destroy();
3696
- };
3697
- }, [completionFn, createState]);
3698
- return { editorRef, clearInput };
3699
- };
3700
-
3701
- // src/filter-input/FilterInput.tsx
3702
- import { jsx, jsxs } from "react/jsx-runtime";
3703
- var classBase = "vuuFilterInput";
3704
- var FilterInput = ({
3705
- existingFilter,
3706
- iconName = "filter",
3707
- namedFilters,
3708
- onSubmitFilter,
3709
- suggestionProvider,
3710
- ...props
3711
- }) => {
3712
- const { editorRef, clearInput } = useCodeMirrorEditor({
3713
- existingFilter,
3714
- onSubmitFilter,
3715
- suggestionProvider
3716
- });
3717
- return /* @__PURE__ */ jsxs("div", { ...props, className: classBase, children: [
3718
- /* @__PURE__ */ jsx(
3719
- Button,
3720
- {
3721
- className: `${classBase}-FilterButton`,
3722
- "data-icon": iconName,
3723
- tabIndex: -1
3724
- }
3725
- ),
3726
- /* @__PURE__ */ jsx("div", { className: `${classBase}-Editor`, ref: editorRef }),
3727
- /* @__PURE__ */ jsx(
3728
- Button,
3729
- {
3730
- className: `${classBase}-ClearButton`,
3731
- "data-icon": "close-circle",
3732
- onClick: clearInput
3733
- }
3734
- )
3735
- ] });
3736
- };
3737
-
3738
- // src/filter-input/useFilterSuggestionProvider.ts
3739
- import {
3740
- asNameSuggestion,
3741
- booleanJoinSuggestions,
3742
- getNamePrompt,
3743
- numericOperators,
3744
- stringOperators,
3745
- toSuggestions
3746
- } from "@vuu-ui/vuu-codemirror";
3747
- import {
3748
- getTypeaheadParams,
3749
- useTypeaheadSuggestions
3750
- } from "@vuu-ui/vuu-data-react";
3751
- import { useCallback as useCallback2, useRef as useRef2 } from "react";
3752
-
3753
- // src/filter-input/filterInfo.ts
3754
- import { createEl } from "@vuu-ui/vuu-utils";
3755
- var filterInfo = (filterName, filterQuery) => {
3756
- const rootElement = createEl("div", "vuuFunctionDoc");
3757
- const headingElement = createEl("div", "function-heading");
3758
- const nameElement = createEl("span", "function-name", filterName);
3759
- headingElement.appendChild(nameElement);
3760
- const child2 = createEl("p", void 0, filterQuery);
3761
- rootElement.appendChild(headingElement);
3762
- rootElement.appendChild(child2);
3763
- return rootElement;
3764
- };
3765
-
3766
- // src/filter-input/useFilterSuggestionProvider.ts
3767
- var NO_NAMED_FILTERS = [];
3768
- var NONE = {};
3769
- var saveAsTab = (onSubmit) => [
3770
- {
3771
- label: "Press ENTER to create TAB",
3772
- apply: () => onSubmit("tab"),
3773
- boost: 6
3774
- }
3775
- ];
3776
- var makeSaveOrExtendSuggestions = (onSubmit, existingFilter, withJoinSuggestions = true) => {
3777
- const result = existingFilter ? [
3778
- {
3779
- label: "REPLACE existing filter",
3780
- apply: () => onSubmit("replace"),
3781
- boost: 8
3782
- },
3783
- {
3784
- label: "AND existing filter",
3785
- apply: () => onSubmit("and"),
3786
- boost: 7
3787
- },
3788
- {
3789
- label: "OR existing filter",
3790
- apply: () => onSubmit("or"),
3791
- boost: 7
3792
- }
3793
- ] : [
3794
- {
3795
- label: "Press ENTER to submit",
3796
- apply: () => onSubmit(),
3797
- boost: 6
3798
- }
3799
- ];
3800
- return withJoinSuggestions ? result.concat(booleanJoinSuggestions).concat(asNameSuggestion) : result;
3801
- };
3802
- var promptToSaveOrExtend = (onSubmit, existingFilter) => makeSaveOrExtendSuggestions(onSubmit, existingFilter, true);
3803
- var promptToSave = (onSubmit) => makeSaveOrExtendSuggestions(onSubmit, void 0);
3804
- var getSaveSuggestions = ({
3805
- existingFilter,
3806
- filterName,
3807
- onSubmit,
3808
- saveOptions
3809
- }) => {
3810
- const includeTabSuggestion = filterName && saveOptions.allowSaveAsTab;
3811
- const result = existingFilter ? promptToSaveOrExtend(onSubmit, existingFilter) : promptToSave(onSubmit);
3812
- if (includeTabSuggestion) {
3813
- return result.concat(saveAsTab(onSubmit));
3814
- } else {
3815
- return result;
3816
- }
3817
- };
3818
- var suggestColumns = (columns) => columns.map((column) => ({
3819
- boost: 5,
3820
- label: column.name
3821
- }));
3822
- var suggestNamedFilters = (namedFilters) => namedFilters ? Array.from(namedFilters.entries()).map(([filterName, filterQuery]) => ({
3823
- info: () => filterInfo(filterName, filterQuery),
3824
- label: filterName,
3825
- type: "filter"
3826
- })) : NO_NAMED_FILTERS;
3827
- var doneCommand = {
3828
- label: "Done",
3829
- apply: "] ",
3830
- type: "keyword",
3831
- boost: 10
3832
- };
3833
- var withApplySpace = (suggestions, startsWith = "") => suggestions.filter((sugg) => startsWith === "" || sugg.label.startsWith(startsWith)).map((suggestion) => ({
3834
- ...suggestion,
3835
- apply: suggestion.label + " "
3836
- }));
3837
- var defaultSaveOptions = {
3838
- allowReplace: true
3839
- };
3840
- var useFilterSuggestionProvider = ({
3841
- columns,
3842
- namedFilters,
3843
- saveOptions = defaultSaveOptions,
3844
- table,
3845
- typeaheadHook: useTypeahead = useTypeaheadSuggestions
3846
- }) => {
3847
- const latestSuggestionsRef = useRef2();
3848
- const getTypeaheadSuggestions = useTypeahead();
3849
- const getSuggestions = useCallback2(
3850
- async (suggestionType, options = NONE) => {
3851
- const {
3852
- columnName,
3853
- existingFilter,
3854
- filterName,
3855
- operator,
3856
- quoted: autoQuoted,
3857
- onSubmit,
3858
- startsWith,
3859
- selection
3860
- } = options;
3861
- switch (suggestionType) {
3862
- case "operator":
3863
- {
3864
- const column = columns.find((col) => col.name === columnName);
3865
- if (column) {
3866
- switch (column.serverDataType) {
3867
- case "string":
3868
- case "char":
3869
- return withApplySpace(stringOperators, startsWith);
3870
- case "int":
3871
- case "long":
3872
- case "double":
3873
- return withApplySpace(numericOperators);
3874
- }
3875
- } else {
3876
- console.warn(`'${columnName}' does not match any column name`);
3877
- }
3878
- }
3879
- break;
3880
- case "column": {
3881
- const columnSuggestions = await suggestColumns(columns);
3882
- const filterSuggestions = await suggestNamedFilters(namedFilters);
3883
- return (latestSuggestionsRef.current = withApplySpace(columnSuggestions)).concat(
3884
- withApplySpace(filterSuggestions)
3885
- );
3886
- }
3887
- case "columnValue":
3888
- {
3889
- if (columnName) {
3890
- const column = columns.find((col) => col.name === columnName);
3891
- if (!column) {
3892
- throw Error(
3893
- `useFilterSUggestionProvider no column ${columnName}`
3894
- );
3895
- }
3896
- const prefix = Array.isArray(selection) ? selection.length === 0 ? "[" : "," : "";
3897
- const params = getTypeaheadParams(
3898
- table,
3899
- columnName,
3900
- startsWith
3901
- );
3902
- const suggestions = await getTypeaheadSuggestions(params);
3903
- const isIllustration = operator === "starts";
3904
- latestSuggestionsRef.current = toSuggestions(suggestions, {
3905
- moveCursorToEnd: autoQuoted,
3906
- quoted: (column == null ? void 0 : column.serverDataType) === "string" && !autoQuoted,
3907
- suffix: autoQuoted ? "" : " ",
3908
- prefix: isIllustration ? startsWith : prefix,
3909
- isIllustration
3910
- });
3911
- if (Array.isArray(selection) && (selection == null ? void 0 : selection.length) > 1) {
3912
- return [doneCommand, ...latestSuggestionsRef.current];
3913
- }
3914
- return latestSuggestionsRef.current;
3915
- }
3916
- }
3917
- break;
3918
- case "save": {
3919
- if (typeof onSubmit !== "function") {
3920
- throw Error(
3921
- "useFilterSuggestionProvider, onSubmit must be supplied for 'save' suggestions"
3922
- );
3923
- }
3924
- return await getSaveSuggestions({
3925
- existingFilter,
3926
- filterName,
3927
- onSubmit,
3928
- saveOptions
3929
- });
3930
- }
3931
- case "name":
3932
- return await getNamePrompt("filter");
3933
- default:
3934
- }
3935
- return [];
3936
- },
3937
- [columns, getTypeaheadSuggestions, namedFilters, saveOptions, table]
3938
- );
3939
- const isPartialMatch = useCallback2(
3940
- async (valueType, columnName, pattern) => {
3941
- const suggestions = (
3942
- // latestSuggestions && latestSuggestions.length > 0
3943
- // ? latestSuggestions
3944
- await getSuggestions(valueType, { columnName })
3945
- );
3946
- if (pattern && suggestions) {
3947
- for (const option of suggestions) {
3948
- if (option.label === pattern) {
3949
- return false;
3950
- } else if (option.label.startsWith(pattern)) {
3951
- return true;
3952
- }
3953
- }
3954
- }
3955
- return false;
3956
- },
3957
- [getSuggestions]
3958
- );
3959
- return {
3960
- getSuggestions,
3961
- isPartialMatch
3962
- };
3963
- };
3964
-
3965
- // src/filter-toolbar/FilterToolbar.tsx
3966
- var import_classnames2 = __toESM(require_classnames(), 1);
3967
- import { Toolbar } from "@heswell/salt-lab";
3968
-
3969
- // src/filter-toolbar/useFilterToolbar.tsx
3970
- import {
3971
- isMultiValueFilter as isMultiValueFilter2,
3972
- isNamedFilter,
3973
- isSingleValueFilter as isSingleValueFilter2
3974
- } from "@vuu-ui/vuu-utils";
3975
- import { ToggleButton, ToolbarField } from "@heswell/salt-lab";
3976
-
3977
- // src/filter-toolbar/FilterDropdown.tsx
3978
- import { Dropdown } from "@heswell/salt-lab";
3979
- import { useCallback as useCallback3, useState } from "react";
3980
- import { jsx as jsx2 } from "react/jsx-runtime";
3981
- var isString = (s) => typeof s === "string";
3982
- var stripQuotes = (selected) => {
3983
- if (isString(selected)) {
3984
- if (selected.startsWith('"') && selected.endsWith('"')) {
3985
- return selected.slice(1, -1);
3986
- } else {
3987
- return selected;
3988
- }
3989
- } else {
3990
- return selected.map(stripQuotes);
3991
- }
3992
- };
3993
- var FilterDropdown = ({
3994
- column,
3995
- selected: selectedProp,
3996
- suggestionProvider,
3997
- ...props
3998
- }) => {
3999
- const selected = selectedProp != null ? stripQuotes(selectedProp) : void 0;
4000
- const initialValues = Array.isArray(selected) ? selected : selected != null ? [selected] : [];
4001
- const [values, setValues] = useState(initialValues);
4002
- console.log({ initialValues });
4003
- const handleOpenChange = useCallback3(
4004
- async (isOpen) => {
4005
- if (isOpen) {
4006
- const values2 = await suggestionProvider.getSuggestions("columnValue", {
4007
- columnName: column
4008
- });
4009
- console.log({ values: values2 });
4010
- setValues(values2.map((suggestion) => suggestion.label));
4011
- }
4012
- },
4013
- [column, suggestionProvider]
4014
- );
4015
- return /* @__PURE__ */ jsx2(
4016
- Dropdown,
4017
- {
4018
- ...props,
4019
- onOpenChange: handleOpenChange,
4020
- selected,
4021
- source: values
4022
- }
4023
- );
4024
- };
4025
-
4026
- // src/filter-toolbar/FilterDropdownMultiSelect.tsx
4027
- import { Dropdown as Dropdown2 } from "@heswell/salt-lab";
4028
- import { useCallback as useCallback4, useState as useState2 } from "react";
4029
- import { jsx as jsx3 } from "react/jsx-runtime";
4030
- var isString2 = (s) => typeof s === "string";
4031
- var stripQuotes2 = (selected) => {
4032
- if (selected === void 0) {
4033
- return void 0;
4034
- } else if (isString2(selected)) {
4035
- if (selected.startsWith('"') && selected.endsWith('"')) {
4036
- return selected.slice(1, -1);
4037
- } else {
4038
- return selected;
4039
- }
4040
- } else {
4041
- return selected.map(stripQuotes2);
4042
- }
4043
- };
4044
- var FilterDropdownMultiSelect = ({
4045
- column,
4046
- selected: selectedProp,
4047
- suggestionProvider,
4048
- ...props
4049
- }) => {
4050
- const selected = stripQuotes2(selectedProp);
4051
- const initialValues = Array.isArray(selected) ? selected : selected != null ? [selected] : [];
4052
- const [values, setValues] = useState2(initialValues);
4053
- const handleOpenChange = useCallback4(
4054
- async (isOpen) => {
4055
- if (isOpen) {
4056
- const values2 = await suggestionProvider.getSuggestions("columnValue", {
4057
- columnName: column
4058
- });
4059
- console.log({ values: values2 });
4060
- setValues(values2.map((suggestion) => suggestion.label));
4061
- }
4062
- },
4063
- [column, suggestionProvider]
4064
- );
4065
- return /* @__PURE__ */ jsx3(
4066
- Dropdown2,
4067
- {
4068
- ...props,
4069
- onOpenChange: handleOpenChange,
4070
- selected,
4071
- selectionStrategy: "multiple",
4072
- source: values
4073
- }
4074
- );
4075
- };
4076
-
4077
- // src/filter-toolbar/useFilterToolbar.tsx
4078
- import { jsx as jsx4 } from "react/jsx-runtime";
4079
- var filterToControl = (filter, suggestionProvider) => {
4080
- if (isNamedFilter(filter)) {
4081
- return /* @__PURE__ */ jsx4(
4082
- ToggleButton,
4083
- {
4084
- className: "vuuToggleButton",
4085
- toggled: true,
4086
- variant: "secondary",
4087
- children: filter.name
4088
- }
4089
- );
4090
- }
4091
- if (isSingleValueFilter2(filter)) {
4092
- const { column, value } = filter;
4093
- return /* @__PURE__ */ jsx4(
4094
- ToolbarField,
4095
- {
4096
- className: "vuuFilterDropdown",
4097
- label: column,
4098
- labelPlacement: "top",
4099
- children: /* @__PURE__ */ jsx4(
4100
- FilterDropdown,
4101
- {
4102
- column,
4103
- selected: value.toString(),
4104
- selectionStrategy: "default",
4105
- source: [value.toString()],
4106
- suggestionProvider,
4107
- style: { width: 100 }
4108
- }
4109
- )
4110
- },
4111
- column
4112
- );
4113
- }
4114
- if (isMultiValueFilter2(filter)) {
4115
- const values = filter.values.map((v) => v.toString());
4116
- return /* @__PURE__ */ jsx4(
4117
- ToolbarField,
4118
- {
4119
- className: "vuuFilterDropdown",
4120
- label: filter.column,
4121
- labelPlacement: "top",
4122
- children: /* @__PURE__ */ jsx4(
4123
- FilterDropdownMultiSelect,
4124
- {
4125
- column: filter.column,
4126
- selected: values,
4127
- source: values,
4128
- suggestionProvider,
4129
- style: { width: 100 }
4130
- }
4131
- )
4132
- },
4133
- filter.column
4134
- );
4135
- }
4136
- return filter.filters.map(
4137
- (filter2) => filterToControl(filter2, suggestionProvider)
4138
- );
4139
- };
4140
- var useFilterToolbar = ({
4141
- filter,
4142
- suggestionProvider
4143
- }) => {
4144
- if (filter) {
4145
- return filterToControl(filter, suggestionProvider);
4146
- }
4147
- return [];
4148
- };
4149
-
4150
- // src/filter-toolbar/FilterToolbar.tsx
4151
- import { jsx as jsx5 } from "react/jsx-runtime";
4152
- var FilterToolbar = ({
4153
- className,
4154
- filter,
4155
- suggestionProvider,
4156
- ...props
4157
- }) => {
4158
- console.log(`FilterToolbar ${JSON.stringify(filter, null, 2)}`);
4159
- const toolbarItems = useFilterToolbar({ filter, suggestionProvider });
4160
- return /* @__PURE__ */ jsx5(Toolbar, { className: (0, import_classnames2.default)("vuuFilterToolbar", className), ...props, children: toolbarItems });
4161
- };
4162
-
4163
- // src/filter-utils.ts
4164
- import {
4165
- extractFilterForColumn,
4166
- isAndFilter,
4167
- isInFilter,
4168
- isMultiClauseFilter as isMultiClauseFilter2,
4169
- isMultiValueFilter as isMultiValueFilter3,
4170
- isOrFilter,
4171
- isSingleValueFilter as isSingleValueFilter3,
4172
- partition
4173
- } from "@vuu-ui/vuu-utils";
4174
- var AND = "and";
4175
- var EQUALS = "=";
4176
- var GREATER_THAN = ">";
4177
- var LESS_THAN = "<";
4178
- var OR = "or";
4179
- var STARTS_WITH = "starts";
4180
- var ENDS_WITH = "ends";
4181
- var IN = "in";
4182
- var filterClauses = (filter, clauses = []) => {
4183
- if (filter) {
4184
- if (isMultiClauseFilter2(filter)) {
4185
- filter.filters.forEach((f) => clauses.push(...filterClauses(f)));
4186
- } else {
4187
- clauses.push(filter);
4188
- }
4189
- }
4190
- return clauses;
4191
- };
4192
- var DEFAULT_ADD_FILTER_OPTS = {
4193
- combineWith: "and"
4194
- };
4195
- var addFilter = (existingFilter, filter, { combineWith = AND } = DEFAULT_ADD_FILTER_OPTS) => {
4196
- var _a;
4197
- if (includesNoValues(filter)) {
4198
- if (isMultiClauseFilter2(filter)) {
4199
- } else {
4200
- existingFilter = removeFilterForColumn(existingFilter, {
4201
- name: filter.column
4202
- });
4203
- }
4204
- } else if (includesAllValues(filter)) {
4205
- if (isMultiClauseFilter2(filter)) {
4206
- }
4207
- return removeFilterForColumn(existingFilter, { name: (_a = filter.column) != null ? _a : "" });
4208
- }
4209
- if (!existingFilter) {
4210
- return filter;
4211
- }
4212
- if (!filter) {
4213
- return existingFilter;
4214
- }
4215
- if (existingFilter.op === AND && filter.op === AND) {
4216
- return {
4217
- op: AND,
4218
- filters: combine(existingFilter.filters, filter.filters)
4219
- };
4220
- }
4221
- if (existingFilter.op === AND) {
4222
- const filters = replaceOrInsert(existingFilter.filters, filter);
4223
- return filters.length > 1 ? { op: AND, filters } : filters[0];
4224
- }
4225
- if (filter.op === AND) {
4226
- return { op: AND, filters: filter.filters.concat(existingFilter) };
4227
- }
4228
- if (filterEquals(existingFilter, filter, true)) {
4229
- return filter;
4230
- }
4231
- if (canMerge(existingFilter, filter)) {
4232
- return merge(existingFilter, filter);
4233
- }
4234
- return { op: combineWith, filters: [existingFilter, filter] };
4235
- };
4236
- var includesNoValues = (filter) => {
4237
- if (!filter) {
4238
- return false;
4239
- }
4240
- if (isInFilter(filter) && filter.values.length === 0) {
4241
- return true;
4242
- }
4243
- return isAndFilter(filter) && filter.filters.some((f) => includesNoValues(f));
4244
- };
4245
- var includesAllValues = (filter) => {
4246
- if (!filter) {
4247
- return false;
4248
- }
4249
- if (filter.op === STARTS_WITH && filter.value === "") {
4250
- return true;
4251
- }
4252
- return filter.op === STARTS_WITH && filter.value === "";
4253
- };
4254
- var replaceOrInsert = (filters, filter) => {
4255
- return filters.concat(filter);
4256
- };
4257
- var merge = (f1, f2) => {
4258
- if (includesNoValues(f2)) {
4259
- return f2;
4260
- }
4261
- if (isInFilter(f1) && isInFilter(f2)) {
4262
- return {
4263
- ...f1,
4264
- values: [
4265
- ...f1.values,
4266
- ...f2.values.filter(
4267
- (v) => !f1.values.includes(v)
4268
- )
4269
- ]
4270
- };
4271
- } else if (isInFilter(f1) && f2.op === EQUALS) {
4272
- return {
4273
- ...f1,
4274
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
4275
- // @ts-ignore
4276
- values: f1.values.concat([f2.value])
4277
- };
4278
- } else if (f1.op === EQUALS && f2.op === EQUALS) {
4279
- return {
4280
- column: f1.column,
4281
- op: IN,
4282
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
4283
- // @ts-ignore
4284
- values: [f1.value, f2.value]
4285
- };
4286
- }
4287
- return f2;
4288
- };
4289
- var combine = (existingFilters, replacementFilters) => {
4290
- const equivalentType = ({ op: t1 }, { op: t2 }) => {
4291
- return t1 === t2 || t1[0] === t2[0];
4292
- };
4293
- const replaces = (existingFilter, replacementFilter) => {
4294
- return existingFilter.column === replacementFilter.column && equivalentType(existingFilter, replacementFilter);
4295
- };
4296
- const stillApplicable = (existingFilter) => replacementFilters.some(
4297
- (replacementFilter) => replaces(existingFilter, replacementFilter)
4298
- ) === false;
4299
- return existingFilters.filter(stillApplicable).concat(replacementFilters);
4300
- };
4301
- var removeFilter = (sourceFilter, filterToRemove) => {
4302
- if (filterEquals(sourceFilter, filterToRemove, true)) {
4303
- return null;
4304
- }
4305
- if (sourceFilter.op !== AND) {
4306
- throw Error(
4307
- `removeFilter cannot remove ${JSON.stringify(
4308
- filterToRemove
4309
- )} from ${JSON.stringify(sourceFilter)}`
4310
- );
4311
- }
4312
- const filters = sourceFilter.filters.filter(
4313
- (f) => !filterEquals(f, filterToRemove)
4314
- );
4315
- return filters.length > 0 ? { type: AND, filters } : null;
4316
- };
4317
- var splitFilterOnColumn = (columnName, filter) => {
4318
- if (!filter) {
4319
- return [void 0, void 0];
4320
- }
4321
- if (filter.column === columnName) {
4322
- return [filter, void 0];
4323
- }
4324
- if (filter.op !== AND) {
4325
- return [void 0, filter];
4326
- }
4327
- const [[columnFilter = void 0], filters] = partition(
4328
- filter.filters,
4329
- (f) => f.column === columnName
4330
- );
4331
- return filters.length === 1 ? [columnFilter, filters[0]] : [columnFilter, { op: AND, filters }];
4332
- };
4333
- var overrideColName = (filter, column) => {
4334
- if (isMultiClauseFilter2(filter)) {
4335
- return {
4336
- op: filter.op,
4337
- filters: filter.filters.map((f) => overrideColName(f, column))
4338
- };
4339
- }
4340
- return { ...filter, column };
4341
- };
4342
- var filterIncludesColumn = (filter, column) => {
4343
- if (!filter) {
4344
- return false;
4345
- }
4346
- const { op, column: filterColName } = filter;
4347
- switch (op) {
4348
- case AND:
4349
- case OR:
4350
- return filter.filters != null && filter.filters.some((f) => filterIncludesColumn(f, column));
4351
- default:
4352
- return filterColName === column.name;
4353
- }
4354
- };
4355
- var removeFilterForColumn = (sourceFilter, column) => {
4356
- const colName = column.name;
4357
- if (!sourceFilter) {
4358
- return void 0;
4359
- }
4360
- if (sourceFilter.column === colName) {
4361
- return void 0;
4362
- }
4363
- if (isAndFilter(sourceFilter) || isOrFilter(sourceFilter)) {
4364
- const { op } = sourceFilter;
4365
- const filters = sourceFilter.filters;
4366
- const otherColFilters = filters.filter((f) => f.column !== colName);
4367
- switch (otherColFilters.length) {
4368
- case 0:
4369
- return void 0;
4370
- case 1:
4371
- return otherColFilters[0];
4372
- default:
4373
- return { op, filters: otherColFilters };
4374
- }
4375
- }
4376
- return sourceFilter;
4377
- };
4378
- var canMerge = (f1, f2) => f1.column === f2.column && (f1.op === "=" || f1.op === "in") && (f2.op === "=" || f2.op === "in");
4379
- var sameValues = (arr1, arr2) => {
4380
- if (arr1 === arr2) {
4381
- return true;
4382
- }
4383
- if (arr1.length === arr2.length) {
4384
- const a = arr1.slice().sort();
4385
- const b = arr2.slice().sort();
4386
- return a.join("|") === b.join("|");
4387
- }
4388
- return false;
4389
- };
4390
- var filterEquals = (f1, f2, strict = false) => {
4391
- if (!strict) {
4392
- return true;
4393
- }
4394
- if (f1 && f2 && canMerge(f1, f2)) {
4395
- return f1.op === f2.op && (isSingleValueFilter3(f1) && isSingleValueFilter3(f2) && f1.value === f2.value || isMultiValueFilter3(f1) && isMultiValueFilter3(f2) && sameValues(f1.values, f2.values));
4396
- }
4397
- return false;
4398
- };
4399
- var updateFilter = (filter, newFilter, mode) => {
4400
- if (filter && newFilter) {
4401
- if (mode === "replace") {
4402
- return newFilter;
4403
- }
4404
- if (filter.op === "and") {
4405
- return {
4406
- ...filter,
4407
- filters: filter.filters.concat(newFilter)
4408
- };
4409
- }
4410
- const { column: columnName } = newFilter;
4411
- if (columnName) {
4412
- const existingClause = newFilter.column ? extractFilterForColumn(filter, columnName) : void 0;
4413
- if (existingClause && columnName) {
4414
- const result = removeFilterForColumn(filter, { name: columnName });
4415
- return updateFilter(result, newFilter, "add");
4416
- }
4417
- }
4418
- return {
4419
- op: "and",
4420
- filters: [filter, newFilter]
4421
- };
4422
- }
4423
- if (newFilter) {
4424
- return newFilter;
4425
- }
4426
- return filter;
4427
- };
4428
- var getTypeaheadFilter = (column, filterValues, isStartsWithFilter) => {
4429
- if (filterValues.length === 0) {
4430
- return void 0;
4431
- }
4432
- if (isStartsWithFilter) {
4433
- const startsWith = filterValues[0].substring(0, filterValues[0].length - 3);
4434
- return {
4435
- column,
4436
- op: "starts",
4437
- value: `"${startsWith}"`
4438
- };
4439
- }
4440
- return {
4441
- column,
4442
- op: "in",
4443
- values: filterValues.map((value) => `"${value}"`)
4444
- };
4445
- };
4446
- var getNumericFilter = (column, operator, value) => {
4447
- if (operator === void 0)
4448
- return void 0;
4449
- if (value === void 0 || isNaN(value))
4450
- return void 0;
4451
- return { column, op: operator, value };
4452
- };
4453
- export {
4454
- AND,
4455
- ENDS_WITH,
4456
- EQUALS,
4457
- FilterInput,
4458
- FilterToolbar,
4459
- GREATER_THAN,
4460
- IN,
4461
- LESS_THAN,
4462
- OR,
4463
- STARTS_WITH,
4464
- addFilter,
4465
- filterClauses,
4466
- filterEquals,
4467
- filterIncludesColumn,
4468
- getNumericFilter,
4469
- getTypeaheadFilter,
4470
- overrideColName,
4471
- removeFilter,
4472
- splitFilterOnColumn,
4473
- updateFilter,
4474
- useCodeMirrorEditor,
4475
- useFilterSuggestionProvider
4476
- };
1
+ var Xt=Object.create;var Je=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var qt=Object.getPrototypeOf,Zt=Object.prototype.hasOwnProperty;var Jt=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Kt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yt(e))!Zt.call(s,i)&&i!==t&&Je(s,i,{get:()=>e[i],enumerable:!(r=Gt(e,i))||r.enumerable});return s};var Ke=(s,e,t)=>(t=s!=null?Xt(qt(s)):{},Kt(e||!s||!s.__esModule?Je(t,"default",{value:s,enumerable:!0}):t,s));var et=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var V=(s,e,t)=>(et(s,e,"read from private field"),t?t.call(s):e.get(s)),tt=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)},Ae=(s,e,t,r)=>(et(s,e,"write to private field"),r?r.call(s,t):e.set(s,t),t);var Le=Jt((Xs,ke)=>{(function(){"use strict";var s={}.hasOwnProperty,e="[native code]";function t(){for(var r=[],i=0;i<arguments.length;i++){var n=arguments[i];if(n){var o=typeof n;if(o==="string"||o==="number")r.push(n);else if(Array.isArray(n)){if(n.length){var l=t.apply(null,n);l&&r.push(l)}}else if(o==="object"){if(n.toString!==Object.prototype.toString&&!n.toString.toString().includes("[native code]")){r.push(n.toString());continue}for(var a in n)s.call(n,a)&&n[a]&&r.push(a)}}}return r.join(" ")}typeof ke<"u"&&ke.exports?(t.default=t,ke.exports=t):typeof define=="function"&&typeof define.amd=="object"&&define.amd?define("classnames",[],function(){return t}):window.classNames=t})()});import{Button as Nt}from"@salt-ds/core";import{autocompletion as yr,defaultKeymap as kr,EditorState as Pt,EditorView as wt,ensureSyntaxTree as vr,keymap as $e,minimalSetup as Or,startCompletion as Ft}from"@vuu-ui/vuu-codemirror";var er=0,oe=class{constructor(e,t){this.from=e,this.to=t}},k=class{constructor(e={}){this.id=er++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=R.match(e)),t=>{let r=e(t);return r===void 0?null:[this,r]}}};k.closedBy=new k({deserialize:s=>s.split(" ")});k.openedBy=new k({deserialize:s=>s.split(" ")});k.group=new k({deserialize:s=>s.split(" ")});k.contextHash=new k({perNode:!0});k.lookAhead=new k({perNode:!0});k.mounted=new k({perNode:!0});var tr=Object.create(null),R=class{constructor(e,t,r,i=0){this.name=e,this.props=t,this.id=r,this.flags=i}static define(e){let t=e.props&&e.props.length?Object.create(null):tr,r=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),i=new R(e.name||"",t,e.id,r);if(e.props){for(let n of e.props)if(Array.isArray(n)||(n=n(i)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(k.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let r in e)for(let i of r.split(" "))t[i]=e[r];return r=>{for(let i=r.prop(k.group),n=-1;n<(i?i.length:0);n++){let o=t[n<0?r.name:i[n]];if(o)return o}}}};R.none=new R("",Object.create(null),0,8);var K=class{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let t=[];for(let r of this.types){let i=null;for(let n of e){let o=n(r);o&&(i||(i=Object.assign({},r.props)),i[o[0].id]=o[1])}t.push(i?new R(r.name,i,r.id,r.flags):r)}return new K(t)}},de=new WeakMap,rt=new WeakMap,F;(function(s){s[s.ExcludeBuffers=1]="ExcludeBuffers",s[s.IncludeAnonymous=2]="IncludeAnonymous",s[s.IgnoreMounts=4]="IgnoreMounts",s[s.IgnoreOverlays=8]="IgnoreOverlays"})(F||(F={}));var A=class{constructor(e,t,r,i,n){if(this.type=e,this.children=t,this.positions=r,this.length=i,this.props=null,n&&n.length){this.props=Object.create(null);for(let[o,l]of n)this.props[typeof o=="number"?o:o.id]=l}}toString(){let e=this.prop(k.mounted);if(e&&!e.overlay)return e.tree.toString();let t="";for(let r of this.children){let i=r.toString();i&&(t&&(t+=","),t+=i)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}cursor(e=0){return new te(this.topNode,e)}cursorAt(e,t=0,r=0){let i=de.get(this)||this.topNode,n=new te(i);return n.moveTo(e,t),de.set(this,n._tree),n}get topNode(){return new B(this,0,0,null)}resolve(e,t=0){let r=ee(de.get(this)||this.topNode,e,t,!1);return de.set(this,r),r}resolveInner(e,t=0){let r=ee(rt.get(this)||this.topNode,e,t,!0);return rt.set(this,r),r}iterate(e){let{enter:t,leave:r,from:i=0,to:n=this.length}=e,o=e.mode||0,l=(o&F.IncludeAnonymous)>0;for(let a=this.cursor(o|F.IncludeAnonymous);;){let u=!1;if(a.from<=n&&a.to>=i&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;u=!0}for(;u&&r&&(l||!a.type.isAnonymous)&&r(a),!a.nextSibling();){if(!a.parent())return;u=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Re(R.none,this.children,this.positions,0,this.children.length,0,this.length,(t,r,i)=>new A(this.type,t,r,i,this.propValues),e.makeTree||((t,r,i)=>new A(R.none,t,r,i)))}static build(e){return rr(e)}};A.empty=new A(R.none,[],[],0);var le=class{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new le(this.buffer,this.index)}},$=class{constructor(e,t,r){this.buffer=e,this.length=t,this.set=r}get type(){return R.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],r=this.buffer[e+3],i=this.set.types[t],n=i.name;if(/\W/.test(n)&&!i.isError&&(n=JSON.stringify(n)),e+=4,r==e)return n;let o=[];for(;e<r;)o.push(this.childString(e)),e=this.buffer[e+3];return n+"("+o.join(",")+")"}findChild(e,t,r,i,n){let{buffer:o}=this,l=-1;for(let a=e;a!=t&&!(it(n,i,o[a+1],o[a+2])&&(l=a,r>0));a=o[a+3]);return l}slice(e,t,r){let i=this.buffer,n=new Uint16Array(t-e),o=0;for(let l=e,a=0;l<t;){n[a++]=i[l++],n[a++]=i[l++]-r;let u=n[a++]=i[l++]-r;n[a++]=i[l++]-e,o=Math.max(o,u)}return new $(n,o,this.set)}};function it(s,e,t,r){switch(s){case-2:return t<e;case-1:return r>=e&&t<e;case 0:return t<e&&r>e;case 1:return t<=e&&r>e;case 2:return r>e;case 4:return!0}}function nt(s,e){let t=s.childBefore(e);for(;t;){let r=t.lastChild;if(!r||r.to!=t.to)break;r.type.isError&&r.from==r.to?(s=t,t=r.prevSibling):t=r}return s}function ee(s,e,t,r){for(var i;s.from==s.to||(t<1?s.from>=e:s.from>e)||(t>-1?s.to<=e:s.to<e);){let o=!r&&s instanceof B&&s.index<0?null:s.parent;if(!o)return s;s=o}let n=r?0:F.IgnoreOverlays;if(r)for(let o=s,l=o.parent;l;o=l,l=o.parent)o instanceof B&&o.index<0&&((i=l.enter(e,t,n))===null||i===void 0?void 0:i.from)!=o.from&&(s=l);for(;;){let o=s.enter(e,t,n);if(!o)return s;s=o}}var B=class{constructor(e,t,r,i){this._tree=e,this.from=t,this.index=r,this._parent=i}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,t,r,i,n=0){for(let o=this;;){for(let{children:l,positions:a}=o._tree,u=t>0?l.length:-1;e!=u;e+=t){let c=l[e],h=a[e]+o.from;if(it(i,r,h,h+c.length)){if(c instanceof $){if(n&F.ExcludeBuffers)continue;let f=c.findChild(0,c.buffer.length,t,r-h,i);if(f>-1)return new _(new Te(o,c,e,h),null,f)}else if(n&F.IncludeAnonymous||!c.type.isAnonymous||Ee(c)){let f;if(!(n&F.IgnoreMounts)&&c.props&&(f=c.prop(k.mounted))&&!f.overlay)return new B(f.tree,h,e,o);let p=new B(c,h,e,o);return n&F.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,r,i)}}}if(n&F.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,r=0){let i;if(!(r&F.IgnoreOverlays)&&(i=this._tree.prop(k.mounted))&&i.overlay){let n=e-this.from;for(let{from:o,to:l}of i.overlay)if((t>0?o<=n:o<n)&&(t<0?l>=n:l>n))return new B(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(e=0){return new te(this,e)}get tree(){return this._tree}toTree(){return this._tree}resolve(e,t=0){return ee(this,e,t,!1)}resolveInner(e,t=0){return ee(this,e,t,!0)}enterUnfinishedNodesBefore(e){return nt(this,e)}getChild(e,t=null,r=null){let i=me(this,e,t,r);return i.length?i[0]:null}getChildren(e,t=null,r=null){return me(this,e,t,r)}toString(){return this._tree.toString()}get node(){return this}matchContext(e){return be(this,e)}};function me(s,e,t,r){let i=s.cursor(),n=[];if(!i.firstChild())return n;if(t!=null){for(;!i.type.is(t);)if(!i.nextSibling())return n}for(;;){if(r!=null&&i.type.is(r))return n;if(i.type.is(e)&&n.push(i.node),!i.nextSibling())return r==null?n:[]}}function be(s,e,t=e.length-1){for(let r=s.parent;t>=0;r=r.parent){if(!r)return!1;if(!r.type.isAnonymous){if(e[t]&&e[t]!=r.name)return!1;t--}}return!0}var Te=class{constructor(e,t,r,i){this.parent=e,this.buffer=t,this.index=r,this.start=i}},_=class{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,r){this.context=e,this._parent=t,this.index=r,this.type=e.buffer.set.types[e.buffer.buffer[r]]}child(e,t,r){let{buffer:i}=this.context,n=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.context.start,r);return n<0?null:new _(this.context,this,n)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,r=0){if(r&F.ExcludeBuffers)return null;let{buffer:i}=this.context,n=i.findChild(this.index+4,i.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return n<0?null:new _(this.context,this,n)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new _(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new _(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}cursor(e=0){return new te(this,e)}get tree(){return null}toTree(){let e=[],t=[],{buffer:r}=this.context,i=this.index+4,n=r.buffer[this.index+3];if(n>i){let o=r.buffer[this.index+1];e.push(r.slice(i,n,o)),t.push(0)}return new A(this.type,e,t,this.to-this.from)}resolve(e,t=0){return ee(this,e,t,!1)}resolveInner(e,t=0){return ee(this,e,t,!0)}enterUnfinishedNodesBefore(e){return nt(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,r=null){let i=me(this,e,t,r);return i.length?i[0]:null}getChildren(e,t=null,r=null){return me(this,e,t,r)}get node(){return this}matchContext(e){return be(this,e)}},te=class{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof B)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let r=e._parent;r;r=r._parent)this.stack.unshift(r.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:r,buffer:i}=this.buffer;return this.type=t||i.set.types[i.buffer[e]],this.from=r+i.buffer[e+1],this.to=r+i.buffer[e+2],!0}yield(e){return e?e instanceof B?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,r){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,r,this.mode));let{buffer:i}=this.buffer,n=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.buffer.start,r);return n<0?!1:(this.stack.push(this.index),this.yieldBuf(n))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,r=this.mode){return this.buffer?r&F.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,r))}parent(){if(!this.buffer)return this.yieldNode(this.mode&F.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&F.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,r=this.stack.length-1;if(e<0){let i=r<0?0:this.stack[r]+4;if(this.index!=i)return this.yieldBuf(t.findChild(i,this.index,-1,0,4))}else{let i=t.buffer[this.index+3];if(i<(r<0?t.buffer.length:t.buffer[this.stack[r]+3]))return this.yieldBuf(i)}return r<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,r,{buffer:i}=this;if(i){if(e>0){if(this.index<i.buffer.buffer.length)return!1}else for(let n=0;n<this.index;n++)if(i.buffer.buffer[n+3]<this.index)return!1;({index:t,parent:r}=i)}else({index:t,_parent:r}=this._tree);for(;r;{index:t,_parent:r}=r)if(t>-1)for(let n=t+e,o=e<0?-1:r._tree.children.length;n!=o;n+=e){let l=r._tree.children[n];if(this.mode&F.IncludeAnonymous||l instanceof $||!l.type.isAnonymous||Ee(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,r=0;if(e&&e.context==this.buffer)e:for(let i=this.index,n=this.stack.length;n>=0;){for(let o=e;o;o=o._parent)if(o.index==i){if(i==this.index)return o;t=o,r=n+1;break e}i=this.stack[--n]}for(let i=r;i<this.stack.length;i++)t=new _(this.buffer,t,this.stack[i]);return this.bufferNode=new _(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let r=0;;){let i=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){r++;continue}this.type.isAnonymous||(i=!0)}for(;i&&t&&t(this),i=this.type.isAnonymous,!this.nextSibling();){if(!r)return;this.parent(),r--,i=!0}}}matchContext(e){if(!this.buffer)return be(this.node,e);let{buffer:t}=this.buffer,{types:r}=t.set;for(let i=e.length-1,n=this.stack.length-1;i>=0;n--){if(n<0)return be(this.node,e,i);let o=r[t.buffer[this.stack[n]]];if(!o.isAnonymous){if(e[i]&&e[i]!=o.name)return!1;i--}}return!0}};function Ee(s){return s.children.some(e=>e instanceof $||!e.type.isAnonymous||Ee(e))}function rr(s){var e;let{buffer:t,nodeSet:r,maxBufferLength:i=1024,reused:n=[],minRepeatType:o=r.types.length}=s,l=Array.isArray(t)?new le(t,t.length):t,a=r.types,u=0,c=0;function h(S,v,g,b,P){let{id:y,start:x,end:C,size:E}=l,Q=c;for(;E<0;)if(l.next(),E==-1){let X=n[y];g.push(X),b.push(x-S);return}else if(E==-3){u=y;return}else if(E==-4){c=y;return}else throw new RangeError(`Unrecognized record size: ${E}`);let Z=a[y],H,W,qe=x-S;if(C-x<=i&&(W=m(l.pos-v,P))){let X=new Uint16Array(W.size-W.skip),M=l.pos-W.size,L=X.length;for(;l.pos>M;)L=T(W.start,X,L);H=new $(X,C-W.start,r),qe=W.start-S}else{let X=l.pos-E;l.next();let M=[],L=[],Y=y>=o?y:-1,J=0,pe=C;for(;l.pos>X;)Y>=0&&l.id==Y&&l.size>=0?(l.end<=pe-i&&(p(M,L,x,J,l.end,pe,Y,Q),J=M.length,pe=l.end),l.next()):h(x,X,M,L,Y);if(Y>=0&&J>0&&J<M.length&&p(M,L,x,J,x,pe,Y,Q),M.reverse(),L.reverse(),Y>-1&&J>0){let Ze=f(Z);H=Re(Z,M,L,0,M.length,0,C-x,Ze,Ze)}else H=d(Z,M,L,C-x,Q-C)}g.push(H),b.push(qe)}function f(S){return(v,g,b)=>{let P=0,y=v.length-1,x,C;if(y>=0&&(x=v[y])instanceof A){if(!y&&x.type==S&&x.length==b)return x;(C=x.prop(k.lookAhead))&&(P=g[y]+x.length+C)}return d(S,v,g,b,P)}}function p(S,v,g,b,P,y,x,C){let E=[],Q=[];for(;S.length>b;)E.push(S.pop()),Q.push(v.pop()+g-P);S.push(d(r.types[x],E,Q,y-P,C-y)),v.push(P-g)}function d(S,v,g,b,P=0,y){if(u){let x=[k.contextHash,u];y=y?[x].concat(y):[x]}if(P>25){let x=[k.lookAhead,P];y=y?[x].concat(y):[x]}return new A(S,v,g,b,y)}function m(S,v){let g=l.fork(),b=0,P=0,y=0,x=g.end-i,C={size:0,start:0,skip:0};e:for(let E=g.pos-S;g.pos>E;){let Q=g.size;if(g.id==v&&Q>=0){C.size=b,C.start=P,C.skip=y,y+=4,b+=4,g.next();continue}let Z=g.pos-Q;if(Q<0||Z<E||g.start<x)break;let H=g.id>=o?4:0,W=g.start;for(g.next();g.pos>Z;){if(g.size<0)if(g.size==-3)H+=4;else break e;else g.id>=o&&(H+=4);g.next()}P=W,b+=Q,y+=H}return(v<0||b==S)&&(C.size=b,C.start=P,C.skip=y),C.size>4?C:void 0}function T(S,v,g){let{id:b,start:P,end:y,size:x}=l;if(l.next(),x>=0&&b<o){let C=g;if(x>4){let E=l.pos-(x-4);for(;l.pos>E;)g=T(S,v,g)}v[--g]=C,v[--g]=y-S,v[--g]=P-S,v[--g]=b}else x==-3?u=b:x==-4&&(c=b);return g}let N=[],w=[];for(;l.pos>0;)h(s.start||0,s.bufferStart||0,N,w,-1);let O=(e=s.length)!==null&&e!==void 0?e:N.length?w[0]+N[0].length:0;return new A(a[s.topID],N.reverse(),w.reverse(),O)}var st=new WeakMap;function ge(s,e){if(!s.isAnonymous||e instanceof $||e.type!=s)return 1;let t=st.get(e);if(t==null){t=1;for(let r of e.children){if(r.type!=s||!(r instanceof A)){t=1;break}t+=ge(s,r)}st.set(e,t)}return t}function Re(s,e,t,r,i,n,o,l,a){let u=0;for(let d=r;d<i;d++)u+=ge(s,e[d]);let c=Math.ceil(u*1.5/8),h=[],f=[];function p(d,m,T,N,w){for(let O=T;O<N;){let S=O,v=m[O],g=ge(s,d[O]);for(O++;O<N;O++){let b=ge(s,d[O]);if(g+b>=c)break;g+=b}if(O==S+1){if(g>c){let b=d[S];p(b.children,b.positions,0,b.children.length,m[S]+w);continue}h.push(d[S])}else{let b=m[O-1]+d[O-1].length-v;h.push(Re(s,d,m,S,O,v,b,null,a))}f.push(v+w-n)}}return p(e,t,r,i,0),(l||a)(h,f,o)}var xe=class{startParse(e,t,r){return typeof e=="string"&&(e=new Ne(e)),r=r?r.length?r.map(i=>new oe(i.from,i.to)):[new oe(0,0)]:[new oe(0,e.length)],this.createParse(e,t||[],r)}parse(e,t,r){let i=this.startParse(e,t,r);for(;;){let n=i.advance();if(n)return n}}},Ne=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var Fs=new k({perNode:!0});var se=class{constructor(e,t,r,i,n,o,l,a,u,c=0,h){this.p=e,this.stack=t,this.state=r,this.reducePos=i,this.pos=n,this.score=o,this.buffer=l,this.bufferBase=a,this.curContext=u,this.lookAhead=c,this.parent=h}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,r=0){let i=e.parser.context;return new se(e,[],t,r,r,0,[],0,i?new Se(i,i.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let r=e>>19,i=e&65535,{parser:n}=this.p,o=n.dynamicPrecedence(i);if(o&&(this.score+=o),r==0){this.pushState(n.getGoto(this.state,i,!0),this.reducePos),i<n.minRepeatTerm&&this.storeNode(i,this.reducePos,this.reducePos,4,!0),this.reduceContext(i,this.reducePos);return}let l=this.stack.length-(r-1)*3-(e&262144?6:0),a=l?this.stack[l-2]:this.p.ranges[0].from,u=this.reducePos-a;u>=2e3&&!(!((t=this.p.parser.nodeSet.types[i])===null||t===void 0)&&t.isAnonymous)&&(a==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=u):this.p.lastBigReductionSize<u&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=a,this.p.lastBigReductionSize=u));let c=l?this.stack[l-1]:0,h=this.bufferBase+this.buffer.length-c;if(i<n.minRepeatTerm||e&131072){let f=n.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(i,a,f,h+4,!0)}if(e&262144)this.state=this.stack[l];else{let f=this.stack[l-3];this.state=n.getGoto(f,i,!0)}for(;this.stack.length>l;)this.stack.pop();this.reduceContext(i,a)}storeNode(e,t,r,i=4,n=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let o=this,l=this.buffer.length;if(l==0&&o.parent&&(l=o.bufferBase-o.parent.bufferBase,o=o.parent),l>0&&o.buffer[l-4]==0&&o.buffer[l-1]>-1){if(t==r)return;if(o.buffer[l-2]>=t){o.buffer[l-2]=r;return}}}if(!n||this.pos==r)this.buffer.push(e,t,r,i);else{let o=this.buffer.length;if(o>0&&this.buffer[o-4]!=0)for(;o>0&&this.buffer[o-2]>r;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,i>4&&(i-=4);this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=r,this.buffer[o+3]=i}}shift(e,t,r){let i=this.pos;if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=r,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,r,4);else{let n=e,{parser:o}=this.p;(r>this.pos||t<=o.maxNode)&&(this.pos=r,o.stateFlag(n,1)||(this.reducePos=r)),this.pushState(n,i),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,r,4)}}apply(e,t,r){e&65536?this.reduce(e):this.shift(e,t,r)}useNode(e,t){let r=this.p.reused.length-1;(r<0||this.p.reused[r]!=e)&&(this.p.reused.push(e),r++);let i=this.pos;this.reducePos=this.pos=i+e.length,this.pushState(t,i),this.buffer.push(r,i,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let r=e.buffer.slice(t),i=e.bufferBase+t;for(;e&&i==e.bufferBase;)e=e.parent;return new se(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,r,i,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let r=e<=this.p.parser.maxNode;r&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,r?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new De(this);;){let r=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(r==0)return!1;if(!(r&65536))return!0;t.reduce(r)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>4<<1||this.stack.length>=120){let i=[];for(let n=0,o;n<t.length;n+=2)(o=t[n+1])!=this.state&&this.p.parser.hasAction(o,e)&&i.push(t[n],o);if(this.stack.length<120)for(let n=0;i.length<4<<1&&n<t.length;n+=2){let o=t[n+1];i.some((l,a)=>a&1&&l==o)||i.push(t[n],o)}t=i}let r=[];for(let i=0;i<t.length&&r.length<4;i+=2){let n=t[i+1];if(n==this.state)continue;let o=this.split();o.pushState(n,this.pos),o.storeNode(0,o.pos,o.pos,4,!0),o.shiftContext(t[i],this.pos),o.score-=200,r.push(o)}return r}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if(!(t&65536))return!1;if(!e.validAction(this.state,t)){let r=t>>19,i=t&65535,n=this.stack.length-r*3;if(n<0||e.getGoto(this.stack[n],i,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],r=(i,n)=>{if(!t.includes(i))return t.push(i),e.allActions(i,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-n;if(l>1){let a=o&65535,u=this.stack.length-l*3;if(u>=0&&e.getGoto(this.stack[u],a,!1)>=0)return l<<19|65536|a}}else{let l=r(o,n+1);if(l!=null)return l}})};return r(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new Se(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){e>this.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},Se=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},ot;(function(s){s[s.Insert=200]="Insert",s[s.Delete=190]="Delete",s[s.Reduce=100]="Reduce",s[s.MaxNext=4]="MaxNext",s[s.MaxInsertStackDepth=300]="MaxInsertStackDepth",s[s.DampenInsertStackDepth=120]="DampenInsertStackDepth",s[s.MinBigReduction=2e3]="MinBigReduction"})(ot||(ot={}));var De=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,r=e>>19;r==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(r-1)*3;let i=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=i}},ie=class{constructor(e,t,r){this.stack=e,this.pos=t,this.index=r,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new ie(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new ie(this.stack,this.pos,this.index)}};function ae(s,e=Uint16Array){if(typeof s!="string")return s;let t=null;for(let r=0,i=0;r<s.length;){let n=0;for(;;){let o=s.charCodeAt(r++),l=!1;if(o==126){n=65535;break}o>=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),n+=a,l)break;n*=46}t?t[i++]=n:t=new e(n)}return t}var re=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},lt=new re,Qe=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=lt,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let r=this.range,i=this.rangeIndex,n=this.pos+e;for(;n<r.from;){if(!i)return null;let o=this.ranges[--i];n-=r.from-o.to,r=o}for(;t<0?n>r.to:n>=r.to;){if(i==this.ranges.length-1)return null;let o=this.ranges[++i];n+=o.from-r.to,r=o}return n}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,r,i;if(t>=0&&t<this.chunk.length)r=this.pos+e,i=this.chunk.charCodeAt(t);else{let n=this.resolveOffset(e,1);if(n==null)return-1;if(r=n,r>=this.chunk2Pos&&r<this.chunk2Pos+this.chunk2.length)i=this.chunk2.charCodeAt(r-this.chunk2Pos);else{let o=this.rangeIndex,l=this.range;for(;l.to<=r;)l=this.ranges[++o];this.chunk2=this.input.chunk(this.chunk2Pos=r),r+this.chunk2.length>l.to&&(this.chunk2=this.chunk2.slice(0,l.to-r)),i=this.chunk2.charCodeAt(0)}}return r>=this.token.lookAhead&&(this.token.lookAhead=r+1),i}acceptToken(e,t=0){let r=t?this.resolveOffset(t,-1):this.pos;if(r==null||r<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=e,this.token.end=r}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=lt,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let r="";for(let i of this.ranges){if(i.from>=t)break;i.to>e&&(r+=this.input.read(Math.max(i.from,e),Math.min(i.to,t)))}return r}},G=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:r}=t.p;dt(this.data,e,t,this.id,r.data,r.tokenPrecTable)}};G.prototype.contextual=G.prototype.fallback=G.prototype.extend=!1;var Me=class{constructor(e,t,r){this.precTable=t,this.elseToken=r,this.data=typeof e=="string"?ae(e):e}token(e,t){let r=e.pos,i=0;for(;;){let n=e.next<0,o=e.resolveOffset(1,1);if(dt(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(n||i++,o==null)break;e.reset(o,e.token)}i&&(e.reset(r,e.token),e.acceptToken(this.elseToken,i))}};Me.prototype.contextual=G.prototype.fallback=G.prototype.extend=!1;function dt(s,e,t,r,i,n){let o=0,l=1<<r,{dialect:a}=t.p.parser;e:for(;l&s[o];){let u=s[o+1];for(let p=o+3;p<u;p+=2)if((s[p+1]&l)>0){let d=s[p];if(a.allows(d)&&(e.token.value==-1||e.token.value==d||ir(d,e.token.value,i,n))){e.acceptToken(d);break}}let c=e.next,h=0,f=s[o+2];if(e.next<0&&f>h&&s[u+f*3-3]==65535&&s[u+f*3-3]==65535){o=s[u+f*3-1];continue e}for(;h<f;){let p=h+f>>1,d=u+p+(p<<1),m=s[d],T=s[d+1]||65536;if(c<m)f=p;else if(c>=T)h=p+1;else{o=s[d+2],e.advance();continue e}}break}}function at(s,e,t){for(let r=e,i;(i=s[r])!=65535;r++)if(i==t)return r-e;return-1}function ir(s,e,t,r){let i=at(t,r,e);return i<0||at(t,r,s)<i}var z=typeof process<"u"&&process.env&&/\bparse\b/.test(process.env.LOG),Ie=null,ut;(function(s){s[s.Margin=25]="Margin"})(ut||(ut={}));function ht(s,e,t){let r=s.cursor(F.IncludeAnonymous);for(r.moveTo(e);;)if(!(t<0?r.childBefore(e):r.childAfter(e)))for(;;){if((t<0?r.to<e:r.from>e)&&!r.type.isError)return t<0?Math.max(0,Math.min(r.to-1,e-25)):Math.min(s.length,Math.max(r.from+1,e+25));if(t<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return t<0?0:s.length}}var Be=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?ht(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?ht(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let r=this.trees[t],i=this.index[t];if(i==r.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let n=r.children[i],o=this.start[t]+r.positions[i];if(o>e)return this.nextStart=o,null;if(n instanceof A){if(o==e){if(o<this.safeFrom)return null;let l=o+n.length;if(l<=this.safeTo){let a=n.prop(k.lookAhead);if(!a||l+a<this.fragment.to)return n}}this.index[t]++,o+n.length>=Math.max(this.safeFrom,e)&&(this.trees.push(n),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+n.length}}},ze=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(r=>new re)}getActions(e){let t=0,r=null,{parser:i}=e.p,{tokenizers:n}=i,o=i.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let u=0;u<n.length;u++){if(!(1<<u&o))continue;let c=n[u],h=this.tokens[u];if(!(r&&!c.fallback)&&((c.contextual||h.start!=e.pos||h.mask!=o||h.context!=l)&&(this.updateCachedToken(h,c,e),h.mask=o,h.context=l),h.lookAhead>h.end+25&&(a=Math.max(h.lookAhead,a)),h.value!=0)){let f=t;if(h.extended>-1&&(t=this.addActions(e,h.extended,h.end,t)),t=this.addActions(e,h.value,h.end,t),!c.extend&&(r=h,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!r&&e.pos==this.stream.end&&(r=new re,r.value=e.p.parser.eofTerm,r.start=r.end=e.pos,t=this.addActions(e,r.value,r.end,t)),this.mainToken=r,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new re,{pos:r,p:i}=e;return t.start=r,t.end=Math.min(r+1,i.stream.end),t.value=r==i.stream.end?i.parser.eofTerm:0,t}updateCachedToken(e,t,r){let i=this.stream.clipPos(r.pos);if(t.token(this.stream.reset(i,e),r),e.value>-1){let{parser:n}=r.p;for(let o=0;o<n.specialized.length;o++)if(n.specialized[o]==e.value){let l=n.specializers[o](this.stream.read(e.start,e.end),r);if(l>=0&&r.p.parser.dialect.allows(l>>1)){l&1?e.extended=l>>1:e.value=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(i+1)}putAction(e,t,r,i){for(let n=0;n<i;n+=3)if(this.actions[n]==e)return i;return this.actions[i++]=e,this.actions[i++]=t,this.actions[i++]=r,i}addActions(e,t,r,i){let{state:n}=e,{parser:o}=e.p,{data:l}=o;for(let a=0;a<2;a++)for(let u=o.stateSlot(n,a?2:1);;u+=3){if(l[u]==65535)if(l[u+1]==1)u=j(l,u+2);else{i==0&&l[u+1]==2&&(i=this.putAction(j(l,u+2),t,r,i));break}l[u]==t&&(i=this.putAction(j(l,u+1),t,r,i))}return i}},ft;(function(s){s[s.Distance=5]="Distance",s[s.MaxRemainingPerStep=3]="MaxRemainingPerStep",s[s.MinBufferLengthPrune=500]="MinBufferLengthPrune",s[s.ForceReduceLimit=10]="ForceReduceLimit",s[s.CutDepth=15e3]="CutDepth",s[s.CutTo=9e3]="CutTo",s[s.MaxLeftAssociativeReductionCount=300]="MaxLeftAssociativeReductionCount",s[s.MaxStackCount=12]="MaxStackCount"})(ft||(ft={}));var Ve=class{constructor(e,t,r,i){this.parser=e,this.input=t,this.ranges=i,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new Qe(t,i),this.tokens=new ze(e,this.stream),this.topTerm=e.top[1];let{from:n}=i[0];this.stacks=[se.start(this,e.top[0],n)],this.fragments=r.length&&this.stream.end-n>e.bufferLength*4?new Be(r,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,r=this.stacks=[],i,n;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;o<e.length;o++){let l=e[o];for(;;){if(this.tokens.mainToken=null,l.pos>t)r.push(l);else{if(this.advanceStack(l,r,e))continue;{i||(i=[],n=[]),i.push(l);let a=this.tokens.getMainToken(l);n.push(a.value,a.end)}}break}}if(!r.length){let o=i&&nr(i);if(o)return this.stackToTree(o);if(this.parser.strict)throw z&&i&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&i){let o=this.stoppedAt!=null&&i[0].pos>this.stoppedAt?i[0]:this.runRecovery(i,n,r);if(o)return this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(r.length>o)for(r.sort((l,a)=>a.score-l.score);r.length>o;)r.pop();r.some(l=>l.reducePos>t)&&this.recovering--}else if(r.length>1){e:for(let o=0;o<r.length-1;o++){let l=r[o];for(let a=o+1;a<r.length;a++){let u=r[a];if(l.sameState(u)||l.buffer.length>500&&u.buffer.length>500)if((l.score-u.score||l.buffer.length-u.buffer.length)>0)r.splice(a--,1);else{r.splice(o--,1);continue e}}}r.length>12&&r.splice(12,r.length-12)}this.minStackPos=r[0].pos;for(let o=1;o<r.length;o++)r[o].pos<this.minStackPos&&(this.minStackPos=r[o].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}advanceStack(e,t,r){let i=e.pos,{parser:n}=this,o=z?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&i>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let u=e.curContext&&e.curContext.tracker.strict,c=u?e.curContext.hash:0;for(let h=this.fragments.nodeAt(i);h;){let f=this.parser.nodeSet.types[h.type.id]==h.type?n.getGoto(e.state,h.type.id):-1;if(f>-1&&h.length&&(!u||(h.prop(k.contextHash)||0)==c))return e.useNode(h,f),z&&console.log(o+this.stackID(e)+` (via reuse of ${n.getName(h.type.id)})`),!0;if(!(h instanceof A)||h.children.length==0||h.positions[0]>0)break;let p=h.children[0];if(p instanceof A&&h.positions[0]==0)h=p;else break}}let l=n.stateSlot(e.state,4);if(l>0)return e.reduce(l),z&&console.log(o+this.stackID(e)+` (via always-reduce ${n.getName(l&65535)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let u=0;u<a.length;){let c=a[u++],h=a[u++],f=a[u++],p=u==a.length||!r,d=p?e:e.split();if(d.apply(c,h,f),z&&console.log(o+this.stackID(d)+` (via ${c&65536?`reduce of ${n.getName(c&65535)}`:"shift"} for ${n.getName(h)} @ ${i}${d==e?"":", split"})`),p)return!0;d.pos>i?t.push(d):r.push(d)}return!1}advanceFully(e,t){let r=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>r)return ct(e,t),!0}}runRecovery(e,t,r){let i=null,n=!1;for(let o=0;o<e.length;o++){let l=e[o],a=t[o<<1],u=t[(o<<1)+1],c=z?this.stackID(l)+" -> ":"";if(l.deadEnd&&(n||(n=!0,l.restart(),z&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,r))))continue;let h=l.split(),f=c;for(let p=0;h.forceReduce()&&p<10&&(z&&console.log(f+this.stackID(h)+" (via force-reduce)"),!this.advanceFully(h,r));p++)z&&(f=this.stackID(h)+" -> ");for(let p of l.recoverByInsert(a))z&&console.log(c+this.stackID(p)+" (via recover-insert)"),this.advanceFully(p,r);this.stream.end>l.pos?(u==l.pos&&(u++,a=0),l.recoverByDelete(a,u),z&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),ct(l,r)):(!i||i.score<l.score)&&(i=l)}return i}stackToTree(e){return e.close(),A.build({buffer:ie.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(Ie||(Ie=new WeakMap)).get(e);return t||Ie.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function ct(s,e){for(let t=0;t<e.length;t++){let r=e[t];if(r.pos==s.pos&&r.sameState(s)){e[t].score<s.score&&(e[t]=s);return}}e.push(s)}var _e=class{constructor(e,t,r){this.source=e,this.flags=t,this.disabled=r}allows(e){return!this.disabled||this.disabled[e]==0}};var q=class extends xe{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;l<e.repeatNodeCount;l++)t.push("");let r=Object.keys(e.topRules).map(l=>e.topRules[l][1]),i=[];for(let l=0;l<t.length;l++)i.push([]);function n(l,a,u){i[l].push([a,a.deserialize(String(u))])}if(e.nodeProps)for(let l of e.nodeProps){let a=l[0];typeof a=="string"&&(a=k[a]);for(let u=1;u<l.length;){let c=l[u++];if(c>=0)n(c,a,l[u++]);else{let h=l[u+-c];for(let f=-c;f>0;f--)n(l[u++],a,h);u++}}}this.nodeSet=new K(t.map((l,a)=>R.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:i[a],top:r.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=ae(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;l<this.specializerSpecs.length;l++)this.specialized[l]=this.specializerSpecs[l].term;this.specializers=this.specializerSpecs.map(pt),this.states=ae(e.states,Uint32Array),this.data=ae(e.stateData),this.goto=ae(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(l=>typeof l=="number"?new G(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,r){let i=new Ve(this,e,t,r);for(let n of this.wrappers)i=n(i,e,t,r);return i}getGoto(e,t,r=!1){let i=this.goto;if(t>=i[0])return-1;for(let n=i[t+1];;){let o=i[n++],l=o&1,a=i[n++];if(l&&r)return a;for(let u=n+(o>>1);n<u;n++)if(i[n]==e)return a;if(l)return-1}}hasAction(e,t){let r=this.data;for(let i=0;i<2;i++)for(let n=this.stateSlot(e,i?2:1),o;;n+=3){if((o=r[n])==65535)if(r[n+1]==1)o=r[n=j(r,n+2)];else{if(r[n+1]==2)return j(r,n+2);break}if(o==t||o==0)return j(r,n+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,r=>r==t?!0:null)}allActions(e,t){let r=this.stateSlot(e,4),i=r?t(r):void 0;for(let n=this.stateSlot(e,1);i==null;n+=3){if(this.data[n]==65535)if(this.data[n+1]==1)n=j(this.data,n+2);else break;i=t(j(this.data,n+1))}return i}nextStates(e){let t=[];for(let r=this.stateSlot(e,1);;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=j(this.data,r+2);else break;if(!(this.data[r+2]&1)){let i=this.data[r+1];t.some((n,o)=>o&1&&n==i)||t.push(this.data[r],i)}}return t}configure(e){let t=Object.assign(Object.create(q.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let r=this.topRules[e.top];if(!r)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=r}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(r=>{let i=e.tokenizers.find(n=>n.from==r);return i?i.to:r})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((r,i)=>{let n=e.specializers.find(l=>l.from==r.external);if(!n)return r;let o=Object.assign(Object.assign({},r),{external:n.to});return t.specializers[i]=pt(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),r=t.map(()=>!1);if(e)for(let n of e.split(" ")){let o=t.indexOf(n);o>=0&&(r[o]=!0)}let i=null;for(let n=0;n<t.length;n++)if(!r[n])for(let o=this.dialects[t[n]],l;(l=this.data[o++])!=65535;)(i||(i=new Uint8Array(this.maxTerm+1)))[l]=1;return new _e(e,r,i)}static deserialize(e){return new q(e)}};function j(s,e){return s[e]|s[e+1]<<16}function nr(s){let e=null;for(let t of s){let r=t.p.stoppedAt;(t.pos==t.p.stream.end||r!=null&&t.pos>r)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.score<t.score)&&(e=t)}return e}function pt(s){if(s.external){let e=s.extend?1:0;return(t,r)=>s.external(t,r)<<1|e}return s.get}var ue=q.deserialize({version:14,states:"%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",stateData:"#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",goto:"#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",nodeNames:"\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",maxTerm:39,skippedNodes:[0],repeatNodeCount:1,tokenData:"6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",tokenizers:[0,1],topRules:{Filter:[0,1]},tokenPrec:0});import{isMultiClauseFilter as he,isMultiValueFilter as or,isSingleValueFilter as lr}from"@vuu-ui/vuu-utils";var I,We=class{constructor(){tt(this,I,void 0)}setFilterCombinatorOp(e,t=V(this,I)){he(t)&&t.op===e||Ae(this,I,{op:e,filters:[V(this,I)]})}add(e){if(V(this,I)===void 0)Ae(this,I,e);else if(he(V(this,I)))V(this,I).filters.push(e);else throw Error("Invalid filter passed to FilterExpression")}setColumn(e,t=V(this,I)){if(he(t)){let r=t.filters.at(-1);r&&this.setColumn(e,r)}else t&&(t.column=e)}setOp(e,t=V(this,I)){if(he(t)){let r=t.filters.at(-1);r&&this.setOp(e,r)}else t&&(t.op=e)}setValue(e,t=V(this,I)){var r;if(he(t)){let i=t.filters.at(-1);i&&this.setValue(e,i)}else or(t)?((r=t.values)!=null||(t.values=[]),t.values.push(e)):lr(t)&&(t.value=e)}toJSON(e=V(this,I)){return this.name?{...e,name:this.name}:e}};I=new WeakMap;var ye=(s,e)=>{let t=new We,r=s.cursor();do{let{name:i,from:n,to:o}=r;switch(i){case"ColumnValueExpression":t.add({});break;case"ColumnSetExpression":t.add({op:"in"});break;case"Or":case"And":t.setFilterCombinatorOp(e.substring(n,o));break;case"Column":t.setColumn(e.substring(n,o));break;case"Operator":t.setOp(e.substring(n,o));break;case"String":t.setValue(e.substring(n+1,o-1));break;case"Number":t.setValue(parseFloat(e.substring(n,o)));break;case"True":t.setValue(!0);break;case"False":t.setValue(!1);break;case"FilterName":t.name=e.substring(n,o);break;default:}}while(r.next());return t.toJSON()};var zs=ue.configure({strict:!0});var At=Ke(Le(),1);import{useEffect as Cr,useMemo as Pr,useRef as je}from"react";import{LanguageSupport as ur,LRLanguage as hr,styleTags as fr,tags as ve}from"@vuu-ui/vuu-codemirror";var cr=hr.define({name:"VuuFilterQuery",parser:ue.configure({props:[fr({Identifier:ve.variableName,String:ve.string,Or:ve.emphasis,Operator:ve.operator})]})}),gt=()=>new ur(cr);import{HighlightStyle as pr,syntaxHighlighting as dr,tags as mt}from"@vuu-ui/vuu-codemirror";var gr=pr.define([{tag:mt.variableName,color:"var(--vuuFilterEditor-variableColor)"},{tag:mt.comment,color:"green",fontStyle:"italic"}]),bt=dr(gr);import{EditorView as mr}from"@vuu-ui/vuu-codemirror";var xt=mr.theme({"&":{color:"var(--vuuFilterEditor-color)",backgroundColor:"var(--vuuFilterEditor-background)",fontSize:"var(--vuuFilterEditor-fontSize)"},".cm-content":{caretColor:"var(--vuuFilterEditor-cursorColor)",padding:0},".cm-line":{lineHeight:"var(--vuuFilterEditor-lineHeight)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--vuuFilterEditor-cursorColor)"},"&.cm-focused .cm-selectionBackground, ::selection":{backgroundColor:"var(--vuuFilterEditor-selectionBackground)"},".cm-selectionBackground, ::selection":{backgroundColor:"var(--vuuFilterEditor-selectionBackground)"},".cm-scroller":{fontFamily:"var(--vuuFilterEditor-fontFamily)"},".cm-tooltip":{background:"var(--vuuFilterEditor-tooltipBackground)",border:"var(--vuuFilterEditor-tooltipBorder)",boxShadow:"var(--vuuFilterEditor-tooltipElevation)","&.cm-tooltip-autocomplete > ul":{fontFamily:"var(--vuuFilterEditor-fontFamily)",fontSize:"var(--vuuFilterEditor-fontSize)",maxHeight:"240px"},"&.cm-tooltip-autocomplete > ul > li":{alignItems:"center",display:"flex",height:"var(--vuuFilterEditor-suggestion-height)",padding:"0 3px",lineHeight:"var(--vuuFilterEditor-suggestion-height)"},"&.cm-tooltip-autocomplete li[aria-selected]":{background:"var(--vuuFilterEditor-suggestion-selectedBackground)",color:"var(--vuuFilterEditor-suggestion-selectedColor)"}},".cm-completionIcon":{height:"18px",flex:"0 0 16px"},".cm-completionLabel":{flex:"1 1 auto"},".cm-completionIcon-filter":{position:"relative","&:after":{background:"var(--salt-text-secondary-foreground)",content:"''","-webkit-mask":"var(--svg-filter) center center/13px 13px","-webkit-mask-repeat":"no-repeat",position:"absolute",height:"18px",left:"0px",top:"0px",width:"16px"}}},{dark:!1});import{getNodeByName as ne,getValue as U,syntaxTree as br}from"@vuu-ui/vuu-codemirror";import{useCallback as St}from"react";var yt=(s,e)=>{let t=s.prevSibling||s.parent;for(;t&&!["Column","Operator","In"].includes(t.name);)t=t.prevSibling||t.parent;if((t==null?void 0:t.name)==="In"||(t==null?void 0:t.name)==="Operator")return U(t,e)},xr=(s,e,t)=>{let r=U(s,e);if(!(t===void 0||r===t)&&["contains","ends","starts"].some(i=>i.startsWith(r.toLowerCase())))return r},kt=(s,e)=>{let t=s.prevSibling||s.parent||s.lastChild;for(;t&&t.name==="\u26A0";)t=t.prevSibling;if(t&&["As","Or","And"].includes(t.name))return U(t,e)},vt=(s,e)=>{if(s.name==="FilterName")return U(s,e);{let t=s.prevSibling||s.parent||s.lastChild;for(;t&&t.name!=="FilterName";)t=t.prevSibling;if(t&&t.name==="FilterName")return U(s,e)}},Ot=(s,e)=>{let t=s.prevSibling;if((t==null?void 0:t.name)==="Column")return U(t,e);if((t==null?void 0:t.name)==="Operator")return Ot(t,e)},Sr=(s,e)=>{let t=s.lastChild,r=[];for(;t&&t.name!=="In";){let i=U(t,e);if(i)r.push(i);else break;t=t.prevSibling}return r};var Ct=(s,e,t)=>{let r=St(async(i,n,o={})=>{let{startsWith:l=""}=o,a=await s.getSuggestions(n,o);return{from:i.pos-l.length,options:a}},[s]);return St(async i=>{var c,h;let{state:n,pos:o}=i,l=(c=i.matchBefore(/\w*/))!=null?c:{from:0,to:0,text:void 0},u=br(n).resolveInner(o,-1);switch(console.log({nodeBeforeName:u.name}),u.name){case"Filter":if(i.pos===0)return r(i,"column");if(kt(u,n)==="as")return r(i,"name");{let p=vt(u,n);return r(i,"save",{onSubmit:e.current,existingFilter:t,filterName:p})}case"String":{let f=yt(u,n),p=Ot(u,n),{from:d,to:m}=u;if(m-d===2&&i.pos===d+1){if(p&&f)return r(i,"columnValue",{columnName:p,operator:f,quoted:!0,startsWith:l.text})}else console.log(`we have a string, column is ${p} ${d} ${m}`)}break;case"As":return r(i,"name");case"FilterName":return r(i,"save",{onSubmit:e.current,existingFilter:t,filterName:vt(u,n)});case"Column":{let f=U(u,n);return await s.isPartialMatch("column",void 0,f)?r(i,"column",{startsWith:f}):r(i,"operator",{columnName:f})}case"\u26A0":{let f=ne(u,n),p=yt(u,n),d=p?void 0:xr(u,n,f);return d?r(i,"operator",{columnName:f,startsWith:d}):r(i,"columnValue",{columnName:f,operator:p,startsWith:l.text})}case"Identifier":if(kt(u,n)==="as")return{from:i.pos,options:[{label:"press ENTER to apply filter and save",apply:()=>e.current(),boost:5}]};break;case"ColumnSetExpression":case"Values":{let f=ne(u,n),p=Sr(u,n);return r(i,"columnValue",{columnName:f,selection:p})}case"Comma":case"LBrack":{let f=ne(u,n);return r(i,"columnValue",{columnName:f})}case"ColumnValueExpression":{let f=(h=u.lastChild)==null?void 0:h.prevSibling;if((f==null?void 0:f.name)==="Column")return r(i,"operator",{columnName:ne(u,n)});if((f==null?void 0:f.name)==="Operator")return r(i,"columnValue",{columnName:ne(f,n),operator:U(f,n)})}break;case"In":return{from:i.pos,options:[{label:"[",apply:" [",type:"text"}]};case"Eq":return r(i,"columnValue",{columnName:ne(u,n)});case"AndExpression":case"OrExpression":return r(i,"column");default:}},[t,r,e,s])};var fe=s=>{if(s.current==null)throw Error("EditorView not defined");return s.current},wr=s=>(0,At.default)("vuuSuggestion",{vuuIllustration:s.isIllustration}),Fr=s=>{let e=s.lastIndexOf(" as ");return e!==-1?s.slice(0,e):s},Ar=()=>console.log("noooop"),Tt=({existingFilter:s,onSubmitFilter:e,suggestionProvider:t})=>{let r=je(null),i=je(Ar),n=je(),o=Ct(t,i,s),[l,a]=Pr(()=>{let u=()=>{let m=fe(n),T=m.state.doc.toString(),N=vr(m.state,m.state.doc.length,5e3);if(N){let w=ye(N,T);return[w,Fr(T),w.name]}else return[void 0,"",void 0]},c=()=>{fe(n).setState(d())},h=m=>{let[T,N,w]=u();e==null||e(T,N,m,w),c()},f=m=>$e.of([{key:m,run(){return h(),!0}}]),p=m=>$e.of([{key:m,run(){return Ft(fe(n)),!0}}]),d=()=>Pt.create({doc:"",extensions:[Or,yr({override:[o],optionClass:wr}),gt(),$e.of(kr),f("Ctrl-Enter"),p("ArrowDown"),wt.updateListener.of(m=>{let T=fe(n);m.docChanged&&Ft(T)}),Pt.transactionFilter.of(m=>m.newDoc.lines>1?[]:m),xt,bt]});return i.current=m=>{h(m),setTimeout(()=>{fe(n).focus()},100)},[d,c]},[o,e]);return Cr(()=>{if(!r.current)throw Error("editor not in dom");return n.current=new wt({state:l(),parent:r.current}),()=>{var u;(u=n.current)==null||u.destroy()}},[o,l]),{editorRef:r,clearInput:a}};import{jsx as Ue,jsxs as Tr}from"react/jsx-runtime";var Oe="vuuFilterInput",Ti=({existingFilter:s,iconName:e="filter",namedFilters:t,onSubmitFilter:r,suggestionProvider:i,...n})=>{let{editorRef:o,clearInput:l}=Tt({existingFilter:s,onSubmitFilter:r,suggestionProvider:i});return Tr("div",{...n,className:Oe,children:[Ue(Nt,{className:`${Oe}-FilterButton`,"data-icon":e,tabIndex:-1}),Ue("div",{className:`${Oe}-Editor`,ref:o}),Ue(Nt,{className:`${Oe}-ClearButton`,"data-icon":"close-circle",onClick:l})]})};import{asNameSuggestion as Nr,booleanJoinSuggestions as Er,getNamePrompt as Rr,numericOperators as Ir,stringOperators as Dr,toSuggestions as Qr}from"@vuu-ui/vuu-codemirror";import{getTypeaheadParams as Mr,useTypeaheadSuggestions as Br}from"@vuu-ui/vuu-data-react";import{useCallback as Rt,useRef as zr}from"react";import{createEl as Ce}from"@vuu-ui/vuu-utils";var Et=(s,e)=>{let t=Ce("div","vuuFunctionDoc"),r=Ce("div","function-heading"),i=Ce("span","function-name",s);r.appendChild(i);let n=Ce("p",void 0,e);return t.appendChild(r),t.appendChild(n),t};var Vr=[],_r={},Wr=s=>[{label:"Press ENTER to create TAB",apply:()=>s("tab"),boost:6}],It=(s,e,t=!0)=>{let r=e?[{label:"REPLACE existing filter",apply:()=>s("replace"),boost:8},{label:"AND existing filter",apply:()=>s("and"),boost:7},{label:"OR existing filter",apply:()=>s("or"),boost:7}]:[{label:"Press ENTER to submit",apply:()=>s(),boost:6}];return t?r.concat(Er).concat(Nr):r},Lr=(s,e)=>It(s,e,!0),$r=s=>It(s,void 0),jr=({existingFilter:s,filterName:e,onSubmit:t,saveOptions:r})=>{let i=e&&r.allowSaveAsTab,n=s?Lr(t,s):$r(t);return i?n.concat(Wr(t)):n},Ur=s=>s.map(e=>({boost:5,label:e.name})),Hr=s=>s?Array.from(s.entries()).map(([e,t])=>({info:()=>Et(e,t),label:e,type:"filter"})):Vr,Xr={label:"Done",apply:"] ",type:"keyword",boost:10},Pe=(s,e="")=>s.filter(t=>e===""||t.label.startsWith(e)).map(t=>({...t,apply:t.label+" "})),Gr={allowReplace:!0},_i=({columns:s,namedFilters:e,saveOptions:t=Gr,table:r,typeaheadHook:i=Br})=>{let n=zr(),o=i(),l=Rt(async(u,c=_r)=>{let{columnName:h,existingFilter:f,filterName:p,operator:d,quoted:m,onSubmit:T,startsWith:N,selection:w}=c;switch(u){case"operator":{let O=s.find(S=>S.name===h);if(O)switch(O.serverDataType){case"string":case"char":return Pe(Dr,N);case"int":case"long":case"double":return Pe(Ir)}else console.warn(`'${h}' does not match any column name`)}break;case"column":{let O=await Ur(s),S=await Hr(e);return(n.current=Pe(O)).concat(Pe(S))}case"columnValue":if(h){let O=s.find(P=>P.name===h);if(!O)throw Error(`useFilterSUggestionProvider no column ${h}`);let S=Array.isArray(w)?w.length===0?"[":",":"",v=Mr(r,h,N),g=await o(v),b=d==="starts";return n.current=Qr(g,{moveCursorToEnd:m,quoted:(O==null?void 0:O.serverDataType)==="string"&&!m,suffix:m?"":" ",prefix:b?N:S,isIllustration:b}),Array.isArray(w)&&(w==null?void 0:w.length)>1?[Xr,...n.current]:n.current}break;case"save":{if(typeof T!="function")throw Error("useFilterSuggestionProvider, onSubmit must be supplied for 'save' suggestions");return await jr({existingFilter:f,filterName:p,onSubmit:T,saveOptions:t})}case"name":return await Rr("filter");default:}return[]},[s,o,e,t,r]),a=Rt(async(u,c,h)=>{let f=await l(u,{columnName:c});if(h&&f)for(let p of f){if(p.label===h)return!1;if(p.label.startsWith(h))return!0}return!1},[l]);return{getSuggestions:l,isPartialMatch:a}};var Wt=Ke(Le(),1);import{Toolbar as us}from"@heswell/salt-lab";import{isMultiValueFilter as ns,isNamedFilter as os,isSingleValueFilter as ls}from"@vuu-ui/vuu-utils";import{ToggleButton as as,ToolbarField as zt}from"@heswell/salt-lab";import{Dropdown as Yr}from"@heswell/salt-lab";import{useCallback as qr,useState as Zr}from"react";import{jsx as Kr}from"react/jsx-runtime";var Jr=s=>typeof s=="string",Dt=s=>Jr(s)?s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1):s:s.map(Dt),Qt=({column:s,selected:e,suggestionProvider:t,...r})=>{let i=e!=null?Dt(e):void 0,n=Array.isArray(i)?i:i!=null?[i]:[],[o,l]=Zr(n);console.log({initialValues:n});let a=qr(async u=>{if(u){let c=await t.getSuggestions("columnValue",{columnName:s});console.log({values:c}),l(c.map(h=>h.label))}},[s,t]);return Kr(Yr,{...r,onOpenChange:a,selected:i,source:o})};import{Dropdown as es}from"@heswell/salt-lab";import{useCallback as ts,useState as rs}from"react";import{jsx as is}from"react/jsx-runtime";var ss=s=>typeof s=="string",Mt=s=>{if(s!==void 0)return ss(s)?s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1):s:s.map(Mt)},Bt=({column:s,selected:e,suggestionProvider:t,...r})=>{let i=Mt(e),n=Array.isArray(i)?i:i!=null?[i]:[],[o,l]=rs(n),a=ts(async u=>{if(u){let c=await t.getSuggestions("columnValue",{columnName:s});console.log({values:c}),l(c.map(h=>h.label))}},[s,t]);return is(es,{...r,onOpenChange:a,selected:i,selectionStrategy:"multiple",source:o})};import{jsx as ce}from"react/jsx-runtime";var Vt=(s,e)=>{if(os(s))return ce(as,{className:"vuuToggleButton",toggled:!0,variant:"secondary",children:s.name});if(ls(s)){let{column:t,value:r}=s;return ce(zt,{className:"vuuFilterDropdown",label:t,labelPlacement:"top",children:ce(Qt,{column:t,selected:r.toString(),selectionStrategy:"default",source:[r.toString()],suggestionProvider:e,style:{width:100}})},t)}if(ns(s)){let t=s.values.map(r=>r.toString());return ce(zt,{className:"vuuFilterDropdown",label:s.column,labelPlacement:"top",children:ce(Bt,{column:s.column,selected:t,source:t,suggestionProvider:e,style:{width:100}})},s.column)}return s.filters.map(t=>Vt(t,e))},_t=({filter:s,suggestionProvider:e})=>s?Vt(s,e):[];import{jsx as hs}from"react/jsx-runtime";var gn=({className:s,filter:e,suggestionProvider:t,...r})=>{console.log(`FilterToolbar ${JSON.stringify(e,null,2)}`);let i=_t({filter:e,suggestionProvider:t});return hs(us,{className:(0,Wt.default)("vuuFilterToolbar",s),...r,children:i})};import{extractFilterForColumn as fs,isAndFilter as Ut,isInFilter as we,isMultiClauseFilter as Fe,isMultiValueFilter as Lt,isOrFilter as cs,isSingleValueFilter as $t,partition as ps}from"@vuu-ui/vuu-utils";var D="and",He="=",kn=">",vn="<",ds="or",jt="starts",On="ends",gs="in",ms=(s,e=[])=>(s&&(Fe(s)?s.filters.forEach(t=>e.push(...ms(t))):e.push(s)),e),bs={combineWith:"and"},Cn=(s,e,{combineWith:t=D}=bs)=>{var r;if(Ye(e))Fe(e)||(s=Xe(s,{name:e.column}));else if(xs(e))return Fe(e),Xe(s,{name:(r=e.column)!=null?r:""});if(!s)return e;if(!e)return s;if(s.op===D&&e.op===D)return{op:D,filters:ks(s.filters,e.filters)};if(s.op===D){let i=Ss(s.filters,e);return i.length>1?{op:D,filters:i}:i[0]}return e.op===D?{op:D,filters:e.filters.concat(s)}:Ge(s,e,!0)?e:Ht(s,e)?ys(s,e):{op:t,filters:[s,e]}},Ye=s=>s?we(s)&&s.values.length===0?!0:Ut(s)&&s.filters.some(e=>Ye(e)):!1,xs=s=>s?s.op===jt&&s.value===""?!0:s.op===jt&&s.value==="":!1,Ss=(s,e)=>s.concat(e),ys=(s,e)=>Ye(e)?e:we(s)&&we(e)?{...s,values:[...s.values,...e.values.filter(t=>!s.values.includes(t))]}:we(s)&&e.op===He?{...s,values:s.values.concat([e.value])}:s.op===He&&e.op===He?{column:s.column,op:gs,values:[s.value,e.value]}:e,ks=(s,e)=>{let t=({op:n},{op:o})=>n===o||n[0]===o[0],r=(n,o)=>n.column===o.column&&t(n,o),i=n=>e.some(o=>r(n,o))===!1;return s.filter(i).concat(e)},Pn=(s,e)=>{if(Ge(s,e,!0))return null;if(s.op!==D)throw Error(`removeFilter cannot remove ${JSON.stringify(e)} from ${JSON.stringify(s)}`);let t=s.filters.filter(r=>!Ge(r,e));return t.length>0?{type:D,filters:t}:null},wn=(s,e)=>{if(!e)return[void 0,void 0];if(e.column===s)return[e,void 0];if(e.op!==D)return[void 0,e];let[[t=void 0],r]=ps(e.filters,i=>i.column===s);return r.length===1?[t,r[0]]:[t,{op:D,filters:r}]},vs=(s,e)=>Fe(s)?{op:s.op,filters:s.filters.map(t=>vs(t,e))}:{...s,column:e},Os=(s,e)=>{if(!s)return!1;let{op:t,column:r}=s;switch(t){case D:case ds:return s.filters!=null&&s.filters.some(i=>Os(i,e));default:return r===e.name}},Xe=(s,e)=>{let t=e.name;if(s&&s.column!==t){if(Ut(s)||cs(s)){let{op:r}=s,n=s.filters.filter(o=>o.column!==t);switch(n.length){case 0:return;case 1:return n[0];default:return{op:r,filters:n}}}return s}},Ht=(s,e)=>s.column===e.column&&(s.op==="="||s.op==="in")&&(e.op==="="||e.op==="in"),Cs=(s,e)=>{if(s===e)return!0;if(s.length===e.length){let t=s.slice().sort(),r=e.slice().sort();return t.join("|")===r.join("|")}return!1},Ge=(s,e,t=!1)=>t?s&&e&&Ht(s,e)?s.op===e.op&&($t(s)&&$t(e)&&s.value===e.value||Lt(s)&&Lt(e)&&Cs(s.values,e.values)):!1:!0,Ps=(s,e,t)=>{if(s&&e){if(t==="replace")return e;if(s.op==="and")return{...s,filters:s.filters.concat(e)};let{column:r}=e;if(r&&(e.column?fs(s,r):void 0)&&r){let n=Xe(s,{name:r});return Ps(n,e,"add")}return{op:"and",filters:[s,e]}}return e||s},Fn=(s,e,t)=>{if(e.length!==0){if(t){let r=e[0].substring(0,e[0].length-3);return{column:s,op:"starts",value:`"${r}"`}}return{column:s,op:"in",values:e.map(r=>`"${r}"`)}}},An=(s,e,t)=>{if(e!==void 0&&!(t===void 0||isNaN(t)))return{column:s,op:e,value:t}};export{D as AND,On as ENDS_WITH,He as EQUALS,Ti as FilterInput,gn as FilterToolbar,kn as GREATER_THAN,gs as IN,vn as LESS_THAN,ds as OR,jt as STARTS_WITH,Cn as addFilter,ms as filterClauses,Ge as filterEquals,Os as filterIncludesColumn,An as getNumericFilter,Fn as getTypeaheadFilter,vs as overrideColName,Pn as removeFilter,wn as splitFilterOnColumn,Ps as updateFilter,Tt as useCodeMirrorEditor,_i as useFilterSuggestionProvider};
4477
2
  /*! Bundled license information:
4478
3
 
4479
4
  classnames/index.js: