@standardbeagle/data-router 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2904 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import require$$0, { createContext, useMemo, useReducer, useContext, useRef, useEffect, useCallback, forwardRef } from "react";
8
+ var jsxRuntime = { exports: {} };
9
+ var reactJsxRuntime_production_min = {};
10
+ /**
11
+ * @license React
12
+ * react-jsx-runtime.production.min.js
13
+ *
14
+ * Copyright (c) Facebook, Inc. and its affiliates.
15
+ *
16
+ * This source code is licensed under the MIT license found in the
17
+ * LICENSE file in the root directory of this source tree.
18
+ */
19
+ var hasRequiredReactJsxRuntime_production_min;
20
+ function requireReactJsxRuntime_production_min() {
21
+ if (hasRequiredReactJsxRuntime_production_min)
22
+ return reactJsxRuntime_production_min;
23
+ hasRequiredReactJsxRuntime_production_min = 1;
24
+ var f = require$$0, k2 = Symbol.for("react.element"), l2 = Symbol.for("react.fragment"), m2 = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p2 = { key: true, ref: true, __self: true, __source: true };
25
+ function q2(c, a, g2) {
26
+ var b2, d = {}, e = null, h2 = null;
27
+ void 0 !== g2 && (e = "" + g2);
28
+ void 0 !== a.key && (e = "" + a.key);
29
+ void 0 !== a.ref && (h2 = a.ref);
30
+ for (b2 in a)
31
+ m2.call(a, b2) && !p2.hasOwnProperty(b2) && (d[b2] = a[b2]);
32
+ if (c && c.defaultProps)
33
+ for (b2 in a = c.defaultProps, a)
34
+ void 0 === d[b2] && (d[b2] = a[b2]);
35
+ return { $$typeof: k2, type: c, key: e, ref: h2, props: d, _owner: n.current };
36
+ }
37
+ reactJsxRuntime_production_min.Fragment = l2;
38
+ reactJsxRuntime_production_min.jsx = q2;
39
+ reactJsxRuntime_production_min.jsxs = q2;
40
+ return reactJsxRuntime_production_min;
41
+ }
42
+ var reactJsxRuntime_development = {};
43
+ /**
44
+ * @license React
45
+ * react-jsx-runtime.development.js
46
+ *
47
+ * Copyright (c) Facebook, Inc. and its affiliates.
48
+ *
49
+ * This source code is licensed under the MIT license found in the
50
+ * LICENSE file in the root directory of this source tree.
51
+ */
52
+ var hasRequiredReactJsxRuntime_development;
53
+ function requireReactJsxRuntime_development() {
54
+ if (hasRequiredReactJsxRuntime_development)
55
+ return reactJsxRuntime_development;
56
+ hasRequiredReactJsxRuntime_development = 1;
57
+ if (process.env.NODE_ENV !== "production") {
58
+ (function() {
59
+ var React = require$$0;
60
+ var REACT_ELEMENT_TYPE = Symbol.for("react.element");
61
+ var REACT_PORTAL_TYPE = Symbol.for("react.portal");
62
+ var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
63
+ var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
64
+ var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
65
+ var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
66
+ var REACT_CONTEXT_TYPE = Symbol.for("react.context");
67
+ var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
68
+ var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
69
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
70
+ var REACT_MEMO_TYPE = Symbol.for("react.memo");
71
+ var REACT_LAZY_TYPE = Symbol.for("react.lazy");
72
+ var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
73
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
74
+ var FAUX_ITERATOR_SYMBOL = "@@iterator";
75
+ function getIteratorFn(maybeIterable) {
76
+ if (maybeIterable === null || typeof maybeIterable !== "object") {
77
+ return null;
78
+ }
79
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
80
+ if (typeof maybeIterator === "function") {
81
+ return maybeIterator;
82
+ }
83
+ return null;
84
+ }
85
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
86
+ function error(format) {
87
+ {
88
+ {
89
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
90
+ args[_key2 - 1] = arguments[_key2];
91
+ }
92
+ printWarning("error", format, args);
93
+ }
94
+ }
95
+ }
96
+ function printWarning(level, format, args) {
97
+ {
98
+ var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
99
+ var stack = ReactDebugCurrentFrame2.getStackAddendum();
100
+ if (stack !== "") {
101
+ format += "%s";
102
+ args = args.concat([stack]);
103
+ }
104
+ var argsWithFormat = args.map(function(item) {
105
+ return String(item);
106
+ });
107
+ argsWithFormat.unshift("Warning: " + format);
108
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
109
+ }
110
+ }
111
+ var enableScopeAPI = false;
112
+ var enableCacheElement = false;
113
+ var enableTransitionTracing = false;
114
+ var enableLegacyHidden = false;
115
+ var enableDebugTracing = false;
116
+ var REACT_MODULE_REFERENCE;
117
+ {
118
+ REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
119
+ }
120
+ function isValidElementType(type) {
121
+ if (typeof type === "string" || typeof type === "function") {
122
+ return true;
123
+ }
124
+ if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
125
+ return true;
126
+ }
127
+ if (typeof type === "object" && type !== null) {
128
+ if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
129
+ // types supported by any Flight configuration anywhere since
130
+ // we don't know which Flight build this will end up being used
131
+ // with.
132
+ type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) {
133
+ return true;
134
+ }
135
+ }
136
+ return false;
137
+ }
138
+ function getWrappedName(outerType, innerType, wrapperName) {
139
+ var displayName = outerType.displayName;
140
+ if (displayName) {
141
+ return displayName;
142
+ }
143
+ var functionName = innerType.displayName || innerType.name || "";
144
+ return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
145
+ }
146
+ function getContextName(type) {
147
+ return type.displayName || "Context";
148
+ }
149
+ function getComponentNameFromType(type) {
150
+ if (type == null) {
151
+ return null;
152
+ }
153
+ {
154
+ if (typeof type.tag === "number") {
155
+ error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
156
+ }
157
+ }
158
+ if (typeof type === "function") {
159
+ return type.displayName || type.name || null;
160
+ }
161
+ if (typeof type === "string") {
162
+ return type;
163
+ }
164
+ switch (type) {
165
+ case REACT_FRAGMENT_TYPE:
166
+ return "Fragment";
167
+ case REACT_PORTAL_TYPE:
168
+ return "Portal";
169
+ case REACT_PROFILER_TYPE:
170
+ return "Profiler";
171
+ case REACT_STRICT_MODE_TYPE:
172
+ return "StrictMode";
173
+ case REACT_SUSPENSE_TYPE:
174
+ return "Suspense";
175
+ case REACT_SUSPENSE_LIST_TYPE:
176
+ return "SuspenseList";
177
+ }
178
+ if (typeof type === "object") {
179
+ switch (type.$$typeof) {
180
+ case REACT_CONTEXT_TYPE:
181
+ var context = type;
182
+ return getContextName(context) + ".Consumer";
183
+ case REACT_PROVIDER_TYPE:
184
+ var provider = type;
185
+ return getContextName(provider._context) + ".Provider";
186
+ case REACT_FORWARD_REF_TYPE:
187
+ return getWrappedName(type, type.render, "ForwardRef");
188
+ case REACT_MEMO_TYPE:
189
+ var outerName = type.displayName || null;
190
+ if (outerName !== null) {
191
+ return outerName;
192
+ }
193
+ return getComponentNameFromType(type.type) || "Memo";
194
+ case REACT_LAZY_TYPE: {
195
+ var lazyComponent = type;
196
+ var payload = lazyComponent._payload;
197
+ var init = lazyComponent._init;
198
+ try {
199
+ return getComponentNameFromType(init(payload));
200
+ } catch (x2) {
201
+ return null;
202
+ }
203
+ }
204
+ }
205
+ }
206
+ return null;
207
+ }
208
+ var assign = Object.assign;
209
+ var disabledDepth = 0;
210
+ var prevLog;
211
+ var prevInfo;
212
+ var prevWarn;
213
+ var prevError;
214
+ var prevGroup;
215
+ var prevGroupCollapsed;
216
+ var prevGroupEnd;
217
+ function disabledLog() {
218
+ }
219
+ disabledLog.__reactDisabledLog = true;
220
+ function disableLogs() {
221
+ {
222
+ if (disabledDepth === 0) {
223
+ prevLog = console.log;
224
+ prevInfo = console.info;
225
+ prevWarn = console.warn;
226
+ prevError = console.error;
227
+ prevGroup = console.group;
228
+ prevGroupCollapsed = console.groupCollapsed;
229
+ prevGroupEnd = console.groupEnd;
230
+ var props = {
231
+ configurable: true,
232
+ enumerable: true,
233
+ value: disabledLog,
234
+ writable: true
235
+ };
236
+ Object.defineProperties(console, {
237
+ info: props,
238
+ log: props,
239
+ warn: props,
240
+ error: props,
241
+ group: props,
242
+ groupCollapsed: props,
243
+ groupEnd: props
244
+ });
245
+ }
246
+ disabledDepth++;
247
+ }
248
+ }
249
+ function reenableLogs() {
250
+ {
251
+ disabledDepth--;
252
+ if (disabledDepth === 0) {
253
+ var props = {
254
+ configurable: true,
255
+ enumerable: true,
256
+ writable: true
257
+ };
258
+ Object.defineProperties(console, {
259
+ log: assign({}, props, {
260
+ value: prevLog
261
+ }),
262
+ info: assign({}, props, {
263
+ value: prevInfo
264
+ }),
265
+ warn: assign({}, props, {
266
+ value: prevWarn
267
+ }),
268
+ error: assign({}, props, {
269
+ value: prevError
270
+ }),
271
+ group: assign({}, props, {
272
+ value: prevGroup
273
+ }),
274
+ groupCollapsed: assign({}, props, {
275
+ value: prevGroupCollapsed
276
+ }),
277
+ groupEnd: assign({}, props, {
278
+ value: prevGroupEnd
279
+ })
280
+ });
281
+ }
282
+ if (disabledDepth < 0) {
283
+ error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
284
+ }
285
+ }
286
+ }
287
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
288
+ var prefix;
289
+ function describeBuiltInComponentFrame(name, source, ownerFn) {
290
+ {
291
+ if (prefix === void 0) {
292
+ try {
293
+ throw Error();
294
+ } catch (x2) {
295
+ var match = x2.stack.trim().match(/\n( *(at )?)/);
296
+ prefix = match && match[1] || "";
297
+ }
298
+ }
299
+ return "\n" + prefix + name;
300
+ }
301
+ }
302
+ var reentry = false;
303
+ var componentFrameCache;
304
+ {
305
+ var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
306
+ componentFrameCache = new PossiblyWeakMap();
307
+ }
308
+ function describeNativeComponentFrame(fn2, construct) {
309
+ if (!fn2 || reentry) {
310
+ return "";
311
+ }
312
+ {
313
+ var frame = componentFrameCache.get(fn2);
314
+ if (frame !== void 0) {
315
+ return frame;
316
+ }
317
+ }
318
+ var control;
319
+ reentry = true;
320
+ var previousPrepareStackTrace = Error.prepareStackTrace;
321
+ Error.prepareStackTrace = void 0;
322
+ var previousDispatcher;
323
+ {
324
+ previousDispatcher = ReactCurrentDispatcher.current;
325
+ ReactCurrentDispatcher.current = null;
326
+ disableLogs();
327
+ }
328
+ try {
329
+ if (construct) {
330
+ var Fake = function() {
331
+ throw Error();
332
+ };
333
+ Object.defineProperty(Fake.prototype, "props", {
334
+ set: function() {
335
+ throw Error();
336
+ }
337
+ });
338
+ if (typeof Reflect === "object" && Reflect.construct) {
339
+ try {
340
+ Reflect.construct(Fake, []);
341
+ } catch (x2) {
342
+ control = x2;
343
+ }
344
+ Reflect.construct(fn2, [], Fake);
345
+ } else {
346
+ try {
347
+ Fake.call();
348
+ } catch (x2) {
349
+ control = x2;
350
+ }
351
+ fn2.call(Fake.prototype);
352
+ }
353
+ } else {
354
+ try {
355
+ throw Error();
356
+ } catch (x2) {
357
+ control = x2;
358
+ }
359
+ fn2();
360
+ }
361
+ } catch (sample) {
362
+ if (sample && control && typeof sample.stack === "string") {
363
+ var sampleLines = sample.stack.split("\n");
364
+ var controlLines = control.stack.split("\n");
365
+ var s = sampleLines.length - 1;
366
+ var c = controlLines.length - 1;
367
+ while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
368
+ c--;
369
+ }
370
+ for (; s >= 1 && c >= 0; s--, c--) {
371
+ if (sampleLines[s] !== controlLines[c]) {
372
+ if (s !== 1 || c !== 1) {
373
+ do {
374
+ s--;
375
+ c--;
376
+ if (c < 0 || sampleLines[s] !== controlLines[c]) {
377
+ var _frame = "\n" + sampleLines[s].replace(" at new ", " at ");
378
+ if (fn2.displayName && _frame.includes("<anonymous>")) {
379
+ _frame = _frame.replace("<anonymous>", fn2.displayName);
380
+ }
381
+ {
382
+ if (typeof fn2 === "function") {
383
+ componentFrameCache.set(fn2, _frame);
384
+ }
385
+ }
386
+ return _frame;
387
+ }
388
+ } while (s >= 1 && c >= 0);
389
+ }
390
+ break;
391
+ }
392
+ }
393
+ }
394
+ } finally {
395
+ reentry = false;
396
+ {
397
+ ReactCurrentDispatcher.current = previousDispatcher;
398
+ reenableLogs();
399
+ }
400
+ Error.prepareStackTrace = previousPrepareStackTrace;
401
+ }
402
+ var name = fn2 ? fn2.displayName || fn2.name : "";
403
+ var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
404
+ {
405
+ if (typeof fn2 === "function") {
406
+ componentFrameCache.set(fn2, syntheticFrame);
407
+ }
408
+ }
409
+ return syntheticFrame;
410
+ }
411
+ function describeFunctionComponentFrame(fn2, source, ownerFn) {
412
+ {
413
+ return describeNativeComponentFrame(fn2, false);
414
+ }
415
+ }
416
+ function shouldConstruct(Component) {
417
+ var prototype = Component.prototype;
418
+ return !!(prototype && prototype.isReactComponent);
419
+ }
420
+ function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
421
+ if (type == null) {
422
+ return "";
423
+ }
424
+ if (typeof type === "function") {
425
+ {
426
+ return describeNativeComponentFrame(type, shouldConstruct(type));
427
+ }
428
+ }
429
+ if (typeof type === "string") {
430
+ return describeBuiltInComponentFrame(type);
431
+ }
432
+ switch (type) {
433
+ case REACT_SUSPENSE_TYPE:
434
+ return describeBuiltInComponentFrame("Suspense");
435
+ case REACT_SUSPENSE_LIST_TYPE:
436
+ return describeBuiltInComponentFrame("SuspenseList");
437
+ }
438
+ if (typeof type === "object") {
439
+ switch (type.$$typeof) {
440
+ case REACT_FORWARD_REF_TYPE:
441
+ return describeFunctionComponentFrame(type.render);
442
+ case REACT_MEMO_TYPE:
443
+ return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
444
+ case REACT_LAZY_TYPE: {
445
+ var lazyComponent = type;
446
+ var payload = lazyComponent._payload;
447
+ var init = lazyComponent._init;
448
+ try {
449
+ return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
450
+ } catch (x2) {
451
+ }
452
+ }
453
+ }
454
+ }
455
+ return "";
456
+ }
457
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
458
+ var loggedTypeFailures = {};
459
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
460
+ function setCurrentlyValidatingElement(element) {
461
+ {
462
+ if (element) {
463
+ var owner = element._owner;
464
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
465
+ ReactDebugCurrentFrame.setExtraStackFrame(stack);
466
+ } else {
467
+ ReactDebugCurrentFrame.setExtraStackFrame(null);
468
+ }
469
+ }
470
+ }
471
+ function checkPropTypes(typeSpecs, values, location, componentName, element) {
472
+ {
473
+ var has = Function.call.bind(hasOwnProperty);
474
+ for (var typeSpecName in typeSpecs) {
475
+ if (has(typeSpecs, typeSpecName)) {
476
+ var error$1 = void 0;
477
+ try {
478
+ if (typeof typeSpecs[typeSpecName] !== "function") {
479
+ var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
480
+ err.name = "Invariant Violation";
481
+ throw err;
482
+ }
483
+ error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
484
+ } catch (ex) {
485
+ error$1 = ex;
486
+ }
487
+ if (error$1 && !(error$1 instanceof Error)) {
488
+ setCurrentlyValidatingElement(element);
489
+ error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
490
+ setCurrentlyValidatingElement(null);
491
+ }
492
+ if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
493
+ loggedTypeFailures[error$1.message] = true;
494
+ setCurrentlyValidatingElement(element);
495
+ error("Failed %s type: %s", location, error$1.message);
496
+ setCurrentlyValidatingElement(null);
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }
502
+ var isArrayImpl = Array.isArray;
503
+ function isArray(a) {
504
+ return isArrayImpl(a);
505
+ }
506
+ function typeName(value) {
507
+ {
508
+ var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
509
+ var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
510
+ return type;
511
+ }
512
+ }
513
+ function willCoercionThrow(value) {
514
+ {
515
+ try {
516
+ testStringCoercion(value);
517
+ return false;
518
+ } catch (e) {
519
+ return true;
520
+ }
521
+ }
522
+ }
523
+ function testStringCoercion(value) {
524
+ return "" + value;
525
+ }
526
+ function checkKeyStringCoercion(value) {
527
+ {
528
+ if (willCoercionThrow(value)) {
529
+ error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
530
+ return testStringCoercion(value);
531
+ }
532
+ }
533
+ }
534
+ var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
535
+ var RESERVED_PROPS = {
536
+ key: true,
537
+ ref: true,
538
+ __self: true,
539
+ __source: true
540
+ };
541
+ var specialPropKeyWarningShown;
542
+ var specialPropRefWarningShown;
543
+ var didWarnAboutStringRefs;
544
+ {
545
+ didWarnAboutStringRefs = {};
546
+ }
547
+ function hasValidRef(config) {
548
+ {
549
+ if (hasOwnProperty.call(config, "ref")) {
550
+ var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
551
+ if (getter && getter.isReactWarning) {
552
+ return false;
553
+ }
554
+ }
555
+ }
556
+ return config.ref !== void 0;
557
+ }
558
+ function hasValidKey(config) {
559
+ {
560
+ if (hasOwnProperty.call(config, "key")) {
561
+ var getter = Object.getOwnPropertyDescriptor(config, "key").get;
562
+ if (getter && getter.isReactWarning) {
563
+ return false;
564
+ }
565
+ }
566
+ }
567
+ return config.key !== void 0;
568
+ }
569
+ function warnIfStringRefCannotBeAutoConverted(config, self) {
570
+ {
571
+ if (typeof config.ref === "string" && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
572
+ var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
573
+ if (!didWarnAboutStringRefs[componentName]) {
574
+ error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
575
+ didWarnAboutStringRefs[componentName] = true;
576
+ }
577
+ }
578
+ }
579
+ }
580
+ function defineKeyPropWarningGetter(props, displayName) {
581
+ {
582
+ var warnAboutAccessingKey = function() {
583
+ if (!specialPropKeyWarningShown) {
584
+ specialPropKeyWarningShown = true;
585
+ error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
586
+ }
587
+ };
588
+ warnAboutAccessingKey.isReactWarning = true;
589
+ Object.defineProperty(props, "key", {
590
+ get: warnAboutAccessingKey,
591
+ configurable: true
592
+ });
593
+ }
594
+ }
595
+ function defineRefPropWarningGetter(props, displayName) {
596
+ {
597
+ var warnAboutAccessingRef = function() {
598
+ if (!specialPropRefWarningShown) {
599
+ specialPropRefWarningShown = true;
600
+ error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
601
+ }
602
+ };
603
+ warnAboutAccessingRef.isReactWarning = true;
604
+ Object.defineProperty(props, "ref", {
605
+ get: warnAboutAccessingRef,
606
+ configurable: true
607
+ });
608
+ }
609
+ }
610
+ var ReactElement = function(type, key, ref, self, source, owner, props) {
611
+ var element = {
612
+ // This tag allows us to uniquely identify this as a React Element
613
+ $$typeof: REACT_ELEMENT_TYPE,
614
+ // Built-in properties that belong on the element
615
+ type,
616
+ key,
617
+ ref,
618
+ props,
619
+ // Record the component responsible for creating this element.
620
+ _owner: owner
621
+ };
622
+ {
623
+ element._store = {};
624
+ Object.defineProperty(element._store, "validated", {
625
+ configurable: false,
626
+ enumerable: false,
627
+ writable: true,
628
+ value: false
629
+ });
630
+ Object.defineProperty(element, "_self", {
631
+ configurable: false,
632
+ enumerable: false,
633
+ writable: false,
634
+ value: self
635
+ });
636
+ Object.defineProperty(element, "_source", {
637
+ configurable: false,
638
+ enumerable: false,
639
+ writable: false,
640
+ value: source
641
+ });
642
+ if (Object.freeze) {
643
+ Object.freeze(element.props);
644
+ Object.freeze(element);
645
+ }
646
+ }
647
+ return element;
648
+ };
649
+ function jsxDEV(type, config, maybeKey, source, self) {
650
+ {
651
+ var propName;
652
+ var props = {};
653
+ var key = null;
654
+ var ref = null;
655
+ if (maybeKey !== void 0) {
656
+ {
657
+ checkKeyStringCoercion(maybeKey);
658
+ }
659
+ key = "" + maybeKey;
660
+ }
661
+ if (hasValidKey(config)) {
662
+ {
663
+ checkKeyStringCoercion(config.key);
664
+ }
665
+ key = "" + config.key;
666
+ }
667
+ if (hasValidRef(config)) {
668
+ ref = config.ref;
669
+ warnIfStringRefCannotBeAutoConverted(config, self);
670
+ }
671
+ for (propName in config) {
672
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
673
+ props[propName] = config[propName];
674
+ }
675
+ }
676
+ if (type && type.defaultProps) {
677
+ var defaultProps = type.defaultProps;
678
+ for (propName in defaultProps) {
679
+ if (props[propName] === void 0) {
680
+ props[propName] = defaultProps[propName];
681
+ }
682
+ }
683
+ }
684
+ if (key || ref) {
685
+ var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
686
+ if (key) {
687
+ defineKeyPropWarningGetter(props, displayName);
688
+ }
689
+ if (ref) {
690
+ defineRefPropWarningGetter(props, displayName);
691
+ }
692
+ }
693
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
694
+ }
695
+ }
696
+ var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
697
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
698
+ function setCurrentlyValidatingElement$1(element) {
699
+ {
700
+ if (element) {
701
+ var owner = element._owner;
702
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
703
+ ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
704
+ } else {
705
+ ReactDebugCurrentFrame$1.setExtraStackFrame(null);
706
+ }
707
+ }
708
+ }
709
+ var propTypesMisspellWarningShown;
710
+ {
711
+ propTypesMisspellWarningShown = false;
712
+ }
713
+ function isValidElement(object) {
714
+ {
715
+ return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
716
+ }
717
+ }
718
+ function getDeclarationErrorAddendum() {
719
+ {
720
+ if (ReactCurrentOwner$1.current) {
721
+ var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
722
+ if (name) {
723
+ return "\n\nCheck the render method of `" + name + "`.";
724
+ }
725
+ }
726
+ return "";
727
+ }
728
+ }
729
+ function getSourceInfoErrorAddendum(source) {
730
+ {
731
+ if (source !== void 0) {
732
+ var fileName = source.fileName.replace(/^.*[\\\/]/, "");
733
+ var lineNumber = source.lineNumber;
734
+ return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
735
+ }
736
+ return "";
737
+ }
738
+ }
739
+ var ownerHasKeyUseWarning = {};
740
+ function getCurrentComponentErrorInfo(parentType) {
741
+ {
742
+ var info = getDeclarationErrorAddendum();
743
+ if (!info) {
744
+ var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
745
+ if (parentName) {
746
+ info = "\n\nCheck the top-level render call using <" + parentName + ">.";
747
+ }
748
+ }
749
+ return info;
750
+ }
751
+ }
752
+ function validateExplicitKey(element, parentType) {
753
+ {
754
+ if (!element._store || element._store.validated || element.key != null) {
755
+ return;
756
+ }
757
+ element._store.validated = true;
758
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
759
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
760
+ return;
761
+ }
762
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
763
+ var childOwner = "";
764
+ if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
765
+ childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
766
+ }
767
+ setCurrentlyValidatingElement$1(element);
768
+ error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
769
+ setCurrentlyValidatingElement$1(null);
770
+ }
771
+ }
772
+ function validateChildKeys(node, parentType) {
773
+ {
774
+ if (typeof node !== "object") {
775
+ return;
776
+ }
777
+ if (isArray(node)) {
778
+ for (var i = 0; i < node.length; i++) {
779
+ var child = node[i];
780
+ if (isValidElement(child)) {
781
+ validateExplicitKey(child, parentType);
782
+ }
783
+ }
784
+ } else if (isValidElement(node)) {
785
+ if (node._store) {
786
+ node._store.validated = true;
787
+ }
788
+ } else if (node) {
789
+ var iteratorFn = getIteratorFn(node);
790
+ if (typeof iteratorFn === "function") {
791
+ if (iteratorFn !== node.entries) {
792
+ var iterator = iteratorFn.call(node);
793
+ var step;
794
+ while (!(step = iterator.next()).done) {
795
+ if (isValidElement(step.value)) {
796
+ validateExplicitKey(step.value, parentType);
797
+ }
798
+ }
799
+ }
800
+ }
801
+ }
802
+ }
803
+ }
804
+ function validatePropTypes(element) {
805
+ {
806
+ var type = element.type;
807
+ if (type === null || type === void 0 || typeof type === "string") {
808
+ return;
809
+ }
810
+ var propTypes;
811
+ if (typeof type === "function") {
812
+ propTypes = type.propTypes;
813
+ } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
814
+ // Inner props are checked in the reconciler.
815
+ type.$$typeof === REACT_MEMO_TYPE)) {
816
+ propTypes = type.propTypes;
817
+ } else {
818
+ return;
819
+ }
820
+ if (propTypes) {
821
+ var name = getComponentNameFromType(type);
822
+ checkPropTypes(propTypes, element.props, "prop", name, element);
823
+ } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
824
+ propTypesMisspellWarningShown = true;
825
+ var _name = getComponentNameFromType(type);
826
+ error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
827
+ }
828
+ if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
829
+ error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
830
+ }
831
+ }
832
+ }
833
+ function validateFragmentProps(fragment) {
834
+ {
835
+ var keys = Object.keys(fragment.props);
836
+ for (var i = 0; i < keys.length; i++) {
837
+ var key = keys[i];
838
+ if (key !== "children" && key !== "key") {
839
+ setCurrentlyValidatingElement$1(fragment);
840
+ error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
841
+ setCurrentlyValidatingElement$1(null);
842
+ break;
843
+ }
844
+ }
845
+ if (fragment.ref !== null) {
846
+ setCurrentlyValidatingElement$1(fragment);
847
+ error("Invalid attribute `ref` supplied to `React.Fragment`.");
848
+ setCurrentlyValidatingElement$1(null);
849
+ }
850
+ }
851
+ }
852
+ function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
853
+ {
854
+ var validType = isValidElementType(type);
855
+ if (!validType) {
856
+ var info = "";
857
+ if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
858
+ info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
859
+ }
860
+ var sourceInfo = getSourceInfoErrorAddendum(source);
861
+ if (sourceInfo) {
862
+ info += sourceInfo;
863
+ } else {
864
+ info += getDeclarationErrorAddendum();
865
+ }
866
+ var typeString;
867
+ if (type === null) {
868
+ typeString = "null";
869
+ } else if (isArray(type)) {
870
+ typeString = "array";
871
+ } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
872
+ typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
873
+ info = " Did you accidentally export a JSX literal instead of a component?";
874
+ } else {
875
+ typeString = typeof type;
876
+ }
877
+ error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
878
+ }
879
+ var element = jsxDEV(type, props, key, source, self);
880
+ if (element == null) {
881
+ return element;
882
+ }
883
+ if (validType) {
884
+ var children = props.children;
885
+ if (children !== void 0) {
886
+ if (isStaticChildren) {
887
+ if (isArray(children)) {
888
+ for (var i = 0; i < children.length; i++) {
889
+ validateChildKeys(children[i], type);
890
+ }
891
+ if (Object.freeze) {
892
+ Object.freeze(children);
893
+ }
894
+ } else {
895
+ error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
896
+ }
897
+ } else {
898
+ validateChildKeys(children, type);
899
+ }
900
+ }
901
+ }
902
+ if (type === REACT_FRAGMENT_TYPE) {
903
+ validateFragmentProps(element);
904
+ } else {
905
+ validatePropTypes(element);
906
+ }
907
+ return element;
908
+ }
909
+ }
910
+ function jsxWithValidationStatic(type, props, key) {
911
+ {
912
+ return jsxWithValidation(type, props, key, true);
913
+ }
914
+ }
915
+ function jsxWithValidationDynamic(type, props, key) {
916
+ {
917
+ return jsxWithValidation(type, props, key, false);
918
+ }
919
+ }
920
+ var jsx = jsxWithValidationDynamic;
921
+ var jsxs = jsxWithValidationStatic;
922
+ reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
923
+ reactJsxRuntime_development.jsx = jsx;
924
+ reactJsxRuntime_development.jsxs = jsxs;
925
+ })();
926
+ }
927
+ return reactJsxRuntime_development;
928
+ }
929
+ if (process.env.NODE_ENV === "production") {
930
+ jsxRuntime.exports = requireReactJsxRuntime_production_min();
931
+ } else {
932
+ jsxRuntime.exports = requireReactJsxRuntime_development();
933
+ }
934
+ var jsxRuntimeExports = jsxRuntime.exports;
935
+ function m(n, e, ...t) {
936
+ if (import.meta.NODE_ENV !== "production" && e === void 0)
937
+ throw new Error("invariant requires an error message argument");
938
+ if (!n) {
939
+ let o;
940
+ if (e === void 0)
941
+ o = new Error(
942
+ "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings."
943
+ );
944
+ else {
945
+ let s = 0;
946
+ o = new Error(
947
+ e.replace(/%s/g, function() {
948
+ return t[s++];
949
+ })
950
+ ), o.name = "Invariant Violation";
951
+ }
952
+ throw o.framesToPop = 1, o;
953
+ }
954
+ }
955
+ const l = (n) => typeof n == "function", P = (n) => n.length === 0, j = (n) => n.toString(), w = (n) => typeof n == "string", C = "/", h = "||";
956
+ const p = (n) => n, v = (n) => n === null;
957
+ function A(n, e = p, t) {
958
+ m(
959
+ l(e) || v(e),
960
+ "Expected payloadCreator to be a function, undefined or null"
961
+ );
962
+ const o = v(e) || e === p ? p : (i, ...u) => i instanceof Error ? i : e(i, ...u), s = l(t), c = n.toString(), r = (...i) => {
963
+ const u = o(...i), f = { type: n };
964
+ return u instanceof Error && (f.error = true), u !== void 0 && (f.payload = u), s && (f.meta = t(...i)), f;
965
+ };
966
+ return r.toString = () => c, r;
967
+ }
968
+ const g = (n) => {
969
+ if (typeof n != "object" || n === null)
970
+ return false;
971
+ let e = n;
972
+ for (; Object.getPrototypeOf(e) !== null; )
973
+ e = Object.getPrototypeOf(e);
974
+ return Object.getPrototypeOf(n) === e;
975
+ }, x = (n) => Array.isArray(n), T = (n) => n == null, Z = (n) => n[n.length - 1], K = /\s/, _ = /([-.:_])/, q = /([a-z][A-Z]|[A-Z][a-z])/, O = "/", G = /[\W_]+(.|$)/g, Y = (n) => n.replace(G, (e, t) => t ? " " + t : ""), B = /(.)([A-Z]+)/g, H = (n) => n.replace(
976
+ B,
977
+ (e, t, o) => t + " " + o.toLowerCase().split("").join(" ")
978
+ ), J = (n) => K.test(n) ? n.toLowerCase() : _.test(n) ? (Y(n) || n).toLowerCase() : q.test(n) ? H(n).toLowerCase() : n.toLowerCase(), Q = (n) => J(n).replace(/[\W_]+(.|$)/g, (e, t) => t ? " " + t : "").trim(), I = (n) => Q(n).replace(
979
+ /\s(\w)/g,
980
+ (e, t) => t.toUpperCase()
981
+ ), R = (n) => n.includes(O) ? n.split(O).map(I).join(O) : I(n), S = (n, e) => n.reduce(
982
+ (t, o) => e(t, o),
983
+ {}
984
+ ), b = (n) => typeof Map < "u" && n instanceof Map;
985
+ function $(n) {
986
+ if (b(n))
987
+ return Array.from(n.keys());
988
+ if (typeof Reflect < "u" && typeof Reflect.ownKeys == "function")
989
+ return Reflect.ownKeys(n);
990
+ let e = Object.getOwnPropertyNames(n);
991
+ return typeof Object.getOwnPropertySymbols == "function" && (e = e.concat(Object.getOwnPropertySymbols(n))), e;
992
+ }
993
+ function L(n, e) {
994
+ return b(e) ? e.get(n) : e[n];
995
+ }
996
+ const M = (n) => function e(t, { namespace: o = C, prefix: s } = {}, c = {}, r = "") {
997
+ function i(f) {
998
+ if (!r)
999
+ return f;
1000
+ const d = f.toString().split(h), a = r.split(h);
1001
+ return [].concat(
1002
+ ...a.map((E) => d.map((y) => `${E}${o}${y}`))
1003
+ ).join(h);
1004
+ }
1005
+ function u(f) {
1006
+ return r || !s || s && new RegExp(`^${s}${o}`).test(f) ? f : `${s}${o}${f}`;
1007
+ }
1008
+ return $(t).forEach((f) => {
1009
+ const d = u(i(f)), a = L(f, t);
1010
+ n(a) ? e(a, { namespace: o, prefix: s }, c, d) : c[d] = a;
1011
+ }), c;
1012
+ }, X = M(g);
1013
+ function k(n, { namespace: e = C, prefix: t } = {}) {
1014
+ function o(c, r, i) {
1015
+ const u = R(i.shift());
1016
+ P(i) ? r[u] = n[c] : (r[u] || (r[u] = {}), o(
1017
+ c,
1018
+ r[u],
1019
+ i
1020
+ ));
1021
+ }
1022
+ const s = {};
1023
+ return Object.getOwnPropertyNames(n).forEach((c) => {
1024
+ const r = t ? c.replace(`${t}${e}`, "") : c;
1025
+ return o(
1026
+ c,
1027
+ s,
1028
+ r.split(e)
1029
+ );
1030
+ }), s;
1031
+ }
1032
+ function fn(n, ...e) {
1033
+ const t = g(Z(e)) ? e.pop() : {};
1034
+ return m(
1035
+ e.every(w) && (w(n) || g(n)),
1036
+ "Expected optional object followed by string action types"
1037
+ ), w(n) ? N(
1038
+ [n, ...e],
1039
+ t
1040
+ ) : {
1041
+ ...F(n, t),
1042
+ ...N(e, t)
1043
+ };
1044
+ }
1045
+ function F(n, e) {
1046
+ const t = X(n, e), o = U(t);
1047
+ return k(o, e);
1048
+ }
1049
+ function U(n, { prefix: e, namespace: t = C } = {}) {
1050
+ function o(s) {
1051
+ if (l(s) || T(s))
1052
+ return true;
1053
+ if (x(s)) {
1054
+ const [c = p, r] = s;
1055
+ return l(c) && l(r);
1056
+ }
1057
+ return false;
1058
+ }
1059
+ return S(
1060
+ Object.keys(n),
1061
+ (s, c) => {
1062
+ const r = n[c];
1063
+ m(
1064
+ o(r),
1065
+ `Expected function, undefined, null, or array with payload and meta functions for ${c}`
1066
+ );
1067
+ const i = e ? `${e}${t}${c}` : c, u = x(r) ? A(i, ...r) : A(i, r);
1068
+ return { ...s, [c]: u };
1069
+ }
1070
+ );
1071
+ }
1072
+ function N(n, e) {
1073
+ const t = S(
1074
+ n,
1075
+ (s, c) => ({ ...s, [c]: p })
1076
+ ), o = U(t, e);
1077
+ return S(
1078
+ Object.keys(o),
1079
+ (s, c) => ({
1080
+ ...s,
1081
+ [R(c)]: o[c]
1082
+ })
1083
+ );
1084
+ }
1085
+ const tn = (n) => n === void 0;
1086
+ function on(n, e = p, t) {
1087
+ const o = j(n).split(h);
1088
+ m(
1089
+ !tn(t),
1090
+ `defaultState for reducer handling ${o.join(", ")} should be defined`
1091
+ ), m(
1092
+ l(e) || g(e),
1093
+ "Expected reducer to be a function or object with next and throw reducers"
1094
+ );
1095
+ const [s, c] = l(e) ? [e, e] : [e.next, e.throw].map(
1096
+ (r) => T(r) ? p : r
1097
+ );
1098
+ return (r = t, i) => {
1099
+ const { type: u } = i;
1100
+ return !u || !o.includes(j(u)) ? r : (i.error === true ? c : s)(r, i);
1101
+ };
1102
+ }
1103
+ const rn = function() {
1104
+ for (var n = arguments.length, e = Array(n), t = 0; t < n; t++)
1105
+ e[t] = arguments[t];
1106
+ var o = typeof e[0] != "function" && e.shift(), s = e;
1107
+ if (typeof o > "u")
1108
+ throw new TypeError("The initial state may not be undefined. If you do not want to set a value for this reducer, you can use null instead of undefined.");
1109
+ return function(c, r) {
1110
+ for (var i = arguments.length, u = Array(i > 2 ? i - 2 : 0), f = 2; f < i; f++)
1111
+ u[f - 2] = arguments[f];
1112
+ var d = typeof c > "u", a = typeof r > "u";
1113
+ return d && a && o ? o : s.reduce(function(E, y, V) {
1114
+ if (typeof y > "u")
1115
+ throw new TypeError("An undefined reducer was passed in at index " + V);
1116
+ return y.apply(void 0, [E, r].concat(u));
1117
+ }, d && !a && o ? o : c);
1118
+ };
1119
+ };
1120
+ function cn(n) {
1121
+ const e = $(n), t = e.every(
1122
+ (o) => o === "next" || o === "throw"
1123
+ );
1124
+ return e.length > 0 && e.length <= 2 && t;
1125
+ }
1126
+ const sn = M(
1127
+ (n) => (g(n) || b(n)) && !cn(n)
1128
+ );
1129
+ function ln(n, e, t = {}) {
1130
+ m(
1131
+ g(n) || b(n),
1132
+ "Expected handlers to be a plain object."
1133
+ );
1134
+ const o = sn(n, t), s = $(o).map(
1135
+ (r) => on(r, L(r, o), e)
1136
+ ), c = rn(e, ...s);
1137
+ return (r = e, i) => c(r, i);
1138
+ }
1139
+ function parseXPath(xpath) {
1140
+ if (!xpath || xpath === "/") {
1141
+ return [];
1142
+ }
1143
+ const path = xpath.startsWith("/") ? xpath.slice(1) : xpath;
1144
+ const segments = path.split("/").filter((segment) => segment.length > 0);
1145
+ return segments.map((segment) => {
1146
+ const arrayMatch = segment.match(/^(.+)\[(\d+)\]$/);
1147
+ if (arrayMatch) {
1148
+ return {
1149
+ property: arrayMatch[1],
1150
+ index: parseInt(arrayMatch[2], 10),
1151
+ isArray: true
1152
+ };
1153
+ }
1154
+ return { property: segment };
1155
+ });
1156
+ }
1157
+ function combineXPaths(base, relative) {
1158
+ if (relative.startsWith("/")) {
1159
+ return relative;
1160
+ }
1161
+ if (relative === "..") {
1162
+ const segments = parseXPath(base);
1163
+ if (segments.length === 0)
1164
+ return "/";
1165
+ const result2 = segments.slice(0, -1).map(formatSegment).join("/");
1166
+ return result2 === "" ? "/" : "/" + result2;
1167
+ }
1168
+ if (relative.startsWith("../")) {
1169
+ const upLevels = (relative.match(/\.\.\//g) || []).length;
1170
+ const remainingPath = relative.replace(/^(\.\.\/)+/, "");
1171
+ const baseSegments2 = parseXPath(base);
1172
+ const newBaseSegments = baseSegments2.slice(0, Math.max(0, baseSegments2.length - upLevels));
1173
+ if (remainingPath) {
1174
+ const newSegments = parseXPath(remainingPath);
1175
+ const result3 = [...newBaseSegments, ...newSegments].map(formatSegment).join("/");
1176
+ return result3 === "" ? "/" : "/" + result3;
1177
+ }
1178
+ const result2 = newBaseSegments.map(formatSegment).join("/");
1179
+ return result2 === "" ? "/" : "/" + result2;
1180
+ }
1181
+ const baseSegments = parseXPath(base);
1182
+ const relativeSegments = parseXPath(relative);
1183
+ const result = [...baseSegments, ...relativeSegments].map(formatSegment).join("/");
1184
+ return result === "" ? "/" : "/" + result;
1185
+ }
1186
+ function formatSegment(segment) {
1187
+ if (segment.isArray && segment.index !== void 0) {
1188
+ return `${segment.property}[${segment.index}]`;
1189
+ }
1190
+ return segment.property;
1191
+ }
1192
+ function getDataAtXPath(data, xpath) {
1193
+ if (!xpath || xpath === "/") {
1194
+ return data;
1195
+ }
1196
+ const segments = parseXPath(xpath);
1197
+ let current = data;
1198
+ for (const segment of segments) {
1199
+ if (current === null || current === void 0) {
1200
+ return void 0;
1201
+ }
1202
+ if (segment.isArray && segment.index !== void 0) {
1203
+ const array = current[segment.property];
1204
+ if (!Array.isArray(array) || segment.index >= array.length) {
1205
+ return void 0;
1206
+ }
1207
+ current = array[segment.index];
1208
+ } else {
1209
+ current = current[segment.property];
1210
+ }
1211
+ }
1212
+ return current;
1213
+ }
1214
+ function setDataAtXPath(data, xpath, value, operation = "replace") {
1215
+ if (!xpath || xpath === "/") {
1216
+ if (operation === "merge" && typeof data === "object" && typeof value === "object") {
1217
+ return { ...data, ...value };
1218
+ }
1219
+ return operation === "delete" ? {} : value;
1220
+ }
1221
+ const segments = parseXPath(xpath);
1222
+ const result = { ...data };
1223
+ let current = result;
1224
+ for (let i = 0; i < segments.length - 1; i++) {
1225
+ const segment = segments[i];
1226
+ if (segment.isArray && segment.index !== void 0) {
1227
+ if (!current[segment.property] || !Array.isArray(current[segment.property])) {
1228
+ current[segment.property] = [];
1229
+ }
1230
+ current[segment.property] = [...current[segment.property]];
1231
+ while (current[segment.property].length <= segment.index) {
1232
+ current[segment.property].push({});
1233
+ }
1234
+ current = current[segment.property][segment.index];
1235
+ } else {
1236
+ if (!current[segment.property]) {
1237
+ current[segment.property] = {};
1238
+ } else {
1239
+ current[segment.property] = { ...current[segment.property] };
1240
+ }
1241
+ current = current[segment.property];
1242
+ }
1243
+ }
1244
+ const lastSegment = segments[segments.length - 1];
1245
+ if (lastSegment.isArray && lastSegment.index !== void 0) {
1246
+ if (!current[lastSegment.property] || !Array.isArray(current[lastSegment.property])) {
1247
+ current[lastSegment.property] = [];
1248
+ }
1249
+ current[lastSegment.property] = [...current[lastSegment.property]];
1250
+ if (operation === "delete") {
1251
+ current[lastSegment.property].splice(lastSegment.index, 1);
1252
+ } else if (operation === "append") {
1253
+ current[lastSegment.property].push(value);
1254
+ } else {
1255
+ while (current[lastSegment.property].length <= lastSegment.index) {
1256
+ current[lastSegment.property].push({});
1257
+ }
1258
+ if (operation === "merge" && typeof current[lastSegment.property][lastSegment.index] === "object" && typeof value === "object") {
1259
+ current[lastSegment.property][lastSegment.index] = {
1260
+ ...current[lastSegment.property][lastSegment.index],
1261
+ ...value
1262
+ };
1263
+ } else {
1264
+ current[lastSegment.property][lastSegment.index] = value;
1265
+ }
1266
+ }
1267
+ } else {
1268
+ if (operation === "delete") {
1269
+ delete current[lastSegment.property];
1270
+ } else if (operation === "append") {
1271
+ if (!current[lastSegment.property] || !Array.isArray(current[lastSegment.property])) {
1272
+ current[lastSegment.property] = [];
1273
+ } else {
1274
+ current[lastSegment.property] = [...current[lastSegment.property]];
1275
+ }
1276
+ current[lastSegment.property].push(value);
1277
+ } else if (operation === "merge" && typeof current[lastSegment.property] === "object" && typeof value === "object") {
1278
+ current[lastSegment.property] = { ...current[lastSegment.property], ...value };
1279
+ } else {
1280
+ current[lastSegment.property] = value;
1281
+ }
1282
+ }
1283
+ return result;
1284
+ }
1285
+ function extractXPathParams(pattern, actual) {
1286
+ const patternSegments = parseXPath(pattern);
1287
+ const actualSegments = parseXPath(actual);
1288
+ const params = {};
1289
+ if (patternSegments.length !== actualSegments.length) {
1290
+ return params;
1291
+ }
1292
+ for (let i = 0; i < patternSegments.length; i++) {
1293
+ const patternSeg = patternSegments[i];
1294
+ const actualSeg = actualSegments[i];
1295
+ if (patternSeg.property.startsWith(":")) {
1296
+ const paramName = patternSeg.property.slice(1);
1297
+ params[paramName] = actualSeg.property;
1298
+ } else if (patternSeg.property !== actualSeg.property) {
1299
+ return {};
1300
+ }
1301
+ if (patternSeg.isArray && actualSeg.isArray) {
1302
+ if (patternSeg.index !== void 0 && actualSeg.index !== void 0) {
1303
+ if (patternSeg.index !== actualSeg.index) {
1304
+ return {};
1305
+ }
1306
+ }
1307
+ } else if (patternSeg.isArray !== actualSeg.isArray) {
1308
+ return {};
1309
+ }
1310
+ }
1311
+ return params;
1312
+ }
1313
+ const defaultState = {
1314
+ data: {},
1315
+ xpath: "/",
1316
+ history: [],
1317
+ location: 0,
1318
+ asyncStates: {},
1319
+ pendingOperations: /* @__PURE__ */ new Set(),
1320
+ commandQueue: {
1321
+ pending: [],
1322
+ executing: /* @__PURE__ */ new Map(),
1323
+ maxConcurrent: 3
1324
+ },
1325
+ optimisticUpdates: {}
1326
+ };
1327
+ const reducer = ln({
1328
+ NAVIGATE: (state, action) => {
1329
+ let { history, location } = state;
1330
+ if (location > 0) {
1331
+ history = history.slice(0, history.length - location);
1332
+ }
1333
+ const newXPath = combineXPaths(state.xpath, action.payload);
1334
+ if (newXPath === state.xpath) {
1335
+ return state;
1336
+ }
1337
+ return {
1338
+ ...state,
1339
+ xpath: newXPath,
1340
+ history: [state.xpath, ...history],
1341
+ location: 0
1342
+ };
1343
+ },
1344
+ BACK: (state, action) => {
1345
+ const steps = Math.max(1, action.payload);
1346
+ const targetLocation = state.location + steps;
1347
+ if (targetLocation > state.history.length) {
1348
+ return state;
1349
+ }
1350
+ const historyIndex = targetLocation - 1;
1351
+ const newXPath = state.history[historyIndex];
1352
+ if (!newXPath) {
1353
+ return state;
1354
+ }
1355
+ return {
1356
+ ...state,
1357
+ xpath: newXPath,
1358
+ location: targetLocation
1359
+ };
1360
+ },
1361
+ FORWARD: (state, action) => {
1362
+ const steps = Math.max(1, action.payload);
1363
+ const targetLocation = state.location - steps;
1364
+ if (targetLocation < 0) {
1365
+ return state;
1366
+ }
1367
+ if (targetLocation === 0) {
1368
+ return state;
1369
+ }
1370
+ const historyIndex = targetLocation - 1;
1371
+ const newXPath = state.history[historyIndex];
1372
+ if (!newXPath) {
1373
+ return state;
1374
+ }
1375
+ return {
1376
+ ...state,
1377
+ xpath: newXPath,
1378
+ location: targetLocation
1379
+ };
1380
+ },
1381
+ DATA_OPERATION: (state, action) => {
1382
+ const { xpath, operation, data } = action.payload;
1383
+ const absoluteXPath = combineXPaths(state.xpath, xpath);
1384
+ const newData = setDataAtXPath(state.data, absoluteXPath, data, operation);
1385
+ return {
1386
+ ...state,
1387
+ data: newData
1388
+ };
1389
+ },
1390
+ ASYNC_START: (state, action) => {
1391
+ const { xpath, requestId, optimisticData } = action.payload;
1392
+ const absoluteXPath = combineXPaths(state.xpath, xpath);
1393
+ let newData = state.data;
1394
+ let newOptimisticUpdates = state.optimisticUpdates;
1395
+ if (optimisticData !== void 0) {
1396
+ const optimisticId = `${requestId}_${absoluteXPath}`;
1397
+ newOptimisticUpdates = {
1398
+ ...state.optimisticUpdates,
1399
+ [optimisticId]: {
1400
+ id: optimisticId,
1401
+ xpath: absoluteXPath,
1402
+ originalData: state.data,
1403
+ optimisticData,
1404
+ rollbackOnError: true
1405
+ }
1406
+ };
1407
+ newData = setDataAtXPath(state.data, absoluteXPath, optimisticData, "replace");
1408
+ }
1409
+ return {
1410
+ ...state,
1411
+ data: newData,
1412
+ asyncStates: {
1413
+ ...state.asyncStates,
1414
+ [absoluteXPath]: {
1415
+ status: "loading",
1416
+ timestamp: Date.now(),
1417
+ requestId
1418
+ }
1419
+ },
1420
+ pendingOperations: /* @__PURE__ */ new Set([...state.pendingOperations, requestId]),
1421
+ optimisticUpdates: newOptimisticUpdates
1422
+ };
1423
+ },
1424
+ ASYNC_SUCCESS: (state, action) => {
1425
+ const { xpath, requestId, data, timestamp } = action.payload;
1426
+ const absoluteXPath = combineXPaths(state.xpath, xpath);
1427
+ const newData = setDataAtXPath(state.data, absoluteXPath, data, "replace");
1428
+ const newPendingOperations = new Set(state.pendingOperations);
1429
+ newPendingOperations.delete(requestId);
1430
+ const optimisticId = `${requestId}_${absoluteXPath}`;
1431
+ const newOptimisticUpdates = { ...state.optimisticUpdates };
1432
+ delete newOptimisticUpdates[optimisticId];
1433
+ return {
1434
+ ...state,
1435
+ data: newData,
1436
+ asyncStates: {
1437
+ ...state.asyncStates,
1438
+ [absoluteXPath]: {
1439
+ status: "success",
1440
+ timestamp,
1441
+ requestId
1442
+ }
1443
+ },
1444
+ pendingOperations: newPendingOperations,
1445
+ optimisticUpdates: newOptimisticUpdates
1446
+ };
1447
+ },
1448
+ ASYNC_ERROR: (state, action) => {
1449
+ const { xpath, requestId, error, shouldRollback } = action.payload;
1450
+ const absoluteXPath = combineXPaths(state.xpath, xpath);
1451
+ const optimisticId = `${requestId}_${absoluteXPath}`;
1452
+ const optimisticUpdate = state.optimisticUpdates[optimisticId];
1453
+ let newData = state.data;
1454
+ const newOptimisticUpdates = { ...state.optimisticUpdates };
1455
+ if (shouldRollback && optimisticUpdate) {
1456
+ newData = optimisticUpdate.originalData;
1457
+ delete newOptimisticUpdates[optimisticId];
1458
+ }
1459
+ const newPendingOperations = new Set(state.pendingOperations);
1460
+ newPendingOperations.delete(requestId);
1461
+ return {
1462
+ ...state,
1463
+ data: newData,
1464
+ asyncStates: {
1465
+ ...state.asyncStates,
1466
+ [absoluteXPath]: {
1467
+ status: "error",
1468
+ error,
1469
+ timestamp: Date.now(),
1470
+ requestId
1471
+ }
1472
+ },
1473
+ pendingOperations: newPendingOperations,
1474
+ optimisticUpdates: newOptimisticUpdates
1475
+ };
1476
+ },
1477
+ ASYNC_CANCEL: (state, action) => {
1478
+ const { xpath, requestId } = action.payload;
1479
+ const absoluteXPath = combineXPaths(state.xpath, xpath);
1480
+ const optimisticId = `${requestId}_${absoluteXPath}`;
1481
+ const optimisticUpdate = state.optimisticUpdates[optimisticId];
1482
+ let newData = state.data;
1483
+ const newOptimisticUpdates = { ...state.optimisticUpdates };
1484
+ if (optimisticUpdate) {
1485
+ newData = optimisticUpdate.originalData;
1486
+ delete newOptimisticUpdates[optimisticId];
1487
+ }
1488
+ const newPendingOperations = new Set(state.pendingOperations);
1489
+ newPendingOperations.delete(requestId);
1490
+ return {
1491
+ ...state,
1492
+ data: newData,
1493
+ asyncStates: {
1494
+ ...state.asyncStates,
1495
+ [absoluteXPath]: {
1496
+ status: "idle",
1497
+ timestamp: Date.now(),
1498
+ requestId
1499
+ }
1500
+ },
1501
+ pendingOperations: newPendingOperations,
1502
+ optimisticUpdates: newOptimisticUpdates
1503
+ };
1504
+ },
1505
+ COMMAND_QUEUE_UPDATE: (state, action) => {
1506
+ const { operation, command, commandId } = action.payload;
1507
+ switch (operation) {
1508
+ case "add":
1509
+ if (!command)
1510
+ return state;
1511
+ return {
1512
+ ...state,
1513
+ commandQueue: {
1514
+ ...state.commandQueue,
1515
+ pending: [...state.commandQueue.pending, command]
1516
+ }
1517
+ };
1518
+ case "execute":
1519
+ if (!command)
1520
+ return state;
1521
+ const newExecuting = new Map(state.commandQueue.executing);
1522
+ newExecuting.set(command.id, command);
1523
+ return {
1524
+ ...state,
1525
+ commandQueue: {
1526
+ ...state.commandQueue,
1527
+ pending: state.commandQueue.pending.filter((c) => c.id !== command.id),
1528
+ executing: newExecuting
1529
+ }
1530
+ };
1531
+ case "remove":
1532
+ if (!commandId)
1533
+ return state;
1534
+ const updatedExecuting = new Map(state.commandQueue.executing);
1535
+ updatedExecuting.delete(commandId);
1536
+ return {
1537
+ ...state,
1538
+ commandQueue: {
1539
+ ...state.commandQueue,
1540
+ executing: updatedExecuting
1541
+ }
1542
+ };
1543
+ default:
1544
+ return state;
1545
+ }
1546
+ }
1547
+ }, defaultState);
1548
+ const DataContext = createContext(defaultState);
1549
+ const DataDispatchContext = createContext(null);
1550
+ const DataRouteContext = createContext({
1551
+ xpath: "/",
1552
+ data: {},
1553
+ targetData: {},
1554
+ params: {}
1555
+ });
1556
+ function DataProvider({ initialData = {}, initialXPath = "/", children }) {
1557
+ const initialState = useMemo(() => ({
1558
+ data: initialData,
1559
+ xpath: initialXPath,
1560
+ history: [],
1561
+ location: 0,
1562
+ asyncStates: {},
1563
+ pendingOperations: /* @__PURE__ */ new Set(),
1564
+ commandQueue: {
1565
+ pending: [],
1566
+ executing: /* @__PURE__ */ new Map(),
1567
+ maxConcurrent: 3
1568
+ },
1569
+ optimisticUpdates: {}
1570
+ }), [initialData, initialXPath]);
1571
+ const [state, dispatch] = useReducer(reducer, initialState);
1572
+ const dataContextValue = useMemo(() => state, [
1573
+ state.data,
1574
+ state.xpath,
1575
+ state.history,
1576
+ state.location,
1577
+ state.asyncStates,
1578
+ state.pendingOperations,
1579
+ state.commandQueue,
1580
+ state.optimisticUpdates
1581
+ ]);
1582
+ const dispatchContextValue = useMemo(() => dispatch, [dispatch]);
1583
+ const routeContextValue = useMemo(() => {
1584
+ const targetData = getDataAtXPath(state.data, state.xpath);
1585
+ const params = extractXPathParams("*", state.xpath);
1586
+ return {
1587
+ xpath: state.xpath,
1588
+ data: state.data,
1589
+ targetData,
1590
+ params
1591
+ };
1592
+ }, [state.data, state.xpath]);
1593
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(DataContext.Provider, { value: dataContextValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(DataDispatchContext.Provider, { value: dispatchContextValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(DataRouteContext.Provider, { value: routeContextValue, children }) }) });
1594
+ }
1595
+ const {
1596
+ navigate,
1597
+ back,
1598
+ forward,
1599
+ dataOperation,
1600
+ asyncStart,
1601
+ asyncSuccess,
1602
+ asyncError,
1603
+ asyncCancel,
1604
+ commandQueueUpdate
1605
+ } = fn({
1606
+ NAVIGATE: (xpath) => xpath,
1607
+ BACK: (count = 1) => Math.max(1, count),
1608
+ FORWARD: (count = 1) => Math.max(1, count),
1609
+ DATA_OPERATION: (xpath, operation, data) => ({ xpath, operation, data }),
1610
+ ASYNC_START: (xpath, requestId, operation, priority = "normal", optimisticData) => ({ xpath, requestId, operation, priority, optimisticData }),
1611
+ ASYNC_SUCCESS: (xpath, requestId, data, timestamp = Date.now()) => ({ xpath, requestId, data, timestamp }),
1612
+ ASYNC_ERROR: (xpath, requestId, error, shouldRollback = true) => ({ xpath, requestId, error, shouldRollback }),
1613
+ ASYNC_CANCEL: (xpath, requestId) => ({ xpath, requestId }),
1614
+ COMMAND_QUEUE_UPDATE: (operation, command, commandId) => ({ operation, command, commandId })
1615
+ });
1616
+ function generateRequestId() {
1617
+ return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1618
+ }
1619
+ function useNavigate() {
1620
+ const dispatch = useContext(DataDispatchContext);
1621
+ if (!dispatch) {
1622
+ throw new Error("useNavigate must be used within a DataProvider");
1623
+ }
1624
+ return (xpath) => dispatch(navigate(xpath));
1625
+ }
1626
+ function useNavigation() {
1627
+ const dispatch = useContext(DataDispatchContext);
1628
+ const dataState = useContext(DataContext);
1629
+ if (!dispatch || !dataState) {
1630
+ throw new Error("useNavigation must be used within a DataProvider");
1631
+ }
1632
+ return {
1633
+ navigate: (xpath) => dispatch(navigate(xpath)),
1634
+ back: (count = 1) => dispatch(back(count)),
1635
+ forward: (count = 1) => dispatch(forward(count)),
1636
+ hasBack: dataState.location < dataState.history.length,
1637
+ hasForward: dataState.location > 0,
1638
+ xpath: dataState.xpath,
1639
+ history: dataState.history,
1640
+ location: dataState.location
1641
+ };
1642
+ }
1643
+ function useHistory() {
1644
+ const dataState = useContext(DataContext);
1645
+ if (!dataState) {
1646
+ throw new Error("useHistory must be used within a DataProvider");
1647
+ }
1648
+ return dataState.history;
1649
+ }
1650
+ function useXPath() {
1651
+ const dataState = useContext(DataContext);
1652
+ if (!dataState) {
1653
+ throw new Error("useXPath must be used within a DataProvider");
1654
+ }
1655
+ return dataState.xpath;
1656
+ }
1657
+ function useData() {
1658
+ const dataState = useContext(DataContext);
1659
+ if (!dataState) {
1660
+ throw new Error("useData must be used within a DataProvider");
1661
+ }
1662
+ return dataState.data;
1663
+ }
1664
+ function useTargetData() {
1665
+ const routeContext = useContext(DataRouteContext);
1666
+ if (!routeContext) {
1667
+ throw new Error("useTargetData must be used within a DataProvider");
1668
+ }
1669
+ return routeContext.targetData;
1670
+ }
1671
+ function useDataAtXPath(xpath) {
1672
+ const dataState = useContext(DataContext);
1673
+ if (!dataState) {
1674
+ throw new Error("useDataAtXPath must be used within a DataProvider");
1675
+ }
1676
+ return getDataAtXPath(dataState.data, xpath);
1677
+ }
1678
+ function useDataManipulation() {
1679
+ const dispatch = useContext(DataDispatchContext);
1680
+ if (!dispatch) {
1681
+ throw new Error("useDataManipulation must be used within a DataProvider");
1682
+ }
1683
+ return {
1684
+ setData: (xpath, data, operation = "replace") => {
1685
+ dispatch(dataOperation(xpath, operation, data));
1686
+ },
1687
+ mergeData: (xpath, data) => {
1688
+ dispatch(dataOperation(xpath, "merge", data));
1689
+ },
1690
+ replaceData: (xpath, data) => {
1691
+ dispatch(dataOperation(xpath, "replace", data));
1692
+ },
1693
+ appendData: (xpath, data) => {
1694
+ dispatch(dataOperation(xpath, "append", data));
1695
+ },
1696
+ deleteData: (xpath) => {
1697
+ dispatch(dataOperation(xpath, "delete", null));
1698
+ }
1699
+ };
1700
+ }
1701
+ class CommandQueueManager {
1702
+ constructor(dispatch, maxConcurrent = 3) {
1703
+ __publicField(this, "queue", {
1704
+ pending: [],
1705
+ executing: /* @__PURE__ */ new Map(),
1706
+ maxConcurrent: 3
1707
+ });
1708
+ __publicField(this, "dispatch");
1709
+ __publicField(this, "destroyed", false);
1710
+ this.dispatch = dispatch;
1711
+ this.queue = { ...this.queue, maxConcurrent };
1712
+ }
1713
+ destroy() {
1714
+ this.destroyed = true;
1715
+ this.queue.executing.forEach((command) => {
1716
+ command.abortController.abort();
1717
+ });
1718
+ this.queue = {
1719
+ pending: [],
1720
+ executing: /* @__PURE__ */ new Map(),
1721
+ maxConcurrent: this.queue.maxConcurrent
1722
+ };
1723
+ }
1724
+ createCommand(xpath, operation, promise, priority = "normal") {
1725
+ const abortController = new AbortController();
1726
+ const commandId = generateRequestId();
1727
+ const wrappedPromise = promise.then(
1728
+ (result) => {
1729
+ this.removeFromExecuting(commandId);
1730
+ return result;
1731
+ },
1732
+ (error) => {
1733
+ this.removeFromExecuting(commandId);
1734
+ throw error;
1735
+ }
1736
+ );
1737
+ return {
1738
+ id: commandId,
1739
+ xpath,
1740
+ operation,
1741
+ abortController,
1742
+ promise: wrappedPromise,
1743
+ timestamp: Date.now(),
1744
+ priority
1745
+ };
1746
+ }
1747
+ enqueue(command) {
1748
+ if (this.destroyed)
1749
+ return;
1750
+ this.queue = {
1751
+ ...this.queue,
1752
+ pending: [...this.queue.pending, command]
1753
+ };
1754
+ this.dispatch({
1755
+ type: "COMMAND_QUEUE_UPDATE",
1756
+ payload: { operation: "add", command }
1757
+ });
1758
+ this.processQueue();
1759
+ }
1760
+ cancel(commandId) {
1761
+ const executingCommand = this.queue.executing.get(commandId);
1762
+ if (executingCommand) {
1763
+ executingCommand.abortController.abort();
1764
+ this.removeFromExecuting(commandId);
1765
+ }
1766
+ this.queue = {
1767
+ ...this.queue,
1768
+ pending: this.queue.pending.filter((cmd) => cmd.id !== commandId)
1769
+ };
1770
+ }
1771
+ cancelByXPath(xpath) {
1772
+ this.queue.executing.forEach((command, id) => {
1773
+ if (command.xpath === xpath) {
1774
+ command.abortController.abort();
1775
+ this.removeFromExecuting(id);
1776
+ }
1777
+ });
1778
+ this.queue = {
1779
+ ...this.queue,
1780
+ pending: this.queue.pending.filter((cmd) => cmd.xpath !== xpath)
1781
+ };
1782
+ }
1783
+ processQueue() {
1784
+ if (this.destroyed)
1785
+ return;
1786
+ while (this.queue.executing.size < this.queue.maxConcurrent && this.queue.pending.length > 0) {
1787
+ const sortedPending = [...this.queue.pending].sort((a, b2) => {
1788
+ const priorityOrder = { high: 3, normal: 2, low: 1 };
1789
+ return priorityOrder[b2.priority] - priorityOrder[a.priority] || a.timestamp - b2.timestamp;
1790
+ });
1791
+ const command = sortedPending[0];
1792
+ if (command) {
1793
+ this.executeCommand(command);
1794
+ } else {
1795
+ break;
1796
+ }
1797
+ }
1798
+ }
1799
+ executeCommand(command) {
1800
+ if (this.destroyed)
1801
+ return;
1802
+ const newExecuting = new Map(this.queue.executing);
1803
+ newExecuting.set(command.id, command);
1804
+ this.queue = {
1805
+ ...this.queue,
1806
+ pending: this.queue.pending.filter((c) => c.id !== command.id),
1807
+ executing: newExecuting
1808
+ };
1809
+ this.dispatch({
1810
+ type: "COMMAND_QUEUE_UPDATE",
1811
+ payload: { operation: "execute", command }
1812
+ });
1813
+ command.promise.catch(() => {
1814
+ });
1815
+ }
1816
+ removeFromExecuting(commandId) {
1817
+ const updatedExecuting = new Map(this.queue.executing);
1818
+ updatedExecuting.delete(commandId);
1819
+ this.queue = {
1820
+ ...this.queue,
1821
+ executing: updatedExecuting
1822
+ };
1823
+ this.dispatch({
1824
+ type: "COMMAND_QUEUE_UPDATE",
1825
+ payload: { operation: "remove", commandId }
1826
+ });
1827
+ queueMicrotask(() => this.processQueue());
1828
+ }
1829
+ updateQueue(newQueue) {
1830
+ this.queue = newQueue;
1831
+ }
1832
+ hasPendingOperations(xpath) {
1833
+ if (!xpath) {
1834
+ return this.queue.pending.length > 0 || this.queue.executing.size > 0;
1835
+ }
1836
+ return this.queue.pending.some((cmd) => cmd.xpath === xpath) || Array.from(this.queue.executing.values()).some((cmd) => cmd.xpath === xpath);
1837
+ }
1838
+ getQueuedOperations(xpath) {
1839
+ const allCommands = [
1840
+ ...this.queue.pending,
1841
+ ...Array.from(this.queue.executing.values())
1842
+ ];
1843
+ return xpath ? allCommands.filter((cmd) => cmd.xpath === xpath) : allCommands;
1844
+ }
1845
+ }
1846
+ function useAsyncData(xpath, fetcher, config = {}) {
1847
+ const dataState = useContext(DataContext);
1848
+ const dispatch = useContext(DataDispatchContext);
1849
+ if (!dataState || !dispatch) {
1850
+ throw new Error("useAsyncData must be used within a DataProvider");
1851
+ }
1852
+ const {
1853
+ enabled = true,
1854
+ staleTime = 0,
1855
+ cacheTime = 5 * 60 * 1e3,
1856
+ // 5 minutes
1857
+ refetchOnWindowFocus = false,
1858
+ refetchOnReconnect = false,
1859
+ retryCount = 3,
1860
+ retryDelay = 1e3,
1861
+ onSuccess,
1862
+ onError
1863
+ } = config;
1864
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
1865
+ const asyncState = dataState.asyncStates[absoluteXPath];
1866
+ const currentData = getDataAtXPath(dataState.data, absoluteXPath);
1867
+ const commandQueueRef = useRef();
1868
+ const retryCountRef = useRef(0);
1869
+ const currentRequestIdRef = useRef();
1870
+ if (!commandQueueRef.current) {
1871
+ commandQueueRef.current = new CommandQueueManager(dispatch);
1872
+ }
1873
+ useEffect(() => {
1874
+ return () => {
1875
+ var _a;
1876
+ (_a = commandQueueRef.current) == null ? void 0 : _a.destroy();
1877
+ };
1878
+ }, []);
1879
+ useEffect(() => {
1880
+ if (commandQueueRef.current) {
1881
+ commandQueueRef.current.updateQueue(dataState.commandQueue);
1882
+ }
1883
+ }, [dataState.commandQueue]);
1884
+ const executeRequest = useCallback(async (requestId) => {
1885
+ try {
1886
+ dispatch(asyncStart(absoluteXPath, requestId, "fetch"));
1887
+ const result = await fetcher();
1888
+ dispatch(asyncSuccess(absoluteXPath, requestId, result));
1889
+ retryCountRef.current = 0;
1890
+ onSuccess == null ? void 0 : onSuccess(result);
1891
+ return result;
1892
+ } catch (error) {
1893
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
1894
+ if (retryCountRef.current < retryCount) {
1895
+ retryCountRef.current++;
1896
+ const delay = retryDelay * Math.pow(2, retryCountRef.current - 1);
1897
+ await new Promise((resolve) => setTimeout(resolve, delay));
1898
+ return executeRequest(requestId);
1899
+ }
1900
+ dispatch(asyncError(absoluteXPath, requestId, errorInstance, false));
1901
+ onError == null ? void 0 : onError(errorInstance);
1902
+ throw errorInstance;
1903
+ }
1904
+ }, [absoluteXPath, fetcher, dispatch, retryCount, retryDelay, onSuccess, onError]);
1905
+ const refetch = useCallback(async () => {
1906
+ const requestId = generateRequestId();
1907
+ currentRequestIdRef.current = requestId;
1908
+ if (commandQueueRef.current) {
1909
+ const command = commandQueueRef.current.createCommand(
1910
+ absoluteXPath,
1911
+ "fetch",
1912
+ executeRequest(requestId),
1913
+ "normal"
1914
+ );
1915
+ commandQueueRef.current.enqueue(command);
1916
+ return command.promise;
1917
+ }
1918
+ return executeRequest(requestId);
1919
+ }, [absoluteXPath, executeRequest]);
1920
+ const cancel = useCallback(() => {
1921
+ if (currentRequestIdRef.current && commandQueueRef.current) {
1922
+ commandQueueRef.current.cancel(currentRequestIdRef.current);
1923
+ }
1924
+ }, []);
1925
+ const invalidate = useCallback(() => {
1926
+ if (commandQueueRef.current) {
1927
+ commandQueueRef.current.cancelByXPath(absoluteXPath);
1928
+ }
1929
+ if (asyncState) {
1930
+ dispatch({
1931
+ type: "ASYNC_CANCEL",
1932
+ payload: {
1933
+ xpath: absoluteXPath,
1934
+ requestId: asyncState.requestId || generateRequestId()
1935
+ }
1936
+ });
1937
+ }
1938
+ }, [absoluteXPath, asyncState, dispatch]);
1939
+ const isStale = useCallback(() => {
1940
+ if (!(asyncState == null ? void 0 : asyncState.timestamp))
1941
+ return true;
1942
+ return Date.now() - asyncState.timestamp > staleTime;
1943
+ }, [asyncState == null ? void 0 : asyncState.timestamp, staleTime]);
1944
+ useEffect(() => {
1945
+ if (enabled && (!asyncState || asyncState.status === "idle")) {
1946
+ refetch().catch(() => {
1947
+ });
1948
+ }
1949
+ }, [enabled, absoluteXPath]);
1950
+ useEffect(() => {
1951
+ if (!refetchOnWindowFocus)
1952
+ return;
1953
+ const handleFocus = () => {
1954
+ if (enabled && isStale()) {
1955
+ refetch().catch(() => {
1956
+ });
1957
+ }
1958
+ };
1959
+ window.addEventListener("focus", handleFocus);
1960
+ return () => window.removeEventListener("focus", handleFocus);
1961
+ }, [enabled, refetchOnWindowFocus, refetch, isStale]);
1962
+ useEffect(() => {
1963
+ if (!refetchOnReconnect)
1964
+ return;
1965
+ const handleOnline = () => {
1966
+ if (enabled && isStale()) {
1967
+ refetch().catch(() => {
1968
+ });
1969
+ }
1970
+ };
1971
+ window.addEventListener("online", handleOnline);
1972
+ return () => window.removeEventListener("online", handleOnline);
1973
+ }, [enabled, refetchOnReconnect, refetch, isStale]);
1974
+ useEffect(() => {
1975
+ return () => {
1976
+ if (cacheTime === 0) {
1977
+ invalidate();
1978
+ }
1979
+ };
1980
+ }, [cacheTime, invalidate]);
1981
+ const status = (asyncState == null ? void 0 : asyncState.status) || "idle";
1982
+ return {
1983
+ data: currentData,
1984
+ isLoading: status === "loading",
1985
+ isError: status === "error",
1986
+ isSuccess: status === "success",
1987
+ isIdle: status === "idle",
1988
+ error: asyncState == null ? void 0 : asyncState.error,
1989
+ refetch,
1990
+ cancel,
1991
+ invalidate
1992
+ };
1993
+ }
1994
+ function useAsyncMutation(xpath, mutationFn, config = {}) {
1995
+ const dataState = useContext(DataContext);
1996
+ const dispatch = useContext(DataDispatchContext);
1997
+ if (!dataState || !dispatch) {
1998
+ throw new Error("useAsyncMutation must be used within a DataProvider");
1999
+ }
2000
+ const {
2001
+ optimisticUpdate,
2002
+ rollbackOnError = true,
2003
+ invalidate = [],
2004
+ retryCount = 0,
2005
+ // Mutations typically don't retry by default
2006
+ retryDelay = 1e3,
2007
+ onSuccess,
2008
+ onError,
2009
+ onSettled
2010
+ } = config;
2011
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2012
+ const asyncState = dataState.asyncStates[absoluteXPath];
2013
+ const currentData = getDataAtXPath(dataState.data, absoluteXPath);
2014
+ const commandQueueRef = useRef();
2015
+ const retryCountRef = useRef(0);
2016
+ const lastVariablesRef = useRef();
2017
+ if (!commandQueueRef.current) {
2018
+ commandQueueRef.current = new CommandQueueManager(dispatch);
2019
+ commandQueueRef.current.updateQueue(dataState.commandQueue);
2020
+ }
2021
+ useEffect(() => {
2022
+ return () => {
2023
+ var _a;
2024
+ (_a = commandQueueRef.current) == null ? void 0 : _a.destroy();
2025
+ };
2026
+ }, []);
2027
+ const executeMutation = useCallback(async (variables, requestId) => {
2028
+ try {
2029
+ let optimisticData;
2030
+ if (optimisticUpdate && currentData !== void 0) {
2031
+ optimisticData = optimisticUpdate(currentData, variables);
2032
+ }
2033
+ dispatch(asyncStart(
2034
+ absoluteXPath,
2035
+ requestId,
2036
+ "mutate",
2037
+ "high",
2038
+ // Mutations get high priority
2039
+ optimisticData
2040
+ ));
2041
+ const result = await mutationFn(variables);
2042
+ dispatch(asyncSuccess(absoluteXPath, requestId, result));
2043
+ if (invalidate.length > 0 && commandQueueRef.current) {
2044
+ invalidate.forEach((path) => {
2045
+ const invalidatePath = combineXPaths(dataState.xpath, path);
2046
+ commandQueueRef.current.cancelByXPath(invalidatePath);
2047
+ dispatch({
2048
+ type: "ASYNC_CANCEL",
2049
+ payload: {
2050
+ xpath: invalidatePath,
2051
+ requestId: generateRequestId()
2052
+ }
2053
+ });
2054
+ });
2055
+ }
2056
+ retryCountRef.current = 0;
2057
+ onSuccess == null ? void 0 : onSuccess(result, variables);
2058
+ onSettled == null ? void 0 : onSettled(result, void 0, variables);
2059
+ return result;
2060
+ } catch (error) {
2061
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
2062
+ if (retryCountRef.current < retryCount) {
2063
+ retryCountRef.current++;
2064
+ const delay = retryDelay * Math.pow(2, retryCountRef.current - 1);
2065
+ await new Promise((resolve) => setTimeout(resolve, delay));
2066
+ return executeMutation(variables, requestId);
2067
+ }
2068
+ dispatch(asyncError(absoluteXPath, requestId, errorInstance, rollbackOnError));
2069
+ onError == null ? void 0 : onError(errorInstance, variables);
2070
+ onSettled == null ? void 0 : onSettled(void 0, errorInstance, variables);
2071
+ throw errorInstance;
2072
+ }
2073
+ }, [
2074
+ absoluteXPath,
2075
+ mutationFn,
2076
+ optimisticUpdate,
2077
+ currentData,
2078
+ dispatch,
2079
+ invalidate,
2080
+ dataState.xpath,
2081
+ retryCount,
2082
+ retryDelay,
2083
+ rollbackOnError,
2084
+ onSuccess,
2085
+ onError,
2086
+ onSettled
2087
+ ]);
2088
+ const mutateAsync = useCallback(async (variables) => {
2089
+ const requestId = generateRequestId();
2090
+ lastVariablesRef.current = variables;
2091
+ if (commandQueueRef.current) {
2092
+ const command = commandQueueRef.current.createCommand(
2093
+ absoluteXPath,
2094
+ "mutate",
2095
+ executeMutation(variables, requestId),
2096
+ "high"
2097
+ );
2098
+ commandQueueRef.current.enqueue(command);
2099
+ return command.promise;
2100
+ }
2101
+ return executeMutation(variables, requestId);
2102
+ }, [absoluteXPath, executeMutation]);
2103
+ const mutate = useCallback((variables) => {
2104
+ return mutateAsync(variables).catch((error) => {
2105
+ console.error("Mutation failed:", error);
2106
+ throw error;
2107
+ });
2108
+ }, [mutateAsync]);
2109
+ const reset = useCallback(() => {
2110
+ if ((asyncState == null ? void 0 : asyncState.requestId) && commandQueueRef.current) {
2111
+ commandQueueRef.current.cancel(asyncState.requestId);
2112
+ }
2113
+ dispatch({
2114
+ type: "ASYNC_CANCEL",
2115
+ payload: {
2116
+ xpath: absoluteXPath,
2117
+ requestId: (asyncState == null ? void 0 : asyncState.requestId) || generateRequestId()
2118
+ }
2119
+ });
2120
+ retryCountRef.current = 0;
2121
+ }, [absoluteXPath, asyncState == null ? void 0 : asyncState.requestId, dispatch]);
2122
+ const status = (asyncState == null ? void 0 : asyncState.status) || "idle";
2123
+ return {
2124
+ mutate,
2125
+ mutateAsync,
2126
+ reset,
2127
+ isLoading: status === "loading",
2128
+ isError: status === "error",
2129
+ isSuccess: status === "success",
2130
+ isIdle: status === "idle",
2131
+ data: currentData,
2132
+ error: asyncState == null ? void 0 : asyncState.error
2133
+ };
2134
+ }
2135
+ function useAsyncState(xpath) {
2136
+ const dataState = useContext(DataContext);
2137
+ if (!dataState) {
2138
+ throw new Error("useAsyncState must be used within a DataProvider");
2139
+ }
2140
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2141
+ const asyncState = dataState.asyncStates[absoluteXPath];
2142
+ const currentData = getDataAtXPath(dataState.data, absoluteXPath);
2143
+ const isPending = dataState.pendingOperations.has((asyncState == null ? void 0 : asyncState.requestId) || "");
2144
+ const asyncStateInfo = useMemo(() => {
2145
+ if (!asyncState)
2146
+ return void 0;
2147
+ return {
2148
+ ...asyncState,
2149
+ xpath: absoluteXPath,
2150
+ hasPendingOperation: isPending,
2151
+ isStale: (staleTime = 0) => {
2152
+ if (!asyncState.timestamp)
2153
+ return true;
2154
+ return Date.now() - asyncState.timestamp > staleTime;
2155
+ }
2156
+ };
2157
+ }, [asyncState, absoluteXPath, isPending]);
2158
+ const status = (asyncState == null ? void 0 : asyncState.status) || "idle";
2159
+ return {
2160
+ data: currentData,
2161
+ asyncState: asyncStateInfo,
2162
+ isLoading: status === "loading",
2163
+ isError: status === "error",
2164
+ isSuccess: status === "success",
2165
+ isIdle: status === "idle",
2166
+ error: asyncState == null ? void 0 : asyncState.error,
2167
+ isPending,
2168
+ lastUpdated: asyncState == null ? void 0 : asyncState.timestamp
2169
+ };
2170
+ }
2171
+ function useAsyncStates(xpaths) {
2172
+ const dataState = useContext(DataContext);
2173
+ if (!dataState) {
2174
+ throw new Error("useAsyncStates must be used within a DataProvider");
2175
+ }
2176
+ return useMemo(() => {
2177
+ const results = {};
2178
+ xpaths.forEach((xpath) => {
2179
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2180
+ const asyncState = dataState.asyncStates[absoluteXPath];
2181
+ const currentData = getDataAtXPath(dataState.data, absoluteXPath);
2182
+ const isPending = dataState.pendingOperations.has((asyncState == null ? void 0 : asyncState.requestId) || "");
2183
+ const asyncStateInfo = asyncState ? {
2184
+ ...asyncState,
2185
+ xpath: absoluteXPath,
2186
+ hasPendingOperation: isPending,
2187
+ isStale: (staleTime = 0) => {
2188
+ if (!asyncState.timestamp)
2189
+ return true;
2190
+ return Date.now() - asyncState.timestamp > staleTime;
2191
+ }
2192
+ } : void 0;
2193
+ const status = (asyncState == null ? void 0 : asyncState.status) || "idle";
2194
+ results[xpath] = {
2195
+ data: currentData,
2196
+ asyncState: asyncStateInfo,
2197
+ isLoading: status === "loading",
2198
+ isError: status === "error",
2199
+ isSuccess: status === "success",
2200
+ isIdle: status === "idle",
2201
+ error: asyncState == null ? void 0 : asyncState.error,
2202
+ isPending,
2203
+ lastUpdated: asyncState == null ? void 0 : asyncState.timestamp
2204
+ };
2205
+ });
2206
+ return results;
2207
+ }, [dataState, xpaths]);
2208
+ }
2209
+ function useGlobalAsyncState() {
2210
+ const dataState = useContext(DataContext);
2211
+ if (!dataState) {
2212
+ throw new Error("useGlobalAsyncState must be used within a DataProvider");
2213
+ }
2214
+ return useMemo(() => {
2215
+ const allStates = Object.entries(dataState.asyncStates);
2216
+ const pendingCount = dataState.pendingOperations.size;
2217
+ const executingCount = dataState.commandQueue.executing.size;
2218
+ const queuedCount = dataState.commandQueue.pending.length;
2219
+ const summary = {
2220
+ totalStates: allStates.length,
2221
+ loadingStates: allStates.filter(([, state]) => state.status === "loading").length,
2222
+ errorStates: allStates.filter(([, state]) => state.status === "error").length,
2223
+ successStates: allStates.filter(([, state]) => state.status === "success").length,
2224
+ idleStates: allStates.filter(([, state]) => state.status === "idle").length,
2225
+ pendingOperations: pendingCount,
2226
+ executingOperations: executingCount,
2227
+ queuedOperations: queuedCount,
2228
+ hasAnyLoading: allStates.some(([, state]) => state.status === "loading"),
2229
+ hasAnyError: allStates.some(([, state]) => state.status === "error"),
2230
+ optimisticUpdateCount: Object.keys(dataState.optimisticUpdates).length
2231
+ };
2232
+ const statesByStatus = {
2233
+ loading: allStates.filter(([, state]) => state.status === "loading"),
2234
+ error: allStates.filter(([, state]) => state.status === "error"),
2235
+ success: allStates.filter(([, state]) => state.status === "success"),
2236
+ idle: allStates.filter(([, state]) => state.status === "idle")
2237
+ };
2238
+ return {
2239
+ summary,
2240
+ statesByStatus,
2241
+ asyncStates: dataState.asyncStates,
2242
+ pendingOperations: dataState.pendingOperations,
2243
+ commandQueue: dataState.commandQueue,
2244
+ optimisticUpdates: dataState.optimisticUpdates
2245
+ };
2246
+ }, [dataState]);
2247
+ }
2248
+ function useAsyncBatch(operations, config = {}) {
2249
+ const dataState = useContext(DataContext);
2250
+ const dispatch = useContext(DataDispatchContext);
2251
+ if (!dataState || !dispatch) {
2252
+ throw new Error("useAsyncBatch must be used within a DataProvider");
2253
+ }
2254
+ const {
2255
+ concurrency = 3,
2256
+ failFast = false,
2257
+ retryCount = 1,
2258
+ retryDelay = 1e3,
2259
+ onBatchComplete,
2260
+ onBatchError
2261
+ } = config;
2262
+ const commandQueueRef = useRef();
2263
+ const resultsRef = useRef([]);
2264
+ const statusRef = useRef("idle");
2265
+ const batchIdRef = useRef();
2266
+ if (!commandQueueRef.current) {
2267
+ commandQueueRef.current = new CommandQueueManager(dispatch, concurrency);
2268
+ commandQueueRef.current.updateQueue(dataState.commandQueue);
2269
+ }
2270
+ useEffect(() => {
2271
+ return () => {
2272
+ var _a;
2273
+ (_a = commandQueueRef.current) == null ? void 0 : _a.destroy();
2274
+ };
2275
+ }, []);
2276
+ const executeOperation = useCallback(async (operation, retryAttempt = 0) => {
2277
+ var _a, _b;
2278
+ const absoluteXPath = combineXPaths(dataState.xpath, operation.xpath);
2279
+ const requestId = generateRequestId();
2280
+ try {
2281
+ dispatch(asyncStart(absoluteXPath, requestId, "fetch", operation.priority));
2282
+ const result = await operation.fetcher();
2283
+ dispatch(asyncSuccess(absoluteXPath, requestId, result));
2284
+ (_a = operation.onSuccess) == null ? void 0 : _a.call(operation, result);
2285
+ return {
2286
+ xpath: operation.xpath,
2287
+ status: "success",
2288
+ data: result
2289
+ };
2290
+ } catch (error) {
2291
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
2292
+ if (retryAttempt < retryCount) {
2293
+ const delay = retryDelay * Math.pow(2, retryAttempt);
2294
+ await new Promise((resolve) => setTimeout(resolve, delay));
2295
+ return executeOperation(operation, retryAttempt + 1);
2296
+ }
2297
+ dispatch(asyncError(absoluteXPath, requestId, errorInstance, false));
2298
+ (_b = operation.onError) == null ? void 0 : _b.call(operation, errorInstance);
2299
+ return {
2300
+ xpath: operation.xpath,
2301
+ status: "error",
2302
+ error: errorInstance
2303
+ };
2304
+ }
2305
+ }, [dataState.xpath, dispatch, retryCount, retryDelay]);
2306
+ const execute = useCallback(async () => {
2307
+ var _a;
2308
+ if (statusRef.current === "loading") {
2309
+ throw new Error("Batch operation is already in progress");
2310
+ }
2311
+ statusRef.current = "loading";
2312
+ batchIdRef.current = generateRequestId();
2313
+ resultsRef.current = operations.map((op) => ({
2314
+ xpath: op.xpath,
2315
+ status: "pending"
2316
+ }));
2317
+ try {
2318
+ const promises = operations.map(async (operation, index) => {
2319
+ try {
2320
+ const result = await executeOperation(operation);
2321
+ resultsRef.current[index] = result;
2322
+ if (failFast && result.status === "error" && commandQueueRef.current) {
2323
+ operations.slice(index + 1).forEach((op) => {
2324
+ const absoluteXPath = combineXPaths(dataState.xpath, op.xpath);
2325
+ commandQueueRef.current.cancelByXPath(absoluteXPath);
2326
+ });
2327
+ throw result.error;
2328
+ }
2329
+ return result;
2330
+ } catch (error) {
2331
+ const errorResult = {
2332
+ xpath: operation.xpath,
2333
+ status: "error",
2334
+ error: error instanceof Error ? error : new Error(String(error))
2335
+ };
2336
+ resultsRef.current[index] = errorResult;
2337
+ if (failFast) {
2338
+ throw error;
2339
+ }
2340
+ return errorResult;
2341
+ }
2342
+ });
2343
+ const results = await Promise.allSettled(promises);
2344
+ const finalResults = results.map(
2345
+ (result, index) => result.status === "fulfilled" ? result.value : {
2346
+ xpath: operations[index].xpath,
2347
+ status: "error",
2348
+ error: result.reason instanceof Error ? result.reason : new Error(String(result.reason))
2349
+ }
2350
+ );
2351
+ resultsRef.current = finalResults;
2352
+ const hasErrors = finalResults.some((r) => r.status === "error");
2353
+ statusRef.current = hasErrors ? "error" : "success";
2354
+ if (hasErrors && onBatchError) {
2355
+ const firstError = (_a = finalResults.find((r) => r.status === "error")) == null ? void 0 : _a.error;
2356
+ onBatchError(firstError || new Error("Batch operation failed"), finalResults);
2357
+ } else if (!hasErrors && onBatchComplete) {
2358
+ onBatchComplete(finalResults);
2359
+ }
2360
+ return finalResults;
2361
+ } catch (error) {
2362
+ statusRef.current = "error";
2363
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
2364
+ if (onBatchError) {
2365
+ onBatchError(errorInstance, resultsRef.current);
2366
+ }
2367
+ throw errorInstance;
2368
+ }
2369
+ }, [operations, executeOperation, failFast, onBatchComplete, onBatchError, dataState.xpath]);
2370
+ const cancel = useCallback(() => {
2371
+ if (commandQueueRef.current && batchIdRef.current) {
2372
+ operations.forEach((operation) => {
2373
+ const absoluteXPath = combineXPaths(dataState.xpath, operation.xpath);
2374
+ commandQueueRef.current.cancelByXPath(absoluteXPath);
2375
+ });
2376
+ }
2377
+ statusRef.current = "idle";
2378
+ resultsRef.current = [];
2379
+ }, [operations, dataState.xpath]);
2380
+ const progress = useMemo(() => {
2381
+ const total = operations.length;
2382
+ const completed = resultsRef.current.filter((r) => r.status === "success").length;
2383
+ const failed = resultsRef.current.filter((r) => r.status === "error").length;
2384
+ const pending = resultsRef.current.filter((r) => r.status === "pending").length;
2385
+ return {
2386
+ total,
2387
+ completed,
2388
+ failed,
2389
+ pending,
2390
+ percentage: total > 0 ? Math.round((completed + failed) / total * 100) : 0
2391
+ };
2392
+ }, [operations.length, resultsRef.current]);
2393
+ return {
2394
+ execute,
2395
+ cancel,
2396
+ isLoading: statusRef.current === "loading",
2397
+ isError: statusRef.current === "error",
2398
+ isSuccess: statusRef.current === "success",
2399
+ isIdle: statusRef.current === "idle",
2400
+ results: resultsRef.current,
2401
+ progress
2402
+ };
2403
+ }
2404
+ function useAsyncParallel(operations, config) {
2405
+ return useAsyncBatch(
2406
+ operations.map((op) => ({ ...op, priority: "normal" })),
2407
+ { ...config, concurrency: operations.length }
2408
+ );
2409
+ }
2410
+ function useAsyncSequential(operations, config) {
2411
+ return useAsyncBatch(
2412
+ operations.map((op) => ({ ...op, priority: "normal" })),
2413
+ { ...config, concurrency: 1 }
2414
+ );
2415
+ }
2416
+ function useOptimisticUpdates(xpath, config = {}) {
2417
+ const dataState = useContext(DataContext);
2418
+ const dispatch = useContext(DataDispatchContext);
2419
+ if (!dataState || !dispatch) {
2420
+ throw new Error("useOptimisticUpdates must be used within a DataProvider");
2421
+ }
2422
+ const {
2423
+ onRollback,
2424
+ onCommit
2425
+ } = config;
2426
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2427
+ const apply = useCallback((newData) => {
2428
+ const updateId = generateRequestId();
2429
+ dispatch({
2430
+ type: "ASYNC_START",
2431
+ payload: {
2432
+ xpath: absoluteXPath,
2433
+ requestId: updateId,
2434
+ operation: "mutate",
2435
+ priority: "normal",
2436
+ optimisticData: newData
2437
+ }
2438
+ });
2439
+ return updateId;
2440
+ }, [absoluteXPath, dispatch]);
2441
+ const rollback = useCallback((updateId) => {
2442
+ const optimisticId = `${updateId}_${absoluteXPath}`;
2443
+ const optimisticUpdate = dataState.optimisticUpdates[optimisticId];
2444
+ if (optimisticUpdate) {
2445
+ dispatch({
2446
+ type: "ASYNC_CANCEL",
2447
+ payload: {
2448
+ xpath: absoluteXPath,
2449
+ requestId: updateId
2450
+ }
2451
+ });
2452
+ onRollback == null ? void 0 : onRollback(optimisticUpdate.originalData);
2453
+ }
2454
+ }, [absoluteXPath, dataState.optimisticUpdates, dispatch, onRollback]);
2455
+ const commit = useCallback((updateId) => {
2456
+ const optimisticId = `${updateId}_${absoluteXPath}`;
2457
+ const optimisticUpdate = dataState.optimisticUpdates[optimisticId];
2458
+ if (optimisticUpdate) {
2459
+ dispatch({
2460
+ type: "ASYNC_SUCCESS",
2461
+ payload: {
2462
+ xpath: absoluteXPath,
2463
+ requestId: updateId,
2464
+ data: optimisticUpdate.optimisticData,
2465
+ timestamp: Date.now()
2466
+ }
2467
+ });
2468
+ onCommit == null ? void 0 : onCommit(optimisticUpdate.optimisticData);
2469
+ }
2470
+ }, [absoluteXPath, dataState.optimisticUpdates, dispatch, onCommit]);
2471
+ const rollbackAll = useCallback(() => {
2472
+ Object.entries(dataState.optimisticUpdates).forEach(([optimisticId, update]) => {
2473
+ if (update.xpath === absoluteXPath) {
2474
+ const updateId = optimisticId.split("_")[0];
2475
+ rollback(updateId);
2476
+ }
2477
+ });
2478
+ }, [dataState.optimisticUpdates, absoluteXPath, rollback]);
2479
+ const getOriginalData = useCallback((updateId) => {
2480
+ const optimisticId = `${updateId}_${absoluteXPath}`;
2481
+ const optimisticUpdate = dataState.optimisticUpdates[optimisticId];
2482
+ return optimisticUpdate ? getDataAtXPath(optimisticUpdate.originalData, absoluteXPath) : void 0;
2483
+ }, [dataState.optimisticUpdates, absoluteXPath]);
2484
+ const optimisticUpdateIds = Object.keys(dataState.optimisticUpdates).filter((id) => id.endsWith(`_${absoluteXPath}`)).map((id) => id.split("_")[0]);
2485
+ return {
2486
+ apply,
2487
+ rollback,
2488
+ commit,
2489
+ rollbackAll,
2490
+ getOriginalData,
2491
+ hasOptimisticUpdates: optimisticUpdateIds.length > 0,
2492
+ optimisticUpdateIds
2493
+ };
2494
+ }
2495
+ function useOptimisticList(xpath, config = {}) {
2496
+ const baseResult = useOptimisticUpdates(xpath, config);
2497
+ const dataState = useContext(DataContext);
2498
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2499
+ const currentList = getDataAtXPath(dataState.data, absoluteXPath) || [];
2500
+ const addItem = useCallback((item, position) => {
2501
+ const newList = [...currentList];
2502
+ if (position !== void 0 && position >= 0 && position <= newList.length) {
2503
+ newList.splice(position, 0, item);
2504
+ } else {
2505
+ newList.push(item);
2506
+ }
2507
+ return baseResult.apply(newList);
2508
+ }, [currentList, baseResult]);
2509
+ const updateItem = useCallback((index, item) => {
2510
+ if (index < 0 || index >= currentList.length) {
2511
+ throw new Error(`Index ${index} is out of bounds for list of length ${currentList.length}`);
2512
+ }
2513
+ const newList = [...currentList];
2514
+ newList[index] = item;
2515
+ return baseResult.apply(newList);
2516
+ }, [currentList, baseResult]);
2517
+ const removeItem = useCallback((index) => {
2518
+ if (index < 0 || index >= currentList.length) {
2519
+ throw new Error(`Index ${index} is out of bounds for list of length ${currentList.length}`);
2520
+ }
2521
+ const newList = [...currentList];
2522
+ newList.splice(index, 1);
2523
+ return baseResult.apply(newList);
2524
+ }, [currentList, baseResult]);
2525
+ const moveItem = useCallback((fromIndex, toIndex) => {
2526
+ if (fromIndex < 0 || fromIndex >= currentList.length || toIndex < 0 || toIndex >= currentList.length) {
2527
+ throw new Error("Move indices are out of bounds");
2528
+ }
2529
+ const newList = [...currentList];
2530
+ const [movedItem] = newList.splice(fromIndex, 1);
2531
+ newList.splice(toIndex, 0, movedItem);
2532
+ return baseResult.apply(newList);
2533
+ }, [currentList, baseResult]);
2534
+ return {
2535
+ ...baseResult,
2536
+ addItem,
2537
+ updateItem,
2538
+ removeItem,
2539
+ moveItem
2540
+ };
2541
+ }
2542
+ function useOptimisticObject(xpath, config = {}) {
2543
+ const baseResult = useOptimisticUpdates(xpath, config);
2544
+ const dataState = useContext(DataContext);
2545
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2546
+ const currentObject = getDataAtXPath(dataState.data, absoluteXPath) || {};
2547
+ const updateProperty = useCallback((key, value) => {
2548
+ const newObject = { ...currentObject, [key]: value };
2549
+ return baseResult.apply(newObject);
2550
+ }, [currentObject, baseResult]);
2551
+ const updateProperties = useCallback((updates) => {
2552
+ const newObject = { ...currentObject, ...updates };
2553
+ return baseResult.apply(newObject);
2554
+ }, [currentObject, baseResult]);
2555
+ const removeProperty = useCallback((key) => {
2556
+ const newObject = { ...currentObject };
2557
+ delete newObject[key];
2558
+ return baseResult.apply(newObject);
2559
+ }, [currentObject, baseResult]);
2560
+ const mergeObject = useCallback((updates) => {
2561
+ const newObject = { ...currentObject };
2562
+ Object.entries(updates).forEach(([key, value]) => {
2563
+ if (typeof newObject[key] === "object" && typeof value === "object" && newObject[key] !== null && value !== null) {
2564
+ newObject[key] = { ...newObject[key], ...value };
2565
+ } else {
2566
+ newObject[key] = value;
2567
+ }
2568
+ });
2569
+ return baseResult.apply(newObject);
2570
+ }, [currentObject, baseResult]);
2571
+ return {
2572
+ ...baseResult,
2573
+ updateProperty,
2574
+ updateProperties,
2575
+ removeProperty,
2576
+ mergeObject
2577
+ };
2578
+ }
2579
+ function useInvalidation() {
2580
+ const dataState = useContext(DataContext);
2581
+ const dispatch = useContext(DataDispatchContext);
2582
+ if (!dataState || !dispatch) {
2583
+ throw new Error("useInvalidation must be used within a DataProvider");
2584
+ }
2585
+ const commandQueueRef = useRef();
2586
+ if (!commandQueueRef.current) {
2587
+ commandQueueRef.current = new CommandQueueManager(dispatch);
2588
+ }
2589
+ useEffect(() => {
2590
+ var _a;
2591
+ (_a = commandQueueRef.current) == null ? void 0 : _a.updateQueue(dataState.commandQueue);
2592
+ }, [dataState.commandQueue]);
2593
+ useEffect(() => {
2594
+ return () => {
2595
+ var _a;
2596
+ (_a = commandQueueRef.current) == null ? void 0 : _a.destroy();
2597
+ };
2598
+ }, []);
2599
+ const invalidate = useCallback((xpath, config = {}) => {
2600
+ const {
2601
+ includeChildren = false,
2602
+ includeParents = false,
2603
+ clearData = false
2604
+ } = config;
2605
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2606
+ const pathsToInvalidate = /* @__PURE__ */ new Set([absoluteXPath]);
2607
+ if (includeChildren) {
2608
+ Object.keys(dataState.asyncStates).forEach((statePath) => {
2609
+ if (statePath.startsWith(absoluteXPath + "/") || statePath.startsWith(absoluteXPath + "[")) {
2610
+ pathsToInvalidate.add(statePath);
2611
+ }
2612
+ });
2613
+ }
2614
+ if (includeParents) {
2615
+ const segments = parseXPath(absoluteXPath);
2616
+ for (let i = segments.length - 1; i >= 0; i--) {
2617
+ const parentSegments = segments.slice(0, i);
2618
+ const parentPath = parentSegments.length === 0 ? "/" : "/" + parentSegments.map(
2619
+ (seg) => seg.isArray && seg.index !== void 0 ? `${seg.property}[${seg.index}]` : seg.property
2620
+ ).join("/");
2621
+ if (dataState.asyncStates[parentPath]) {
2622
+ pathsToInvalidate.add(parentPath);
2623
+ }
2624
+ }
2625
+ }
2626
+ pathsToInvalidate.forEach((path) => {
2627
+ var _a;
2628
+ const asyncState = dataState.asyncStates[path];
2629
+ (_a = commandQueueRef.current) == null ? void 0 : _a.cancelByXPath(path);
2630
+ if (asyncState) {
2631
+ dispatch({
2632
+ type: "ASYNC_CANCEL",
2633
+ payload: {
2634
+ xpath: path,
2635
+ requestId: asyncState.requestId || generateRequestId()
2636
+ }
2637
+ });
2638
+ }
2639
+ if (clearData) {
2640
+ dispatch({
2641
+ type: "DATA_OPERATION",
2642
+ payload: {
2643
+ xpath: path,
2644
+ operation: "delete",
2645
+ data: null
2646
+ }
2647
+ });
2648
+ }
2649
+ });
2650
+ }, [dataState, dispatch]);
2651
+ const invalidateMany = useCallback((xpaths, config = {}) => {
2652
+ xpaths.forEach((xpath) => invalidate(xpath, config));
2653
+ }, [invalidate]);
2654
+ const invalidatePattern = useCallback((pattern, config = {}) => {
2655
+ const regex = new RegExp(
2656
+ pattern.replace(/\*/g, ".*").replace(/\[(\d+)\]/g, "\\[$1\\]").replace(/\[\*\]/g, "\\[\\d+\\]")
2657
+ );
2658
+ const matchingPaths = Object.keys(dataState.asyncStates).filter(
2659
+ (path) => regex.test(path)
2660
+ );
2661
+ invalidateMany(matchingPaths, config);
2662
+ }, [dataState.asyncStates, invalidateMany]);
2663
+ const invalidateAll = useCallback(() => {
2664
+ dataState.commandQueue.executing.forEach((command) => {
2665
+ command.abortController.abort();
2666
+ });
2667
+ dataState.commandQueue.pending.forEach((command) => {
2668
+ command.abortController.abort();
2669
+ });
2670
+ Object.keys(dataState.asyncStates).forEach((path) => {
2671
+ const asyncState = dataState.asyncStates[path];
2672
+ dispatch({
2673
+ type: "ASYNC_CANCEL",
2674
+ payload: {
2675
+ xpath: path,
2676
+ requestId: asyncState.requestId || generateRequestId()
2677
+ }
2678
+ });
2679
+ });
2680
+ dispatch({
2681
+ type: "COMMAND_QUEUE_UPDATE",
2682
+ payload: {
2683
+ operation: "remove",
2684
+ commandId: "all"
2685
+ }
2686
+ });
2687
+ }, [dataState, dispatch]);
2688
+ const revalidate = useCallback((xpath) => {
2689
+ const absoluteXPath = combineXPaths(dataState.xpath, xpath);
2690
+ const asyncState = dataState.asyncStates[absoluteXPath];
2691
+ if (asyncState) {
2692
+ dispatch({
2693
+ type: "ASYNC_START",
2694
+ payload: {
2695
+ xpath: absoluteXPath,
2696
+ requestId: generateRequestId(),
2697
+ operation: "fetch",
2698
+ priority: "normal"
2699
+ }
2700
+ });
2701
+ }
2702
+ }, [dataState, dispatch]);
2703
+ const revalidateMany = useCallback((xpaths) => {
2704
+ xpaths.forEach((xpath) => revalidate(xpath));
2705
+ }, [revalidate]);
2706
+ const getInvalidationCount = useCallback(() => {
2707
+ return Object.keys(dataState.asyncStates).filter((path) => {
2708
+ const state = dataState.asyncStates[path];
2709
+ return state.status === "idle" || state.status === "error";
2710
+ }).length;
2711
+ }, [dataState.asyncStates]);
2712
+ return {
2713
+ invalidate,
2714
+ invalidateMany,
2715
+ invalidatePattern,
2716
+ invalidateAll,
2717
+ revalidate,
2718
+ revalidateMany,
2719
+ getInvalidationCount
2720
+ };
2721
+ }
2722
+ function useAutoInvalidation(dependencies, config = {}) {
2723
+ const { invalidateMany } = useInvalidation();
2724
+ const { debounceMs = 100, onInvalidate, ...invalidationConfig } = config;
2725
+ const debouncedInvalidate = useCallback(
2726
+ /* @__PURE__ */ (() => {
2727
+ let timeoutId;
2728
+ return (paths) => {
2729
+ clearTimeout(timeoutId);
2730
+ timeoutId = setTimeout(() => {
2731
+ invalidateMany(paths, invalidationConfig);
2732
+ onInvalidate == null ? void 0 : onInvalidate(paths);
2733
+ }, debounceMs);
2734
+ };
2735
+ })(),
2736
+ [invalidateMany, invalidationConfig, debounceMs, onInvalidate]
2737
+ );
2738
+ return {
2739
+ trigger: () => debouncedInvalidate(dependencies),
2740
+ invalidateDependencies: () => invalidateMany(dependencies, invalidationConfig)
2741
+ };
2742
+ }
2743
+ function useQueryInvalidation() {
2744
+ const dataState = useContext(DataContext);
2745
+ const { invalidatePattern, invalidateMany } = useInvalidation();
2746
+ const invalidateQueries = useCallback((queryKey) => {
2747
+ if (Array.isArray(queryKey)) {
2748
+ invalidateMany(queryKey);
2749
+ } else {
2750
+ invalidatePattern(queryKey);
2751
+ }
2752
+ }, [invalidatePattern, invalidateMany]);
2753
+ const invalidateQueriesMatching = useCallback((predicate) => {
2754
+ const matchingPaths = Object.keys(dataState.asyncStates).filter(predicate);
2755
+ invalidateMany(matchingPaths);
2756
+ }, [dataState.asyncStates, invalidateMany]);
2757
+ const getQueries = useCallback((queryKey) => {
2758
+ if (!queryKey) {
2759
+ return Object.keys(dataState.asyncStates);
2760
+ }
2761
+ if (Array.isArray(queryKey)) {
2762
+ return queryKey.filter((path) => dataState.asyncStates[path]);
2763
+ }
2764
+ const regex = new RegExp(queryKey.replace(/\*/g, ".*"));
2765
+ return Object.keys(dataState.asyncStates).filter((path) => regex.test(path));
2766
+ }, [dataState.asyncStates]);
2767
+ return {
2768
+ invalidateQueries,
2769
+ invalidateQueriesMatching,
2770
+ getQueries
2771
+ };
2772
+ }
2773
+ function Form({
2774
+ xpath = "",
2775
+ operation = "merge",
2776
+ onSubmit,
2777
+ children,
2778
+ ...props
2779
+ }) {
2780
+ const navigate2 = useNavigate();
2781
+ const { setData } = useDataManipulation();
2782
+ const handleSubmit = (event) => {
2783
+ event.preventDefault();
2784
+ const form = event.currentTarget;
2785
+ const formData = new window.FormData(form);
2786
+ const data = {};
2787
+ for (const [key, value] of formData.entries()) {
2788
+ if (data[key]) {
2789
+ if (Array.isArray(data[key])) {
2790
+ data[key].push(value);
2791
+ } else {
2792
+ data[key] = [data[key], value];
2793
+ }
2794
+ } else {
2795
+ data[key] = value;
2796
+ }
2797
+ }
2798
+ if (onSubmit) {
2799
+ onSubmit(data, navigate2);
2800
+ } else if (xpath) {
2801
+ setData(xpath, data, operation);
2802
+ }
2803
+ };
2804
+ return /* @__PURE__ */ jsxRuntimeExports.jsx("form", { ...props, onSubmit: handleSubmit, children });
2805
+ }
2806
+ function Button({
2807
+ dataAction = "merge",
2808
+ targetXPath,
2809
+ navigateTo,
2810
+ children,
2811
+ onClick,
2812
+ type = "submit",
2813
+ ...props
2814
+ }) {
2815
+ const { setData } = useDataManipulation();
2816
+ const navigate2 = useNavigate();
2817
+ const handleClick = (event) => {
2818
+ if (onClick) {
2819
+ onClick(event);
2820
+ }
2821
+ if (event.defaultPrevented) {
2822
+ return;
2823
+ }
2824
+ if (type === "submit") {
2825
+ const form = event.currentTarget.closest("form");
2826
+ if (form && targetXPath) {
2827
+ const formData = new window.FormData(form);
2828
+ const data = {};
2829
+ for (const [key, value] of formData.entries()) {
2830
+ if (data[key]) {
2831
+ if (Array.isArray(data[key])) {
2832
+ data[key].push(value);
2833
+ } else {
2834
+ data[key] = [data[key], value];
2835
+ }
2836
+ } else {
2837
+ data[key] = value;
2838
+ }
2839
+ }
2840
+ setData(targetXPath, data, dataAction);
2841
+ }
2842
+ }
2843
+ if (navigateTo) {
2844
+ navigate2(navigateTo);
2845
+ }
2846
+ };
2847
+ return /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type, ...props, onClick: handleClick, children });
2848
+ }
2849
+ const Link = forwardRef(({ to, children, ...rest }, ref) => {
2850
+ const navigate2 = useNavigate();
2851
+ const handleClick = (event) => {
2852
+ if (!event.defaultPrevented) {
2853
+ event.preventDefault();
2854
+ navigate2(to);
2855
+ }
2856
+ };
2857
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
2858
+ "a",
2859
+ {
2860
+ ...rest,
2861
+ href: "#",
2862
+ ref,
2863
+ onClick: handleClick,
2864
+ children
2865
+ }
2866
+ );
2867
+ });
2868
+ Link.displayName = "Link";
2869
+ export {
2870
+ Button,
2871
+ CommandQueueManager,
2872
+ DataProvider,
2873
+ Form,
2874
+ Link,
2875
+ asyncCancel,
2876
+ asyncError,
2877
+ asyncStart,
2878
+ asyncSuccess,
2879
+ commandQueueUpdate,
2880
+ generateRequestId,
2881
+ useAsyncBatch,
2882
+ useAsyncData,
2883
+ useAsyncMutation,
2884
+ useAsyncParallel,
2885
+ useAsyncSequential,
2886
+ useAsyncState,
2887
+ useAsyncStates,
2888
+ useAutoInvalidation,
2889
+ useData,
2890
+ useDataAtXPath,
2891
+ useDataManipulation,
2892
+ useGlobalAsyncState,
2893
+ useHistory,
2894
+ useInvalidation,
2895
+ useNavigate,
2896
+ useNavigation,
2897
+ useOptimisticList,
2898
+ useOptimisticObject,
2899
+ useOptimisticUpdates,
2900
+ useQueryInvalidation,
2901
+ useTargetData,
2902
+ useXPath
2903
+ };
2904
+ //# sourceMappingURL=index.es.js.map