@jucie.io/state 1.0.37 → 1.0.38

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/dist/lib/gsru.js CHANGED
@@ -3,6 +3,9 @@ import { traverse } from './tree/traverse.js';
3
3
  import { graft, detach, replace } from './tree/mutate.js';
4
4
  import { isPrimitive } from '../utils/isPrimitive.js';
5
5
  import { clone } from '../utils/clone.js';
6
+ import { traverseChunks } from './tree/traverseChunks.js';
7
+ import { resolveChunks } from './tree/resolveChunks.js';
8
+ import { reportedAs } from './reportedAs.js';
6
9
 
7
10
  function spread(value) {
8
11
  if (Array.isArray(value)) {
@@ -22,9 +25,10 @@ export function get(state, marker, cb) {
22
25
  shouldCallCallback = true;
23
26
  return state;
24
27
  },
25
- path: ({path}) => {
28
+ path: ({ chunks }) => {
29
+ // Called back even when a query finds nothing, so a reader still hears when the item turns up.
26
30
  shouldCallCallback = true;
27
- return traverse(state, path);
31
+ return traverseChunks(state, chunks);
28
32
  }
29
33
  });
30
34
  } catch (error) {
@@ -40,6 +44,7 @@ export function get(state, marker, cb) {
40
44
  export function set(state, marker, value, method, cb) {
41
45
  let from;
42
46
  let shouldCallCallback = false;
47
+ let reportedMarker = marker;
43
48
 
44
49
  try {
45
50
  return dispatch(marker, {
@@ -49,9 +54,13 @@ export function set(state, marker, value, method, cb) {
49
54
  shouldCallCallback = true;
50
55
  return value;
51
56
  },
52
- path: ({path}) => {
57
+ path: (pathMarker) => {
58
+ const path = resolveChunks(state, pathMarker.chunks, { addMissing: true });
59
+ // Inside an item a query can't find: nothing to write into, and no change.
60
+ if (path === undefined) return undefined;
53
61
  from = spread(traverse(state, path));
54
62
  graft(state, path, value);
63
+ reportedMarker = reportedAs(pathMarker, path);
55
64
  shouldCallCallback = true;
56
65
  return value;
57
66
  }
@@ -61,7 +70,7 @@ export function set(state, marker, value, method, cb) {
61
70
  return undefined;
62
71
  } finally {
63
72
  if (shouldCallCallback && cb) {
64
- cb(marker, method, value, from);
73
+ cb(reportedMarker, method, value, from);
65
74
  }
66
75
  }
67
76
  }
@@ -69,6 +78,10 @@ export function set(state, marker, value, method, cb) {
69
78
  export function remove(state, marker, method, cb) {
70
79
  let from;
71
80
  let shouldCallCallback = false;
81
+ let reportedMarker = marker;
82
+ // A path with no query reports its removal even when nothing was there; a query that finds nothing removed
83
+ // nothing it can name, so it reports nothing.
84
+ let foundNothing = false;
72
85
  try {
73
86
  return dispatch(marker, {
74
87
  global: () => {
@@ -77,8 +90,14 @@ export function remove(state, marker, method, cb) {
77
90
  shouldCallCallback = true;
78
91
  return from;
79
92
  },
80
- path: ({path}) => {
93
+ path: (pathMarker) => {
94
+ const path = resolveChunks(state, pathMarker.chunks);
95
+ if (path === undefined) {
96
+ foundNothing = true;
97
+ return undefined;
98
+ }
81
99
  from = detach(state, path);
100
+ reportedMarker = reportedAs(pathMarker, path);
82
101
  shouldCallCallback = true;
83
102
  return from;
84
103
  }
@@ -87,8 +106,8 @@ export function remove(state, marker, method, cb) {
87
106
  console.error(error);
88
107
  return undefined;
89
108
  } finally {
90
- if (cb) {
91
- cb(marker, method, undefined, from);
109
+ if (cb && !foundNothing) {
110
+ cb(reportedMarker, method, undefined, from);
92
111
  }
93
112
  }
94
113
  }
@@ -96,6 +115,7 @@ export function remove(state, marker, method, cb) {
96
115
  export function update(state, marker, fn, method, cb) {
97
116
  let from, to;
98
117
  let shouldCallCallback = false;
118
+ let reportedMarker = marker;
99
119
  try {
100
120
  return dispatch(marker, {
101
121
  global: () => {
@@ -105,11 +125,15 @@ export function update(state, marker, fn, method, cb) {
105
125
  shouldCallCallback = true;
106
126
  return to;
107
127
  },
108
- path: ({ path }) => {
128
+ path: (pathMarker) => {
129
+ const path = resolveChunks(state, pathMarker.chunks, { addMissing: true });
130
+ // Inside an item a query can't find: nothing to update, and `fn` isn't called.
131
+ if (path === undefined) return undefined;
109
132
  from = isGlobalPath(path) ? state : traverse(state, path);
110
133
  const clonePrev = isPrimitive(from) ? from : clone(from);
111
134
  to = fn(clonePrev);
112
135
  graft(state, path, to);
136
+ reportedMarker = reportedAs(pathMarker, path);
113
137
  shouldCallCallback = true;
114
138
  return to;
115
139
  }
@@ -119,7 +143,7 @@ export function update(state, marker, fn, method, cb) {
119
143
  return undefined;
120
144
  } finally {
121
145
  if (shouldCallCallback && cb) {
122
- cb(marker, method, to, from);
146
+ cb(reportedMarker, method, to, from);
123
147
  }
124
148
  }
125
149
  }
@@ -1,4 +1,5 @@
1
1
  import { encodePath } from './pathEncoder.js';
2
+ import { isQuerySegment } from './query/isQuerySegment.js';
2
3
  import { GLOBAL_TAG } from './TOKENS.js';
3
4
  import {
4
5
  MARKER_GLOBAL,
@@ -48,19 +49,48 @@ export function normalizePaths(args = []) {
48
49
  return [1, [[...args]] ];
49
50
  }
50
51
 
51
- function pathHasEphemeral(path) {
52
- if (!Array.isArray(path)) {
53
- return false;
54
- }
52
+ const PATH_EPHEMERAL = 1;
53
+ const PATH_QUERY = 2;
55
54
 
55
+ // One pass over a path's segments, for what a marker needs to know: whether a segment is ephemeral (a string
56
+ // starting with '.'), and whether one is a query (a plain object). A plain path pays this one pass, as before.
57
+ function scanPath(path) {
58
+ let flags = 0;
59
+ if (!Array.isArray(path)) return flags;
56
60
  for (let i = 0; i < path.length; i++) {
57
61
  const segment = path[i];
58
- if (typeof segment === 'string' && segment.charCodeAt(0) === 46) { // '.'
59
- return true;
62
+ if (typeof segment === 'string') {
63
+ if (segment.charCodeAt(0) === 46) flags |= PATH_EPHEMERAL; // '.'
64
+ } else if (isQuerySegment(segment)) {
65
+ flags |= PATH_QUERY;
60
66
  }
61
67
  }
68
+ return flags;
69
+ }
62
70
 
63
- return false;
71
+ /**
72
+ * A path as the steps to walk it: runs of keys, each walked with `traverse` from where the step before left off, and
73
+ * the queries between them, each searched in the list the run before it reached. Every path is walked this way: one
74
+ * with no query is one run. `['foo', 'bar', { name: 'x' }, 'baz']` is `[['foo', 'bar'], { name: 'x' }, ['baz']]`, and
75
+ * `['foo', 'bar']` is `[['foo', 'bar']]`. A run is an array and a query a plain object, so a walker tells them apart,
76
+ * and no run is empty.
77
+ */
78
+ function chunksOf(path, hasQuery) {
79
+ if (!hasQuery) return [path];
80
+ const chunks = [];
81
+ let run = null;
82
+ for (const segment of path) {
83
+ if (isQuerySegment(segment)) {
84
+ if (run) chunks.push(run);
85
+ run = null;
86
+ chunks.push(segment);
87
+ continue;
88
+ }
89
+ if (!run) run = [];
90
+ run.push(segment);
91
+ }
92
+ if (run) chunks.push(run);
93
+ return chunks;
64
94
  }
65
95
 
66
96
  // Marker factory
@@ -72,6 +102,7 @@ export function createMarker(paths = []) {
72
102
  length: 0,
73
103
  path: [],
74
104
  children: null,
105
+ chunks: null,
75
106
  type: MARKER_GLOBAL
76
107
  };
77
108
  }
@@ -80,8 +111,9 @@ export function createMarker(paths = []) {
80
111
  const type = length === 1 ? MARKER_SINGLE : MARKER_MANY;
81
112
  const path = length === 1 ? normalizedPaths[0] : normalizedPaths;
82
113
  const children = length > 1 ? normalizedPaths.map(path => createMarker(path)) : null;
114
+ const flags = type === MARKER_SINGLE ? scanPath(path) : 0;
83
115
  const isEphemeral = type === MARKER_SINGLE
84
- ? pathHasEphemeral(path)
116
+ ? (flags & PATH_EPHEMERAL) !== 0
85
117
  : children.some(child => isEphemeralMarker(child));
86
118
 
87
119
  let markerType = type;
@@ -95,6 +127,8 @@ export function createMarker(paths = []) {
95
127
  length,
96
128
  path,
97
129
  children,
130
+ // A many-marker's children each have their own.
131
+ chunks: type === MARKER_SINGLE ? chunksOf(path, (flags & PATH_QUERY) !== 0) : null,
98
132
  type: markerType
99
133
  };
100
134
  }
@@ -1,4 +1,6 @@
1
1
  import { GLOBAL_TAG } from './TOKENS.js';
2
+ import { isQuerySegment } from './query/isQuerySegment.js';
3
+ import { canonicalQuery } from './query/canonicalQuery.js';
2
4
 
3
5
  // Fast helpers
4
6
  function escapeStr(str) {
@@ -46,6 +48,10 @@ export function encodePath(segments) {
46
48
  } else if (typeof v === "string") {
47
49
  // 's' tag
48
50
  parts[i] = "s" + escapeStr(v);
51
+ } else if (isQuerySegment(v)) {
52
+ // 'q' tag: a query, as canonical JSON. The address names the item the query finds, whatever its index, and
53
+ // is escaped like 's' so a '.' in a value can't split it (what's above an address is read by its dots).
54
+ parts[i] = "q" + escapeStr(canonicalQuery(v));
49
55
  } else {
50
56
  // If you need more types, add here (e.g., booleans 'b', floats 'f').
51
57
  throw new TypeError(`Unsupported segment type at index ${i}: ${v}`);
@@ -81,6 +87,8 @@ export function decodeAddress(address) {
81
87
  out[i] = num;
82
88
  } else if (tag === "s") {
83
89
  out[i] = unescapeStr(body);
90
+ } else if (tag === "q") {
91
+ out[i] = JSON.parse(unescapeStr(body));
84
92
  } else {
85
93
  throw new Error(`Unknown type tag "${tag}" in token "${token}"`);
86
94
  }
@@ -0,0 +1,21 @@
1
+ const QUERY_VALUE_TYPES = new Set(['string', 'number', 'boolean']);
2
+
3
+ /**
4
+ * A query as JSON with its keys sorted, so `{ a, b }` and `{ b, a }` encode to one address. JSON keeps types, so
5
+ * `{ id: 1 }` and `{ id: '1' }` stay two queries, as `===` already says. A query with no fields would match any item,
6
+ * and one holding an object could never match (`===` compares objects by reference), so both are refused.
7
+ */
8
+ export function canonicalQuery(query) {
9
+ const keys = Object.keys(query).sort();
10
+ if (keys.length === 0) {
11
+ throw new TypeError('A query segment needs at least one field, as in { name: "src" }: an empty query matches any item.');
12
+ }
13
+ const sorted = {};
14
+ for (const key of keys) {
15
+ if (!QUERY_VALUE_TYPES.has(typeof query[key])) {
16
+ throw new TypeError(`A query segment's values are strings, numbers or booleans; "${key}" holds ${typeof query[key]}. Match on a field that holds a plain value, such as an id.`);
17
+ }
18
+ sorted[key] = query[key];
19
+ }
20
+ return JSON.stringify(sorted);
21
+ }
@@ -0,0 +1,5 @@
1
+ // An item matches a query when every field the query names holds the same value (`===`). Item level only: unlike
2
+ // `findWhere`, a query never matches something nested inside an item.
3
+ export function isMatch(item, query) {
4
+ return item !== null && typeof item === 'object' && Object.keys(query).every((key) => item[key] === query[key]);
5
+ }
@@ -0,0 +1,5 @@
1
+ // A path segment that's a plain object is a query: it names a list item by what the item holds, and is resolved to
2
+ // that item's index whenever the path is read or written. Strings and numbers are keys and indices, as always.
3
+ export function isQuerySegment(segment) {
4
+ return segment !== null && typeof segment === 'object' && !Array.isArray(segment);
5
+ }
@@ -0,0 +1,5 @@
1
+ // The marker a write reports with: as it was for a path with no query, which resolves to the path itself, and with
2
+ // `resolved` beside the path as written for one with a query, saying where its queries landed.
3
+ export function reportedAs(marker, resolved) {
4
+ return resolved === marker.path ? marker : { ...marker, resolved };
5
+ }
@@ -0,0 +1,46 @@
1
+ import { traverse } from './traverse.js';
2
+ import { isMatch } from '../query/isMatch.js';
3
+
4
+ /**
5
+ * Where a write to a path lands: its marker's chunks as one concrete path, or undefined when it has nowhere to land.
6
+ * Each run of keys is kept, and walked with `traverse` from where the step before left off; each query becomes the
7
+ * index of the first matching item in the list it reached. A path with no query is one run, and resolves to that run
8
+ * itself: the same array as the marker's path, so a caller can tell nothing was resolved.
9
+ *
10
+ * Keys pass through where nothing exists yet, as a plain path's do, so `graft` still makes them. A query inside an
11
+ * item that isn't there finds nothing, and the write has nothing to write into. With `addMissing`, a final query that
12
+ * finds nothing resolves to the slot past the end of its list (index 0 of a list not yet made), so `graft` adds the
13
+ * item there, as `addWhere` does; without it, as for a removal, it lands nowhere.
14
+ */
15
+ export function resolveChunks(state, chunks, { addMissing = false } = {}) {
16
+ const length = chunks.length;
17
+ if (length === 1 && Array.isArray(chunks[0])) return chunks[0];
18
+
19
+ const concrete = [];
20
+ let node = state;
21
+ let i = 0;
22
+ while (i < length) {
23
+ const chunk = chunks[i];
24
+ if (Array.isArray(chunk)) {
25
+ concrete.push(...chunk);
26
+ node = node === undefined || node === null ? undefined : traverse(node, chunk);
27
+ } else {
28
+ const isFinal = i === length - 1;
29
+ if (node === undefined && isFinal && addMissing) {
30
+ concrete.push(0);
31
+ return concrete;
32
+ }
33
+ if (!Array.isArray(node)) return undefined;
34
+ const index = node.findIndex((item) => isMatch(item, chunk));
35
+ if (index === -1) {
36
+ if (!(isFinal && addMissing)) return undefined;
37
+ concrete.push(node.length);
38
+ return concrete;
39
+ }
40
+ concrete.push(index);
41
+ node = node[index];
42
+ }
43
+ i++;
44
+ }
45
+ return concrete;
46
+ }
@@ -0,0 +1,29 @@
1
+ import { traverse } from './traverse.js';
2
+ import { isMatch } from '../query/isMatch.js';
3
+
4
+ /**
5
+ * What a path names, read in one pass from its marker's chunks: each run of keys with `traverse`, from where the step
6
+ * before left off, and each query as the first item of the list it reached that matches. A path with no query is one
7
+ * run, so this is one `traverse`. Undefined when a query finds nothing, or meets something that isn't a list.
8
+ *
9
+ * A `while` over a length read once, as the other hot loops here (`dispatch`): every read in the state comes through
10
+ * this.
11
+ */
12
+ export function traverseChunks(state, chunks) {
13
+ const length = chunks.length;
14
+ let node = state;
15
+ let i = 0;
16
+ while (i < length) {
17
+ if (node === undefined || node === null) return undefined;
18
+ const chunk = chunks[i];
19
+ if (Array.isArray(chunk)) {
20
+ node = traverse(node, chunk);
21
+ } else if (Array.isArray(node)) {
22
+ node = node.find((item) => isMatch(item, chunk));
23
+ } else {
24
+ return undefined;
25
+ }
26
+ i++;
27
+ }
28
+ return node;
29
+ }
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- var A="*",w=Symbol("STATE_CONTEXT"),Jt=Symbol("MATCHER"),k="CREATED",E="DELETED",T="UPDATED",M=1,O=2,U=4,I=8;function St(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="~"?e+="~~":n==="."?e+="~d":e+=n}return e.length===0?"~e":e}function st(t){let e=new Array(t.length);for(let r=0;r<t.length;r++){let n=t[r];if(typeof n=="number"&&Number.isInteger(n))e[r]="n"+String(n);else if(typeof n=="string")e[r]="s"+St(n);else throw new TypeError(`Unsupported segment type at index ${r}: ${n}`)}return e.join(".")}function ct(t){return(t.type&M)===M}function Q(t){return(t.type&O)===O}function X(t){return(t.type&U)===U}function ut(t){return(t.type&I)===I}function Y(t){return!t||t.length===0||t===A||t[0]===A}function ht(t=[]){let e=t.length;return e===0?[0,[]]:e===1&&t[0]===A?[0,[]]:Array.isArray(t[0])?e===1?[1,[t[0]]]:[e,t]:[1,[[...t]]]}function Wt(t){if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++){let r=t[e];if(typeof r=="string"&&r.charCodeAt(0)===46)return!0}return!1}function b(t=[]){if(Y(t))return{address:A,isMarker:!0,length:0,path:[],children:null,type:M};let[e,r]=ht(t),n=e===1?O:U,i=e===1?r[0]:r,o=e>1?r.map(u=>b(u)):null,s=n===O?Wt(i):o.some(u=>ut(u)),c=n;return s&&(c|=I),{address:n===O?st(i):null,isMarker:!0,length:e,path:i,children:o,type:c}}function f(t,e){if(e.length===0)return t;let[r,n]=ht(e);if(ct(t))return b(n,t.state);if(Q(t)){if(r===0)return t;if(r===1){let i=[...t.path,...n[0]];return b(i,t.state)}else{let i=n.map(o=>[...t.path,...o]);return b(i,t.state)}}if(X(t)){let i=new Array(t.length),o=0;for(;o<t.length;)i[o]=f(t.children[o],e),o++;let s=[];for(o=0;o<i.length;){let c=i[o];if(Q(c))s.push(c.path);else if(X(c)){let u=0;for(;u<c.length;)s.push(c.children[u].path),u++}o++}return b(s,t.state)}return t}function g(t,{global:e,path:r,ephemeral:n,error:i}){try{if(!t.isMarker)return;if(ct(t))return e?e(t):void 0;if(ut(t))return n?n(t):r?r(t):void 0;if(Q(t))return r?r(t):void 0;if(X(t)){let o=new Array(t.length),s=0;for(;s<t.length;){let c=t.children[s];o[s]=g(c,{global:e,path:r,ephemeral:n,error:i}),s++}return o}return}catch(o){return i?i(o.message):void 0}}var S=[null,null,(t,e)=>t?.[e[0]]?.[e[1]],(t,e)=>t?.[e[0]]?.[e[1]]?.[e[2]],(t,e)=>t?.[e[0]]?.[e[1]]?.[e[2]]?.[e[3]],(t,e)=>t?.[e[0]]?.[e[1]]?.[e[2]]?.[e[3]]?.[e[4]],(t,e)=>t?.[e[0]]?.[e[1]]?.[e[2]]?.[e[3]]?.[e[4]]?.[e[5]],(t,e)=>t?.[e[0]]?.[e[1]]?.[e[2]]?.[e[3]]?.[e[4]]?.[e[5]]?.[e[6]],(t,e)=>t?.[e[0]]?.[e[1]]?.[e[2]]?.[e[3]]?.[e[4]]?.[e[5]]?.[e[6]]?.[e[7]]];function Pt(t){let r="obj"+Array.from({length:t},(i,o)=>`?.[path[${o}]]`).join(""),n=new Function("obj","path",`return ${r}`);return S[t]=n,n}function m(t,e){let r=e.length;return r===0?t:r===1?t[e[0]]:r<S.length&&S[r]||S[r]?S[r](t,e):Pt(r)(t,e)}function p(t){return typeof t=="number"?[]:{}}var L=[null,null,(t,e,r)=>{let[n,i]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=r,r},(t,e,r)=>{let[n,i,o]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=i in t[n]?t[n][i]:p(o),t[n][i][o]=r,r},(t,e,r)=>{let[n,i,o,s]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=i in t[n]?t[n][i]:p(o),t[n][i][o]=o in t[n][i]?t[n][i][o]:p(s),t[n][i][o][s]=r,r},(t,e,r)=>{let[n,i,o,s,c]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=i in t[n]?t[n][i]:p(o),t[n][i][o]=o in t[n][i]?t[n][i][o]:p(s),t[n][i][o][s]=s in t[n][i][o]?t[n][i][o][s]:p(c),t[n][i][o][s][c]=r,r},(t,e,r)=>{let[n,i,o,s,c,u]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=i in t[n]?t[n][i]:p(o),t[n][i][o]=o in t[n][i]?t[n][i][o]:p(s),t[n][i][o][s]=s in t[n][i][o]?t[n][i][o][s]:p(c),t[n][i][o][s][c]=c in t[n][i][o][s]?t[n][i][o][s][c]:p(u),t[n][i][o][s][c][u]=r,r},(t,e,r)=>{let[n,i,o,s,c,u,h]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=i in t[n]?t[n][i]:p(o),t[n][i][o]=o in t[n][i]?t[n][i][o]:p(s),t[n][i][o][s]=s in t[n][i][o]?t[n][i][o][s]:p(c),t[n][i][o][s][c]=c in t[n][i][o][s]?t[n][i][o][s][c]:p(u),t[n][i][o][s][c][u]=u in t[n][i][o][s][c]?t[n][i][o][s][c][u]:p(h),t[n][i][o][s][c][u][h]=r,r},(t,e,r)=>{let[n,i,o,s,c,u,h,l]=e;return t[n]=n in t?t[n]:p(i),t[n][i]=i in t[n]?t[n][i]:p(o),t[n][i][o]=o in t[n][i]?t[n][i][o]:p(s),t[n][i][o][s]=s in t[n][i][o]?t[n][i][o][s]:p(c),t[n][i][o][s][c]=c in t[n][i][o][s]?t[n][i][o][s][c]:p(u),t[n][i][o][s][c][u]=u in t[n][i][o][s][c]?t[n][i][o][s][c][u]:p(h),t[n][i][o][s][c][u][h]=h in t[n][i][o][s][c][u]?t[n][i][o][s][c][u][h]:p(l),t[n][i][o][s][c][u][h][l]=r,r}];function jt(t){let e=Array.from({length:t},(s,c)=>`v${c}`),n=`const [${e.join(", ")}] = path;
2
- `,i="state";for(let s=0;s<t-1;s++){let c=e[s],u=e[s+1];n+=`${i}[${c}] = (${i}[${c}] !== undefined && typeof ${i}[${c}] === 'object') ? ${i}[${c}] : createNodeType(${u});
3
- `,i+=`[${c}]`}n+=`${i}[${e[t-1]}] = value;
4
- return state;`;let o=new Function("state","path","value","createNodeType",n);return L[t]=(s,c,u)=>o(s,c,u,p),L[t]}function j(t,e,r){let n=e.length;return n===0?Object.assign(t,r):n===1?t[e[0]]=r:L[n]?L[n](t,e,r):jt(n)(t,e,r)}function lt(t,e){let r=e.length;if(r===0)return;if(r===1){let c=t[e[0]];return Array.isArray(t)?t.splice(e[0],1):delete t[e[0]],c}let n=e.slice(0,-1),i=e[r-1],o=m(t,n);if(!o)return;let s=o[i];return Array.isArray(o)?o.splice(i,1):delete o[i],s}function $(t,e){let r=Object.keys(t),n=0;for(;n<r.length;)delete t[r[n]],n++;let i=Object.keys(e);for(n=0;n<i.length;){let o=i[n],s=e[o];s&&typeof s=="object"&&!Array.isArray(s)?(t[o]=t[o]||{},$(t[o],s)):t[o]=s,n++}return t}function ft(t){let e=Object.keys(t);for(let r of e)delete t[r];return t}function at(t){let e=typeof t;return t==null||e==="string"||e==="number"||e==="boolean"||e==="bigint"||e==="symbol"||e==="function"}var v=t=>structuredClone?structuredClone(t):JSON.parse(JSON.stringify(t));function $t(t){return Array.isArray(t)?[...t]:typeof t=="object"&&t!==null?{...t}:t}function y(t,e,r){let n=!1;try{return g(e,{global:()=>(n=!0,t),path:({path:i})=>(n=!0,m(t,i))})}catch(i){console.error(i);return}finally{n&&r&&r(e)}}function x(t,e,r,n,i){let o,s=!1;try{return g(e,{global:()=>(o={...t},t=$(t,r),s=!0,r),path:({path:c})=>(o=$t(m(t,c)),j(t,c,r),s=!0,r)})}catch(c){console.error(c);return}finally{s&&i&&i(e,n,r,o)}}function C(t,e,r,n){let i,o=!1;try{return g(e,{global:()=>(i=t,t=$(t,{}),o=!0,i),path:({path:s})=>(i=lt(t,s),o=!0,i)})}catch(s){console.error(s);return}finally{n&&n(e,r,void 0,i)}}function W(t,e,r,n,i){let o,s,c=!1;try{return g(e,{global:()=>(o=t,s=r(t),t=$(t,s),c=!0,s),path:({path:u})=>{o=Y(u)?t:m(t,u);let h=at(o)?o:v(o);return s=r(h),j(t,u,s),c=!0,s}})}catch(u){console.error(u);return}finally{c&&i&&i(e,n,s,o)}}function Z(t,e){let r=m(t,e);if(r===void 0)r=[],j(t,e,r);else if(!Array.isArray(r))throw new TypeError(`Expected array at path "${e.join(".")}", got ${typeof r}`);return r}function _(t,e,r,n,i){let o=!1;try{return g(e,{path:({path:s})=>(Z(t,s).push(r),o=!0,r)})}catch(s){console.error(s);return}finally{o&&i&&i(e,n,r,void 0)}}function R(t,e,r,n,i){let o=!1;try{return g(e,{path:({path:s})=>(Z(t,s).unshift(r),o=!0,r)})}catch(s){console.error(s);return}finally{o&&i&&i(e,n,r,void 0)}}function V(t,e,r,n,i){let o,s=!1;try{return g(e,{path:({path:c})=>(o=Z(t,c).splice(...r),s=!0,o)})}catch(c){console.error(c);return}finally{s&&i&&i(e,n,r,o)}}function tt(t,e){if(!(t&&t[0]==="."))return e}function B(t,e=tt,r=""){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(i=>B(i,e));let n={};for(let i of Object.keys(t)){let o=e(i,t[i]);typeof o<"u"&&(n[i]=B(o,e,i))}return n}import{encode as _t,decode as Rt}from"cbor-x";var H=new Uint8Array([74,83,67,50]),G=2;function pt(t){let r="";for(let n=0;n<t.length;n+=8192){let i=t.slice(n,n+8192);r+=String.fromCharCode(...i)}return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function dt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e+"=".repeat((4-e.length%4)%4),n=atob(r),i=new Uint8Array(n.length);for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);return i}function F(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t[r]>>>0;return e}function z(t,e,r=0){return new DataView(e.buffer,e.byteOffset+r,4).setUint32(0,t,!0),r+4}function J(t,e=0){return new DataView(t.buffer,t.byteOffset+e,4).getUint32(0,!0)}function yt(t,e,r=0){return new DataView(e.buffer,e.byteOffset+r,2).setUint16(0,t,!0),r+2}function gt(t,e=0){return new DataView(t.buffer,t.byteOffset+e,2).getUint16(0,!0)}function mt(t,e,r=0){return e[r]=t,r+1}function bt(t,e=0){return t[e]}function At(t){return _t(t)}function xt(t){return[Rt(t),t.length]}async function et(t,{replacer:e=tt}={}){let r=B(t,e),n=At(r),i=4+n.length,o=new Uint8Array(i),s=0;s=z(n.length,o,s),o.set(n,s);let c=F(o),u=15,h=new Uint8Array(u+o.length);return h.set(H,0),yt(G,h,4),mt(0,h,6),z(c,h,7),z(o.length,h,11),h.set(o,15),pt(h)}async function wt(t,e){let r=dt(t);if(r.length<15)throw new Error("Invalid capsule: too short");for(let d=0;d<4;d++)if(r[d]!==H[d])throw new Error("Invalid capsule: bad magic");let n=gt(r,4);if(n!==G)throw new Error(`Unsupported capsule version: ${n}`);let i=bt(r,6),o=J(r,7),s=J(r,11);if(s<0)throw new Error("Invalid capsule: negative payload length");if(r.length!==15+s)throw new Error("Invalid capsule: length mismatch");let c=r.slice(15),u=F(c);if(o!==u)throw new Error("Integrity check failed: checksum mismatch");let h=0,l=J(c,h);if(h+=4,h+l>c.length)throw new Error(`Data length ${l} exceeds payload bounds at offset ${h}`);let[a]=xt(c.slice(h,h+l));return e&&e(a),{data:a,meta:{version:n,flags:i,bytes:r.length,checksum:u.toString(16)}}}function Dt(t,e,r){switch(e){case"is":case"===":case"==":return t===r;case"not":case"!==":case"!=":return t!==r;case"includes":return Array.isArray(t)&&t.includes(r);case"has":return typeof t=="object"&&t!==null&&Object.values(t).includes(r);case"in":return typeof t=="object"&&t!==null&&r in t;case"gt":case">":return t>r;case"lt":case"<":return t<r;case"gte":case">=":return t>=r;case"lte":case"<=":return t<=r;default:throw new Error(`Unknown matcher: ${e}`)}}function K(t,e,r,n,i=[],o=!1){let s=[];if(t===null||typeof t!="object")return s;for(let[c,u]of Object.entries(t)){if(c===e&&Dt(u,r,n)&&(s.push([...i,c]),!o))return s;if(typeof u=="object"&&u!==null)if(Array.isArray(u))for(let h=0;h<u.length;h++){let l=u[h];if(l&&typeof l=="object"){let a=K(l,e,r,n,[...i,c,h],o);if(s.push(...a),!o&&s.length>0)return s}}else{let h=K(u,e,r,n,[...i,c],o);if(s.push(...h),!o&&s.length>0)return s}}return s}function nt(t,e,r="is",n){return K(t,e,r,n,[],!1)?.[0]}function Et(t,e,r="is",n){return K(t,e,r,n,[],!0)}function Nt(t,e){let r=Object.keys(e);if(r.length===0)return!1;for(let n=0;n<r.length;n++)if(t[r[n]]!==e[r[n]])return!1;return!0}function q(t,e,r=[],n=!1){let i=[];if(t===null||typeof t!="object"||Nt(t,e)&&(i.push([...r]),!n))return i;if(Array.isArray(t))for(let o=0;o<t.length;o++){let s=t[o];if(s&&typeof s=="object"){let c=q(s,e,[...r,o],n);if(i.push(...c),!n&&i.length>0)return i}}else for(let[o,s]of Object.entries(t))if(typeof s=="object"&&s!==null){let c=q(s,e,[...r,o],n);if(i.push(...c),!n&&i.length>0)return i}return i}function P(t,e){return q(t,e,[],!1)?.[0]}function D(t,e){return q(t,e,[],!0)}var je={[k]:E,[E]:k,[T]:T};function Ct(t,e){return e===void 0?k:t===void 0?E:T}function rt(t,e,r,n,i){return g(t,{global:()=>({path:A,method:e,operation:Ct(r,n),from:n,to:r}),path:o=>{let s={path:o.path,method:e,operation:Ct(r,n),from:n,to:r};return i&&(s.query=i),s}})}function Mt(t,e){return t!==null&&typeof t=="object"&&Object.keys(e).every(r=>t[r]===e[r])}function Ut(t){if(t.length===0)return[];if(t.length===1)return t[0];let e=[],r=t[0];for(let n=0;n<r.length&&t.every(i=>i[n]===r[n]);n++)e.push(r[n]);return e}var N=class t{#t;#e;#o=0;#l=0;#c=0;#i=null;#n;#r;#f=new Map;#u;static create(e={}){return new t(e)}constructor(e,r=null,n=null,i=null,o=null){this.#u=o||this,this.#t=e,this.#n=n||this.#p(),this.#r=i||this.#d(),this.#e=r||b(),this.#o=0}install(...e){let r=new Map;for(let n of e){if(this.#f.has(n.name)){console.warn(`Plugin "${n.name}" already installed`);continue}if(!n.install){console.warn(`Plugin "${n.name}" does not have an install function`);continue}let i=n.install(this);if(this.#f.set(n.name,i),i.initialize&&r.set(n.name,()=>i.initialize(this,i.options)),i.actions){let o=i.actions(this,i.options);Object.defineProperty(this,n.name,{value:o,writable:!1,enumerable:!0,configurable:!1})}}return r.forEach(n=>n()),this}get batching(){return this.#o>0}get(...e){return y(this.#t,f(this.#e,e),this.#r)}clone(...e){let r=y(this.#t,f(this.#e,e),this.#r);if(typeof r=="object"&&r!==null)try{return v(r)}catch{return console.warn(`Failed to clone data: ${r}`),r}return r}has(...e){let r=f(this.#e,e);return g(r,{global:()=>{},path:n=>y(this.#t,n,this.#r)!==void 0})}keys(...e){let r=f(this.#e,e);return g(r,{global:()=>Object.keys(this.#t),path:n=>Object.keys(y(this.#t,n,this.#r)||{})})}typeof(...e){let r=f(this.#e,e);return g(r,{global:()=>{},path:({path:i})=>typeof y(this.#t,i,this.#r)})}findWhen(e,r="is",n){let i=y(this.#t,this.#e,null);return nt(i,e,r,n)}findAllWhen(e,r="is",n){let i=y(this.#t,this.#e,null);return Et(i,e,r,n)}findWhere(...e){let r=e.pop(),n=e.length?f(this.#e,e):this.#e,i=y(this.#t,n,this.#r),o=P(i,r);if(o!==void 0)return m(i,o)}findAllWhere(...e){let r=e.pop(),n=e.length?f(this.#e,e):this.#e,i=y(this.#t,n,this.#r);return D(i,r).map(s=>m(i,s))}set(...e){let r=e.pop(),n=f(this.#e,e);return x(this.#t,n,r,"set",this.#n)}update(...e){let r=e.pop(),n=f(this.#e,e);return W(this.#t,n,r,"update",this.#n)}apply(e){for(let r of e){let{path:n,operation:i,method:o,to:s,query:c}=r;if(o==="addWhere"||o==="addFirstWhere"){this.#a([n],c,s,"apply",o==="addWhere"?_:R);continue}let u;if(c){let h=n.slice(0,-1),l=f(this.#e,[h]),a=y(this.#t,l,this.#r),d;if(Array.isArray(c)){let[kt,Tt,Ot]=c,ot=nt(a,kt,Tt,Ot);d=ot?ot.slice(0,-1):void 0}else d=P(a,c);if(d===void 0)continue;u=f(this.#e,[[...h,...d]])}else u=f(this.#e,n);switch(i){case k:case T:if(o==="push")_(this.#t,u,s,"apply",this.#n);else if(o==="unshift")R(this.#t,u,s,"apply",this.#n);else if(o==="splice")V(this.#t,u,s,"apply",this.#n);else if(o==="removeMatch"){let h=y(this.#t,u,this.#r);if(Array.isArray(h)){let l=JSON.stringify(s),a=h.findIndex(d=>JSON.stringify(d)===l);a!==-1&&h.splice(a,1)}}else x(this.#t,u,s,"apply",this.#n);break;case E:C(this.#t,u,"apply",this.#n);break}}}load(e){return x(this.#t,this.#e,e,"load",this.#n),this}remove(...e){let r=f(this.#e,e);return C(this.#t,r,"remove",this.#n)}push(...e){let r=e.pop(),n=f(this.#e,e);return _(this.#t,n,r,"push",this.#n)}unshift(...e){let r=e.pop(),n=f(this.#e,e);return R(this.#t,n,r,"unshift",this.#n)}splice(e,...r){let n=f(this.#e,Array.isArray(e[0])?e:[e]);return V(this.#t,n,r,"splice",this.#n)}addWhere(e,r,n){return this.#a(e,r,n,"addWhere",_)}addFirstWhere(e,r,n){return this.#a(e,r,n,"addFirstWhere",R)}#a(e,r,n,i,o){let s=f(this.#e,e),c=y(this.#t,s,this.#r),u=Array.isArray(c)?c.find(h=>Mt(h,r)):void 0;return u!==void 0?u:o(this.#t,s,n,i,(h,l,a,d)=>this.#n(h,l,a,d,r))}#s(e){return Array.isArray(e[0])?e[0]:e}setWhere(e,r,n){let i=f(this.#e,e),o=y(this.#t,i,this.#r),s=P(o,r);if(s===void 0)return;let c=[...this.#s(e),...s],u=f(this.#e,[c]);return x(this.#t,u,n,"setWhere",(h,l,a,d)=>this.#n(h,l,a,d,r))}updateWhere(e,r,n){let i=f(this.#e,e),o=y(this.#t,i,this.#r),s=P(o,r);if(s===void 0)return;let c=[...this.#s(e),...s],u=f(this.#e,[c]);return W(this.#t,u,n,"updateWhere",(h,l,a,d)=>this.#n(h,l,a,d,r))}removeWhere(e,r){let n=f(this.#e,e),i=y(this.#t,n,this.#r),o=P(i,r);if(o===void 0)return;let s=[...this.#s(e),...o],c=f(this.#e,[s]);return C(this.#t,c,"removeWhere",(u,h,l,a)=>this.#n(u,h,l,a,r))}setAllWhere(e,r,n){return this.batch(()=>{let i=f(this.#e,e),o=y(this.#t,i,this.#r),s=D(o,r),c=this.#s(e),u=(h,l,a,d)=>this.#n(h,l,a,d,r);for(let h of s){let l=f(this.#e,[[...c,...h]]);x(this.#t,l,n,"setAllWhere",u)}})}updateAllWhere(e,r,n){return this.batch(()=>{let i=f(this.#e,e),o=y(this.#t,i,this.#r),s=D(o,r),c=this.#s(e),u=(h,l,a,d)=>this.#n(h,l,a,d,r);for(let h of s){let l=f(this.#e,[[...c,...h]]);W(this.#t,l,n,"updateAllWhere",u)}})}removeAllWhere(e,r){return this.batch(()=>{let n=f(this.#e,e),i=y(this.#t,n,this.#r),o=D(i,r),s=this.#s(e),c=(h,l,a,d)=>this.#n(h,l,a,d,r),u=[];for(let h=o.length-1;h>=0;h--){let l=f(this.#e,[[...s,...o[h]]]);u.push(C(this.#t,l,"removeAllWhere",c))}return u})}setWhen(e,r,n,i){let o=[e,r,n],s=this.findWhen(e,r,n);if(!s)return;let c=s.slice(0,-1),u=f(this.#e,[c]);return x(this.#t,u,i,"setWhen",(h,l,a,d)=>this.#n(h,l,a,d,o))}updateWhen(e,r,n,i){let o=[e,r,n],s=this.findWhen(e,r,n);if(!s)return;let c=s.slice(0,-1),u=f(this.#e,[c]);return W(this.#t,u,i,"updateWhen",(h,l,a,d)=>this.#n(h,l,a,d,o))}removeWhen(e,r,n){let i=[e,r,n],o=this.findWhen(e,r,n);if(!o)return;let s=o.slice(0,-1),c=f(this.#e,[s]);return C(this.#t,c,"removeWhen",(u,h,l,a)=>this.#n(u,h,l,a,i))}setAllWhen(e,r,n,i){return this.batch(()=>{let o=[e,r,n],s=(u,h,l,a)=>this.#n(u,h,l,a,o),c=this.findAllWhen(e,r,n);for(let u of c){let h=u.slice(0,-1),l=f(this.#e,[h]);x(this.#t,l,i,"setAllWhen",s)}})}updateAllWhen(e,r,n,i){return this.batch(()=>{let o=[e,r,n],s=(u,h,l,a)=>this.#n(u,h,l,a,o),c=this.findAllWhen(e,r,n);for(let u of c){let h=u.slice(0,-1),l=f(this.#e,[h]);W(this.#t,l,i,"updateAllWhen",s)}})}removeAllWhen(e,r,n){return this.batch(()=>{let i=[e,r,n],o=(u,h,l,a)=>this.#n(u,h,l,a,i),s=this.findAllWhen(e,r,n),c=[];for(let u=s.length-1;u>=0;u--){let h=s[u].slice(0,-1),l=f(this.#e,[h]);c.push(C(this.#t,l,"removeAllWhen",o))}return c})}async export(...e){try{let r=f(this.#e,e),n=g(r,{global:async()=>await et(this.#t),path:async i=>await et(y(this.#t,i,this.#r))});return Array.isArray(n)?await Promise.all(n):await n}catch(r){throw console.trace(`Failed to export state: ${r.message}`),r}}async import(e){try{let{data:r}=await wt(e);return this.load(r),this}catch(r){throw console.trace(`Failed to import state: ${r.message}`),r}}reset(){ft(this.#t);for(let e of this.#f.values())e.reset&&e.reset();this.#n=this.#p(),this.#e=b([],this),this.#o=0,this.#l=0,this.#c=0,this.#i=null}ref(...e){let r=f(this.#e,e);return new t(this.#t,r,this.#n,this.#r,this.#u)}batch(e){return this.#o++,this.#h("onBatchStart",this.batching),e?(e(this),this.endBatch()):()=>this.endBatch()}endBatch(){return this.#o--,this.#o===0&&this.#h("onBatchEnd"),this}silent(e){return this.#l++,e?(e(this),this.endSilent()):()=>this.endSilent()}endSilent(){return this.#l--,this}quiet(e){let r=this.#u;if(r!==this){let n=r.quiet();if(!e)return()=>(n(),this);try{e(this)}finally{n()}return this}if(this.#c++,this.#c===1&&(this.#i=[]),!e)return()=>this.endQuiet();try{e(this)}finally{this.endQuiet()}return this}endQuiet(){if(this.#u!==this)return this.#u.endQuiet(),this;if(this.#c--,this.#c===0){let e=this.#i;if(this.#i=null,e&&e.length>0){let r=Ut(e),n=b(r.length?[r]:[]),i=r.length?m(this.#t,r):this.#t,o=rt(n,"quiet",i);i===void 0&&(o.operation=E),this.#h("onStateChange",n,o,!1)}}return this}#p(){return(e,r,n=void 0,i=void 0,o)=>{if(!(this.#l>0)){if(this.#i){g(e,{global:()=>this.#i.push([]),path:({path:s})=>this.#i.push(s)});return}this.#h("onStateChange",e,rt(e,r,n,i,o),this.batching)}}}#d(){return e=>this.#h("onStateAccess",e)}#h(e,...r){for(let n of this.#f.values())typeof n[e]=="function"&&n[e](...r)}},It=(...t)=>N.create(...t),Lt=t=>t instanceof N;var it=class{static name=null;static options={};static configure(e){return e={...this.options,...e},{install:r=>this.install(r,e),name:this.name,options:e}}static install(e,r){r={...this.options,...r};let n=new this(e,r);return Object.defineProperty(n,"state",{value:e,writable:!1,configurable:!1}),Object.defineProperty(n,"options",{value:r,writable:!1,configurable:!1}),n}};function vt(t){globalThis[w]||(globalThis[w]=t)}function Bt(){return globalThis[w]!==void 0}function Ht(t){globalThis[w]=t}function Gt(){return globalThis[w]||null}function Ft(){return Gt()}function zt(){globalThis[w]=void 0}export{it as Plugin,N as State,zt as clearState,It as createState,Ht as forceState,Bt as hasState,Lt as isState,vt as provideState,Ft as useState};
1
+ var w="*",T=Symbol("STATE_CONTEXT"),Ze=Symbol("MATCHER"),S="CREATED",O="DELETED",k="UPDATED",L=1,x=2,H=4,G=8,_=0,R=1,ue=2,V=-1;function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var De=new Set(["string","number","boolean"]);function fe(e){let t=Object.keys(e).sort();if(t.length===0)throw new TypeError('A query segment needs at least one field, as in { name: "src" }: an empty query matches any item.');let n={};for(let r of t){if(!De.has(typeof e[r]))throw new TypeError(`A query segment's values are strings, numbers or booleans; "${r}" holds ${typeof e[r]}. Match on a field that holds a plain value, such as an id.`);n[r]=e[r]}return JSON.stringify(n)}function le(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];r==="~"?t+="~~":r==="."?t+="~d":t+=r}return t.length===0?"~e":t}function he(e){let t=new Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];if(typeof r=="number"&&Number.isInteger(r))t[n]="n"+String(r);else if(typeof r=="string")t[n]="s"+le(r);else if(N(r))t[n]="q"+le(fe(r));else throw new TypeError(`Unsupported segment type at index ${n}: ${r}`)}return t.join(".")}function C(e){return(e.type&L)===L}function ee(e){return(e.type&x)===x}function M(e){return(e.type&H)===H}function ae(e){return(e.type&G)===G}function te(e){return!e||e.length===0||e===w||e[0]===w}function de(e=[]){let t=e.length;return t===0?[0,[]]:t===1&&e[0]===w?[0,[]]:Array.isArray(e[0])?t===1?[1,[e[0]]]:[t,e]:[1,[[...e]]]}var pe=1,ye=2;function Ie(e){let t=0;if(!Array.isArray(e))return t;for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"?r.charCodeAt(0)===46&&(t|=pe):N(r)&&(t|=ye)}return t}function We(e,t){if(!t)return[e];let n=[],r=null;for(let i of e){if(N(i)){r&&n.push(r),r=null,n.push(i);continue}r||(r=[]),r.push(i)}return r&&n.push(r),n}function E(e=[]){if(te(e))return{address:w,isMarker:!0,length:0,path:[],children:null,chunks:null,type:L};let[t,n]=de(e),r=t===1?x:H,i=t===1?n[0]:n,o=t>1?n.map(f=>E(f)):null,s=r===x?Ie(i):0,c=r===x?(s&pe)!==0:o.some(f=>ae(f)),u=r;return c&&(u|=G),{address:r===x?he(i):null,isMarker:!0,length:t,path:i,children:o,chunks:r===x?We(i,(s&ye)!==0):null,type:u}}function a(e,t){if(t.length===0)return e;let[n,r]=de(t);if(C(e))return E(r,e.state);if(ee(e)){if(n===0)return e;if(n===1){let i=[...e.path,...r[0]];return E(i,e.state)}else{let i=r.map(o=>[...e.path,...o]);return E(i,e.state)}}if(M(e)){let i=new Array(e.length),o=0;for(;o<e.length;)i[o]=a(e.children[o],t),o++;let s=[];for(o=0;o<i.length;){let c=i[o];if(ee(c))s.push(c.path);else if(M(c)){let u=0;for(;u<c.length;)s.push(c.children[u].path),u++}o++}return E(s,e.state)}return e}function d(e,{global:t,path:n,ephemeral:r,error:i}){try{if(!e.isMarker)return;if(C(e))return t?t(e):void 0;if(ae(e))return r?r(e):n?n(e):void 0;if(ee(e))return n?n(e):void 0;if(M(e)){let o=new Array(e.length),s=0;for(;s<e.length;){let c=e.children[s];o[s]=d(c,{global:t,path:n,ephemeral:r,error:i}),s++}return o}return}catch(o){return i?i(o.message):void 0}}function me(e,t){return C(e)&&C(t)?_:C(t)?R:!e.address||!t.address?V:e.address===t.address?_:e.address.startsWith(t.address+".")?R:t.address.startsWith(e.address+".")?ue:V}var j=[null,null,(e,t)=>e?.[t[0]]?.[t[1]],(e,t)=>e?.[t[0]]?.[t[1]]?.[t[2]],(e,t)=>e?.[t[0]]?.[t[1]]?.[t[2]]?.[t[3]],(e,t)=>e?.[t[0]]?.[t[1]]?.[t[2]]?.[t[3]]?.[t[4]],(e,t)=>e?.[t[0]]?.[t[1]]?.[t[2]]?.[t[3]]?.[t[4]]?.[t[5]],(e,t)=>e?.[t[0]]?.[t[1]]?.[t[2]]?.[t[3]]?.[t[4]]?.[t[5]]?.[t[6]],(e,t)=>e?.[t[0]]?.[t[1]]?.[t[2]]?.[t[3]]?.[t[4]]?.[t[5]]?.[t[6]]?.[t[7]]];function Pe(e){let n="obj"+Array.from({length:e},(i,o)=>`?.[path[${o}]]`).join(""),r=new Function("obj","path",`return ${n}`);return j[e]=r,r}function p(e,t){let n=t.length;return n===0?e:n===1?e[t[0]]:n<j.length&&j[n]||j[n]?j[n](e,t):Pe(n)(e,t)}function l(e){return typeof e=="number"?[]:{}}var B=[null,null,(e,t,n)=>{let[r,i]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=n,n},(e,t,n)=>{let[r,i,o]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=i in e[r]?e[r][i]:l(o),e[r][i][o]=n,n},(e,t,n)=>{let[r,i,o,s]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=i in e[r]?e[r][i]:l(o),e[r][i][o]=o in e[r][i]?e[r][i][o]:l(s),e[r][i][o][s]=n,n},(e,t,n)=>{let[r,i,o,s,c]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=i in e[r]?e[r][i]:l(o),e[r][i][o]=o in e[r][i]?e[r][i][o]:l(s),e[r][i][o][s]=s in e[r][i][o]?e[r][i][o][s]:l(c),e[r][i][o][s][c]=n,n},(e,t,n)=>{let[r,i,o,s,c,u]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=i in e[r]?e[r][i]:l(o),e[r][i][o]=o in e[r][i]?e[r][i][o]:l(s),e[r][i][o][s]=s in e[r][i][o]?e[r][i][o][s]:l(c),e[r][i][o][s][c]=c in e[r][i][o][s]?e[r][i][o][s][c]:l(u),e[r][i][o][s][c][u]=n,n},(e,t,n)=>{let[r,i,o,s,c,u,f]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=i in e[r]?e[r][i]:l(o),e[r][i][o]=o in e[r][i]?e[r][i][o]:l(s),e[r][i][o][s]=s in e[r][i][o]?e[r][i][o][s]:l(c),e[r][i][o][s][c]=c in e[r][i][o][s]?e[r][i][o][s][c]:l(u),e[r][i][o][s][c][u]=u in e[r][i][o][s][c]?e[r][i][o][s][c][u]:l(f),e[r][i][o][s][c][u][f]=n,n},(e,t,n)=>{let[r,i,o,s,c,u,f,h]=t;return e[r]=r in e?e[r]:l(i),e[r][i]=i in e[r]?e[r][i]:l(o),e[r][i][o]=o in e[r][i]?e[r][i][o]:l(s),e[r][i][o][s]=s in e[r][i][o]?e[r][i][o][s]:l(c),e[r][i][o][s][c]=c in e[r][i][o][s]?e[r][i][o][s][c]:l(u),e[r][i][o][s][c][u]=u in e[r][i][o][s][c]?e[r][i][o][s][c][u]:l(f),e[r][i][o][s][c][u][f]=f in e[r][i][o][s][c][u]?e[r][i][o][s][c][u][f]:l(h),e[r][i][o][s][c][u][f][h]=n,n}];function ve(e){let t=Array.from({length:e},(s,c)=>`v${c}`),r=`const [${t.join(", ")}] = path;
2
+ `,i="state";for(let s=0;s<e-1;s++){let c=t[s],u=t[s+1];r+=`${i}[${c}] = (${i}[${c}] !== undefined && typeof ${i}[${c}] === 'object') ? ${i}[${c}] : createNodeType(${u});
3
+ `,i+=`[${c}]`}r+=`${i}[${t[e-1]}] = value;
4
+ return state;`;let o=new Function("state","path","value","createNodeType",r);return B[e]=(s,c,u)=>o(s,c,u,l),B[e]}function U(e,t,n){let r=t.length;return r===0?Object.assign(e,n):r===1?e[t[0]]=n:B[r]?B[r](e,t,n):ve(r)(e,t,n)}function ge(e,t){let n=t.length;if(n===0)return;if(n===1){let c=e[t[0]];return Array.isArray(e)?e.splice(t[0],1):delete e[t[0]],c}let r=t.slice(0,-1),i=t[n-1],o=p(e,r);if(!o)return;let s=o[i];return Array.isArray(o)?o.splice(i,1):delete o[i],s}function D(e,t){let n=Object.keys(e),r=0;for(;r<n.length;)delete e[n[r]],r++;let i=Object.keys(t);for(r=0;r<i.length;){let o=i[r],s=t[o];s&&typeof s=="object"&&!Array.isArray(s)?(e[o]=e[o]||{},D(e[o],s)):e[o]=s,r++}return e}function Ae(e){let t=Object.keys(e);for(let n of t)delete e[n];return e}function be(e){let t=typeof e;return e==null||t==="string"||t==="number"||t==="boolean"||t==="bigint"||t==="symbol"||t==="function"}var F=e=>structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e));function $(e,t){return e!==null&&typeof e=="object"&&Object.keys(t).every(n=>e[n]===t[n])}function we(e,t){let n=t.length,r=e,i=0;for(;i<n;){if(r==null)return;let o=t[i];if(Array.isArray(o))r=p(r,o);else if(Array.isArray(r))r=r.find(s=>$(s,o));else return;i++}return r}function g(e,t,{addMissing:n=!1}={}){let r=t.length;if(r===1&&Array.isArray(t[0]))return t[0];let i=[],o=e,s=0;for(;s<r;){let c=t[s];if(Array.isArray(c))i.push(...c),o=o==null?void 0:p(o,c);else{let u=s===r-1;if(o===void 0&&u&&n)return i.push(0),i;if(!Array.isArray(o))return;let f=o.findIndex(h=>$(h,c));if(f===-1)return u&&n?(i.push(o.length),i):void 0;i.push(f),o=o[f]}s++}return i}function A(e,t){return t===e.path?e:{...e,resolved:t}}function Le(e){return Array.isArray(e)?[...e]:typeof e=="object"&&e!==null?{...e}:e}function y(e,t,n){let r=!1;try{return d(t,{global:()=>(r=!0,e),path:({chunks:i})=>(r=!0,we(e,i))})}catch(i){console.error(i);return}finally{r&&n&&n(t)}}function I(e,t,n,r,i){let o,s=!1,c=t;try{return d(t,{global:()=>(o={...e},e=D(e,n),s=!0,n),path:u=>{let f=g(e,u.chunks,{addMissing:!0});if(f!==void 0)return o=Le(p(e,f)),U(e,f,n),c=A(u,f),s=!0,n}})}catch(u){console.error(u);return}finally{s&&i&&i(c,r,n,o)}}function re(e,t,n,r){let i,o=!1,s=t,c=!1;try{return d(t,{global:()=>(i=e,e=D(e,{}),o=!0,i),path:u=>{let f=g(e,u.chunks);if(f===void 0){c=!0;return}return i=ge(e,f),s=A(u,f),o=!0,i}})}catch(u){console.error(u);return}finally{r&&!c&&r(s,n,void 0,i)}}function xe(e,t,n,r,i){let o,s,c=!1,u=t;try{return d(t,{global:()=>(o=e,s=n(e),e=D(e,s),c=!0,s),path:f=>{let h=g(e,f.chunks,{addMissing:!0});if(h===void 0)return;o=te(h)?e:p(e,h);let m=be(o)?o:F(o);return s=n(m),U(e,h,s),u=A(f,h),c=!0,s}})}catch(f){console.error(f);return}finally{c&&i&&i(u,r,s,o)}}function ne(e,t){let n=p(e,t);if(n===void 0)n=[],U(e,t,n);else if(!Array.isArray(n))throw new TypeError(`Expected array at path "${t.join(".")}", got ${typeof n}`);return n}function W(e,t,n,r,i){let o=!1,s=t;try{return d(t,{path:c=>{let u=g(e,c.chunks);return u===void 0?void 0:(s=A(c,u),ne(e,u).push(n),o=!0,n)}})}catch(c){console.error(c);return}finally{o&&i&&i(s,r,n,void 0)}}function P(e,t,n,r,i){let o=!1,s=t;try{return d(t,{path:c=>{let u=g(e,c.chunks);return u===void 0?void 0:(s=A(c,u),ne(e,u).unshift(n),o=!0,n)}})}catch(c){console.error(c);return}finally{o&&i&&i(s,r,n,void 0)}}function ie(e,t,n,r,i){let o,s=!1,c=t;try{return d(t,{path:u=>{let f=g(e,u.chunks);return f===void 0?void 0:(c=A(u,f),o=ne(e,f).splice(...n),s=!0,o)}})}catch(u){console.error(u);return}finally{s&&i&&i(c,r,n,o)}}function oe(e,t){if(!(e&&e[0]==="."))return t}function q(e,t=oe,n=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>q(i,t));let r={};for(let i of Object.keys(e)){let o=t(i,e[i]);typeof o<"u"&&(r[i]=q(o,t,i))}return r}import{encode as He,decode as Ge}from"cbor-x";var Q=new Uint8Array([74,83,67,50]),J=2;function Ee(e){let n="";for(let r=0;r<e.length;r+=8192){let i=e.slice(r,r+8192);n+=String.fromCharCode(...i)}return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ce(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),r=atob(n),i=new Uint8Array(r.length);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return i}function z(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e[n]>>>0;return t}function K(e,t,n=0){return new DataView(t.buffer,t.byteOffset+n,4).setUint32(0,e,!0),n+4}function X(e,t=0){return new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0)}function Te(e,t,n=0){return new DataView(t.buffer,t.byteOffset+n,2).setUint16(0,e,!0),n+2}function Oe(e,t=0){return new DataView(e.buffer,e.byteOffset+t,2).getUint16(0,!0)}function Se(e,t,n=0){return t[n]=e,n+1}function ke(e,t=0){return e[t]}function je(e){return He(e)}function $e(e){return[Ge(e),e.length]}async function se(e,{replacer:t=oe}={}){let n=q(e,t),r=je(n),i=4+r.length,o=new Uint8Array(i),s=0;s=K(r.length,o,s),o.set(r,s);let c=z(o),u=15,f=new Uint8Array(u+o.length);return f.set(Q,0),Te(J,f,4),Se(0,f,6),K(c,f,7),K(o.length,f,11),f.set(o,15),Ee(f)}async function _e(e,t){let n=Ce(e);if(n.length<15)throw new Error("Invalid capsule: too short");for(let b=0;b<4;b++)if(n[b]!==Q[b])throw new Error("Invalid capsule: bad magic");let r=Oe(n,4);if(r!==J)throw new Error(`Unsupported capsule version: ${r}`);let i=ke(n,6),o=X(n,7),s=X(n,11);if(s<0)throw new Error("Invalid capsule: negative payload length");if(n.length!==15+s)throw new Error("Invalid capsule: length mismatch");let c=n.slice(15),u=z(c);if(o!==u)throw new Error("Integrity check failed: checksum mismatch");let f=0,h=X(c,f);if(f+=4,f+h>c.length)throw new Error(`Data length ${h} exceeds payload bounds at offset ${f}`);let[m]=$e(c.slice(f,f+h));return t&&t(m),{data:m,meta:{version:r,flags:i,bytes:n.length,checksum:u.toString(16)}}}function Be(e,t,n){switch(t){case"is":case"===":case"==":return e===n;case"not":case"!==":case"!=":return e!==n;case"includes":return Array.isArray(e)&&e.includes(n);case"has":return typeof e=="object"&&e!==null&&Object.values(e).includes(n);case"in":return typeof e=="object"&&e!==null&&n in e;case"gt":case">":return e>n;case"lt":case"<":return e<n;case"gte":case">=":return e>=n;case"lte":case"<=":return e<=n;default:throw new Error(`Unknown matcher: ${t}`)}}function Y(e,t,n,r,i=[],o=!1){let s=[];if(e===null||typeof e!="object")return s;for(let[c,u]of Object.entries(e)){if(c===t&&Be(u,n,r)&&(s.push([...i,c]),!o))return s;if(typeof u=="object"&&u!==null)if(Array.isArray(u))for(let f=0;f<u.length;f++){let h=u[f];if(h&&typeof h=="object"){let m=Y(h,t,n,r,[...i,c,f],o);if(s.push(...m),!o&&s.length>0)return s}}else{let f=Y(u,t,n,r,[...i,c],o);if(s.push(...f),!o&&s.length>0)return s}}return s}function Re(e,t,n="is",r){return Y(e,t,n,r,[],!1)?.[0]}function Ne(e,t,n="is",r){return Y(e,t,n,r,[],!0)}var Xt={[S]:O,[O]:S,[k]:k};function Me(e,t){return t===void 0?S:e===void 0?O:k}function Z(e,t,n,r,i){return d(e,{global:()=>({path:w,method:t,operation:Me(n,r),from:r,to:n}),path:o=>{let s={path:o.path,method:t,operation:Me(n,r),from:r,to:n};return i&&(s.query=i),o.resolved&&(s.resolved=o.resolved),s}})}function Ue(e){return Array.isArray(e)?[...e]:e!==null&&typeof e=="object"?{...e}:e}var v=class e{#e;#t;#o=0;#f=0;#s=0;#i=null;#u=!1;#r;#n;#l=new Map;#h;static create(t={}){return new e(t)}constructor(t,n=null,r=null,i=null,o=null){this.#h=o||this,this.#e=t,this.#r=r||this.#p(),this.#n=i||this.#g(),this.#t=n||E(),this.#o=0}install(...t){let n=new Map;for(let r of t){if(this.#l.has(r.name)){console.warn(`Plugin "${r.name}" already installed`);continue}if(!r.install){console.warn(`Plugin "${r.name}" does not have an install function`);continue}let i=r.install(this);if(this.#l.set(r.name,i),i.initialize&&n.set(r.name,()=>i.initialize(this,i.options)),i.actions){let o=i.actions(this,i.options);Object.defineProperty(this,r.name,{value:o,writable:!1,enumerable:!0,configurable:!1})}}return n.forEach(r=>r()),this}get batching(){return this.#o>0}get(...t){return y(this.#e,a(this.#t,t),this.#n)}clone(...t){let n=y(this.#e,a(this.#t,t),this.#n);if(typeof n=="object"&&n!==null)try{return F(n)}catch{return console.warn(`Failed to clone data: ${n}`),n}return n}has(...t){let n=a(this.#t,t);return d(n,{global:()=>{},path:r=>y(this.#e,r,this.#n)!==void 0})}keys(...t){let n=a(this.#t,t);return d(n,{global:()=>Object.keys(this.#e),path:r=>Object.keys(y(this.#e,r,this.#n)||{})})}typeof(...t){let n=a(this.#t,t);return d(n,{global:()=>{},path:({path:i})=>typeof y(this.#e,i,this.#n)})}findWhere(t,n="is",r){return Re(y(this.#e,this.#t,null),t,n,r)}findAllWhere(t,n="is",r){return Ne(y(this.#e,this.#t,null),t,n,r)}set(...t){let n=t.pop(),r=a(this.#t,t);return I(this.#e,r,n,"set",this.#r)}update(...t){let n=t.pop(),r=a(this.#t,t);return xe(this.#e,r,n,"update",this.#r)}updateEach(...t){let n=t.pop(),r=a(this.#t,t),i=y(this.#e,r,this.#n);if(i===null||typeof i!="object")return;let o;if(Array.isArray(i)){o=[];for(let s=0;s<i.length;s++){let c=n(Ue(i[s]),s);c!==void 0&&o.push(c)}}else{o={};for(let s of Object.keys(i)){let c=n(Ue(i[s]),s);c!==void 0&&(o[s]=c)}}return I(this.#e,r,o,"updateEach",this.#r)}apply(t){for(let n of t){let{path:r,operation:i,method:o,to:s,query:c}=n;if(o==="addWhere"||o==="addFirstWhere"){this.#a([r],c,s,"apply",o==="addWhere"?W:P);continue}let u=a(this.#t,r);switch(i){case S:case k:if(o==="push")W(this.#e,u,s,"apply",this.#r);else if(o==="unshift")P(this.#e,u,s,"apply",this.#r);else if(o==="splice")ie(this.#e,u,s,"apply",this.#r);else if(o==="removeMatch"){let f=y(this.#e,u,this.#n);if(Array.isArray(f)){let h=JSON.stringify(s),m=f.findIndex(b=>JSON.stringify(b)===h);m!==-1&&f.splice(m,1)}}else I(this.#e,u,s,"apply",this.#r);break;case O:re(this.#e,u,"apply",this.#r);break}}}load(t){return I(this.#e,this.#t,t,"load",this.#r),this}remove(...t){let n=a(this.#t,t);return re(this.#e,n,"remove",this.#r)}push(...t){let n=t.pop(),r=a(this.#t,t);return W(this.#e,r,n,"push",this.#r)}unshift(...t){let n=t.pop(),r=a(this.#t,t);return P(this.#e,r,n,"unshift",this.#r)}splice(t,...n){let r=a(this.#t,Array.isArray(t[0])?t:[t]);return ie(this.#e,r,n,"splice",this.#r)}addWhere(t,n,r){return this.#a(t,n,r,"addWhere",W)}addFirstWhere(t,n,r){return this.#a(t,n,r,"addFirstWhere",P)}#a(t,n,r,i,o){let s=a(this.#t,t),c=y(this.#e,s,this.#n),u=Array.isArray(c)?c.find(f=>$(f,n)):void 0;return u!==void 0?u:o(this.#e,s,r,i,(f,h,m,b)=>this.#r(f,h,m,b,n))}setWhere(t,n,r,i){let o=this.findWhere(t,n,r);return o===void 0?void 0:this.set(o.slice(0,-1),i)}updateWhere(t,n,r,i){let o=this.findWhere(t,n,r);return o===void 0?void 0:this.update(o.slice(0,-1),i)}removeWhere(t,n,r){let i=this.findWhere(t,n,r);return i===void 0?void 0:this.remove(i.slice(0,-1))}setAllWhere(t,n,r,i){let o=this.findAllWhere(t,n,r);return this.batch(()=>{for(let s of o)this.set(s.slice(0,-1),i)})}updateAllWhere(t,n,r,i){let o=this.findAllWhere(t,n,r);return this.batch(()=>{for(let s of o)this.update(s.slice(0,-1),i)})}removeAllWhere(t,n,r){let i=this.findAllWhere(t,n,r);return this.batch(()=>{for(let o=i.length-1;o>=0;o--)this.remove(i[o].slice(0,-1))})}async export(...t){try{let n=a(this.#t,t),r=d(n,{global:async()=>await se(this.#e),path:async i=>await se(y(this.#e,i,this.#n))});return Array.isArray(r)?await Promise.all(r):await r}catch(n){throw console.trace(`Failed to export state: ${n.message}`),n}}async import(t){try{let{data:n}=await _e(t);return this.load(n),this}catch(n){throw console.trace(`Failed to import state: ${n.message}`),n}}reset(){Ae(this.#e);for(let t of this.#l.values())t.reset&&t.reset();this.#r=this.#p(),this.#t=E([],this),this.#o=0,this.#f=0,this.#s=0,this.#i=null,this.#u=!1}ref(...t){let n=a(this.#t,t);return new e(this.#e,n,this.#r,this.#n,this.#h)}batch(t){return this.#o++,this.#c("onBatchStart",this.batching),t?(t(this),this.endBatch()):()=>this.endBatch()}endBatch(){return this.#o--,this.#o===0&&this.#c("onBatchEnd"),this}silent(t){return this.#f++,t?(t(this),this.endSilent()):()=>this.endSilent()}endSilent(){return this.#f--,this}quiet(t,n){if(!Array.isArray(t))throw new TypeError(`quiet: name the path its writes fall under, as in quiet(["nodeGraph"], (state) => \u2026). Use [] for the whole state, or a ref's own path.`);let r=t.length===0?this.#t:a(this.#t,[t]);if(this.#h.#y(r),!n)return()=>this.endQuiet();try{n(this)}finally{this.endQuiet()}return this}endQuiet(){return this.#h.#m(),this}#y(t){if(this.#s>0&&!this.#d(t))throw new Error(`quiet: "${t.address}" isn't inside the quiet already open at "${this.#i.address}". Nest a quiet only under its parent's path.`);this.#s===0&&(this.#i=t,this.#u=!1),this.#s++}#m(){if(this.#s--,this.#s>0)return;let t=this.#i,n=this.#u;if(this.#i=null,this.#u=!1,!n)return;if(C(t)){this.#c("onStateChange",t,Z(t,"quiet",this.#e),!1);return}let r=g(this.#e,t.chunks),i=r===void 0?t:A(t,r),o=r===void 0?void 0:p(this.#e,r),s=Z(i,"quiet",o);o===void 0&&(s.operation=O),this.#c("onStateChange",i,s,!1)}#d(t){let n=this.#i;if(C(n))return!0;if(M(t))return t.children.every(i=>this.#d(i));let r=me(t,n);return r===_||r===R}#p(){return(t,n,r=void 0,i=void 0,o)=>{if(!(this.#f>0)){if(this.#i&&this.#d(t)){this.#u=!0;return}if(this.#c("onStateChange",t,Z(t,n,r,i,o),this.batching),this.#i)throw new Error(`quiet: a write to "${t.address}" falls outside the quiet path "${this.#i.address}". It was made, and reported on its own; write only under the quiet path, or name a wider one.`)}}}#g(){return t=>this.#c("onStateAccess",t)}#c(t,...n){for(let r of this.#l.values())typeof r[t]=="function"&&r[t](...n)}},Fe=(...e)=>v.create(...e),qe=e=>e instanceof v;var ce=class{static name=null;static options={};static configure(t){return t={...this.options,...t},{install:n=>this.install(n,t),name:this.name,options:t}}static install(t,n){n={...this.options,...n};let r=new this(t,n);return Object.defineProperty(r,"state",{value:t,writable:!1,configurable:!1}),Object.defineProperty(r,"options",{value:n,writable:!1,configurable:!1}),r}};function Qe(e){globalThis[T]||(globalThis[T]=e)}function Je(){return globalThis[T]!==void 0}function ze(e){globalThis[T]=e}function Ke(){return globalThis[T]||null}function Xe(){return Ke()}function Ye(){globalThis[T]=void 0}export{ce as Plugin,v as State,Ye as clearState,Fe as createState,ze as forceState,Je as hasState,qe as isState,Qe as provideState,Xe as useState};
5
5
  //# sourceMappingURL=main.js.map