@biglogic/rgs 3.8.2 → 3.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/advanced.cjs +1 -0
- package/core/advanced.js +1 -0
- package/core/minimal.cjs +1 -0
- package/core/minimal.js +1 -19
- package/index.cjs +1 -0
- package/index.js +1 -3925
- package/package.json +43 -47
- package/types/rgs.d.ts +7 -0
- package/docs/SUMMARY.md +0 -55
- package/docs/_config.yml +0 -1
- package/docs/chapters/case-studies.md +0 -69
- package/docs/chapters/faq.md +0 -53
- package/docs/chapters/getting-started.md +0 -68
- package/docs/chapters/local-first-sync.md +0 -146
- package/docs/chapters/migration-guide.md +0 -284
- package/docs/chapters/persistence-and-safety.md +0 -125
- package/docs/chapters/philosophy.md +0 -54
- package/docs/chapters/security-architecture.md +0 -50
- package/docs/chapters/the-magnetar-way.md +0 -69
package/index.js
CHANGED
|
@@ -1,3925 +1 @@
|
|
|
1
|
-
var __create = Object.create;
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
-
var __commonJS = (cb, mod) => function __require() {
|
|
9
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
10
|
-
};
|
|
11
|
-
var __copyProps = (to, from, except, desc) => {
|
|
12
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
-
for (let key of __getOwnPropNames(from))
|
|
14
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
-
}
|
|
17
|
-
return to;
|
|
18
|
-
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
-
mod
|
|
26
|
-
));
|
|
27
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
28
|
-
|
|
29
|
-
// node_modules/react/cjs/react.development.js
|
|
30
|
-
var require_react_development = __commonJS({
|
|
31
|
-
"node_modules/react/cjs/react.development.js"(exports, module) {
|
|
32
|
-
"use strict";
|
|
33
|
-
(function() {
|
|
34
|
-
function defineDeprecationWarning(methodName, info) {
|
|
35
|
-
Object.defineProperty(Component.prototype, methodName, {
|
|
36
|
-
get: function() {
|
|
37
|
-
console.warn(
|
|
38
|
-
"%s(...) is deprecated in plain JavaScript React classes. %s",
|
|
39
|
-
info[0],
|
|
40
|
-
info[1]
|
|
41
|
-
);
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
function getIteratorFn(maybeIterable) {
|
|
46
|
-
if (null === maybeIterable || "object" !== typeof maybeIterable)
|
|
47
|
-
return null;
|
|
48
|
-
maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
|
|
49
|
-
return "function" === typeof maybeIterable ? maybeIterable : null;
|
|
50
|
-
}
|
|
51
|
-
function warnNoop(publicInstance, callerName) {
|
|
52
|
-
publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
|
|
53
|
-
var warningKey = publicInstance + "." + callerName;
|
|
54
|
-
didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error(
|
|
55
|
-
"Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",
|
|
56
|
-
callerName,
|
|
57
|
-
publicInstance
|
|
58
|
-
), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
|
|
59
|
-
}
|
|
60
|
-
function Component(props, context, updater) {
|
|
61
|
-
this.props = props;
|
|
62
|
-
this.context = context;
|
|
63
|
-
this.refs = emptyObject;
|
|
64
|
-
this.updater = updater || ReactNoopUpdateQueue;
|
|
65
|
-
}
|
|
66
|
-
function ComponentDummy() {
|
|
67
|
-
}
|
|
68
|
-
function PureComponent(props, context, updater) {
|
|
69
|
-
this.props = props;
|
|
70
|
-
this.context = context;
|
|
71
|
-
this.refs = emptyObject;
|
|
72
|
-
this.updater = updater || ReactNoopUpdateQueue;
|
|
73
|
-
}
|
|
74
|
-
function noop() {
|
|
75
|
-
}
|
|
76
|
-
function testStringCoercion(value) {
|
|
77
|
-
return "" + value;
|
|
78
|
-
}
|
|
79
|
-
function checkKeyStringCoercion(value) {
|
|
80
|
-
try {
|
|
81
|
-
testStringCoercion(value);
|
|
82
|
-
var JSCompiler_inline_result = false;
|
|
83
|
-
} catch (e) {
|
|
84
|
-
JSCompiler_inline_result = true;
|
|
85
|
-
}
|
|
86
|
-
if (JSCompiler_inline_result) {
|
|
87
|
-
JSCompiler_inline_result = console;
|
|
88
|
-
var JSCompiler_temp_const = JSCompiler_inline_result.error;
|
|
89
|
-
var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
|
|
90
|
-
JSCompiler_temp_const.call(
|
|
91
|
-
JSCompiler_inline_result,
|
|
92
|
-
"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
|
|
93
|
-
JSCompiler_inline_result$jscomp$0
|
|
94
|
-
);
|
|
95
|
-
return testStringCoercion(value);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
function getComponentNameFromType(type) {
|
|
99
|
-
if (null == type) return null;
|
|
100
|
-
if ("function" === typeof type)
|
|
101
|
-
return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
|
|
102
|
-
if ("string" === typeof type) return type;
|
|
103
|
-
switch (type) {
|
|
104
|
-
case REACT_FRAGMENT_TYPE:
|
|
105
|
-
return "Fragment";
|
|
106
|
-
case REACT_PROFILER_TYPE:
|
|
107
|
-
return "Profiler";
|
|
108
|
-
case REACT_STRICT_MODE_TYPE:
|
|
109
|
-
return "StrictMode";
|
|
110
|
-
case REACT_SUSPENSE_TYPE:
|
|
111
|
-
return "Suspense";
|
|
112
|
-
case REACT_SUSPENSE_LIST_TYPE:
|
|
113
|
-
return "SuspenseList";
|
|
114
|
-
case REACT_ACTIVITY_TYPE:
|
|
115
|
-
return "Activity";
|
|
116
|
-
}
|
|
117
|
-
if ("object" === typeof type)
|
|
118
|
-
switch ("number" === typeof type.tag && console.error(
|
|
119
|
-
"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
|
|
120
|
-
), type.$$typeof) {
|
|
121
|
-
case REACT_PORTAL_TYPE:
|
|
122
|
-
return "Portal";
|
|
123
|
-
case REACT_CONTEXT_TYPE:
|
|
124
|
-
return type.displayName || "Context";
|
|
125
|
-
case REACT_CONSUMER_TYPE:
|
|
126
|
-
return (type._context.displayName || "Context") + ".Consumer";
|
|
127
|
-
case REACT_FORWARD_REF_TYPE:
|
|
128
|
-
var innerType = type.render;
|
|
129
|
-
type = type.displayName;
|
|
130
|
-
type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
|
|
131
|
-
return type;
|
|
132
|
-
case REACT_MEMO_TYPE:
|
|
133
|
-
return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
|
|
134
|
-
case REACT_LAZY_TYPE:
|
|
135
|
-
innerType = type._payload;
|
|
136
|
-
type = type._init;
|
|
137
|
-
try {
|
|
138
|
-
return getComponentNameFromType(type(innerType));
|
|
139
|
-
} catch (x) {
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
return null;
|
|
143
|
-
}
|
|
144
|
-
function getTaskName(type) {
|
|
145
|
-
if (type === REACT_FRAGMENT_TYPE) return "<>";
|
|
146
|
-
if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
|
|
147
|
-
return "<...>";
|
|
148
|
-
try {
|
|
149
|
-
var name = getComponentNameFromType(type);
|
|
150
|
-
return name ? "<" + name + ">" : "<...>";
|
|
151
|
-
} catch (x) {
|
|
152
|
-
return "<...>";
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
function getOwner() {
|
|
156
|
-
var dispatcher = ReactSharedInternals.A;
|
|
157
|
-
return null === dispatcher ? null : dispatcher.getOwner();
|
|
158
|
-
}
|
|
159
|
-
function UnknownOwner() {
|
|
160
|
-
return Error("react-stack-top-frame");
|
|
161
|
-
}
|
|
162
|
-
function hasValidKey(config) {
|
|
163
|
-
if (hasOwnProperty.call(config, "key")) {
|
|
164
|
-
var getter = Object.getOwnPropertyDescriptor(config, "key").get;
|
|
165
|
-
if (getter && getter.isReactWarning) return false;
|
|
166
|
-
}
|
|
167
|
-
return void 0 !== config.key;
|
|
168
|
-
}
|
|
169
|
-
function defineKeyPropWarningGetter(props, displayName) {
|
|
170
|
-
function warnAboutAccessingKey() {
|
|
171
|
-
specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
|
|
172
|
-
"%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://react.dev/link/special-props)",
|
|
173
|
-
displayName
|
|
174
|
-
));
|
|
175
|
-
}
|
|
176
|
-
warnAboutAccessingKey.isReactWarning = true;
|
|
177
|
-
Object.defineProperty(props, "key", {
|
|
178
|
-
get: warnAboutAccessingKey,
|
|
179
|
-
configurable: true
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
function elementRefGetterWithDeprecationWarning() {
|
|
183
|
-
var componentName = getComponentNameFromType(this.type);
|
|
184
|
-
didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
|
|
185
|
-
"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
|
|
186
|
-
));
|
|
187
|
-
componentName = this.props.ref;
|
|
188
|
-
return void 0 !== componentName ? componentName : null;
|
|
189
|
-
}
|
|
190
|
-
function ReactElement(type, key, props, owner, debugStack, debugTask) {
|
|
191
|
-
var refProp = props.ref;
|
|
192
|
-
type = {
|
|
193
|
-
$$typeof: REACT_ELEMENT_TYPE,
|
|
194
|
-
type,
|
|
195
|
-
key,
|
|
196
|
-
props,
|
|
197
|
-
_owner: owner
|
|
198
|
-
};
|
|
199
|
-
null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
|
|
200
|
-
enumerable: false,
|
|
201
|
-
get: elementRefGetterWithDeprecationWarning
|
|
202
|
-
}) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
|
|
203
|
-
type._store = {};
|
|
204
|
-
Object.defineProperty(type._store, "validated", {
|
|
205
|
-
configurable: false,
|
|
206
|
-
enumerable: false,
|
|
207
|
-
writable: true,
|
|
208
|
-
value: 0
|
|
209
|
-
});
|
|
210
|
-
Object.defineProperty(type, "_debugInfo", {
|
|
211
|
-
configurable: false,
|
|
212
|
-
enumerable: false,
|
|
213
|
-
writable: true,
|
|
214
|
-
value: null
|
|
215
|
-
});
|
|
216
|
-
Object.defineProperty(type, "_debugStack", {
|
|
217
|
-
configurable: false,
|
|
218
|
-
enumerable: false,
|
|
219
|
-
writable: true,
|
|
220
|
-
value: debugStack
|
|
221
|
-
});
|
|
222
|
-
Object.defineProperty(type, "_debugTask", {
|
|
223
|
-
configurable: false,
|
|
224
|
-
enumerable: false,
|
|
225
|
-
writable: true,
|
|
226
|
-
value: debugTask
|
|
227
|
-
});
|
|
228
|
-
Object.freeze && (Object.freeze(type.props), Object.freeze(type));
|
|
229
|
-
return type;
|
|
230
|
-
}
|
|
231
|
-
function cloneAndReplaceKey(oldElement, newKey) {
|
|
232
|
-
newKey = ReactElement(
|
|
233
|
-
oldElement.type,
|
|
234
|
-
newKey,
|
|
235
|
-
oldElement.props,
|
|
236
|
-
oldElement._owner,
|
|
237
|
-
oldElement._debugStack,
|
|
238
|
-
oldElement._debugTask
|
|
239
|
-
);
|
|
240
|
-
oldElement._store && (newKey._store.validated = oldElement._store.validated);
|
|
241
|
-
return newKey;
|
|
242
|
-
}
|
|
243
|
-
function validateChildKeys(node) {
|
|
244
|
-
isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
|
|
245
|
-
}
|
|
246
|
-
function isValidElement(object) {
|
|
247
|
-
return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
|
|
248
|
-
}
|
|
249
|
-
function escape(key) {
|
|
250
|
-
var escaperLookup = { "=": "=0", ":": "=2" };
|
|
251
|
-
return "$" + key.replace(/[=:]/g, function(match) {
|
|
252
|
-
return escaperLookup[match];
|
|
253
|
-
});
|
|
254
|
-
}
|
|
255
|
-
function getElementKey(element, index) {
|
|
256
|
-
return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36);
|
|
257
|
-
}
|
|
258
|
-
function resolveThenable(thenable) {
|
|
259
|
-
switch (thenable.status) {
|
|
260
|
-
case "fulfilled":
|
|
261
|
-
return thenable.value;
|
|
262
|
-
case "rejected":
|
|
263
|
-
throw thenable.reason;
|
|
264
|
-
default:
|
|
265
|
-
switch ("string" === typeof thenable.status ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(
|
|
266
|
-
function(fulfilledValue) {
|
|
267
|
-
"pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
|
|
268
|
-
},
|
|
269
|
-
function(error) {
|
|
270
|
-
"pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error);
|
|
271
|
-
}
|
|
272
|
-
)), thenable.status) {
|
|
273
|
-
case "fulfilled":
|
|
274
|
-
return thenable.value;
|
|
275
|
-
case "rejected":
|
|
276
|
-
throw thenable.reason;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
throw thenable;
|
|
280
|
-
}
|
|
281
|
-
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
|
|
282
|
-
var type = typeof children;
|
|
283
|
-
if ("undefined" === type || "boolean" === type) children = null;
|
|
284
|
-
var invokeCallback = false;
|
|
285
|
-
if (null === children) invokeCallback = true;
|
|
286
|
-
else
|
|
287
|
-
switch (type) {
|
|
288
|
-
case "bigint":
|
|
289
|
-
case "string":
|
|
290
|
-
case "number":
|
|
291
|
-
invokeCallback = true;
|
|
292
|
-
break;
|
|
293
|
-
case "object":
|
|
294
|
-
switch (children.$$typeof) {
|
|
295
|
-
case REACT_ELEMENT_TYPE:
|
|
296
|
-
case REACT_PORTAL_TYPE:
|
|
297
|
-
invokeCallback = true;
|
|
298
|
-
break;
|
|
299
|
-
case REACT_LAZY_TYPE:
|
|
300
|
-
return invokeCallback = children._init, mapIntoArray(
|
|
301
|
-
invokeCallback(children._payload),
|
|
302
|
-
array,
|
|
303
|
-
escapedPrefix,
|
|
304
|
-
nameSoFar,
|
|
305
|
-
callback
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
if (invokeCallback) {
|
|
310
|
-
invokeCallback = children;
|
|
311
|
-
callback = callback(invokeCallback);
|
|
312
|
-
var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
|
|
313
|
-
isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
|
|
314
|
-
return c;
|
|
315
|
-
})) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(
|
|
316
|
-
callback,
|
|
317
|
-
escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(
|
|
318
|
-
userProvidedKeyEscapeRegex,
|
|
319
|
-
"$&/"
|
|
320
|
-
) + "/") + childKey
|
|
321
|
-
), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
|
|
322
|
-
return 1;
|
|
323
|
-
}
|
|
324
|
-
invokeCallback = 0;
|
|
325
|
-
childKey = "" === nameSoFar ? "." : nameSoFar + ":";
|
|
326
|
-
if (isArrayImpl(children))
|
|
327
|
-
for (var i = 0; i < children.length; i++)
|
|
328
|
-
nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
|
|
329
|
-
nameSoFar,
|
|
330
|
-
array,
|
|
331
|
-
escapedPrefix,
|
|
332
|
-
type,
|
|
333
|
-
callback
|
|
334
|
-
);
|
|
335
|
-
else if (i = getIteratorFn(children), "function" === typeof i)
|
|
336
|
-
for (i === children.entries && (didWarnAboutMaps || console.warn(
|
|
337
|
-
"Using Maps as children is not supported. Use an array of keyed ReactElements instead."
|
|
338
|
-
), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
|
|
339
|
-
nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
|
|
340
|
-
nameSoFar,
|
|
341
|
-
array,
|
|
342
|
-
escapedPrefix,
|
|
343
|
-
type,
|
|
344
|
-
callback
|
|
345
|
-
);
|
|
346
|
-
else if ("object" === type) {
|
|
347
|
-
if ("function" === typeof children.then)
|
|
348
|
-
return mapIntoArray(
|
|
349
|
-
resolveThenable(children),
|
|
350
|
-
array,
|
|
351
|
-
escapedPrefix,
|
|
352
|
-
nameSoFar,
|
|
353
|
-
callback
|
|
354
|
-
);
|
|
355
|
-
array = String(children);
|
|
356
|
-
throw Error(
|
|
357
|
-
"Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
|
|
358
|
-
);
|
|
359
|
-
}
|
|
360
|
-
return invokeCallback;
|
|
361
|
-
}
|
|
362
|
-
function mapChildren(children, func, context) {
|
|
363
|
-
if (null == children) return children;
|
|
364
|
-
var result = [], count = 0;
|
|
365
|
-
mapIntoArray(children, result, "", "", function(child) {
|
|
366
|
-
return func.call(context, child, count++);
|
|
367
|
-
});
|
|
368
|
-
return result;
|
|
369
|
-
}
|
|
370
|
-
function lazyInitializer(payload) {
|
|
371
|
-
if (-1 === payload._status) {
|
|
372
|
-
var ioInfo = payload._ioInfo;
|
|
373
|
-
null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
|
|
374
|
-
ioInfo = payload._result;
|
|
375
|
-
var thenable = ioInfo();
|
|
376
|
-
thenable.then(
|
|
377
|
-
function(moduleObject) {
|
|
378
|
-
if (0 === payload._status || -1 === payload._status) {
|
|
379
|
-
payload._status = 1;
|
|
380
|
-
payload._result = moduleObject;
|
|
381
|
-
var _ioInfo = payload._ioInfo;
|
|
382
|
-
null != _ioInfo && (_ioInfo.end = performance.now());
|
|
383
|
-
void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject);
|
|
384
|
-
}
|
|
385
|
-
},
|
|
386
|
-
function(error) {
|
|
387
|
-
if (0 === payload._status || -1 === payload._status) {
|
|
388
|
-
payload._status = 2;
|
|
389
|
-
payload._result = error;
|
|
390
|
-
var _ioInfo2 = payload._ioInfo;
|
|
391
|
-
null != _ioInfo2 && (_ioInfo2.end = performance.now());
|
|
392
|
-
void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error);
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
);
|
|
396
|
-
ioInfo = payload._ioInfo;
|
|
397
|
-
if (null != ioInfo) {
|
|
398
|
-
ioInfo.value = thenable;
|
|
399
|
-
var displayName = thenable.displayName;
|
|
400
|
-
"string" === typeof displayName && (ioInfo.name = displayName);
|
|
401
|
-
}
|
|
402
|
-
-1 === payload._status && (payload._status = 0, payload._result = thenable);
|
|
403
|
-
}
|
|
404
|
-
if (1 === payload._status)
|
|
405
|
-
return ioInfo = payload._result, void 0 === ioInfo && console.error(
|
|
406
|
-
"lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
|
|
407
|
-
ioInfo
|
|
408
|
-
), "default" in ioInfo || console.error(
|
|
409
|
-
"lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",
|
|
410
|
-
ioInfo
|
|
411
|
-
), ioInfo.default;
|
|
412
|
-
throw payload._result;
|
|
413
|
-
}
|
|
414
|
-
function resolveDispatcher() {
|
|
415
|
-
var dispatcher = ReactSharedInternals.H;
|
|
416
|
-
null === dispatcher && console.error(
|
|
417
|
-
"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
|
|
418
|
-
);
|
|
419
|
-
return dispatcher;
|
|
420
|
-
}
|
|
421
|
-
function releaseAsyncTransition() {
|
|
422
|
-
ReactSharedInternals.asyncTransitions--;
|
|
423
|
-
}
|
|
424
|
-
function enqueueTask(task) {
|
|
425
|
-
if (null === enqueueTaskImpl)
|
|
426
|
-
try {
|
|
427
|
-
var requireString = ("require" + Math.random()).slice(0, 7);
|
|
428
|
-
enqueueTaskImpl = (module && module[requireString]).call(
|
|
429
|
-
module,
|
|
430
|
-
"timers"
|
|
431
|
-
).setImmediate;
|
|
432
|
-
} catch (_err) {
|
|
433
|
-
enqueueTaskImpl = function(callback) {
|
|
434
|
-
false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error(
|
|
435
|
-
"This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."
|
|
436
|
-
));
|
|
437
|
-
var channel = new MessageChannel();
|
|
438
|
-
channel.port1.onmessage = callback;
|
|
439
|
-
channel.port2.postMessage(void 0);
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
return enqueueTaskImpl(task);
|
|
443
|
-
}
|
|
444
|
-
function aggregateErrors(errors2) {
|
|
445
|
-
return 1 < errors2.length && "function" === typeof AggregateError ? new AggregateError(errors2) : errors2[0];
|
|
446
|
-
}
|
|
447
|
-
function popActScope(prevActQueue, prevActScopeDepth) {
|
|
448
|
-
prevActScopeDepth !== actScopeDepth - 1 && console.error(
|
|
449
|
-
"You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "
|
|
450
|
-
);
|
|
451
|
-
actScopeDepth = prevActScopeDepth;
|
|
452
|
-
}
|
|
453
|
-
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
|
|
454
|
-
var queue = ReactSharedInternals.actQueue;
|
|
455
|
-
if (null !== queue)
|
|
456
|
-
if (0 !== queue.length)
|
|
457
|
-
try {
|
|
458
|
-
flushActQueue(queue);
|
|
459
|
-
enqueueTask(function() {
|
|
460
|
-
return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
|
|
461
|
-
});
|
|
462
|
-
return;
|
|
463
|
-
} catch (error) {
|
|
464
|
-
ReactSharedInternals.thrownErrors.push(error);
|
|
465
|
-
}
|
|
466
|
-
else ReactSharedInternals.actQueue = null;
|
|
467
|
-
0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
|
|
468
|
-
}
|
|
469
|
-
function flushActQueue(queue) {
|
|
470
|
-
if (!isFlushing) {
|
|
471
|
-
isFlushing = true;
|
|
472
|
-
var i = 0;
|
|
473
|
-
try {
|
|
474
|
-
for (; i < queue.length; i++) {
|
|
475
|
-
var callback = queue[i];
|
|
476
|
-
do {
|
|
477
|
-
ReactSharedInternals.didUsePromise = false;
|
|
478
|
-
var continuation = callback(false);
|
|
479
|
-
if (null !== continuation) {
|
|
480
|
-
if (ReactSharedInternals.didUsePromise) {
|
|
481
|
-
queue[i] = callback;
|
|
482
|
-
queue.splice(0, i);
|
|
483
|
-
return;
|
|
484
|
-
}
|
|
485
|
-
callback = continuation;
|
|
486
|
-
} else break;
|
|
487
|
-
} while (1);
|
|
488
|
-
}
|
|
489
|
-
queue.length = 0;
|
|
490
|
-
} catch (error) {
|
|
491
|
-
queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
|
|
492
|
-
} finally {
|
|
493
|
-
isFlushing = false;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
|
|
498
|
-
var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
|
|
499
|
-
isMounted: function() {
|
|
500
|
-
return false;
|
|
501
|
-
},
|
|
502
|
-
enqueueForceUpdate: function(publicInstance) {
|
|
503
|
-
warnNoop(publicInstance, "forceUpdate");
|
|
504
|
-
},
|
|
505
|
-
enqueueReplaceState: function(publicInstance) {
|
|
506
|
-
warnNoop(publicInstance, "replaceState");
|
|
507
|
-
},
|
|
508
|
-
enqueueSetState: function(publicInstance) {
|
|
509
|
-
warnNoop(publicInstance, "setState");
|
|
510
|
-
}
|
|
511
|
-
}, assign = Object.assign, emptyObject = {};
|
|
512
|
-
Object.freeze(emptyObject);
|
|
513
|
-
Component.prototype.isReactComponent = {};
|
|
514
|
-
Component.prototype.setState = function(partialState, callback) {
|
|
515
|
-
if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
|
|
516
|
-
throw Error(
|
|
517
|
-
"takes an object of state variables to update or a function which returns an object of state variables."
|
|
518
|
-
);
|
|
519
|
-
this.updater.enqueueSetState(this, partialState, callback, "setState");
|
|
520
|
-
};
|
|
521
|
-
Component.prototype.forceUpdate = function(callback) {
|
|
522
|
-
this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
|
|
523
|
-
};
|
|
524
|
-
var deprecatedAPIs = {
|
|
525
|
-
isMounted: [
|
|
526
|
-
"isMounted",
|
|
527
|
-
"Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
|
|
528
|
-
],
|
|
529
|
-
replaceState: [
|
|
530
|
-
"replaceState",
|
|
531
|
-
"Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
|
|
532
|
-
]
|
|
533
|
-
};
|
|
534
|
-
for (fnName in deprecatedAPIs)
|
|
535
|
-
deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
|
|
536
|
-
ComponentDummy.prototype = Component.prototype;
|
|
537
|
-
deprecatedAPIs = PureComponent.prototype = new ComponentDummy();
|
|
538
|
-
deprecatedAPIs.constructor = PureComponent;
|
|
539
|
-
assign(deprecatedAPIs, Component.prototype);
|
|
540
|
-
deprecatedAPIs.isPureReactComponent = true;
|
|
541
|
-
var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = {
|
|
542
|
-
H: null,
|
|
543
|
-
A: null,
|
|
544
|
-
T: null,
|
|
545
|
-
S: null,
|
|
546
|
-
actQueue: null,
|
|
547
|
-
asyncTransitions: 0,
|
|
548
|
-
isBatchingLegacy: false,
|
|
549
|
-
didScheduleLegacyUpdate: false,
|
|
550
|
-
didUsePromise: false,
|
|
551
|
-
thrownErrors: [],
|
|
552
|
-
getCurrentStack: null,
|
|
553
|
-
recentlyCreatedOwnerStacks: 0
|
|
554
|
-
}, hasOwnProperty = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
|
|
555
|
-
return null;
|
|
556
|
-
};
|
|
557
|
-
deprecatedAPIs = {
|
|
558
|
-
react_stack_bottom_frame: function(callStackForError) {
|
|
559
|
-
return callStackForError();
|
|
560
|
-
}
|
|
561
|
-
};
|
|
562
|
-
var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
|
|
563
|
-
var didWarnAboutElementRef = {};
|
|
564
|
-
var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
|
|
565
|
-
deprecatedAPIs,
|
|
566
|
-
UnknownOwner
|
|
567
|
-
)();
|
|
568
|
-
var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
|
|
569
|
-
var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
|
|
570
|
-
if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
|
|
571
|
-
var event = new window.ErrorEvent("error", {
|
|
572
|
-
bubbles: true,
|
|
573
|
-
cancelable: true,
|
|
574
|
-
message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
|
|
575
|
-
error
|
|
576
|
-
});
|
|
577
|
-
if (!window.dispatchEvent(event)) return;
|
|
578
|
-
} else if ("object" === typeof process && "function" === typeof process.emit) {
|
|
579
|
-
process.emit("uncaughtException", error);
|
|
580
|
-
return;
|
|
581
|
-
}
|
|
582
|
-
console.error(error);
|
|
583
|
-
}, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) {
|
|
584
|
-
queueMicrotask(function() {
|
|
585
|
-
return queueMicrotask(callback);
|
|
586
|
-
});
|
|
587
|
-
} : enqueueTask;
|
|
588
|
-
deprecatedAPIs = Object.freeze({
|
|
589
|
-
__proto__: null,
|
|
590
|
-
c: function(size) {
|
|
591
|
-
return resolveDispatcher().useMemoCache(size);
|
|
592
|
-
}
|
|
593
|
-
});
|
|
594
|
-
var fnName = {
|
|
595
|
-
map: mapChildren,
|
|
596
|
-
forEach: function(children, forEachFunc, forEachContext) {
|
|
597
|
-
mapChildren(
|
|
598
|
-
children,
|
|
599
|
-
function() {
|
|
600
|
-
forEachFunc.apply(this, arguments);
|
|
601
|
-
},
|
|
602
|
-
forEachContext
|
|
603
|
-
);
|
|
604
|
-
},
|
|
605
|
-
count: function(children) {
|
|
606
|
-
var n = 0;
|
|
607
|
-
mapChildren(children, function() {
|
|
608
|
-
n++;
|
|
609
|
-
});
|
|
610
|
-
return n;
|
|
611
|
-
},
|
|
612
|
-
toArray: function(children) {
|
|
613
|
-
return mapChildren(children, function(child) {
|
|
614
|
-
return child;
|
|
615
|
-
}) || [];
|
|
616
|
-
},
|
|
617
|
-
only: function(children) {
|
|
618
|
-
if (!isValidElement(children))
|
|
619
|
-
throw Error(
|
|
620
|
-
"React.Children.only expected to receive a single React element child."
|
|
621
|
-
);
|
|
622
|
-
return children;
|
|
623
|
-
}
|
|
624
|
-
};
|
|
625
|
-
exports.Activity = REACT_ACTIVITY_TYPE;
|
|
626
|
-
exports.Children = fnName;
|
|
627
|
-
exports.Component = Component;
|
|
628
|
-
exports.Fragment = REACT_FRAGMENT_TYPE;
|
|
629
|
-
exports.Profiler = REACT_PROFILER_TYPE;
|
|
630
|
-
exports.PureComponent = PureComponent;
|
|
631
|
-
exports.StrictMode = REACT_STRICT_MODE_TYPE;
|
|
632
|
-
exports.Suspense = REACT_SUSPENSE_TYPE;
|
|
633
|
-
exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
|
|
634
|
-
exports.__COMPILER_RUNTIME = deprecatedAPIs;
|
|
635
|
-
exports.act = function(callback) {
|
|
636
|
-
var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
|
|
637
|
-
actScopeDepth++;
|
|
638
|
-
var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false;
|
|
639
|
-
try {
|
|
640
|
-
var result = callback();
|
|
641
|
-
} catch (error) {
|
|
642
|
-
ReactSharedInternals.thrownErrors.push(error);
|
|
643
|
-
}
|
|
644
|
-
if (0 < ReactSharedInternals.thrownErrors.length)
|
|
645
|
-
throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
|
|
646
|
-
if (null !== result && "object" === typeof result && "function" === typeof result.then) {
|
|
647
|
-
var thenable = result;
|
|
648
|
-
queueSeveralMicrotasks(function() {
|
|
649
|
-
didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
|
|
650
|
-
"You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"
|
|
651
|
-
));
|
|
652
|
-
});
|
|
653
|
-
return {
|
|
654
|
-
then: function(resolve, reject) {
|
|
655
|
-
didAwaitActCall = true;
|
|
656
|
-
thenable.then(
|
|
657
|
-
function(returnValue) {
|
|
658
|
-
popActScope(prevActQueue, prevActScopeDepth);
|
|
659
|
-
if (0 === prevActScopeDepth) {
|
|
660
|
-
try {
|
|
661
|
-
flushActQueue(queue), enqueueTask(function() {
|
|
662
|
-
return recursivelyFlushAsyncActWork(
|
|
663
|
-
returnValue,
|
|
664
|
-
resolve,
|
|
665
|
-
reject
|
|
666
|
-
);
|
|
667
|
-
});
|
|
668
|
-
} catch (error$0) {
|
|
669
|
-
ReactSharedInternals.thrownErrors.push(error$0);
|
|
670
|
-
}
|
|
671
|
-
if (0 < ReactSharedInternals.thrownErrors.length) {
|
|
672
|
-
var _thrownError = aggregateErrors(
|
|
673
|
-
ReactSharedInternals.thrownErrors
|
|
674
|
-
);
|
|
675
|
-
ReactSharedInternals.thrownErrors.length = 0;
|
|
676
|
-
reject(_thrownError);
|
|
677
|
-
}
|
|
678
|
-
} else resolve(returnValue);
|
|
679
|
-
},
|
|
680
|
-
function(error) {
|
|
681
|
-
popActScope(prevActQueue, prevActScopeDepth);
|
|
682
|
-
0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(
|
|
683
|
-
ReactSharedInternals.thrownErrors
|
|
684
|
-
), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
|
|
685
|
-
}
|
|
686
|
-
);
|
|
687
|
-
}
|
|
688
|
-
};
|
|
689
|
-
}
|
|
690
|
-
var returnValue$jscomp$0 = result;
|
|
691
|
-
popActScope(prevActQueue, prevActScopeDepth);
|
|
692
|
-
0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() {
|
|
693
|
-
didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
|
|
694
|
-
"A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"
|
|
695
|
-
));
|
|
696
|
-
}), ReactSharedInternals.actQueue = null);
|
|
697
|
-
if (0 < ReactSharedInternals.thrownErrors.length)
|
|
698
|
-
throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
|
|
699
|
-
return {
|
|
700
|
-
then: function(resolve, reject) {
|
|
701
|
-
didAwaitActCall = true;
|
|
702
|
-
0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
|
|
703
|
-
return recursivelyFlushAsyncActWork(
|
|
704
|
-
returnValue$jscomp$0,
|
|
705
|
-
resolve,
|
|
706
|
-
reject
|
|
707
|
-
);
|
|
708
|
-
})) : resolve(returnValue$jscomp$0);
|
|
709
|
-
}
|
|
710
|
-
};
|
|
711
|
-
};
|
|
712
|
-
exports.cache = function(fn) {
|
|
713
|
-
return function() {
|
|
714
|
-
return fn.apply(null, arguments);
|
|
715
|
-
};
|
|
716
|
-
};
|
|
717
|
-
exports.cacheSignal = function() {
|
|
718
|
-
return null;
|
|
719
|
-
};
|
|
720
|
-
exports.captureOwnerStack = function() {
|
|
721
|
-
var getCurrentStack = ReactSharedInternals.getCurrentStack;
|
|
722
|
-
return null === getCurrentStack ? null : getCurrentStack();
|
|
723
|
-
};
|
|
724
|
-
exports.cloneElement = function(element, config, children) {
|
|
725
|
-
if (null === element || void 0 === element)
|
|
726
|
-
throw Error(
|
|
727
|
-
"The argument must be a React element, but you passed " + element + "."
|
|
728
|
-
);
|
|
729
|
-
var props = assign({}, element.props), key = element.key, owner = element._owner;
|
|
730
|
-
if (null != config) {
|
|
731
|
-
var JSCompiler_inline_result;
|
|
732
|
-
a: {
|
|
733
|
-
if (hasOwnProperty.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
|
|
734
|
-
config,
|
|
735
|
-
"ref"
|
|
736
|
-
).get) && JSCompiler_inline_result.isReactWarning) {
|
|
737
|
-
JSCompiler_inline_result = false;
|
|
738
|
-
break a;
|
|
739
|
-
}
|
|
740
|
-
JSCompiler_inline_result = void 0 !== config.ref;
|
|
741
|
-
}
|
|
742
|
-
JSCompiler_inline_result && (owner = getOwner());
|
|
743
|
-
hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
|
|
744
|
-
for (propName in config)
|
|
745
|
-
!hasOwnProperty.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
|
|
746
|
-
}
|
|
747
|
-
var propName = arguments.length - 2;
|
|
748
|
-
if (1 === propName) props.children = children;
|
|
749
|
-
else if (1 < propName) {
|
|
750
|
-
JSCompiler_inline_result = Array(propName);
|
|
751
|
-
for (var i = 0; i < propName; i++)
|
|
752
|
-
JSCompiler_inline_result[i] = arguments[i + 2];
|
|
753
|
-
props.children = JSCompiler_inline_result;
|
|
754
|
-
}
|
|
755
|
-
props = ReactElement(
|
|
756
|
-
element.type,
|
|
757
|
-
key,
|
|
758
|
-
props,
|
|
759
|
-
owner,
|
|
760
|
-
element._debugStack,
|
|
761
|
-
element._debugTask
|
|
762
|
-
);
|
|
763
|
-
for (key = 2; key < arguments.length; key++)
|
|
764
|
-
validateChildKeys(arguments[key]);
|
|
765
|
-
return props;
|
|
766
|
-
};
|
|
767
|
-
exports.createContext = function(defaultValue) {
|
|
768
|
-
defaultValue = {
|
|
769
|
-
$$typeof: REACT_CONTEXT_TYPE,
|
|
770
|
-
_currentValue: defaultValue,
|
|
771
|
-
_currentValue2: defaultValue,
|
|
772
|
-
_threadCount: 0,
|
|
773
|
-
Provider: null,
|
|
774
|
-
Consumer: null
|
|
775
|
-
};
|
|
776
|
-
defaultValue.Provider = defaultValue;
|
|
777
|
-
defaultValue.Consumer = {
|
|
778
|
-
$$typeof: REACT_CONSUMER_TYPE,
|
|
779
|
-
_context: defaultValue
|
|
780
|
-
};
|
|
781
|
-
defaultValue._currentRenderer = null;
|
|
782
|
-
defaultValue._currentRenderer2 = null;
|
|
783
|
-
return defaultValue;
|
|
784
|
-
};
|
|
785
|
-
exports.createElement = function(type, config, children) {
|
|
786
|
-
for (var i = 2; i < arguments.length; i++)
|
|
787
|
-
validateChildKeys(arguments[i]);
|
|
788
|
-
i = {};
|
|
789
|
-
var key = null;
|
|
790
|
-
if (null != config)
|
|
791
|
-
for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn(
|
|
792
|
-
"Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
|
|
793
|
-
)), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
|
|
794
|
-
hasOwnProperty.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]);
|
|
795
|
-
var childrenLength = arguments.length - 2;
|
|
796
|
-
if (1 === childrenLength) i.children = children;
|
|
797
|
-
else if (1 < childrenLength) {
|
|
798
|
-
for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++)
|
|
799
|
-
childArray[_i] = arguments[_i + 2];
|
|
800
|
-
Object.freeze && Object.freeze(childArray);
|
|
801
|
-
i.children = childArray;
|
|
802
|
-
}
|
|
803
|
-
if (type && type.defaultProps)
|
|
804
|
-
for (propName in childrenLength = type.defaultProps, childrenLength)
|
|
805
|
-
void 0 === i[propName] && (i[propName] = childrenLength[propName]);
|
|
806
|
-
key && defineKeyPropWarningGetter(
|
|
807
|
-
i,
|
|
808
|
-
"function" === typeof type ? type.displayName || type.name || "Unknown" : type
|
|
809
|
-
);
|
|
810
|
-
var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
|
|
811
|
-
return ReactElement(
|
|
812
|
-
type,
|
|
813
|
-
key,
|
|
814
|
-
i,
|
|
815
|
-
getOwner(),
|
|
816
|
-
propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
|
|
817
|
-
propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
|
|
818
|
-
);
|
|
819
|
-
};
|
|
820
|
-
exports.createRef = function() {
|
|
821
|
-
var refObject = { current: null };
|
|
822
|
-
Object.seal(refObject);
|
|
823
|
-
return refObject;
|
|
824
|
-
};
|
|
825
|
-
exports.forwardRef = function(render) {
|
|
826
|
-
null != render && render.$$typeof === REACT_MEMO_TYPE ? console.error(
|
|
827
|
-
"forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."
|
|
828
|
-
) : "function" !== typeof render ? console.error(
|
|
829
|
-
"forwardRef requires a render function but was given %s.",
|
|
830
|
-
null === render ? "null" : typeof render
|
|
831
|
-
) : 0 !== render.length && 2 !== render.length && console.error(
|
|
832
|
-
"forwardRef render functions accept exactly two parameters: props and ref. %s",
|
|
833
|
-
1 === render.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."
|
|
834
|
-
);
|
|
835
|
-
null != render && null != render.defaultProps && console.error(
|
|
836
|
-
"forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?"
|
|
837
|
-
);
|
|
838
|
-
var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
|
|
839
|
-
Object.defineProperty(elementType, "displayName", {
|
|
840
|
-
enumerable: false,
|
|
841
|
-
configurable: true,
|
|
842
|
-
get: function() {
|
|
843
|
-
return ownName;
|
|
844
|
-
},
|
|
845
|
-
set: function(name) {
|
|
846
|
-
ownName = name;
|
|
847
|
-
render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name);
|
|
848
|
-
}
|
|
849
|
-
});
|
|
850
|
-
return elementType;
|
|
851
|
-
};
|
|
852
|
-
exports.isValidElement = isValidElement;
|
|
853
|
-
exports.lazy = function(ctor) {
|
|
854
|
-
ctor = { _status: -1, _result: ctor };
|
|
855
|
-
var lazyType = {
|
|
856
|
-
$$typeof: REACT_LAZY_TYPE,
|
|
857
|
-
_payload: ctor,
|
|
858
|
-
_init: lazyInitializer
|
|
859
|
-
}, ioInfo = {
|
|
860
|
-
name: "lazy",
|
|
861
|
-
start: -1,
|
|
862
|
-
end: -1,
|
|
863
|
-
value: null,
|
|
864
|
-
owner: null,
|
|
865
|
-
debugStack: Error("react-stack-top-frame"),
|
|
866
|
-
debugTask: console.createTask ? console.createTask("lazy()") : null
|
|
867
|
-
};
|
|
868
|
-
ctor._ioInfo = ioInfo;
|
|
869
|
-
lazyType._debugInfo = [{ awaited: ioInfo }];
|
|
870
|
-
return lazyType;
|
|
871
|
-
};
|
|
872
|
-
exports.memo = function(type, compare) {
|
|
873
|
-
null == type && console.error(
|
|
874
|
-
"memo: The first argument must be a component. Instead received: %s",
|
|
875
|
-
null === type ? "null" : typeof type
|
|
876
|
-
);
|
|
877
|
-
compare = {
|
|
878
|
-
$$typeof: REACT_MEMO_TYPE,
|
|
879
|
-
type,
|
|
880
|
-
compare: void 0 === compare ? null : compare
|
|
881
|
-
};
|
|
882
|
-
var ownName;
|
|
883
|
-
Object.defineProperty(compare, "displayName", {
|
|
884
|
-
enumerable: false,
|
|
885
|
-
configurable: true,
|
|
886
|
-
get: function() {
|
|
887
|
-
return ownName;
|
|
888
|
-
},
|
|
889
|
-
set: function(name) {
|
|
890
|
-
ownName = name;
|
|
891
|
-
type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
|
|
892
|
-
}
|
|
893
|
-
});
|
|
894
|
-
return compare;
|
|
895
|
-
};
|
|
896
|
-
exports.startTransition = function(scope) {
|
|
897
|
-
var prevTransition = ReactSharedInternals.T, currentTransition = {};
|
|
898
|
-
currentTransition._updatedFibers = /* @__PURE__ */ new Set();
|
|
899
|
-
ReactSharedInternals.T = currentTransition;
|
|
900
|
-
try {
|
|
901
|
-
var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
|
|
902
|
-
null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
|
|
903
|
-
"object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop, reportGlobalError));
|
|
904
|
-
} catch (error) {
|
|
905
|
-
reportGlobalError(error);
|
|
906
|
-
} finally {
|
|
907
|
-
null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn(
|
|
908
|
-
"Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
|
|
909
|
-
)), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
|
|
910
|
-
"We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
|
|
911
|
-
), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
|
|
912
|
-
}
|
|
913
|
-
};
|
|
914
|
-
exports.unstable_useCacheRefresh = function() {
|
|
915
|
-
return resolveDispatcher().useCacheRefresh();
|
|
916
|
-
};
|
|
917
|
-
exports.use = function(usable) {
|
|
918
|
-
return resolveDispatcher().use(usable);
|
|
919
|
-
};
|
|
920
|
-
exports.useActionState = function(action, initialState, permalink) {
|
|
921
|
-
return resolveDispatcher().useActionState(
|
|
922
|
-
action,
|
|
923
|
-
initialState,
|
|
924
|
-
permalink
|
|
925
|
-
);
|
|
926
|
-
};
|
|
927
|
-
exports.useCallback = function(callback, deps) {
|
|
928
|
-
return resolveDispatcher().useCallback(callback, deps);
|
|
929
|
-
};
|
|
930
|
-
exports.useContext = function(Context) {
|
|
931
|
-
var dispatcher = resolveDispatcher();
|
|
932
|
-
Context.$$typeof === REACT_CONSUMER_TYPE && console.error(
|
|
933
|
-
"Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"
|
|
934
|
-
);
|
|
935
|
-
return dispatcher.useContext(Context);
|
|
936
|
-
};
|
|
937
|
-
exports.useDebugValue = function(value, formatterFn) {
|
|
938
|
-
return resolveDispatcher().useDebugValue(value, formatterFn);
|
|
939
|
-
};
|
|
940
|
-
exports.useDeferredValue = function(value, initialValue) {
|
|
941
|
-
return resolveDispatcher().useDeferredValue(value, initialValue);
|
|
942
|
-
};
|
|
943
|
-
exports.useEffect = function(create, deps) {
|
|
944
|
-
null == create && console.warn(
|
|
945
|
-
"React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
|
|
946
|
-
);
|
|
947
|
-
return resolveDispatcher().useEffect(create, deps);
|
|
948
|
-
};
|
|
949
|
-
exports.useEffectEvent = function(callback) {
|
|
950
|
-
return resolveDispatcher().useEffectEvent(callback);
|
|
951
|
-
};
|
|
952
|
-
exports.useId = function() {
|
|
953
|
-
return resolveDispatcher().useId();
|
|
954
|
-
};
|
|
955
|
-
exports.useImperativeHandle = function(ref, create, deps) {
|
|
956
|
-
return resolveDispatcher().useImperativeHandle(ref, create, deps);
|
|
957
|
-
};
|
|
958
|
-
exports.useInsertionEffect = function(create, deps) {
|
|
959
|
-
null == create && console.warn(
|
|
960
|
-
"React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
|
|
961
|
-
);
|
|
962
|
-
return resolveDispatcher().useInsertionEffect(create, deps);
|
|
963
|
-
};
|
|
964
|
-
exports.useLayoutEffect = function(create, deps) {
|
|
965
|
-
null == create && console.warn(
|
|
966
|
-
"React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
|
|
967
|
-
);
|
|
968
|
-
return resolveDispatcher().useLayoutEffect(create, deps);
|
|
969
|
-
};
|
|
970
|
-
exports.useMemo = function(create, deps) {
|
|
971
|
-
return resolveDispatcher().useMemo(create, deps);
|
|
972
|
-
};
|
|
973
|
-
exports.useOptimistic = function(passthrough, reducer) {
|
|
974
|
-
return resolveDispatcher().useOptimistic(passthrough, reducer);
|
|
975
|
-
};
|
|
976
|
-
exports.useReducer = function(reducer, initialArg, init) {
|
|
977
|
-
return resolveDispatcher().useReducer(reducer, initialArg, init);
|
|
978
|
-
};
|
|
979
|
-
exports.useRef = function(initialValue) {
|
|
980
|
-
return resolveDispatcher().useRef(initialValue);
|
|
981
|
-
};
|
|
982
|
-
exports.useState = function(initialState) {
|
|
983
|
-
return resolveDispatcher().useState(initialState);
|
|
984
|
-
};
|
|
985
|
-
exports.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
|
|
986
|
-
return resolveDispatcher().useSyncExternalStore(
|
|
987
|
-
subscribe,
|
|
988
|
-
getSnapshot,
|
|
989
|
-
getServerSnapshot
|
|
990
|
-
);
|
|
991
|
-
};
|
|
992
|
-
exports.useTransition = function() {
|
|
993
|
-
return resolveDispatcher().useTransition();
|
|
994
|
-
};
|
|
995
|
-
exports.version = "19.2.4";
|
|
996
|
-
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
|
|
997
|
-
})();
|
|
998
|
-
}
|
|
999
|
-
});
|
|
1000
|
-
|
|
1001
|
-
// node_modules/react/index.js
|
|
1002
|
-
var require_react = __commonJS({
|
|
1003
|
-
"node_modules/react/index.js"(exports, module) {
|
|
1004
|
-
"use strict";
|
|
1005
|
-
if (false) {
|
|
1006
|
-
module.exports = null;
|
|
1007
|
-
} else {
|
|
1008
|
-
module.exports = require_react_development();
|
|
1009
|
-
}
|
|
1010
|
-
}
|
|
1011
|
-
});
|
|
1012
|
-
|
|
1013
|
-
// node_modules/immer/dist/immer.mjs
|
|
1014
|
-
var NOTHING = /* @__PURE__ */ Symbol.for("immer-nothing");
|
|
1015
|
-
var DRAFTABLE = /* @__PURE__ */ Symbol.for("immer-draftable");
|
|
1016
|
-
var DRAFT_STATE = /* @__PURE__ */ Symbol.for("immer-state");
|
|
1017
|
-
var errors = true ? [
|
|
1018
|
-
// All error codes, starting by 0:
|
|
1019
|
-
function(plugin) {
|
|
1020
|
-
return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
|
|
1021
|
-
},
|
|
1022
|
-
function(thing) {
|
|
1023
|
-
return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
|
|
1024
|
-
},
|
|
1025
|
-
"This object has been frozen and should not be mutated",
|
|
1026
|
-
function(data) {
|
|
1027
|
-
return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
|
|
1028
|
-
},
|
|
1029
|
-
"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
|
|
1030
|
-
"Immer forbids circular references",
|
|
1031
|
-
"The first or second argument to `produce` must be a function",
|
|
1032
|
-
"The third argument to `produce` must be a function or undefined",
|
|
1033
|
-
"First argument to `createDraft` must be a plain object, an array, or an immerable object",
|
|
1034
|
-
"First argument to `finishDraft` must be a draft returned by `createDraft`",
|
|
1035
|
-
function(thing) {
|
|
1036
|
-
return `'current' expects a draft, got: ${thing}`;
|
|
1037
|
-
},
|
|
1038
|
-
"Object.defineProperty() cannot be used on an Immer draft",
|
|
1039
|
-
"Object.setPrototypeOf() cannot be used on an Immer draft",
|
|
1040
|
-
"Immer only supports deleting array indices",
|
|
1041
|
-
"Immer only supports setting array indices and the 'length' property",
|
|
1042
|
-
function(thing) {
|
|
1043
|
-
return `'original' expects a draft, got: ${thing}`;
|
|
1044
|
-
}
|
|
1045
|
-
// Note: if more errors are added, the errorOffset in Patches.ts should be increased
|
|
1046
|
-
// See Patches.ts for additional errors
|
|
1047
|
-
] : [];
|
|
1048
|
-
function die(error, ...args) {
|
|
1049
|
-
if (true) {
|
|
1050
|
-
const e = errors[error];
|
|
1051
|
-
const msg = isFunction(e) ? e.apply(null, args) : e;
|
|
1052
|
-
throw new Error(`[Immer] ${msg}`);
|
|
1053
|
-
}
|
|
1054
|
-
throw new Error(
|
|
1055
|
-
`[Immer] minified error nr: ${error}. Full error at: [SEC-REMOVED]`
|
|
1056
|
-
);
|
|
1057
|
-
}
|
|
1058
|
-
var O = Object;
|
|
1059
|
-
var getPrototypeOf = O.getPrototypeOf;
|
|
1060
|
-
var CONSTRUCTOR = "constructor";
|
|
1061
|
-
var PROTOTYPE = "prototype";
|
|
1062
|
-
var CONFIGURABLE = "configurable";
|
|
1063
|
-
var ENUMERABLE = "enumerable";
|
|
1064
|
-
var WRITABLE = "writable";
|
|
1065
|
-
var VALUE = "value";
|
|
1066
|
-
var isDraft = (value) => !!value && !!value[DRAFT_STATE];
|
|
1067
|
-
function isDraftable(value) {
|
|
1068
|
-
if (!value)
|
|
1069
|
-
return false;
|
|
1070
|
-
return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
|
|
1071
|
-
}
|
|
1072
|
-
var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
|
|
1073
|
-
var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
|
|
1074
|
-
function isPlainObject(value) {
|
|
1075
|
-
if (!value || !isObjectish(value))
|
|
1076
|
-
return false;
|
|
1077
|
-
const proto = getPrototypeOf(value);
|
|
1078
|
-
if (proto === null || proto === O[PROTOTYPE])
|
|
1079
|
-
return true;
|
|
1080
|
-
const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
|
|
1081
|
-
if (Ctor === Object)
|
|
1082
|
-
return true;
|
|
1083
|
-
if (!isFunction(Ctor))
|
|
1084
|
-
return false;
|
|
1085
|
-
let ctorString = cachedCtorStrings.get(Ctor);
|
|
1086
|
-
if (ctorString === void 0) {
|
|
1087
|
-
ctorString = Function.toString.call(Ctor);
|
|
1088
|
-
cachedCtorStrings.set(Ctor, ctorString);
|
|
1089
|
-
}
|
|
1090
|
-
return ctorString === objectCtorString;
|
|
1091
|
-
}
|
|
1092
|
-
function each(obj, iter, strict = true) {
|
|
1093
|
-
if (getArchtype(obj) === 0) {
|
|
1094
|
-
const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
|
|
1095
|
-
keys.forEach((key) => {
|
|
1096
|
-
iter(key, obj[key], obj);
|
|
1097
|
-
});
|
|
1098
|
-
} else {
|
|
1099
|
-
obj.forEach((entry, index) => iter(index, entry, obj));
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
function getArchtype(thing) {
|
|
1103
|
-
const state = thing[DRAFT_STATE];
|
|
1104
|
-
return state ? state.type_ : isArray(thing) ? 1 : isMap(thing) ? 2 : isSet(thing) ? 3 : 0;
|
|
1105
|
-
}
|
|
1106
|
-
var has = (thing, prop, type = getArchtype(thing)) => type === 2 ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
|
|
1107
|
-
var get = (thing, prop, type = getArchtype(thing)) => (
|
|
1108
|
-
// @ts-ignore
|
|
1109
|
-
type === 2 ? thing.get(prop) : thing[prop]
|
|
1110
|
-
);
|
|
1111
|
-
var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
|
|
1112
|
-
if (type === 2)
|
|
1113
|
-
thing.set(propOrOldValue, value);
|
|
1114
|
-
else if (type === 3) {
|
|
1115
|
-
thing.add(value);
|
|
1116
|
-
} else
|
|
1117
|
-
thing[propOrOldValue] = value;
|
|
1118
|
-
};
|
|
1119
|
-
function is(x, y) {
|
|
1120
|
-
if (x === y) {
|
|
1121
|
-
return x !== 0 || 1 / x === 1 / y;
|
|
1122
|
-
} else {
|
|
1123
|
-
return x !== x && y !== y;
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
var isArray = Array.isArray;
|
|
1127
|
-
var isMap = (target) => target instanceof Map;
|
|
1128
|
-
var isSet = (target) => target instanceof Set;
|
|
1129
|
-
var isObjectish = (target) => typeof target === "object";
|
|
1130
|
-
var isFunction = (target) => typeof target === "function";
|
|
1131
|
-
var isBoolean = (target) => typeof target === "boolean";
|
|
1132
|
-
function isArrayIndex(value) {
|
|
1133
|
-
const n = +value;
|
|
1134
|
-
return Number.isInteger(n) && String(n) === value;
|
|
1135
|
-
}
|
|
1136
|
-
var latest = (state) => state.copy_ || state.base_;
|
|
1137
|
-
var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
|
|
1138
|
-
function shallowCopy(base, strict) {
|
|
1139
|
-
if (isMap(base)) {
|
|
1140
|
-
return new Map(base);
|
|
1141
|
-
}
|
|
1142
|
-
if (isSet(base)) {
|
|
1143
|
-
return new Set(base);
|
|
1144
|
-
}
|
|
1145
|
-
if (isArray(base))
|
|
1146
|
-
return Array[PROTOTYPE].slice.call(base);
|
|
1147
|
-
const isPlain = isPlainObject(base);
|
|
1148
|
-
if (strict === true || strict === "class_only" && !isPlain) {
|
|
1149
|
-
const descriptors = O.getOwnPropertyDescriptors(base);
|
|
1150
|
-
delete descriptors[DRAFT_STATE];
|
|
1151
|
-
let keys = Reflect.ownKeys(descriptors);
|
|
1152
|
-
for (let i = 0; i < keys.length; i++) {
|
|
1153
|
-
const key = keys[i];
|
|
1154
|
-
const desc = descriptors[key];
|
|
1155
|
-
if (desc[WRITABLE] === false) {
|
|
1156
|
-
desc[WRITABLE] = true;
|
|
1157
|
-
desc[CONFIGURABLE] = true;
|
|
1158
|
-
}
|
|
1159
|
-
if (desc.get || desc.set)
|
|
1160
|
-
descriptors[key] = {
|
|
1161
|
-
[CONFIGURABLE]: true,
|
|
1162
|
-
[WRITABLE]: true,
|
|
1163
|
-
// could live with !!desc.set as well here...
|
|
1164
|
-
[ENUMERABLE]: desc[ENUMERABLE],
|
|
1165
|
-
[VALUE]: base[key]
|
|
1166
|
-
};
|
|
1167
|
-
}
|
|
1168
|
-
return O.create(getPrototypeOf(base), descriptors);
|
|
1169
|
-
} else {
|
|
1170
|
-
const proto = getPrototypeOf(base);
|
|
1171
|
-
if (proto !== null && isPlain) {
|
|
1172
|
-
return { ...base };
|
|
1173
|
-
}
|
|
1174
|
-
const obj = O.create(proto);
|
|
1175
|
-
return O.assign(obj, base);
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1178
|
-
function freeze(obj, deep = false) {
|
|
1179
|
-
if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
|
|
1180
|
-
return obj;
|
|
1181
|
-
if (getArchtype(obj) > 1) {
|
|
1182
|
-
O.defineProperties(obj, {
|
|
1183
|
-
set: dontMutateMethodOverride,
|
|
1184
|
-
add: dontMutateMethodOverride,
|
|
1185
|
-
clear: dontMutateMethodOverride,
|
|
1186
|
-
delete: dontMutateMethodOverride
|
|
1187
|
-
});
|
|
1188
|
-
}
|
|
1189
|
-
O.freeze(obj);
|
|
1190
|
-
if (deep)
|
|
1191
|
-
each(
|
|
1192
|
-
obj,
|
|
1193
|
-
(_key, value) => {
|
|
1194
|
-
freeze(value, true);
|
|
1195
|
-
},
|
|
1196
|
-
false
|
|
1197
|
-
);
|
|
1198
|
-
return obj;
|
|
1199
|
-
}
|
|
1200
|
-
function dontMutateFrozenCollections() {
|
|
1201
|
-
die(2);
|
|
1202
|
-
}
|
|
1203
|
-
var dontMutateMethodOverride = {
|
|
1204
|
-
[VALUE]: dontMutateFrozenCollections
|
|
1205
|
-
};
|
|
1206
|
-
function isFrozen(obj) {
|
|
1207
|
-
if (obj === null || !isObjectish(obj))
|
|
1208
|
-
return true;
|
|
1209
|
-
return O.isFrozen(obj);
|
|
1210
|
-
}
|
|
1211
|
-
var PluginMapSet = "MapSet";
|
|
1212
|
-
var PluginPatches = "Patches";
|
|
1213
|
-
var PluginArrayMethods = "ArrayMethods";
|
|
1214
|
-
var plugins = {};
|
|
1215
|
-
function getPlugin(pluginKey) {
|
|
1216
|
-
const plugin = plugins[pluginKey];
|
|
1217
|
-
if (!plugin) {
|
|
1218
|
-
die(0, pluginKey);
|
|
1219
|
-
}
|
|
1220
|
-
return plugin;
|
|
1221
|
-
}
|
|
1222
|
-
var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
|
|
1223
|
-
var currentScope;
|
|
1224
|
-
var getCurrentScope = () => currentScope;
|
|
1225
|
-
var createScope = (parent_, immer_) => ({
|
|
1226
|
-
drafts_: [],
|
|
1227
|
-
parent_,
|
|
1228
|
-
immer_,
|
|
1229
|
-
// Whenever the modified draft contains a draft from another scope, we
|
|
1230
|
-
// need to prevent auto-freezing so the unowned draft can be finalized.
|
|
1231
|
-
canAutoFreeze_: true,
|
|
1232
|
-
unfinalizedDrafts_: 0,
|
|
1233
|
-
handledSet_: /* @__PURE__ */ new Set(),
|
|
1234
|
-
processedForPatches_: /* @__PURE__ */ new Set(),
|
|
1235
|
-
mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
|
|
1236
|
-
arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
|
|
1237
|
-
});
|
|
1238
|
-
function usePatchesInScope(scope, patchListener) {
|
|
1239
|
-
if (patchListener) {
|
|
1240
|
-
scope.patchPlugin_ = getPlugin(PluginPatches);
|
|
1241
|
-
scope.patches_ = [];
|
|
1242
|
-
scope.inversePatches_ = [];
|
|
1243
|
-
scope.patchListener_ = patchListener;
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
function revokeScope(scope) {
|
|
1247
|
-
leaveScope(scope);
|
|
1248
|
-
scope.drafts_.forEach(revokeDraft);
|
|
1249
|
-
scope.drafts_ = null;
|
|
1250
|
-
}
|
|
1251
|
-
function leaveScope(scope) {
|
|
1252
|
-
if (scope === currentScope) {
|
|
1253
|
-
currentScope = scope.parent_;
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
|
|
1257
|
-
function revokeDraft(draft) {
|
|
1258
|
-
const state = draft[DRAFT_STATE];
|
|
1259
|
-
if (state.type_ === 0 || state.type_ === 1)
|
|
1260
|
-
state.revoke_();
|
|
1261
|
-
else
|
|
1262
|
-
state.revoked_ = true;
|
|
1263
|
-
}
|
|
1264
|
-
function processResult(result, scope) {
|
|
1265
|
-
scope.unfinalizedDrafts_ = scope.drafts_.length;
|
|
1266
|
-
const baseDraft = scope.drafts_[0];
|
|
1267
|
-
const isReplaced = result !== void 0 && result !== baseDraft;
|
|
1268
|
-
if (isReplaced) {
|
|
1269
|
-
if (baseDraft[DRAFT_STATE].modified_) {
|
|
1270
|
-
revokeScope(scope);
|
|
1271
|
-
die(4);
|
|
1272
|
-
}
|
|
1273
|
-
if (isDraftable(result)) {
|
|
1274
|
-
result = finalize(scope, result);
|
|
1275
|
-
}
|
|
1276
|
-
const { patchPlugin_ } = scope;
|
|
1277
|
-
if (patchPlugin_) {
|
|
1278
|
-
patchPlugin_.generateReplacementPatches_(
|
|
1279
|
-
baseDraft[DRAFT_STATE].base_,
|
|
1280
|
-
result,
|
|
1281
|
-
scope
|
|
1282
|
-
);
|
|
1283
|
-
}
|
|
1284
|
-
} else {
|
|
1285
|
-
result = finalize(scope, baseDraft);
|
|
1286
|
-
}
|
|
1287
|
-
maybeFreeze(scope, result, true);
|
|
1288
|
-
revokeScope(scope);
|
|
1289
|
-
if (scope.patches_) {
|
|
1290
|
-
scope.patchListener_(scope.patches_, scope.inversePatches_);
|
|
1291
|
-
}
|
|
1292
|
-
return result !== NOTHING ? result : void 0;
|
|
1293
|
-
}
|
|
1294
|
-
function finalize(rootScope, value) {
|
|
1295
|
-
if (isFrozen(value))
|
|
1296
|
-
return value;
|
|
1297
|
-
const state = value[DRAFT_STATE];
|
|
1298
|
-
if (!state) {
|
|
1299
|
-
const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
|
|
1300
|
-
return finalValue;
|
|
1301
|
-
}
|
|
1302
|
-
if (!isSameScope(state, rootScope)) {
|
|
1303
|
-
return value;
|
|
1304
|
-
}
|
|
1305
|
-
if (!state.modified_) {
|
|
1306
|
-
return state.base_;
|
|
1307
|
-
}
|
|
1308
|
-
if (!state.finalized_) {
|
|
1309
|
-
const { callbacks_ } = state;
|
|
1310
|
-
if (callbacks_) {
|
|
1311
|
-
while (callbacks_.length > 0) {
|
|
1312
|
-
const callback = callbacks_.pop();
|
|
1313
|
-
callback(rootScope);
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
|
-
generatePatchesAndFinalize(state, rootScope);
|
|
1317
|
-
}
|
|
1318
|
-
return state.copy_;
|
|
1319
|
-
}
|
|
1320
|
-
function maybeFreeze(scope, value, deep = false) {
|
|
1321
|
-
if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
|
|
1322
|
-
freeze(value, deep);
|
|
1323
|
-
}
|
|
1324
|
-
}
|
|
1325
|
-
function markStateFinalized(state) {
|
|
1326
|
-
state.finalized_ = true;
|
|
1327
|
-
state.scope_.unfinalizedDrafts_--;
|
|
1328
|
-
}
|
|
1329
|
-
var isSameScope = (state, rootScope) => state.scope_ === rootScope;
|
|
1330
|
-
var EMPTY_LOCATIONS_RESULT = [];
|
|
1331
|
-
function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
|
|
1332
|
-
const parentCopy = latest(parent);
|
|
1333
|
-
const parentType = parent.type_;
|
|
1334
|
-
if (originalKey !== void 0) {
|
|
1335
|
-
const currentValue = get(parentCopy, originalKey, parentType);
|
|
1336
|
-
if (currentValue === draftValue) {
|
|
1337
|
-
set(parentCopy, originalKey, finalizedValue, parentType);
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
if (!parent.draftLocations_) {
|
|
1342
|
-
const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
|
|
1343
|
-
each(parentCopy, (key, value) => {
|
|
1344
|
-
if (isDraft(value)) {
|
|
1345
|
-
const keys = draftLocations.get(value) || [];
|
|
1346
|
-
keys.push(key);
|
|
1347
|
-
draftLocations.set(value, keys);
|
|
1348
|
-
}
|
|
1349
|
-
});
|
|
1350
|
-
}
|
|
1351
|
-
const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
|
|
1352
|
-
for (const location of locations) {
|
|
1353
|
-
set(parentCopy, location, finalizedValue, parentType);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
function registerChildFinalizationCallback(parent, child, key) {
|
|
1357
|
-
parent.callbacks_.push(function childCleanup(rootScope) {
|
|
1358
|
-
const state = child;
|
|
1359
|
-
if (!state || !isSameScope(state, rootScope)) {
|
|
1360
|
-
return;
|
|
1361
|
-
}
|
|
1362
|
-
rootScope.mapSetPlugin_?.fixSetContents(state);
|
|
1363
|
-
const finalizedValue = getFinalValue(state);
|
|
1364
|
-
updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
|
|
1365
|
-
generatePatchesAndFinalize(state, rootScope);
|
|
1366
|
-
});
|
|
1367
|
-
}
|
|
1368
|
-
function generatePatchesAndFinalize(state, rootScope) {
|
|
1369
|
-
const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 || state.type_ === 1 && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);
|
|
1370
|
-
if (shouldFinalize) {
|
|
1371
|
-
const { patchPlugin_ } = rootScope;
|
|
1372
|
-
if (patchPlugin_) {
|
|
1373
|
-
const basePath = patchPlugin_.getPath(state);
|
|
1374
|
-
if (basePath) {
|
|
1375
|
-
patchPlugin_.generatePatches_(state, basePath, rootScope);
|
|
1376
|
-
}
|
|
1377
|
-
}
|
|
1378
|
-
markStateFinalized(state);
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
function handleCrossReference(target, key, value) {
|
|
1382
|
-
const { scope_ } = target;
|
|
1383
|
-
if (isDraft(value)) {
|
|
1384
|
-
const state = value[DRAFT_STATE];
|
|
1385
|
-
if (isSameScope(state, scope_)) {
|
|
1386
|
-
state.callbacks_.push(function crossReferenceCleanup() {
|
|
1387
|
-
prepareCopy(target);
|
|
1388
|
-
const finalizedValue = getFinalValue(state);
|
|
1389
|
-
updateDraftInParent(target, value, finalizedValue, key);
|
|
1390
|
-
});
|
|
1391
|
-
}
|
|
1392
|
-
} else if (isDraftable(value)) {
|
|
1393
|
-
target.callbacks_.push(function nestedDraftCleanup() {
|
|
1394
|
-
const targetCopy = latest(target);
|
|
1395
|
-
if (target.type_ === 3) {
|
|
1396
|
-
if (targetCopy.has(value)) {
|
|
1397
|
-
handleValue(value, scope_.handledSet_, scope_);
|
|
1398
|
-
}
|
|
1399
|
-
} else {
|
|
1400
|
-
if (get(targetCopy, key, target.type_) === value) {
|
|
1401
|
-
if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {
|
|
1402
|
-
handleValue(
|
|
1403
|
-
get(target.copy_, key, target.type_),
|
|
1404
|
-
scope_.handledSet_,
|
|
1405
|
-
scope_
|
|
1406
|
-
);
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
});
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
function handleValue(target, handledSet, rootScope) {
|
|
1414
|
-
if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
|
|
1415
|
-
return target;
|
|
1416
|
-
}
|
|
1417
|
-
if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
|
|
1418
|
-
return target;
|
|
1419
|
-
}
|
|
1420
|
-
handledSet.add(target);
|
|
1421
|
-
each(target, (key, value) => {
|
|
1422
|
-
if (isDraft(value)) {
|
|
1423
|
-
const state = value[DRAFT_STATE];
|
|
1424
|
-
if (isSameScope(state, rootScope)) {
|
|
1425
|
-
const updatedValue = getFinalValue(state);
|
|
1426
|
-
set(target, key, updatedValue, target.type_);
|
|
1427
|
-
markStateFinalized(state);
|
|
1428
|
-
}
|
|
1429
|
-
} else if (isDraftable(value)) {
|
|
1430
|
-
handleValue(value, handledSet, rootScope);
|
|
1431
|
-
}
|
|
1432
|
-
});
|
|
1433
|
-
return target;
|
|
1434
|
-
}
|
|
1435
|
-
function createProxyProxy(base, parent) {
|
|
1436
|
-
const baseIsArray = isArray(base);
|
|
1437
|
-
const state = {
|
|
1438
|
-
type_: baseIsArray ? 1 : 0,
|
|
1439
|
-
// Track which produce call this is associated with.
|
|
1440
|
-
scope_: parent ? parent.scope_ : getCurrentScope(),
|
|
1441
|
-
// True for both shallow and deep changes.
|
|
1442
|
-
modified_: false,
|
|
1443
|
-
// Used during finalization.
|
|
1444
|
-
finalized_: false,
|
|
1445
|
-
// Track which properties have been assigned (true) or deleted (false).
|
|
1446
|
-
// actually instantiated in `prepareCopy()`
|
|
1447
|
-
assigned_: void 0,
|
|
1448
|
-
// The parent draft state.
|
|
1449
|
-
parent_: parent,
|
|
1450
|
-
// The base state.
|
|
1451
|
-
base_: base,
|
|
1452
|
-
// The base proxy.
|
|
1453
|
-
draft_: null,
|
|
1454
|
-
// set below
|
|
1455
|
-
// The base copy with any updated values.
|
|
1456
|
-
copy_: null,
|
|
1457
|
-
// Called by the `produce` function.
|
|
1458
|
-
revoke_: null,
|
|
1459
|
-
isManual_: false,
|
|
1460
|
-
// `callbacks` actually gets assigned in `createProxy`
|
|
1461
|
-
callbacks_: void 0
|
|
1462
|
-
};
|
|
1463
|
-
let target = state;
|
|
1464
|
-
let traps = objectTraps;
|
|
1465
|
-
if (baseIsArray) {
|
|
1466
|
-
target = [state];
|
|
1467
|
-
traps = arrayTraps;
|
|
1468
|
-
}
|
|
1469
|
-
const { revoke, proxy } = Proxy.revocable(target, traps);
|
|
1470
|
-
state.draft_ = proxy;
|
|
1471
|
-
state.revoke_ = revoke;
|
|
1472
|
-
return [proxy, state];
|
|
1473
|
-
}
|
|
1474
|
-
var objectTraps = {
|
|
1475
|
-
get(state, prop) {
|
|
1476
|
-
if (prop === DRAFT_STATE)
|
|
1477
|
-
return state;
|
|
1478
|
-
let arrayPlugin = state.scope_.arrayMethodsPlugin_;
|
|
1479
|
-
const isArrayWithStringProp = state.type_ === 1 && typeof prop === "string";
|
|
1480
|
-
if (isArrayWithStringProp) {
|
|
1481
|
-
if (arrayPlugin?.isArrayOperationMethod(prop)) {
|
|
1482
|
-
return arrayPlugin.createMethodInterceptor(state, prop);
|
|
1483
|
-
}
|
|
1484
|
-
}
|
|
1485
|
-
const source = latest(state);
|
|
1486
|
-
if (!has(source, prop, state.type_)) {
|
|
1487
|
-
return readPropFromProto(state, source, prop);
|
|
1488
|
-
}
|
|
1489
|
-
const value = source[prop];
|
|
1490
|
-
if (state.finalized_ || !isDraftable(value)) {
|
|
1491
|
-
return value;
|
|
1492
|
-
}
|
|
1493
|
-
if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(
|
|
1494
|
-
state.operationMethod
|
|
1495
|
-
) && isArrayIndex(prop)) {
|
|
1496
|
-
return value;
|
|
1497
|
-
}
|
|
1498
|
-
if (value === peek(state.base_, prop)) {
|
|
1499
|
-
prepareCopy(state);
|
|
1500
|
-
const childKey = state.type_ === 1 ? +prop : prop;
|
|
1501
|
-
const childDraft = createProxy(state.scope_, value, state, childKey);
|
|
1502
|
-
return state.copy_[childKey] = childDraft;
|
|
1503
|
-
}
|
|
1504
|
-
return value;
|
|
1505
|
-
},
|
|
1506
|
-
has(state, prop) {
|
|
1507
|
-
return prop in latest(state);
|
|
1508
|
-
},
|
|
1509
|
-
ownKeys(state) {
|
|
1510
|
-
return Reflect.ownKeys(latest(state));
|
|
1511
|
-
},
|
|
1512
|
-
set(state, prop, value) {
|
|
1513
|
-
const desc = getDescriptorFromProto(latest(state), prop);
|
|
1514
|
-
if (desc?.set) {
|
|
1515
|
-
desc.set.call(state.draft_, value);
|
|
1516
|
-
return true;
|
|
1517
|
-
}
|
|
1518
|
-
if (!state.modified_) {
|
|
1519
|
-
const current2 = peek(latest(state), prop);
|
|
1520
|
-
const currentState = current2?.[DRAFT_STATE];
|
|
1521
|
-
if (currentState && currentState.base_ === value) {
|
|
1522
|
-
state.copy_[prop] = value;
|
|
1523
|
-
state.assigned_.set(prop, false);
|
|
1524
|
-
return true;
|
|
1525
|
-
}
|
|
1526
|
-
if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))
|
|
1527
|
-
return true;
|
|
1528
|
-
prepareCopy(state);
|
|
1529
|
-
markChanged(state);
|
|
1530
|
-
}
|
|
1531
|
-
if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
|
|
1532
|
-
(value !== void 0 || prop in state.copy_) || // special case: NaN
|
|
1533
|
-
Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
|
|
1534
|
-
return true;
|
|
1535
|
-
state.copy_[prop] = value;
|
|
1536
|
-
state.assigned_.set(prop, true);
|
|
1537
|
-
handleCrossReference(state, prop, value);
|
|
1538
|
-
return true;
|
|
1539
|
-
},
|
|
1540
|
-
deleteProperty(state, prop) {
|
|
1541
|
-
prepareCopy(state);
|
|
1542
|
-
if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
|
|
1543
|
-
state.assigned_.set(prop, false);
|
|
1544
|
-
markChanged(state);
|
|
1545
|
-
} else {
|
|
1546
|
-
state.assigned_.delete(prop);
|
|
1547
|
-
}
|
|
1548
|
-
if (state.copy_) {
|
|
1549
|
-
delete state.copy_[prop];
|
|
1550
|
-
}
|
|
1551
|
-
return true;
|
|
1552
|
-
},
|
|
1553
|
-
// Note: We never coerce `desc.value` into an Immer draft, because we can't make
|
|
1554
|
-
// the same guarantee in ES5 mode.
|
|
1555
|
-
getOwnPropertyDescriptor(state, prop) {
|
|
1556
|
-
const owner = latest(state);
|
|
1557
|
-
const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
|
|
1558
|
-
if (!desc)
|
|
1559
|
-
return desc;
|
|
1560
|
-
return {
|
|
1561
|
-
[WRITABLE]: true,
|
|
1562
|
-
[CONFIGURABLE]: state.type_ !== 1 || prop !== "length",
|
|
1563
|
-
[ENUMERABLE]: desc[ENUMERABLE],
|
|
1564
|
-
[VALUE]: owner[prop]
|
|
1565
|
-
};
|
|
1566
|
-
},
|
|
1567
|
-
defineProperty() {
|
|
1568
|
-
die(11);
|
|
1569
|
-
},
|
|
1570
|
-
getPrototypeOf(state) {
|
|
1571
|
-
return getPrototypeOf(state.base_);
|
|
1572
|
-
},
|
|
1573
|
-
setPrototypeOf() {
|
|
1574
|
-
die(12);
|
|
1575
|
-
}
|
|
1576
|
-
};
|
|
1577
|
-
var arrayTraps = {};
|
|
1578
|
-
for (let key in objectTraps) {
|
|
1579
|
-
let fn = objectTraps[key];
|
|
1580
|
-
arrayTraps[key] = function() {
|
|
1581
|
-
const args = arguments;
|
|
1582
|
-
args[0] = args[0][0];
|
|
1583
|
-
return fn.apply(this, args);
|
|
1584
|
-
};
|
|
1585
|
-
}
|
|
1586
|
-
arrayTraps.deleteProperty = function(state, prop) {
|
|
1587
|
-
if (isNaN(parseInt(prop)))
|
|
1588
|
-
die(13);
|
|
1589
|
-
return arrayTraps.set.call(this, state, prop, void 0);
|
|
1590
|
-
};
|
|
1591
|
-
arrayTraps.set = function(state, prop, value) {
|
|
1592
|
-
if (prop !== "length" && isNaN(parseInt(prop)))
|
|
1593
|
-
die(14);
|
|
1594
|
-
return objectTraps.set.call(this, state[0], prop, value, state[0]);
|
|
1595
|
-
};
|
|
1596
|
-
function peek(draft, prop) {
|
|
1597
|
-
const state = draft[DRAFT_STATE];
|
|
1598
|
-
const source = state ? latest(state) : draft;
|
|
1599
|
-
return source[prop];
|
|
1600
|
-
}
|
|
1601
|
-
function readPropFromProto(state, source, prop) {
|
|
1602
|
-
const desc = getDescriptorFromProto(source, prop);
|
|
1603
|
-
return desc ? VALUE in desc ? desc[VALUE] : (
|
|
1604
|
-
// This is a very special case, if the prop is a getter defined by the
|
|
1605
|
-
// prototype, we should invoke it with the draft as context!
|
|
1606
|
-
desc.get?.call(state.draft_)
|
|
1607
|
-
) : void 0;
|
|
1608
|
-
}
|
|
1609
|
-
function getDescriptorFromProto(source, prop) {
|
|
1610
|
-
if (!(prop in source))
|
|
1611
|
-
return void 0;
|
|
1612
|
-
let proto = getPrototypeOf(source);
|
|
1613
|
-
while (proto) {
|
|
1614
|
-
const desc = Object.getOwnPropertyDescriptor(proto, prop);
|
|
1615
|
-
if (desc)
|
|
1616
|
-
return desc;
|
|
1617
|
-
proto = getPrototypeOf(proto);
|
|
1618
|
-
}
|
|
1619
|
-
return void 0;
|
|
1620
|
-
}
|
|
1621
|
-
function markChanged(state) {
|
|
1622
|
-
if (!state.modified_) {
|
|
1623
|
-
state.modified_ = true;
|
|
1624
|
-
if (state.parent_) {
|
|
1625
|
-
markChanged(state.parent_);
|
|
1626
|
-
}
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
function prepareCopy(state) {
|
|
1630
|
-
if (!state.copy_) {
|
|
1631
|
-
state.assigned_ = /* @__PURE__ */ new Map();
|
|
1632
|
-
state.copy_ = shallowCopy(
|
|
1633
|
-
state.base_,
|
|
1634
|
-
state.scope_.immer_.useStrictShallowCopy_
|
|
1635
|
-
);
|
|
1636
|
-
}
|
|
1637
|
-
}
|
|
1638
|
-
var Immer2 = class {
|
|
1639
|
-
constructor(config) {
|
|
1640
|
-
this.autoFreeze_ = true;
|
|
1641
|
-
this.useStrictShallowCopy_ = false;
|
|
1642
|
-
this.useStrictIteration_ = false;
|
|
1643
|
-
this.produce = (base, recipe, patchListener) => {
|
|
1644
|
-
if (isFunction(base) && !isFunction(recipe)) {
|
|
1645
|
-
const defaultBase = recipe;
|
|
1646
|
-
recipe = base;
|
|
1647
|
-
const self = this;
|
|
1648
|
-
return function curriedProduce(base2 = defaultBase, ...args) {
|
|
1649
|
-
return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
|
|
1650
|
-
};
|
|
1651
|
-
}
|
|
1652
|
-
if (!isFunction(recipe))
|
|
1653
|
-
die(6);
|
|
1654
|
-
if (patchListener !== void 0 && !isFunction(patchListener))
|
|
1655
|
-
die(7);
|
|
1656
|
-
let result;
|
|
1657
|
-
if (isDraftable(base)) {
|
|
1658
|
-
const scope = enterScope(this);
|
|
1659
|
-
const proxy = createProxy(scope, base, void 0);
|
|
1660
|
-
let hasError = true;
|
|
1661
|
-
try {
|
|
1662
|
-
result = recipe(proxy);
|
|
1663
|
-
hasError = false;
|
|
1664
|
-
} finally {
|
|
1665
|
-
if (hasError)
|
|
1666
|
-
revokeScope(scope);
|
|
1667
|
-
else
|
|
1668
|
-
leaveScope(scope);
|
|
1669
|
-
}
|
|
1670
|
-
usePatchesInScope(scope, patchListener);
|
|
1671
|
-
return processResult(result, scope);
|
|
1672
|
-
} else if (!base || !isObjectish(base)) {
|
|
1673
|
-
result = recipe(base);
|
|
1674
|
-
if (result === void 0)
|
|
1675
|
-
result = base;
|
|
1676
|
-
if (result === NOTHING)
|
|
1677
|
-
result = void 0;
|
|
1678
|
-
if (this.autoFreeze_)
|
|
1679
|
-
freeze(result, true);
|
|
1680
|
-
if (patchListener) {
|
|
1681
|
-
const p = [];
|
|
1682
|
-
const ip = [];
|
|
1683
|
-
getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
|
|
1684
|
-
patches_: p,
|
|
1685
|
-
inversePatches_: ip
|
|
1686
|
-
});
|
|
1687
|
-
patchListener(p, ip);
|
|
1688
|
-
}
|
|
1689
|
-
return result;
|
|
1690
|
-
} else
|
|
1691
|
-
die(1, base);
|
|
1692
|
-
};
|
|
1693
|
-
this.produceWithPatches = (base, recipe) => {
|
|
1694
|
-
if (isFunction(base)) {
|
|
1695
|
-
return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
|
|
1696
|
-
}
|
|
1697
|
-
let patches, inversePatches;
|
|
1698
|
-
const result = this.produce(base, recipe, (p, ip) => {
|
|
1699
|
-
patches = p;
|
|
1700
|
-
inversePatches = ip;
|
|
1701
|
-
});
|
|
1702
|
-
return [result, patches, inversePatches];
|
|
1703
|
-
};
|
|
1704
|
-
if (isBoolean(config?.autoFreeze))
|
|
1705
|
-
this.setAutoFreeze(config.autoFreeze);
|
|
1706
|
-
if (isBoolean(config?.useStrictShallowCopy))
|
|
1707
|
-
this.setUseStrictShallowCopy(config.useStrictShallowCopy);
|
|
1708
|
-
if (isBoolean(config?.useStrictIteration))
|
|
1709
|
-
this.setUseStrictIteration(config.useStrictIteration);
|
|
1710
|
-
}
|
|
1711
|
-
createDraft(base) {
|
|
1712
|
-
if (!isDraftable(base))
|
|
1713
|
-
die(8);
|
|
1714
|
-
if (isDraft(base))
|
|
1715
|
-
base = current(base);
|
|
1716
|
-
const scope = enterScope(this);
|
|
1717
|
-
const proxy = createProxy(scope, base, void 0);
|
|
1718
|
-
proxy[DRAFT_STATE].isManual_ = true;
|
|
1719
|
-
leaveScope(scope);
|
|
1720
|
-
return proxy;
|
|
1721
|
-
}
|
|
1722
|
-
finishDraft(draft, patchListener) {
|
|
1723
|
-
const state = draft && draft[DRAFT_STATE];
|
|
1724
|
-
if (!state || !state.isManual_)
|
|
1725
|
-
die(9);
|
|
1726
|
-
const { scope_: scope } = state;
|
|
1727
|
-
usePatchesInScope(scope, patchListener);
|
|
1728
|
-
return processResult(void 0, scope);
|
|
1729
|
-
}
|
|
1730
|
-
/**
|
|
1731
|
-
* Pass true to automatically freeze all copies created by Immer.
|
|
1732
|
-
*
|
|
1733
|
-
* By default, auto-freezing is enabled.
|
|
1734
|
-
*/
|
|
1735
|
-
setAutoFreeze(value) {
|
|
1736
|
-
this.autoFreeze_ = value;
|
|
1737
|
-
}
|
|
1738
|
-
/**
|
|
1739
|
-
* Pass true to enable strict shallow copy.
|
|
1740
|
-
*
|
|
1741
|
-
* By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
|
|
1742
|
-
*/
|
|
1743
|
-
setUseStrictShallowCopy(value) {
|
|
1744
|
-
this.useStrictShallowCopy_ = value;
|
|
1745
|
-
}
|
|
1746
|
-
/**
|
|
1747
|
-
* Pass false to use faster iteration that skips non-enumerable properties
|
|
1748
|
-
* but still handles symbols for compatibility.
|
|
1749
|
-
*
|
|
1750
|
-
* By default, strict iteration is enabled (includes all own properties).
|
|
1751
|
-
*/
|
|
1752
|
-
setUseStrictIteration(value) {
|
|
1753
|
-
this.useStrictIteration_ = value;
|
|
1754
|
-
}
|
|
1755
|
-
shouldUseStrictIteration() {
|
|
1756
|
-
return this.useStrictIteration_;
|
|
1757
|
-
}
|
|
1758
|
-
applyPatches(base, patches) {
|
|
1759
|
-
let i;
|
|
1760
|
-
for (i = patches.length - 1; i >= 0; i--) {
|
|
1761
|
-
const patch = patches[i];
|
|
1762
|
-
if (patch.path.length === 0 && patch.op === "replace") {
|
|
1763
|
-
base = patch.value;
|
|
1764
|
-
break;
|
|
1765
|
-
}
|
|
1766
|
-
}
|
|
1767
|
-
if (i > -1) {
|
|
1768
|
-
patches = patches.slice(i + 1);
|
|
1769
|
-
}
|
|
1770
|
-
const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
|
|
1771
|
-
if (isDraft(base)) {
|
|
1772
|
-
return applyPatchesImpl(base, patches);
|
|
1773
|
-
}
|
|
1774
|
-
return this.produce(
|
|
1775
|
-
base,
|
|
1776
|
-
(draft) => applyPatchesImpl(draft, patches)
|
|
1777
|
-
);
|
|
1778
|
-
}
|
|
1779
|
-
};
|
|
1780
|
-
function createProxy(rootScope, value, parent, key) {
|
|
1781
|
-
const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
|
|
1782
|
-
const scope = parent?.scope_ ?? getCurrentScope();
|
|
1783
|
-
scope.drafts_.push(draft);
|
|
1784
|
-
state.callbacks_ = parent?.callbacks_ ?? [];
|
|
1785
|
-
state.key_ = key;
|
|
1786
|
-
if (parent && key !== void 0) {
|
|
1787
|
-
registerChildFinalizationCallback(parent, state, key);
|
|
1788
|
-
} else {
|
|
1789
|
-
state.callbacks_.push(function rootDraftCleanup(rootScope2) {
|
|
1790
|
-
rootScope2.mapSetPlugin_?.fixSetContents(state);
|
|
1791
|
-
const { patchPlugin_ } = rootScope2;
|
|
1792
|
-
if (state.modified_ && patchPlugin_) {
|
|
1793
|
-
patchPlugin_.generatePatches_(state, [], rootScope2);
|
|
1794
|
-
}
|
|
1795
|
-
});
|
|
1796
|
-
}
|
|
1797
|
-
return draft;
|
|
1798
|
-
}
|
|
1799
|
-
function current(value) {
|
|
1800
|
-
if (!isDraft(value))
|
|
1801
|
-
die(10, value);
|
|
1802
|
-
return currentImpl(value);
|
|
1803
|
-
}
|
|
1804
|
-
function currentImpl(value) {
|
|
1805
|
-
if (!isDraftable(value) || isFrozen(value))
|
|
1806
|
-
return value;
|
|
1807
|
-
const state = value[DRAFT_STATE];
|
|
1808
|
-
let copy;
|
|
1809
|
-
let strict = true;
|
|
1810
|
-
if (state) {
|
|
1811
|
-
if (!state.modified_)
|
|
1812
|
-
return state.base_;
|
|
1813
|
-
state.finalized_ = true;
|
|
1814
|
-
copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
|
|
1815
|
-
strict = state.scope_.immer_.shouldUseStrictIteration();
|
|
1816
|
-
} else {
|
|
1817
|
-
copy = shallowCopy(value, true);
|
|
1818
|
-
}
|
|
1819
|
-
each(
|
|
1820
|
-
copy,
|
|
1821
|
-
(key, childValue) => {
|
|
1822
|
-
set(copy, key, currentImpl(childValue));
|
|
1823
|
-
},
|
|
1824
|
-
strict
|
|
1825
|
-
);
|
|
1826
|
-
if (state) {
|
|
1827
|
-
state.finalized_ = false;
|
|
1828
|
-
}
|
|
1829
|
-
return copy;
|
|
1830
|
-
}
|
|
1831
|
-
var immer = new Immer2();
|
|
1832
|
-
var produce = immer.produce;
|
|
1833
|
-
|
|
1834
|
-
// core/security.ts
|
|
1835
|
-
var REGEX_TIMEOUT_MS = 100;
|
|
1836
|
-
var safeRegexTest = (pattern, key) => {
|
|
1837
|
-
const startTime = Date.now();
|
|
1838
|
-
if (/\(\.*\+\?\)\+/.test(pattern) || /\(\.*\?\)\*/.test(pattern)) {
|
|
1839
|
-
console.warn(`[gstate] Potentially dangerous regex pattern blocked: ${pattern}`);
|
|
1840
|
-
return false;
|
|
1841
|
-
}
|
|
1842
|
-
if (pattern.length > 500) {
|
|
1843
|
-
console.warn(`[gstate] Regex pattern exceeds maximum length limit`);
|
|
1844
|
-
return false;
|
|
1845
|
-
}
|
|
1846
|
-
try {
|
|
1847
|
-
const regex = new RegExp(pattern);
|
|
1848
|
-
const result = regex.test(key);
|
|
1849
|
-
const elapsed = Date.now() - startTime;
|
|
1850
|
-
if (elapsed > REGEX_TIMEOUT_MS) {
|
|
1851
|
-
console.warn(`[gstate] Slow regex detected (${elapsed}ms) for pattern: ${pattern}`);
|
|
1852
|
-
}
|
|
1853
|
-
return result;
|
|
1854
|
-
} catch {
|
|
1855
|
-
return false;
|
|
1856
|
-
}
|
|
1857
|
-
};
|
|
1858
|
-
var safeRandomUUID = () => {
|
|
1859
|
-
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
1860
|
-
try {
|
|
1861
|
-
return crypto.randomUUID();
|
|
1862
|
-
} catch {
|
|
1863
|
-
}
|
|
1864
|
-
}
|
|
1865
|
-
throw new Error("Cryptographically secure random UUID generation is required but crypto.randomUUID is unavailable. Please use a browser or environment with Web Crypto API support.");
|
|
1866
|
-
};
|
|
1867
|
-
var isCryptoAvailable = typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined" && typeof crypto.subtle.generateKey === "function";
|
|
1868
|
-
var deriveKeyFromPassword = async (password, salt, iterations = 1e5) => {
|
|
1869
|
-
if (!isCryptoAvailable) throw new Error("Web Crypto API not available");
|
|
1870
|
-
const passwordKey = await crypto.subtle.importKey(
|
|
1871
|
-
"raw",
|
|
1872
|
-
new TextEncoder().encode(password),
|
|
1873
|
-
"PBKDF2",
|
|
1874
|
-
false,
|
|
1875
|
-
["deriveKey"]
|
|
1876
|
-
);
|
|
1877
|
-
const key = await crypto.subtle.deriveKey(
|
|
1878
|
-
{
|
|
1879
|
-
name: "PBKDF2",
|
|
1880
|
-
salt: new Uint8Array(salt),
|
|
1881
|
-
iterations,
|
|
1882
|
-
hash: "SHA-256"
|
|
1883
|
-
},
|
|
1884
|
-
passwordKey,
|
|
1885
|
-
{ name: "AES-GCM", length: 256 },
|
|
1886
|
-
true,
|
|
1887
|
-
["encrypt", "decrypt"]
|
|
1888
|
-
);
|
|
1889
|
-
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
1890
|
-
return { key, iv };
|
|
1891
|
-
};
|
|
1892
|
-
var generateSalt = (length = 16) => {
|
|
1893
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
1894
|
-
};
|
|
1895
|
-
var generateEncryptionKey = async () => {
|
|
1896
|
-
if (!isCryptoAvailable) throw new Error("Web Crypto API not available");
|
|
1897
|
-
const key = await crypto.subtle.generateKey(
|
|
1898
|
-
{ name: "AES-GCM", length: 256 },
|
|
1899
|
-
true,
|
|
1900
|
-
["encrypt", "decrypt"]
|
|
1901
|
-
), iv = crypto.getRandomValues(new Uint8Array(12));
|
|
1902
|
-
return { key, iv };
|
|
1903
|
-
};
|
|
1904
|
-
var exportKey = async (encryptionKey) => {
|
|
1905
|
-
const exportedKey = await crypto.subtle.exportKey("raw", encryptionKey.key);
|
|
1906
|
-
return {
|
|
1907
|
-
key: btoa(String.fromCharCode(...new Uint8Array(exportedKey))),
|
|
1908
|
-
iv: btoa(String.fromCharCode(...encryptionKey.iv))
|
|
1909
|
-
};
|
|
1910
|
-
};
|
|
1911
|
-
var importKey = async (keyData, ivData) => {
|
|
1912
|
-
const keyBytes = Uint8Array.from(atob(keyData), (c) => c.charCodeAt(0)), ivBytes = Uint8Array.from(atob(ivData), (c) => c.charCodeAt(0)), key = await crypto.subtle.importKey(
|
|
1913
|
-
"raw",
|
|
1914
|
-
keyBytes,
|
|
1915
|
-
{ name: "AES-GCM", length: 256 },
|
|
1916
|
-
true,
|
|
1917
|
-
["encrypt", "decrypt"]
|
|
1918
|
-
);
|
|
1919
|
-
return { key, iv: ivBytes };
|
|
1920
|
-
};
|
|
1921
|
-
var encrypt = async (data, encryptionKey) => {
|
|
1922
|
-
const encoder = new TextEncoder(), encoded = encoder.encode(JSON.stringify(data)), encrypted = await crypto.subtle.encrypt(
|
|
1923
|
-
{ name: "AES-GCM", iv: encryptionKey.iv },
|
|
1924
|
-
encryptionKey.key,
|
|
1925
|
-
encoded
|
|
1926
|
-
), combined = new Uint8Array(encryptionKey.iv.length + encrypted.byteLength);
|
|
1927
|
-
combined.set(encryptionKey.iv);
|
|
1928
|
-
combined.set(new Uint8Array(encrypted), encryptionKey.iv.length);
|
|
1929
|
-
return btoa(String.fromCharCode(...combined));
|
|
1930
|
-
};
|
|
1931
|
-
var decrypt = async (encryptedData, encryptionKey) => {
|
|
1932
|
-
const combined = Uint8Array.from(atob(encryptedData), (c) => c.charCodeAt(0)), iv = combined.slice(0, 12), ciphertext = combined.slice(12), decrypted = await crypto.subtle.decrypt(
|
|
1933
|
-
{ name: "AES-GCM", iv },
|
|
1934
|
-
encryptionKey.key,
|
|
1935
|
-
ciphertext
|
|
1936
|
-
);
|
|
1937
|
-
return JSON.parse(new TextDecoder().decode(decrypted));
|
|
1938
|
-
};
|
|
1939
|
-
var _auditLogger = null;
|
|
1940
|
-
var setAuditLogger = (logger) => {
|
|
1941
|
-
_auditLogger = logger;
|
|
1942
|
-
};
|
|
1943
|
-
var isAuditActive = () => _auditLogger !== null;
|
|
1944
|
-
var logAudit = (entry) => {
|
|
1945
|
-
if (_auditLogger) _auditLogger(entry);
|
|
1946
|
-
};
|
|
1947
|
-
var addAccessRule = (rules, pattern, perms) => {
|
|
1948
|
-
rules.set(pattern instanceof RegExp ? pattern.source : pattern, perms);
|
|
1949
|
-
};
|
|
1950
|
-
var hasPermission = (rules, key, action, _userId) => {
|
|
1951
|
-
if (rules.size === 0) return true;
|
|
1952
|
-
for (const [pattern, perms] of rules) {
|
|
1953
|
-
let matches;
|
|
1954
|
-
if (typeof pattern === "function") {
|
|
1955
|
-
matches = pattern(key, _userId);
|
|
1956
|
-
} else {
|
|
1957
|
-
matches = safeRegexTest(pattern, key);
|
|
1958
|
-
}
|
|
1959
|
-
if (matches) {
|
|
1960
|
-
return perms.includes(action) || perms.includes("admin");
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1963
|
-
return false;
|
|
1964
|
-
};
|
|
1965
|
-
var sanitizeValue = (value) => {
|
|
1966
|
-
if (typeof value === "string") {
|
|
1967
|
-
let decoded = value.replace(/&#[xX]?[0-9a-fA-F]+;?/g, (match) => {
|
|
1968
|
-
const hexMatch = match.match(/&#x([0-9a-fA-F]+);?/i);
|
|
1969
|
-
if (hexMatch && hexMatch[1]) {
|
|
1970
|
-
return String.fromCharCode(parseInt(hexMatch[1], 16));
|
|
1971
|
-
}
|
|
1972
|
-
const decMatch = match.match(/&#([0-9]+);?/);
|
|
1973
|
-
if (decMatch && decMatch[1]) {
|
|
1974
|
-
return String.fromCharCode(parseInt(decMatch[1], 10));
|
|
1975
|
-
}
|
|
1976
|
-
return match;
|
|
1977
|
-
});
|
|
1978
|
-
try {
|
|
1979
|
-
decoded = decodeURIComponent(decoded);
|
|
1980
|
-
} catch {
|
|
1981
|
-
}
|
|
1982
|
-
const schemeCheck = decoded.replace(/\b(javascript|vbscript|data:text\/html|about:blank|chrome:)/gi, "[SEC-REMOVED]");
|
|
1983
|
-
return schemeCheck.replace(/<script\b[^>]*>[\s\S]*?<\s*\/\s*script\b[^>]*>/gi, "[SEC-REMOVED]").replace(/on\w+\s*=/gi, "[SEC-REMOVED]=").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, "[SEC-REMOVED]").replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi, "[SEC-REMOVED]").replace(/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi, "[SEC-REMOVED]").replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi, "[SEC-REMOVED]").replace(/<form\b[^<]*(?:(?!<\/form>)<[^<]*)*<\/form>/gi, "[SEC-REMOVED]").replace(/<base\b[^<]*(?:(?!<\/base>)<[^<]*)*<\/base>/gi, "[SEC-REMOVED]").replace(/<link\b[^<]*(?:(?!<\/link>)<[^<]*)*<\/link>/gi, "[SEC-REMOVED]").replace(/<meta\b[^<]*(?:(?!<\/meta>)<[^<]*)*<\/meta>/gi, "[SEC-REMOVED]").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, "[SEC-REMOVED]");
|
|
1984
|
-
}
|
|
1985
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
1986
|
-
if (Object.getPrototypeOf(value) === Object.prototype) {
|
|
1987
|
-
const sanitized = {};
|
|
1988
|
-
for (const [k, v] of Object.entries(value)) {
|
|
1989
|
-
sanitized[k] = sanitizeValue(v);
|
|
1990
|
-
}
|
|
1991
|
-
return sanitized;
|
|
1992
|
-
}
|
|
1993
|
-
return value;
|
|
1994
|
-
}
|
|
1995
|
-
if (Array.isArray(value)) {
|
|
1996
|
-
return value.map((v) => sanitizeValue(v));
|
|
1997
|
-
}
|
|
1998
|
-
return value;
|
|
1999
|
-
};
|
|
2000
|
-
var validateKey = (key) => /^[a-zA-Z0-9_.-]+$/.test(key) && key.length <= 256;
|
|
2001
|
-
var recordConsent = (consents, userId, purpose, granted) => {
|
|
2002
|
-
const record = { id: safeRandomUUID(), purpose, granted, timestamp: Date.now() }, user = consents.get(userId) || [];
|
|
2003
|
-
user.push(record);
|
|
2004
|
-
consents.set(userId, user);
|
|
2005
|
-
logAudit({ timestamp: Date.now(), action: "set", key: `consent:${purpose}`, userId, success: true });
|
|
2006
|
-
return record;
|
|
2007
|
-
};
|
|
2008
|
-
var hasConsent = (consents, userId, purpose) => {
|
|
2009
|
-
const userConsents = consents.get(userId);
|
|
2010
|
-
if (!userConsents) return false;
|
|
2011
|
-
for (let i = userConsents.length - 1; i >= 0; i--) {
|
|
2012
|
-
const record = userConsents[i];
|
|
2013
|
-
if (record && record.purpose === purpose) {
|
|
2014
|
-
return record.granted;
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
return false;
|
|
2018
|
-
};
|
|
2019
|
-
var revokeConsent = (consents, userId, purpose) => {
|
|
2020
|
-
return recordConsent(consents, userId, purpose, false);
|
|
2021
|
-
};
|
|
2022
|
-
var getConsents = (consents, userId) => consents.get(userId) || [];
|
|
2023
|
-
var exportUserData = (consents, userId) => ({ userId, exportedAt: Date.now(), consents: consents.get(userId) || [] });
|
|
2024
|
-
var deleteUserData = (consents, userId) => {
|
|
2025
|
-
const count = consents.get(userId)?.length || 0;
|
|
2026
|
-
consents.delete(userId);
|
|
2027
|
-
return { success: true, deletedConsents: count };
|
|
2028
|
-
};
|
|
2029
|
-
|
|
2030
|
-
// core/utils.ts
|
|
2031
|
-
var deepClone = (obj) => {
|
|
2032
|
-
if (obj === null || typeof obj !== "object") return obj;
|
|
2033
|
-
if (typeof structuredClone === "function") {
|
|
2034
|
-
try {
|
|
2035
|
-
return structuredClone(obj);
|
|
2036
|
-
} catch (_e) {
|
|
2037
|
-
}
|
|
2038
|
-
}
|
|
2039
|
-
const seen = /* @__PURE__ */ new WeakMap();
|
|
2040
|
-
const clone = (value) => {
|
|
2041
|
-
if (value === null || typeof value !== "object") return value;
|
|
2042
|
-
if (typeof value === "function") return value;
|
|
2043
|
-
if (seen.has(value)) return seen.get(value);
|
|
2044
|
-
if (value instanceof Date) return new Date(value.getTime());
|
|
2045
|
-
if (value instanceof RegExp) return new RegExp(value.source, value.flags);
|
|
2046
|
-
if (value instanceof Map) {
|
|
2047
|
-
const result2 = /* @__PURE__ */ new Map();
|
|
2048
|
-
seen.set(value, result2);
|
|
2049
|
-
value.forEach((v, k) => result2.set(clone(k), clone(v)));
|
|
2050
|
-
return result2;
|
|
2051
|
-
}
|
|
2052
|
-
if (value instanceof Set) {
|
|
2053
|
-
const result2 = /* @__PURE__ */ new Set();
|
|
2054
|
-
seen.set(value, result2);
|
|
2055
|
-
value.forEach((v) => result2.add(clone(v)));
|
|
2056
|
-
return result2;
|
|
2057
|
-
}
|
|
2058
|
-
const result = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
|
|
2059
|
-
seen.set(value, result);
|
|
2060
|
-
const keys = [...Object.keys(value), ...Object.getOwnPropertySymbols(value)];
|
|
2061
|
-
for (const key of keys) {
|
|
2062
|
-
result[key] = clone(value[key]);
|
|
2063
|
-
}
|
|
2064
|
-
return result;
|
|
2065
|
-
};
|
|
2066
|
-
return clone(obj);
|
|
2067
|
-
};
|
|
2068
|
-
var isEqual = (a, b) => {
|
|
2069
|
-
if (a === b) return true;
|
|
2070
|
-
if (a === null || b === null) return a === b;
|
|
2071
|
-
if (typeof a !== "object" || typeof b !== "object") return a === b;
|
|
2072
|
-
if (Array.isArray(a) && Array.isArray(b)) {
|
|
2073
|
-
if (a.length !== b.length) return false;
|
|
2074
|
-
for (let i = 0; i < a.length; i++) if (!isEqual(a[i], b[i])) return false;
|
|
2075
|
-
return true;
|
|
2076
|
-
}
|
|
2077
|
-
const keysA = Object.keys(a);
|
|
2078
|
-
const keysB = Object.keys(b);
|
|
2079
|
-
if (keysA.length !== keysB.length) return false;
|
|
2080
|
-
for (let i = 0; i < keysA.length; i++) {
|
|
2081
|
-
const key = keysA[i];
|
|
2082
|
-
if (!(key in b) || !isEqual(a[key], b[key])) return false;
|
|
2083
|
-
}
|
|
2084
|
-
return true;
|
|
2085
|
-
};
|
|
2086
|
-
|
|
2087
|
-
// core/persistence.ts
|
|
2088
|
-
var _getPrefix = (namespace) => `${namespace}_`;
|
|
2089
|
-
var flushDisk = async (ctx) => {
|
|
2090
|
-
if (!ctx.storage) return;
|
|
2091
|
-
const { store, config, diskQueue, storage, encryptionKey, audit, onError, silent, currentVersion } = ctx;
|
|
2092
|
-
const prefix = _getPrefix(config.namespace || "gstate");
|
|
2093
|
-
try {
|
|
2094
|
-
const stateObj = {};
|
|
2095
|
-
store.forEach((v, k) => {
|
|
2096
|
-
stateObj[k] = v;
|
|
2097
|
-
});
|
|
2098
|
-
let dataValue;
|
|
2099
|
-
const isEncoded = config?.encoded;
|
|
2100
|
-
if (isEncoded) {
|
|
2101
|
-
dataValue = btoa(JSON.stringify(stateObj));
|
|
2102
|
-
} else {
|
|
2103
|
-
dataValue = JSON.stringify(stateObj);
|
|
2104
|
-
}
|
|
2105
|
-
storage.setItem(prefix.replace("_", ""), JSON.stringify({
|
|
2106
|
-
v: 1,
|
|
2107
|
-
t: Date.now(),
|
|
2108
|
-
e: null,
|
|
2109
|
-
d: dataValue,
|
|
2110
|
-
_sys_v: currentVersion,
|
|
2111
|
-
_b64: isEncoded ? true : void 0
|
|
2112
|
-
}));
|
|
2113
|
-
audit("set", "FULL_STATE", true);
|
|
2114
|
-
} catch (e) {
|
|
2115
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2116
|
-
if (onError) onError(error, { operation: "persist", key: "FULL_STATE" });
|
|
2117
|
-
else if (!silent) console.error(`[gstate] Persist failed: `, error);
|
|
2118
|
-
}
|
|
2119
|
-
const queue = Array.from(diskQueue.entries());
|
|
2120
|
-
diskQueue.clear();
|
|
2121
|
-
for (const [key, data] of queue) {
|
|
2122
|
-
try {
|
|
2123
|
-
if (!key || !/^[a-zA-Z0-9_.-]+$/.test(key) || key.length > 256) {
|
|
2124
|
-
console.warn(`[gstate] Invalid storage key: ${key}`);
|
|
2125
|
-
continue;
|
|
2126
|
-
}
|
|
2127
|
-
let dataValue = data.value;
|
|
2128
|
-
const isEncoded = data.options.encoded || data.options.encrypted || data.options.secure;
|
|
2129
|
-
if (data.options.encrypted) {
|
|
2130
|
-
if (!encryptionKey) throw new Error(`Encryption key missing for "${key}"`);
|
|
2131
|
-
dataValue = await encrypt(data.value, encryptionKey);
|
|
2132
|
-
} else if (isEncoded) {
|
|
2133
|
-
dataValue = btoa(JSON.stringify(data.value));
|
|
2134
|
-
} else if (typeof data.value === "object" && data.value !== null) {
|
|
2135
|
-
dataValue = JSON.stringify(data.value);
|
|
2136
|
-
}
|
|
2137
|
-
storage.setItem(`${prefix}${key}`, JSON.stringify({
|
|
2138
|
-
v: ctx.versions.get(key) || 1,
|
|
2139
|
-
t: Date.now(),
|
|
2140
|
-
e: data.options.ttl ? Date.now() + data.options.ttl : null,
|
|
2141
|
-
d: dataValue,
|
|
2142
|
-
_sys_v: currentVersion,
|
|
2143
|
-
_enc: data.options.encrypted ? true : void 0,
|
|
2144
|
-
_b64: data.options.encoded || data.options.secure ? true : void 0
|
|
2145
|
-
}));
|
|
2146
|
-
audit("set", key, true);
|
|
2147
|
-
} catch (e) {
|
|
2148
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2149
|
-
if (onError) onError(error, { operation: "persist", key });
|
|
2150
|
-
else if (!silent) console.error(`[gstate] Persist failed: `, error);
|
|
2151
|
-
}
|
|
2152
|
-
}
|
|
2153
|
-
};
|
|
2154
|
-
var hydrateStore = async (ctx, calculateSize, emit) => {
|
|
2155
|
-
const { storage, config, encryptionKey, audit, onError, silent, currentVersion, store, sizes, versions } = ctx;
|
|
2156
|
-
const prefix = _getPrefix(config.namespace || "gstate");
|
|
2157
|
-
const immer2 = config.immer ?? true;
|
|
2158
|
-
if (!storage) return;
|
|
2159
|
-
try {
|
|
2160
|
-
const persisted = {};
|
|
2161
|
-
let savedV = 0;
|
|
2162
|
-
for (let i = 0; i < (storage.length || 0); i++) {
|
|
2163
|
-
const k = storage.key(i);
|
|
2164
|
-
if (!k || !k.startsWith(prefix)) continue;
|
|
2165
|
-
const raw = storage.getItem(k);
|
|
2166
|
-
if (!raw) continue;
|
|
2167
|
-
try {
|
|
2168
|
-
const meta = JSON.parse(raw), key = k.substring(prefix.length);
|
|
2169
|
-
savedV = Math.max(savedV, meta._sys_v !== void 0 ? meta._sys_v : meta.v || 0);
|
|
2170
|
-
if (meta.e && Date.now() > meta.e) {
|
|
2171
|
-
storage.removeItem(k);
|
|
2172
|
-
i--;
|
|
2173
|
-
continue;
|
|
2174
|
-
}
|
|
2175
|
-
let d = meta.d;
|
|
2176
|
-
if (meta._enc && encryptionKey) {
|
|
2177
|
-
d = await decrypt(d, encryptionKey);
|
|
2178
|
-
} else if (typeof d === "string") {
|
|
2179
|
-
if (meta._b64) {
|
|
2180
|
-
try {
|
|
2181
|
-
d = JSON.parse(atob(d));
|
|
2182
|
-
} catch (_e) {
|
|
2183
|
-
}
|
|
2184
|
-
} else if (d.startsWith("{") || d.startsWith("[")) {
|
|
2185
|
-
try {
|
|
2186
|
-
d = JSON.parse(d);
|
|
2187
|
-
} catch (_e) {
|
|
2188
|
-
}
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
persisted[key] = d;
|
|
2192
|
-
audit("hydrate", key, true);
|
|
2193
|
-
} catch (err) {
|
|
2194
|
-
audit("hydrate", k, false, String(err));
|
|
2195
|
-
const error = err instanceof Error ? err : new Error(String(err));
|
|
2196
|
-
if (onError) onError(error, { operation: "hydration", key: k });
|
|
2197
|
-
else if (!silent) console.error(`[gstate] Hydration failed for "${k}": `, err);
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
const final = savedV < currentVersion && config.migrate ? config.migrate(persisted, savedV) : persisted;
|
|
2201
|
-
Object.entries(final).forEach(([k, v]) => {
|
|
2202
|
-
const frozen = immer2 && v !== null && typeof v === "object" ? freeze(deepClone(v), true) : v;
|
|
2203
|
-
const size = calculateSize(frozen);
|
|
2204
|
-
const oldSize = sizes.get(k) || 0;
|
|
2205
|
-
ctx.totalSize = ctx.totalSize - oldSize + size;
|
|
2206
|
-
sizes.set(k, size);
|
|
2207
|
-
store.set(k, frozen);
|
|
2208
|
-
versions.set(k, 1);
|
|
2209
|
-
});
|
|
2210
|
-
emit();
|
|
2211
|
-
} catch (e) {
|
|
2212
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2213
|
-
if (onError) onError(error, { operation: "hydration" });
|
|
2214
|
-
else if (!silent) console.error(`[gstate] Hydration failed: `, error);
|
|
2215
|
-
}
|
|
2216
|
-
};
|
|
2217
|
-
|
|
2218
|
-
// core/plugins.ts
|
|
2219
|
-
var runHook = (ctx, name, hookContext) => {
|
|
2220
|
-
if (ctx.plugins.size === 0) return;
|
|
2221
|
-
for (const p of ctx.plugins.values()) {
|
|
2222
|
-
const hook = p.hooks?.[name];
|
|
2223
|
-
if (hook) {
|
|
2224
|
-
try {
|
|
2225
|
-
hook(hookContext);
|
|
2226
|
-
} catch (e) {
|
|
2227
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2228
|
-
if (ctx.onError) ctx.onError(error, { operation: `plugin:${p.name}:${name}`, key: hookContext.key });
|
|
2229
|
-
else if (!ctx.silent) console.error(`[gstate] Plugin "${p.name}" error:`, e);
|
|
2230
|
-
}
|
|
2231
|
-
}
|
|
2232
|
-
}
|
|
2233
|
-
};
|
|
2234
|
-
var installPlugin = (ctx, plugin, storeInstance) => {
|
|
2235
|
-
try {
|
|
2236
|
-
ctx.plugins.set(plugin.name, plugin);
|
|
2237
|
-
plugin.hooks?.onInstall?.({ store: storeInstance });
|
|
2238
|
-
} catch (e) {
|
|
2239
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2240
|
-
if (ctx.onError) ctx.onError(error, { operation: "plugin:install", key: plugin.name });
|
|
2241
|
-
else if (!ctx.silent) console.error(`[gstate] Failed to install plugin "${plugin.name}": `, e);
|
|
2242
|
-
}
|
|
2243
|
-
};
|
|
2244
|
-
|
|
2245
|
-
// core/sync.ts
|
|
2246
|
-
var SyncEngine = class {
|
|
2247
|
-
constructor(store, config) {
|
|
2248
|
-
__publicField(this, "store");
|
|
2249
|
-
__publicField(this, "config");
|
|
2250
|
-
__publicField(this, "pendingQueue", /* @__PURE__ */ new Map());
|
|
2251
|
-
__publicField(this, "remoteVersions", /* @__PURE__ */ new Map());
|
|
2252
|
-
__publicField(this, "syncTimer", null);
|
|
2253
|
-
__publicField(this, "onlineStatusListeners", /* @__PURE__ */ new Set());
|
|
2254
|
-
__publicField(this, "syncStateListeners", /* @__PURE__ */ new Set());
|
|
2255
|
-
__publicField(this, "_isOnline", true);
|
|
2256
|
-
__publicField(this, "_isSyncing", false);
|
|
2257
|
-
this.store = store;
|
|
2258
|
-
this.config = {
|
|
2259
|
-
endpoint: config.endpoint,
|
|
2260
|
-
authToken: config.authToken || "",
|
|
2261
|
-
strategy: config.strategy || "last-write-wins",
|
|
2262
|
-
autoSyncInterval: config.autoSyncInterval ?? 3e4,
|
|
2263
|
-
syncOnReconnect: config.syncOnReconnect ?? true,
|
|
2264
|
-
debounceTime: config.debounceTime ?? 1e3,
|
|
2265
|
-
fetch: config.fetch || fetch,
|
|
2266
|
-
onSync: config.onSync || (() => {
|
|
2267
|
-
}),
|
|
2268
|
-
onConflict: config.onConflict || (() => ({ action: "accept-local" })),
|
|
2269
|
-
maxRetries: config.maxRetries ?? 3
|
|
2270
|
-
};
|
|
2271
|
-
this._isOnline = typeof navigator !== "undefined" ? navigator.onLine : true;
|
|
2272
|
-
this._setupOnlineListener();
|
|
2273
|
-
this._setupStoreListener();
|
|
2274
|
-
if (this.config.autoSyncInterval > 0) {
|
|
2275
|
-
this._startAutoSync();
|
|
2276
|
-
}
|
|
2277
|
-
}
|
|
2278
|
-
/**
|
|
2279
|
-
* Get current auth token (supports both static string and getter function)
|
|
2280
|
-
*/
|
|
2281
|
-
_getAuthToken() {
|
|
2282
|
-
const token = this.config.authToken;
|
|
2283
|
-
if (typeof token === "function") {
|
|
2284
|
-
return token() || "";
|
|
2285
|
-
}
|
|
2286
|
-
return token || "";
|
|
2287
|
-
}
|
|
2288
|
-
_setupOnlineListener() {
|
|
2289
|
-
if (typeof window === "undefined") return;
|
|
2290
|
-
window.addEventListener("online", () => {
|
|
2291
|
-
this._isOnline = true;
|
|
2292
|
-
this._notifyOnlineChange(true);
|
|
2293
|
-
if (this.config.syncOnReconnect) {
|
|
2294
|
-
this.sync();
|
|
2295
|
-
}
|
|
2296
|
-
});
|
|
2297
|
-
window.addEventListener("offline", () => {
|
|
2298
|
-
this._isOnline = false;
|
|
2299
|
-
this._notifyOnlineChange(false);
|
|
2300
|
-
});
|
|
2301
|
-
}
|
|
2302
|
-
_setupStoreListener() {
|
|
2303
|
-
this.store._subscribe(() => {
|
|
2304
|
-
});
|
|
2305
|
-
}
|
|
2306
|
-
_startAutoSync() {
|
|
2307
|
-
setInterval(() => {
|
|
2308
|
-
if (this._isOnline && !this._isSyncing && this.pendingQueue.size > 0) {
|
|
2309
|
-
this.sync();
|
|
2310
|
-
}
|
|
2311
|
-
}, this.config.autoSyncInterval);
|
|
2312
|
-
}
|
|
2313
|
-
_notifyOnlineChange(online) {
|
|
2314
|
-
this.onlineStatusListeners.forEach((cb) => cb(online));
|
|
2315
|
-
this._notifyStateChange();
|
|
2316
|
-
}
|
|
2317
|
-
_notifyStateChange() {
|
|
2318
|
-
const state = this.getState();
|
|
2319
|
-
this.syncStateListeners.forEach((cb) => cb(state));
|
|
2320
|
-
}
|
|
2321
|
-
/**
|
|
2322
|
-
* Queue a change for synchronization
|
|
2323
|
-
*/
|
|
2324
|
-
queueChange(key, value) {
|
|
2325
|
-
const version = this.store._getVersion(key) || 1;
|
|
2326
|
-
this.pendingQueue.set(key, {
|
|
2327
|
-
key,
|
|
2328
|
-
value: deepClone(value),
|
|
2329
|
-
timestamp: Date.now(),
|
|
2330
|
-
version
|
|
2331
|
-
});
|
|
2332
|
-
this._notifyStateChange();
|
|
2333
|
-
if (this.syncTimer) clearTimeout(this.syncTimer);
|
|
2334
|
-
this.syncTimer = setTimeout(() => {
|
|
2335
|
-
if (this._isOnline) this.sync();
|
|
2336
|
-
}, this.config.debounceTime);
|
|
2337
|
-
}
|
|
2338
|
-
/**
|
|
2339
|
-
* Perform synchronization with remote server
|
|
2340
|
-
*/
|
|
2341
|
-
async sync() {
|
|
2342
|
-
if (this._isSyncing) {
|
|
2343
|
-
return {
|
|
2344
|
-
success: false,
|
|
2345
|
-
syncedKeys: [],
|
|
2346
|
-
conflicts: [],
|
|
2347
|
-
errors: ["Sync already in progress"],
|
|
2348
|
-
timestamp: Date.now(),
|
|
2349
|
-
duration: 0
|
|
2350
|
-
};
|
|
2351
|
-
}
|
|
2352
|
-
this._isSyncing = true;
|
|
2353
|
-
this._notifyStateChange();
|
|
2354
|
-
const startTime = Date.now();
|
|
2355
|
-
const syncedKeys = [];
|
|
2356
|
-
const conflicts = [];
|
|
2357
|
-
const errors2 = [];
|
|
2358
|
-
try {
|
|
2359
|
-
const pendingChanges = Array.from(this.pendingQueue.values());
|
|
2360
|
-
if (pendingChanges.length === 0) {
|
|
2361
|
-
this._isSyncing = false;
|
|
2362
|
-
this._notifyStateChange();
|
|
2363
|
-
return {
|
|
2364
|
-
success: true,
|
|
2365
|
-
syncedKeys: [],
|
|
2366
|
-
conflicts: [],
|
|
2367
|
-
errors: [],
|
|
2368
|
-
timestamp: Date.now(),
|
|
2369
|
-
duration: Date.now() - startTime
|
|
2370
|
-
};
|
|
2371
|
-
}
|
|
2372
|
-
await this._fetchRemoteVersions(pendingChanges.map((p) => p.key));
|
|
2373
|
-
for (const change of pendingChanges) {
|
|
2374
|
-
try {
|
|
2375
|
-
const remoteVersion = this.remoteVersions.get(change.key);
|
|
2376
|
-
if (!remoteVersion) {
|
|
2377
|
-
await this._pushChange(change);
|
|
2378
|
-
syncedKeys.push(change.key);
|
|
2379
|
-
this.pendingQueue.delete(change.key);
|
|
2380
|
-
} else if (remoteVersion.version >= change.version) {
|
|
2381
|
-
const conflict = {
|
|
2382
|
-
key: change.key,
|
|
2383
|
-
localValue: change.value,
|
|
2384
|
-
remoteValue: remoteVersion.value,
|
|
2385
|
-
localVersion: change.version,
|
|
2386
|
-
remoteVersion: remoteVersion.version,
|
|
2387
|
-
timestamp: change.timestamp
|
|
2388
|
-
};
|
|
2389
|
-
conflicts.push(conflict);
|
|
2390
|
-
const resolution = this.config.onConflict(conflict);
|
|
2391
|
-
await this._resolveConflict(change, remoteVersion, resolution);
|
|
2392
|
-
syncedKeys.push(change.key);
|
|
2393
|
-
this.pendingQueue.delete(change.key);
|
|
2394
|
-
} else {
|
|
2395
|
-
await this._pushChange(change);
|
|
2396
|
-
syncedKeys.push(change.key);
|
|
2397
|
-
this.pendingQueue.delete(change.key);
|
|
2398
|
-
}
|
|
2399
|
-
} catch (err) {
|
|
2400
|
-
errors2.push(`Failed to sync "${change.key}": ${err}`);
|
|
2401
|
-
}
|
|
2402
|
-
}
|
|
2403
|
-
const result = {
|
|
2404
|
-
success: errors2.length === 0,
|
|
2405
|
-
syncedKeys,
|
|
2406
|
-
conflicts,
|
|
2407
|
-
errors: errors2,
|
|
2408
|
-
timestamp: Date.now(),
|
|
2409
|
-
duration: Date.now() - startTime
|
|
2410
|
-
};
|
|
2411
|
-
this.config.onSync(result);
|
|
2412
|
-
return result;
|
|
2413
|
-
} catch (err) {
|
|
2414
|
-
const errorMsg = `Sync failed: ${err}`;
|
|
2415
|
-
errors2.push(errorMsg);
|
|
2416
|
-
return {
|
|
2417
|
-
success: false,
|
|
2418
|
-
syncedKeys,
|
|
2419
|
-
conflicts,
|
|
2420
|
-
errors: errors2,
|
|
2421
|
-
timestamp: Date.now(),
|
|
2422
|
-
duration: Date.now() - startTime
|
|
2423
|
-
};
|
|
2424
|
-
} finally {
|
|
2425
|
-
this._isSyncing = false;
|
|
2426
|
-
this._notifyStateChange();
|
|
2427
|
-
}
|
|
2428
|
-
}
|
|
2429
|
-
async _fetchRemoteVersions(keys) {
|
|
2430
|
-
try {
|
|
2431
|
-
const authToken = this._getAuthToken();
|
|
2432
|
-
const response = await this.config.fetch(`${this.config.endpoint}/versions`, {
|
|
2433
|
-
method: "POST",
|
|
2434
|
-
headers: {
|
|
2435
|
-
"Content-Type": "application/json",
|
|
2436
|
-
...authToken && { "Authorization": `Bearer ${authToken}` }
|
|
2437
|
-
},
|
|
2438
|
-
body: JSON.stringify({ keys })
|
|
2439
|
-
});
|
|
2440
|
-
if (response.ok) {
|
|
2441
|
-
const data = await response.json();
|
|
2442
|
-
if (data.versions) {
|
|
2443
|
-
for (const [key, version] of Object.entries(data.versions)) {
|
|
2444
|
-
this.remoteVersions.set(key, version);
|
|
2445
|
-
}
|
|
2446
|
-
}
|
|
2447
|
-
}
|
|
2448
|
-
} catch (err) {
|
|
2449
|
-
console.warn("[SyncEngine] Failed to fetch remote versions:", err);
|
|
2450
|
-
}
|
|
2451
|
-
}
|
|
2452
|
-
async _pushChange(change) {
|
|
2453
|
-
let retries = 0;
|
|
2454
|
-
while (retries < this.config.maxRetries) {
|
|
2455
|
-
try {
|
|
2456
|
-
const authToken = this._getAuthToken();
|
|
2457
|
-
const response = await this.config.fetch(`${this.config.endpoint}/sync`, {
|
|
2458
|
-
method: "POST",
|
|
2459
|
-
headers: {
|
|
2460
|
-
"Content-Type": "application/json",
|
|
2461
|
-
...authToken && { "Authorization": `Bearer ${authToken}` }
|
|
2462
|
-
},
|
|
2463
|
-
body: JSON.stringify({
|
|
2464
|
-
key: change.key,
|
|
2465
|
-
value: change.value,
|
|
2466
|
-
version: change.version,
|
|
2467
|
-
timestamp: change.timestamp
|
|
2468
|
-
})
|
|
2469
|
-
});
|
|
2470
|
-
if (response.ok) {
|
|
2471
|
-
const data = await response.json();
|
|
2472
|
-
if (data.version) {
|
|
2473
|
-
this.remoteVersions.set(change.key, {
|
|
2474
|
-
version: data.version,
|
|
2475
|
-
timestamp: data.timestamp || Date.now(),
|
|
2476
|
-
value: change.value
|
|
2477
|
-
});
|
|
2478
|
-
}
|
|
2479
|
-
return;
|
|
2480
|
-
}
|
|
2481
|
-
retries++;
|
|
2482
|
-
} catch (err) {
|
|
2483
|
-
retries++;
|
|
2484
|
-
if (retries >= this.config.maxRetries) throw err;
|
|
2485
|
-
}
|
|
2486
|
-
}
|
|
2487
|
-
}
|
|
2488
|
-
async _resolveConflict(localChange, remoteVersion, resolution) {
|
|
2489
|
-
switch (resolution.action) {
|
|
2490
|
-
case "accept-local":
|
|
2491
|
-
await this._pushChange({
|
|
2492
|
-
...localChange,
|
|
2493
|
-
version: remoteVersion.version + 1,
|
|
2494
|
-
timestamp: Date.now()
|
|
2495
|
-
});
|
|
2496
|
-
break;
|
|
2497
|
-
case "accept-remote":
|
|
2498
|
-
this.store.set(localChange.key, remoteVersion.value);
|
|
2499
|
-
break;
|
|
2500
|
-
case "merge":
|
|
2501
|
-
this.store.set(localChange.key, resolution.value);
|
|
2502
|
-
await this._pushChange({
|
|
2503
|
-
key: localChange.key,
|
|
2504
|
-
value: resolution.value,
|
|
2505
|
-
version: Math.max(localChange.version, remoteVersion.version) + 1,
|
|
2506
|
-
timestamp: Date.now()
|
|
2507
|
-
});
|
|
2508
|
-
break;
|
|
2509
|
-
case "discard":
|
|
2510
|
-
break;
|
|
2511
|
-
}
|
|
2512
|
-
}
|
|
2513
|
-
/**
|
|
2514
|
-
* Get current sync state
|
|
2515
|
-
*/
|
|
2516
|
-
getState() {
|
|
2517
|
-
return {
|
|
2518
|
-
isOnline: this._isOnline,
|
|
2519
|
-
isSyncing: this._isSyncing,
|
|
2520
|
-
lastSyncTimestamp: null,
|
|
2521
|
-
// Could track this
|
|
2522
|
-
pendingChanges: this.pendingQueue.size,
|
|
2523
|
-
conflicts: 0
|
|
2524
|
-
// Could track unresolved conflicts
|
|
2525
|
-
};
|
|
2526
|
-
}
|
|
2527
|
-
/**
|
|
2528
|
-
* Subscribe to online status changes
|
|
2529
|
-
*/
|
|
2530
|
-
onOnlineChange(callback) {
|
|
2531
|
-
this.onlineStatusListeners.add(callback);
|
|
2532
|
-
return () => this.onlineStatusListeners.delete(callback);
|
|
2533
|
-
}
|
|
2534
|
-
/**
|
|
2535
|
-
* Subscribe to sync state changes
|
|
2536
|
-
*/
|
|
2537
|
-
onStateChange(callback) {
|
|
2538
|
-
this.syncStateListeners.add(callback);
|
|
2539
|
-
return () => this.syncStateListeners.delete(callback);
|
|
2540
|
-
}
|
|
2541
|
-
/**
|
|
2542
|
-
* Force push all pending changes
|
|
2543
|
-
*/
|
|
2544
|
-
async flush() {
|
|
2545
|
-
return this.sync();
|
|
2546
|
-
}
|
|
2547
|
-
/**
|
|
2548
|
-
* Destroy the sync engine
|
|
2549
|
-
*/
|
|
2550
|
-
destroy() {
|
|
2551
|
-
if (this.syncTimer) clearTimeout(this.syncTimer);
|
|
2552
|
-
this.pendingQueue.clear();
|
|
2553
|
-
this.onlineStatusListeners.clear();
|
|
2554
|
-
this.syncStateListeners.clear();
|
|
2555
|
-
}
|
|
2556
|
-
};
|
|
2557
|
-
var createSyncEngine = (store, config) => {
|
|
2558
|
-
return new SyncEngine(store, config);
|
|
2559
|
-
};
|
|
2560
|
-
|
|
2561
|
-
// core/env.ts
|
|
2562
|
-
var isProduction = () => {
|
|
2563
|
-
try {
|
|
2564
|
-
if (typeof process !== "undefined" && false) return true;
|
|
2565
|
-
const glob = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : {};
|
|
2566
|
-
if (typeof glob.__DEV__ !== "undefined" && glob.__DEV__ === false) return true;
|
|
2567
|
-
return false;
|
|
2568
|
-
} catch {
|
|
2569
|
-
return false;
|
|
2570
|
-
}
|
|
2571
|
-
};
|
|
2572
|
-
var isDevelopment = () => !isProduction();
|
|
2573
|
-
|
|
2574
|
-
// core/store.ts
|
|
2575
|
-
var StorageAdapters = {
|
|
2576
|
-
local: () => typeof window !== "undefined" ? window.localStorage : null,
|
|
2577
|
-
session: () => typeof window !== "undefined" ? window.sessionStorage : null,
|
|
2578
|
-
memory: () => {
|
|
2579
|
-
const _m = /* @__PURE__ */ new Map();
|
|
2580
|
-
return {
|
|
2581
|
-
getItem: (k) => _m.get(k) || null,
|
|
2582
|
-
setItem: (k, v) => _m.set(k, v),
|
|
2583
|
-
removeItem: (k) => _m.delete(k),
|
|
2584
|
-
key: (i) => Array.from(_m.keys())[i] || null,
|
|
2585
|
-
get length() {
|
|
2586
|
-
return _m.size;
|
|
2587
|
-
}
|
|
2588
|
-
};
|
|
2589
|
-
}
|
|
2590
|
-
};
|
|
2591
|
-
var createStore = (config) => {
|
|
2592
|
-
const _store = /* @__PURE__ */ new Map(), _versions = /* @__PURE__ */ new Map(), _sizes = /* @__PURE__ */ new Map(), _listeners = /* @__PURE__ */ new Set(), _keyListeners = /* @__PURE__ */ new Map(), _middlewares = /* @__PURE__ */ new Set(), _watchers = /* @__PURE__ */ new Map(), _computed = /* @__PURE__ */ new Map(), _computedDeps = /* @__PURE__ */ new Map(), _plugins = /* @__PURE__ */ new Map(), _diskQueue = /* @__PURE__ */ new Map(), _regexCache = /* @__PURE__ */ new Map(), _accessRules = /* @__PURE__ */ new Map(), _consents = /* @__PURE__ */ new Map(), _namespace = config?.namespace || "gstate", _silent = config?.silent ?? false, _debounceTime = config?.debounceTime ?? 150, _currentVersion = config?.version ?? 0, _storage = config?.storage || StorageAdapters.local(), _onError = config?.onError, _maxObjectSize = config?.maxObjectSize ?? 0, _maxTotalSize = config?.maxTotalSize ?? 0, _encryptionKey = config?.encryptionKey ?? null, _validateInput = config?.validateInput ?? true, _auditEnabled = config?.auditEnabled ?? true, _userId = config?.userId, _immer = config?.immer ?? true, _persistByDefault = config?.persistByDefault ?? config?.persistence ?? config?.persist ?? false;
|
|
2593
|
-
if (config?.accessRules) {
|
|
2594
|
-
config.accessRules.forEach((rule) => addAccessRule(_accessRules, rule.pattern, rule.permissions));
|
|
2595
|
-
}
|
|
2596
|
-
let _isTransaction = false, _pendingEmit = false, _isReady = false, _totalSize = 0, _diskTimer = null, _snapshot = null;
|
|
2597
|
-
let _readyResolver;
|
|
2598
|
-
const _readyPromise = new Promise((resolve) => {
|
|
2599
|
-
_readyResolver = resolve;
|
|
2600
|
-
});
|
|
2601
|
-
const _getPrefix2 = () => `${_namespace}_`;
|
|
2602
|
-
const getPersistenceContext = () => ({
|
|
2603
|
-
store: _store,
|
|
2604
|
-
versions: _versions,
|
|
2605
|
-
sizes: _sizes,
|
|
2606
|
-
totalSize: _totalSize,
|
|
2607
|
-
storage: _storage,
|
|
2608
|
-
config: config || {},
|
|
2609
|
-
diskQueue: _diskQueue,
|
|
2610
|
-
encryptionKey: _encryptionKey,
|
|
2611
|
-
audit: _audit,
|
|
2612
|
-
onError: _onError,
|
|
2613
|
-
silent: _silent,
|
|
2614
|
-
debounceTime: _debounceTime,
|
|
2615
|
-
currentVersion: _currentVersion
|
|
2616
|
-
});
|
|
2617
|
-
const getPluginContext = () => ({
|
|
2618
|
-
plugins: _plugins,
|
|
2619
|
-
onError: _onError,
|
|
2620
|
-
silent: _silent
|
|
2621
|
-
});
|
|
2622
|
-
const _calculateSize = (val) => {
|
|
2623
|
-
if (val === null || val === void 0) return 0;
|
|
2624
|
-
const type = typeof val;
|
|
2625
|
-
if (type === "boolean") return 4;
|
|
2626
|
-
if (type === "number") return 8;
|
|
2627
|
-
if (type === "string") return val.length * 2;
|
|
2628
|
-
if (type !== "object") return 0;
|
|
2629
|
-
let bytes = 0;
|
|
2630
|
-
const stack = [val];
|
|
2631
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
2632
|
-
while (stack.length > 0) {
|
|
2633
|
-
const value = stack.pop();
|
|
2634
|
-
if (typeof value === "boolean") {
|
|
2635
|
-
bytes += 4;
|
|
2636
|
-
} else if (typeof value === "number") {
|
|
2637
|
-
bytes += 8;
|
|
2638
|
-
} else if (typeof value === "string") {
|
|
2639
|
-
bytes += value.length * 2;
|
|
2640
|
-
} else if (typeof value === "object" && value !== null) {
|
|
2641
|
-
const obj = value;
|
|
2642
|
-
if (seen.has(obj)) continue;
|
|
2643
|
-
seen.add(obj);
|
|
2644
|
-
if (Array.isArray(obj)) {
|
|
2645
|
-
for (let i = 0; i < obj.length; i++) stack.push(obj[i]);
|
|
2646
|
-
} else {
|
|
2647
|
-
for (const key of Object.keys(obj)) {
|
|
2648
|
-
bytes += key.length * 2;
|
|
2649
|
-
stack.push(obj[key]);
|
|
2650
|
-
}
|
|
2651
|
-
}
|
|
2652
|
-
}
|
|
2653
|
-
}
|
|
2654
|
-
return bytes;
|
|
2655
|
-
};
|
|
2656
|
-
const _runHook = (name, context) => {
|
|
2657
|
-
runHook(getPluginContext(), name, context);
|
|
2658
|
-
};
|
|
2659
|
-
const _audit = (action, key, success, error) => {
|
|
2660
|
-
if (_auditEnabled && isAuditActive() && logAudit) {
|
|
2661
|
-
logAudit({ timestamp: Date.now(), action, key, userId: _userId, success, error });
|
|
2662
|
-
}
|
|
2663
|
-
};
|
|
2664
|
-
const _updateComputed = (key) => {
|
|
2665
|
-
const comp = _computed.get(key);
|
|
2666
|
-
if (!comp) return;
|
|
2667
|
-
const depsFound = /* @__PURE__ */ new Set();
|
|
2668
|
-
const getter = (k) => {
|
|
2669
|
-
depsFound.add(k);
|
|
2670
|
-
if (_computed.has(k)) return _computed.get(k).lastValue;
|
|
2671
|
-
return instance.get(k);
|
|
2672
|
-
};
|
|
2673
|
-
const newValue = comp.selector(getter);
|
|
2674
|
-
comp.deps.forEach((d) => {
|
|
2675
|
-
if (!depsFound.has(d)) {
|
|
2676
|
-
const dependents = _computedDeps.get(d);
|
|
2677
|
-
if (dependents) {
|
|
2678
|
-
dependents.delete(key);
|
|
2679
|
-
if (dependents.size === 0) _computedDeps.delete(d);
|
|
2680
|
-
}
|
|
2681
|
-
}
|
|
2682
|
-
});
|
|
2683
|
-
depsFound.forEach((d) => {
|
|
2684
|
-
if (!comp.deps.has(d)) {
|
|
2685
|
-
if (!_computedDeps.has(d)) _computedDeps.set(d, /* @__PURE__ */ new Set());
|
|
2686
|
-
_computedDeps.get(d).add(key);
|
|
2687
|
-
}
|
|
2688
|
-
});
|
|
2689
|
-
comp.deps = depsFound;
|
|
2690
|
-
if (!isEqual(comp.lastValue, newValue)) {
|
|
2691
|
-
comp.lastValue = _immer && newValue !== null && typeof newValue === "object" ? freeze(deepClone(newValue), true) : newValue;
|
|
2692
|
-
_versions.set(key, (_versions.get(key) || 0) + 1);
|
|
2693
|
-
_emit(key);
|
|
2694
|
-
}
|
|
2695
|
-
};
|
|
2696
|
-
const _emit = (changedKey) => {
|
|
2697
|
-
if (changedKey) {
|
|
2698
|
-
if (_computedDeps.has(changedKey)) {
|
|
2699
|
-
const dependents = _computedDeps.get(changedKey);
|
|
2700
|
-
for (const dependentKey of dependents) {
|
|
2701
|
-
_updateComputed(dependentKey);
|
|
2702
|
-
}
|
|
2703
|
-
}
|
|
2704
|
-
const watchers = _watchers.get(changedKey);
|
|
2705
|
-
if (watchers) {
|
|
2706
|
-
const val = instance.get(changedKey);
|
|
2707
|
-
for (const w of watchers) {
|
|
2708
|
-
try {
|
|
2709
|
-
w(val);
|
|
2710
|
-
} catch (e) {
|
|
2711
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2712
|
-
if (_onError) _onError(error, { operation: "watcher", key: changedKey });
|
|
2713
|
-
else if (!_silent) console.error(`[gstate] Watcher error for "${changedKey}":`, e);
|
|
2714
|
-
}
|
|
2715
|
-
}
|
|
2716
|
-
}
|
|
2717
|
-
const keyListeners = _keyListeners.get(changedKey);
|
|
2718
|
-
if (keyListeners) {
|
|
2719
|
-
for (const l of keyListeners) {
|
|
2720
|
-
try {
|
|
2721
|
-
l();
|
|
2722
|
-
} catch (e) {
|
|
2723
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2724
|
-
if (_onError) _onError(error, { operation: "keyListener", key: changedKey });
|
|
2725
|
-
else if (!_silent) console.error(`[gstate] Listener error for "${changedKey}":`, e);
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
}
|
|
2729
|
-
}
|
|
2730
|
-
if (_isTransaction) {
|
|
2731
|
-
_pendingEmit = true;
|
|
2732
|
-
return;
|
|
2733
|
-
}
|
|
2734
|
-
for (const l of _listeners) {
|
|
2735
|
-
try {
|
|
2736
|
-
l();
|
|
2737
|
-
} catch (e) {
|
|
2738
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2739
|
-
if (_onError) _onError(error, { operation: "listener" });
|
|
2740
|
-
else if (!_silent) console.error(`[gstate] Global listener error: `, e);
|
|
2741
|
-
}
|
|
2742
|
-
}
|
|
2743
|
-
};
|
|
2744
|
-
const _flushDisk = async () => {
|
|
2745
|
-
flushDisk(getPersistenceContext());
|
|
2746
|
-
};
|
|
2747
|
-
const _methodNamespace = {};
|
|
2748
|
-
const instance = {
|
|
2749
|
-
_setSilently: (key, value) => {
|
|
2750
|
-
const oldSize = _sizes.get(key) || 0, frozen = _immer && value !== null && typeof value === "object" ? freeze(deepClone(value), true) : value;
|
|
2751
|
-
const hasLimits = (_maxObjectSize > 0 || _maxTotalSize > 0) && !isProduction();
|
|
2752
|
-
const newSize = hasLimits ? _calculateSize(frozen) : 0;
|
|
2753
|
-
_totalSize = _totalSize - oldSize + newSize;
|
|
2754
|
-
_sizes.set(key, newSize);
|
|
2755
|
-
_store.set(key, frozen);
|
|
2756
|
-
_versions.set(key, (_versions.get(key) || 0) + 1);
|
|
2757
|
-
_snapshot = null;
|
|
2758
|
-
},
|
|
2759
|
-
/**
|
|
2760
|
-
* Registers a custom method on the store instance.
|
|
2761
|
-
* @param pluginName - Plugin name
|
|
2762
|
-
* @param methodName - Method name
|
|
2763
|
-
* @param fn - Method function
|
|
2764
|
-
*/
|
|
2765
|
-
_registerMethod: (pluginName, methodName, fn) => {
|
|
2766
|
-
const isUnsafeKey = (key) => key === "__proto__" || key === "constructor" || key === "prototype";
|
|
2767
|
-
if (isUnsafeKey(pluginName) || isUnsafeKey(methodName)) {
|
|
2768
|
-
console.warn("[gstate] Refusing to register method with unsafe key:", pluginName, methodName);
|
|
2769
|
-
return;
|
|
2770
|
-
}
|
|
2771
|
-
if (!_methodNamespace[pluginName]) _methodNamespace[pluginName] = {};
|
|
2772
|
-
_methodNamespace[pluginName][methodName] = fn;
|
|
2773
|
-
},
|
|
2774
|
-
set: (key, valOrUp, options = {}) => {
|
|
2775
|
-
const oldVal = _store.get(key), newVal = _immer && typeof valOrUp === "function" ? produce(oldVal, valOrUp) : valOrUp;
|
|
2776
|
-
if (_validateInput && !validateKey(key)) {
|
|
2777
|
-
if (!_silent) console.warn(`[gstate] Invalid key: ${key}`);
|
|
2778
|
-
return false;
|
|
2779
|
-
}
|
|
2780
|
-
if (!hasPermission(_accessRules, key, "write", _userId)) {
|
|
2781
|
-
_audit("set", key, false, "RBAC Denied");
|
|
2782
|
-
if (!_silent) console.error(`[gstate] RBAC Denied for "${key}"`);
|
|
2783
|
-
return false;
|
|
2784
|
-
}
|
|
2785
|
-
const sani = _validateInput ? sanitizeValue(newVal) : newVal;
|
|
2786
|
-
const oldSize = _sizes.get(key) || 0;
|
|
2787
|
-
_runHook("onBeforeSet", { key, value: sani, store: instance, version: _versions.get(key) || 0 });
|
|
2788
|
-
const frozen = _immer && sani !== null && typeof sani === "object" ? freeze(deepClone(sani), true) : sani;
|
|
2789
|
-
if (!isEqual(oldVal, frozen)) {
|
|
2790
|
-
const hasLimits = (_maxObjectSize > 0 || _maxTotalSize > 0) && !isProduction();
|
|
2791
|
-
const finalSize = hasLimits ? _calculateSize(frozen) : 0;
|
|
2792
|
-
if (_maxObjectSize > 0 && finalSize > _maxObjectSize) {
|
|
2793
|
-
const error = new Error(`Object size (${finalSize} bytes) exceeds maxObjectSize (${_maxObjectSize} bytes)`);
|
|
2794
|
-
if (_onError) _onError(error, { operation: "set", key });
|
|
2795
|
-
else if (!_silent) console.warn(`[gstate] ${error.message} for "${key}"`);
|
|
2796
|
-
}
|
|
2797
|
-
if (_maxTotalSize > 0) {
|
|
2798
|
-
const est = _totalSize - oldSize + finalSize;
|
|
2799
|
-
if (est > _maxTotalSize) {
|
|
2800
|
-
const error = new Error(`Total store size (${est} bytes) exceeds limit (${_maxTotalSize} bytes)`);
|
|
2801
|
-
if (_onError) _onError(error, { operation: "set" });
|
|
2802
|
-
else if (!_silent) console.warn(`[gstate] ${error.message}`);
|
|
2803
|
-
}
|
|
2804
|
-
}
|
|
2805
|
-
_totalSize = _totalSize - oldSize + finalSize;
|
|
2806
|
-
_sizes.set(key, finalSize);
|
|
2807
|
-
_store.set(key, frozen);
|
|
2808
|
-
_versions.set(key, (_versions.get(key) || 0) + 1);
|
|
2809
|
-
_snapshot = null;
|
|
2810
|
-
const shouldPersist = options.persist ?? _persistByDefault;
|
|
2811
|
-
if (shouldPersist) {
|
|
2812
|
-
_diskQueue.set(key, { value: frozen, options: { ...options, persist: shouldPersist, encoded: options.encoded || config?.encoded } });
|
|
2813
|
-
if (_diskTimer) clearTimeout(_diskTimer);
|
|
2814
|
-
_diskTimer = setTimeout(_flushDisk, _debounceTime);
|
|
2815
|
-
}
|
|
2816
|
-
_runHook("onSet", { key, value: frozen, store: instance, version: _versions.get(key) });
|
|
2817
|
-
_audit("set", key, true);
|
|
2818
|
-
_emit(key);
|
|
2819
|
-
return true;
|
|
2820
|
-
}
|
|
2821
|
-
return false;
|
|
2822
|
-
},
|
|
2823
|
-
get: (key) => {
|
|
2824
|
-
if (!hasPermission(_accessRules, key, "read", _userId)) {
|
|
2825
|
-
_audit("get", key, false, "RBAC Denied");
|
|
2826
|
-
return null;
|
|
2827
|
-
}
|
|
2828
|
-
const val = _store.get(key);
|
|
2829
|
-
_runHook("onGet", { store: instance, key, value: val });
|
|
2830
|
-
_audit("get", key, true);
|
|
2831
|
-
return val;
|
|
2832
|
-
},
|
|
2833
|
-
compute: (key, selector) => {
|
|
2834
|
-
try {
|
|
2835
|
-
if (!_computed.has(key)) {
|
|
2836
|
-
_computed.set(key, { selector, lastValue: null, deps: /* @__PURE__ */ new Set() });
|
|
2837
|
-
_updateComputed(key);
|
|
2838
|
-
}
|
|
2839
|
-
return _computed.get(key).lastValue;
|
|
2840
|
-
} catch (e) {
|
|
2841
|
-
const error = e instanceof Error ? e : new Error(String(e));
|
|
2842
|
-
if (_onError) _onError(error, { operation: "compute", key });
|
|
2843
|
-
else if (!_silent) console.error(`[gstate] Compute error for "${key}": `, e);
|
|
2844
|
-
return null;
|
|
2845
|
-
}
|
|
2846
|
-
},
|
|
2847
|
-
watch: (key, callback) => {
|
|
2848
|
-
if (!_watchers.has(key)) _watchers.set(key, /* @__PURE__ */ new Set());
|
|
2849
|
-
const set2 = _watchers.get(key);
|
|
2850
|
-
set2.add(callback);
|
|
2851
|
-
return () => {
|
|
2852
|
-
set2.delete(callback);
|
|
2853
|
-
if (set2.size === 0) _watchers.delete(key);
|
|
2854
|
-
};
|
|
2855
|
-
},
|
|
2856
|
-
remove: (key) => {
|
|
2857
|
-
if (!hasPermission(_accessRules, key, "delete", _userId)) {
|
|
2858
|
-
_audit("delete", key, false, "RBAC Denied");
|
|
2859
|
-
return false;
|
|
2860
|
-
}
|
|
2861
|
-
const old = _store.get(key), deleted = _store.delete(key);
|
|
2862
|
-
if (deleted) {
|
|
2863
|
-
_totalSize -= _sizes.get(key) || 0;
|
|
2864
|
-
_sizes.delete(key);
|
|
2865
|
-
_runHook("onRemove", { store: instance, key, value: old });
|
|
2866
|
-
_snapshot = null;
|
|
2867
|
-
}
|
|
2868
|
-
_versions.set(key, (_versions.get(key) || 0) + 1);
|
|
2869
|
-
if (_storage) _storage.removeItem(`${_getPrefix2()}${key}`);
|
|
2870
|
-
_audit("delete", key, true);
|
|
2871
|
-
_emit(key);
|
|
2872
|
-
return deleted;
|
|
2873
|
-
},
|
|
2874
|
-
delete: (key) => instance.remove(key),
|
|
2875
|
-
deleteAll: () => {
|
|
2876
|
-
Array.from(_store.keys()).forEach((k) => instance.remove(k));
|
|
2877
|
-
if (_storage) {
|
|
2878
|
-
const prefix = _namespace + "_";
|
|
2879
|
-
for (let i = 0; i < (_storage.length || 0); i++) {
|
|
2880
|
-
const k = _storage.key(i);
|
|
2881
|
-
if (k?.startsWith(prefix)) {
|
|
2882
|
-
_storage.removeItem(k);
|
|
2883
|
-
i--;
|
|
2884
|
-
}
|
|
2885
|
-
}
|
|
2886
|
-
}
|
|
2887
|
-
_totalSize = 0;
|
|
2888
|
-
_sizes.clear();
|
|
2889
|
-
_snapshot = null;
|
|
2890
|
-
return true;
|
|
2891
|
-
},
|
|
2892
|
-
list: () => Object.fromEntries(_store.entries()),
|
|
2893
|
-
use: (m) => {
|
|
2894
|
-
_middlewares.add(m);
|
|
2895
|
-
},
|
|
2896
|
-
transaction: (fn) => {
|
|
2897
|
-
_isTransaction = true;
|
|
2898
|
-
_runHook("onTransaction", { store: instance, key: "START" });
|
|
2899
|
-
try {
|
|
2900
|
-
fn();
|
|
2901
|
-
} finally {
|
|
2902
|
-
_isTransaction = false;
|
|
2903
|
-
_runHook("onTransaction", { store: instance, key: "END" });
|
|
2904
|
-
if (_pendingEmit) {
|
|
2905
|
-
_pendingEmit = false;
|
|
2906
|
-
_emit();
|
|
2907
|
-
}
|
|
2908
|
-
}
|
|
2909
|
-
},
|
|
2910
|
-
destroy: () => {
|
|
2911
|
-
if (_diskTimer) {
|
|
2912
|
-
clearTimeout(_diskTimer);
|
|
2913
|
-
_diskTimer = null;
|
|
2914
|
-
}
|
|
2915
|
-
_diskQueue.clear();
|
|
2916
|
-
if (typeof window !== "undefined") window.removeEventListener("beforeunload", _unloadHandler);
|
|
2917
|
-
_runHook("onDestroy", { store: instance });
|
|
2918
|
-
_listeners.clear();
|
|
2919
|
-
_keyListeners.clear();
|
|
2920
|
-
_watchers.clear();
|
|
2921
|
-
_computed.clear();
|
|
2922
|
-
_computedDeps.clear();
|
|
2923
|
-
_plugins.clear();
|
|
2924
|
-
_store.clear();
|
|
2925
|
-
_sizes.clear();
|
|
2926
|
-
_totalSize = 0;
|
|
2927
|
-
_accessRules.clear();
|
|
2928
|
-
_consents.clear();
|
|
2929
|
-
_versions.clear();
|
|
2930
|
-
_regexCache.clear();
|
|
2931
|
-
_middlewares.clear();
|
|
2932
|
-
},
|
|
2933
|
-
_addPlugin: (p) => {
|
|
2934
|
-
installPlugin(getPluginContext(), p, instance);
|
|
2935
|
-
},
|
|
2936
|
-
_removePlugin: (name) => {
|
|
2937
|
-
_plugins.delete(name);
|
|
2938
|
-
},
|
|
2939
|
-
_subscribe: (cb, key) => {
|
|
2940
|
-
if (key) {
|
|
2941
|
-
if (!_keyListeners.has(key)) _keyListeners.set(key, /* @__PURE__ */ new Set());
|
|
2942
|
-
const set2 = _keyListeners.get(key);
|
|
2943
|
-
set2.add(cb);
|
|
2944
|
-
return () => {
|
|
2945
|
-
set2.delete(cb);
|
|
2946
|
-
if (set2.size === 0) _keyListeners.delete(key);
|
|
2947
|
-
};
|
|
2948
|
-
}
|
|
2949
|
-
_listeners.add(cb);
|
|
2950
|
-
return () => _listeners.delete(cb);
|
|
2951
|
-
},
|
|
2952
|
-
_getVersion: (key) => _versions.get(key) ?? 0,
|
|
2953
|
-
// Enterprise Security & Compliance
|
|
2954
|
-
addAccessRule: (pattern, permissions) => addAccessRule(_accessRules, pattern, permissions),
|
|
2955
|
-
hasPermission: (key, action, userId) => hasPermission(_accessRules, key, action, userId),
|
|
2956
|
-
recordConsent: (userId, purpose, granted) => recordConsent(_consents, userId, purpose, granted),
|
|
2957
|
-
hasConsent: (userId, purpose) => hasConsent(_consents, userId, purpose),
|
|
2958
|
-
getConsents: (userId) => getConsents(_consents, userId),
|
|
2959
|
-
revokeConsent: (userId, purpose) => revokeConsent(_consents, userId, purpose),
|
|
2960
|
-
exportUserData: (userId) => exportUserData(_consents, userId),
|
|
2961
|
-
deleteUserData: (userId) => deleteUserData(_consents, userId),
|
|
2962
|
-
getSnapshot: () => {
|
|
2963
|
-
if (!_snapshot) {
|
|
2964
|
-
_snapshot = Object.fromEntries(_store.entries());
|
|
2965
|
-
}
|
|
2966
|
-
return _snapshot;
|
|
2967
|
-
},
|
|
2968
|
-
get plugins() {
|
|
2969
|
-
return _methodNamespace;
|
|
2970
|
-
},
|
|
2971
|
-
get isReady() {
|
|
2972
|
-
return _isReady;
|
|
2973
|
-
},
|
|
2974
|
-
get namespace() {
|
|
2975
|
-
return _namespace;
|
|
2976
|
-
},
|
|
2977
|
-
get userId() {
|
|
2978
|
-
return _userId;
|
|
2979
|
-
},
|
|
2980
|
-
whenReady: () => _readyPromise
|
|
2981
|
-
};
|
|
2982
|
-
const secMethods = ["addAccessRule", "recordConsent", "hasConsent", "getConsents", "revokeConsent", "exportUserData", "deleteUserData"];
|
|
2983
|
-
secMethods.forEach((m) => {
|
|
2984
|
-
const fn = instance[m];
|
|
2985
|
-
if (fn) instance._registerMethod("security", m, fn);
|
|
2986
|
-
});
|
|
2987
|
-
const _unloadHandler = () => {
|
|
2988
|
-
if (_diskQueue.size > 0) _flushDisk();
|
|
2989
|
-
};
|
|
2990
|
-
if (typeof window !== "undefined") window.addEventListener("beforeunload", _unloadHandler);
|
|
2991
|
-
if (_storage) {
|
|
2992
|
-
hydrateStore(
|
|
2993
|
-
getPersistenceContext(),
|
|
2994
|
-
// We pass the calculateSize function to update memory usage correctly after hydration
|
|
2995
|
-
(val) => {
|
|
2996
|
-
const hasLimits = (_maxObjectSize > 0 || _maxTotalSize > 0) && !isProduction();
|
|
2997
|
-
return hasLimits ? _calculateSize(val) : 0;
|
|
2998
|
-
},
|
|
2999
|
-
() => {
|
|
3000
|
-
_isReady = true;
|
|
3001
|
-
_snapshot = null;
|
|
3002
|
-
_readyResolver();
|
|
3003
|
-
_emit();
|
|
3004
|
-
}
|
|
3005
|
-
).then(() => {
|
|
3006
|
-
});
|
|
3007
|
-
} else {
|
|
3008
|
-
_isReady = true;
|
|
3009
|
-
_readyResolver();
|
|
3010
|
-
}
|
|
3011
|
-
let _syncEngine = null;
|
|
3012
|
-
if (config?.sync) {
|
|
3013
|
-
_syncEngine = new SyncEngine(instance, config.sync);
|
|
3014
|
-
instance._registerMethod("sync", "flush", () => _syncEngine?.flush());
|
|
3015
|
-
instance._registerMethod("sync", "getState", () => _syncEngine?.getState());
|
|
3016
|
-
instance._registerMethod("sync", "onStateChange", (cb) => _syncEngine?.onStateChange(cb));
|
|
3017
|
-
}
|
|
3018
|
-
return instance;
|
|
3019
|
-
};
|
|
3020
|
-
|
|
3021
|
-
// core/hooks.ts
|
|
3022
|
-
var import_react = __toESM(require_react(), 1);
|
|
3023
|
-
var _defaultStore = null;
|
|
3024
|
-
var initState = (config) => {
|
|
3025
|
-
if (_defaultStore && !config?.namespace) {
|
|
3026
|
-
if (!config?.silent) {
|
|
3027
|
-
console.warn(
|
|
3028
|
-
"[gstate] Store already exists. Pass a unique namespace to create additional stores."
|
|
3029
|
-
);
|
|
3030
|
-
}
|
|
3031
|
-
}
|
|
3032
|
-
const store = createStore(config);
|
|
3033
|
-
_defaultStore = store;
|
|
3034
|
-
return store;
|
|
3035
|
-
};
|
|
3036
|
-
var destroyState = () => {
|
|
3037
|
-
if (_defaultStore) {
|
|
3038
|
-
_defaultStore.destroy();
|
|
3039
|
-
_defaultStore = null;
|
|
3040
|
-
}
|
|
3041
|
-
};
|
|
3042
|
-
var useIsStoreReady = (store) => {
|
|
3043
|
-
const targetStore = store || _defaultStore;
|
|
3044
|
-
const subscribe = (0, import_react.useMemo)(
|
|
3045
|
-
() => (callback) => targetStore ? targetStore._subscribe(callback) : () => {
|
|
3046
|
-
},
|
|
3047
|
-
[targetStore]
|
|
3048
|
-
);
|
|
3049
|
-
return (0, import_react.useSyncExternalStore)(
|
|
3050
|
-
subscribe,
|
|
3051
|
-
() => targetStore ? targetStore.isReady : false,
|
|
3052
|
-
() => true
|
|
3053
|
-
// SSR is always "ready" as it doesn't hydrate from local storage
|
|
3054
|
-
);
|
|
3055
|
-
};
|
|
3056
|
-
var getStore = () => _defaultStore;
|
|
3057
|
-
function useStore(keyOrSelector, store) {
|
|
3058
|
-
const targetStore = (0, import_react.useMemo)(
|
|
3059
|
-
() => store || _defaultStore,
|
|
3060
|
-
[store]
|
|
3061
|
-
);
|
|
3062
|
-
const ghostStore = (0, import_react.useMemo)(() => {
|
|
3063
|
-
const noop = () => {
|
|
3064
|
-
};
|
|
3065
|
-
const noopFalse = () => false;
|
|
3066
|
-
const noopNull = () => null;
|
|
3067
|
-
return {
|
|
3068
|
-
set: noopFalse,
|
|
3069
|
-
get: noopNull,
|
|
3070
|
-
remove: noopFalse,
|
|
3071
|
-
delete: noopFalse,
|
|
3072
|
-
deleteAll: noopFalse,
|
|
3073
|
-
list: () => ({}),
|
|
3074
|
-
compute: noopNull,
|
|
3075
|
-
watch: () => () => {
|
|
3076
|
-
},
|
|
3077
|
-
use: noop,
|
|
3078
|
-
transaction: noop,
|
|
3079
|
-
destroy: noop,
|
|
3080
|
-
_subscribe: () => () => {
|
|
3081
|
-
},
|
|
3082
|
-
_setSilently: noop,
|
|
3083
|
-
_registerMethod: noop,
|
|
3084
|
-
_addPlugin: noop,
|
|
3085
|
-
_removePlugin: noop,
|
|
3086
|
-
_getVersion: () => 0,
|
|
3087
|
-
get isReady() {
|
|
3088
|
-
return false;
|
|
3089
|
-
},
|
|
3090
|
-
whenReady: () => Promise.resolve(),
|
|
3091
|
-
get plugins() {
|
|
3092
|
-
return {};
|
|
3093
|
-
},
|
|
3094
|
-
getSnapshot: () => ({}),
|
|
3095
|
-
// Ghost snapshot
|
|
3096
|
-
get namespace() {
|
|
3097
|
-
return "ghost";
|
|
3098
|
-
},
|
|
3099
|
-
get userId() {
|
|
3100
|
-
return void 0;
|
|
3101
|
-
}
|
|
3102
|
-
};
|
|
3103
|
-
}, []);
|
|
3104
|
-
const safeStore = targetStore || ghostStore;
|
|
3105
|
-
const isSelector = typeof keyOrSelector === "function";
|
|
3106
|
-
const key = !isSelector ? keyOrSelector : null;
|
|
3107
|
-
const selector = isSelector ? keyOrSelector : null;
|
|
3108
|
-
const subscribe = (0, import_react.useCallback)(
|
|
3109
|
-
(callback) => {
|
|
3110
|
-
if (isSelector) {
|
|
3111
|
-
return safeStore._subscribe(callback);
|
|
3112
|
-
} else {
|
|
3113
|
-
return safeStore._subscribe(callback, key);
|
|
3114
|
-
}
|
|
3115
|
-
},
|
|
3116
|
-
[safeStore, isSelector, key]
|
|
3117
|
-
);
|
|
3118
|
-
const getSnapshot = (0, import_react.useCallback)(() => {
|
|
3119
|
-
if (isSelector) {
|
|
3120
|
-
return selector(safeStore.getSnapshot());
|
|
3121
|
-
} else {
|
|
3122
|
-
return safeStore.get(key) ?? void 0;
|
|
3123
|
-
}
|
|
3124
|
-
}, [safeStore, isSelector, key, selector]);
|
|
3125
|
-
const getServerSnapshot = (0, import_react.useCallback)(() => {
|
|
3126
|
-
if (isSelector) {
|
|
3127
|
-
try {
|
|
3128
|
-
return selector({});
|
|
3129
|
-
} catch {
|
|
3130
|
-
return void 0;
|
|
3131
|
-
}
|
|
3132
|
-
} else {
|
|
3133
|
-
return void 0;
|
|
3134
|
-
}
|
|
3135
|
-
}, [selector, isSelector]);
|
|
3136
|
-
const value = (0, import_react.useSyncExternalStore)(
|
|
3137
|
-
subscribe,
|
|
3138
|
-
getSnapshot,
|
|
3139
|
-
// Cast needed for union types
|
|
3140
|
-
getServerSnapshot
|
|
3141
|
-
);
|
|
3142
|
-
const setter = (0, import_react.useCallback)(
|
|
3143
|
-
(val, options) => {
|
|
3144
|
-
if (isSelector) {
|
|
3145
|
-
if (!isProduction()) {
|
|
3146
|
-
console.warn("[gstate] Cannot set value when using a selector.");
|
|
3147
|
-
}
|
|
3148
|
-
return false;
|
|
3149
|
-
}
|
|
3150
|
-
return safeStore.set(key, val, options);
|
|
3151
|
-
},
|
|
3152
|
-
[safeStore, isSelector, key]
|
|
3153
|
-
);
|
|
3154
|
-
(0, import_react.useDebugValue)(value, (v) => isSelector ? `Selector: ${JSON.stringify(v)}` : `${key}: ${JSON.stringify(v)}`);
|
|
3155
|
-
if (isSelector) {
|
|
3156
|
-
return value;
|
|
3157
|
-
}
|
|
3158
|
-
return [value, setter];
|
|
3159
|
-
}
|
|
3160
|
-
var _syncEngines = /* @__PURE__ */ new Map();
|
|
3161
|
-
var initSync = (store, config) => {
|
|
3162
|
-
const key = store.namespace;
|
|
3163
|
-
if (_syncEngines.has(key)) {
|
|
3164
|
-
console.warn(`[gstate] Sync engine already exists for namespace "${key}". Call destroySync first.`);
|
|
3165
|
-
return _syncEngines.get(key);
|
|
3166
|
-
}
|
|
3167
|
-
const engine = new SyncEngine(store, config);
|
|
3168
|
-
_syncEngines.set(key, engine);
|
|
3169
|
-
return engine;
|
|
3170
|
-
};
|
|
3171
|
-
var destroySync = (namespace) => {
|
|
3172
|
-
const engine = _syncEngines.get(namespace);
|
|
3173
|
-
if (engine) {
|
|
3174
|
-
engine.destroy();
|
|
3175
|
-
_syncEngines.delete(namespace);
|
|
3176
|
-
}
|
|
3177
|
-
};
|
|
3178
|
-
function useSyncedState(key, store) {
|
|
3179
|
-
const targetStore = store || _defaultStore;
|
|
3180
|
-
const namespace = targetStore?.namespace || "default";
|
|
3181
|
-
const engine = _syncEngines.get(namespace);
|
|
3182
|
-
const result = useStore(key, targetStore);
|
|
3183
|
-
const value = result[0];
|
|
3184
|
-
const setter = result[1];
|
|
3185
|
-
const [syncState, setSyncState] = (0, import_react.useState)(() => engine?.getState() || {
|
|
3186
|
-
isOnline: true,
|
|
3187
|
-
isSyncing: false,
|
|
3188
|
-
lastSyncTimestamp: null,
|
|
3189
|
-
pendingChanges: 0,
|
|
3190
|
-
conflicts: 0
|
|
3191
|
-
});
|
|
3192
|
-
(0, import_react.useEffect)(() => {
|
|
3193
|
-
if (!engine) return;
|
|
3194
|
-
const unsubscribe = engine.onStateChange(setSyncState);
|
|
3195
|
-
return unsubscribe;
|
|
3196
|
-
}, [engine]);
|
|
3197
|
-
const syncedSetter = (0, import_react.useCallback)(
|
|
3198
|
-
(val, options) => {
|
|
3199
|
-
const result2 = setter(val, options);
|
|
3200
|
-
if (result2 && engine) {
|
|
3201
|
-
const currentValue = targetStore?.get(key);
|
|
3202
|
-
engine.queueChange(key, currentValue);
|
|
3203
|
-
}
|
|
3204
|
-
return result2;
|
|
3205
|
-
},
|
|
3206
|
-
[setter, engine, key, targetStore]
|
|
3207
|
-
);
|
|
3208
|
-
return [value, syncedSetter, syncState];
|
|
3209
|
-
}
|
|
3210
|
-
var useSyncStatus = () => {
|
|
3211
|
-
const [state, setState] = (0, import_react.useState)({
|
|
3212
|
-
isOnline: true,
|
|
3213
|
-
isSyncing: false,
|
|
3214
|
-
lastSyncTimestamp: null,
|
|
3215
|
-
pendingChanges: 0,
|
|
3216
|
-
conflicts: 0
|
|
3217
|
-
});
|
|
3218
|
-
(0, import_react.useEffect)(() => {
|
|
3219
|
-
const updateState = () => {
|
|
3220
|
-
let isOnline = true;
|
|
3221
|
-
let isSyncing = false;
|
|
3222
|
-
let pendingChanges = 0;
|
|
3223
|
-
let conflicts = 0;
|
|
3224
|
-
_syncEngines.forEach((engine) => {
|
|
3225
|
-
const s = engine.getState();
|
|
3226
|
-
isOnline = isOnline && s.isOnline;
|
|
3227
|
-
isSyncing = isSyncing || s.isSyncing;
|
|
3228
|
-
pendingChanges += s.pendingChanges;
|
|
3229
|
-
conflicts += s.conflicts;
|
|
3230
|
-
});
|
|
3231
|
-
setState({
|
|
3232
|
-
isOnline,
|
|
3233
|
-
isSyncing,
|
|
3234
|
-
lastSyncTimestamp: null,
|
|
3235
|
-
pendingChanges,
|
|
3236
|
-
conflicts
|
|
3237
|
-
});
|
|
3238
|
-
};
|
|
3239
|
-
updateState();
|
|
3240
|
-
const unsubscribes = Array.from(_syncEngines.values()).map(
|
|
3241
|
-
(engine) => engine.onStateChange(updateState)
|
|
3242
|
-
);
|
|
3243
|
-
return () => unsubscribes.forEach((fn) => fn());
|
|
3244
|
-
}, []);
|
|
3245
|
-
return state;
|
|
3246
|
-
};
|
|
3247
|
-
var triggerSync = async (namespace) => {
|
|
3248
|
-
const targetNamespace = namespace || _defaultStore?.namespace;
|
|
3249
|
-
if (!targetNamespace) return;
|
|
3250
|
-
const engine = _syncEngines.get(targetNamespace);
|
|
3251
|
-
if (engine) {
|
|
3252
|
-
await engine.flush();
|
|
3253
|
-
}
|
|
3254
|
-
};
|
|
3255
|
-
|
|
3256
|
-
// core/async.ts
|
|
3257
|
-
var createAsyncStore = (resolver, options) => {
|
|
3258
|
-
const key = options?.key || "async_data";
|
|
3259
|
-
const store = options?.store || createStore({
|
|
3260
|
-
namespace: `async_${key}`,
|
|
3261
|
-
silent: true
|
|
3262
|
-
});
|
|
3263
|
-
if (store.get(key) == null) {
|
|
3264
|
-
store.set(key, { data: null, loading: false, error: null, updatedAt: null });
|
|
3265
|
-
}
|
|
3266
|
-
const run = async () => {
|
|
3267
|
-
const current2 = store.get(key);
|
|
3268
|
-
store.set(key, {
|
|
3269
|
-
...current2 || { data: null, loading: false, error: null, updatedAt: null },
|
|
3270
|
-
loading: true,
|
|
3271
|
-
error: null
|
|
3272
|
-
});
|
|
3273
|
-
if ("whenReady" in store && !store.isReady) await store.whenReady();
|
|
3274
|
-
try {
|
|
3275
|
-
const result = await resolver();
|
|
3276
|
-
const prev = store.get(key);
|
|
3277
|
-
store.set(key, {
|
|
3278
|
-
...prev || { data: null, loading: false, error: null, updatedAt: null },
|
|
3279
|
-
data: result,
|
|
3280
|
-
loading: false,
|
|
3281
|
-
updatedAt: Date.now()
|
|
3282
|
-
}, { persist: options?.persist });
|
|
3283
|
-
} catch (e) {
|
|
3284
|
-
const prev = store.get(key);
|
|
3285
|
-
store.set(key, {
|
|
3286
|
-
...prev || { data: null, loading: false, error: null, updatedAt: null },
|
|
3287
|
-
error: e instanceof Error ? e : new Error(String(e)),
|
|
3288
|
-
loading: false
|
|
3289
|
-
});
|
|
3290
|
-
}
|
|
3291
|
-
};
|
|
3292
|
-
return Object.assign(store, { execute: run });
|
|
3293
|
-
};
|
|
3294
|
-
|
|
3295
|
-
// plugins/official/immer.plugin.ts
|
|
3296
|
-
var immerPlugin = () => ({
|
|
3297
|
-
name: "gstate-immer",
|
|
3298
|
-
hooks: {
|
|
3299
|
-
onInstall: ({ store }) => {
|
|
3300
|
-
store._registerMethod("immer", "setWithProduce", ((key, updater) => {
|
|
3301
|
-
return store.set(key, updater);
|
|
3302
|
-
}));
|
|
3303
|
-
}
|
|
3304
|
-
}
|
|
3305
|
-
});
|
|
3306
|
-
|
|
3307
|
-
// plugins/official/undo-redo.plugin.ts
|
|
3308
|
-
var undoRedoPlugin = (options) => {
|
|
3309
|
-
let _history = [];
|
|
3310
|
-
let _cursor = -1;
|
|
3311
|
-
let _isRestoring = false;
|
|
3312
|
-
const _limit = options?.limit || 50;
|
|
3313
|
-
return {
|
|
3314
|
-
name: "gstate-undo-redo",
|
|
3315
|
-
hooks: {
|
|
3316
|
-
onInstall: ({ store }) => {
|
|
3317
|
-
_history.push(store.list());
|
|
3318
|
-
_cursor = 0;
|
|
3319
|
-
store._registerMethod("undoRedo", "undo", () => {
|
|
3320
|
-
if (_cursor > 0) {
|
|
3321
|
-
_isRestoring = true;
|
|
3322
|
-
_cursor--;
|
|
3323
|
-
const snapshot = _history[_cursor];
|
|
3324
|
-
if (!snapshot) return false;
|
|
3325
|
-
Object.entries(snapshot).forEach(([k, v]) => {
|
|
3326
|
-
store._setSilently(k, v);
|
|
3327
|
-
});
|
|
3328
|
-
_isRestoring = false;
|
|
3329
|
-
return true;
|
|
3330
|
-
}
|
|
3331
|
-
return false;
|
|
3332
|
-
});
|
|
3333
|
-
store._registerMethod("undoRedo", "redo", () => {
|
|
3334
|
-
if (_cursor < _history.length - 1) {
|
|
3335
|
-
_isRestoring = true;
|
|
3336
|
-
_cursor++;
|
|
3337
|
-
const snapshot = _history[_cursor];
|
|
3338
|
-
if (!snapshot) return false;
|
|
3339
|
-
Object.entries(snapshot).forEach(([k, v]) => {
|
|
3340
|
-
store._setSilently(k, v);
|
|
3341
|
-
});
|
|
3342
|
-
_isRestoring = false;
|
|
3343
|
-
return true;
|
|
3344
|
-
}
|
|
3345
|
-
return false;
|
|
3346
|
-
});
|
|
3347
|
-
store._registerMethod("undoRedo", "canUndo", () => _cursor > 0);
|
|
3348
|
-
store._registerMethod("undoRedo", "canRedo", () => _cursor < _history.length - 1);
|
|
3349
|
-
},
|
|
3350
|
-
onSet: ({ store }) => {
|
|
3351
|
-
if (_isRestoring) return;
|
|
3352
|
-
if (_cursor < _history.length - 1) {
|
|
3353
|
-
_history = _history.slice(0, _cursor + 1);
|
|
3354
|
-
}
|
|
3355
|
-
_history.push(store.list());
|
|
3356
|
-
if (_history.length > _limit) {
|
|
3357
|
-
_history.shift();
|
|
3358
|
-
} else {
|
|
3359
|
-
_cursor++;
|
|
3360
|
-
}
|
|
3361
|
-
}
|
|
3362
|
-
}
|
|
3363
|
-
};
|
|
3364
|
-
};
|
|
3365
|
-
|
|
3366
|
-
// plugins/official/schema.plugin.ts
|
|
3367
|
-
var schemaPlugin = (schemas) => ({
|
|
3368
|
-
name: "gstate-schema",
|
|
3369
|
-
hooks: {
|
|
3370
|
-
onSet: ({ key, value }) => {
|
|
3371
|
-
if (!key) return;
|
|
3372
|
-
const validator = schemas[key];
|
|
3373
|
-
if (validator) {
|
|
3374
|
-
const result = validator(value);
|
|
3375
|
-
if (result !== true) {
|
|
3376
|
-
throw new Error(`[Schema Error] Validation failed for key "${key}": ${result === false ? "Invalid type" : result}`);
|
|
3377
|
-
}
|
|
3378
|
-
}
|
|
3379
|
-
}
|
|
3380
|
-
}
|
|
3381
|
-
});
|
|
3382
|
-
|
|
3383
|
-
// plugins/official/devtools.plugin.ts
|
|
3384
|
-
var devToolsPlugin = (options) => {
|
|
3385
|
-
const ext = globalThis;
|
|
3386
|
-
const global = ext;
|
|
3387
|
-
const extension = global.__REDUX_DEVTOOLS_EXTENSION__;
|
|
3388
|
-
if (!extension?.connect) {
|
|
3389
|
-
return { name: "gstate-devtools-noop", hooks: {} };
|
|
3390
|
-
}
|
|
3391
|
-
let _devTools = null;
|
|
3392
|
-
return {
|
|
3393
|
-
name: "gstate-devtools",
|
|
3394
|
-
hooks: {
|
|
3395
|
-
onInstall: ({ store }) => {
|
|
3396
|
-
_devTools = extension.connect({ name: options?.name || "Magnetar Store" });
|
|
3397
|
-
_devTools.init(store.list());
|
|
3398
|
-
},
|
|
3399
|
-
onSet: ({ key, store }) => {
|
|
3400
|
-
if (!key || !_devTools) return;
|
|
3401
|
-
_devTools.send(`SET_${key.toUpperCase()}`, store.list());
|
|
3402
|
-
},
|
|
3403
|
-
onRemove: ({ key, store }) => {
|
|
3404
|
-
if (!key || !_devTools) return;
|
|
3405
|
-
_devTools.send(`REMOVE_${key.toUpperCase()}`, store.list());
|
|
3406
|
-
}
|
|
3407
|
-
}
|
|
3408
|
-
};
|
|
3409
|
-
};
|
|
3410
|
-
|
|
3411
|
-
// plugins/official/snapshot.plugin.ts
|
|
3412
|
-
var snapshotPlugin = () => {
|
|
3413
|
-
const _snapshots = /* @__PURE__ */ new Map();
|
|
3414
|
-
return {
|
|
3415
|
-
name: "gstate-snapshot",
|
|
3416
|
-
hooks: {
|
|
3417
|
-
onInstall: ({ store }) => {
|
|
3418
|
-
store._registerMethod("snapshot", "takeSnapshot", ((name) => {
|
|
3419
|
-
_snapshots.set(name, store.list());
|
|
3420
|
-
}));
|
|
3421
|
-
store._registerMethod("snapshot", "restoreSnapshot", ((name) => {
|
|
3422
|
-
const snap = _snapshots.get(name);
|
|
3423
|
-
if (!snap) return false;
|
|
3424
|
-
store.transaction(() => {
|
|
3425
|
-
Object.entries(snap).forEach(([k, v]) => {
|
|
3426
|
-
store.set(k, v);
|
|
3427
|
-
});
|
|
3428
|
-
});
|
|
3429
|
-
return true;
|
|
3430
|
-
}));
|
|
3431
|
-
store._registerMethod("snapshot", "listSnapshots", (() => Array.from(_snapshots.keys())));
|
|
3432
|
-
store._registerMethod("snapshot", "deleteSnapshot", ((name) => _snapshots.delete(name)));
|
|
3433
|
-
store._registerMethod("snapshot", "clearSnapshots", (() => _snapshots.clear()));
|
|
3434
|
-
}
|
|
3435
|
-
}
|
|
3436
|
-
};
|
|
3437
|
-
};
|
|
3438
|
-
|
|
3439
|
-
// plugins/official/guard.plugin.ts
|
|
3440
|
-
var guardPlugin = (guards) => ({
|
|
3441
|
-
name: "gstate-guard",
|
|
3442
|
-
hooks: {
|
|
3443
|
-
onBeforeSet: ({ key, value, store: _store }) => {
|
|
3444
|
-
if (!key) return;
|
|
3445
|
-
const guard = guards[key];
|
|
3446
|
-
if (guard) {
|
|
3447
|
-
const transformed = guard(value);
|
|
3448
|
-
if (transformed !== value) {
|
|
3449
|
-
}
|
|
3450
|
-
}
|
|
3451
|
-
}
|
|
3452
|
-
}
|
|
3453
|
-
});
|
|
3454
|
-
|
|
3455
|
-
// plugins/official/analytics.plugin.ts
|
|
3456
|
-
var analyticsPlugin = (options) => ({
|
|
3457
|
-
name: "gstate-analytics",
|
|
3458
|
-
hooks: {
|
|
3459
|
-
onSet: ({ key, value }) => {
|
|
3460
|
-
if (!key) return;
|
|
3461
|
-
if (!options.keys || options.keys.includes(key)) {
|
|
3462
|
-
options.provider({ key, value, action: "SET" });
|
|
3463
|
-
}
|
|
3464
|
-
},
|
|
3465
|
-
onRemove: ({ key }) => {
|
|
3466
|
-
if (!key) return;
|
|
3467
|
-
if (!options.keys || options.keys.includes(key)) {
|
|
3468
|
-
options.provider({ key, value: null, action: "REMOVE" });
|
|
3469
|
-
}
|
|
3470
|
-
}
|
|
3471
|
-
}
|
|
3472
|
-
});
|
|
3473
|
-
|
|
3474
|
-
// plugins/official/sync.plugin.ts
|
|
3475
|
-
var syncPlugin = (options) => {
|
|
3476
|
-
const _channel = new BroadcastChannel(options?.channelName || "gstate_sync");
|
|
3477
|
-
let _isSyncing = false;
|
|
3478
|
-
return {
|
|
3479
|
-
name: "gstate-sync",
|
|
3480
|
-
hooks: {
|
|
3481
|
-
onInstall: ({ store }) => {
|
|
3482
|
-
_channel.onmessage = (event) => {
|
|
3483
|
-
const { key, value, action } = event.data;
|
|
3484
|
-
if (!key) return;
|
|
3485
|
-
_isSyncing = true;
|
|
3486
|
-
if (action === "REMOVE") {
|
|
3487
|
-
store.remove(key);
|
|
3488
|
-
} else {
|
|
3489
|
-
store.set(key, value);
|
|
3490
|
-
}
|
|
3491
|
-
_isSyncing = false;
|
|
3492
|
-
};
|
|
3493
|
-
},
|
|
3494
|
-
onSet: ({ key, value }) => {
|
|
3495
|
-
if (!key || _isSyncing) return;
|
|
3496
|
-
_channel.postMessage({ key, value, action: "SET" });
|
|
3497
|
-
},
|
|
3498
|
-
onRemove: ({ key }) => {
|
|
3499
|
-
if (!key || _isSyncing) return;
|
|
3500
|
-
_channel.postMessage({ key, action: "REMOVE" });
|
|
3501
|
-
},
|
|
3502
|
-
onDestroy: () => {
|
|
3503
|
-
_channel.close();
|
|
3504
|
-
}
|
|
3505
|
-
}
|
|
3506
|
-
};
|
|
3507
|
-
};
|
|
3508
|
-
|
|
3509
|
-
// plugins/official/debug.plugin.ts
|
|
3510
|
-
var debugPlugin = () => {
|
|
3511
|
-
if (isProduction()) {
|
|
3512
|
-
return { name: "gstate-debug-noop", hooks: {} };
|
|
3513
|
-
}
|
|
3514
|
-
const isDev = !isProduction();
|
|
3515
|
-
const debugLog = (...args) => {
|
|
3516
|
-
if (isDev) console.debug(...args);
|
|
3517
|
-
};
|
|
3518
|
-
return {
|
|
3519
|
-
name: "gstate-debug",
|
|
3520
|
-
hooks: {
|
|
3521
|
-
onInstall: ({ store }) => {
|
|
3522
|
-
if (typeof window !== "undefined") {
|
|
3523
|
-
window.gstate = {
|
|
3524
|
-
/** Get all state */
|
|
3525
|
-
list: () => {
|
|
3526
|
-
return store.list();
|
|
3527
|
-
},
|
|
3528
|
-
/** Get a specific key */
|
|
3529
|
-
get: (key) => {
|
|
3530
|
-
const val = store.get(key);
|
|
3531
|
-
debugLog(`[gstate] get('${key}'):`, val);
|
|
3532
|
-
return val;
|
|
3533
|
-
},
|
|
3534
|
-
/** Set a value */
|
|
3535
|
-
set: (key, value) => {
|
|
3536
|
-
const result = store.set(key, value);
|
|
3537
|
-
debugLog(`[gstate] set('${key}', ${JSON.stringify(value)}):`, result);
|
|
3538
|
-
return result;
|
|
3539
|
-
},
|
|
3540
|
-
/** Watch a key */
|
|
3541
|
-
watch: (key, callback) => {
|
|
3542
|
-
const unwatch = store.watch(key, callback);
|
|
3543
|
-
debugLog(`[gstate] watching '${key}'`);
|
|
3544
|
-
return unwatch;
|
|
3545
|
-
},
|
|
3546
|
-
/** Get store info */
|
|
3547
|
-
info: () => {
|
|
3548
|
-
const info = {
|
|
3549
|
-
namespace: store.namespace,
|
|
3550
|
-
isReady: store.isReady,
|
|
3551
|
-
keys: Object.keys(store.list()),
|
|
3552
|
-
size: Object.keys(store.list()).length
|
|
3553
|
-
};
|
|
3554
|
-
debugLog("[gstate] Store Info:", info);
|
|
3555
|
-
return info;
|
|
3556
|
-
},
|
|
3557
|
-
/** Clear console and show banner */
|
|
3558
|
-
banner: () => {
|
|
3559
|
-
debugLog(`
|
|
3560
|
-
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
3561
|
-
\u2551 \u{1F9F2} gState Debug \u2551
|
|
3562
|
-
\u2551 Type: gstate.list() \u2551
|
|
3563
|
-
\u2551 gstate.get(key) \u2551
|
|
3564
|
-
\u2551 gstate.set(key, value) \u2551
|
|
3565
|
-
\u2551 gstate.info() \u2551
|
|
3566
|
-
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
|
|
3567
|
-
`);
|
|
3568
|
-
}
|
|
3569
|
-
};
|
|
3570
|
-
debugLog("[gstate] Debug plugin installed. Type gstate.banner() for help.");
|
|
3571
|
-
}
|
|
3572
|
-
},
|
|
3573
|
-
onDestroy: () => {
|
|
3574
|
-
if (typeof window !== "undefined") {
|
|
3575
|
-
delete window.gstate;
|
|
3576
|
-
}
|
|
3577
|
-
}
|
|
3578
|
-
}
|
|
3579
|
-
};
|
|
3580
|
-
};
|
|
3581
|
-
|
|
3582
|
-
// plugins/official/indexeddb.plugin.ts
|
|
3583
|
-
var indexedDBPlugin = (options = {}) => {
|
|
3584
|
-
const dbName = options.dbName || "rgs-db";
|
|
3585
|
-
const storeName = options.storeName || "states";
|
|
3586
|
-
const dbVersion = options.version || 1;
|
|
3587
|
-
let db = null;
|
|
3588
|
-
const getDB = () => {
|
|
3589
|
-
return new Promise((resolve, reject) => {
|
|
3590
|
-
if (db) return resolve(db);
|
|
3591
|
-
const request = indexedDB.open(dbName, dbVersion);
|
|
3592
|
-
request.onerror = () => reject(request.error);
|
|
3593
|
-
request.onsuccess = () => {
|
|
3594
|
-
db = request.result;
|
|
3595
|
-
resolve(db);
|
|
3596
|
-
};
|
|
3597
|
-
request.onupgradeneeded = (event) => {
|
|
3598
|
-
const database = event.target.result;
|
|
3599
|
-
if (!database.objectStoreNames.contains(storeName)) {
|
|
3600
|
-
database.createObjectStore(storeName);
|
|
3601
|
-
}
|
|
3602
|
-
};
|
|
3603
|
-
});
|
|
3604
|
-
};
|
|
3605
|
-
const save = async (key, value) => {
|
|
3606
|
-
const database = await getDB();
|
|
3607
|
-
return new Promise((resolve, reject) => {
|
|
3608
|
-
const tx = database.transaction(storeName, "readwrite");
|
|
3609
|
-
const store = tx.objectStore(storeName);
|
|
3610
|
-
const request = store.put(value, key);
|
|
3611
|
-
request.onsuccess = () => resolve();
|
|
3612
|
-
request.onerror = () => reject(request.error);
|
|
3613
|
-
});
|
|
3614
|
-
};
|
|
3615
|
-
const load = async (key) => {
|
|
3616
|
-
const database = await getDB();
|
|
3617
|
-
return new Promise((resolve, reject) => {
|
|
3618
|
-
const tx = database.transaction(storeName, "readonly");
|
|
3619
|
-
const store = tx.objectStore(storeName);
|
|
3620
|
-
const request = store.get(key);
|
|
3621
|
-
request.onsuccess = () => resolve(request.result);
|
|
3622
|
-
request.onerror = () => reject(request.error);
|
|
3623
|
-
});
|
|
3624
|
-
};
|
|
3625
|
-
const remove = async (key) => {
|
|
3626
|
-
const database = await getDB();
|
|
3627
|
-
return new Promise((resolve, reject) => {
|
|
3628
|
-
const tx = database.transaction(storeName, "readwrite");
|
|
3629
|
-
const store = tx.objectStore(storeName);
|
|
3630
|
-
const request = store.delete(key);
|
|
3631
|
-
request.onsuccess = () => resolve();
|
|
3632
|
-
request.onerror = () => reject(request.error);
|
|
3633
|
-
});
|
|
3634
|
-
};
|
|
3635
|
-
return {
|
|
3636
|
-
name: "indexedDB",
|
|
3637
|
-
hooks: {
|
|
3638
|
-
onInstall: ({ store }) => {
|
|
3639
|
-
store._registerMethod("indexedDB", "clear", async () => {
|
|
3640
|
-
const database = await getDB();
|
|
3641
|
-
const tx = database.transaction(storeName, "readwrite");
|
|
3642
|
-
tx.objectStore(storeName).clear();
|
|
3643
|
-
});
|
|
3644
|
-
},
|
|
3645
|
-
onInit: async ({ store }) => {
|
|
3646
|
-
const database = await getDB();
|
|
3647
|
-
const tx = database.transaction(storeName, "readonly");
|
|
3648
|
-
const objectStore = tx.objectStore(storeName);
|
|
3649
|
-
const request = objectStore.getAllKeys();
|
|
3650
|
-
request.onsuccess = async () => {
|
|
3651
|
-
const keys = request.result;
|
|
3652
|
-
const prefix = store.namespace + "_";
|
|
3653
|
-
for (const key of keys) {
|
|
3654
|
-
if (key.startsWith(prefix)) {
|
|
3655
|
-
const val = await load(key);
|
|
3656
|
-
if (val) {
|
|
3657
|
-
const storeKey = key.substring(prefix.length);
|
|
3658
|
-
store._setSilently(storeKey, val.d);
|
|
3659
|
-
}
|
|
3660
|
-
}
|
|
3661
|
-
}
|
|
3662
|
-
};
|
|
3663
|
-
},
|
|
3664
|
-
onSet: async ({ key, value, store }) => {
|
|
3665
|
-
if (!key) return;
|
|
3666
|
-
const prefix = store.namespace + "_";
|
|
3667
|
-
const data = {
|
|
3668
|
-
d: value,
|
|
3669
|
-
t: Date.now(),
|
|
3670
|
-
v: store._getVersion?.(key) || 1
|
|
3671
|
-
};
|
|
3672
|
-
await save(`${prefix}${key}`, data);
|
|
3673
|
-
},
|
|
3674
|
-
onRemove: async ({ key, store }) => {
|
|
3675
|
-
if (!key) return;
|
|
3676
|
-
const prefix = store.namespace + "_";
|
|
3677
|
-
await remove(`${prefix}${key}`);
|
|
3678
|
-
}
|
|
3679
|
-
}
|
|
3680
|
-
};
|
|
3681
|
-
};
|
|
3682
|
-
|
|
3683
|
-
// plugins/official/cloud-sync.plugin.ts
|
|
3684
|
-
var cloudSyncPlugin = (options) => {
|
|
3685
|
-
const { adapter, autoSyncInterval } = options;
|
|
3686
|
-
const lastSyncedVersions = /* @__PURE__ */ new Map();
|
|
3687
|
-
const stats = {
|
|
3688
|
-
lastSyncTimestamp: null,
|
|
3689
|
-
totalKeysSynced: 0,
|
|
3690
|
-
totalBytesSynced: 0,
|
|
3691
|
-
syncCount: 0,
|
|
3692
|
-
lastDuration: 0,
|
|
3693
|
-
errors: 0
|
|
3694
|
-
};
|
|
3695
|
-
let timer = null;
|
|
3696
|
-
return {
|
|
3697
|
-
name: "cloudSync",
|
|
3698
|
-
hooks: {
|
|
3699
|
-
onInstall: ({ store }) => {
|
|
3700
|
-
store._registerMethod("cloudSync", "sync", async () => {
|
|
3701
|
-
const startTime = performance.now();
|
|
3702
|
-
const dirtyData = {};
|
|
3703
|
-
let bytesCount = 0;
|
|
3704
|
-
try {
|
|
3705
|
-
const allData = store.list();
|
|
3706
|
-
const keys = Object.keys(allData);
|
|
3707
|
-
for (const key of keys) {
|
|
3708
|
-
const currentVersion = store._getVersion?.(key) || 0;
|
|
3709
|
-
const lastVersion = lastSyncedVersions.get(key) || 0;
|
|
3710
|
-
if (currentVersion > lastVersion) {
|
|
3711
|
-
const val = allData[key];
|
|
3712
|
-
dirtyData[key] = val;
|
|
3713
|
-
bytesCount += JSON.stringify(val).length;
|
|
3714
|
-
lastSyncedVersions.set(key, currentVersion);
|
|
3715
|
-
}
|
|
3716
|
-
}
|
|
3717
|
-
if (Object.keys(dirtyData).length === 0) return { status: "no-change", stats };
|
|
3718
|
-
const success = await adapter.save(dirtyData);
|
|
3719
|
-
if (success) {
|
|
3720
|
-
stats.lastSyncTimestamp = Date.now();
|
|
3721
|
-
stats.totalKeysSynced += Object.keys(dirtyData).length;
|
|
3722
|
-
stats.totalBytesSynced += bytesCount;
|
|
3723
|
-
stats.syncCount++;
|
|
3724
|
-
stats.lastDuration = performance.now() - startTime;
|
|
3725
|
-
if (options.onSync) options.onSync(stats);
|
|
3726
|
-
return { status: "success", stats };
|
|
3727
|
-
} else {
|
|
3728
|
-
throw new Error(`Adapter ${adapter.name} failed to save.`);
|
|
3729
|
-
}
|
|
3730
|
-
} catch (err) {
|
|
3731
|
-
stats.errors++;
|
|
3732
|
-
console.error(`[gstate] Cloud Sync Failed (${adapter.name}):`, err);
|
|
3733
|
-
return { status: "error", error: String(err), stats };
|
|
3734
|
-
}
|
|
3735
|
-
});
|
|
3736
|
-
store._registerMethod("cloudSync", "getStats", () => stats);
|
|
3737
|
-
if (autoSyncInterval && autoSyncInterval > 0) {
|
|
3738
|
-
timer = setInterval(() => {
|
|
3739
|
-
const plugins2 = store.plugins;
|
|
3740
|
-
const cs = plugins2.cloudSync;
|
|
3741
|
-
if (cs) cs.sync();
|
|
3742
|
-
}, autoSyncInterval);
|
|
3743
|
-
}
|
|
3744
|
-
},
|
|
3745
|
-
onDestroy: () => {
|
|
3746
|
-
if (timer) clearInterval(timer);
|
|
3747
|
-
}
|
|
3748
|
-
}
|
|
3749
|
-
};
|
|
3750
|
-
};
|
|
3751
|
-
var createMongoAdapter = (apiUrl, apiKey) => ({
|
|
3752
|
-
name: "MongoDB-Atlas",
|
|
3753
|
-
save: async (data) => {
|
|
3754
|
-
const response = await fetch(`${apiUrl}/action/updateOne`, {
|
|
3755
|
-
method: "POST",
|
|
3756
|
-
headers: { "Content-Type": "application/json", "api-key": apiKey },
|
|
3757
|
-
body: JSON.stringify({
|
|
3758
|
-
dataSource: "Cluster0",
|
|
3759
|
-
database: "rgs_cloud",
|
|
3760
|
-
collection: "user_states",
|
|
3761
|
-
filter: { id: "global_state" },
|
|
3762
|
-
// Or specific user ID
|
|
3763
|
-
update: { $set: { data, updatedAt: Date.now() } },
|
|
3764
|
-
upsert: true
|
|
3765
|
-
})
|
|
3766
|
-
});
|
|
3767
|
-
return response.ok;
|
|
3768
|
-
}
|
|
3769
|
-
});
|
|
3770
|
-
var createFirestoreAdapter = (db, docPath) => ({
|
|
3771
|
-
name: "Firebase-Firestore",
|
|
3772
|
-
save: async (data) => {
|
|
3773
|
-
try {
|
|
3774
|
-
const isDev = !isProduction();
|
|
3775
|
-
const debugLog = (...args) => {
|
|
3776
|
-
if (isDev) console.debug(...args);
|
|
3777
|
-
};
|
|
3778
|
-
debugLog("[Mock] Firestore Syncing:", data);
|
|
3779
|
-
return true;
|
|
3780
|
-
} catch (e) {
|
|
3781
|
-
return false;
|
|
3782
|
-
}
|
|
3783
|
-
}
|
|
3784
|
-
});
|
|
3785
|
-
var createSqlRestAdapter = (endpoint, getAuthToken) => ({
|
|
3786
|
-
name: "SQL-REST-API",
|
|
3787
|
-
save: async (data) => {
|
|
3788
|
-
const authToken = getAuthToken();
|
|
3789
|
-
if (!authToken) {
|
|
3790
|
-
console.warn("[gstate] No auth token available for SQL-REST sync");
|
|
3791
|
-
return false;
|
|
3792
|
-
}
|
|
3793
|
-
const response = await fetch(endpoint, {
|
|
3794
|
-
method: "PATCH",
|
|
3795
|
-
headers: {
|
|
3796
|
-
"Content-Type": "application/json",
|
|
3797
|
-
// NOTE: In production, use HTTP-only cookies instead of Bearer tokens
|
|
3798
|
-
// This is provided as a template only - production should use secure auth
|
|
3799
|
-
"Authorization": `Bearer ${authToken}`
|
|
3800
|
-
},
|
|
3801
|
-
body: JSON.stringify(data),
|
|
3802
|
-
credentials: "same-origin"
|
|
3803
|
-
});
|
|
3804
|
-
return response.ok;
|
|
3805
|
-
}
|
|
3806
|
-
});
|
|
3807
|
-
|
|
3808
|
-
// plugins/index.ts
|
|
3809
|
-
var loggerPlugin = (options) => ({
|
|
3810
|
-
name: "gstate-logger",
|
|
3811
|
-
hooks: {
|
|
3812
|
-
onSet: ({ key, value, version }) => {
|
|
3813
|
-
const time = (/* @__PURE__ */ new Date()).toLocaleTimeString(), groupLabel = `[gstate] SET: ${key} (v${version}) @ ${time}`;
|
|
3814
|
-
if (options?.collapsed) console.groupCollapsed(groupLabel);
|
|
3815
|
-
else console.group(groupLabel);
|
|
3816
|
-
console.info("%c Value:", "color: #4CAF50; font-weight: bold;", value);
|
|
3817
|
-
console.groupEnd();
|
|
3818
|
-
},
|
|
3819
|
-
onRemove: ({ key }) => {
|
|
3820
|
-
console.warn(`[gstate] REMOVED: ${key}`);
|
|
3821
|
-
},
|
|
3822
|
-
onTransaction: ({ key }) => {
|
|
3823
|
-
if (key === "START") console.group("\u2500\u2500 TRANSACTION START \u2500\u2500");
|
|
3824
|
-
else console.groupEnd();
|
|
3825
|
-
}
|
|
3826
|
-
}
|
|
3827
|
-
});
|
|
3828
|
-
|
|
3829
|
-
// index.ts
|
|
3830
|
-
var gstate = (initialState, configOrNamespace) => {
|
|
3831
|
-
const config = typeof configOrNamespace === "string" ? { namespace: configOrNamespace } : configOrNamespace;
|
|
3832
|
-
const store = createStore(config);
|
|
3833
|
-
if (initialState) {
|
|
3834
|
-
Object.entries(initialState).forEach(([k, v]) => {
|
|
3835
|
-
if (store.get(k) === null) {
|
|
3836
|
-
store._setSilently(k, v);
|
|
3837
|
-
}
|
|
3838
|
-
});
|
|
3839
|
-
}
|
|
3840
|
-
const magic = (key) => useStore(key, store);
|
|
3841
|
-
if (typeof window !== "undefined" && isDevelopment()) {
|
|
3842
|
-
window.gstate = store;
|
|
3843
|
-
window.gState = store;
|
|
3844
|
-
window.rgs = store;
|
|
3845
|
-
}
|
|
3846
|
-
return Object.assign(magic, store);
|
|
3847
|
-
};
|
|
3848
|
-
var addAccessRule2 = (pattern, perms) => getStore()?.addAccessRule(pattern, perms);
|
|
3849
|
-
var hasPermission2 = (key, action, uid) => getStore()?.hasPermission(key, action, uid) ?? true;
|
|
3850
|
-
var recordConsent2 = (uid, p, g) => {
|
|
3851
|
-
const s = getStore();
|
|
3852
|
-
if (!s) throw new Error("[gstate] recordConsent failed: No store found. call initState() first.");
|
|
3853
|
-
return s.recordConsent(uid, p, g);
|
|
3854
|
-
};
|
|
3855
|
-
var hasConsent2 = (uid, p) => getStore()?.hasConsent(uid, p) ?? false;
|
|
3856
|
-
var getConsents2 = (uid) => getStore()?.getConsents(uid) ?? [];
|
|
3857
|
-
var revokeConsent2 = (uid, p) => getStore()?.revokeConsent(uid, p);
|
|
3858
|
-
var exportUserData2 = (uid) => {
|
|
3859
|
-
const s = getStore();
|
|
3860
|
-
if (!s) throw new Error("[gstate] exportUserData failed: No store found.");
|
|
3861
|
-
return s.exportUserData(uid);
|
|
3862
|
-
};
|
|
3863
|
-
var deleteUserData2 = (uid) => {
|
|
3864
|
-
const s = getStore();
|
|
3865
|
-
if (!s) throw new Error("[gstate] deleteUserData failed: No store found.");
|
|
3866
|
-
return s.deleteUserData(uid);
|
|
3867
|
-
};
|
|
3868
|
-
var clearAccessRules = () => {
|
|
3869
|
-
};
|
|
3870
|
-
var clearAllConsents = () => {
|
|
3871
|
-
};
|
|
3872
|
-
export {
|
|
3873
|
-
SyncEngine,
|
|
3874
|
-
addAccessRule2 as addAccessRule,
|
|
3875
|
-
analyticsPlugin,
|
|
3876
|
-
clearAccessRules,
|
|
3877
|
-
clearAllConsents,
|
|
3878
|
-
cloudSyncPlugin,
|
|
3879
|
-
createAsyncStore,
|
|
3880
|
-
createFirestoreAdapter,
|
|
3881
|
-
createMongoAdapter,
|
|
3882
|
-
createSqlRestAdapter,
|
|
3883
|
-
createStore,
|
|
3884
|
-
createSyncEngine,
|
|
3885
|
-
debugPlugin,
|
|
3886
|
-
deleteUserData2 as deleteUserData,
|
|
3887
|
-
deriveKeyFromPassword,
|
|
3888
|
-
destroyState,
|
|
3889
|
-
destroySync,
|
|
3890
|
-
devToolsPlugin,
|
|
3891
|
-
exportKey,
|
|
3892
|
-
exportUserData2 as exportUserData,
|
|
3893
|
-
generateEncryptionKey,
|
|
3894
|
-
generateSalt,
|
|
3895
|
-
getConsents2 as getConsents,
|
|
3896
|
-
getStore,
|
|
3897
|
-
gstate,
|
|
3898
|
-
guardPlugin,
|
|
3899
|
-
hasConsent2 as hasConsent,
|
|
3900
|
-
hasPermission2 as hasPermission,
|
|
3901
|
-
immerPlugin,
|
|
3902
|
-
importKey,
|
|
3903
|
-
indexedDBPlugin,
|
|
3904
|
-
initState,
|
|
3905
|
-
initSync,
|
|
3906
|
-
isCryptoAvailable,
|
|
3907
|
-
logAudit,
|
|
3908
|
-
loggerPlugin,
|
|
3909
|
-
recordConsent2 as recordConsent,
|
|
3910
|
-
revokeConsent2 as revokeConsent,
|
|
3911
|
-
sanitizeValue,
|
|
3912
|
-
schemaPlugin,
|
|
3913
|
-
setAuditLogger,
|
|
3914
|
-
snapshotPlugin,
|
|
3915
|
-
syncPlugin,
|
|
3916
|
-
triggerSync,
|
|
3917
|
-
undoRedoPlugin,
|
|
3918
|
-
useStore as useGState,
|
|
3919
|
-
useIsStoreReady,
|
|
3920
|
-
useStore as useSimpleState,
|
|
3921
|
-
useStore,
|
|
3922
|
-
useSyncStatus,
|
|
3923
|
-
useSyncedState,
|
|
3924
|
-
validateKey
|
|
3925
|
-
};
|
|
1
|
+
import{useMemo as e,useSyncExternalStore as t,useCallback as n,useDebugValue as r,useState as s,useEffect as o}from"react";var a=Symbol.for("immer-nothing"),i=Symbol.for("immer-draftable"),c=Symbol.for("immer-state"),l=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function u(e,...t){{const n=l[e],r=T(n)?n.apply(null,t):n;throw new Error(`[Immer] ${r}`)}}var d=Object,f=d.getPrototypeOf,y="constructor",p="prototype",h="configurable",g="enumerable",m="writable",_="value",S=e=>!!e&&!!e[c];function w(e){return!!e&&(k(e)||M(e)||!!e[i]||!!e[y]?.[i]||R(e)||j(e))}var b=d[p][y].toString(),v=new WeakMap;function k(e){if(!e||!P(e))return!1;const t=f(e);if(null===t||t===d[p])return!0;const n=d.hasOwnProperty.call(t,y)&&t[y];if(n===Object)return!0;if(!T(n))return!1;let r=v.get(n);return void 0===r&&(r=Function.toString.call(n),v.set(n,r)),r===b}function E(e,t,n=!0){if(0===C(e)){(n?Reflect.ownKeys(e):d.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,r)=>t(r,n,e))}function C(e){const t=e[c];return t?t.type_:M(e)?1:R(e)?2:j(e)?3:0}var O=(e,t,n=C(e))=>2===n?e.has(t):d[p].hasOwnProperty.call(e,t),D=(e,t,n=C(e))=>2===n?e.get(t):e[t],A=(e,t,n,r=C(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n};var M=Array.isArray,R=e=>e instanceof Map,j=e=>e instanceof Set,P=e=>"object"==typeof e,T=e=>"function"==typeof e,I=e=>"boolean"==typeof e;var z=e=>e.copy_||e.base_,V=e=>e.modified_?e.copy_:e.base_;function $(e,t){if(R(e))return new Map(e);if(j(e))return new Set(e);if(M(e))return Array[p].slice.call(e);const n=k(e);if(!0===t||"class_only"===t&&!n){const t=d.getOwnPropertyDescriptors(e);delete t[c];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const s=n[r],o=t[s];!1===o[m]&&(o[m]=!0,o[h]=!0),(o.get||o.set)&&(t[s]={[h]:!0,[m]:!0,[g]:o[g],[_]:e[s]})}return d.create(f(e),t)}{const t=f(e);if(null!==t&&n)return{...e};const r=d.create(t);return d.assign(r,e)}}function x(e,t=!1){return N(e)||S(e)||!w(e)||(C(e)>1&&d.defineProperties(e,{set:U,add:U,clear:U,delete:U}),d.freeze(e),t&&E(e,(e,t)=>{x(t,!0)},!1)),e}var U={[_]:function(){u(2)}};function N(e){return null===e||!P(e)||d.isFrozen(e)}var L="MapSet",F="Patches",K="ArrayMethods",J={};function B(e){const t=J[e];return t||u(0,e),t}var W,Q=e=>!!J[e],G=()=>W;function q(e,t){t&&(e.patchPlugin_=B(F),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function X(e){Z(e),e.drafts_.forEach(Y),e.drafts_=null}function Z(e){e===W&&(W=e.parent_)}var H=e=>W={drafts_:[],parent_:W,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Q(L)?B(L):void 0,arrayMethodsPlugin_:Q(K)?B(K):void 0};function Y(e){const t=e[c];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ee(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[c].modified_&&(X(t),u(4)),w(e)&&(e=te(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[c].base_,e,t)}else e=te(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&x(t,n)}(t,e,!0),X(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==a?e:void 0}function te(e,t){if(N(t))return t;const n=t[c];if(!n){return ie(t,e.handledSet_,e)}if(!re(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;){t.pop()(e)}ae(n,e)}return n.copy_}function ne(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var re=(e,t)=>e.scope_===t,se=[];function oe(e,t,n,r){const s=z(e),o=e.type_;if(void 0!==r){if(D(s,r,o)===t)return void A(s,r,n,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;E(s,(e,n)=>{if(S(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const a=e.draftLocations_.get(t)??se;for(const e of a)A(s,e,n,o)}function ae(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}ne(e)}}function ie(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||S(e)||t.has(e)||!w(e)||N(e)||(t.add(e),E(e,(r,s)=>{if(S(s)){const t=s[c];if(re(t,n)){const n=V(t);A(e,r,n,e.type_),ne(t)}}else w(s)&&ie(s,t,n)})),e}var ce={get(e,t){if(t===c)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const s=z(e);if(!O(s,t,e.type_))return function(e,t,n){const r=de(t,n);return r?_ in r?r[_]:r.get?.call(e.draft_):void 0}(e,s,t);const o=s[t];if(e.finalized_||!w(o))return o;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return o;if(o===ue(e.base_,t)){ye(e);const n=1===e.type_?+t:t,r=pe(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in z(e),ownKeys:e=>Reflect.ownKeys(z(e)),set(e,t,n){const r=de(z(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=ue(z(e),t),a=r?.[c];if(a&&a.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((s=n)===(o=r)?0!==s||1/s==1/o:s!=s&&o!=o)&&(void 0!==n||O(e.base_,t,e.type_)))return!0;ye(e),fe(e)}var s,o;return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(S(n)){const s=n[c];re(s,r)&&s.callbacks_.push(function(){ye(e);const r=V(s);oe(e,n,r,t)})}else w(n)&&e.callbacks_.push(function(){const s=z(e);3===e.type_?s.has(n)&&ie(n,r.handledSet_,r):D(s,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&ie(D(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(ye(e),void 0!==ue(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),fe(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=z(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[m]:!0,[h]:1!==e.type_||"length"!==t,[g]:r[g],[_]:n[t]}:r},defineProperty(){u(11)},getPrototypeOf:e=>f(e.base_),setPrototypeOf(){u(12)}},le={};for(let e in ce){let t=ce[e];le[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function ue(e,t){const n=e[c];return(n?z(n):e)[t]}function de(e,t){if(!(t in e))return;let n=f(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=f(n)}}function fe(e){e.modified_||(e.modified_=!0,e.parent_&&fe(e.parent_))}function ye(e){e.copy_||(e.assigned_=new Map,e.copy_=$(e.base_,e.scope_.immer_.useStrictShallowCopy_))}le.deleteProperty=function(e,t){return isNaN(parseInt(t))&&u(13),le.set.call(this,e,t,void 0)},le.set=function(e,t,n){return"length"!==t&&isNaN(parseInt(t))&&u(14),ce.set.call(this,e[0],t,n,e[0])};function pe(e,t,n,r){const[s,o]=R(t)?B(L).proxyMap_(t,n):j(t)?B(L).proxySet_(t,n):function(e,t){const n=M(e),r={type_:n?1:0,scope_:t?t.scope_:G(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let s=r,o=ce;n&&(s=[r],o=le);const{revoke:a,proxy:i}=Proxy.revocable(s,o);return r.draft_=i,r.revoke_=a,[i,r]}(t,n);return(n?.scope_??G()).drafts_.push(s),o.callbacks_=n?.callbacks_??[],o.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const s=t;if(!s||!re(s,r))return;r.mapSetPlugin_?.fixSetContents(s);const o=V(s);oe(e,s.draft_??s,o,n),ae(s,r)})}(n,o,r):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),s}function he(e){if(!w(e)||N(e))return e;const t=e[c];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=$(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=$(e,!0);return E(n,(e,t)=>{A(n,e,he(t))},r),t&&(t.finalized_=!1),n}var ge=(new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(T(e)&&!T(t)){const n=t;t=e;const r=this;return function(e=n,...s){return r.produce(e,e=>t.call(this,e,...s))}}let r;if(T(t)||u(6),void 0===n||T(n)||u(7),w(e)){const s=H(this),o=pe(s,e,void 0);let a=!0;try{r=t(o),a=!1}finally{a?X(s):Z(s)}return q(s,n),ee(r,s)}if(!e||!P(e)){if(r=t(e),void 0===r&&(r=e),r===a&&(r=void 0),this.autoFreeze_&&x(r,!0),n){const t=[],s=[];B(F).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:s}),n(t,s)}return r}u(1,e)},this.produceWithPatches=(e,t)=>{if(T(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},I(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),I(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),I(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){w(e)||u(8),S(e)&&(e=function(e){S(e)||u(10,e);return he(e)}(e));const t=H(this),n=pe(t,e,void 0);return n[c].isManual_=!0,Z(t),n}finishDraft(e,t){const n=e&&e[c];n&&n.isManual_||u(9);const{scope_:r}=n;return q(r,t),ee(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=B(F).applyPatches_;return S(e)?r(e,t):this.produce(e,e=>r(e,t))}}).produce,me=(e,t)=>{const n=Date.now();if(/\(\.*\+\?\)\+/.test(e)||/\(\.*\?\)\*/.test(e))return!1;if(e.length>500)return!1;try{const n=new RegExp(e).test(t);Date.now();return n}catch{return!1}},_e=()=>{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)try{return crypto.randomUUID()}catch{}throw new Error("Cryptographically secure random UUID generation is required but crypto.randomUUID is unavailable. Please use a browser or environment with Web Crypto API support.")},Se="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.generateKey,we=async(e,t,n=6e5)=>{if(!Se)throw new Error("Web Crypto API not available");const r=await crypto.subtle.importKey("raw",(new TextEncoder).encode(e),"PBKDF2",!1,["deriveKey"]);return{key:await crypto.subtle.deriveKey({name:"PBKDF2",salt:new Uint8Array(t),iterations:n,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),iv:crypto.getRandomValues(new Uint8Array(12))}},be=(e=32)=>crypto.getRandomValues(new Uint8Array(e)),ve=async()=>{if(!Se)throw new Error("Web Crypto API not available");return{key:await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),iv:crypto.getRandomValues(new Uint8Array(12))}},ke=async e=>{const t=await crypto.subtle.exportKey("raw",e.key);return{key:btoa(String.fromCharCode(...new Uint8Array(t))),iv:btoa(String.fromCharCode(...e.iv))}},Ee=async(e,t)=>{const n=Uint8Array.from(atob(e),e=>e.charCodeAt(0)),r=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return{key:await crypto.subtle.importKey("raw",n,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),iv:r}},Ce=async(e,t)=>{const n=(new TextEncoder).encode(JSON.stringify(e)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t.iv},t.key,n),s=new Uint8Array(t.iv.length+r.byteLength);return s.set(t.iv),s.set(new Uint8Array(r),t.iv.length),btoa(String.fromCharCode(...s))},Oe=async(e,t)=>{const n=Uint8Array.from(atob(e),e=>e.charCodeAt(0)),r=n.slice(0,12),s=n.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},t.key,s);return JSON.parse((new TextDecoder).decode(o))},De=null,Ae=e=>{De=e},Me=e=>{De&&De(e)},Re=(e,t,n)=>{e.set(t instanceof RegExp?t.source:t,n)},je=(e,t,n,r)=>{if(0===e.size)return!0;for(const[s,o]of e){let e;if(e="function"==typeof s?s(t,r):me(s,t),e)return o.includes(n)||o.includes("admin")}return!1},Pe=e=>{if("string"==typeof e){let t=e.replace(/&#[xX]?[0-9a-fA-F]+;?/g,e=>{const t=e.match(/&#x([0-9a-fA-F]+);?/i);if(t&&t[1])return String.fromCharCode(parseInt(t[1],16));const n=e.match(/&#([0-9]+);?/);return n&&n[1]?String.fromCharCode(parseInt(n[1],10)):e});try{t=decodeURIComponent(t)}catch{}return t.replace(/\b(javascript|vbscript|data:text\/html|about:blank|chrome:)/gi,"[SEC-REMOVED]").replace(/<script\b[^>]*>[\s\S]*?<\s*\/\s*script\b[^>]*>/gi,"[SEC-REMOVED]").replace(/on\w+\s*=/gi,"[SEC-REMOVED]=").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"[SEC-REMOVED]").replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,"[SEC-REMOVED]").replace(/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi,"[SEC-REMOVED]").replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi,"[SEC-REMOVED]").replace(/<form\b[^<]*(?:(?!<\/form>)<[^<]*)*<\/form>/gi,"[SEC-REMOVED]").replace(/<base\b[^<]*(?:(?!<\/base>)<[^<]*)*<\/base>/gi,"[SEC-REMOVED]").replace(/<link\b[^<]*(?:(?!<\/link>)<[^<]*)*<\/link>/gi,"[SEC-REMOVED]").replace(/<meta\b[^<]*(?:(?!<\/meta>)<[^<]*)*<\/meta>/gi,"[SEC-REMOVED]").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi,"[SEC-REMOVED]")}if(e&&"object"==typeof e&&!Array.isArray(e)){if(Object.getPrototypeOf(e)===Object.prototype){const t={};for(const[n,r]of Object.entries(e))t[n]=Pe(r);return t}return e}return Array.isArray(e)?e.map(e=>Pe(e)):e},Te=e=>/^([a-zA-Z0-9_.-][a-zA-Z0-9_.-]*)$/.test(e)&&e.length<=256&&e.length>0,Ie=(e,t,n,r)=>{const s={id:_e(),purpose:n,granted:r,timestamp:Date.now()},o=e.get(t)||[];return o.push(s),e.set(t,o),Me({timestamp:Date.now(),action:"set",key:`consent:${n}`,userId:t,success:!0}),s},ze=e=>{if(null===e||"object"!=typeof e)return e;if("function"==typeof structuredClone)try{return structuredClone(e)}catch(e){}const t=new WeakMap,n=e=>{if(null===e||"object"!=typeof e)return e;if("function"==typeof e)return e;if(t.has(e))return t.get(e);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const r=new Map;return t.set(e,r),e.forEach((e,t)=>r.set(n(t),n(e))),r}if(e instanceof Set){const r=new Set;return t.set(e,r),e.forEach(e=>r.add(n(e))),r}const r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));t.set(e,r);const s=[...Object.keys(e),...Object.getOwnPropertySymbols(e)];for(const t of s)r[t]=n(e[t]);return r};return n(e)},Ve=(e,t)=>{if(e===t)return!0;if(null===e||null===t)return e===t;if("object"!=typeof e||"object"!=typeof t)return e===t;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Ve(e[n],t[n]))return!1;return!0}const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r=0;r<n.length;r++){const s=n[r];if(!(s in t)||!Ve(e[s],t[s]))return!1}return!0},$e=e=>`${e}_`,xe=class{store;config;pendingQueue=new Map;remoteVersions=new Map;syncTimer=null;onlineStatusListeners=new Set;syncStateListeners=new Set;_isOnline=!0;_isSyncing=!1;constructor(e,t){this.store=e,this.config={endpoint:t.endpoint,authToken:t.authToken||"",strategy:t.strategy||"last-write-wins",autoSyncInterval:t.autoSyncInterval??3e4,syncOnReconnect:t.syncOnReconnect??!0,debounceTime:t.debounceTime??1e3,fetch:t.fetch||fetch,onSync:t.onSync||(()=>{}),onConflict:t.onConflict||(()=>({action:"accept-local"})),maxRetries:t.maxRetries??3},this._isOnline="undefined"==typeof navigator||navigator.onLine,this._setupOnlineListener(),this._setupStoreListener(),this.config.autoSyncInterval>0&&this._startAutoSync()}_getAuthToken(){const e=this.config.authToken;return"function"==typeof e?e()||"":e||""}_setupOnlineListener(){"undefined"!=typeof window&&(window.addEventListener("online",()=>{this._isOnline=!0,this._notifyOnlineChange(!0),this.config.syncOnReconnect&&this.sync()}),window.addEventListener("offline",()=>{this._isOnline=!1,this._notifyOnlineChange(!1)}))}_setupStoreListener(){this.store._subscribe(()=>{})}_startAutoSync(){setInterval(()=>{this._isOnline&&!this._isSyncing&&this.pendingQueue.size>0&&this.sync()},this.config.autoSyncInterval)}_notifyOnlineChange(e){this.onlineStatusListeners.forEach(t=>t(e)),this._notifyStateChange()}_notifyStateChange(){const e=this.getState();this.syncStateListeners.forEach(t=>t(e))}queueChange(e,t){const n=this.store._getVersion(e)||1;this.pendingQueue.set(e,{key:e,value:ze(t),timestamp:Date.now(),version:n}),this._notifyStateChange(),this.syncTimer&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this._isOnline&&this.sync()},this.config.debounceTime)}async sync(){if(this._isSyncing)return{success:!1,syncedKeys:[],conflicts:[],errors:["Sync already in progress"],timestamp:Date.now(),duration:0};this._isSyncing=!0,this._notifyStateChange();const e=Date.now(),t=[],n=[],r=[];try{const s=Array.from(this.pendingQueue.values());if(0===s.length)return this._isSyncing=!1,this._notifyStateChange(),{success:!0,syncedKeys:[],conflicts:[],errors:[],timestamp:Date.now(),duration:Date.now()-e};await this._fetchRemoteVersions(s.map(e=>e.key));for(const e of s)try{const r=this.remoteVersions.get(e.key);if(r)if(r.version>=e.version){const s={key:e.key,localValue:e.value,remoteValue:r.value,localVersion:e.version,remoteVersion:r.version,timestamp:e.timestamp};n.push(s);const o=this.config.onConflict(s);await this._resolveConflict(e,r,o),t.push(e.key),this.pendingQueue.delete(e.key)}else await this._pushChange(e),t.push(e.key),this.pendingQueue.delete(e.key);else await this._pushChange(e),t.push(e.key),this.pendingQueue.delete(e.key)}catch(t){r.push(`Failed to sync "${e.key}": ${t}`)}const o={success:0===r.length,syncedKeys:t,conflicts:n,errors:r,timestamp:Date.now(),duration:Date.now()-e};return this.config.onSync(o),o}catch(s){const o=`Sync failed: ${s}`;return r.push(o),{success:!1,syncedKeys:t,conflicts:n,errors:r,timestamp:Date.now(),duration:Date.now()-e}}finally{this._isSyncing=!1,this._notifyStateChange()}}async _fetchRemoteVersions(e){try{const t=this._getAuthToken(),n=await this.config.fetch(`${this.config.endpoint}/versions`,{method:"POST",headers:{"Content-Type":"application/json",...t&&{Authorization:`Bearer ${t}`}},body:JSON.stringify({keys:e})});if(n.ok){const e=await n.json();if(e.versions)for(const[t,n]of Object.entries(e.versions))this.remoteVersions.set(t,n)}}catch(e){}}async _pushChange(e){let t=0;for(;t<this.config.maxRetries;)try{const n=this._getAuthToken(),r=await this.config.fetch(`${this.config.endpoint}/sync`,{method:"POST",headers:{"Content-Type":"application/json",...n&&{Authorization:`Bearer ${n}`}},body:JSON.stringify({key:e.key,value:e.value,version:e.version,timestamp:e.timestamp})});if(r.ok){const t=await r.json();return void(t.version&&this.remoteVersions.set(e.key,{version:t.version,timestamp:t.timestamp||Date.now(),value:e.value}))}t++}catch(e){if(t++,t>=this.config.maxRetries)throw e}}async _resolveConflict(e,t,n){switch(n.action){case"accept-local":await this._pushChange({...e,version:t.version+1,timestamp:Date.now()});break;case"accept-remote":this.store.set(e.key,t.value);break;case"merge":this.store.set(e.key,n.value),await this._pushChange({key:e.key,value:n.value,version:Math.max(e.version,t.version)+1,timestamp:Date.now()})}}getState(){return{isOnline:this._isOnline,isSyncing:this._isSyncing,lastSyncTimestamp:null,pendingChanges:this.pendingQueue.size,conflicts:0}}onOnlineChange(e){return this.onlineStatusListeners.add(e),()=>this.onlineStatusListeners.delete(e)}onStateChange(e){return this.syncStateListeners.add(e),()=>this.syncStateListeners.delete(e)}async flush(){return this.sync()}destroy(){this.syncTimer&&clearTimeout(this.syncTimer),this.pendingQueue.clear(),this.onlineStatusListeners.clear(),this.syncStateListeners.clear()}},Ue=(e,t)=>new xe(e,t),Ne=()=>{try{0;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};return void 0!==e.__DEV__&&!1===e.__DEV__}catch{return!1}},Le=()=>"undefined"!=typeof window?window.localStorage:null,Fe=e=>{const t=new Map,n=new Map,r=new Map,s=new Set,o=new Map,a=new Set,i=new Map,c=new Map,l=new Map,u=new Map,d=new Map,f=new Map,y=new Map,p=new Map,h=e?.namespace||"gstate",g=e?.silent??!1,m=e?.debounceTime??150,_=e?.version??0,S=e?.storage||Le(),w=e?.onError,b=e?.maxObjectSize??0,v=e?.maxTotalSize??0,k=e?.encryptionKey??null,E=e?.validateInput??!0,C=e?.auditEnabled??!0,O=e?.userId,D=e?.immer??!0,A=e?.persistByDefault??e?.persistence??e?.persist??!1;e?.accessRules&&e.accessRules.forEach(e=>Re(y,e.pattern,e.permissions));let M,R=!1,j=!1,P=!1,T=0,I=null,z=null;const V=new Promise(e=>{M=e}),$=()=>({store:t,versions:n,sizes:r,totalSize:T,storage:S,config:e||{},diskQueue:d,encryptionKey:k,audit:F,onError:w,silent:g,debounceTime:m,currentVersion:_}),U=()=>({plugins:u,onError:w,silent:g}),N=e=>{if(null==e)return 0;const t=typeof e;if("boolean"===t)return 4;if("number"===t)return 8;if("string"===t)return 2*e.length;if("object"!==t)return 0;let n=0;const r=[e],s=new WeakSet;for(;r.length>0;){const e=r.pop();if("boolean"==typeof e)n+=4;else if("number"==typeof e)n+=8;else if("string"==typeof e)n+=2*e.length;else if("object"==typeof e&&null!==e){const t=e;if(s.has(t))continue;if(s.add(t),Array.isArray(t))for(let e=0;e<t.length;e++)r.push(t[e]);else for(const e of Object.keys(t))n+=2*e.length,r.push(t[e])}}return n},L=(e,t)=>{((e,t,n)=>{if(0!==e.plugins.size)for(const r of e.plugins.values()){const s=r.hooks?.[t];if(s)try{s(n)}catch(s){const o=s instanceof Error?s:new Error(String(s));e.onError?e.onError(o,{operation:`plugin:${r.name}:${t}`,key:n.key}):e.silent}}})(U(),e,t)},F=(e,t,n,r)=>{C&&null!==De&&Me&&Me({timestamp:Date.now(),action:e,key:t,userId:O,success:n,error:r})},K=e=>{const t=c.get(e);if(!t)return;const r=new Set,s=t.selector(e=>(r.add(e),c.has(e)?c.get(e).lastValue:Q.get(e)));t.deps.forEach(t=>{if(!r.has(t)){const n=l.get(t);n&&(n.delete(e),0===n.size&&l.delete(t))}}),r.forEach(n=>{t.deps.has(n)||(l.has(n)||l.set(n,new Set),l.get(n).add(e))}),t.deps=r,Ve(t.lastValue,s)||(t.lastValue=D&&null!==s&&"object"==typeof s?x(ze(s),!0):s,n.set(e,(n.get(e)||0)+1),J(e))},J=e=>{if(e){if(l.has(e)){const t=l.get(e);for(const e of t)K(e)}const t=i.get(e);if(t){const n=Q.get(e);for(const r of t)try{r(n)}catch(t){const n=t instanceof Error?t:new Error(String(t));w&&w(n,{operation:"watcher",key:e})}}const n=o.get(e);if(n)for(const t of n)try{t()}catch(t){const n=t instanceof Error?t:new Error(String(t));w&&w(n,{operation:"keyListener",key:e})}}if(R)j=!0;else for(const e of s)try{e()}catch(e){const t=e instanceof Error?e:new Error(String(e));w&&w(t,{operation:"listener"})}},B=async()=>{(async e=>{if(!e.storage)return;const{store:t,config:n,diskQueue:r,storage:s,encryptionKey:o,audit:a,onError:i,silent:c,currentVersion:l}=e,u=$e(n.namespace||"gstate");try{const e={};let r;t.forEach((t,n)=>{e[n]=t});const o=n?.encoded;r=o?btoa(JSON.stringify(e)):JSON.stringify(e),s.setItem(u.replace("_",""),JSON.stringify({v:1,t:Date.now(),e:null,d:r,_sys_v:l,_b64:!!o||void 0})),a("set","FULL_STATE",!0)}catch(e){const t=e instanceof Error?e:new Error(String(e));i&&i(t,{operation:"persist",key:"FULL_STATE"})}const d=Array.from(r.entries());r.clear();for(const[t,n]of d)try{if(!t||!/^[a-zA-Z0-9_.-]+$/.test(t)||t.length>256)continue;let r=n.value;const i=n.options.encoded||n.options.encrypted||n.options.secure;if(n.options.encrypted){if(!o)throw new Error(`Encryption key missing for "${t}"`);r=await Ce(n.value,o)}else i?r=btoa(JSON.stringify(n.value)):"object"==typeof n.value&&null!==n.value&&(r=JSON.stringify(n.value));s.setItem(`${u}${t}`,JSON.stringify({v:e.versions.get(t)||1,t:Date.now(),e:n.options.ttl?Date.now()+n.options.ttl:null,d:r,_sys_v:l,_enc:!!n.options.encrypted||void 0,_b64:!(!n.options.encoded&&!n.options.secure)||void 0})),a("set",t,!0)}catch(e){const n=e instanceof Error?e:new Error(String(e));i&&i(n,{operation:"persist",key:t})}})($())},W={},Q={_setSilently:(e,s)=>{const o=r.get(e)||0,a=D&&null!==s&&"object"==typeof s?x(ze(s),!0):s,i=(b>0||v>0)&&!Ne()?N(a):0;T=T-o+i,r.set(e,i),t.set(e,a),n.set(e,(n.get(e)||0)+1),z=null},_registerMethod:(e,t,n)=>{const r=e=>"__proto__"===e||"constructor"===e||"prototype"===e;r(e)||r(t)||(W[e]||(W[e]={}),W[e][t]=n)},set:(s,o,a={})=>{const i=t.get(s),c=D&&"function"==typeof o?ge(i,o):o;if(E&&!Te(s))return!1;if(!je(y,s,"write",O))return F("set",s,!1,"RBAC Denied"),!1;const l=E?Pe(c):c,u=r.get(s)||0;L("onBeforeSet",{key:s,value:l,store:Q,version:n.get(s)||0});const f=D&&null!==l&&"object"==typeof l?x(ze(l),!0):l;if(!Ve(i,f)){const o=(b>0||v>0)&&!Ne()?N(f):0;if(b>0&&o>b){const e=new Error(`Object size (${o} bytes) exceeds maxObjectSize (${b} bytes)`);w&&w(e,{operation:"set",key:s})}if(v>0){const e=T-u+o;if(e>v){const t=new Error(`Total store size (${e} bytes) exceeds limit (${v} bytes)`);w&&w(t,{operation:"set"})}}T=T-u+o,r.set(s,o),t.set(s,f),n.set(s,(n.get(s)||0)+1),z=null;const i=a.persist??A;return i&&(d.set(s,{value:f,options:{...a,persist:i,encoded:a.encoded||e?.encoded}}),I&&clearTimeout(I),I=setTimeout(B,m)),L("onSet",{key:s,value:f,store:Q,version:n.get(s)}),F("set",s,!0),J(s),!0}return!1},get:e=>{if(!je(y,e,"read",O))return F("get",e,!1,"RBAC Denied"),null;const n=t.get(e);return L("onGet",{store:Q,key:e,value:n}),F("get",e,!0),n},compute:(e,t)=>{try{return c.has(e)||(c.set(e,{selector:t,lastValue:null,deps:new Set}),K(e)),c.get(e).lastValue}catch(t){const n=t instanceof Error?t:new Error(String(t));return w&&w(n,{operation:"compute",key:e}),null}},watch:(e,t)=>{i.has(e)||i.set(e,new Set);const n=i.get(e);return n.add(t),()=>{n.delete(t),0===n.size&&i.delete(e)}},remove:e=>{if(!je(y,e,"delete",O))return F("delete",e,!1,"RBAC Denied"),!1;const s=t.get(e),o=t.delete(e);return o&&(T-=r.get(e)||0,r.delete(e),L("onRemove",{store:Q,key:e,value:s}),z=null),n.set(e,(n.get(e)||0)+1),S&&S.removeItem(`${h}_${e}`),F("delete",e,!0),J(e),o},delete:e=>Q.remove(e),deleteAll:()=>{if(Array.from(t.keys()).forEach(e=>Q.remove(e)),S){const e=h+"_";for(let t=0;t<(S.length||0);t++){const n=S.key(t);n?.startsWith(e)&&(S.removeItem(n),t--)}}return T=0,r.clear(),z=null,!0},list:()=>Object.fromEntries(t.entries()),use:e=>{a.add(e)},transaction:e=>{R=!0,L("onTransaction",{store:Q,key:"START"});try{e()}finally{R=!1,L("onTransaction",{store:Q,key:"END"}),j&&(j=!1,J())}},destroy:()=>{I&&(clearTimeout(I),I=null),d.clear(),"undefined"!=typeof window&&window.removeEventListener("beforeunload",G),L("onDestroy",{store:Q}),s.clear(),o.clear(),i.clear(),c.clear(),l.clear(),u.clear(),t.clear(),r.clear(),T=0,y.clear(),p.clear(),n.clear(),f.clear(),a.clear()},_addPlugin:e=>{((e,t,n)=>{try{e.plugins.set(t.name,t),t.hooks?.onInstall?.({store:n})}catch(n){const r=n instanceof Error?n:new Error(String(n));e.onError?e.onError(r,{operation:"plugin:install",key:t.name}):e.silent}})(U(),e,Q)},_removePlugin:e=>{u.delete(e)},_subscribe:(e,t)=>{if(t){o.has(t)||o.set(t,new Set);const n=o.get(t);return n.add(e),()=>{n.delete(e),0===n.size&&o.delete(t)}}return s.add(e),()=>s.delete(e)},_getVersion:e=>n.get(e)??0,addAccessRule:(e,t)=>Re(y,e,t),hasPermission:(e,t,n)=>je(y,e,t,n),recordConsent:(e,t,n)=>Ie(p,e,t,n),hasConsent:(e,t)=>((e,t,n)=>{const r=e.get(t);if(!r)return!1;for(let e=r.length-1;e>=0;e--){const t=r[e];if(t&&t.purpose===n)return t.granted}return!1})(p,e,t),getConsents:e=>((e,t)=>e.get(t)||[])(p,e),revokeConsent:(e,t)=>((e,t,n)=>Ie(e,t,n,!1))(p,e,t),exportUserData:e=>((e,t)=>({userId:t,exportedAt:Date.now(),consents:e.get(t)||[]}))(p,e),deleteUserData:e=>((e,t)=>{const n=e.get(t)?.length||0;return e.delete(t),{success:!0,deletedConsents:n}})(p,e),getSnapshot:()=>(z||(z=Object.fromEntries(t.entries())),z),get plugins(){return W},get isReady(){return P},get namespace(){return h},get userId(){return O},whenReady:()=>V};["addAccessRule","recordConsent","hasConsent","getConsents","revokeConsent","exportUserData","deleteUserData"].forEach(e=>{const t=Q[e];t&&Q._registerMethod("security",e,t)});const G=()=>{d.size>0&&B()};"undefined"!=typeof window&&window.addEventListener("beforeunload",G),S?(async(e,t,n)=>{const{storage:r,config:s,encryptionKey:o,audit:a,onError:i,silent:c,currentVersion:l,store:u,sizes:d,versions:f}=e,y=$e(s.namespace||"gstate"),p=s.immer??!0;if(r)try{const c={};let h=0;for(let e=0;e<(r.length||0);e++){const t=r.key(e);if(!t||!t.startsWith(y))continue;const n=r.getItem(t);if(n)try{const s=JSON.parse(n),i=t.substring(y.length);if(h=Math.max(h,void 0!==s._sys_v?s._sys_v:s.v||0),s.e&&Date.now()>s.e){r.removeItem(t),e--;continue}let l=s.d;if(s._enc&&o)l=await Oe(l,o);else if("string"==typeof l)if(s._b64)try{l=JSON.parse(atob(l))}catch(e){}else if(l.startsWith("{")||l.startsWith("["))try{l=JSON.parse(l)}catch(e){}c[i]=l,a("hydrate",i,!0)}catch(e){a("hydrate",t,!1,String(e));const n=e instanceof Error?e:new Error(String(e));i&&i(n,{operation:"hydration",key:t})}}const g=h<l&&s.migrate?s.migrate(c,h):c;Object.entries(g).forEach(([n,r])=>{const s=p&&null!==r&&"object"==typeof r?x(ze(r),!0):r,o=t(s),a=d.get(n)||0;e.totalSize=e.totalSize-a+o,d.set(n,o),u.set(n,s),f.set(n,1)}),n()}catch(e){const t=e instanceof Error?e:new Error(String(e));i&&i(t,{operation:"hydration"})}})($(),e=>(b>0||v>0)&&!Ne()?N(e):0,()=>{P=!0,z=null,M(),J()}).then(()=>{}):(P=!0,M());let q=null;return e?.sync&&(q=new xe(Q,e.sync),Q._registerMethod("sync","flush",()=>q?.flush()),Q._registerMethod("sync","getState",()=>q?.getState()),Q._registerMethod("sync","onStateChange",e=>q?.onStateChange(e))),Q},Ke=null,Je=e=>{const t=Fe(e);return Ke=t,t},Be=()=>{Ke&&(Ke.destroy(),Ke=null)},We=n=>{const r=n||Ke,s=e(()=>e=>r?r._subscribe(e):()=>{},[r]);return t(s,()=>!!r&&r.isReady,()=>!0)},Qe=()=>Ke;function Ge(s,o){const a=e(()=>o||Ke,[o]),i=e(()=>{const e=()=>{},t=()=>!1,n=()=>null;return{set:t,get:n,remove:t,delete:t,deleteAll:t,list:()=>({}),compute:n,watch:()=>()=>{},use:e,transaction:e,destroy:e,_subscribe:()=>()=>{},_setSilently:e,_registerMethod:e,_addPlugin:e,_removePlugin:e,_getVersion:()=>0,get isReady(){return!1},whenReady:()=>Promise.resolve(),get plugins(){return{}},getSnapshot:()=>({}),get namespace(){return"ghost"},get userId(){}}},[]),c=a||i,l="function"==typeof s,u=l?null:s,d=l?s:null,f=n(e=>l?c._subscribe(e):c._subscribe(e,u),[c,l,u]),y=n(()=>l?d(c.getSnapshot()):c.get(u)??void 0,[c,l,u,d]),p=n(()=>{if(l)try{return d({})}catch{return}},[d,l]),h=t(f,y,p),g=n((e,t)=>l?(Ne(),!1):c.set(u,e,t),[c,l,u]);return r(h,e=>l?`Selector: ${JSON.stringify(e)}`:`${u}: ${JSON.stringify(e)}`),l?h:[h,g]}var qe=new Map,Xe=(e,t)=>{const n=e.namespace;if(qe.has(n))return qe.get(n);const r=new xe(e,t);return qe.set(n,r),r},Ze=e=>{const t=qe.get(e);t&&(t.destroy(),qe.delete(e))};function He(e,t){const r=t||Ke,a=r?.namespace||"default",i=qe.get(a),c=Ge(e,r),l=c[0],u=c[1],[d,f]=s(()=>i?.getState()||{isOnline:!0,isSyncing:!1,lastSyncTimestamp:null,pendingChanges:0,conflicts:0});o(()=>{if(!i)return;return i.onStateChange(f)},[i]);return[l,n((t,n)=>{const s=u(t,n);if(s&&i){const t=r?.get(e);i.queueChange(e,t)}return s},[u,i,e,r]),d]}var Ye=()=>{const[e,t]=s({isOnline:!0,isSyncing:!1,lastSyncTimestamp:null,pendingChanges:0,conflicts:0});return o(()=>{const e=()=>{let e=!0,n=!1,r=0,s=0;qe.forEach(t=>{const o=t.getState();e=e&&o.isOnline,n=n||o.isSyncing,r+=o.pendingChanges,s+=o.conflicts}),t({isOnline:e,isSyncing:n,lastSyncTimestamp:null,pendingChanges:r,conflicts:s})};e();const n=Array.from(qe.values()).map(t=>t.onStateChange(e));return()=>n.forEach(e=>e())},[]),e},et=async e=>{const t=e||Ke?.namespace;if(!t)return;const n=qe.get(t);n&&await n.flush()},tt=(e,t)=>{const n=t?.key||"async_data",r=t?.store||Fe({namespace:`async_${n}`,silent:!0});null==r.get(n)&&r.set(n,{data:null,loading:!1,error:null,updatedAt:null});return Object.assign(r,{execute:async()=>{const s=r.get(n);r.set(n,{...s||{data:null,loading:!1,error:null,updatedAt:null},loading:!0,error:null}),"whenReady"in r&&!r.isReady&&await r.whenReady();try{const s=await e(),o=r.get(n);r.set(n,{...o||{data:null,loading:!1,error:null,updatedAt:null},data:s,loading:!1,updatedAt:Date.now()},{persist:t?.persist})}catch(e){const t=r.get(n);r.set(n,{...t||{data:null,loading:!1,error:null,updatedAt:null},error:e instanceof Error?e:new Error(String(e)),loading:!1})}}})},nt=()=>({name:"gstate-immer",hooks:{onInstall:({store:e})=>{e._registerMethod("immer","setWithProduce",(t,n)=>e.set(t,n))}}}),rt=e=>{let t=[],n=-1,r=!1;const s=e?.limit||50;return{name:"gstate-undo-redo",hooks:{onInstall:({store:e})=>{t.push(e.list()),n=0,e._registerMethod("undoRedo","undo",()=>{if(n>0){r=!0,n--;const s=t[n];return!!s&&(Object.entries(s).forEach(([t,n])=>{e._setSilently(t,n)}),r=!1,!0)}return!1}),e._registerMethod("undoRedo","redo",()=>{if(n<t.length-1){r=!0,n++;const s=t[n];return!!s&&(Object.entries(s).forEach(([t,n])=>{e._setSilently(t,n)}),r=!1,!0)}return!1}),e._registerMethod("undoRedo","canUndo",()=>n>0),e._registerMethod("undoRedo","canRedo",()=>n<t.length-1)},onSet:({store:e})=>{r||(n<t.length-1&&(t=t.slice(0,n+1)),t.push(e.list()),t.length>s?t.shift():n++)}}}},st=e=>({name:"gstate-schema",hooks:{onSet:({key:t,value:n})=>{if(!t)return;const r=e[t];if(r){const e=r(n);if(!0!==e)throw new Error(`[Schema Error] Validation failed for key "${t}": ${!1===e?"Invalid type":e}`)}}}}),ot=e=>{const t=globalThis.__REDUX_DEVTOOLS_EXTENSION__;if(!t?.connect)return{name:"gstate-devtools-noop",hooks:{}};let n=null;return{name:"gstate-devtools",hooks:{onInstall:({store:r})=>{n=t.connect({name:e?.name||"Magnetar Store"}),n.init(r.list())},onSet:({key:e,store:t})=>{e&&n&&n.send(`SET_${e.toUpperCase()}`,t.list())},onRemove:({key:e,store:t})=>{e&&n&&n.send(`REMOVE_${e.toUpperCase()}`,t.list())}}}},at=()=>{const e=new Map;return{name:"gstate-snapshot",hooks:{onInstall:({store:t})=>{t._registerMethod("snapshot","takeSnapshot",n=>{e.set(n,t.list())}),t._registerMethod("snapshot","restoreSnapshot",n=>{const r=e.get(n);return!!r&&(t.transaction(()=>{Object.entries(r).forEach(([e,n])=>{t.set(e,n)})}),!0)}),t._registerMethod("snapshot","listSnapshots",()=>Array.from(e.keys())),t._registerMethod("snapshot","deleteSnapshot",t=>e.delete(t)),t._registerMethod("snapshot","clearSnapshots",()=>e.clear())}}}},it=e=>({name:"gstate-guard",hooks:{onBeforeSet:({key:t,value:n,store:r})=>{if(!t)return;const s=e[t];s&&s(n)}}}),ct=e=>({name:"gstate-analytics",hooks:{onSet:({key:t,value:n})=>{t&&(e.keys&&!e.keys.includes(t)||e.provider({key:t,value:n,action:"SET"}))},onRemove:({key:t})=>{t&&(e.keys&&!e.keys.includes(t)||e.provider({key:t,value:null,action:"REMOVE"}))}}}),lt=e=>{const t=new BroadcastChannel(e?.channelName||"gstate_sync");let n=!1;return{name:"gstate-sync",hooks:{onInstall:({store:e})=>{t.onmessage=t=>{const{key:r,value:s,action:o}=t.data;r&&(n=!0,"REMOVE"===o?e.remove(r):e.set(r,s),n=!1)}},onSet:({key:e,value:r})=>{e&&!n&&t.postMessage({key:e,value:r,action:"SET"})},onRemove:({key:e})=>{e&&!n&&t.postMessage({key:e,action:"REMOVE"})},onDestroy:()=>{t.close()}}}},ut=()=>{if(Ne())return{name:"gstate-debug-noop",hooks:{}};Ne();return{name:"gstate-debug",hooks:{onInstall:({store:e})=>{"undefined"!=typeof window&&(window.gstate={list:()=>e.list(),get:t=>{const n=e.get(t);return n},set:(t,n)=>{const r=e.set(t,n);return JSON.stringify(n),r},watch:(t,n)=>e.watch(t,n),info:()=>{const t={namespace:e.namespace,isReady:e.isReady,keys:Object.keys(e.list()),size:Object.keys(e.list()).length};return t},banner:()=>{}})},onDestroy:()=>{"undefined"!=typeof window&&delete window.gstate}}}},dt=(e={})=>{const t=e.dbName||"rgs-db",n=e.storeName||"states",r=e.version||1;let s=null;const o=()=>new Promise((e,o)=>{if(s)return e(s);const a=indexedDB.open(t,r);a.onerror=()=>o(a.error),a.onsuccess=()=>{s=a.result,e(s)},a.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(n)||t.createObjectStore(n)}}),a=async e=>{const t=await o();return new Promise((r,s)=>{const o=t.transaction(n,"readonly").objectStore(n).get(e);o.onsuccess=()=>r(o.result),o.onerror=()=>s(o.error)})};return{name:"indexedDB",hooks:{onInstall:({store:e})=>{e._registerMethod("indexedDB","clear",async()=>{(await o()).transaction(n,"readwrite").objectStore(n).clear()})},onInit:async({store:e})=>{const t=(await o()).transaction(n,"readonly").objectStore(n).getAllKeys();t.onsuccess=async()=>{const n=t.result,r=e.namespace+"_";for(const t of n)if(t.startsWith(r)){const n=await a(t);if(n){const s=t.substring(r.length);e._setSilently(s,n.d)}}}},onSet:async({key:e,value:t,store:r})=>{if(!e)return;const s=r.namespace+"_",a={d:t,t:Date.now(),v:r._getVersion?.(e)||1};await(async(e,t)=>{const r=await o();return new Promise((s,o)=>{const a=r.transaction(n,"readwrite").objectStore(n).put(t,e);a.onsuccess=()=>s(),a.onerror=()=>o(a.error)})})(`${s}${e}`,a)},onRemove:async({key:e,store:t})=>{if(!e)return;const r=t.namespace+"_";await(async e=>{const t=await o();return new Promise((r,s)=>{const o=t.transaction(n,"readwrite").objectStore(n).delete(e);o.onsuccess=()=>r(),o.onerror=()=>s(o.error)})})(`${r}${e}`)}}}},ft=e=>{const{adapter:t,autoSyncInterval:n}=e,r=new Map,s={lastSyncTimestamp:null,totalKeysSynced:0,totalBytesSynced:0,syncCount:0,lastDuration:0,errors:0};let o=null;return{name:"cloudSync",hooks:{onInstall:({store:a})=>{a._registerMethod("cloudSync","sync",async()=>{const n=performance.now(),o={};let i=0;try{const c=a.list(),l=Object.keys(c);for(const e of l){const t=a._getVersion?.(e)||0;if(t>(r.get(e)||0)){const n=c[e];o[e]=n,i+=JSON.stringify(n).length,r.set(e,t)}}if(0===Object.keys(o).length)return{status:"no-change",stats:s};if(await t.save(o))return s.lastSyncTimestamp=Date.now(),s.totalKeysSynced+=Object.keys(o).length,s.totalBytesSynced+=i,s.syncCount++,s.lastDuration=performance.now()-n,e.onSync&&e.onSync(s),{status:"success",stats:s};throw new Error(`Adapter ${t.name} failed to save.`)}catch(e){return s.errors++,{status:"error",error:String(e),stats:s}}}),a._registerMethod("cloudSync","getStats",()=>s),n&&n>0&&(o=setInterval(()=>{const e=a.plugins.cloudSync;e&&e.sync()},n))},onDestroy:()=>{o&&clearInterval(o)}}}},yt=(e,t)=>({name:"MongoDB-Atlas",save:async n=>(await fetch(`${e}/action/updateOne`,{method:"POST",headers:{"Content-Type":"application/json","api-key":t},body:JSON.stringify({dataSource:"Cluster0",database:"rgs_cloud",collection:"user_states",filter:{id:"global_state"},update:{$set:{data:n,updatedAt:Date.now()}},upsert:!0})})).ok}),pt=(e,t)=>({name:"Firebase-Firestore",save:async e=>{try{Ne();return(()=>{})("[Mock] Firestore Syncing:",e),!0}catch(e){return!1}}}),ht=(e,t)=>({name:"SQL-REST-API",save:async n=>{const r=t();if(!r)return!1;return(await fetch(e,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n),credentials:"same-origin"})).ok}}),gt=e=>({name:"gstate-logger",hooks:{onSet:({key:e,value:t,version:n})=>{(new Date).toLocaleTimeString()},onRemove:({key:e})=>{},onTransaction:({key:e})=>{}}}),mt=(e,t)=>{const n=Fe("string"==typeof t?{namespace:t}:t);e&&Object.entries(e).forEach(([e,t])=>{null===n.get(e)&&n._setSilently(e,t)});return"undefined"==typeof window||Ne()||(window.gstate=n,window.gState=n,window.rgs=n),Object.assign(e=>Ge(e,n),n)},_t=(e,t)=>Qe()?.addAccessRule(e,t),St=(e,t,n)=>Qe()?.hasPermission(e,t,n)??!0,wt=(e,t,n)=>{const r=Qe();if(!r)throw new Error("[gstate] recordConsent failed: No store found. call initState() first.");return r.recordConsent(e,t,n)},bt=(e,t)=>Qe()?.hasConsent(e,t)??!1,vt=e=>Qe()?.getConsents(e)??[],kt=(e,t)=>Qe()?.revokeConsent(e,t),Et=e=>{const t=Qe();if(!t)throw new Error("[gstate] exportUserData failed: No store found.");return t.exportUserData(e)},Ct=e=>{const t=Qe();if(!t)throw new Error("[gstate] deleteUserData failed: No store found.");return t.deleteUserData(e)},Ot=()=>{},Dt=()=>{};export{xe as SyncEngine,_t as addAccessRule,ct as analyticsPlugin,Ot as clearAccessRules,Dt as clearAllConsents,ft as cloudSyncPlugin,tt as createAsyncStore,pt as createFirestoreAdapter,yt as createMongoAdapter,ht as createSqlRestAdapter,Fe as createStore,Ue as createSyncEngine,ut as debugPlugin,Ct as deleteUserData,we as deriveKeyFromPassword,Be as destroyState,Ze as destroySync,ot as devToolsPlugin,ke as exportKey,Et as exportUserData,ve as generateEncryptionKey,be as generateSalt,vt as getConsents,Qe as getStore,mt as gstate,it as guardPlugin,bt as hasConsent,St as hasPermission,nt as immerPlugin,Ee as importKey,dt as indexedDBPlugin,Je as initState,Xe as initSync,Se as isCryptoAvailable,Me as logAudit,gt as loggerPlugin,wt as recordConsent,kt as revokeConsent,Pe as sanitizeValue,st as schemaPlugin,Ae as setAuditLogger,at as snapshotPlugin,lt as syncPlugin,et as triggerSync,rt as undoRedoPlugin,Ge as useGState,We as useIsStoreReady,Ge as useSimpleState,Ge as useStore,Ye as useSyncStatus,He as useSyncedState,Te as validateKey};
|