@vuu-ui/vuu-data-local 0.8.18-debug

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