@vuu-ui/vuu-data-react 0.8.0-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/cjs/index.js ADDED
@@ -0,0 +1,3668 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __accessCheck = (obj, member, msg) => {
20
+ if (!member.has(obj))
21
+ throw TypeError("Cannot " + msg);
22
+ };
23
+ var __privateGet = (obj, member, getter) => {
24
+ __accessCheck(obj, member, "read from private field");
25
+ return getter ? getter.call(obj) : member.get(obj);
26
+ };
27
+ var __privateAdd = (obj, member, value) => {
28
+ if (member.has(obj))
29
+ throw TypeError("Cannot add the same private member more than once");
30
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
31
+ };
32
+ var __privateSet = (obj, member, value, setter) => {
33
+ __accessCheck(obj, member, "write to private field");
34
+ setter ? setter.call(obj, value) : member.set(obj, value);
35
+ return value;
36
+ };
37
+
38
+ // src/index.ts
39
+ var src_exports = {};
40
+ __export(src_exports, {
41
+ MovingWindow: () => MovingWindow,
42
+ addRowsFromInstruments: () => addRowsFromInstruments,
43
+ getTypeaheadParams: () => getTypeaheadParams,
44
+ isViewportMenusAction: () => isViewportMenusAction,
45
+ isVisualLinkCreatedAction: () => isVisualLinkCreatedAction,
46
+ isVisualLinkRemovedAction: () => isVisualLinkRemovedAction,
47
+ isVisualLinksAction: () => isVisualLinksAction,
48
+ isVuuFeatureAction: () => isVuuFeatureAction,
49
+ isVuuFeatureInvocation: () => isVuuFeatureInvocation,
50
+ useDataSource: () => useDataSource,
51
+ useServerConnectionQuality: () => useServerConnectionQuality,
52
+ useServerConnectionStatus: () => useServerConnectionStatus,
53
+ useTypeaheadSuggestions: () => useTypeaheadSuggestions,
54
+ useVuuMenuActions: () => useVuuMenuActions,
55
+ useVuuTables: () => useVuuTables
56
+ });
57
+ module.exports = __toCommonJS(src_exports);
58
+
59
+ // src/hooks/useDataSource.ts
60
+ var import_vuu_utils = require("@vuu-ui/vuu-utils");
61
+ var import_react = require("react");
62
+ var { SELECTED } = import_vuu_utils.metadataKeys;
63
+ function useDataSource({
64
+ dataSource,
65
+ renderBufferSize = 10
66
+ }) {
67
+ const [, forceUpdate] = (0, import_react.useState)(null);
68
+ const isMounted = (0, import_react.useRef)(true);
69
+ const hasUpdated = (0, import_react.useRef)(false);
70
+ const rafHandle = (0, import_react.useRef)(null);
71
+ const data = (0, import_react.useRef)([]);
72
+ const rangeRef = (0, import_react.useRef)({ from: 0, to: 10 });
73
+ const dataWindow = (0, import_react.useMemo)(
74
+ () => new MovingWindow((0, import_vuu_utils.getFullRange)(rangeRef.current, renderBufferSize)),
75
+ [renderBufferSize]
76
+ );
77
+ const setData = (0, import_react.useCallback)(
78
+ (updates) => {
79
+ for (const row of updates) {
80
+ dataWindow.add(row);
81
+ }
82
+ data.current = dataWindow.data.slice();
83
+ hasUpdated.current = true;
84
+ },
85
+ [dataWindow]
86
+ );
87
+ const datasourceMessageHandler = (0, import_react.useCallback)(
88
+ (message) => {
89
+ if (message.type === "viewport-update") {
90
+ if (message.size !== void 0) {
91
+ dataWindow.setRowCount(message.size);
92
+ }
93
+ if (message.rows) {
94
+ setData(message.rows);
95
+ forceUpdate({});
96
+ } else if (message.size !== void 0) {
97
+ data.current = dataWindow.data.slice();
98
+ hasUpdated.current = true;
99
+ }
100
+ }
101
+ },
102
+ [dataWindow, setData]
103
+ );
104
+ (0, import_react.useEffect)(
105
+ () => () => {
106
+ if (rafHandle.current) {
107
+ cancelAnimationFrame(rafHandle.current);
108
+ rafHandle.current = null;
109
+ }
110
+ isMounted.current = false;
111
+ },
112
+ []
113
+ );
114
+ const setRange = (0, import_react.useCallback)(
115
+ (range) => {
116
+ rangeRef.current = range;
117
+ const fullRange = (0, import_vuu_utils.getFullRange)(rangeRef.current, renderBufferSize);
118
+ dataSource.range = fullRange;
119
+ dataWindow.setRange(fullRange.from, fullRange.to);
120
+ },
121
+ [dataSource, dataWindow, renderBufferSize]
122
+ );
123
+ (0, import_react.useMemo)(() => {
124
+ const { from, to } = rangeRef.current;
125
+ const fullRange = (0, import_vuu_utils.getFullRange)({ from, to }, renderBufferSize);
126
+ dataSource.range = fullRange;
127
+ dataWindow.setRange(fullRange.from, fullRange.to);
128
+ }, [dataSource, dataWindow, renderBufferSize]);
129
+ (0, import_react.useEffect)(() => {
130
+ const { from, to } = (0, import_vuu_utils.getFullRange)(rangeRef.current, renderBufferSize);
131
+ dataSource.subscribe(
132
+ {
133
+ range: { from, to }
134
+ },
135
+ datasourceMessageHandler
136
+ );
137
+ }, [dataSource, datasourceMessageHandler, renderBufferSize]);
138
+ (0, import_react.useEffect)(
139
+ () => () => {
140
+ dataSource.unsubscribe();
141
+ },
142
+ [dataSource]
143
+ );
144
+ return [
145
+ data.current,
146
+ dataWindow.rowCount,
147
+ (0, import_vuu_utils.getFullRange)(rangeRef.current, renderBufferSize),
148
+ setRange
149
+ ];
150
+ }
151
+ var MovingWindow = class {
152
+ constructor({ from, to }) {
153
+ this.rowCount = 0;
154
+ this.setRowCount = (rowCount) => {
155
+ if (rowCount < this.data.length) {
156
+ this.data.length = rowCount;
157
+ }
158
+ this.rowCount = rowCount;
159
+ };
160
+ this.range = new import_vuu_utils.WindowRange(from, to);
161
+ this.data = new Array(to - from);
162
+ }
163
+ add(data) {
164
+ const [index] = data;
165
+ if (this.isWithinRange(index)) {
166
+ const internalIndex = index - this.range.from;
167
+ this.data[internalIndex] = data;
168
+ if (this.data[internalIndex - 1]) {
169
+ if (this.data[internalIndex - 1][SELECTED] === 1 && data[SELECTED] === 0) {
170
+ data[SELECTED] = 2;
171
+ }
172
+ }
173
+ if (index === this.rowCount - 1) {
174
+ this.data.length = internalIndex + 1;
175
+ }
176
+ }
177
+ }
178
+ getAtIndex(index) {
179
+ return this.range.isWithin(index) && this.data[index - this.range.from] != null ? this.data[index - this.range.from] : void 0;
180
+ }
181
+ isWithinRange(index) {
182
+ return this.range.isWithin(index);
183
+ }
184
+ setRange(from, to) {
185
+ if (from !== this.range.from || to !== this.range.to) {
186
+ const [overlapFrom, overlapTo] = this.range.overlap(from, to);
187
+ const newData = new Array(to - from);
188
+ for (let i = overlapFrom; i < overlapTo; i++) {
189
+ const data = this.getAtIndex(i);
190
+ if (data) {
191
+ const index = i - from;
192
+ newData[index] = data;
193
+ }
194
+ }
195
+ this.data = newData;
196
+ this.range.from = from;
197
+ this.range.to = to;
198
+ }
199
+ }
200
+ };
201
+
202
+ // src/hooks/useServerConnectionStatus.ts
203
+ var import_react2 = require("react");
204
+ var import_vuu_data = require("@vuu-ui/vuu-data");
205
+ var useServerConnectionStatus = () => {
206
+ const [connectionStatus, setConnectionStatus] = (0, import_react2.useState)("disconnected");
207
+ const handleStatusChange = (0, import_react2.useCallback)(
208
+ ({ status }) => {
209
+ setConnectionStatus(status);
210
+ },
211
+ []
212
+ );
213
+ (0, import_react2.useEffect)(() => {
214
+ import_vuu_data.ConnectionManager.on("connection-status", handleStatusChange);
215
+ return () => {
216
+ import_vuu_data.ConnectionManager.removeListener("connection-status", handleStatusChange);
217
+ };
218
+ }, [handleStatusChange]);
219
+ return connectionStatus;
220
+ };
221
+
222
+ // src/hooks/useServerConnectionQuality.ts
223
+ var import_react3 = require("react");
224
+ var import_vuu_data2 = require("@vuu-ui/vuu-data");
225
+ var useServerConnectionQuality = () => {
226
+ const [messagesPerSecond, setMessagesPerSecond] = (0, import_react3.useState)(0);
227
+ const handleConnectivityMessage = (0, import_react3.useCallback)(({ messages }) => {
228
+ setMessagesPerSecond(messages.messagesLength);
229
+ }, []);
230
+ (0, import_react3.useEffect)(() => {
231
+ import_vuu_data2.ConnectionManager.on("connection-metrics", handleConnectivityMessage);
232
+ return () => {
233
+ import_vuu_data2.ConnectionManager.removeListener(
234
+ "connection-metrics",
235
+ handleConnectivityMessage
236
+ );
237
+ };
238
+ }, [handleConnectivityMessage]);
239
+ return messagesPerSecond;
240
+ };
241
+
242
+ // src/hooks/useTypeaheadSuggestions.ts
243
+ var import_react4 = require("react");
244
+ var import_vuu_data3 = require("@vuu-ui/vuu-data");
245
+ var TYPEAHEAD_MESSAGE_CONSTANTS = {
246
+ type: "RPC_CALL",
247
+ service: "TypeAheadRpcHandler"
248
+ };
249
+ var getTypeaheadParams = (table, column, text = "", selectedValues = []) => {
250
+ if (text !== "" && !selectedValues.includes(text.toLowerCase())) {
251
+ return [table, column, text];
252
+ }
253
+ return [table, column];
254
+ };
255
+ var useTypeaheadSuggestions = () => {
256
+ const getTypeaheadSuggestions = (0, import_react4.useCallback)(
257
+ async (params) => {
258
+ const rpcMessage = params.length === 2 ? {
259
+ method: "getUniqueFieldValues",
260
+ params,
261
+ ...TYPEAHEAD_MESSAGE_CONSTANTS
262
+ } : {
263
+ method: "getUniqueFieldValuesStartingWith",
264
+ params,
265
+ ...TYPEAHEAD_MESSAGE_CONSTANTS
266
+ };
267
+ const suggestions = await (0, import_vuu_data3.makeRpcCall)(rpcMessage);
268
+ return suggestions;
269
+ },
270
+ []
271
+ );
272
+ return getTypeaheadSuggestions;
273
+ };
274
+
275
+ // ../../node_modules/@lezer/common/dist/index.js
276
+ var DefaultBufferLength = 1024;
277
+ var nextPropID = 0;
278
+ var Range = class {
279
+ constructor(from, to) {
280
+ this.from = from;
281
+ this.to = to;
282
+ }
283
+ };
284
+ var NodeProp = class {
285
+ /// Create a new node prop type.
286
+ constructor(config = {}) {
287
+ this.id = nextPropID++;
288
+ this.perNode = !!config.perNode;
289
+ this.deserialize = config.deserialize || (() => {
290
+ throw new Error("This node type doesn't define a deserialize function");
291
+ });
292
+ }
293
+ /// This is meant to be used with
294
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
295
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
296
+ /// prop values for each node type in the set. Takes a [match
297
+ /// object](#common.NodeType^match) or function that returns undefined
298
+ /// if the node type doesn't get this prop, and the prop's value if
299
+ /// it does.
300
+ add(match) {
301
+ if (this.perNode)
302
+ throw new RangeError("Can't add per-node props to node types");
303
+ if (typeof match != "function")
304
+ match = NodeType.match(match);
305
+ return (type) => {
306
+ let result = match(type);
307
+ return result === void 0 ? null : [this, result];
308
+ };
309
+ }
310
+ };
311
+ NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
312
+ NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
313
+ NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
314
+ NodeProp.contextHash = new NodeProp({ perNode: true });
315
+ NodeProp.lookAhead = new NodeProp({ perNode: true });
316
+ NodeProp.mounted = new NodeProp({ perNode: true });
317
+ var noProps = /* @__PURE__ */ Object.create(null);
318
+ var NodeType = class {
319
+ /// @internal
320
+ constructor(name, props, id, flags = 0) {
321
+ this.name = name;
322
+ this.props = props;
323
+ this.id = id;
324
+ this.flags = flags;
325
+ }
326
+ /// Define a node type.
327
+ static define(spec) {
328
+ let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
329
+ let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
330
+ let type = new NodeType(spec.name || "", props, spec.id, flags);
331
+ if (spec.props)
332
+ for (let src of spec.props) {
333
+ if (!Array.isArray(src))
334
+ src = src(type);
335
+ if (src) {
336
+ if (src[0].perNode)
337
+ throw new RangeError("Can't store a per-node prop on a node type");
338
+ props[src[0].id] = src[1];
339
+ }
340
+ }
341
+ return type;
342
+ }
343
+ /// Retrieves a node prop for this type. Will return `undefined` if
344
+ /// the prop isn't present on this node.
345
+ prop(prop) {
346
+ return this.props[prop.id];
347
+ }
348
+ /// True when this is the top node of a grammar.
349
+ get isTop() {
350
+ return (this.flags & 1) > 0;
351
+ }
352
+ /// True when this node is produced by a skip rule.
353
+ get isSkipped() {
354
+ return (this.flags & 2) > 0;
355
+ }
356
+ /// Indicates whether this is an error node.
357
+ get isError() {
358
+ return (this.flags & 4) > 0;
359
+ }
360
+ /// When true, this node type doesn't correspond to a user-declared
361
+ /// named node, for example because it is used to cache repetition.
362
+ get isAnonymous() {
363
+ return (this.flags & 8) > 0;
364
+ }
365
+ /// Returns true when this node's name or one of its
366
+ /// [groups](#common.NodeProp^group) matches the given string.
367
+ is(name) {
368
+ if (typeof name == "string") {
369
+ if (this.name == name)
370
+ return true;
371
+ let group = this.prop(NodeProp.group);
372
+ return group ? group.indexOf(name) > -1 : false;
373
+ }
374
+ return this.id == name;
375
+ }
376
+ /// Create a function from node types to arbitrary values by
377
+ /// specifying an object whose property names are node or
378
+ /// [group](#common.NodeProp^group) names. Often useful with
379
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
380
+ /// names, separated by spaces, in a single property name to map
381
+ /// multiple node names to a single value.
382
+ static match(map) {
383
+ let direct = /* @__PURE__ */ Object.create(null);
384
+ for (let prop in map)
385
+ for (let name of prop.split(" "))
386
+ direct[name] = map[prop];
387
+ return (node) => {
388
+ for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
389
+ let found = direct[i < 0 ? node.name : groups[i]];
390
+ if (found)
391
+ return found;
392
+ }
393
+ };
394
+ }
395
+ };
396
+ NodeType.none = new NodeType(
397
+ "",
398
+ /* @__PURE__ */ Object.create(null),
399
+ 0,
400
+ 8
401
+ /* NodeFlag.Anonymous */
402
+ );
403
+ var NodeSet = class {
404
+ /// Create a set with the given types. The `id` property of each
405
+ /// type should correspond to its position within the array.
406
+ constructor(types) {
407
+ this.types = types;
408
+ for (let i = 0; i < types.length; i++)
409
+ if (types[i].id != i)
410
+ throw new RangeError("Node type ids should correspond to array positions when creating a node set");
411
+ }
412
+ /// Create a copy of this set with some node properties added. The
413
+ /// arguments to this method can be created with
414
+ /// [`NodeProp.add`](#common.NodeProp.add).
415
+ extend(...props) {
416
+ let newTypes = [];
417
+ for (let type of this.types) {
418
+ let newProps = null;
419
+ for (let source of props) {
420
+ let add = source(type);
421
+ if (add) {
422
+ if (!newProps)
423
+ newProps = Object.assign({}, type.props);
424
+ newProps[add[0].id] = add[1];
425
+ }
426
+ }
427
+ newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
428
+ }
429
+ return new NodeSet(newTypes);
430
+ }
431
+ };
432
+ var CachedNode = /* @__PURE__ */ new WeakMap();
433
+ var CachedInnerNode = /* @__PURE__ */ new WeakMap();
434
+ var IterMode;
435
+ (function(IterMode2) {
436
+ IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
437
+ IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
438
+ IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
439
+ IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
440
+ })(IterMode || (IterMode = {}));
441
+ var Tree = class {
442
+ /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
443
+ constructor(type, children, positions, length, props) {
444
+ this.type = type;
445
+ this.children = children;
446
+ this.positions = positions;
447
+ this.length = length;
448
+ this.props = null;
449
+ if (props && props.length) {
450
+ this.props = /* @__PURE__ */ Object.create(null);
451
+ for (let [prop, value] of props)
452
+ this.props[typeof prop == "number" ? prop : prop.id] = value;
453
+ }
454
+ }
455
+ /// @internal
456
+ toString() {
457
+ let mounted = this.prop(NodeProp.mounted);
458
+ if (mounted && !mounted.overlay)
459
+ return mounted.tree.toString();
460
+ let children = "";
461
+ for (let ch of this.children) {
462
+ let str = ch.toString();
463
+ if (str) {
464
+ if (children)
465
+ children += ",";
466
+ children += str;
467
+ }
468
+ }
469
+ return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
470
+ }
471
+ /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
472
+ /// the tree. Mode can be used to [control](#common.IterMode) which
473
+ /// nodes the cursor visits.
474
+ cursor(mode = 0) {
475
+ return new TreeCursor(this.topNode, mode);
476
+ }
477
+ /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
478
+ /// at the given position and side (see
479
+ /// [`moveTo`](#common.TreeCursor.moveTo).
480
+ cursorAt(pos, side = 0, mode = 0) {
481
+ let scope = CachedNode.get(this) || this.topNode;
482
+ let cursor = new TreeCursor(scope);
483
+ cursor.moveTo(pos, side);
484
+ CachedNode.set(this, cursor._tree);
485
+ return cursor;
486
+ }
487
+ /// Get a [syntax node](#common.SyntaxNode) object for the top of the
488
+ /// tree.
489
+ get topNode() {
490
+ return new TreeNode(this, 0, 0, null);
491
+ }
492
+ /// Get the [syntax node](#common.SyntaxNode) at the given position.
493
+ /// If `side` is -1, this will move into nodes that end at the
494
+ /// position. If 1, it'll move into nodes that start at the
495
+ /// position. With 0, it'll only enter nodes that cover the position
496
+ /// from both sides.
497
+ ///
498
+ /// Note that this will not enter
499
+ /// [overlays](#common.MountedTree.overlay), and you often want
500
+ /// [`resolveInner`](#common.Tree.resolveInner) instead.
501
+ resolve(pos, side = 0) {
502
+ let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
503
+ CachedNode.set(this, node);
504
+ return node;
505
+ }
506
+ /// Like [`resolve`](#common.Tree.resolve), but will enter
507
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
508
+ /// pointing into the innermost overlaid tree at the given position
509
+ /// (with parent links going through all parent structure, including
510
+ /// the host trees).
511
+ resolveInner(pos, side = 0) {
512
+ let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
513
+ CachedInnerNode.set(this, node);
514
+ return node;
515
+ }
516
+ /// Iterate over the tree and its children, calling `enter` for any
517
+ /// node that touches the `from`/`to` region (if given) before
518
+ /// running over such a node's children, and `leave` (if given) when
519
+ /// leaving the node. When `enter` returns `false`, that node will
520
+ /// not have its children iterated over (or `leave` called).
521
+ iterate(spec) {
522
+ let { enter, leave, from = 0, to = this.length } = spec;
523
+ let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
524
+ for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
525
+ let entered = false;
526
+ if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
527
+ if (c.firstChild())
528
+ continue;
529
+ entered = true;
530
+ }
531
+ for (; ; ) {
532
+ if (entered && leave && (anon || !c.type.isAnonymous))
533
+ leave(c);
534
+ if (c.nextSibling())
535
+ break;
536
+ if (!c.parent())
537
+ return;
538
+ entered = true;
539
+ }
540
+ }
541
+ }
542
+ /// Get the value of the given [node prop](#common.NodeProp) for this
543
+ /// node. Works with both per-node and per-type props.
544
+ prop(prop) {
545
+ return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
546
+ }
547
+ /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
548
+ /// format that can be passed to the [`Tree`](#common.Tree)
549
+ /// constructor.
550
+ get propValues() {
551
+ let result = [];
552
+ if (this.props)
553
+ for (let id in this.props)
554
+ result.push([+id, this.props[id]]);
555
+ return result;
556
+ }
557
+ /// Balance the direct children of this tree, producing a copy of
558
+ /// which may have children grouped into subtrees with type
559
+ /// [`NodeType.none`](#common.NodeType^none).
560
+ balance(config = {}) {
561
+ 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)));
562
+ }
563
+ /// Build a tree from a postfix-ordered buffer of node information,
564
+ /// or a cursor over such a buffer.
565
+ static build(data) {
566
+ return buildTree(data);
567
+ }
568
+ };
569
+ Tree.empty = new Tree(NodeType.none, [], [], 0);
570
+ var FlatBufferCursor = class {
571
+ constructor(buffer, index) {
572
+ this.buffer = buffer;
573
+ this.index = index;
574
+ }
575
+ get id() {
576
+ return this.buffer[this.index - 4];
577
+ }
578
+ get start() {
579
+ return this.buffer[this.index - 3];
580
+ }
581
+ get end() {
582
+ return this.buffer[this.index - 2];
583
+ }
584
+ get size() {
585
+ return this.buffer[this.index - 1];
586
+ }
587
+ get pos() {
588
+ return this.index;
589
+ }
590
+ next() {
591
+ this.index -= 4;
592
+ }
593
+ fork() {
594
+ return new FlatBufferCursor(this.buffer, this.index);
595
+ }
596
+ };
597
+ var TreeBuffer = class {
598
+ /// Create a tree buffer.
599
+ constructor(buffer, length, set) {
600
+ this.buffer = buffer;
601
+ this.length = length;
602
+ this.set = set;
603
+ }
604
+ /// @internal
605
+ get type() {
606
+ return NodeType.none;
607
+ }
608
+ /// @internal
609
+ toString() {
610
+ let result = [];
611
+ for (let index = 0; index < this.buffer.length; ) {
612
+ result.push(this.childString(index));
613
+ index = this.buffer[index + 3];
614
+ }
615
+ return result.join(",");
616
+ }
617
+ /// @internal
618
+ childString(index) {
619
+ let id = this.buffer[index], endIndex = this.buffer[index + 3];
620
+ let type = this.set.types[id], result = type.name;
621
+ if (/\W/.test(result) && !type.isError)
622
+ result = JSON.stringify(result);
623
+ index += 4;
624
+ if (endIndex == index)
625
+ return result;
626
+ let children = [];
627
+ while (index < endIndex) {
628
+ children.push(this.childString(index));
629
+ index = this.buffer[index + 3];
630
+ }
631
+ return result + "(" + children.join(",") + ")";
632
+ }
633
+ /// @internal
634
+ findChild(startIndex, endIndex, dir, pos, side) {
635
+ let { buffer } = this, pick = -1;
636
+ for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
637
+ if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
638
+ pick = i;
639
+ if (dir > 0)
640
+ break;
641
+ }
642
+ }
643
+ return pick;
644
+ }
645
+ /// @internal
646
+ slice(startI, endI, from) {
647
+ let b = this.buffer;
648
+ let copy = new Uint16Array(endI - startI), len = 0;
649
+ for (let i = startI, j = 0; i < endI; ) {
650
+ copy[j++] = b[i++];
651
+ copy[j++] = b[i++] - from;
652
+ let to = copy[j++] = b[i++] - from;
653
+ copy[j++] = b[i++] - startI;
654
+ len = Math.max(len, to);
655
+ }
656
+ return new TreeBuffer(copy, len, this.set);
657
+ }
658
+ };
659
+ function checkSide(side, pos, from, to) {
660
+ switch (side) {
661
+ case -2:
662
+ return from < pos;
663
+ case -1:
664
+ return to >= pos && from < pos;
665
+ case 0:
666
+ return from < pos && to > pos;
667
+ case 1:
668
+ return from <= pos && to > pos;
669
+ case 2:
670
+ return to > pos;
671
+ case 4:
672
+ return true;
673
+ }
674
+ }
675
+ function enterUnfinishedNodesBefore(node, pos) {
676
+ let scan = node.childBefore(pos);
677
+ while (scan) {
678
+ let last = scan.lastChild;
679
+ if (!last || last.to != scan.to)
680
+ break;
681
+ if (last.type.isError && last.from == last.to) {
682
+ node = scan;
683
+ scan = last.prevSibling;
684
+ } else {
685
+ scan = last;
686
+ }
687
+ }
688
+ return node;
689
+ }
690
+ function resolveNode(node, pos, side, overlays) {
691
+ var _a;
692
+ while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
693
+ let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
694
+ if (!parent)
695
+ return node;
696
+ node = parent;
697
+ }
698
+ let mode = overlays ? 0 : IterMode.IgnoreOverlays;
699
+ if (overlays)
700
+ for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
701
+ if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
702
+ node = parent;
703
+ }
704
+ for (; ; ) {
705
+ let inner = node.enter(pos, side, mode);
706
+ if (!inner)
707
+ return node;
708
+ node = inner;
709
+ }
710
+ }
711
+ var TreeNode = class {
712
+ constructor(_tree, from, index, _parent) {
713
+ this._tree = _tree;
714
+ this.from = from;
715
+ this.index = index;
716
+ this._parent = _parent;
717
+ }
718
+ get type() {
719
+ return this._tree.type;
720
+ }
721
+ get name() {
722
+ return this._tree.type.name;
723
+ }
724
+ get to() {
725
+ return this.from + this._tree.length;
726
+ }
727
+ nextChild(i, dir, pos, side, mode = 0) {
728
+ for (let parent = this; ; ) {
729
+ for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
730
+ let next = children[i], start = positions[i] + parent.from;
731
+ if (!checkSide(side, pos, start, start + next.length))
732
+ continue;
733
+ if (next instanceof TreeBuffer) {
734
+ if (mode & IterMode.ExcludeBuffers)
735
+ continue;
736
+ let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
737
+ if (index > -1)
738
+ return new BufferNode(new BufferContext(parent, next, i, start), null, index);
739
+ } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
740
+ let mounted;
741
+ if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
742
+ return new TreeNode(mounted.tree, start, i, parent);
743
+ let inner = new TreeNode(next, start, i, parent);
744
+ return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
745
+ }
746
+ }
747
+ if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
748
+ return null;
749
+ if (parent.index >= 0)
750
+ i = parent.index + dir;
751
+ else
752
+ i = dir < 0 ? -1 : parent._parent._tree.children.length;
753
+ parent = parent._parent;
754
+ if (!parent)
755
+ return null;
756
+ }
757
+ }
758
+ get firstChild() {
759
+ return this.nextChild(
760
+ 0,
761
+ 1,
762
+ 0,
763
+ 4
764
+ /* Side.DontCare */
765
+ );
766
+ }
767
+ get lastChild() {
768
+ return this.nextChild(
769
+ this._tree.children.length - 1,
770
+ -1,
771
+ 0,
772
+ 4
773
+ /* Side.DontCare */
774
+ );
775
+ }
776
+ childAfter(pos) {
777
+ return this.nextChild(
778
+ 0,
779
+ 1,
780
+ pos,
781
+ 2
782
+ /* Side.After */
783
+ );
784
+ }
785
+ childBefore(pos) {
786
+ return this.nextChild(
787
+ this._tree.children.length - 1,
788
+ -1,
789
+ pos,
790
+ -2
791
+ /* Side.Before */
792
+ );
793
+ }
794
+ enter(pos, side, mode = 0) {
795
+ let mounted;
796
+ if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
797
+ let rPos = pos - this.from;
798
+ for (let { from, to } of mounted.overlay) {
799
+ if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
800
+ return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
801
+ }
802
+ }
803
+ return this.nextChild(0, 1, pos, side, mode);
804
+ }
805
+ nextSignificantParent() {
806
+ let val = this;
807
+ while (val.type.isAnonymous && val._parent)
808
+ val = val._parent;
809
+ return val;
810
+ }
811
+ get parent() {
812
+ return this._parent ? this._parent.nextSignificantParent() : null;
813
+ }
814
+ get nextSibling() {
815
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
816
+ this.index + 1,
817
+ 1,
818
+ 0,
819
+ 4
820
+ /* Side.DontCare */
821
+ ) : null;
822
+ }
823
+ get prevSibling() {
824
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
825
+ this.index - 1,
826
+ -1,
827
+ 0,
828
+ 4
829
+ /* Side.DontCare */
830
+ ) : null;
831
+ }
832
+ cursor(mode = 0) {
833
+ return new TreeCursor(this, mode);
834
+ }
835
+ get tree() {
836
+ return this._tree;
837
+ }
838
+ toTree() {
839
+ return this._tree;
840
+ }
841
+ resolve(pos, side = 0) {
842
+ return resolveNode(this, pos, side, false);
843
+ }
844
+ resolveInner(pos, side = 0) {
845
+ return resolveNode(this, pos, side, true);
846
+ }
847
+ enterUnfinishedNodesBefore(pos) {
848
+ return enterUnfinishedNodesBefore(this, pos);
849
+ }
850
+ getChild(type, before = null, after = null) {
851
+ let r = getChildren(this, type, before, after);
852
+ return r.length ? r[0] : null;
853
+ }
854
+ getChildren(type, before = null, after = null) {
855
+ return getChildren(this, type, before, after);
856
+ }
857
+ /// @internal
858
+ toString() {
859
+ return this._tree.toString();
860
+ }
861
+ get node() {
862
+ return this;
863
+ }
864
+ matchContext(context) {
865
+ return matchNodeContext(this, context);
866
+ }
867
+ };
868
+ function getChildren(node, type, before, after) {
869
+ let cur = node.cursor(), result = [];
870
+ if (!cur.firstChild())
871
+ return result;
872
+ if (before != null) {
873
+ while (!cur.type.is(before))
874
+ if (!cur.nextSibling())
875
+ return result;
876
+ }
877
+ for (; ; ) {
878
+ if (after != null && cur.type.is(after))
879
+ return result;
880
+ if (cur.type.is(type))
881
+ result.push(cur.node);
882
+ if (!cur.nextSibling())
883
+ return after == null ? result : [];
884
+ }
885
+ }
886
+ function matchNodeContext(node, context, i = context.length - 1) {
887
+ for (let p = node.parent; i >= 0; p = p.parent) {
888
+ if (!p)
889
+ return false;
890
+ if (!p.type.isAnonymous) {
891
+ if (context[i] && context[i] != p.name)
892
+ return false;
893
+ i--;
894
+ }
895
+ }
896
+ return true;
897
+ }
898
+ var BufferContext = class {
899
+ constructor(parent, buffer, index, start) {
900
+ this.parent = parent;
901
+ this.buffer = buffer;
902
+ this.index = index;
903
+ this.start = start;
904
+ }
905
+ };
906
+ var BufferNode = class {
907
+ get name() {
908
+ return this.type.name;
909
+ }
910
+ get from() {
911
+ return this.context.start + this.context.buffer.buffer[this.index + 1];
912
+ }
913
+ get to() {
914
+ return this.context.start + this.context.buffer.buffer[this.index + 2];
915
+ }
916
+ constructor(context, _parent, index) {
917
+ this.context = context;
918
+ this._parent = _parent;
919
+ this.index = index;
920
+ this.type = context.buffer.set.types[context.buffer.buffer[index]];
921
+ }
922
+ child(dir, pos, side) {
923
+ let { buffer } = this.context;
924
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
925
+ return index < 0 ? null : new BufferNode(this.context, this, index);
926
+ }
927
+ get firstChild() {
928
+ return this.child(
929
+ 1,
930
+ 0,
931
+ 4
932
+ /* Side.DontCare */
933
+ );
934
+ }
935
+ get lastChild() {
936
+ return this.child(
937
+ -1,
938
+ 0,
939
+ 4
940
+ /* Side.DontCare */
941
+ );
942
+ }
943
+ childAfter(pos) {
944
+ return this.child(
945
+ 1,
946
+ pos,
947
+ 2
948
+ /* Side.After */
949
+ );
950
+ }
951
+ childBefore(pos) {
952
+ return this.child(
953
+ -1,
954
+ pos,
955
+ -2
956
+ /* Side.Before */
957
+ );
958
+ }
959
+ enter(pos, side, mode = 0) {
960
+ if (mode & IterMode.ExcludeBuffers)
961
+ return null;
962
+ let { buffer } = this.context;
963
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
964
+ return index < 0 ? null : new BufferNode(this.context, this, index);
965
+ }
966
+ get parent() {
967
+ return this._parent || this.context.parent.nextSignificantParent();
968
+ }
969
+ externalSibling(dir) {
970
+ return this._parent ? null : this.context.parent.nextChild(
971
+ this.context.index + dir,
972
+ dir,
973
+ 0,
974
+ 4
975
+ /* Side.DontCare */
976
+ );
977
+ }
978
+ get nextSibling() {
979
+ let { buffer } = this.context;
980
+ let after = buffer.buffer[this.index + 3];
981
+ if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
982
+ return new BufferNode(this.context, this._parent, after);
983
+ return this.externalSibling(1);
984
+ }
985
+ get prevSibling() {
986
+ let { buffer } = this.context;
987
+ let parentStart = this._parent ? this._parent.index + 4 : 0;
988
+ if (this.index == parentStart)
989
+ return this.externalSibling(-1);
990
+ return new BufferNode(this.context, this._parent, buffer.findChild(
991
+ parentStart,
992
+ this.index,
993
+ -1,
994
+ 0,
995
+ 4
996
+ /* Side.DontCare */
997
+ ));
998
+ }
999
+ cursor(mode = 0) {
1000
+ return new TreeCursor(this, mode);
1001
+ }
1002
+ get tree() {
1003
+ return null;
1004
+ }
1005
+ toTree() {
1006
+ let children = [], positions = [];
1007
+ let { buffer } = this.context;
1008
+ let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
1009
+ if (endI > startI) {
1010
+ let from = buffer.buffer[this.index + 1];
1011
+ children.push(buffer.slice(startI, endI, from));
1012
+ positions.push(0);
1013
+ }
1014
+ return new Tree(this.type, children, positions, this.to - this.from);
1015
+ }
1016
+ resolve(pos, side = 0) {
1017
+ return resolveNode(this, pos, side, false);
1018
+ }
1019
+ resolveInner(pos, side = 0) {
1020
+ return resolveNode(this, pos, side, true);
1021
+ }
1022
+ enterUnfinishedNodesBefore(pos) {
1023
+ return enterUnfinishedNodesBefore(this, pos);
1024
+ }
1025
+ /// @internal
1026
+ toString() {
1027
+ return this.context.buffer.childString(this.index);
1028
+ }
1029
+ getChild(type, before = null, after = null) {
1030
+ let r = getChildren(this, type, before, after);
1031
+ return r.length ? r[0] : null;
1032
+ }
1033
+ getChildren(type, before = null, after = null) {
1034
+ return getChildren(this, type, before, after);
1035
+ }
1036
+ get node() {
1037
+ return this;
1038
+ }
1039
+ matchContext(context) {
1040
+ return matchNodeContext(this, context);
1041
+ }
1042
+ };
1043
+ var TreeCursor = class {
1044
+ /// Shorthand for `.type.name`.
1045
+ get name() {
1046
+ return this.type.name;
1047
+ }
1048
+ /// @internal
1049
+ constructor(node, mode = 0) {
1050
+ this.mode = mode;
1051
+ this.buffer = null;
1052
+ this.stack = [];
1053
+ this.index = 0;
1054
+ this.bufferNode = null;
1055
+ if (node instanceof TreeNode) {
1056
+ this.yieldNode(node);
1057
+ } else {
1058
+ this._tree = node.context.parent;
1059
+ this.buffer = node.context;
1060
+ for (let n = node._parent; n; n = n._parent)
1061
+ this.stack.unshift(n.index);
1062
+ this.bufferNode = node;
1063
+ this.yieldBuf(node.index);
1064
+ }
1065
+ }
1066
+ yieldNode(node) {
1067
+ if (!node)
1068
+ return false;
1069
+ this._tree = node;
1070
+ this.type = node.type;
1071
+ this.from = node.from;
1072
+ this.to = node.to;
1073
+ return true;
1074
+ }
1075
+ yieldBuf(index, type) {
1076
+ this.index = index;
1077
+ let { start, buffer } = this.buffer;
1078
+ this.type = type || buffer.set.types[buffer.buffer[index]];
1079
+ this.from = start + buffer.buffer[index + 1];
1080
+ this.to = start + buffer.buffer[index + 2];
1081
+ return true;
1082
+ }
1083
+ yield(node) {
1084
+ if (!node)
1085
+ return false;
1086
+ if (node instanceof TreeNode) {
1087
+ this.buffer = null;
1088
+ return this.yieldNode(node);
1089
+ }
1090
+ this.buffer = node.context;
1091
+ return this.yieldBuf(node.index, node.type);
1092
+ }
1093
+ /// @internal
1094
+ toString() {
1095
+ return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
1096
+ }
1097
+ /// @internal
1098
+ enterChild(dir, pos, side) {
1099
+ if (!this.buffer)
1100
+ return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
1101
+ let { buffer } = this.buffer;
1102
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
1103
+ if (index < 0)
1104
+ return false;
1105
+ this.stack.push(this.index);
1106
+ return this.yieldBuf(index);
1107
+ }
1108
+ /// Move the cursor to this node's first child. When this returns
1109
+ /// false, the node has no child, and the cursor has not been moved.
1110
+ firstChild() {
1111
+ return this.enterChild(
1112
+ 1,
1113
+ 0,
1114
+ 4
1115
+ /* Side.DontCare */
1116
+ );
1117
+ }
1118
+ /// Move the cursor to this node's last child.
1119
+ lastChild() {
1120
+ return this.enterChild(
1121
+ -1,
1122
+ 0,
1123
+ 4
1124
+ /* Side.DontCare */
1125
+ );
1126
+ }
1127
+ /// Move the cursor to the first child that ends after `pos`.
1128
+ childAfter(pos) {
1129
+ return this.enterChild(
1130
+ 1,
1131
+ pos,
1132
+ 2
1133
+ /* Side.After */
1134
+ );
1135
+ }
1136
+ /// Move to the last child that starts before `pos`.
1137
+ childBefore(pos) {
1138
+ return this.enterChild(
1139
+ -1,
1140
+ pos,
1141
+ -2
1142
+ /* Side.Before */
1143
+ );
1144
+ }
1145
+ /// Move the cursor to the child around `pos`. If side is -1 the
1146
+ /// child may end at that position, when 1 it may start there. This
1147
+ /// will also enter [overlaid](#common.MountedTree.overlay)
1148
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
1149
+ /// set to false.
1150
+ enter(pos, side, mode = this.mode) {
1151
+ if (!this.buffer)
1152
+ return this.yield(this._tree.enter(pos, side, mode));
1153
+ return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
1154
+ }
1155
+ /// Move to the node's parent node, if this isn't the top node.
1156
+ parent() {
1157
+ if (!this.buffer)
1158
+ return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
1159
+ if (this.stack.length)
1160
+ return this.yieldBuf(this.stack.pop());
1161
+ let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
1162
+ this.buffer = null;
1163
+ return this.yieldNode(parent);
1164
+ }
1165
+ /// @internal
1166
+ sibling(dir) {
1167
+ if (!this.buffer)
1168
+ 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));
1169
+ let { buffer } = this.buffer, d = this.stack.length - 1;
1170
+ if (dir < 0) {
1171
+ let parentStart = d < 0 ? 0 : this.stack[d] + 4;
1172
+ if (this.index != parentStart)
1173
+ return this.yieldBuf(buffer.findChild(
1174
+ parentStart,
1175
+ this.index,
1176
+ -1,
1177
+ 0,
1178
+ 4
1179
+ /* Side.DontCare */
1180
+ ));
1181
+ } else {
1182
+ let after = buffer.buffer[this.index + 3];
1183
+ if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
1184
+ return this.yieldBuf(after);
1185
+ }
1186
+ return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
1187
+ }
1188
+ /// Move to this node's next sibling, if any.
1189
+ nextSibling() {
1190
+ return this.sibling(1);
1191
+ }
1192
+ /// Move to this node's previous sibling, if any.
1193
+ prevSibling() {
1194
+ return this.sibling(-1);
1195
+ }
1196
+ atLastNode(dir) {
1197
+ let index, parent, { buffer } = this;
1198
+ if (buffer) {
1199
+ if (dir > 0) {
1200
+ if (this.index < buffer.buffer.buffer.length)
1201
+ return false;
1202
+ } else {
1203
+ for (let i = 0; i < this.index; i++)
1204
+ if (buffer.buffer.buffer[i + 3] < this.index)
1205
+ return false;
1206
+ }
1207
+ ({ index, parent } = buffer);
1208
+ } else {
1209
+ ({ index, _parent: parent } = this._tree);
1210
+ }
1211
+ for (; parent; { index, _parent: parent } = parent) {
1212
+ if (index > -1)
1213
+ for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
1214
+ let child = parent._tree.children[i];
1215
+ if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
1216
+ return false;
1217
+ }
1218
+ }
1219
+ return true;
1220
+ }
1221
+ move(dir, enter) {
1222
+ if (enter && this.enterChild(
1223
+ dir,
1224
+ 0,
1225
+ 4
1226
+ /* Side.DontCare */
1227
+ ))
1228
+ return true;
1229
+ for (; ; ) {
1230
+ if (this.sibling(dir))
1231
+ return true;
1232
+ if (this.atLastNode(dir) || !this.parent())
1233
+ return false;
1234
+ }
1235
+ }
1236
+ /// Move to the next node in a
1237
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
1238
+ /// traversal, going from a node to its first child or, if the
1239
+ /// current node is empty or `enter` is false, its next sibling or
1240
+ /// the next sibling of the first parent node that has one.
1241
+ next(enter = true) {
1242
+ return this.move(1, enter);
1243
+ }
1244
+ /// Move to the next node in a last-to-first pre-order traveral. A
1245
+ /// node is followed by its last child or, if it has none, its
1246
+ /// previous sibling or the previous sibling of the first parent
1247
+ /// node that has one.
1248
+ prev(enter = true) {
1249
+ return this.move(-1, enter);
1250
+ }
1251
+ /// Move the cursor to the innermost node that covers `pos`. If
1252
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
1253
+ /// it will enter nodes that start at `pos`.
1254
+ moveTo(pos, side = 0) {
1255
+ while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
1256
+ if (!this.parent())
1257
+ break;
1258
+ while (this.enterChild(1, pos, side)) {
1259
+ }
1260
+ return this;
1261
+ }
1262
+ /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
1263
+ /// position.
1264
+ get node() {
1265
+ if (!this.buffer)
1266
+ return this._tree;
1267
+ let cache = this.bufferNode, result = null, depth = 0;
1268
+ if (cache && cache.context == this.buffer) {
1269
+ scan:
1270
+ for (let index = this.index, d = this.stack.length; d >= 0; ) {
1271
+ for (let c = cache; c; c = c._parent)
1272
+ if (c.index == index) {
1273
+ if (index == this.index)
1274
+ return c;
1275
+ result = c;
1276
+ depth = d + 1;
1277
+ break scan;
1278
+ }
1279
+ index = this.stack[--d];
1280
+ }
1281
+ }
1282
+ for (let i = depth; i < this.stack.length; i++)
1283
+ result = new BufferNode(this.buffer, result, this.stack[i]);
1284
+ return this.bufferNode = new BufferNode(this.buffer, result, this.index);
1285
+ }
1286
+ /// Get the [tree](#common.Tree) that represents the current node, if
1287
+ /// any. Will return null when the node is in a [tree
1288
+ /// buffer](#common.TreeBuffer).
1289
+ get tree() {
1290
+ return this.buffer ? null : this._tree._tree;
1291
+ }
1292
+ /// Iterate over the current node and all its descendants, calling
1293
+ /// `enter` when entering a node and `leave`, if given, when leaving
1294
+ /// one. When `enter` returns `false`, any children of that node are
1295
+ /// skipped, and `leave` isn't called for it.
1296
+ iterate(enter, leave) {
1297
+ for (let depth = 0; ; ) {
1298
+ let mustLeave = false;
1299
+ if (this.type.isAnonymous || enter(this) !== false) {
1300
+ if (this.firstChild()) {
1301
+ depth++;
1302
+ continue;
1303
+ }
1304
+ if (!this.type.isAnonymous)
1305
+ mustLeave = true;
1306
+ }
1307
+ for (; ; ) {
1308
+ if (mustLeave && leave)
1309
+ leave(this);
1310
+ mustLeave = this.type.isAnonymous;
1311
+ if (this.nextSibling())
1312
+ break;
1313
+ if (!depth)
1314
+ return;
1315
+ this.parent();
1316
+ depth--;
1317
+ mustLeave = true;
1318
+ }
1319
+ }
1320
+ }
1321
+ /// Test whether the current node matches a given context—a sequence
1322
+ /// of direct parent node names. Empty strings in the context array
1323
+ /// are treated as wildcards.
1324
+ matchContext(context) {
1325
+ if (!this.buffer)
1326
+ return matchNodeContext(this.node, context);
1327
+ let { buffer } = this.buffer, { types } = buffer.set;
1328
+ for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
1329
+ if (d < 0)
1330
+ return matchNodeContext(this.node, context, i);
1331
+ let type = types[buffer.buffer[this.stack[d]]];
1332
+ if (!type.isAnonymous) {
1333
+ if (context[i] && context[i] != type.name)
1334
+ return false;
1335
+ i--;
1336
+ }
1337
+ }
1338
+ return true;
1339
+ }
1340
+ };
1341
+ function hasChild(tree) {
1342
+ return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1343
+ }
1344
+ function buildTree(data) {
1345
+ var _a;
1346
+ let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1347
+ let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1348
+ let types = nodeSet.types;
1349
+ let contextHash = 0, lookAhead = 0;
1350
+ function takeNode(parentStart, minPos, children2, positions2, inRepeat) {
1351
+ let { id, start, end, size } = cursor;
1352
+ let lookAheadAtStart = lookAhead;
1353
+ while (size < 0) {
1354
+ cursor.next();
1355
+ if (size == -1) {
1356
+ let node2 = reused[id];
1357
+ children2.push(node2);
1358
+ positions2.push(start - parentStart);
1359
+ return;
1360
+ } else if (size == -3) {
1361
+ contextHash = id;
1362
+ return;
1363
+ } else if (size == -4) {
1364
+ lookAhead = id;
1365
+ return;
1366
+ } else {
1367
+ throw new RangeError(`Unrecognized record size: ${size}`);
1368
+ }
1369
+ }
1370
+ let type = types[id], node, buffer2;
1371
+ let startPos = start - parentStart;
1372
+ if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
1373
+ let data2 = new Uint16Array(buffer2.size - buffer2.skip);
1374
+ let endPos = cursor.pos - buffer2.size, index = data2.length;
1375
+ while (cursor.pos > endPos)
1376
+ index = copyToBuffer(buffer2.start, data2, index);
1377
+ node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
1378
+ startPos = buffer2.start - parentStart;
1379
+ } else {
1380
+ let endPos = cursor.pos - size;
1381
+ cursor.next();
1382
+ let localChildren = [], localPositions = [];
1383
+ let localInRepeat = id >= minRepeatType ? id : -1;
1384
+ let lastGroup = 0, lastEnd = end;
1385
+ while (cursor.pos > endPos) {
1386
+ if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1387
+ if (cursor.end <= lastEnd - maxBufferLength) {
1388
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
1389
+ lastGroup = localChildren.length;
1390
+ lastEnd = cursor.end;
1391
+ }
1392
+ cursor.next();
1393
+ } else {
1394
+ takeNode(start, endPos, localChildren, localPositions, localInRepeat);
1395
+ }
1396
+ }
1397
+ if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1398
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
1399
+ localChildren.reverse();
1400
+ localPositions.reverse();
1401
+ if (localInRepeat > -1 && lastGroup > 0) {
1402
+ let make = makeBalanced(type);
1403
+ node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1404
+ } else {
1405
+ node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
1406
+ }
1407
+ }
1408
+ children2.push(node);
1409
+ positions2.push(startPos);
1410
+ }
1411
+ function makeBalanced(type) {
1412
+ return (children2, positions2, length2) => {
1413
+ let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp;
1414
+ if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) {
1415
+ if (!lastI && last.type == type && last.length == length2)
1416
+ return last;
1417
+ if (lookAheadProp = last.prop(NodeProp.lookAhead))
1418
+ lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
1419
+ }
1420
+ return makeTree(type, children2, positions2, length2, lookAhead2);
1421
+ };
1422
+ }
1423
+ function makeRepeatLeaf(children2, positions2, base, i, from, to, type, lookAhead2) {
1424
+ let localChildren = [], localPositions = [];
1425
+ while (children2.length > i) {
1426
+ localChildren.push(children2.pop());
1427
+ localPositions.push(positions2.pop() + base - from);
1428
+ }
1429
+ children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to));
1430
+ positions2.push(from - base);
1431
+ }
1432
+ function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) {
1433
+ if (contextHash) {
1434
+ let pair2 = [NodeProp.contextHash, contextHash];
1435
+ props = props ? [pair2].concat(props) : [pair2];
1436
+ }
1437
+ if (lookAhead2 > 25) {
1438
+ let pair2 = [NodeProp.lookAhead, lookAhead2];
1439
+ props = props ? [pair2].concat(props) : [pair2];
1440
+ }
1441
+ return new Tree(type, children2, positions2, length2, props);
1442
+ }
1443
+ function findBufferSize(maxSize, inRepeat) {
1444
+ let fork = cursor.fork();
1445
+ let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1446
+ let result = { size: 0, start: 0, skip: 0 };
1447
+ scan:
1448
+ for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
1449
+ let nodeSize2 = fork.size;
1450
+ if (fork.id == inRepeat && nodeSize2 >= 0) {
1451
+ result.size = size;
1452
+ result.start = start;
1453
+ result.skip = skip;
1454
+ skip += 4;
1455
+ size += 4;
1456
+ fork.next();
1457
+ continue;
1458
+ }
1459
+ let startPos = fork.pos - nodeSize2;
1460
+ if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
1461
+ break;
1462
+ let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1463
+ let nodeStart = fork.start;
1464
+ fork.next();
1465
+ while (fork.pos > startPos) {
1466
+ if (fork.size < 0) {
1467
+ if (fork.size == -3)
1468
+ localSkipped += 4;
1469
+ else
1470
+ break scan;
1471
+ } else if (fork.id >= minRepeatType) {
1472
+ localSkipped += 4;
1473
+ }
1474
+ fork.next();
1475
+ }
1476
+ start = nodeStart;
1477
+ size += nodeSize2;
1478
+ skip += localSkipped;
1479
+ }
1480
+ if (inRepeat < 0 || size == maxSize) {
1481
+ result.size = size;
1482
+ result.start = start;
1483
+ result.skip = skip;
1484
+ }
1485
+ return result.size > 4 ? result : void 0;
1486
+ }
1487
+ function copyToBuffer(bufferStart, buffer2, index) {
1488
+ let { id, start, end, size } = cursor;
1489
+ cursor.next();
1490
+ if (size >= 0 && id < minRepeatType) {
1491
+ let startIndex = index;
1492
+ if (size > 4) {
1493
+ let endPos = cursor.pos - (size - 4);
1494
+ while (cursor.pos > endPos)
1495
+ index = copyToBuffer(bufferStart, buffer2, index);
1496
+ }
1497
+ buffer2[--index] = startIndex;
1498
+ buffer2[--index] = end - bufferStart;
1499
+ buffer2[--index] = start - bufferStart;
1500
+ buffer2[--index] = id;
1501
+ } else if (size == -3) {
1502
+ contextHash = id;
1503
+ } else if (size == -4) {
1504
+ lookAhead = id;
1505
+ }
1506
+ return index;
1507
+ }
1508
+ let children = [], positions = [];
1509
+ while (cursor.pos > 0)
1510
+ takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1511
+ let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
1512
+ return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1513
+ }
1514
+ var nodeSizeCache = /* @__PURE__ */ new WeakMap();
1515
+ function nodeSize(balanceType, node) {
1516
+ if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1517
+ return 1;
1518
+ let size = nodeSizeCache.get(node);
1519
+ if (size == null) {
1520
+ size = 1;
1521
+ for (let child of node.children) {
1522
+ if (child.type != balanceType || !(child instanceof Tree)) {
1523
+ size = 1;
1524
+ break;
1525
+ }
1526
+ size += nodeSize(balanceType, child);
1527
+ }
1528
+ nodeSizeCache.set(node, size);
1529
+ }
1530
+ return size;
1531
+ }
1532
+ function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
1533
+ let total = 0;
1534
+ for (let i = from; i < to; i++)
1535
+ total += nodeSize(balanceType, children[i]);
1536
+ let maxChild = Math.ceil(
1537
+ total * 1.5 / 8
1538
+ /* Balance.BranchFactor */
1539
+ );
1540
+ let localChildren = [], localPositions = [];
1541
+ function divide(children2, positions2, from2, to2, offset) {
1542
+ for (let i = from2; i < to2; ) {
1543
+ let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children2[i]);
1544
+ i++;
1545
+ for (; i < to2; i++) {
1546
+ let nextSize = nodeSize(balanceType, children2[i]);
1547
+ if (groupSize + nextSize >= maxChild)
1548
+ break;
1549
+ groupSize += nextSize;
1550
+ }
1551
+ if (i == groupFrom + 1) {
1552
+ if (groupSize > maxChild) {
1553
+ let only = children2[groupFrom];
1554
+ divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
1555
+ continue;
1556
+ }
1557
+ localChildren.push(children2[groupFrom]);
1558
+ } else {
1559
+ let length2 = positions2[i - 1] + children2[i - 1].length - groupStart;
1560
+ localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i, groupStart, length2, null, mkTree));
1561
+ }
1562
+ localPositions.push(groupStart + offset - start);
1563
+ }
1564
+ }
1565
+ divide(children, positions, from, to, 0);
1566
+ return (mkTop || mkTree)(localChildren, localPositions, length);
1567
+ }
1568
+ var Parser = class {
1569
+ /// Start a parse, returning a [partial parse](#common.PartialParse)
1570
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
1571
+ /// make the parse incremental.
1572
+ ///
1573
+ /// By default, the entire input is parsed. You can pass `ranges`,
1574
+ /// which should be a sorted array of non-empty, non-overlapping
1575
+ /// ranges, to parse only those ranges. The tree returned in that
1576
+ /// case will start at `ranges[0].from`.
1577
+ startParse(input, fragments, ranges) {
1578
+ if (typeof input == "string")
1579
+ input = new StringInput(input);
1580
+ ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map((r) => new Range(r.from, r.to)) : [new Range(0, 0)];
1581
+ return this.createParse(input, fragments || [], ranges);
1582
+ }
1583
+ /// Run a full parse, returning the resulting tree.
1584
+ parse(input, fragments, ranges) {
1585
+ let parse = this.startParse(input, fragments, ranges);
1586
+ for (; ; ) {
1587
+ let done = parse.advance();
1588
+ if (done)
1589
+ return done;
1590
+ }
1591
+ }
1592
+ };
1593
+ var StringInput = class {
1594
+ constructor(string) {
1595
+ this.string = string;
1596
+ }
1597
+ get length() {
1598
+ return this.string.length;
1599
+ }
1600
+ chunk(from) {
1601
+ return this.string.slice(from);
1602
+ }
1603
+ get lineChunks() {
1604
+ return false;
1605
+ }
1606
+ read(from, to) {
1607
+ return this.string.slice(from, to);
1608
+ }
1609
+ };
1610
+ var stoppedInner = new NodeProp({ perNode: true });
1611
+
1612
+ // ../../node_modules/@lezer/lr/dist/index.js
1613
+ var Stack = class {
1614
+ /// @internal
1615
+ constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) {
1616
+ this.p = p;
1617
+ this.stack = stack;
1618
+ this.state = state;
1619
+ this.reducePos = reducePos;
1620
+ this.pos = pos;
1621
+ this.score = score;
1622
+ this.buffer = buffer;
1623
+ this.bufferBase = bufferBase;
1624
+ this.curContext = curContext;
1625
+ this.lookAhead = lookAhead;
1626
+ this.parent = parent;
1627
+ }
1628
+ /// @internal
1629
+ toString() {
1630
+ return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
1631
+ }
1632
+ // Start an empty stack
1633
+ /// @internal
1634
+ static start(p, state, pos = 0) {
1635
+ let cx = p.parser.context;
1636
+ return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
1637
+ }
1638
+ /// The stack's current [context](#lr.ContextTracker) value, if
1639
+ /// any. Its type will depend on the context tracker's type
1640
+ /// parameter, or it will be `null` if there is no context
1641
+ /// tracker.
1642
+ get context() {
1643
+ return this.curContext ? this.curContext.context : null;
1644
+ }
1645
+ // Push a state onto the stack, tracking its start position as well
1646
+ // as the buffer base at that point.
1647
+ /// @internal
1648
+ pushState(state, start) {
1649
+ this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
1650
+ this.state = state;
1651
+ }
1652
+ // Apply a reduce action
1653
+ /// @internal
1654
+ reduce(action) {
1655
+ var _a;
1656
+ let depth = action >> 19, type = action & 65535;
1657
+ let { parser: parser2 } = this.p;
1658
+ let dPrec = parser2.dynamicPrecedence(type);
1659
+ if (dPrec)
1660
+ this.score += dPrec;
1661
+ if (depth == 0) {
1662
+ this.pushState(parser2.getGoto(this.state, type, true), this.reducePos);
1663
+ if (type < parser2.minRepeatTerm)
1664
+ this.storeNode(type, this.reducePos, this.reducePos, 4, true);
1665
+ this.reduceContext(type, this.reducePos);
1666
+ return;
1667
+ }
1668
+ let base = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0);
1669
+ let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
1670
+ if (size >= 2e3 && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
1671
+ if (start == this.p.lastBigReductionStart) {
1672
+ this.p.bigReductionCount++;
1673
+ this.p.lastBigReductionSize = size;
1674
+ } else if (this.p.lastBigReductionSize < size) {
1675
+ this.p.bigReductionCount = 1;
1676
+ this.p.lastBigReductionStart = start;
1677
+ this.p.lastBigReductionSize = size;
1678
+ }
1679
+ }
1680
+ let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
1681
+ if (type < parser2.minRepeatTerm || action & 131072) {
1682
+ let pos = parser2.stateFlag(
1683
+ this.state,
1684
+ 1
1685
+ /* StateFlag.Skipped */
1686
+ ) ? this.pos : this.reducePos;
1687
+ this.storeNode(type, start, pos, count + 4, true);
1688
+ }
1689
+ if (action & 262144) {
1690
+ this.state = this.stack[base];
1691
+ } else {
1692
+ let baseStateID = this.stack[base - 3];
1693
+ this.state = parser2.getGoto(baseStateID, type, true);
1694
+ }
1695
+ while (this.stack.length > base)
1696
+ this.stack.pop();
1697
+ this.reduceContext(type, start);
1698
+ }
1699
+ // Shift a value into the buffer
1700
+ /// @internal
1701
+ storeNode(term, start, end, size = 4, isReduce = false) {
1702
+ if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
1703
+ let cur = this, top = this.buffer.length;
1704
+ if (top == 0 && cur.parent) {
1705
+ top = cur.bufferBase - cur.parent.bufferBase;
1706
+ cur = cur.parent;
1707
+ }
1708
+ if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) {
1709
+ if (start == end)
1710
+ return;
1711
+ if (cur.buffer[top - 2] >= start) {
1712
+ cur.buffer[top - 2] = end;
1713
+ return;
1714
+ }
1715
+ }
1716
+ }
1717
+ if (!isReduce || this.pos == end) {
1718
+ this.buffer.push(term, start, end, size);
1719
+ } else {
1720
+ let index = this.buffer.length;
1721
+ if (index > 0 && this.buffer[index - 4] != 0)
1722
+ while (index > 0 && this.buffer[index - 2] > end) {
1723
+ this.buffer[index] = this.buffer[index - 4];
1724
+ this.buffer[index + 1] = this.buffer[index - 3];
1725
+ this.buffer[index + 2] = this.buffer[index - 2];
1726
+ this.buffer[index + 3] = this.buffer[index - 1];
1727
+ index -= 4;
1728
+ if (size > 4)
1729
+ size -= 4;
1730
+ }
1731
+ this.buffer[index] = term;
1732
+ this.buffer[index + 1] = start;
1733
+ this.buffer[index + 2] = end;
1734
+ this.buffer[index + 3] = size;
1735
+ }
1736
+ }
1737
+ // Apply a shift action
1738
+ /// @internal
1739
+ shift(action, next, nextEnd) {
1740
+ let start = this.pos;
1741
+ if (action & 131072) {
1742
+ this.pushState(action & 65535, this.pos);
1743
+ } else if ((action & 262144) == 0) {
1744
+ let nextState = action, { parser: parser2 } = this.p;
1745
+ if (nextEnd > this.pos || next <= parser2.maxNode) {
1746
+ this.pos = nextEnd;
1747
+ if (!parser2.stateFlag(
1748
+ nextState,
1749
+ 1
1750
+ /* StateFlag.Skipped */
1751
+ ))
1752
+ this.reducePos = nextEnd;
1753
+ }
1754
+ this.pushState(nextState, start);
1755
+ this.shiftContext(next, start);
1756
+ if (next <= parser2.maxNode)
1757
+ this.buffer.push(next, start, nextEnd, 4);
1758
+ } else {
1759
+ this.pos = nextEnd;
1760
+ this.shiftContext(next, start);
1761
+ if (next <= this.p.parser.maxNode)
1762
+ this.buffer.push(next, start, nextEnd, 4);
1763
+ }
1764
+ }
1765
+ // Apply an action
1766
+ /// @internal
1767
+ apply(action, next, nextEnd) {
1768
+ if (action & 65536)
1769
+ this.reduce(action);
1770
+ else
1771
+ this.shift(action, next, nextEnd);
1772
+ }
1773
+ // Add a prebuilt (reused) node into the buffer.
1774
+ /// @internal
1775
+ useNode(value, next) {
1776
+ let index = this.p.reused.length - 1;
1777
+ if (index < 0 || this.p.reused[index] != value) {
1778
+ this.p.reused.push(value);
1779
+ index++;
1780
+ }
1781
+ let start = this.pos;
1782
+ this.reducePos = this.pos = start + value.length;
1783
+ this.pushState(next, start);
1784
+ this.buffer.push(
1785
+ index,
1786
+ start,
1787
+ this.reducePos,
1788
+ -1
1789
+ /* size == -1 means this is a reused value */
1790
+ );
1791
+ if (this.curContext)
1792
+ this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
1793
+ }
1794
+ // Split the stack. Due to the buffer sharing and the fact
1795
+ // that `this.stack` tends to stay quite shallow, this isn't very
1796
+ // expensive.
1797
+ /// @internal
1798
+ split() {
1799
+ let parent = this;
1800
+ let off = parent.buffer.length;
1801
+ while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
1802
+ off -= 4;
1803
+ let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
1804
+ while (parent && base == parent.bufferBase)
1805
+ parent = parent.parent;
1806
+ return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
1807
+ }
1808
+ // Try to recover from an error by 'deleting' (ignoring) one token.
1809
+ /// @internal
1810
+ recoverByDelete(next, nextEnd) {
1811
+ let isNode = next <= this.p.parser.maxNode;
1812
+ if (isNode)
1813
+ this.storeNode(next, this.pos, nextEnd, 4);
1814
+ this.storeNode(0, this.pos, nextEnd, isNode ? 8 : 4);
1815
+ this.pos = this.reducePos = nextEnd;
1816
+ this.score -= 190;
1817
+ }
1818
+ /// Check if the given term would be able to be shifted (optionally
1819
+ /// after some reductions) on this stack. This can be useful for
1820
+ /// external tokenizers that want to make sure they only provide a
1821
+ /// given token when it applies.
1822
+ canShift(term) {
1823
+ for (let sim = new SimulatedStack(this); ; ) {
1824
+ let action = this.p.parser.stateSlot(
1825
+ sim.state,
1826
+ 4
1827
+ /* ParseState.DefaultReduce */
1828
+ ) || this.p.parser.hasAction(sim.state, term);
1829
+ if (action == 0)
1830
+ return false;
1831
+ if ((action & 65536) == 0)
1832
+ return true;
1833
+ sim.reduce(action);
1834
+ }
1835
+ }
1836
+ // Apply up to Recover.MaxNext recovery actions that conceptually
1837
+ // inserts some missing token or rule.
1838
+ /// @internal
1839
+ recoverByInsert(next) {
1840
+ if (this.stack.length >= 300)
1841
+ return [];
1842
+ let nextStates = this.p.parser.nextStates(this.state);
1843
+ if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
1844
+ let best = [];
1845
+ for (let i = 0, s; i < nextStates.length; i += 2) {
1846
+ if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
1847
+ best.push(nextStates[i], s);
1848
+ }
1849
+ if (this.stack.length < 120)
1850
+ for (let i = 0; best.length < 4 << 1 && i < nextStates.length; i += 2) {
1851
+ let s = nextStates[i + 1];
1852
+ if (!best.some((v, i2) => i2 & 1 && v == s))
1853
+ best.push(nextStates[i], s);
1854
+ }
1855
+ nextStates = best;
1856
+ }
1857
+ let result = [];
1858
+ for (let i = 0; i < nextStates.length && result.length < 4; i += 2) {
1859
+ let s = nextStates[i + 1];
1860
+ if (s == this.state)
1861
+ continue;
1862
+ let stack = this.split();
1863
+ stack.pushState(s, this.pos);
1864
+ stack.storeNode(0, stack.pos, stack.pos, 4, true);
1865
+ stack.shiftContext(nextStates[i], this.pos);
1866
+ stack.score -= 200;
1867
+ result.push(stack);
1868
+ }
1869
+ return result;
1870
+ }
1871
+ // Force a reduce, if possible. Return false if that can't
1872
+ // be done.
1873
+ /// @internal
1874
+ forceReduce() {
1875
+ let reduce = this.p.parser.stateSlot(
1876
+ this.state,
1877
+ 5
1878
+ /* ParseState.ForcedReduce */
1879
+ );
1880
+ if ((reduce & 65536) == 0)
1881
+ return false;
1882
+ let { parser: parser2 } = this.p;
1883
+ if (!parser2.validAction(this.state, reduce)) {
1884
+ let depth = reduce >> 19, term = reduce & 65535;
1885
+ let target = this.stack.length - depth * 3;
1886
+ if (target < 0 || parser2.getGoto(this.stack[target], term, false) < 0)
1887
+ return false;
1888
+ this.storeNode(0, this.reducePos, this.reducePos, 4, true);
1889
+ this.score -= 100;
1890
+ }
1891
+ this.reducePos = this.pos;
1892
+ this.reduce(reduce);
1893
+ return true;
1894
+ }
1895
+ /// @internal
1896
+ forceAll() {
1897
+ while (!this.p.parser.stateFlag(
1898
+ this.state,
1899
+ 2
1900
+ /* StateFlag.Accepting */
1901
+ )) {
1902
+ if (!this.forceReduce()) {
1903
+ this.storeNode(0, this.pos, this.pos, 4, true);
1904
+ break;
1905
+ }
1906
+ }
1907
+ return this;
1908
+ }
1909
+ /// Check whether this state has no further actions (assumed to be a direct descendant of the
1910
+ /// top state, since any other states must be able to continue
1911
+ /// somehow). @internal
1912
+ get deadEnd() {
1913
+ if (this.stack.length != 3)
1914
+ return false;
1915
+ let { parser: parser2 } = this.p;
1916
+ return parser2.data[parser2.stateSlot(
1917
+ this.state,
1918
+ 1
1919
+ /* ParseState.Actions */
1920
+ )] == 65535 && !parser2.stateSlot(
1921
+ this.state,
1922
+ 4
1923
+ /* ParseState.DefaultReduce */
1924
+ );
1925
+ }
1926
+ /// Restart the stack (put it back in its start state). Only safe
1927
+ /// when this.stack.length == 3 (state is directly below the top
1928
+ /// state). @internal
1929
+ restart() {
1930
+ this.state = this.stack[0];
1931
+ this.stack.length = 0;
1932
+ }
1933
+ /// @internal
1934
+ sameState(other) {
1935
+ if (this.state != other.state || this.stack.length != other.stack.length)
1936
+ return false;
1937
+ for (let i = 0; i < this.stack.length; i += 3)
1938
+ if (this.stack[i] != other.stack[i])
1939
+ return false;
1940
+ return true;
1941
+ }
1942
+ /// Get the parser used by this stack.
1943
+ get parser() {
1944
+ return this.p.parser;
1945
+ }
1946
+ /// Test whether a given dialect (by numeric ID, as exported from
1947
+ /// the terms file) is enabled.
1948
+ dialectEnabled(dialectID) {
1949
+ return this.p.parser.dialect.flags[dialectID];
1950
+ }
1951
+ shiftContext(term, start) {
1952
+ if (this.curContext)
1953
+ this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
1954
+ }
1955
+ reduceContext(term, start) {
1956
+ if (this.curContext)
1957
+ this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
1958
+ }
1959
+ /// @internal
1960
+ emitContext() {
1961
+ let last = this.buffer.length - 1;
1962
+ if (last < 0 || this.buffer[last] != -3)
1963
+ this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3);
1964
+ }
1965
+ /// @internal
1966
+ emitLookAhead() {
1967
+ let last = this.buffer.length - 1;
1968
+ if (last < 0 || this.buffer[last] != -4)
1969
+ this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4);
1970
+ }
1971
+ updateContext(context) {
1972
+ if (context != this.curContext.context) {
1973
+ let newCx = new StackContext(this.curContext.tracker, context);
1974
+ if (newCx.hash != this.curContext.hash)
1975
+ this.emitContext();
1976
+ this.curContext = newCx;
1977
+ }
1978
+ }
1979
+ /// @internal
1980
+ setLookAhead(lookAhead) {
1981
+ if (lookAhead > this.lookAhead) {
1982
+ this.emitLookAhead();
1983
+ this.lookAhead = lookAhead;
1984
+ }
1985
+ }
1986
+ /// @internal
1987
+ close() {
1988
+ if (this.curContext && this.curContext.tracker.strict)
1989
+ this.emitContext();
1990
+ if (this.lookAhead > 0)
1991
+ this.emitLookAhead();
1992
+ }
1993
+ };
1994
+ var StackContext = class {
1995
+ constructor(tracker, context) {
1996
+ this.tracker = tracker;
1997
+ this.context = context;
1998
+ this.hash = tracker.strict ? tracker.hash(context) : 0;
1999
+ }
2000
+ };
2001
+ var Recover;
2002
+ (function(Recover2) {
2003
+ Recover2[Recover2["Insert"] = 200] = "Insert";
2004
+ Recover2[Recover2["Delete"] = 190] = "Delete";
2005
+ Recover2[Recover2["Reduce"] = 100] = "Reduce";
2006
+ Recover2[Recover2["MaxNext"] = 4] = "MaxNext";
2007
+ Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
2008
+ Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
2009
+ Recover2[Recover2["MinBigReduction"] = 2e3] = "MinBigReduction";
2010
+ })(Recover || (Recover = {}));
2011
+ var SimulatedStack = class {
2012
+ constructor(start) {
2013
+ this.start = start;
2014
+ this.state = start.state;
2015
+ this.stack = start.stack;
2016
+ this.base = this.stack.length;
2017
+ }
2018
+ reduce(action) {
2019
+ let term = action & 65535, depth = action >> 19;
2020
+ if (depth == 0) {
2021
+ if (this.stack == this.start.stack)
2022
+ this.stack = this.stack.slice();
2023
+ this.stack.push(this.state, 0, 0);
2024
+ this.base += 3;
2025
+ } else {
2026
+ this.base -= (depth - 1) * 3;
2027
+ }
2028
+ let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
2029
+ this.state = goto;
2030
+ }
2031
+ };
2032
+ var StackBufferCursor = class {
2033
+ constructor(stack, pos, index) {
2034
+ this.stack = stack;
2035
+ this.pos = pos;
2036
+ this.index = index;
2037
+ this.buffer = stack.buffer;
2038
+ if (this.index == 0)
2039
+ this.maybeNext();
2040
+ }
2041
+ static create(stack, pos = stack.bufferBase + stack.buffer.length) {
2042
+ return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
2043
+ }
2044
+ maybeNext() {
2045
+ let next = this.stack.parent;
2046
+ if (next != null) {
2047
+ this.index = this.stack.bufferBase - next.bufferBase;
2048
+ this.stack = next;
2049
+ this.buffer = next.buffer;
2050
+ }
2051
+ }
2052
+ get id() {
2053
+ return this.buffer[this.index - 4];
2054
+ }
2055
+ get start() {
2056
+ return this.buffer[this.index - 3];
2057
+ }
2058
+ get end() {
2059
+ return this.buffer[this.index - 2];
2060
+ }
2061
+ get size() {
2062
+ return this.buffer[this.index - 1];
2063
+ }
2064
+ next() {
2065
+ this.index -= 4;
2066
+ this.pos -= 4;
2067
+ if (this.index == 0)
2068
+ this.maybeNext();
2069
+ }
2070
+ fork() {
2071
+ return new StackBufferCursor(this.stack, this.pos, this.index);
2072
+ }
2073
+ };
2074
+ function decodeArray(input, Type = Uint16Array) {
2075
+ if (typeof input != "string")
2076
+ return input;
2077
+ let array = null;
2078
+ for (let pos = 0, out = 0; pos < input.length; ) {
2079
+ let value = 0;
2080
+ for (; ; ) {
2081
+ let next = input.charCodeAt(pos++), stop = false;
2082
+ if (next == 126) {
2083
+ value = 65535;
2084
+ break;
2085
+ }
2086
+ if (next >= 92)
2087
+ next--;
2088
+ if (next >= 34)
2089
+ next--;
2090
+ let digit = next - 32;
2091
+ if (digit >= 46) {
2092
+ digit -= 46;
2093
+ stop = true;
2094
+ }
2095
+ value += digit;
2096
+ if (stop)
2097
+ break;
2098
+ value *= 46;
2099
+ }
2100
+ if (array)
2101
+ array[out++] = value;
2102
+ else
2103
+ array = new Type(value);
2104
+ }
2105
+ return array;
2106
+ }
2107
+ var CachedToken = class {
2108
+ constructor() {
2109
+ this.start = -1;
2110
+ this.value = -1;
2111
+ this.end = -1;
2112
+ this.extended = -1;
2113
+ this.lookAhead = 0;
2114
+ this.mask = 0;
2115
+ this.context = 0;
2116
+ }
2117
+ };
2118
+ var nullToken = new CachedToken();
2119
+ var InputStream = class {
2120
+ /// @internal
2121
+ constructor(input, ranges) {
2122
+ this.input = input;
2123
+ this.ranges = ranges;
2124
+ this.chunk = "";
2125
+ this.chunkOff = 0;
2126
+ this.chunk2 = "";
2127
+ this.chunk2Pos = 0;
2128
+ this.next = -1;
2129
+ this.token = nullToken;
2130
+ this.rangeIndex = 0;
2131
+ this.pos = this.chunkPos = ranges[0].from;
2132
+ this.range = ranges[0];
2133
+ this.end = ranges[ranges.length - 1].to;
2134
+ this.readNext();
2135
+ }
2136
+ /// @internal
2137
+ resolveOffset(offset, assoc) {
2138
+ let range = this.range, index = this.rangeIndex;
2139
+ let pos = this.pos + offset;
2140
+ while (pos < range.from) {
2141
+ if (!index)
2142
+ return null;
2143
+ let next = this.ranges[--index];
2144
+ pos -= range.from - next.to;
2145
+ range = next;
2146
+ }
2147
+ while (assoc < 0 ? pos > range.to : pos >= range.to) {
2148
+ if (index == this.ranges.length - 1)
2149
+ return null;
2150
+ let next = this.ranges[++index];
2151
+ pos += next.from - range.to;
2152
+ range = next;
2153
+ }
2154
+ return pos;
2155
+ }
2156
+ /// @internal
2157
+ clipPos(pos) {
2158
+ if (pos >= this.range.from && pos < this.range.to)
2159
+ return pos;
2160
+ for (let range of this.ranges)
2161
+ if (range.to > pos)
2162
+ return Math.max(pos, range.from);
2163
+ return this.end;
2164
+ }
2165
+ /// Look at a code unit near the stream position. `.peek(0)` equals
2166
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
2167
+ /// on.
2168
+ ///
2169
+ /// Note that looking around during tokenizing creates dependencies
2170
+ /// on potentially far-away content, which may reduce the
2171
+ /// effectiveness incremental parsing—when looking forward—or even
2172
+ /// cause invalid reparses when looking backward more than 25 code
2173
+ /// units, since the library does not track lookbehind.
2174
+ peek(offset) {
2175
+ let idx = this.chunkOff + offset, pos, result;
2176
+ if (idx >= 0 && idx < this.chunk.length) {
2177
+ pos = this.pos + offset;
2178
+ result = this.chunk.charCodeAt(idx);
2179
+ } else {
2180
+ let resolved = this.resolveOffset(offset, 1);
2181
+ if (resolved == null)
2182
+ return -1;
2183
+ pos = resolved;
2184
+ if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
2185
+ result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
2186
+ } else {
2187
+ let i = this.rangeIndex, range = this.range;
2188
+ while (range.to <= pos)
2189
+ range = this.ranges[++i];
2190
+ this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
2191
+ if (pos + this.chunk2.length > range.to)
2192
+ this.chunk2 = this.chunk2.slice(0, range.to - pos);
2193
+ result = this.chunk2.charCodeAt(0);
2194
+ }
2195
+ }
2196
+ if (pos >= this.token.lookAhead)
2197
+ this.token.lookAhead = pos + 1;
2198
+ return result;
2199
+ }
2200
+ /// Accept a token. By default, the end of the token is set to the
2201
+ /// current stream position, but you can pass an offset (relative to
2202
+ /// the stream position) to change that.
2203
+ acceptToken(token, endOffset = 0) {
2204
+ let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
2205
+ if (end == null || end < this.token.start)
2206
+ throw new RangeError("Token end out of bounds");
2207
+ this.token.value = token;
2208
+ this.token.end = end;
2209
+ }
2210
+ getChunk() {
2211
+ if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
2212
+ let { chunk, chunkPos } = this;
2213
+ this.chunk = this.chunk2;
2214
+ this.chunkPos = this.chunk2Pos;
2215
+ this.chunk2 = chunk;
2216
+ this.chunk2Pos = chunkPos;
2217
+ this.chunkOff = this.pos - this.chunkPos;
2218
+ } else {
2219
+ this.chunk2 = this.chunk;
2220
+ this.chunk2Pos = this.chunkPos;
2221
+ let nextChunk = this.input.chunk(this.pos);
2222
+ let end = this.pos + nextChunk.length;
2223
+ this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
2224
+ this.chunkPos = this.pos;
2225
+ this.chunkOff = 0;
2226
+ }
2227
+ }
2228
+ readNext() {
2229
+ if (this.chunkOff >= this.chunk.length) {
2230
+ this.getChunk();
2231
+ if (this.chunkOff == this.chunk.length)
2232
+ return this.next = -1;
2233
+ }
2234
+ return this.next = this.chunk.charCodeAt(this.chunkOff);
2235
+ }
2236
+ /// Move the stream forward N (defaults to 1) code units. Returns
2237
+ /// the new value of [`next`](#lr.InputStream.next).
2238
+ advance(n = 1) {
2239
+ this.chunkOff += n;
2240
+ while (this.pos + n >= this.range.to) {
2241
+ if (this.rangeIndex == this.ranges.length - 1)
2242
+ return this.setDone();
2243
+ n -= this.range.to - this.pos;
2244
+ this.range = this.ranges[++this.rangeIndex];
2245
+ this.pos = this.range.from;
2246
+ }
2247
+ this.pos += n;
2248
+ if (this.pos >= this.token.lookAhead)
2249
+ this.token.lookAhead = this.pos + 1;
2250
+ return this.readNext();
2251
+ }
2252
+ setDone() {
2253
+ this.pos = this.chunkPos = this.end;
2254
+ this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
2255
+ this.chunk = "";
2256
+ return this.next = -1;
2257
+ }
2258
+ /// @internal
2259
+ reset(pos, token) {
2260
+ if (token) {
2261
+ this.token = token;
2262
+ token.start = pos;
2263
+ token.lookAhead = pos + 1;
2264
+ token.value = token.extended = -1;
2265
+ } else {
2266
+ this.token = nullToken;
2267
+ }
2268
+ if (this.pos != pos) {
2269
+ this.pos = pos;
2270
+ if (pos == this.end) {
2271
+ this.setDone();
2272
+ return this;
2273
+ }
2274
+ while (pos < this.range.from)
2275
+ this.range = this.ranges[--this.rangeIndex];
2276
+ while (pos >= this.range.to)
2277
+ this.range = this.ranges[++this.rangeIndex];
2278
+ if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
2279
+ this.chunkOff = pos - this.chunkPos;
2280
+ } else {
2281
+ this.chunk = "";
2282
+ this.chunkOff = 0;
2283
+ }
2284
+ this.readNext();
2285
+ }
2286
+ return this;
2287
+ }
2288
+ /// @internal
2289
+ read(from, to) {
2290
+ if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
2291
+ return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
2292
+ if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
2293
+ return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
2294
+ if (from >= this.range.from && to <= this.range.to)
2295
+ return this.input.read(from, to);
2296
+ let result = "";
2297
+ for (let r of this.ranges) {
2298
+ if (r.from >= to)
2299
+ break;
2300
+ if (r.to > from)
2301
+ result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
2302
+ }
2303
+ return result;
2304
+ }
2305
+ };
2306
+ var TokenGroup = class {
2307
+ constructor(data, id) {
2308
+ this.data = data;
2309
+ this.id = id;
2310
+ }
2311
+ token(input, stack) {
2312
+ let { parser: parser2 } = stack.p;
2313
+ readToken(this.data, input, stack, this.id, parser2.data, parser2.tokenPrecTable);
2314
+ }
2315
+ };
2316
+ TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2317
+ var LocalTokenGroup = class {
2318
+ constructor(data, precTable, elseToken) {
2319
+ this.precTable = precTable;
2320
+ this.elseToken = elseToken;
2321
+ this.data = typeof data == "string" ? decodeArray(data) : data;
2322
+ }
2323
+ token(input, stack) {
2324
+ let start = input.pos, skipped = 0;
2325
+ for (; ; ) {
2326
+ readToken(this.data, input, stack, 0, this.data, this.precTable);
2327
+ if (input.token.value > -1)
2328
+ break;
2329
+ if (this.elseToken == null)
2330
+ return;
2331
+ if (input.next < 0)
2332
+ break;
2333
+ input.advance();
2334
+ input.reset(input.pos, input.token);
2335
+ skipped++;
2336
+ }
2337
+ if (skipped) {
2338
+ input.reset(start, input.token);
2339
+ input.acceptToken(this.elseToken, skipped);
2340
+ }
2341
+ }
2342
+ };
2343
+ LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2344
+ function readToken(data, input, stack, group, precTable, precOffset) {
2345
+ let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
2346
+ scan:
2347
+ for (; ; ) {
2348
+ if ((groupMask & data[state]) == 0)
2349
+ break;
2350
+ let accEnd = data[state + 1];
2351
+ for (let i = state + 3; i < accEnd; i += 2)
2352
+ if ((data[i + 1] & groupMask) > 0) {
2353
+ let term = data[i];
2354
+ if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
2355
+ input.acceptToken(term);
2356
+ break;
2357
+ }
2358
+ }
2359
+ let next = input.next, low = 0, high = data[state + 2];
2360
+ if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 && data[accEnd + high * 3 - 3] == 65535) {
2361
+ state = data[accEnd + high * 3 - 1];
2362
+ continue scan;
2363
+ }
2364
+ for (; low < high; ) {
2365
+ let mid = low + high >> 1;
2366
+ let index = accEnd + mid + (mid << 1);
2367
+ let from = data[index], to = data[index + 1] || 65536;
2368
+ if (next < from)
2369
+ high = mid;
2370
+ else if (next >= to)
2371
+ low = mid + 1;
2372
+ else {
2373
+ state = data[index + 2];
2374
+ input.advance();
2375
+ continue scan;
2376
+ }
2377
+ }
2378
+ break;
2379
+ }
2380
+ }
2381
+ function findOffset(data, start, term) {
2382
+ for (let i = start, next; (next = data[i]) != 65535; i++)
2383
+ if (next == term)
2384
+ return i - start;
2385
+ return -1;
2386
+ }
2387
+ function overrides(token, prev, tableData, tableOffset) {
2388
+ let iPrev = findOffset(tableData, tableOffset, prev);
2389
+ return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
2390
+ }
2391
+ var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
2392
+ var stackIDs = null;
2393
+ var Safety;
2394
+ (function(Safety2) {
2395
+ Safety2[Safety2["Margin"] = 25] = "Margin";
2396
+ })(Safety || (Safety = {}));
2397
+ function cutAt(tree, pos, side) {
2398
+ let cursor = tree.cursor(IterMode.IncludeAnonymous);
2399
+ cursor.moveTo(pos);
2400
+ for (; ; ) {
2401
+ if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
2402
+ for (; ; ) {
2403
+ if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
2404
+ return side < 0 ? Math.max(0, Math.min(
2405
+ cursor.to - 1,
2406
+ pos - 25
2407
+ /* Safety.Margin */
2408
+ )) : Math.min(tree.length, Math.max(
2409
+ cursor.from + 1,
2410
+ pos + 25
2411
+ /* Safety.Margin */
2412
+ ));
2413
+ if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
2414
+ break;
2415
+ if (!cursor.parent())
2416
+ return side < 0 ? 0 : tree.length;
2417
+ }
2418
+ }
2419
+ }
2420
+ var FragmentCursor = class {
2421
+ constructor(fragments, nodeSet) {
2422
+ this.fragments = fragments;
2423
+ this.nodeSet = nodeSet;
2424
+ this.i = 0;
2425
+ this.fragment = null;
2426
+ this.safeFrom = -1;
2427
+ this.safeTo = -1;
2428
+ this.trees = [];
2429
+ this.start = [];
2430
+ this.index = [];
2431
+ this.nextFragment();
2432
+ }
2433
+ nextFragment() {
2434
+ let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
2435
+ if (fr) {
2436
+ this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
2437
+ this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
2438
+ while (this.trees.length) {
2439
+ this.trees.pop();
2440
+ this.start.pop();
2441
+ this.index.pop();
2442
+ }
2443
+ this.trees.push(fr.tree);
2444
+ this.start.push(-fr.offset);
2445
+ this.index.push(0);
2446
+ this.nextStart = this.safeFrom;
2447
+ } else {
2448
+ this.nextStart = 1e9;
2449
+ }
2450
+ }
2451
+ // `pos` must be >= any previously given `pos` for this cursor
2452
+ nodeAt(pos) {
2453
+ if (pos < this.nextStart)
2454
+ return null;
2455
+ while (this.fragment && this.safeTo <= pos)
2456
+ this.nextFragment();
2457
+ if (!this.fragment)
2458
+ return null;
2459
+ for (; ; ) {
2460
+ let last = this.trees.length - 1;
2461
+ if (last < 0) {
2462
+ this.nextFragment();
2463
+ return null;
2464
+ }
2465
+ let top = this.trees[last], index = this.index[last];
2466
+ if (index == top.children.length) {
2467
+ this.trees.pop();
2468
+ this.start.pop();
2469
+ this.index.pop();
2470
+ continue;
2471
+ }
2472
+ let next = top.children[index];
2473
+ let start = this.start[last] + top.positions[index];
2474
+ if (start > pos) {
2475
+ this.nextStart = start;
2476
+ return null;
2477
+ }
2478
+ if (next instanceof Tree) {
2479
+ if (start == pos) {
2480
+ if (start < this.safeFrom)
2481
+ return null;
2482
+ let end = start + next.length;
2483
+ if (end <= this.safeTo) {
2484
+ let lookAhead = next.prop(NodeProp.lookAhead);
2485
+ if (!lookAhead || end + lookAhead < this.fragment.to)
2486
+ return next;
2487
+ }
2488
+ }
2489
+ this.index[last]++;
2490
+ if (start + next.length >= Math.max(this.safeFrom, pos)) {
2491
+ this.trees.push(next);
2492
+ this.start.push(start);
2493
+ this.index.push(0);
2494
+ }
2495
+ } else {
2496
+ this.index[last]++;
2497
+ this.nextStart = start + next.length;
2498
+ }
2499
+ }
2500
+ }
2501
+ };
2502
+ var TokenCache = class {
2503
+ constructor(parser2, stream) {
2504
+ this.stream = stream;
2505
+ this.tokens = [];
2506
+ this.mainToken = null;
2507
+ this.actions = [];
2508
+ this.tokens = parser2.tokenizers.map((_) => new CachedToken());
2509
+ }
2510
+ getActions(stack) {
2511
+ let actionIndex = 0;
2512
+ let main = null;
2513
+ let { parser: parser2 } = stack.p, { tokenizers } = parser2;
2514
+ let mask = parser2.stateSlot(
2515
+ stack.state,
2516
+ 3
2517
+ /* ParseState.TokenizerMask */
2518
+ );
2519
+ let context = stack.curContext ? stack.curContext.hash : 0;
2520
+ let lookAhead = 0;
2521
+ for (let i = 0; i < tokenizers.length; i++) {
2522
+ if ((1 << i & mask) == 0)
2523
+ continue;
2524
+ let tokenizer = tokenizers[i], token = this.tokens[i];
2525
+ if (main && !tokenizer.fallback)
2526
+ continue;
2527
+ if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
2528
+ this.updateCachedToken(token, tokenizer, stack);
2529
+ token.mask = mask;
2530
+ token.context = context;
2531
+ }
2532
+ if (token.lookAhead > token.end + 25)
2533
+ lookAhead = Math.max(token.lookAhead, lookAhead);
2534
+ if (token.value != 0) {
2535
+ let startIndex = actionIndex;
2536
+ if (token.extended > -1)
2537
+ actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
2538
+ actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
2539
+ if (!tokenizer.extend) {
2540
+ main = token;
2541
+ if (actionIndex > startIndex)
2542
+ break;
2543
+ }
2544
+ }
2545
+ }
2546
+ while (this.actions.length > actionIndex)
2547
+ this.actions.pop();
2548
+ if (lookAhead)
2549
+ stack.setLookAhead(lookAhead);
2550
+ if (!main && stack.pos == this.stream.end) {
2551
+ main = new CachedToken();
2552
+ main.value = stack.p.parser.eofTerm;
2553
+ main.start = main.end = stack.pos;
2554
+ actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
2555
+ }
2556
+ this.mainToken = main;
2557
+ return this.actions;
2558
+ }
2559
+ getMainToken(stack) {
2560
+ if (this.mainToken)
2561
+ return this.mainToken;
2562
+ let main = new CachedToken(), { pos, p } = stack;
2563
+ main.start = pos;
2564
+ main.end = Math.min(pos + 1, p.stream.end);
2565
+ main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
2566
+ return main;
2567
+ }
2568
+ updateCachedToken(token, tokenizer, stack) {
2569
+ let start = this.stream.clipPos(stack.pos);
2570
+ tokenizer.token(this.stream.reset(start, token), stack);
2571
+ if (token.value > -1) {
2572
+ let { parser: parser2 } = stack.p;
2573
+ for (let i = 0; i < parser2.specialized.length; i++)
2574
+ if (parser2.specialized[i] == token.value) {
2575
+ let result = parser2.specializers[i](this.stream.read(token.start, token.end), stack);
2576
+ if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
2577
+ if ((result & 1) == 0)
2578
+ token.value = result >> 1;
2579
+ else
2580
+ token.extended = result >> 1;
2581
+ break;
2582
+ }
2583
+ }
2584
+ } else {
2585
+ token.value = 0;
2586
+ token.end = this.stream.clipPos(start + 1);
2587
+ }
2588
+ }
2589
+ putAction(action, token, end, index) {
2590
+ for (let i = 0; i < index; i += 3)
2591
+ if (this.actions[i] == action)
2592
+ return index;
2593
+ this.actions[index++] = action;
2594
+ this.actions[index++] = token;
2595
+ this.actions[index++] = end;
2596
+ return index;
2597
+ }
2598
+ addActions(stack, token, end, index) {
2599
+ let { state } = stack, { parser: parser2 } = stack.p, { data } = parser2;
2600
+ for (let set = 0; set < 2; set++) {
2601
+ for (let i = parser2.stateSlot(
2602
+ state,
2603
+ set ? 2 : 1
2604
+ /* ParseState.Actions */
2605
+ ); ; i += 3) {
2606
+ if (data[i] == 65535) {
2607
+ if (data[i + 1] == 1) {
2608
+ i = pair(data, i + 2);
2609
+ } else {
2610
+ if (index == 0 && data[i + 1] == 2)
2611
+ index = this.putAction(pair(data, i + 2), token, end, index);
2612
+ break;
2613
+ }
2614
+ }
2615
+ if (data[i] == token)
2616
+ index = this.putAction(pair(data, i + 1), token, end, index);
2617
+ }
2618
+ }
2619
+ return index;
2620
+ }
2621
+ };
2622
+ var Rec;
2623
+ (function(Rec2) {
2624
+ Rec2[Rec2["Distance"] = 5] = "Distance";
2625
+ Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
2626
+ Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune";
2627
+ Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit";
2628
+ Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth";
2629
+ Rec2[Rec2["CutTo"] = 9e3] = "CutTo";
2630
+ Rec2[Rec2["MaxLeftAssociativeReductionCount"] = 300] = "MaxLeftAssociativeReductionCount";
2631
+ Rec2[Rec2["MaxStackCount"] = 12] = "MaxStackCount";
2632
+ })(Rec || (Rec = {}));
2633
+ var Parse = class {
2634
+ constructor(parser2, input, fragments, ranges) {
2635
+ this.parser = parser2;
2636
+ this.input = input;
2637
+ this.ranges = ranges;
2638
+ this.recovering = 0;
2639
+ this.nextStackID = 9812;
2640
+ this.minStackPos = 0;
2641
+ this.reused = [];
2642
+ this.stoppedAt = null;
2643
+ this.lastBigReductionStart = -1;
2644
+ this.lastBigReductionSize = 0;
2645
+ this.bigReductionCount = 0;
2646
+ this.stream = new InputStream(input, ranges);
2647
+ this.tokens = new TokenCache(parser2, this.stream);
2648
+ this.topTerm = parser2.top[1];
2649
+ let { from } = ranges[0];
2650
+ this.stacks = [Stack.start(this, parser2.top[0], from)];
2651
+ this.fragments = fragments.length && this.stream.end - from > parser2.bufferLength * 4 ? new FragmentCursor(fragments, parser2.nodeSet) : null;
2652
+ }
2653
+ get parsedPos() {
2654
+ return this.minStackPos;
2655
+ }
2656
+ // Move the parser forward. This will process all parse stacks at
2657
+ // `this.pos` and try to advance them to a further position. If no
2658
+ // stack for such a position is found, it'll start error-recovery.
2659
+ //
2660
+ // When the parse is finished, this will return a syntax tree. When
2661
+ // not, it returns `null`.
2662
+ advance() {
2663
+ let stacks = this.stacks, pos = this.minStackPos;
2664
+ let newStacks = this.stacks = [];
2665
+ let stopped, stoppedTokens;
2666
+ if (this.bigReductionCount > 300 && stacks.length == 1) {
2667
+ let [s] = stacks;
2668
+ while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) {
2669
+ }
2670
+ this.bigReductionCount = this.lastBigReductionSize = 0;
2671
+ }
2672
+ for (let i = 0; i < stacks.length; i++) {
2673
+ let stack = stacks[i];
2674
+ for (; ; ) {
2675
+ this.tokens.mainToken = null;
2676
+ if (stack.pos > pos) {
2677
+ newStacks.push(stack);
2678
+ } else if (this.advanceStack(stack, newStacks, stacks)) {
2679
+ continue;
2680
+ } else {
2681
+ if (!stopped) {
2682
+ stopped = [];
2683
+ stoppedTokens = [];
2684
+ }
2685
+ stopped.push(stack);
2686
+ let tok = this.tokens.getMainToken(stack);
2687
+ stoppedTokens.push(tok.value, tok.end);
2688
+ }
2689
+ break;
2690
+ }
2691
+ }
2692
+ if (!newStacks.length) {
2693
+ let finished = stopped && findFinished(stopped);
2694
+ if (finished)
2695
+ return this.stackToTree(finished);
2696
+ if (this.parser.strict) {
2697
+ if (verbose && stopped)
2698
+ console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
2699
+ throw new SyntaxError("No parse at " + pos);
2700
+ }
2701
+ if (!this.recovering)
2702
+ this.recovering = 5;
2703
+ }
2704
+ if (this.recovering && stopped) {
2705
+ let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
2706
+ if (finished)
2707
+ return this.stackToTree(finished.forceAll());
2708
+ }
2709
+ if (this.recovering) {
2710
+ let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
2711
+ if (newStacks.length > maxRemaining) {
2712
+ newStacks.sort((a, b) => b.score - a.score);
2713
+ while (newStacks.length > maxRemaining)
2714
+ newStacks.pop();
2715
+ }
2716
+ if (newStacks.some((s) => s.reducePos > pos))
2717
+ this.recovering--;
2718
+ } else if (newStacks.length > 1) {
2719
+ outer:
2720
+ for (let i = 0; i < newStacks.length - 1; i++) {
2721
+ let stack = newStacks[i];
2722
+ for (let j = i + 1; j < newStacks.length; j++) {
2723
+ let other = newStacks[j];
2724
+ if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) {
2725
+ if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) {
2726
+ newStacks.splice(j--, 1);
2727
+ } else {
2728
+ newStacks.splice(i--, 1);
2729
+ continue outer;
2730
+ }
2731
+ }
2732
+ }
2733
+ }
2734
+ if (newStacks.length > 12)
2735
+ newStacks.splice(
2736
+ 12,
2737
+ newStacks.length - 12
2738
+ /* Rec.MaxStackCount */
2739
+ );
2740
+ }
2741
+ this.minStackPos = newStacks[0].pos;
2742
+ for (let i = 1; i < newStacks.length; i++)
2743
+ if (newStacks[i].pos < this.minStackPos)
2744
+ this.minStackPos = newStacks[i].pos;
2745
+ return null;
2746
+ }
2747
+ stopAt(pos) {
2748
+ if (this.stoppedAt != null && this.stoppedAt < pos)
2749
+ throw new RangeError("Can't move stoppedAt forward");
2750
+ this.stoppedAt = pos;
2751
+ }
2752
+ // Returns an updated version of the given stack, or null if the
2753
+ // stack can't advance normally. When `split` and `stacks` are
2754
+ // given, stacks split off by ambiguous operations will be pushed to
2755
+ // `split`, or added to `stacks` if they move `pos` forward.
2756
+ advanceStack(stack, stacks, split) {
2757
+ let start = stack.pos, { parser: parser2 } = this;
2758
+ let base = verbose ? this.stackID(stack) + " -> " : "";
2759
+ if (this.stoppedAt != null && start > this.stoppedAt)
2760
+ return stack.forceReduce() ? stack : null;
2761
+ if (this.fragments) {
2762
+ let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
2763
+ for (let cached = this.fragments.nodeAt(start); cached; ) {
2764
+ let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser2.getGoto(stack.state, cached.type.id) : -1;
2765
+ if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
2766
+ stack.useNode(cached, match);
2767
+ if (verbose)
2768
+ console.log(base + this.stackID(stack) + ` (via reuse of ${parser2.getName(cached.type.id)})`);
2769
+ return true;
2770
+ }
2771
+ if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
2772
+ break;
2773
+ let inner = cached.children[0];
2774
+ if (inner instanceof Tree && cached.positions[0] == 0)
2775
+ cached = inner;
2776
+ else
2777
+ break;
2778
+ }
2779
+ }
2780
+ let defaultReduce = parser2.stateSlot(
2781
+ stack.state,
2782
+ 4
2783
+ /* ParseState.DefaultReduce */
2784
+ );
2785
+ if (defaultReduce > 0) {
2786
+ stack.reduce(defaultReduce);
2787
+ if (verbose)
2788
+ console.log(base + this.stackID(stack) + ` (via always-reduce ${parser2.getName(
2789
+ defaultReduce & 65535
2790
+ /* Action.ValueMask */
2791
+ )})`);
2792
+ return true;
2793
+ }
2794
+ if (stack.stack.length >= 15e3) {
2795
+ while (stack.stack.length > 9e3 && stack.forceReduce()) {
2796
+ }
2797
+ }
2798
+ let actions = this.tokens.getActions(stack);
2799
+ for (let i = 0; i < actions.length; ) {
2800
+ let action = actions[i++], term = actions[i++], end = actions[i++];
2801
+ let last = i == actions.length || !split;
2802
+ let localStack = last ? stack : stack.split();
2803
+ localStack.apply(action, term, end);
2804
+ if (verbose)
2805
+ console.log(base + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser2.getName(
2806
+ action & 65535
2807
+ /* Action.ValueMask */
2808
+ )}`} for ${parser2.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
2809
+ if (last)
2810
+ return true;
2811
+ else if (localStack.pos > start)
2812
+ stacks.push(localStack);
2813
+ else
2814
+ split.push(localStack);
2815
+ }
2816
+ return false;
2817
+ }
2818
+ // Advance a given stack forward as far as it will go. Returns the
2819
+ // (possibly updated) stack if it got stuck, or null if it moved
2820
+ // forward and was given to `pushStackDedup`.
2821
+ advanceFully(stack, newStacks) {
2822
+ let pos = stack.pos;
2823
+ for (; ; ) {
2824
+ if (!this.advanceStack(stack, null, null))
2825
+ return false;
2826
+ if (stack.pos > pos) {
2827
+ pushStackDedup(stack, newStacks);
2828
+ return true;
2829
+ }
2830
+ }
2831
+ }
2832
+ runRecovery(stacks, tokens, newStacks) {
2833
+ let finished = null, restarted = false;
2834
+ for (let i = 0; i < stacks.length; i++) {
2835
+ let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
2836
+ let base = verbose ? this.stackID(stack) + " -> " : "";
2837
+ if (stack.deadEnd) {
2838
+ if (restarted)
2839
+ continue;
2840
+ restarted = true;
2841
+ stack.restart();
2842
+ if (verbose)
2843
+ console.log(base + this.stackID(stack) + " (restarted)");
2844
+ let done = this.advanceFully(stack, newStacks);
2845
+ if (done)
2846
+ continue;
2847
+ }
2848
+ let force = stack.split(), forceBase = base;
2849
+ for (let j = 0; force.forceReduce() && j < 10; j++) {
2850
+ if (verbose)
2851
+ console.log(forceBase + this.stackID(force) + " (via force-reduce)");
2852
+ let done = this.advanceFully(force, newStacks);
2853
+ if (done)
2854
+ break;
2855
+ if (verbose)
2856
+ forceBase = this.stackID(force) + " -> ";
2857
+ }
2858
+ for (let insert of stack.recoverByInsert(token)) {
2859
+ if (verbose)
2860
+ console.log(base + this.stackID(insert) + " (via recover-insert)");
2861
+ this.advanceFully(insert, newStacks);
2862
+ }
2863
+ if (this.stream.end > stack.pos) {
2864
+ if (tokenEnd == stack.pos) {
2865
+ tokenEnd++;
2866
+ token = 0;
2867
+ }
2868
+ stack.recoverByDelete(token, tokenEnd);
2869
+ if (verbose)
2870
+ console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
2871
+ pushStackDedup(stack, newStacks);
2872
+ } else if (!finished || finished.score < stack.score) {
2873
+ finished = stack;
2874
+ }
2875
+ }
2876
+ return finished;
2877
+ }
2878
+ // Convert the stack's buffer to a syntax tree.
2879
+ stackToTree(stack) {
2880
+ stack.close();
2881
+ return Tree.build({
2882
+ buffer: StackBufferCursor.create(stack),
2883
+ nodeSet: this.parser.nodeSet,
2884
+ topID: this.topTerm,
2885
+ maxBufferLength: this.parser.bufferLength,
2886
+ reused: this.reused,
2887
+ start: this.ranges[0].from,
2888
+ length: stack.pos - this.ranges[0].from,
2889
+ minRepeatType: this.parser.minRepeatTerm
2890
+ });
2891
+ }
2892
+ stackID(stack) {
2893
+ let id = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack);
2894
+ if (!id)
2895
+ stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
2896
+ return id + stack;
2897
+ }
2898
+ };
2899
+ function pushStackDedup(stack, newStacks) {
2900
+ for (let i = 0; i < newStacks.length; i++) {
2901
+ let other = newStacks[i];
2902
+ if (other.pos == stack.pos && other.sameState(stack)) {
2903
+ if (newStacks[i].score < stack.score)
2904
+ newStacks[i] = stack;
2905
+ return;
2906
+ }
2907
+ }
2908
+ newStacks.push(stack);
2909
+ }
2910
+ var Dialect = class {
2911
+ constructor(source, flags, disabled) {
2912
+ this.source = source;
2913
+ this.flags = flags;
2914
+ this.disabled = disabled;
2915
+ }
2916
+ allows(term) {
2917
+ return !this.disabled || this.disabled[term] == 0;
2918
+ }
2919
+ };
2920
+ var LRParser = class extends Parser {
2921
+ /// @internal
2922
+ constructor(spec) {
2923
+ super();
2924
+ this.wrappers = [];
2925
+ if (spec.version != 14)
2926
+ throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
2927
+ let nodeNames = spec.nodeNames.split(" ");
2928
+ this.minRepeatTerm = nodeNames.length;
2929
+ for (let i = 0; i < spec.repeatNodeCount; i++)
2930
+ nodeNames.push("");
2931
+ let topTerms = Object.keys(spec.topRules).map((r) => spec.topRules[r][1]);
2932
+ let nodeProps = [];
2933
+ for (let i = 0; i < nodeNames.length; i++)
2934
+ nodeProps.push([]);
2935
+ function setProp(nodeID, prop, value) {
2936
+ nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
2937
+ }
2938
+ if (spec.nodeProps)
2939
+ for (let propSpec of spec.nodeProps) {
2940
+ let prop = propSpec[0];
2941
+ if (typeof prop == "string")
2942
+ prop = NodeProp[prop];
2943
+ for (let i = 1; i < propSpec.length; ) {
2944
+ let next = propSpec[i++];
2945
+ if (next >= 0) {
2946
+ setProp(next, prop, propSpec[i++]);
2947
+ } else {
2948
+ let value = propSpec[i + -next];
2949
+ for (let j = -next; j > 0; j--)
2950
+ setProp(propSpec[i++], prop, value);
2951
+ i++;
2952
+ }
2953
+ }
2954
+ }
2955
+ this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
2956
+ name: i >= this.minRepeatTerm ? void 0 : name,
2957
+ id: i,
2958
+ props: nodeProps[i],
2959
+ top: topTerms.indexOf(i) > -1,
2960
+ error: i == 0,
2961
+ skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
2962
+ })));
2963
+ if (spec.propSources)
2964
+ this.nodeSet = this.nodeSet.extend(...spec.propSources);
2965
+ this.strict = false;
2966
+ this.bufferLength = DefaultBufferLength;
2967
+ let tokenArray = decodeArray(spec.tokenData);
2968
+ this.context = spec.context;
2969
+ this.specializerSpecs = spec.specialized || [];
2970
+ this.specialized = new Uint16Array(this.specializerSpecs.length);
2971
+ for (let i = 0; i < this.specializerSpecs.length; i++)
2972
+ this.specialized[i] = this.specializerSpecs[i].term;
2973
+ this.specializers = this.specializerSpecs.map(getSpecializer);
2974
+ this.states = decodeArray(spec.states, Uint32Array);
2975
+ this.data = decodeArray(spec.stateData);
2976
+ this.goto = decodeArray(spec.goto);
2977
+ this.maxTerm = spec.maxTerm;
2978
+ this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
2979
+ this.topRules = spec.topRules;
2980
+ this.dialects = spec.dialects || {};
2981
+ this.dynamicPrecedences = spec.dynamicPrecedences || null;
2982
+ this.tokenPrecTable = spec.tokenPrec;
2983
+ this.termNames = spec.termNames || null;
2984
+ this.maxNode = this.nodeSet.types.length - 1;
2985
+ this.dialect = this.parseDialect();
2986
+ this.top = this.topRules[Object.keys(this.topRules)[0]];
2987
+ }
2988
+ createParse(input, fragments, ranges) {
2989
+ let parse = new Parse(this, input, fragments, ranges);
2990
+ for (let w of this.wrappers)
2991
+ parse = w(parse, input, fragments, ranges);
2992
+ return parse;
2993
+ }
2994
+ /// Get a goto table entry @internal
2995
+ getGoto(state, term, loose = false) {
2996
+ let table = this.goto;
2997
+ if (term >= table[0])
2998
+ return -1;
2999
+ for (let pos = table[term + 1]; ; ) {
3000
+ let groupTag = table[pos++], last = groupTag & 1;
3001
+ let target = table[pos++];
3002
+ if (last && loose)
3003
+ return target;
3004
+ for (let end = pos + (groupTag >> 1); pos < end; pos++)
3005
+ if (table[pos] == state)
3006
+ return target;
3007
+ if (last)
3008
+ return -1;
3009
+ }
3010
+ }
3011
+ /// Check if this state has an action for a given terminal @internal
3012
+ hasAction(state, terminal) {
3013
+ let data = this.data;
3014
+ for (let set = 0; set < 2; set++) {
3015
+ for (let i = this.stateSlot(
3016
+ state,
3017
+ set ? 2 : 1
3018
+ /* ParseState.Actions */
3019
+ ), next; ; i += 3) {
3020
+ if ((next = data[i]) == 65535) {
3021
+ if (data[i + 1] == 1)
3022
+ next = data[i = pair(data, i + 2)];
3023
+ else if (data[i + 1] == 2)
3024
+ return pair(data, i + 2);
3025
+ else
3026
+ break;
3027
+ }
3028
+ if (next == terminal || next == 0)
3029
+ return pair(data, i + 1);
3030
+ }
3031
+ }
3032
+ return 0;
3033
+ }
3034
+ /// @internal
3035
+ stateSlot(state, slot) {
3036
+ return this.states[state * 6 + slot];
3037
+ }
3038
+ /// @internal
3039
+ stateFlag(state, flag) {
3040
+ return (this.stateSlot(
3041
+ state,
3042
+ 0
3043
+ /* ParseState.Flags */
3044
+ ) & flag) > 0;
3045
+ }
3046
+ /// @internal
3047
+ validAction(state, action) {
3048
+ if (action == this.stateSlot(
3049
+ state,
3050
+ 4
3051
+ /* ParseState.DefaultReduce */
3052
+ ))
3053
+ return true;
3054
+ for (let i = this.stateSlot(
3055
+ state,
3056
+ 1
3057
+ /* ParseState.Actions */
3058
+ ); ; i += 3) {
3059
+ if (this.data[i] == 65535) {
3060
+ if (this.data[i + 1] == 1)
3061
+ i = pair(this.data, i + 2);
3062
+ else
3063
+ return false;
3064
+ }
3065
+ if (action == pair(this.data, i + 1))
3066
+ return true;
3067
+ }
3068
+ }
3069
+ /// Get the states that can follow this one through shift actions or
3070
+ /// goto jumps. @internal
3071
+ nextStates(state) {
3072
+ let result = [];
3073
+ for (let i = this.stateSlot(
3074
+ state,
3075
+ 1
3076
+ /* ParseState.Actions */
3077
+ ); ; i += 3) {
3078
+ if (this.data[i] == 65535) {
3079
+ if (this.data[i + 1] == 1)
3080
+ i = pair(this.data, i + 2);
3081
+ else
3082
+ break;
3083
+ }
3084
+ if ((this.data[i + 2] & 65536 >> 16) == 0) {
3085
+ let value = this.data[i + 1];
3086
+ if (!result.some((v, i2) => i2 & 1 && v == value))
3087
+ result.push(this.data[i], value);
3088
+ }
3089
+ }
3090
+ return result;
3091
+ }
3092
+ /// Configure the parser. Returns a new parser instance that has the
3093
+ /// given settings modified. Settings not provided in `config` are
3094
+ /// kept from the original parser.
3095
+ configure(config) {
3096
+ let copy = Object.assign(Object.create(LRParser.prototype), this);
3097
+ if (config.props)
3098
+ copy.nodeSet = this.nodeSet.extend(...config.props);
3099
+ if (config.top) {
3100
+ let info = this.topRules[config.top];
3101
+ if (!info)
3102
+ throw new RangeError(`Invalid top rule name ${config.top}`);
3103
+ copy.top = info;
3104
+ }
3105
+ if (config.tokenizers)
3106
+ copy.tokenizers = this.tokenizers.map((t) => {
3107
+ let found = config.tokenizers.find((r) => r.from == t);
3108
+ return found ? found.to : t;
3109
+ });
3110
+ if (config.specializers) {
3111
+ copy.specializers = this.specializers.slice();
3112
+ copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
3113
+ let found = config.specializers.find((r) => r.from == s.external);
3114
+ if (!found)
3115
+ return s;
3116
+ let spec = Object.assign(Object.assign({}, s), { external: found.to });
3117
+ copy.specializers[i] = getSpecializer(spec);
3118
+ return spec;
3119
+ });
3120
+ }
3121
+ if (config.contextTracker)
3122
+ copy.context = config.contextTracker;
3123
+ if (config.dialect)
3124
+ copy.dialect = this.parseDialect(config.dialect);
3125
+ if (config.strict != null)
3126
+ copy.strict = config.strict;
3127
+ if (config.wrap)
3128
+ copy.wrappers = copy.wrappers.concat(config.wrap);
3129
+ if (config.bufferLength != null)
3130
+ copy.bufferLength = config.bufferLength;
3131
+ return copy;
3132
+ }
3133
+ /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
3134
+ /// are registered for this parser.
3135
+ hasWrappers() {
3136
+ return this.wrappers.length > 0;
3137
+ }
3138
+ /// Returns the name associated with a given term. This will only
3139
+ /// work for all terms when the parser was generated with the
3140
+ /// `--names` option. By default, only the names of tagged terms are
3141
+ /// stored.
3142
+ getName(term) {
3143
+ return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
3144
+ }
3145
+ /// The eof term id is always allocated directly after the node
3146
+ /// types. @internal
3147
+ get eofTerm() {
3148
+ return this.maxNode + 1;
3149
+ }
3150
+ /// The type of top node produced by the parser.
3151
+ get topNode() {
3152
+ return this.nodeSet.types[this.top[1]];
3153
+ }
3154
+ /// @internal
3155
+ dynamicPrecedence(term) {
3156
+ let prec = this.dynamicPrecedences;
3157
+ return prec == null ? 0 : prec[term] || 0;
3158
+ }
3159
+ /// @internal
3160
+ parseDialect(dialect) {
3161
+ let values = Object.keys(this.dialects), flags = values.map(() => false);
3162
+ if (dialect)
3163
+ for (let part of dialect.split(" ")) {
3164
+ let id = values.indexOf(part);
3165
+ if (id >= 0)
3166
+ flags[id] = true;
3167
+ }
3168
+ let disabled = null;
3169
+ for (let i = 0; i < values.length; i++)
3170
+ if (!flags[i]) {
3171
+ for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535; )
3172
+ (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
3173
+ }
3174
+ return new Dialect(dialect, flags, disabled);
3175
+ }
3176
+ /// Used by the output of the parser generator. Not available to
3177
+ /// user code. @hide
3178
+ static deserialize(spec) {
3179
+ return new LRParser(spec);
3180
+ }
3181
+ };
3182
+ function pair(data, off) {
3183
+ return data[off] | data[off + 1] << 16;
3184
+ }
3185
+ function findFinished(stacks) {
3186
+ let best = null;
3187
+ for (let stack of stacks) {
3188
+ let stopped = stack.p.stoppedAt;
3189
+ if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(
3190
+ stack.state,
3191
+ 2
3192
+ /* StateFlag.Accepting */
3193
+ ) && (!best || best.score < stack.score))
3194
+ best = stack;
3195
+ }
3196
+ return best;
3197
+ }
3198
+ function getSpecializer(spec) {
3199
+ if (spec.external) {
3200
+ let mask = spec.extend ? 1 : 0;
3201
+ return (value, stack) => spec.external(value, stack) << 1 | mask;
3202
+ }
3203
+ return spec.get;
3204
+ }
3205
+
3206
+ // ../vuu-filter-parser/src/generated/filter-parser.js
3207
+ var parser = LRParser.deserialize({
3208
+ version: 14,
3209
+ 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",
3210
+ 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",
3211
+ goto: "#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",
3212
+ 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",
3213
+ maxTerm: 39,
3214
+ skippedNodes: [0],
3215
+ repeatNodeCount: 1,
3216
+ 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",
3217
+ tokenizers: [0, 1],
3218
+ topRules: { "Filter": [0, 1] },
3219
+ tokenPrec: 0
3220
+ });
3221
+
3222
+ // ../vuu-filter-parser/src/FilterTreeWalker.ts
3223
+ var import_vuu_utils2 = require("@vuu-ui/vuu-utils");
3224
+ var _filter;
3225
+ var FilterExpression = class {
3226
+ constructor() {
3227
+ __privateAdd(this, _filter, void 0);
3228
+ }
3229
+ setFilterCombinatorOp(op, filter = __privateGet(this, _filter)) {
3230
+ if ((0, import_vuu_utils2.isMultiClauseFilter)(filter) && filter.op === op) {
3231
+ return;
3232
+ } else {
3233
+ __privateSet(this, _filter, {
3234
+ op,
3235
+ filters: [__privateGet(this, _filter)]
3236
+ });
3237
+ }
3238
+ }
3239
+ add(filter) {
3240
+ if (__privateGet(this, _filter) === void 0) {
3241
+ __privateSet(this, _filter, filter);
3242
+ } else if ((0, import_vuu_utils2.isMultiClauseFilter)(__privateGet(this, _filter))) {
3243
+ __privateGet(this, _filter).filters.push(filter);
3244
+ } else {
3245
+ throw Error(`Invalid filter passed to FilterExpression`);
3246
+ }
3247
+ }
3248
+ setColumn(column, filter = __privateGet(this, _filter)) {
3249
+ if ((0, import_vuu_utils2.isMultiClauseFilter)(filter)) {
3250
+ const target = filter.filters.at(-1);
3251
+ if (target) {
3252
+ this.setColumn(column, target);
3253
+ }
3254
+ } else if (filter) {
3255
+ filter.column = column;
3256
+ }
3257
+ }
3258
+ setOp(value, filter = __privateGet(this, _filter)) {
3259
+ if ((0, import_vuu_utils2.isMultiClauseFilter)(filter)) {
3260
+ const target = filter.filters.at(-1);
3261
+ if (target) {
3262
+ this.setOp(value, target);
3263
+ }
3264
+ } else if (filter) {
3265
+ filter.op = value;
3266
+ }
3267
+ }
3268
+ setValue(value, filter = __privateGet(this, _filter)) {
3269
+ var _a;
3270
+ if ((0, import_vuu_utils2.isMultiClauseFilter)(filter)) {
3271
+ const target = filter.filters.at(-1);
3272
+ if (target) {
3273
+ this.setValue(value, target);
3274
+ }
3275
+ } else if ((0, import_vuu_utils2.isMultiValueFilter)(filter)) {
3276
+ (_a = filter.values) != null ? _a : filter.values = [];
3277
+ filter.values.push(value);
3278
+ } else if ((0, import_vuu_utils2.isSingleValueFilter)(filter)) {
3279
+ filter.value = value;
3280
+ }
3281
+ }
3282
+ toJSON(filter = __privateGet(this, _filter)) {
3283
+ if (this.name) {
3284
+ return {
3285
+ ...filter,
3286
+ name: this.name
3287
+ };
3288
+ } else {
3289
+ return filter;
3290
+ }
3291
+ }
3292
+ };
3293
+ _filter = new WeakMap();
3294
+ var walkTree = (tree, source) => {
3295
+ const filterExpression = new FilterExpression();
3296
+ const cursor = tree.cursor();
3297
+ do {
3298
+ const { name, from, to } = cursor;
3299
+ switch (name) {
3300
+ case "ColumnValueExpression":
3301
+ filterExpression.add({});
3302
+ break;
3303
+ case "ColumnSetExpression":
3304
+ filterExpression.add({ op: "in" });
3305
+ break;
3306
+ case "Or":
3307
+ case "And":
3308
+ filterExpression.setFilterCombinatorOp(source.substring(from, to));
3309
+ break;
3310
+ case "Column":
3311
+ filterExpression.setColumn(source.substring(from, to));
3312
+ break;
3313
+ case "Operator":
3314
+ filterExpression.setOp(source.substring(from, to));
3315
+ break;
3316
+ case "String":
3317
+ filterExpression.setValue(source.substring(from + 1, to - 1));
3318
+ break;
3319
+ case "Number":
3320
+ filterExpression.setValue(parseFloat(source.substring(from, to)));
3321
+ break;
3322
+ case "True":
3323
+ filterExpression.setValue(true);
3324
+ break;
3325
+ case "False":
3326
+ filterExpression.setValue(false);
3327
+ break;
3328
+ case "FilterName":
3329
+ filterExpression.name = source.substring(from, to);
3330
+ break;
3331
+ default:
3332
+ }
3333
+ } while (cursor.next());
3334
+ return filterExpression.toJSON();
3335
+ };
3336
+
3337
+ // ../vuu-filter-parser/src/FilterParser.ts
3338
+ var strictParser = parser.configure({ strict: true });
3339
+ var parseFilter = (filterQuery) => {
3340
+ const parseTree = strictParser.parse(filterQuery);
3341
+ const filter = walkTree(parseTree, filterQuery);
3342
+ return filter;
3343
+ };
3344
+
3345
+ // ../vuu-filter-parser/src/filter-evaluation-utils.ts
3346
+ var filterPredicateMap = /* @__PURE__ */ new Map();
3347
+ var filterReject = () => false;
3348
+ var getFilterPredicate = (columnMap, filterQuery) => {
3349
+ let predicate = filterPredicateMap.get(filterQuery);
3350
+ if (predicate) {
3351
+ return predicate;
3352
+ }
3353
+ try {
3354
+ const filter = parseFilter(filterQuery);
3355
+ predicate = filterPredicate(columnMap, filter);
3356
+ filterPredicateMap.set(filterQuery, predicate);
3357
+ return predicate;
3358
+ } catch (err) {
3359
+ console.warn(
3360
+ `filter-evaluation-utils, failed to parse filter "${filterQuery}"`
3361
+ );
3362
+ return filterReject;
3363
+ }
3364
+ };
3365
+ function filterPredicate(columnMap, filter) {
3366
+ switch (filter.op) {
3367
+ case "in":
3368
+ return testInclude(columnMap, filter);
3369
+ case "=":
3370
+ return testEQ(columnMap, filter);
3371
+ case ">":
3372
+ return testGT(columnMap, filter);
3373
+ case ">=":
3374
+ return testGE(columnMap, filter);
3375
+ case "<":
3376
+ return testLT(columnMap, filter);
3377
+ case "<=":
3378
+ return testLE(columnMap, filter);
3379
+ case "starts":
3380
+ return testSW(columnMap, filter);
3381
+ case "and":
3382
+ return testAND(columnMap, filter);
3383
+ case "or":
3384
+ return testOR(columnMap, filter);
3385
+ default:
3386
+ console.log(`unrecognized filter type ${filter.op}`);
3387
+ return () => true;
3388
+ }
3389
+ }
3390
+ var testInclude = (columnMap, filter) => {
3391
+ return (row) => filter.values.indexOf(row[columnMap[filter.column]]) !== -1;
3392
+ };
3393
+ var testEQ = (columnMap, filter) => {
3394
+ return (row) => row[columnMap[filter.column]] === filter.value;
3395
+ };
3396
+ var testGT = (columnMap, filter) => {
3397
+ return (row) => row[columnMap[filter.column]] > filter.value;
3398
+ };
3399
+ var testGE = (columnMap, filter) => {
3400
+ return (row) => row[columnMap[filter.column]] >= filter.value;
3401
+ };
3402
+ var testLT = (columnMap, filter) => {
3403
+ return (row) => row[columnMap[filter.column]] < filter.value;
3404
+ };
3405
+ var testLE = (columnMap, filter) => {
3406
+ return (row) => row[columnMap[filter.column]] <= filter.value;
3407
+ };
3408
+ var testSW = (columnMap, filter) => {
3409
+ const filterValue = filter.value;
3410
+ if (typeof filterValue !== "string") {
3411
+ throw Error("string filter applied to value of wrong type");
3412
+ }
3413
+ return (row) => {
3414
+ const rowValue = row[columnMap[filter.column]];
3415
+ if (typeof rowValue !== "string") {
3416
+ throw Error("string filter applied to value of wrong type");
3417
+ }
3418
+ return rowValue.toLowerCase().startsWith(filterValue.toLowerCase());
3419
+ };
3420
+ };
3421
+ var testAND = (columnMap, filter) => {
3422
+ const filters = filter.filters.map((f1) => filterPredicate(columnMap, f1));
3423
+ return (row) => filters.every((fn) => fn(row));
3424
+ };
3425
+ function testOR(columnMap, filter) {
3426
+ const filters = filter.filters.map((f1) => filterPredicate(columnMap, f1));
3427
+ return (row) => filters.some((fn) => fn(row));
3428
+ }
3429
+
3430
+ // src/hooks/useVuuMenuActions.ts
3431
+ var import_vuu_utils3 = require("@vuu-ui/vuu-utils");
3432
+ var import_react5 = require("react");
3433
+ var addRowsFromInstruments = "addRowsFromInstruments";
3434
+ var { KEY } = import_vuu_utils3.metadataKeys;
3435
+ var NO_CONFIG = {};
3436
+ var isVisualLinksAction = (action) => action.type === "vuu-links";
3437
+ var isVisualLinkCreatedAction = (action) => action.type === "vuu-link-created";
3438
+ var isVisualLinkRemovedAction = (action) => action.type === "vuu-link-removed";
3439
+ var isViewportMenusAction = (action) => action.type === "vuu-menu";
3440
+ var isVuuFeatureAction = (action) => isViewportMenusAction(action) || isVisualLinksAction(action);
3441
+ var isVuuFeatureInvocation = (action) => action.type === "vuu-link-created" || action.type === "vuu-link-removed";
3442
+ var isMenuItem = (menu) => "rpcName" in menu;
3443
+ var isGroupMenuItem = (menu) => "menus" in menu;
3444
+ var isRoot = (menu) => menu.name === "ROOT";
3445
+ var isCellMenu = (options) => options.context === "cell";
3446
+ var isRowMenu = (options) => options.context === "row";
3447
+ var isSelectionMenu = (options) => options.context === "selected-rows";
3448
+ var vuuContextCompatibleWithTableLocation = (uiLocation, vuuContext, selectedRowCount = 0) => {
3449
+ switch (uiLocation) {
3450
+ case "grid":
3451
+ if (vuuContext === "selected-rows") {
3452
+ return selectedRowCount > 0;
3453
+ } else {
3454
+ return true;
3455
+ }
3456
+ case "header":
3457
+ return vuuContext === "grid";
3458
+ default:
3459
+ return false;
3460
+ }
3461
+ };
3462
+ var gridRowMeetsFilterCriteria = (context, row, selectedRows, filter, columnMap) => {
3463
+ if (context === "cell" || context === "row") {
3464
+ const filterPredicate2 = getFilterPredicate(columnMap, filter);
3465
+ return filterPredicate2(row);
3466
+ } else if (context === "selected-rows") {
3467
+ if (selectedRows.length === 0) {
3468
+ return false;
3469
+ } else {
3470
+ const filterPredicate2 = getFilterPredicate(columnMap, filter);
3471
+ return selectedRows.every(filterPredicate2);
3472
+ }
3473
+ }
3474
+ return true;
3475
+ };
3476
+ var getMenuRpcRequest = (options) => {
3477
+ const { rpcName } = options;
3478
+ if (isCellMenu(options)) {
3479
+ return {
3480
+ field: options.field,
3481
+ rowKey: options.rowKey,
3482
+ rpcName,
3483
+ value: options.value,
3484
+ type: "VIEW_PORT_MENU_CELL_RPC"
3485
+ };
3486
+ } else if (isRowMenu(options)) {
3487
+ return {
3488
+ rowKey: options.rowKey,
3489
+ row: options.row,
3490
+ rpcName,
3491
+ type: "VIEW_PORT_MENU_ROW_RPC"
3492
+ };
3493
+ } else if (isSelectionMenu(options)) {
3494
+ return {
3495
+ rpcName,
3496
+ type: "VIEW_PORT_MENUS_SELECT_RPC"
3497
+ };
3498
+ } else {
3499
+ return {
3500
+ rpcName,
3501
+ type: "VIEW_PORT_MENU_TABLE_RPC"
3502
+ };
3503
+ }
3504
+ };
3505
+ var hasFilter = ({ filter }) => typeof filter === "string" && filter.length > 0;
3506
+ var getMenuItemOptions = (menu, options) => {
3507
+ switch (menu.context) {
3508
+ case "cell":
3509
+ return {
3510
+ ...menu,
3511
+ field: options.columnName,
3512
+ rowKey: options.row[KEY],
3513
+ value: options.row[options.columnMap[options.columnName]]
3514
+ };
3515
+ case "row":
3516
+ return {
3517
+ ...menu,
3518
+ row: (0, import_vuu_utils3.getRowRecord)(options.row, options.columnMap),
3519
+ rowKey: options.row[KEY]
3520
+ };
3521
+ default:
3522
+ return menu;
3523
+ }
3524
+ };
3525
+ var menuShouldBeRenderedInThisContext = (menuItem, tableLocation, options) => {
3526
+ var _a;
3527
+ if (isGroupMenuItem(menuItem)) {
3528
+ return menuItem.menus.some(
3529
+ (childMenu) => menuShouldBeRenderedInThisContext(childMenu, tableLocation, options)
3530
+ );
3531
+ }
3532
+ if (!vuuContextCompatibleWithTableLocation(
3533
+ tableLocation,
3534
+ menuItem.context,
3535
+ (_a = options.selectedRows) == null ? void 0 : _a.length
3536
+ )) {
3537
+ return false;
3538
+ }
3539
+ if (tableLocation === "grid" && hasFilter(menuItem)) {
3540
+ return gridRowMeetsFilterCriteria(
3541
+ menuItem.context,
3542
+ options.row,
3543
+ options.selectedRows,
3544
+ menuItem.filter,
3545
+ options.columnMap
3546
+ );
3547
+ }
3548
+ if (isCellMenu(menuItem) && menuItem.field !== "*") {
3549
+ return menuItem.field === options.columnName;
3550
+ }
3551
+ return true;
3552
+ };
3553
+ var buildMenuDescriptor = (menu, tableLocation, options) => {
3554
+ if (menuShouldBeRenderedInThisContext(menu, tableLocation, options)) {
3555
+ if (isMenuItem(menu)) {
3556
+ return {
3557
+ label: menu.name,
3558
+ action: "MENU_RPC_CALL",
3559
+ options: getMenuItemOptions(menu, options)
3560
+ };
3561
+ } else {
3562
+ const children = menu.menus.map(
3563
+ (childMenu) => buildMenuDescriptor(childMenu, tableLocation, options)
3564
+ ).filter(
3565
+ (childMenu) => childMenu !== void 0
3566
+ );
3567
+ if (children.length > 0) {
3568
+ return {
3569
+ label: menu.name,
3570
+ children
3571
+ };
3572
+ }
3573
+ }
3574
+ }
3575
+ };
3576
+ var useVuuMenuActions = ({
3577
+ dataSource,
3578
+ menuActionConfig = NO_CONFIG,
3579
+ onRpcResponse
3580
+ }) => {
3581
+ const buildViewserverMenuOptions = (0, import_react5.useCallback)(
3582
+ (tableLocation, options) => {
3583
+ const { visualLink, visualLinks, vuuMenu } = menuActionConfig;
3584
+ const descriptors = [];
3585
+ if (tableLocation === "grid" && visualLinks && !visualLink) {
3586
+ visualLinks.forEach((linkDescriptor) => {
3587
+ const { link, label: linkLabel } = linkDescriptor;
3588
+ const label = linkLabel ? linkLabel : link.toTable;
3589
+ descriptors.push({
3590
+ label: `Link to ${label}`,
3591
+ action: "link-table",
3592
+ options: linkDescriptor
3593
+ });
3594
+ });
3595
+ }
3596
+ if (vuuMenu) {
3597
+ const menuDescriptor = buildMenuDescriptor(
3598
+ vuuMenu,
3599
+ tableLocation,
3600
+ options
3601
+ );
3602
+ if (isRoot(vuuMenu) && (0, import_vuu_utils3.isGroupMenuItemDescriptor)(menuDescriptor)) {
3603
+ descriptors.push(...menuDescriptor.children);
3604
+ } else if (menuDescriptor) {
3605
+ descriptors.push(menuDescriptor);
3606
+ }
3607
+ }
3608
+ return descriptors;
3609
+ },
3610
+ [menuActionConfig]
3611
+ );
3612
+ const handleMenuAction = (0, import_react5.useCallback)(
3613
+ (type, options) => {
3614
+ if (type === "MENU_RPC_CALL") {
3615
+ const rpcRequest = getMenuRpcRequest(options);
3616
+ dataSource.menuRpcCall(rpcRequest).then((rpcResponse) => {
3617
+ if (onRpcResponse && rpcResponse) {
3618
+ onRpcResponse && onRpcResponse(rpcResponse);
3619
+ }
3620
+ });
3621
+ return true;
3622
+ } else if (type === "link-table") {
3623
+ return dataSource.visualLink = options, true;
3624
+ } else {
3625
+ console.log(
3626
+ `useViewServer handleMenuAction, can't handle action type ${type}`
3627
+ );
3628
+ }
3629
+ return false;
3630
+ },
3631
+ [dataSource, onRpcResponse]
3632
+ );
3633
+ return {
3634
+ buildViewserverMenuOptions,
3635
+ handleMenuAction
3636
+ };
3637
+ };
3638
+
3639
+ // src/hooks/useVuuTables.ts
3640
+ var import_react6 = require("react");
3641
+ var import_vuu_data4 = require("@vuu-ui/vuu-data");
3642
+ var useVuuTables = () => {
3643
+ const [tables, setTables] = (0, import_react6.useState)();
3644
+ const buildTables = (0, import_react6.useCallback)((schemas) => {
3645
+ const vuuTables = /* @__PURE__ */ new Map();
3646
+ schemas.forEach((schema) => {
3647
+ vuuTables.set(schema.table.table, schema);
3648
+ });
3649
+ return vuuTables;
3650
+ }, []);
3651
+ (0, import_react6.useEffect)(() => {
3652
+ async function fetchTableMetadata() {
3653
+ const server = await (0, import_vuu_data4.getServerAPI)();
3654
+ const { tables: tables2 } = await server.getTableList();
3655
+ const tableSchemas = buildTables(
3656
+ await Promise.all(
3657
+ tables2.map(
3658
+ (tableDescriptor) => server.getTableSchema(tableDescriptor)
3659
+ )
3660
+ )
3661
+ );
3662
+ setTables(tableSchemas);
3663
+ }
3664
+ fetchTableMetadata();
3665
+ }, [buildTables]);
3666
+ return tables;
3667
+ };
3668
+ //# sourceMappingURL=index.js.map