fetchium 0.3.0 → 0.3.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/cjs/development/QueryClient-BefSCMoE.js +2 -0
  3. package/dist/cjs/development/{QueryClient-QKhS8mhg.js.map → QueryClient-BefSCMoE.js.map} +1 -1
  4. package/dist/cjs/development/index.js +1 -1
  5. package/dist/cjs/{production/mutation-CgS9gXW7.js → development/mutation-OJNwoJcf.js} +2 -2
  6. package/dist/cjs/{production/mutation-CgS9gXW7.js.map → development/mutation-OJNwoJcf.js.map} +1 -1
  7. package/dist/cjs/development/react/index.js +1 -1
  8. package/dist/cjs/development/rest/index.js +1 -1
  9. package/dist/cjs/development/topic/index.js +1 -1
  10. package/dist/cjs/production/QueryClient-rbPYznie.js +2 -0
  11. package/dist/cjs/production/{QueryClient-DIAqDTHF.js.map → QueryClient-rbPYznie.js.map} +1 -1
  12. package/dist/cjs/production/index.js +1 -1
  13. package/dist/cjs/{development/mutation-w67Vpuvw.js → production/mutation-CjSajlTU.js} +2 -2
  14. package/dist/cjs/{development/mutation-w67Vpuvw.js.map → production/mutation-CjSajlTU.js.map} +1 -1
  15. package/dist/cjs/production/react/index.js +1 -1
  16. package/dist/cjs/production/rest/index.js +1 -1
  17. package/dist/cjs/production/topic/index.js +1 -1
  18. package/dist/esm/EntityInstance.d.ts.map +1 -1
  19. package/dist/esm/development/{QueryClient-C9tBdK1Z.js → QueryClient-DfxP7pt2.js} +511 -514
  20. package/dist/esm/development/{QueryClient-C9tBdK1Z.js.map → QueryClient-DfxP7pt2.js.map} +1 -1
  21. package/dist/esm/development/index.js +2 -2
  22. package/dist/esm/development/{mutation-Dx63NCGk.js → mutation-DZAq7Pbu.js} +2 -2
  23. package/dist/esm/development/{mutation-Dx63NCGk.js.map → mutation-DZAq7Pbu.js.map} +1 -1
  24. package/dist/esm/development/react/index.js +1 -1
  25. package/dist/esm/development/rest/index.js +2 -2
  26. package/dist/esm/development/topic/index.js +1 -1
  27. package/dist/esm/production/{QueryClient-D64xo0EA.js → QueryClient-DrWSXg0y.js} +408 -409
  28. package/dist/esm/production/{QueryClient-D64xo0EA.js.map → QueryClient-DrWSXg0y.js.map} +1 -1
  29. package/dist/esm/production/index.js +2 -2
  30. package/dist/esm/production/{mutation-Aw1JE7VO.js → mutation-B8dmX5lz.js} +2 -2
  31. package/dist/esm/production/{mutation-Aw1JE7VO.js.map → mutation-B8dmX5lz.js.map} +1 -1
  32. package/dist/esm/production/react/index.js +1 -1
  33. package/dist/esm/production/rest/index.js +2 -2
  34. package/dist/esm/production/topic/index.js +1 -1
  35. package/package.json +3 -3
  36. package/dist/cjs/development/QueryClient-QKhS8mhg.js +0 -2
  37. package/dist/cjs/production/QueryClient-DIAqDTHF.js +0 -2
@@ -1,6 +1,6 @@
1
- import { A as r, E as s, G as t, L as o, a as n, M as i, N as M, b as g, c as u, d as y, e as f, Q as C, f as N, g as Q, h as d, R as k, i as l, j as p, k as m, q as E, r as R, t as w } from "./QueryClient-D64xo0EA.js";
1
+ import { A as r, E as s, G as t, L as o, a as n, M as i, N as M, b as g, c as u, d as y, e as f, Q as C, f as N, g as Q, h as d, R as k, i as l, j as p, k as m, q as E, r as R, t as w } from "./QueryClient-DrWSXg0y.js";
2
2
  import { Q as F } from "./QueryAdapter-Bu5UJjE4.js";
3
- import { M as A, g as K, m as Y } from "./mutation-Aw1JE7VO.js";
3
+ import { M as A, g as K, m as Y } from "./mutation-B8dmX5lz.js";
4
4
  export {
5
5
  r as ARRAY_KEY,
6
6
  s as Entity,
@@ -1,5 +1,5 @@
1
1
  import { getContext as h } from "signalium";
2
- import { l as y, h as D, m as w, V as u, t as d } from "./QueryClient-D64xo0EA.js";
2
+ import { l as y, h as D, m as w, V as u, t as d } from "./QueryClient-DrWSXg0y.js";
3
3
  class x {
4
4
  static adapter;
5
5
  params;
@@ -55,4 +55,4 @@ export {
55
55
  S as g,
56
56
  C as m
57
57
  };
58
- //# sourceMappingURL=mutation-Aw1JE7VO.js.map
58
+ //# sourceMappingURL=mutation-B8dmX5lz.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mutation-Aw1JE7VO.js","sources":["../../../src/mutation.ts"],"sourcesContent":["import { getContext, ReactiveTask } from 'signalium';\nimport { ExtractType, InternalTypeDef, MutationEffects, TypeDef, RetryConfig, TypeDefShape } from './types.js';\nimport { QueryClientContext, type QueryContext } from './QueryClient.js';\nimport { ValidatorDef, t } from './typeDefs.js';\nimport { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.js';\nimport type { QueryAdapter, QueryAdapterClass } from './QueryAdapter.js';\n\n// ================================\n// Mutation Definition Types\n// ================================\n\nexport interface MutationConfigOptions {\n retry?: RetryConfig | number | false;\n}\n\nexport interface MutationDefinition<Request, Response> {\n id: string;\n requestShape: InternalTypeDef;\n responseShape: InternalTypeDef | undefined;\n captured: CapturedDefinition<Mutation>;\n optimisticUpdates: boolean;\n config?: MutationConfigOptions;\n effects?: MutationEffects;\n hasGetEffects: boolean;\n adapterClass: QueryAdapterClass;\n}\n\n// ================================\n// Mutation base class\n// ================================\n\nexport abstract class Mutation {\n static adapter?: QueryAdapterClass;\n\n readonly params?: TypeDefShape;\n readonly result?: TypeDefShape;\n readonly optimisticUpdates?: boolean;\n readonly config?: MutationConfigOptions;\n readonly effects?: Readonly<MutationEffects>;\n\n declare context: QueryContext;\n\n abstract getIdentityKey(): unknown;\n\n getEffects?(): MutationEffects;\n\n constructor() {\n return createDefinitionProxy(this);\n }\n}\n\n// ================================\n// Mutation definition cache and lookup\n// ================================\n\nconst mutationDefCache = new WeakMap<new () => Mutation, () => MutationDefinition<any, any>>();\n\nexport const mutationKeyForClass = (cls: new () => Mutation): string => {\n const getMutationDef = mutationDefCache.get(cls);\n\n if (getMutationDef === undefined) {\n throw new Error('Mutation definition not found');\n }\n\n return getMutationDef().id;\n};\n\n// ================================\n// Internal: build mutation definition from class\n// ================================\n\nfunction buildMutationDefinition(MutationClass: new () => Mutation): () => MutationDefinition<any, any> {\n let cached = mutationDefCache.get(MutationClass);\n\n if (cached !== undefined) {\n return cached;\n }\n\n let mutationDefinition: MutationDefinition<any, any> | undefined;\n\n const getter = (): MutationDefinition<any, any> => {\n if (mutationDefinition !== undefined) {\n return mutationDefinition;\n }\n\n const instance = new MutationClass();\n const captured = extractDefinition(instance);\n const { fields } = captured;\n\n const id = `mutation:${String(captured.methods.getIdentityKey.call(fields))}`;\n\n const requestDef = fields.params ?? {};\n const requestShape = (requestDef instanceof ValidatorDef\n ? requestDef\n : t.object(requestDef)) as unknown as InternalTypeDef;\n const responseDef = fields.result;\n const responseShape =\n responseDef !== undefined\n ? ((responseDef instanceof ValidatorDef ? responseDef : t.object(responseDef)) as unknown as InternalTypeDef)\n : undefined;\n\n const adapterClass = (MutationClass as typeof Mutation).adapter;\n if (!adapterClass) {\n throw new Error(\n `Mutation class \"${MutationClass.name}\" must define a static \\`adapter\\` property. ` +\n `Extend RESTMutation (from fetchium/rest) or set \\`static adapter = MyAdapter\\` on your mutation class.`,\n );\n }\n\n mutationDefinition = {\n id,\n requestShape,\n responseShape,\n captured,\n optimisticUpdates: fields.optimisticUpdates ?? false,\n config: fields.config,\n effects: fields.effects,\n hasGetEffects: typeof captured.methods.getEffects === 'function',\n adapterClass,\n };\n\n return mutationDefinition;\n };\n\n mutationDefCache.set(MutationClass, getter);\n return getter;\n}\n\n// ================================\n// Public API\n// ================================\n\nexport function getMutation<T extends Mutation>(\n MutationClass: new () => T,\n): ReactiveTask<Readonly<ExtractType<T['result']>>, [ExtractType<T['params']>]> {\n const getMutationDef = buildMutationDefinition(MutationClass);\n\n const queryClient = getContext(QueryClientContext);\n\n if (queryClient === undefined) {\n throw new Error('QueryClient not found');\n }\n\n return queryClient.getMutation<any, any>(getMutationDef());\n}\n"],"names":["Mutation","createDefinitionProxy","mutationDefCache","mutationKeyForClass","cls","getMutationDef","buildMutationDefinition","MutationClass","cached","mutationDefinition","getter","instance","captured","extractDefinition","fields","id","requestDef","requestShape","ValidatorDef","t","responseDef","responseShape","adapterClass","getMutation","queryClient","getContext","QueryClientContext"],"mappings":";;AA+BO,MAAeA,EAAS;AAAA,EAC7B,OAAO;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAQT,cAAc;AACZ,WAAOC,EAAsB,IAAI;AAAA,EACnC;AACF;AAMA,MAAMC,wBAAuB,QAAA,GAEhBC,IAAsB,CAACC,MAAoC;AACtE,QAAMC,IAAiBH,EAAiB,IAAIE,CAAG;AAE/C,MAAIC,MAAmB;AACrB,UAAM,IAAI,MAAM,+BAA+B;AAGjD,SAAOA,IAAiB;AAC1B;AAMA,SAASC,EAAwBC,GAAuE;AACtG,MAAIC,IAASN,EAAiB,IAAIK,CAAa;AAE/C,MAAIC,MAAW;AACb,WAAOA;AAGT,MAAIC;AAEJ,QAAMC,IAAS,MAAoC;AACjD,QAAID,MAAuB;AACzB,aAAOA;AAGT,UAAME,IAAW,IAAIJ,EAAA,GACfK,IAAWC,EAAkBF,CAAQ,GACrC,EAAE,QAAAG,MAAWF,GAEbG,IAAK,YAAY,OAAOH,EAAS,QAAQ,eAAe,KAAKE,CAAM,CAAC,CAAC,IAErEE,IAAaF,EAAO,UAAU,CAAA,GAC9BG,IAAgBD,aAAsBE,IACxCF,IACAG,EAAE,OAAOH,CAAU,GACjBI,IAAcN,EAAO,QACrBO,IACJD,MAAgB,SACVA,aAAuBF,IAAeE,IAAcD,EAAE,OAAOC,CAAW,IAC1E,QAEAE,IAAgBf,EAAkC;AACxD,QAAI,CAACe;AACH,YAAM,IAAI;AAAA,QACR,mBAAmBf,EAAc,IAAI;AAAA,MAAA;AAKzC,WAAAE,IAAqB;AAAA,MACnB,IAAAM;AAAA,MACA,cAAAE;AAAA,MACA,eAAAI;AAAA,MACA,UAAAT;AAAA,MACA,mBAAmBE,EAAO,qBAAqB;AAAA,MAC/C,QAAQA,EAAO;AAAA,MACf,SAASA,EAAO;AAAA,MAChB,eAAe,OAAOF,EAAS,QAAQ,cAAe;AAAA,MACtD,cAAAU;AAAA,IAAA,GAGKb;AAAA,EACT;AAEA,SAAAP,EAAiB,IAAIK,GAAeG,CAAM,GACnCA;AACT;AAMO,SAASa,EACdhB,GAC8E;AAC9E,QAAMF,IAAiBC,EAAwBC,CAAa,GAEtDiB,IAAcC,EAAWC,CAAkB;AAEjD,MAAIF,MAAgB;AAClB,UAAM,IAAI,MAAM,uBAAuB;AAGzC,SAAOA,EAAY,YAAsBnB,GAAgB;AAC3D;"}
1
+ {"version":3,"file":"mutation-B8dmX5lz.js","sources":["../../../src/mutation.ts"],"sourcesContent":["import { getContext, ReactiveTask } from 'signalium';\nimport { ExtractType, InternalTypeDef, MutationEffects, TypeDef, RetryConfig, TypeDefShape } from './types.js';\nimport { QueryClientContext, type QueryContext } from './QueryClient.js';\nimport { ValidatorDef, t } from './typeDefs.js';\nimport { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.js';\nimport type { QueryAdapter, QueryAdapterClass } from './QueryAdapter.js';\n\n// ================================\n// Mutation Definition Types\n// ================================\n\nexport interface MutationConfigOptions {\n retry?: RetryConfig | number | false;\n}\n\nexport interface MutationDefinition<Request, Response> {\n id: string;\n requestShape: InternalTypeDef;\n responseShape: InternalTypeDef | undefined;\n captured: CapturedDefinition<Mutation>;\n optimisticUpdates: boolean;\n config?: MutationConfigOptions;\n effects?: MutationEffects;\n hasGetEffects: boolean;\n adapterClass: QueryAdapterClass;\n}\n\n// ================================\n// Mutation base class\n// ================================\n\nexport abstract class Mutation {\n static adapter?: QueryAdapterClass;\n\n readonly params?: TypeDefShape;\n readonly result?: TypeDefShape;\n readonly optimisticUpdates?: boolean;\n readonly config?: MutationConfigOptions;\n readonly effects?: Readonly<MutationEffects>;\n\n declare context: QueryContext;\n\n abstract getIdentityKey(): unknown;\n\n getEffects?(): MutationEffects;\n\n constructor() {\n return createDefinitionProxy(this);\n }\n}\n\n// ================================\n// Mutation definition cache and lookup\n// ================================\n\nconst mutationDefCache = new WeakMap<new () => Mutation, () => MutationDefinition<any, any>>();\n\nexport const mutationKeyForClass = (cls: new () => Mutation): string => {\n const getMutationDef = mutationDefCache.get(cls);\n\n if (getMutationDef === undefined) {\n throw new Error('Mutation definition not found');\n }\n\n return getMutationDef().id;\n};\n\n// ================================\n// Internal: build mutation definition from class\n// ================================\n\nfunction buildMutationDefinition(MutationClass: new () => Mutation): () => MutationDefinition<any, any> {\n let cached = mutationDefCache.get(MutationClass);\n\n if (cached !== undefined) {\n return cached;\n }\n\n let mutationDefinition: MutationDefinition<any, any> | undefined;\n\n const getter = (): MutationDefinition<any, any> => {\n if (mutationDefinition !== undefined) {\n return mutationDefinition;\n }\n\n const instance = new MutationClass();\n const captured = extractDefinition(instance);\n const { fields } = captured;\n\n const id = `mutation:${String(captured.methods.getIdentityKey.call(fields))}`;\n\n const requestDef = fields.params ?? {};\n const requestShape = (requestDef instanceof ValidatorDef\n ? requestDef\n : t.object(requestDef)) as unknown as InternalTypeDef;\n const responseDef = fields.result;\n const responseShape =\n responseDef !== undefined\n ? ((responseDef instanceof ValidatorDef ? responseDef : t.object(responseDef)) as unknown as InternalTypeDef)\n : undefined;\n\n const adapterClass = (MutationClass as typeof Mutation).adapter;\n if (!adapterClass) {\n throw new Error(\n `Mutation class \"${MutationClass.name}\" must define a static \\`adapter\\` property. ` +\n `Extend RESTMutation (from fetchium/rest) or set \\`static adapter = MyAdapter\\` on your mutation class.`,\n );\n }\n\n mutationDefinition = {\n id,\n requestShape,\n responseShape,\n captured,\n optimisticUpdates: fields.optimisticUpdates ?? false,\n config: fields.config,\n effects: fields.effects,\n hasGetEffects: typeof captured.methods.getEffects === 'function',\n adapterClass,\n };\n\n return mutationDefinition;\n };\n\n mutationDefCache.set(MutationClass, getter);\n return getter;\n}\n\n// ================================\n// Public API\n// ================================\n\nexport function getMutation<T extends Mutation>(\n MutationClass: new () => T,\n): ReactiveTask<Readonly<ExtractType<T['result']>>, [ExtractType<T['params']>]> {\n const getMutationDef = buildMutationDefinition(MutationClass);\n\n const queryClient = getContext(QueryClientContext);\n\n if (queryClient === undefined) {\n throw new Error('QueryClient not found');\n }\n\n return queryClient.getMutation<any, any>(getMutationDef());\n}\n"],"names":["Mutation","createDefinitionProxy","mutationDefCache","mutationKeyForClass","cls","getMutationDef","buildMutationDefinition","MutationClass","cached","mutationDefinition","getter","instance","captured","extractDefinition","fields","id","requestDef","requestShape","ValidatorDef","t","responseDef","responseShape","adapterClass","getMutation","queryClient","getContext","QueryClientContext"],"mappings":";;AA+BO,MAAeA,EAAS;AAAA,EAC7B,OAAO;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAQT,cAAc;AACZ,WAAOC,EAAsB,IAAI;AAAA,EACnC;AACF;AAMA,MAAMC,wBAAuB,QAAA,GAEhBC,IAAsB,CAACC,MAAoC;AACtE,QAAMC,IAAiBH,EAAiB,IAAIE,CAAG;AAE/C,MAAIC,MAAmB;AACrB,UAAM,IAAI,MAAM,+BAA+B;AAGjD,SAAOA,IAAiB;AAC1B;AAMA,SAASC,EAAwBC,GAAuE;AACtG,MAAIC,IAASN,EAAiB,IAAIK,CAAa;AAE/C,MAAIC,MAAW;AACb,WAAOA;AAGT,MAAIC;AAEJ,QAAMC,IAAS,MAAoC;AACjD,QAAID,MAAuB;AACzB,aAAOA;AAGT,UAAME,IAAW,IAAIJ,EAAA,GACfK,IAAWC,EAAkBF,CAAQ,GACrC,EAAE,QAAAG,MAAWF,GAEbG,IAAK,YAAY,OAAOH,EAAS,QAAQ,eAAe,KAAKE,CAAM,CAAC,CAAC,IAErEE,IAAaF,EAAO,UAAU,CAAA,GAC9BG,IAAgBD,aAAsBE,IACxCF,IACAG,EAAE,OAAOH,CAAU,GACjBI,IAAcN,EAAO,QACrBO,IACJD,MAAgB,SACVA,aAAuBF,IAAeE,IAAcD,EAAE,OAAOC,CAAW,IAC1E,QAEAE,IAAgBf,EAAkC;AACxD,QAAI,CAACe;AACH,YAAM,IAAI;AAAA,QACR,mBAAmBf,EAAc,IAAI;AAAA,MAAA;AAKzC,WAAAE,IAAqB;AAAA,MACnB,IAAAM;AAAA,MACA,cAAAE;AAAA,MACA,eAAAI;AAAA,MACA,UAAAT;AAAA,MACA,mBAAmBE,EAAO,qBAAqB;AAAA,MAC/C,QAAQA,EAAO;AAAA,MACf,SAASA,EAAO;AAAA,MAChB,eAAe,OAAOF,EAAS,QAAQ,cAAe;AAAA,MACtD,cAAAU;AAAA,IAAA,GAGKb;AAAA,EACT;AAEA,SAAAP,EAAiB,IAAIK,GAAeG,CAAM,GACnCA;AACT;AAMO,SAASa,EACdhB,GAC8E;AAC9E,QAAMF,IAAiBC,EAAwBC,CAAa,GAEtDiB,IAAcC,EAAWC,CAAkB;AAEjD,MAAIF,MAAgB;AAClB,UAAM,IAAI,MAAM,uBAAuB;AAGzC,SAAOA,EAAY,YAAsBnB,GAAgB;AAC3D;"}
@@ -1,5 +1,5 @@
1
1
  import { useReactive as t } from "signalium/react";
2
- import { k as o } from "../QueryClient-D64xo0EA.js";
2
+ import { k as o } from "../QueryClient-DrWSXg0y.js";
3
3
  function i(e, ...r) {
4
4
  return t(() => o(e, ...r));
5
5
  }
@@ -1,6 +1,6 @@
1
- import { n as v, o as U, f as O } from "../QueryClient-D64xo0EA.js";
1
+ import { n as v, o as U, f as O } from "../QueryClient-DrWSXg0y.js";
2
2
  import { Q as T } from "../QueryAdapter-Bu5UJjE4.js";
3
- import { M as w } from "../mutation-Aw1JE7VO.js";
3
+ import { M as w } from "../mutation-B8dmX5lz.js";
4
4
  class P extends T {
5
5
  _fetch;
6
6
  _baseUrl;
@@ -1,4 +1,4 @@
1
- import { f as l } from "../QueryClient-D64xo0EA.js";
1
+ import { f as l } from "../QueryClient-DrWSXg0y.js";
2
2
  import { Q as d } from "../QueryAdapter-Bu5UJjE4.js";
3
3
  class f extends d {
4
4
  _topics = /* @__PURE__ */ new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fetchium",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -140,7 +140,7 @@
140
140
  },
141
141
  "peerDependencies": {
142
142
  "react": ">=19.0.0",
143
- "signalium": ">=3.0.0"
143
+ "signalium": ">=3.0.1"
144
144
  },
145
145
  "peerDependenciesMeta": {
146
146
  "react": {
@@ -176,7 +176,7 @@
176
176
  "react": "^19.0.0",
177
177
  "react-dom": "^19.0.0",
178
178
  "rollup-plugin-const-enum": "^1.1.4",
179
- "signalium": "3.0.0",
179
+ "signalium": "3.0.1",
180
180
  "vite": "^7.1.2",
181
181
  "vite-plugin-babel": "^1.3.0",
182
182
  "vite-plugin-dts": "^4.5.4",
@@ -1,2 +0,0 @@
1
- "use strict";const C=require("signalium"),x=require("signalium/utils"),Qt=require("./shared-Ct5zKrt4.js"),Dt=require("./stores/sync.js");var $=(e=>(e.Always="always",e.Online="online",e.OfflineFirst="offlineFirst",e))($||{}),d=(e=>(e[e.UNDEFINED=1]="UNDEFINED",e[e.NULL=2]="NULL",e[e.NUMBER=4]="NUMBER",e[e.STRING=8]="STRING",e[e.BOOLEAN=16]="BOOLEAN",e[e.OBJECT=32]="OBJECT",e[e.ARRAY=64]="ARRAY",e[e.ID=128]="ID",e[e.RECORD=256]="RECORD",e[e.UNION=512]="UNION",e[e.ENTITY=1024]="ENTITY",e[e.HAS_FORMAT=4096]="HAS_FORMAT",e[e.IS_EAGER_FORMAT=8192]="IS_EAGER_FORMAT",e[e.PARSE_RESULT=16384]="PARSE_RESULT",e[e.LIVE=32768]="LIVE",e))(d||{});const I=Symbol("array"),k=Symbol("record"),ht=Symbol("QUERY_ID");var Z=(e=>(e[e.Array=0]="Array",e[e.Value=1]="Value",e))(Z||{});class L{type;entityDefs;constraintFieldRefs;sort;valueType;onCreate;onUpdate;onDelete;constructor(t,n,i,r,s,o,a,c){this.type=t,this.entityDefs=n,this.constraintFieldRefs=i,this.sort=r,this.valueType=s,this.onCreate=o,this.onUpdate=a,this.onDelete=c}static array(t,n,i){return new L(0,t,n,i,void 0,void 0,void 0,void 0)}static value(t,n,i,r,s,o){return new L(1,t,n,void 0,i,r,s,o)}}const R=new WeakMap;function P(e){return R.get(e)}var tt=(e=>(e[e.Query=0]="Query",e[e.Entity=1]="Entity",e))(tt||{});class xe{constructor(t,n,i){this._onEvict=n,this._intervalId=setInterval(this._tick,t*6e4*i)}_currentFlush=new Map;_nextFlush=new Map;_intervalId;schedule(t,n){this._nextFlush.set(t,n)}cancel(t){this._currentFlush.delete(t),this._nextFlush.delete(t)}_tick=()=>{const{_currentFlush:t,_nextFlush:n,_onEvict:i}=this;for(const[r,s]of t)i(r,s);this._currentFlush=n,this._nextFlush=new Map};destroy(){clearInterval(this._intervalId)}}class Bt{_buckets=new Map;_nextTickEntries=new Map;_nextTickScheduled=!1;_onEvict;_multiplier;constructor(t,n=1){this._onEvict=t,this._multiplier=n}schedule(t,n,i){if(n===1/0)return;if(n===0){const{_nextTickEntries:o}=this;o.set(t,i),this._nextTickScheduled||(this._nextTickScheduled=!0,setTimeout(this._flushNextTick,0));return}const{_buckets:r}=this;let s=r.get(n);s||(s=new xe(n,this._onEvict,this._multiplier),r.set(n,s)),s.schedule(t,i)}cancel(t,n){if(n!==1/0){if(n===0){this._nextTickEntries.delete(t);return}this._buckets.get(n)?.cancel(t)}}_flushNextTick=()=>{const{_nextTickEntries:t,_onEvict:n}=this;this._nextTickScheduled=!1;for(const[i,r]of t)n(i,r);t.clear()};destroy(){const{_buckets:t,_nextTickEntries:n}=this;for(const i of t.values())i.destroy();t.clear(),n.clear()}}class Yt{schedule(t,n,i){}cancel(t,n){}destroy(){}}const J=Symbol("fieldRef"),F=Symbol("fieldRefPath"),yt=Symbol("DEFINITION_TARGET"),X=Symbol("CANCEL_PROXY"),Ae=/\[([^\]]+)\]/g;function Gt(e){const t={[J]:!0,[F]:e};return new Proxy(t,Ne)}const Ne={get(e,t){if(t===J)return!0;if(t===F)return e[F];if(t===Symbol.toPrimitive||t==="toString"||t==="valueOf"){const i=e[F];return()=>`[${i.join(".")}]`}if(typeof t=="symbol")return;const n=e[F];return Gt([...n,t])},has(e,t){return t===J||t===F}};function Ht(e){return typeof e=="object"&&e!==null&&e[J]===!0}function Wt(e){return e[F]}function pt(e){let t=!1;return new Proxy(e,{set(n,i,r){return n[i]=r,!0},get(n,i){if(t)throw new Error("Definition proxy accessed after extraction. Avoid arrow functions that capture `this`.");return i===yt?n:i===X?()=>{t=!0}:typeof i=="symbol"?n[i]:Gt([i])}})}function zt(e){const t=e[yt];e[X]();const n={};for(const s of Object.getOwnPropertyNames(t))n[s]=t[s];const i={};let r=Object.getPrototypeOf(t);for(;r&&r!==Object.prototype;){for(const s of Object.getOwnPropertyNames(r)){if(s==="constructor")continue;const o=Object.getOwnPropertyDescriptor(r,s);typeof o.value=="function"&&!(s in i)&&(i[s]=o.value)}r=Object.getPrototypeOf(r)}return{fields:n,methods:i}}function gt(e,t){let n=t;for(const i of e){if(n==null)return;n=n[i]}return n}function De(e,t){return e.replace(Ae,(n,i)=>{const r=i.split("."),s=gt(r,t);return s!=null?encodeURIComponent(String(s)):""})}function Y(e,t){if(Ht(e))return gt(Wt(e),t);if(typeof e=="string")return De(e,t);if(Array.isArray(e))return e.map(n=>Y(n,t));if(typeof e=="object"&&e!==null&&Object.getPrototypeOf(e)===Object.prototype){const n={};for(const i of Object.keys(e))n[i]=Y(e[i],t);return n}return e}function ot(e,t,n){const i=e.fields,r=e.methods,s={params:t},o={};for(const[a,c]of Object.entries(i))o[a]=Y(c,s);o.params=t,o.context=n;for(const[a,c]of Object.entries(r))o[a]=c.bind(o);return o}class et{static cache;constructor(){return pt(this)}}const Jt=Object.entries,at=Object.keys;let Xt=()=>{};{const t=(i,r)=>{if(i.size!==r.size)return!1;for(const s of i)if(!r.has(s))return!1;return!0},n=(i,r)=>{if(i===r)return!0;if(typeof i!=typeof r)return!1;if(typeof i=="number"){const s=r;if((i&65535)!==(s&65535))return!1;const o=i>>16,a=s>>16;return!(o!==0&&a!==0&&o!==a)}if(typeof i=="string")return i===r;if(i instanceof Set&&r instanceof Set)return t(i,r);if(i instanceof v&&r instanceof v){const s=i.mask,o=r.mask;if((s&65535)!==(o&65535))return!1;const a=s>>16,c=o>>16;if(a!==0&&c!==0&&a!==c)return!1;if(i.shape===r.shape)return!0;if(i.shape!==void 0&&r.shape!==void 0&&typeof i.shape=="object"&&typeof r.shape=="object"){const f=i.shape,l=r.shape;for(const u of Object.keys(f))if(u in l&&!n(f[u],l[u]))return!1;for(const u of Object.keys(l))if(u in f&&!n(f[u],l[u]))return!1}return!0}return!1};Xt=(i,r,s,o)=>{if(!n(s,o))throw new Error(`[fetchium] Entity typename '${i}' has incompatible type for field '${r}' across different entity definitions`)}}function It(e){return typeof e=="number"?e|d.UNDEFINED:e instanceof v?(e.mask&d.UNDEFINED)!==0?e:v.cloneWith(e,d.UNDEFINED):e}function kt(e){return e instanceof v&&(e.mask&d.OBJECT)!==0&&(e.mask&(d.ENTITY|d.ARRAY|d.UNION|d.RECORD|d.LIVE))===0}function Zt(e,t,n){const i=new Set;for(const s of e)if(s!==void 0)for(const o of Object.keys(s))i.add(o);const r={};for(const s of i){let o=0,a;const c=[];let f=!0;for(const l of e){const u=l?.[s];u!==void 0?(o++,a===void 0&&(a=u),a!==void 0&&u!==a&&!kt(u)&&Xt(n,s,a,u),kt(u)?c.push(u.shape):(f=!1,c.push(void 0))):(f=!1,c.push(void 0))}if(f&&o>0){const l=Zt(c,t,n),u=new v(d.OBJECT,l);r[s]=o<t?It(u):u}else r[s]=o<t?It(a):a}return r}class v{mask;shape;typenameField=void 0;typenameValue=void 0;idField=void 0;values=void 0;_methods=void 0;_entityConfig=void 0;_entityClass=void 0;_entityCache=void 0;_liveConfig=void 0;constructor(t,n,i,r,s,o){this.mask=t,this.shape=n,this.values=i,this.typenameField=r,this.typenameValue=s,this.idField=o}static merge(t){if(t.length===1)return t[0];const n=t.length,i=t.map(f=>f.shape),r=t[0].typenameValue??"(unknown)",s=Zt(i,n,r);let o,a,c;for(const f of t){if(o===void 0&&f.idField!==void 0)o=f.idField;else if(o!==void 0&&f.idField!==void 0&&f.idField!==o)throw new Error(`[fetchium] Entity typename '${f.typenameValue}' has conflicting id fields: '${String(o)}' vs '${String(f.idField)}'`);a===void 0&&(a=f.typenameField),c===void 0&&(c=f.typenameValue)}return new v(d.ENTITY|d.OBJECT,s,void 0,a,c,o)}static cloneWith(t,n){const i=new v(n|t.mask,t.shape,t.values,t.typenameField,t.typenameValue,t.idField);return i._methods=t._methods,i._entityConfig=t._entityConfig,i._entityClass=t._entityClass,i._entityCache=t._entityCache,i._liveConfig=t._liveConfig,i}}class q extends Set{lowercaseMap;constructor(t){super(t),this.lowercaseMap=new Map;for(const n of t)if(typeof n=="string"){const i=n.toLowerCase(),r=this.lowercaseMap.get(i);if(r!==void 0)throw new Error(`Case-insensitive enum cannot have multiple values with the same lowercase form: '${r}' and '${n}' both become '${i}'`);this.lowercaseMap.set(i,n)}}has(t){return this.get(t)!==void 0}get(t){if(typeof t=="string")return this.lowercaseMap.get(t.toLowerCase());if(super.has(t))return t}}const Ie=1128875347;x.registerCustomHash(q,e=>{let t=Ie;for(const n of e)t+=x.hashValue(n);return t>>>0});function vt(e,t){return new v(e,t)}function ke(e){return vt(d.ARRAY,e)}function Fe(e){return vt(d.RECORD|d.OBJECT,e)}function Me(e){return vt(d.PARSE_RESULT,e)}function te(e,t){let n=e,i,r,s;for(const[o,a]of Jt(t))switch(typeof a){case"number":if((a&d.ID)!==0){if(i!==void 0)throw new Error(`Duplicate id field: ${o}`);i=o}break;case"string":if(r!==void 0&&r!==o)throw new Error(`Duplicate typename field: ${o}`);r=o,s=a;break;case"object":if(a instanceof q||a instanceof Set)break;a.mask&d.LIVE&&(n|=d.LIVE);break}return new v(n,t,void 0,r,s,i)}function Te(e){return te(d.OBJECT,e)}function Ft(e,t,n){const i=e.mask;if((i&d.UNION)!==0){const r=e;if(r.typenameField!==void 0){if(n!==void 0&&n!==r.typenameField)throw new Error(`Union typename field conflict: Cannot merge unions with different typename fields ('${n}' vs '${r.typenameField}')`);n=r.typenameField}const s=r.shape;if(s!==void 0)for(const o of[...at(s),I,k]){const a=s[o];if(t[o]!==void 0&&t[o]!==a)throw new Error(`Union merge conflict: Duplicate typename value '${String(o)}' found when merging nested unions (${String(t[o])} vs ${String(a)})`);t[o]=a}}else if((i&d.ARRAY)!==0){if(t[I]!==void 0)throw new Error("Array shape already defined");t[I]=e.shape}else if((i&d.RECORD)!==0){if(t[k]!==void 0)throw new Error("Record shape already defined");t[k]=e.shape}else{const r=e.typenameField,s=e.typenameValue;if(s===void 0)throw new Error("Object definitions must have a typename to be in a union with other objects, records, or arrays");if(n!==void 0&&r!==n)throw new Error("Object definitions must have the same typename field to be in the same union");n=r,t[s]=e}return n}function mt(...e){const t=e;let n=0,i=0,r,s,o,a,c=0;for(const l of t){if(typeof l=="number"){n|=l;continue}if(l instanceof Set){if(s===void 0)s=new Set(l);else for(const u of l)s.add(u);continue}if(i++,c|=l.mask,i===1){r=l;continue}i===2&&(o=Object.create(null),a=Ft(r,o,a)),a=Ft(l,o,a)}if(i===0)return s===void 0?n:n===0?s:new v(n|d.UNION,void 0,s);if(i===1)return v.cloneWith(r,n);const f=n|c|d.UNION;return new v(f,o,s,a)}function _t(e,t,n){const i=e;if(typeof i=="number")return i|t;if(i instanceof Set)return mt(e,t);let r=n.get(i);return r===void 0&&(r=v.cloneWith(i,t),n.set(i,r)),r}const Pe=new WeakMap,je=new WeakMap,$e=new WeakMap;function Le(e){return _t(e,d.UNDEFINED|d.NULL,$e)}function Ue(e){return _t(e,d.UNDEFINED,Pe)}function qe(e){return _t(e,d.NULL,je)}function Ve(e){return e}function Ke(e){return new Set([e])}const ee=((...e)=>new Set(e));ee.caseInsensitive=(...e)=>new q(e);const wt=16;let Qe=0;const ct=[],ne=[],ie=new Map,re=new Map,nt=new WeakSet;class G{_raw;_formatted;_parsed;_formatId;constructor(t,n,i){this._raw=t,this._formatId=n,i?(this._formatted=ct[n](t),this._parsed=!0):this._parsed=!1,nt.add(this)}getValue(){return this._parsed||(this._formatted=ct[this._formatId](this._raw),this._parsed=!0),this._formatted}toJSON(){return this._parsed?ne[this._formatId](this._formatted):this._raw}}function Be(e){const t=ie.get(e);if(t===void 0)throw new Error(`Format ${e} not registered`);return t}function Mt(e){const t=e>>wt;return re.get(t)}function Et(e,t,n,i,r){const s=Qe++;ct[s]=n,ne[s]=i,re.set(s,e);const o=r?.eager??!0,c=s<<wt|t|d.HAS_FORMAT|(o?d.IS_EAGER_FORMAT:0);ie.set(e,c)}Et("date",d.STRING,e=>{const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)throw new Error(`Invalid date string: ${e}. Expected YYYY-MM-DD format.`);const[,n,i,r]=t,s=new Date(Date.UTC(parseInt(n,10),parseInt(i,10)-1,parseInt(r,10)));if(isNaN(s.getTime()))throw new Error(`Invalid date string: ${e}`);return s},e=>{const t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0");return`${t}-${n}-${i}`});Et("date-time",d.STRING,e=>{const t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date-time string: ${e}`);return t},e=>e.toISOString());const Tt=new WeakMap;function U(e){let t=Tt.get(e);if(t===void 0){const n=new e,i=n[yt]??n;n[X]&&n[X]();const r={};for(const[f,l]of Jt(i)){if(!(typeof l=="number"||typeof l=="string"||l instanceof Set||l instanceof v||l instanceof q))throw new Error(`[fetchium] Entity '${e.name}' field '${f}' has an invalid type definition. All entity fields must be type definitions (e.g. t.string, t.number, t.entity(...), etc). Got: ${typeof l=="object"?l?.constructor?.name??typeof l:typeof l}`);r[f]=l}const s=Object.getPrototypeOf(e.prototype);if(s!=null){const f=s.constructor;if(f!==et&&typeof f=="function"){const u=U(f).shape;for(const h of at(u))if(h in r&&r[h]!==u[h])throw new Error(`Cannot extend: field '${h}' already exists in type definition`)}}const o={},a=e.prototype;for(const f of Object.getOwnPropertyNames(a))f!=="constructor"&&typeof a[f]=="function"&&(o[f]=a[f]);t=te(d.ENTITY|d.OBJECT,r),t._entityClass=e,at(o).length>0&&(t._methods=o),typeof o.__subscribe=="function"&&(t._entityConfig={hasSubscribe:!0});const c=e;c.cache&&(t._entityCache=c.cache),Tt.set(e,t)}return t}function Ye(e){return U(e)}function se(e,t){if(t==null)return;const n=new Map;if(Array.isArray(t))for(const i of t){const[r,s]=i,a=U(r).typenameValue;if(a===void 0)continue;const c=[];for(const[f,l]of Object.entries(s))c.push([f,l]);c.length>0&&n.set(a,c)}else{const r=Object.entries(t);if(r.length===0)return;const s=r.map(([o,a])=>[o,a]);for(const o of e){const a=o.typenameValue;a!==void 0&&n.set(a,s)}}return n.size>0?n:void 0}function oe(e){return Array.isArray(e)?e.map(t=>U(t)):[U(e)]}function Ge(e,t){const n=oe(e),i=n.length===1?n[0]:mt(...n.map(o=>o)),r=d.ARRAY|d.LIVE,s=new v(r,i);return s._liveConfig=L.array(n,se(n,t?.constraints),t?.sort),s}function He(e,t,n){const i=oe(t),r=e,s=d.LIVE,o=new v(s,void 0);return o._liveConfig=L.value(i,se(i,n?.constraints),r,n.onCreate,n.onUpdate,n.onDelete),o}const ae={format:Be,typename:Ve,const:Ke,enum:ee,id:d.ID|d.STRING|d.NUMBER,string:d.STRING,number:d.NUMBER,boolean:d.BOOLEAN,null:d.NULL,undefined:d.UNDEFINED,array:ke,object:Te,record:Fe,union:mt,nullish:Le,optional:Ue,nullable:qe,result:Me,entity:Ye,liveArray:Ge,liveValue:He};function B(e){if(e instanceof q)return Array.from(e).map(i=>typeof i=="string"?`"${i}"`:String(i)).join(" | ");if(e instanceof Set)return Array.from(e).map(i=>typeof i=="string"?`"${i}"`:String(i)).join(" | ");if(typeof e=="string")return`"${e}"`;if(typeof e=="boolean")return String(e);if(typeof e=="number"){if((e&d.HAS_FORMAT)!==0){const r=Mt(e);if(r)return`"${r}"`}const i=[];return e&d.UNDEFINED&&i.push("undefined"),e&d.NULL&&i.push("null"),e&d.NUMBER&&i.push("number"),e&d.STRING&&i.push("string"),e&d.BOOLEAN&&i.push("boolean"),e&d.OBJECT&&i.push("object"),e&d.ARRAY&&i.push("array"),i.length===0?"unknown":i.length===1?i[0]:i.join(" | ")}let t=e.mask;if(t&d.UNION){const n=e,i=[];if(n.values!==void 0&&n.values.size>0)for(const s of n.values){const o=typeof s=="string"?`"${s}"`:String(s);i.push(o)}if(n.shape!==void 0){n.shape[I]!==void 0&&i.push(`Array<${B(n.shape[I])}>`),n.shape[k]!==void 0&&i.push(`Record<string, ${B(n.shape[k])}>`);for(const[s,o]of Object.entries(n.shape))s!==I&&s!==k&&i.push(s)}if(t=n.mask,(t&d.HAS_FORMAT)!==0){const s=Mt(t);s&&i.push(`"${s}"`)}return t&d.UNDEFINED&&i.push("undefined"),t&d.NULL&&i.push("null"),t&d.NUMBER&&i.push("number"),t&d.STRING&&i.push("string"),t&d.BOOLEAN&&i.push("boolean"),i.length===0?"union":i.join(" | ")}if(t&d.ENTITY)return`Entity<${e.typenameValue}>`;if(t&d.ARRAY){const n=e.shape;return`Array<${B(n)}>`}if(t&d.RECORD){const n=e.shape;return`Record<string, ${B(n)}>`}if(t&d.OBJECT){const n=e.typenameValue;return n?`Object<${n}>`:"object"}return"unknown"}function Q(e,t,n){return new TypeError(`Validation error at ${e}: expected ${B(t)}, got ${typeof n=="object"?n===null?"null":Array.isArray(n)?"array":"object":typeof n}`)}const ce=Array.isArray;function Pt(e){if(e===null)return d.NULL;switch(typeof e){case"number":return d.NUMBER;case"string":return d.STRING;case"boolean":return d.BOOLEAN;case"undefined":return d.UNDEFINED;case"object":return ce(e)?d.ARRAY:d.OBJECT;default:throw new Error(`Invalid type: ${typeof e}`)}}function We(e){return j(e)}function j(e){if(e===null||typeof e!="object")return e;if(ce(e))return e.map(n=>j(n));if(e instanceof Date)return new Date(e.getTime());if(e instanceof Map){const n=new Map;for(const[i,r]of e)n.set(j(i),j(r));return n}if(e instanceof Set){const n=new Set;for(const i of e)n.add(j(i));return n}const t={};for(const n of Object.keys(e))t[n]=j(e[n]);return t}const bt=Object.entries,ze=()=>{};class ft{queryClient=void 0;preloadedEntities=void 0;warn=ze;isPartialEvent=!1;seen=void 0;seenByKey=void 0;reset(t,n,i,r=!1){this.queryClient=t,this.preloadedEntities=n,this.warn=i,this.isPartialEvent=r,t!==void 0&&(this.seen===void 0?(this.seen=new Map,this.seenByKey=new Map):(this.seen.clear(),this.seenByKey.clear()))}}function fe(e,t,n){return M(e,t,n,"")}function Je(e,t,n){return Ct(e,t,n)}function jt(e,t,n,i){const r=e>>wt;if((e&d.IS_EAGER_FORMAT)!==0)try{return new G(t,r,!0)}catch(o){if((e&d.UNDEFINED)!==0){n.warn("Invalid formatted value for optional type, defaulting to undefined",{value:t,path:i,error:o instanceof Error?o.message:String(o)});return}throw o}return new G(t,r,!1)}function M(e,t,n,i){const r=t;if(r instanceof q){const c=r.get(e);if(c===void 0)throw Q(i,r,e);return c}if(r instanceof Set){if(!r.has(e))throw Q(i,r,e);return e}if(typeof r=="string"){if(e==null)return r;if(e!==r)throw Q(i,r,e);return e}if(typeof r=="number"){const c=Pt(e);if((r&c)===0){if((r&d.UNDEFINED)!==0){n.warn("Invalid value for optional type, defaulting to undefined",{value:e,path:i});return}throw Q(i,r,e)}return(r&d.HAS_FORMAT)!==0&&e!==null&&e!==void 0?jt(r,e,n,i):e}const s=r.mask,o=r._liveConfig;if(o!==void 0&&o.type===Z.Value)return o.valueType!==void 0?M(e,o.valueType,n,i):e;if((s&d.PARSE_RESULT)!==0)try{return{success:!0,value:M(e,r.shape,n,i)}}catch(c){return{success:!1,error:c instanceof Error?c:new Error(String(c))}}const a=Pt(e);if((s&a)===0&&!r.values?.has(e)){if((s&d.UNDEFINED)!==0){n.warn("Invalid value for optional type, defaulting to undefined",{value:e,path:i});return}throw Q(i,s,e)}return a<d.OBJECT?(s&d.HAS_FORMAT)!==0&&e!==null&&e!==void 0?jt(s,e,n,i):e:(s&d.UNION)!==0?Xe(a,e,r,n,i):a===d.ARRAY?ue(e,r.shape,n,i):(s&d.RECORD)!==0?de(e,r.shape,n,i):(s&d.ENTITY)!==0&&n.queryClient!==void 0?Ct(e,r,n):le(e,r,n,i)}function Xe(e,t,n,i,r){if(e===d.ARRAY){const s=n.shape[I];return s===void 0||typeof s=="number"?t:ue(t,s,i,r)}else{const s=n.typenameField,o=s?t[s]:void 0;if(o===void 0||typeof o!="string"){const c=n.shape[k];if(c===void 0)throw new Error(`Typename field '${s}' is required for union discrimination but was not found in the data`);return de(t,c,i,r)}const a=n.shape[o];if(a===void 0||typeof a=="number")throw new Error(`Unknown typename '${o}' in union`);return a.mask&d.ENTITY&&i.queryClient!==void 0?Ct(t,a,i):le(t,a,i,r)}}function ue(e,t,n,i){const r=[];for(let s=0;s<e.length;s++)try{r.push(M(e[s],t,n,`${i}[${s}]`))}catch(o){n.warn("Failed to parse array item, filtering out",{index:s,value:e[s],error:o instanceof Error?o.message:String(o)})}return r}function de(e,t,n,i){for(const[r,s]of bt(e))e[r]=M(s,t,n,`${i}["${r}"]`);return e}function le(e,t,n,i){if(R.has(e))return e;const r=t.shape;for(const[s,o]of bt(r))e[s]=M(e[s],o,n,`${i}.${s}`);return e}function Ct(e,t,n){const i=n.queryClient,r=n.preloadedEntities;let s,o;if(r!==void 0)s=e.__entityRef,o=s;else{const p=e[t.idField];if(p==null||typeof p!="string"&&typeof p!="number")throw new Error(`Entity id must be a string or number: ${t.typenameValue} (got ${typeof p})`);o=p,s=x.hashValue([t.typenameValue,o])}const a=n.seenByKey.get(s);if(a!==void 0)return a.data;if(r!==void 0){const w=i.entityMap.getEntity(s)?.data??r.get(s);if(w===void 0)throw new Error(`Cached entity ${s} not found in preloaded map`);e=w}const c={};typeof t.idField=="symbol"&&(c[t.idField]=o);const f=i.entityMap.getEntity(s),l=n.isPartialEvent&&f!==void 0,u={key:s,shape:t,data:c,rawKeys:l?new Set(Object.keys(e)):void 0};n.seen.set(c,u),n.seenByKey.set(s,u);const h=`[[${t.typenameValue}:${o}]]`,g=t.shape;for(const[p,w]of bt(g))l&&!(p in e)||(c[p]=M(e[p],w,n,`${h}.${p}`));return c}function Ze(e,t){return tn(e,t.shape,t.typenameField)}function tn(e,t,n){if(t===void 0)return!0;for(const i of Object.keys(t)){if(i===n)continue;const r=t[i];if(r instanceof v){if((r.mask&d.UNDEFINED)!==0)continue;if(!(i in e)||e[i]===void 0)return!1}else if(typeof r=="number"){if((r&d.UNDEFINED)!==0)continue;if(!(i in e)||e[i]===void 0)return!1}else if(!(i in e)||e[i]===void 0)return!1}return!0}const en=Object.prototype,z=new WeakMap;function D(e){if(typeof e!="object"||e===null)return e;if(nt.has(e))return D(e.getValue());if(R.has(e))return e;if(Array.isArray(e)){let t=z.get(e);return t===void 0&&(t=new Proxy(e,nn),z.set(e,t)),t}if(Object.getPrototypeOf(e)===en){let t=z.get(e);return t===void 0&&(t=new Proxy(e,rn),z.set(e,t)),t}return e}const nn={get(e,t,n){if(typeof t=="string"){const i=Number(t);if(Number.isInteger(i)&&i>=0&&i<e.length)return D(e[i])}return Reflect.get(e,t,n)},set(){throw new Error("Cannot mutate a read-only array")},deleteProperty(){throw new Error("Cannot mutate a read-only array")}},rn={get(e,t,n){return typeof t=="string"?D(e[t]):Reflect.get(e,t,n)},set(){throw new Error("Cannot mutate a read-only object")},deleteProperty(){throw new Error("Cannot mutate a read-only object")},has(e,t){return t in e},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)}},sn=(e,t,n)=>{const i=e,r=Object.keys(i),s=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0;let o=!s||Object.keys(s).length!==r.length;const a={};for(let c=0;c<r.length;c++){const f=r[c],l=i[f];let u;typeof l=="function"?u=l:u=n(l,s?.[f]),a[f]=u,!o&&u!==s?.[f]&&(o=!0)}return o?a:s},$t=new WeakSet;function he(e){const t=e.prototype;$t.has(t)||($t.add(t),x.registerCustomSnapshot(e,sn))}he(et);class on{_notifier;_queryClient;_proxies=new Map;key;typename;id;idField;data;refCount=0;entityRefs;liveCollections=[];satisfiedDefs=new WeakSet;parseId=-1;_entityCache;_extraMethods;_extraGetters;constructor(t,n,i,r,s,o){this._notifier=C.notifier(),this._queryClient=o,this.key=t,this.typename=n,this.id=i,this.idField=r,this.data=s,this.entityRefs=void 0}retain(){this.refCount++;const t=this._entityCache?.gcTime;t!==void 0&&this._queryClient.gcManager.cancel(this.key,t)}release(){if(--this.refCount>0)return;if(this.refCount<0)throw new Error(`Entity ${this.typename}:${this.id} released more times than retained`);const t=this._entityCache?.gcTime;t!==void 0?this._queryClient.gcManager.schedule(this.key,t,tt.Entity):this.evict()}evict(){const t=this.liveCollections.slice();this.liveCollections.length=0;for(const i of t)i.destroy();this._queryClient.entityMap.remove(this.key);const n=this.entityRefs;if(this.entityRefs=void 0,n)for(const i of n.keys())i.release()}setChildRefs(t,n){const i=this.entityRefs;if(t!==void 0&&t.size>0)for(const r of t.keys())(i===void 0||!i.has(r))&&r.retain();if(i!==void 0&&i.size>0)for(const r of i.keys())(t===void 0||!t.has(r))&&r.release();this.entityRefs=t,n&&this.save()}addChildRef(t){this.entityRefs===void 0&&(this.entityRefs=new Map);const n=this.entityRefs.get(t)??0;this.entityRefs.set(t,n+1),n===0&&t.retain(),this.save()}removeChildRef(t){if(this.entityRefs===void 0)return;const n=this.entityRefs.get(t);n!==void 0&&(n<=1?(this.entityRefs.delete(t),t.release()):this.entityRefs.set(t,n-1),this.save())}getProxy(t){const n=t;let i=this._proxies.get(n);return i===void 0&&(i=cn(this,this.key,t,this._notifier,this._queryClient),this._proxies.set(n,i)),i}get proxy(){return this._proxies.values().next().value}satisfiesDef(t){return this.satisfiedDefs.has(t)?!0:Ze(this.data,t)?(this.satisfiedDefs.add(t),!0):!1}save(){this._queryClient.entityMap.save(this)}notify(){this._notifier.notify()}consume(){this._notifier.consume()}}function an(e,t,n){const i=[];for(const r of e){if(typeof r!="object"||r===null)continue;const s=R.get(r);if(s===void 0)continue;const o=n.entityMap.getEntity(s);o!==void 0&&o.satisfiesDef(t)&&i.push(r)}return i}function cn(e,t,n,i,r){const s=n.shape??{},o=n,a=o._methods,c=o._entityClass,f=o._entityConfig,l=c?c.prototype:et.prototype;c!==void 0&&he(c);const u=n.typenameField,h=new Map,g=new Map,p=()=>({__entityRef:t});let w;f?.hasSubscribe&&a&&"__subscribe"in a&&(w=C.relay(E=>{const y=b=>{b.__eventSource=t,r.applyMutationEvent(b)},_=a.__subscribe.call(m,y);return E.value=m,_}));let m;if(u&&!(u in s))throw new Error(`typenameField "${u}" must be declared in the entity shape`);const S=Object.keys(s);if(S.includes("__typename")||S.push("__typename"),a)for(const E of Object.keys(a))S.includes(E)||S.push(E);let T,A=S;function V(){const E=e._extraMethods;if(E!==T){if(T=E,A=S.slice(),E!==void 0)for(const _ of Object.keys(E))A.includes(_)||A.push(_);const y=e._extraGetters;if(y!==void 0)for(const _ of Object.keys(y))A.includes(_)||A.push(_)}return A}const K={getPrototypeOf(){return l},get(E,y){if(typeof y=="symbol")return;if(y==="toJSON")return p;if(y==="__context")return r.getContext();if(y==="__typename")return e.typename;if(w?.value,i.consume(),typeof y=="string"){const b=e._extraGetters;if(b!==void 0&&y in b)return b[y]();const N=e._extraMethods;if(N!==void 0&&y in N){let O=h.get(y);return O||(O=N[y].bind(m),h.set(y,O)),O}if(a&&y in a){let O=h.get(y);return O||(O=C.reactiveMethod(m,a[y].bind(m)),h.set(y,O)),O}}const _=e.data[y];if(typeof _=="object"&&_!==null&&nt.has(_))return D(_.getValue());if(Array.isArray(_)&&typeof y=="string"){const b=s[y];if(b instanceof v&&(b.mask&d.ARRAY)!==0){const N=b.shape;if(N instanceof v&&(N.mask&d.ENTITY)!==0){const O=N.typenameValue;if(O!==void 0){const At=r.getEntityDefsForTypename(O);if(At!==void 0&&At.length>1){const it=g.get(y);if(it!==void 0&&it.source===_)return D(it.filtered);const Nt=an(_,N,r);return g.set(y,{source:_,filtered:Nt}),D(Nt)}}}}return D(_)}return D(_)},set(){throw new Error("Entity properties are read-only")},has(E,y){if(y==="__typename")return!0;if(typeof y=="string"){const _=e._extraGetters;if(_&&y in _)return!0;const b=e._extraMethods;if(b&&y in b||a&&y in a)return!0}return y in s},ownKeys(){return V()},getOwnPropertyDescriptor(E,y){if(y==="__typename")return{enumerable:!0,configurable:!0,value:e.typename,writable:!1};if(y in s)return{enumerable:!0,configurable:!0,value:K.get(E,y,m),writable:!1};if(typeof y=="string"){const _=e._extraGetters;if(_&&y in _)return{enumerable:!0,configurable:!0,value:K.get(E,y,m),writable:!1};const b=e._extraMethods;if(b&&y in b)return{enumerable:!0,configurable:!0,value:K.get(E,y,m),writable:!1};if(a&&y in a)return{enumerable:!1,configurable:!0,value:K.get(E,y,m),writable:!1}}}};return m=new Proxy({},K),R.set(m,t),C.setScopeOwner(m,r),m}class fn{instances=new Map;persistEntity;constructor(t){this.persistEntity=t}hasEntity(t){return this.instances.has(t)}getEntity(t){return this.instances.get(t)}getOrCreateEntity(t,n,i,r){let s=this.instances.get(t);if(s===void 0){const o=i.idField;if(o===void 0)throw new Error(`Entity id field is required ${i.typenameValue}`);const a=n[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Entity id must be string or number: ${i.typenameValue}`);const c=i;s=new on(t,i.typenameValue,a,o,n,r),s._entityCache=c._entityCache,this.instances.set(t,s)}return s.parseId=r.currentParseId,s}remove(t){this.instances.delete(t)}save(t){let n;if(t.entityRefs){n=new Set;for(const i of t.entityRefs.keys())n.add(i.key)}this.persistEntity(t.key,t.data,n)}}class Ot{onlineSignal;manualOverride=void 0;eventListenersAttached=!1;constructor(t){const n=t??this.detectOnlineStatus();this.onlineSignal=C.signal(n),this.canAttachListeners()&&this.attachEventListeners()}get isOnline(){return this.manualOverride!==void 0?this.manualOverride:this.onlineSignal.value}setNetworkStatus(t){this.manualOverride=t,this.onlineSignal.value=t}clearManualOverride(){this.manualOverride=void 0,this.onlineSignal.value=this.detectOnlineStatus()}getOnlineSignal(){return this.onlineSignal}detectOnlineStatus(){return typeof navigator<"u"&&"onLine"in navigator?navigator.onLine:!0}canAttachListeners(){return typeof window<"u"&&typeof window.addEventListener=="function"}destroy(){this.eventListenersAttached&&this.handleOnline&&this.handleOffline&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline),this.eventListenersAttached=!1)}handleOnline=void 0;handleOffline=void 0;attachEventListeners(){this.eventListenersAttached||(this.handleOnline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!0)},this.handleOffline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!1)},window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.eventListenersAttached=!0)}}class Rt{static onlineSignal=C.signal(!0);get isOnline(){return!0}setNetworkStatus(t){}clearManualOverride(){}getOnlineSignal(){return Rt.onlineSignal}destroy(){}}const ye=new Ot,un=C.context(ye);function St(e,t=typeof window>"u"){let n;e===!1?n=0:e===void 0||e===!0?n=t?0:3:typeof e=="number"?n=e:n=e.retries;const i=typeof e=="object"&&e.retryDelay?e.retryDelay:r=>1e3*Math.pow(2,r);return{retries:n,retryDelay:i}}class dn{static cache;static adapter;params;config;constructor(){return pt(this)}}const Lt=new WeakMap;class W{constructor(t,n){this.captured=n,this.statics=t}statics;createExecutionContext(t,n){return ot(this.captured,t,n)}resolveOptions(t){const{methods:n}=this.captured,i=n.getConfig?n.getConfig.call(t):t.config,r=St(i?.retry);return{config:i,retryConfig:r}}static for(t){let n=Lt.get(t);if(n!==void 0)return n;const i=new t,r=zt(i),s=String(r.methods.getIdentityKey.call(r.fields)),o=r.fields.result,a=o instanceof v?o:ae.object(o),c=(a.mask&d.ENTITY)!==0,f=t.cache,l=r.fields.fetchNext,u=t.adapter;if(!u)throw new Error(`Query class "${t.name}" must define a static \`adapter\` property. Extend RESTQuery (from fetchium/rest) or set \`static adapter = MyAdapter\` on your query class.`);const h=typeof u.prototype.sendNext=="function",g=c?a:new v(d.ENTITY|d.OBJECT,a.shape,void 0,void 0,s,ht);return n=new W({id:s,shape:g,cache:f,rawFetchNext:l,hasSendNext:h,isEntityResult:c,adapterClass:u},r),Lt.set(t,n),n}}const ln=(e,t)=>{const n=W.for(e);return xt(n,t)};function hn(e,...t){const n=W.for(e),i=C.getContext(Se);if(i===void 0)throw new Error("QueryClient not found");const r=t[0];return i.getQuery(n,r)}function ut(e){if(e.reason!==void 0)return e.reason;if(typeof DOMException<"u")return new DOMException("The operation was aborted","AbortError");const t=new Error("The operation was aborted");return t.name="AbortError",t}function pe(e,t){return new Promise((n,i)=>{if(t?.aborted){i(ut(t));return}const r=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(r),i(ut(t))},{once:!0})})}async function dt(e,t,n){if(t.retries<0)throw new Error("retries must be non-negative");const i=Math.max(0,t.retries);let r;for(let s=0;s<=i;s++){if(n?.aborted)throw ut(n);try{return await e()}catch(o){if(r=o,s>=i)throw o;await pe(t.retryDelay(s),n)}}throw r}class yn{def;queryKey;storageKey=-1;relay;queryClient;initialized=!1;updatedAt=void 0;params=void 0;unsubscribe=void 0;_relayState=void 0;_isActive=!1;wasPaused=!1;currentParams=void 0;debounceTimer=void 0;config=void 0;retryConfig=St(void 0);_abortController=void 0;_executionCtx=void 0;_executionCtxKey=-1;rootEntity;_extraMethods={};_queryId=0;get key(){return this.queryKey}get relayState(){if(!this._relayState)throw new Error("Relay state not initialized");return this._relayState}constructor(t,n,i,r){this.def=t,this.queryClient=n,this.queryKey=i,this.params=r,this._extraMethods={__refetch:this.refetch},t.statics.hasSendNext&&(this._extraMethods.__fetchNext=this.fetchNext);const s=Kt(r);this._queryId=s!==void 0?x.hashValue(s):0,this.relay=C.relay(o=>{this._relayState=o;const a=()=>{this._isActive=!1,clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this._abortController?.abort(),this._abortController=void 0,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.unsubscribe?.(),this.unsubscribe=void 0;const f=this.config?.gcTime??Qt.DEFAULT_GC_TIME;this.queryClient.gcManager.schedule(this.queryKey,f,tt.Query)},c=(f=!1)=>{const{wasPaused:l,isPaused:u,initialized:h}=this;if(this.wasPaused=u,u&&!l&&h){a();return}this._isActive=!0;const g=Kt(this.params),p=xt(this.def,g),w=p!==this.storageKey;w&&(this.currentParams=g,this.storageKey=p),this.getOrCreateExecutionContext(),this.initialized?l||f?(this.queryClient.activateQuery(this),f&&this.updatedAt!==void 0&&this.setupSubscription(),this.relayState.isPending&&this._abortController===void 0?this.runQueryImmediately():(this.config?.refreshStaleOnReconnect??!0)&&this.isStale&&this.runDebounced()):w&&(this.setupSubscription(),this.runDebounced()):(this.queryClient.activateQuery(this),this.initialize())};return c(!0),{update:c,deactivate:a}},{desc:`Query(${t.statics.id})`})}applyData(t,n,i=!1,r){const s=this.def;return this.rootEntity=this.queryClient.parseAndApplyRootEntity(t,this._queryId,s.statics.shape,n,i,r),this.rootEntity._extraMethods===void 0&&(this.rootEntity._extraMethods=this._extraMethods,this.rootEntity._extraGetters={__hasNext:()=>this.hasNext,__isFetchingNext:()=>this._fetchNextPromise!==void 0}),this.rootEntity.getProxy(s.statics.shape)}saveQueryMetadata(){if(this.rootEntity===void 0||this.updatedAt===void 0)return;const t=new Map(this.rootEntity.entityRefs??[]);t.set(this.rootEntity,1),this.queryClient.saveQueryData(this.def,this.storageKey,{__entityRef:this.rootEntity.key},this.updatedAt,t)}async initialize(){const t=this.queryClient,n=this.relayState;this.initialized=!0;let i;try{i=await t.loadCachedQuery(this.def,this.storageKey),i!==void 0&&(this.updatedAt=i.updatedAt,n.value=this.applyData(i.value,!1,!1,i.preloadedEntities))}catch(r){t.store.deleteQuery(this.storageKey),t.getContext().log?.warn?.("Failed to initialize query, the query cache may be corrupted or invalid",r)}if(!this.isPaused)try{if(i!==void 0&&this.setupSubscription(),i===void 0||this.isStale){if(await pe(0),this.isPaused)return;this.runQueryImmediately()}}catch(r){n.setError(r)}}setupSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0;const t=this.config?.subscribe;if(!t)return;const n=this._executionCtx;this.unsubscribe=t.call(n,i=>{i.__eventSource=this.queryKey,this.queryClient.applyMutationEvent(i)})}getOrCreateExecutionContext(){return(this._executionCtx===void 0||this._executionCtxKey!==this.storageKey)&&(this._executionCtxKey=this.storageKey,this._executionCtx=this.def.createExecutionContext(this.currentParams??{},this.queryClient.getContext()),this._executionCtx.refetch=()=>this.refetch(),this._executionCtx.rawFetchNext=this.def.statics.rawFetchNext),this.resolveAndApplyOptions(),this._executionCtx}resolveAndApplyOptions(){const t=this.def.resolveOptions(this._executionCtx);this.config=t.config,this.retryConfig=t.retryConfig}async runQuery(){const t=this.def;if(this.isPaused)throw new Error("Query is paused due to network status");const n=this.getOrCreateExecutionContext(),i=this.queryClient.getAdapter(t.statics.adapterClass),r=this._abortController?.signal??new AbortController().signal;return dt(async()=>{const s=await i.send(n,r);this.updatedAt=Date.now();const o=this.applyData(s,!0);return this.saveQueryMetadata(),this.unsubscribe===void 0&&this.setupSubscription(),o},this.retryConfig,r)}runQueryImmediately(){this._abortController?.abort(),this._abortController=new AbortController,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.relayState.setPromise(this.runQuery())}runDebounced(){if(this.relayState.isPending)return;const t=this.config?.debounce??0;clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runQueryImmediately()},t)}refetch=()=>this.relayState.isPending?this.relay:(this.runQueryImmediately(),this.relay);markStale(){this.updatedAt=0,this._isActive&&!this.isPaused&&this.runDebounced()}get resolvedParams(){return this.currentParams}_fetchNextPromise=void 0;_fetchNextAbort=void 0;fetchNext=()=>{if(this.updatedAt===void 0)throw new Error("Cannot call __fetchNext before initial data has loaded");return this._fetchNextPromise!==void 0?this._fetchNextPromise:(queueMicrotask(()=>this.rootEntity?.notify()),this._fetchNextPromise=this.runFetchNext().then(t=>(this._fetchNextPromise=void 0,this.rootEntity?.notify(),t),t=>{throw this._fetchNextPromise=void 0,this.rootEntity?.notify(),t}),this._fetchNextPromise)};get hasNext(){if(this.rootEntity===void 0||!this._executionCtx)return!1;const t=this.queryClient.getAdapter(this.def.statics.adapterClass);return t.hasNext?(this._executionCtx.resultData=this.rootEntity.data,t.hasNext(this._executionCtx)):!1}async runFetchNext(){const t=this.def;this._fetchNextAbort=new AbortController;const n=this._fetchNextAbort.signal,i=this.getOrCreateExecutionContext();i.resultData=this.rootEntity.data;const r=this.queryClient.getAdapter(t.statics.adapterClass);return dt(async()=>{const s=await r.sendNext(i,n);this.updatedAt=Date.now();const o=this.applyData(s,!0,!0);return this.saveQueryMetadata(),o},this.retryConfig,n)}get isStale(){if(this.updatedAt===void 0)return!0;const t=this.config?.staleTime??0;return Date.now()-this.updatedAt>=t}get isPaused(){const t=this.config?.networkMode??$.Online;if(t===$.Always)return!1;const n=this.queryClient.networkManager.getOnlineSignal().value;switch(t){case $.Online:return!n;case $.OfflineFirst:return!n&&this.updatedAt===void 0;default:return!1}}}class pn{def;queryClient;_inFlight=!1;task;constructor(t,n){this.def=t,this.queryClient=n,this.task=this.createTask()}createTask(){return C.task(async t=>{if(this._inFlight)throw new Error("A mutation is already in progress. Await the previous call before starting a new one.");this._inFlight=!0;try{const n=await this.executeWithRetry(t),i=this.validateResponse(n);return this.processEffects(t,i),i}finally{this._inFlight=!1}},{desc:`Mutation(${this.def.id})`})}validateResponse(t){const n=this.def.responseShape;if(!(n instanceof v))return t;const i=this.queryClient.getContext().log?.warn??(()=>{}),r=new ft;return r.reset(void 0,void 0,i),fe(t,n,r)}processEffects(t,n){let i;if(this.def.hasGetEffects){const s=ot(this.def.captured,t??{},this.queryClient.getContext());s.result=n,i=s.getEffects()}else if(this.def.effects!==void 0){const s={params:t,result:n};i=Y(this.def.effects,s)}if(i===void 0)return;const r=this.queryClient;rt(i.creates,"create",r),rt(i.updates,"update",r),rt(i.deletes,"delete",r),i.invalidates&&r.invalidateQueries(i.invalidates)}executeWithRetry(t){const n=St(this.def.config?.retry,!0),i=this.queryClient.getAdapter(this.def.adapterClass);if(!i.sendMutation)throw new Error(`Adapter "${this.def.adapterClass.name}" does not implement sendMutation(). Add a sendMutation() method to handle mutations.`);return dt(async()=>{const r=new AbortController,s=ot(this.def.captured,t??{},this.queryClient.getContext());return await i.sendMutation(s,r.signal)},n)}}function gn(e){return typeof e=="string"?e:U(e).typenameValue}function rt(e,t,n){if(e)for(const[i,r]of e){const s=gn(i);s!==void 0&&n.applyMutationEvent({type:t,typename:s,data:r})}}const ge="__eventSource";function ve(e){return{field:e,segments:e.indexOf(".")!==-1?e.split("."):void 0}}function vn(e){return e.map(ve)}function mn(e,t){if(t.segments===void 0)return e[t.field];let n=e;for(const i of t.segments){if(n==null)return;n=n[i]}return n}function me(e,t){const n=[];for(let i=0;i<t.length;i++){const r=t[i],s=mn(e,r);if(s===void 0)return;n.push(r.field,s)}return x.hashValue(n)}function _n(e,t){if(e===void 0)return;const n=new Map;for(const[i,r]of e){const s=r.slice().sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0),o=[];let a=!0;for(const[c,f]of s){let l;if(Ht(f)){const u=Wt(f);l=gt(u,t)}else l=f;if(l===void 0){a=!1;break}o.push(c,l)}a&&n.set(i,x.hashValue(o))}return n.size>0?n:void 0}function Ut(e,t){const n=e.get(t);if(n!==void 0)return n.map(([i])=>i).sort()}class wn{fields;fieldPaths;_bindings=new Map;constructor(t){this.fields=t,this.fieldPaths=t.map(ve)}register(t,n){let i=this._bindings.get(t);i===void 0&&(i=new Set,this._bindings.set(t,i)),i.add(n)}unregister(t,n){const i=this._bindings.get(t);i!==void 0&&(i.delete(n),i.size===0&&this._bindings.delete(t))}getMatching(t){return this._bindings.get(t)}get isEmpty(){return this._bindings.size===0}}function qt(e){return x.hashValue(e)}class En{_groups=new Map;getOrCreateGroup(t){const n=qt(t);let i=this._groups.get(n);return i===void 0&&(i=new wn(t),this._groups.set(n,i)),i}register(t,n,i){this.getOrCreateGroup(n).register(t,i)}unregister(t,n,i){const r=qt(n),s=this._groups.get(r);s!==void 0&&(s.unregister(t,i),s.isEmpty&&this._groups.delete(r))}registerBinding(t,n){const i=t._constraintHashes.get(n);if(i===void 0)return;const r=Ut(t._constraintFieldRefs,n);r!==void 0&&this.register(i,r,t)}unregisterBinding(t,n){const i=t._constraintHashes.get(n);if(i===void 0)return;const r=Ut(t._constraintFieldRefs,n);r!==void 0&&this.unregister(i,r,t)}routeEvent(t,n,i,r,s,o){for(const a of this._groups.values()){const c=me(n,a.fieldPaths);if(c===void 0)continue;const f=a.getMatching(c);if(f!==void 0)for(const l of f)l.onEvent(t,i,r,s,o)}}}function Vt(e){const t=new Set;for(const n of e)if(typeof n=="object"&&n!==null){const i=P(n);i!==void 0&&t.add(i)}return t}class _e{_queryClient;_parent;_constraintHashes;_entityDefsByTypename;_constraintFieldRefs;instance;constructor(t,n,i,r,s,o){this._queryClient=i,this._parent=r,this._constraintHashes=s,this._constraintFieldRefs=n,this.instance=o,this._entityDefsByTypename=new Map;for(const a of t)a.typenameValue!==void 0&&this._entityDefsByTypename.set(a.typenameValue,a);nt.add(this)}getValue(){return this.instance.getValue()}toJSON(){return this.instance.getRawValue()}reset(t){this.instance.reset(t)}append(t){this.instance.append(t)}onEvent(t,n,i,r,s){const o=this._entityDefsByTypename.get(t);if(o===void 0)return;const a=this._queryClient.entityMap.getEntity(n);if(i==="delete"){const f=a!==void 0?a.getProxy(o):s;f!==void 0&&(this.instance.onEvent(n,f,s??a?.data??{},"delete"),r?.());return}if(a===void 0||!a.satisfiesDef(o))return;r?.();const c=a.getProxy(o);this.instance.onEvent(n,c,a.data,i)}destroy(){this._queryClient.unregisterLiveCollection(this);const t=this._parent.liveCollections,n=t.indexOf(this);n!==-1&&t.splice(n,1)}}class bn{_notifier;_items;_keys;_outputSignal;_queryClient;_parent;constructor(t,n,i,r,s,o){this._notifier=C.notifier(),this._items=i,this._keys=Vt(i),this._queryClient=t,this._parent=n;const a=r!==void 0&&s!==void 0,c=o!==void 0;(a||c)&&(this._outputSignal=C.reactiveSignal(()=>{this._notifier.consume();let f=this._items;if(a){const l=[];for(const u of f){if(typeof u!="object"||u===null){l.push(u);continue}const h=P(u);if(h===void 0){l.push(u);continue}const g=t.entityMap.getEntity(h);if(g===void 0){l.push(u);continue}g.consume(),me(g.data,r)===s&&l.push(u)}f=l}return c&&(f=(f===this._items?f.slice():f).sort(o)),f}))}onEvent(t,n,i,r){switch(r){case"create":this.add(t,n);break;case"update":!this.has(t)&&n!==void 0&&this.add(t,n);break;case"delete":this.remove(t);break}}getValue(){return this._outputSignal!==void 0?this._outputSignal.value:(this._notifier.consume(),this._items)}getRawValue(){return this._items}add(t,n){if(this._keys.has(t))return!1;this._keys.add(t),this._items.push(n);const i=this._queryClient.entityMap.getEntity(t);return i!==void 0&&(this._parent.addChildRef(i),i.save()),this._notifier.notify(),!0}remove(t){if(!this._keys.has(t))return!1;this._keys.delete(t);const n=this._findIndex(t);n!==-1&&this._items.splice(n,1);const i=this._queryClient.entityMap.getEntity(t);return i!==void 0&&this._parent.removeChildRef(i),this._notifier.notify(),!0}has(t){return this._keys.has(t)}reset(t){const n=this._items,i=Array.isArray(t)?t:[];this._items=i,this._keys=Vt(i);for(const r of i)if(typeof r=="object"&&r!==null){const s=P(r);if(s!==void 0){const o=this._queryClient.entityMap.getEntity(s);o!==void 0&&this._parent.addChildRef(o)}}for(const r of n)if(typeof r=="object"&&r!==null){const s=P(r);if(s!==void 0){const o=this._queryClient.entityMap.getEntity(s);o!==void 0&&this._parent.removeChildRef(o)}}this._notifier.notify()}append(t){if(Array.isArray(t))for(const n of t){if(typeof n!="object"||n===null)continue;const i=P(n);i!==void 0&&this.add(i,n)}}_findIndex(t){for(let n=0;n<this._items.length;n++){const i=this._items[n];if(typeof i=="object"&&i!==null&&P(i)===t)return n}return-1}}class Cn{_notifier;_value;_createdKeys;_deletedKeys;_queryClient;_parent;_onCreate;_onUpdate;_onDelete;constructor(t,n,i,r,s,o){this._notifier=C.notifier(),this._value=i,this._createdKeys=new Set,this._deletedKeys=new Set,this._queryClient=t,this._parent=n,this._onCreate=r,this._onUpdate=s,this._onDelete=o}onEvent(t,n,i,r){switch(r){case"create":if(this._createdKeys.has(t))return;this._createdKeys.add(t),this._value=this._onCreate(this._value,n);break;case"update":this._value=this._onUpdate(this._value,n??i);break;case"delete":if(this._deletedKeys.has(t))return;this._deletedKeys.add(t),this._value=this._onDelete(this._value,n??i);break}this._notifier.notify()}getValue(){return this._notifier.consume(),this._value}getRawValue(){return this._value}reset(t){this._value=t,this._createdKeys.clear(),this._deletedKeys.clear(),this._notifier.notify()}append(t){}}function we(e,t,n,i,r){let s=e.constraintFieldRefs;if(s===void 0){s=new Map;for(const f of e.entityDefs){const l=f.typenameValue;l!==void 0&&s.set(l,[[ge,n.key]])}}const o=_n(s,i)??new Map;let a;if(e.type===Z.Array){let f,l;if(e.constraintFieldRefs!==void 0&&o.size>0&&o.size===1)for(const[u]of e.constraintFieldRefs){const h=o.get(u);if(h!==void 0){l=h;const g=e.constraintFieldRefs.get(u);g!==void 0&&(f=vn(g.map(([p])=>p)));break}}a=new bn(r,n,Array.isArray(t)?t:[],f,l,e.sort)}else a=new Cn(r,n,t,e.onCreate,e.onUpdate,e.onDelete);const c=new _e(e.entityDefs,s,r,n,o,a);return n.liveCollections.push(c),r.registerLiveCollection(c),c}const Ee=Object.entries,be=Object.prototype;function st(e,t,n,i=!1){const r=e.queryClient;r.currentParseId++;const s=e.seen,o=new Map;return{data:H(t,s,r,n,o,i),entityRefs:o}}function H(e,t,n,i,r,s){if(typeof e!="object"||e===null)return e;const o=t.get(e);if(o!==void 0)return On(o,t,n,i,r,s);if(Array.isArray(e)){for(let a=0;a<e.length;a++){const c=e[a];typeof c=="object"&&c!==null&&!(c instanceof G)&&!R.has(c)&&(e[a]=H(c,t,n,i,r,s))}return e}if(Object.getPrototypeOf(e)===be&&!R.has(e)){const a=e;for(const c of Object.keys(a)){const f=a[c];typeof f=="object"&&f!==null&&!(f instanceof G)&&!R.has(f)&&(a[c]=H(f,t,n,i,r,s))}}return e}function Ce(e){return typeof e=="object"&&e!==null&&!(e instanceof G)&&!R.has(e)}function On(e,t,n,i,r,s){const{key:o,data:a,shape:c,rawKeys:f}=e,l=c.shape,u=n.prepareEntity(o,a,c),h=u.data,g=h!==a,p=g&&f!==void 0&&u.entityRefs!==void 0?new Map(u.entityRefs):new Map;if(g?(Oe(l,a,h,f,u,h,t,n,i,p,s),u.notify()):Re(l,a,u,a,t,n,i,p,s),s&&u.liveCollections.length>0)for(const m of u.liveCollections){const S=m.instance.getRawValue();if(Array.isArray(S))for(const T of S){if(typeof T!="object"||T===null)continue;const A=R.get(T);if(A===void 0)continue;const V=n.entityMap.getEntity(A);V!==void 0&&p.set(V,(p.get(V)??0)+1)}}u.setChildRefs(p.size>0?p:void 0,i);const w=u.getProxy(c);return r.set(u,(r.get(u)??0)+1),w}function Oe(e,t,n,i,r,s,o,a,c,f,l){for(const[u,h]of Ee(e))if(!(i!==void 0&&!i.has(u)))if(Ce(t[u])&&(t[u]=H(t[u],o,a,c,f,l)),h instanceof v&&h._liveConfig!==void 0){const g=n[u];g instanceof _e?l?g.append(t[u]):g.reset(t[u]):n[u]=we(h._liveConfig,t[u],r,s,a)}else{const g=t[u],p=n[u];if(lt(g)&&lt(p)){const w=h instanceof v&&h.shape!==void 0?h.shape:void 0;if(w!==void 0)Oe(w,g,p,void 0,r,s,o,a,c,f,l);else for(const m of Object.keys(g))p[m]=g[m];n[u]=p}else n[u]=g}}function Re(e,t,n,i,r,s,o,a,c){for(const[f,l]of Ee(e))if(f in t)if(Ce(t[f])&&(t[f]=H(t[f],r,s,o,a,c)),l instanceof v&&l._liveConfig!==void 0)t[f]=we(l._liveConfig,t[f],n,i,s);else{const u=t[f];if(lt(u)){const h=l instanceof v&&l.shape!==void 0?l.shape:void 0;h!==void 0&&Re(h,u,n,i,r,s,o,a,c)}}}function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===be&&!R.has(e)}function Rn(e){if(e!==void 0)return typeof e=="string"?e:typeof e=="function"?e():e.value}function Sn(e){return C.isSignal(e)}function Kt(e){if(e===void 0)return;const t={};for(const[n,i]of Object.entries(e))Sn(i)?t[n]=i.value:t[n]=i;return t}const xt=(e,t)=>x.hashValue([e.statics.id,t]);class xn{entityMap;queryInstances=new Map;mutationInstances=new Map;gcManager;networkManager;isServer;store;currentParseId=0;context;typenameRegistry=new Map;constraintRegistry=new Map;mergedDefCache=new Map;adapters=new Map;networkUnsubscribe;constructor(t={}){const{store:n=new Dt.SyncQueryStore(new Dt.MemoryPersistentStore),log:i,evictionMultiplier:r,adapters:s,networkManager:o,gcManager:a,...c}=t;this.isServer=typeof window>"u",this.store=n,this.context={...c,log:i??console,evictionMultiplier:r},this.gcManager=t.gcManager??(this.isServer?new Yt:new Bt(this.handleEviction,r)),this.networkManager=t.networkManager??new Ot,this.entityMap=new fn((u,h,g)=>this.store.saveEntity(u,h,g));for(const u of t.adapters??[])this.adapters.set(u.constructor,u),u.register(this);const f=this.networkManager.getOnlineSignal(),l=C.watcher(()=>f.value);this.networkUnsubscribe=l.addListener(()=>{const u=f.value;for(const h of this.adapters.values())h.onNetworkStatusChange?.(u)},{skipInitial:!0}),this.store.purgeStaleQueries?.()}getAdapter(t){const n=this.adapters.get(t);if(n)return n;let i;for(const s of this.adapters.values())if(s instanceof t){if(i!==void 0)throw new Error(`Adapter lookup for ${t.name} matches multiple registered adapters: ${i.constructor.name} and ${s.constructor.name}. Register only one adapter per lookup base on a single QueryClient, or split into separate QueryClients.`);i??=s}if(i!==void 0)return this.adapters.set(t,i),i;let r;try{r=new t}catch{throw new Error(`No adapter registered for ${t.name} and auto-instantiation failed. Pass an instance via QueryClient config: new QueryClient({ store, adapters: [new ${t.name}(...)] })`)}return this.adapters.set(t,r),r.register(this),r}getContext(){return this.context}registerEntityDef(t){const n=t.typenameValue;if(n===void 0||t._entityClass===void 0)return;const i=this.typenameRegistry.get(n);if(i!==void 0){if(i.indexOf(t)!==-1)return;i.push(t),this.mergedDefCache.delete(n),this.getMergedDef(n)}else this.typenameRegistry.set(n,[t])}getEntityDefsForTypename(t){return this.typenameRegistry.get(t)}getMergedDef(t){let n=this.mergedDefCache.get(t);if(n!==void 0)return n;const i=this.typenameRegistry.get(t);if(i!==void 0)return n=v.merge(i),this.mergedDefCache.set(t,n),n}saveQueryData(t,n,i,r,s){const o=s!==void 0&&s.size>0?new Set([...s.keys()].map(a=>a.key)):void 0;this.store.saveQuery(t,n,i,r,o)}activateQuery(t){const{def:n,queryKey:i,storageKey:r,config:s}=t;this.store.activateQuery(n,r);const o=s?.gcTime??Qt.DEFAULT_GC_TIME;this.gcManager.cancel(i,o)}loadCachedQuery(t,n){return this.store.loadQuery(t,n)}getQuery(t,n){const i=xt(t,n);let r=this.queryInstances.get(i);return r===void 0&&(r=new yn(t,this,i,n),this.queryInstances.set(i,r)),r.relay}getMutation(t){const n=t.id;let i=this.mutationInstances.get(n);return i===void 0&&(i=new pn(t,this),this.mutationInstances.set(n,i)),i.task}parseData(t,n,i){const r=this.context.log?.warn??(()=>{}),s=new ft;return s.reset(this,i,r),{data:fe(t,n,s),ctx:s}}applyRefs(t,n=!0,i=!1){return st(t.ctx,t.data,n,i)}parseAndApplyRootEntity(t,n,i,r,s=!1,o){typeof i.idField=="symbol"&&typeof t=="object"&&t!==null&&!("__entityRef"in t)&&(t[ht]=n);const a=this.parseData(t,i,o),c=st(a.ctx,a.data,r,s),f=R.get(c.data);return this.entityMap.getEntity(f)}prepareEntity(t,n,i){return this.registerEntityDef(i),this.entityMap.getOrCreateEntity(t,n,i,this)}applyMutationEvent(t){const{type:n,typename:i}=t,r=this.getMergedDef(i);if(r===void 0)return;const s=r.idField;if(s===void 0||typeof s=="symbol")return;const o=t.data,a=t.id!==void 0?t.id:n==="delete"&&(typeof o=="string"||typeof o=="number")?o:o[s];if(a===void 0)return;const c=x.hashValue([i,a]),f=t.__eventSource,l=typeof o=="object"&&o!==null?o:{},u=this.entityMap.getEntity(c);if(n==="delete"){const w=u!==void 0?u.data:l;this.routeEvent(i,w,c,n,f,void 0,w);return}try{const w=this.context.log?.warn??(()=>{}),m=new ft;m.reset(this,void 0,w,!0);const S=Je(l,r,m);st(m,S,!0)}catch(w){if(this.context.log?.warn?.("Failed to apply mutation event",w),u===void 0){const m=this.entityMap.getEntity(c);m!==void 0&&m.evict()}return}const h=this.entityMap.getEntity(c);if(h===void 0)return;this.entityMap.save(h);const g=u===void 0;let p=!1;this.routeEvent(i,h.data,c,n,f,()=>{p=!0}),g&&!p&&h.evict()}invalidateQueries(t){for(const n of t){const i=Array.isArray(n),r=i?n[0]:n,s=i?n[1]:void 0,a=W.for(r).statics.id;for(const[,c]of this.queryInstances)c.def.statics.id===a&&(s===void 0||An(c.resolvedParams,s))&&c.markStale()}}handleEviction=(t,n)=>{if(n===tt.Query){const r=this.queryInstances.get(t);if(r===void 0)return;r.rootEntity?.evict(),this.queryInstances.delete(t);return}const i=this.entityMap.getEntity(t);i!==void 0&&i.evict()};getOrCreateMatcher(t){let n=this.constraintRegistry.get(t);return n===void 0&&(n=new En,this.constraintRegistry.set(t,n)),n}registerLiveCollection(t){for(const[n,i]of t._entityDefsByTypename)this.registerEntityDef(i),this.getOrCreateMatcher(n).registerBinding(t,n)}unregisterLiveCollection(t){for(const n of t._entityDefsByTypename.keys()){const i=this.constraintRegistry.get(n);i!==void 0&&i.unregisterBinding(t,n)}}routeEvent(t,n,i,r,s,o,a){const c=this.constraintRegistry.get(t);if(c===void 0)return;const f=s!==void 0?{...n,[ge]:s}:n;c.routeEvent(t,f,i,r,o,a)}destroy(){this.networkUnsubscribe?.(),this.gcManager.destroy(),this.networkManager.destroy();for(const t of this.adapters.values())t.destroy?.();this.adapters.clear(),this.queryInstances.clear(),this.mutationInstances.clear(),this.constraintRegistry.clear(),this.typenameRegistry.clear(),this.mergedDefCache.clear()}}const Se=C.context(void 0);function An(e,t){if(e===void 0)return!1;for(const n in t)if(e[n]!==t[n])return!1;return!0}exports.ARRAY_KEY=I;exports.Entity=et;exports.GcManager=Bt;exports.LiveFieldConfig=L;exports.LiveFieldType=Z;exports.Mask=d;exports.NetworkManager=Ot;exports.NetworkManagerContext=un;exports.NetworkMode=$;exports.NoOpGcManager=Yt;exports.NoOpNetworkManager=Rt;exports.QUERY_ID=ht;exports.Query=dn;exports.QueryClient=xn;exports.QueryClientContext=Se;exports.RECORD_KEY=k;exports.ValidatorDef=v;exports.createDefinitionProxy=pt;exports.defaultNetworkManager=ye;exports.draft=We;exports.extractDefinition=zt;exports.fetchQuery=hn;exports.queryKeyForClass=ln;exports.registerFormat=Et;exports.reifyValue=Y;exports.resolveBaseUrl=Rn;exports.t=ae;
2
- //# sourceMappingURL=QueryClient-QKhS8mhg.js.map
@@ -1,2 +0,0 @@
1
- "use strict";const C=require("signalium"),S=require("signalium/utils"),qt=require("./shared-Ct5zKrt4.js"),St=require("./stores/sync.js");var P=(e=>(e.Always="always",e.Online="online",e.OfflineFirst="offlineFirst",e))(P||{}),d=(e=>(e[e.UNDEFINED=1]="UNDEFINED",e[e.NULL=2]="NULL",e[e.NUMBER=4]="NUMBER",e[e.STRING=8]="STRING",e[e.BOOLEAN=16]="BOOLEAN",e[e.OBJECT=32]="OBJECT",e[e.ARRAY=64]="ARRAY",e[e.ID=128]="ID",e[e.RECORD=256]="RECORD",e[e.UNION=512]="UNION",e[e.ENTITY=1024]="ENTITY",e[e.HAS_FORMAT=4096]="HAS_FORMAT",e[e.IS_EAGER_FORMAT=8192]="IS_EAGER_FORMAT",e[e.PARSE_RESULT=16384]="PARSE_RESULT",e[e.LIVE=32768]="LIVE",e))(d||{});const U=Symbol("array"),V=Symbol("record"),dt=Symbol("QUERY_ID");var H=(e=>(e[e.Array=0]="Array",e[e.Value=1]="Value",e))(H||{});class j{type;entityDefs;constraintFieldRefs;sort;valueType;onCreate;onUpdate;onDelete;constructor(t,i,n,s,r,o,a,c){this.type=t,this.entityDefs=i,this.constraintFieldRefs=n,this.sort=s,this.valueType=r,this.onCreate=o,this.onUpdate=a,this.onDelete=c}static array(t,i,n){return new j(0,t,i,n,void 0,void 0,void 0,void 0)}static value(t,i,n,s,r,o){return new j(1,t,i,void 0,n,s,r,o)}}const O=new WeakMap;function F(e){return O.get(e)}var J=(e=>(e[e.Query=0]="Query",e[e.Entity=1]="Entity",e))(J||{});class Ee{constructor(t,i,n){this._onEvict=i,this._intervalId=setInterval(this._tick,t*6e4*n)}_currentFlush=new Map;_nextFlush=new Map;_intervalId;schedule(t,i){this._nextFlush.set(t,i)}cancel(t){this._currentFlush.delete(t),this._nextFlush.delete(t)}_tick=()=>{const{_currentFlush:t,_nextFlush:i,_onEvict:n}=this;for(const[s,r]of t)n(s,r);this._currentFlush=i,this._nextFlush=new Map};destroy(){clearInterval(this._intervalId)}}class Ut{_buckets=new Map;_nextTickEntries=new Map;_nextTickScheduled=!1;_onEvict;_multiplier;constructor(t,i=1){this._onEvict=t,this._multiplier=i}schedule(t,i,n){if(i===1/0)return;if(i===0){const{_nextTickEntries:o}=this;o.set(t,n),this._nextTickScheduled||(this._nextTickScheduled=!0,setTimeout(this._flushNextTick,0));return}const{_buckets:s}=this;let r=s.get(i);r||(r=new Ee(i,this._onEvict,this._multiplier),s.set(i,r)),r.schedule(t,n)}cancel(t,i){if(i!==1/0){if(i===0){this._nextTickEntries.delete(t);return}this._buckets.get(i)?.cancel(t)}}_flushNextTick=()=>{const{_nextTickEntries:t,_onEvict:i}=this;this._nextTickScheduled=!1;for(const[n,s]of t)i(n,s);t.clear()};destroy(){const{_buckets:t,_nextTickEntries:i}=this;for(const n of t.values())n.destroy();t.clear(),i.clear()}}class Vt{schedule(t,i,n){}cancel(t,i){}destroy(){}}const W=Symbol("fieldRef"),M=Symbol("fieldRefPath"),lt=Symbol("DEFINITION_TARGET"),z=Symbol("CANCEL_PROXY"),be=/\[([^\]]+)\]/g;function Kt(e){const t={[W]:!0,[M]:e};return new Proxy(t,Ce)}const Ce={get(e,t){if(t===W)return!0;if(t===M)return e[M];if(t===Symbol.toPrimitive||t==="toString"||t==="valueOf"){const n=e[M];return()=>`[${n.join(".")}]`}if(typeof t=="symbol")return;const i=e[M];return Kt([...i,t])},has(e,t){return t===W||t===M}};function $t(e){return typeof e=="object"&&e!==null&&e[W]===!0}function Qt(e){return e[M]}function ht(e){return new Proxy(e,{set(t,i,n){return t[i]=n,!0},get(t,i){return i===lt?t:i===z?()=>{}:typeof i=="symbol"?t[i]:Kt([i])}})}function Bt(e){const t=e[lt];e[z]();const i={};for(const r of Object.getOwnPropertyNames(t))i[r]=t[r];const n={};let s=Object.getPrototypeOf(t);for(;s&&s!==Object.prototype;){for(const r of Object.getOwnPropertyNames(s)){if(r==="constructor")continue;const o=Object.getOwnPropertyDescriptor(s,r);typeof o.value=="function"&&!(r in n)&&(n[r]=o.value)}s=Object.getPrototypeOf(s)}return{fields:i,methods:n}}function yt(e,t){let i=t;for(const n of e){if(i==null)return;i=i[n]}return i}function xe(e,t){return e.replace(be,(i,n)=>{const s=n.split("."),r=yt(s,t);return r!=null?encodeURIComponent(String(r)):""})}function K(e,t){if($t(e))return yt(Qt(e),t);if(typeof e=="string")return xe(e,t);if(Array.isArray(e))return e.map(i=>K(i,t));if(typeof e=="object"&&e!==null&&Object.getPrototypeOf(e)===Object.prototype){const i={};for(const n of Object.keys(e))i[n]=K(e[n],t);return i}return e}function st(e,t,i){const n=e.fields,s=e.methods,r={params:t},o={};for(const[a,c]of Object.entries(n))o[a]=K(c,r);o.params=t,o.context=i;for(const[a,c]of Object.entries(s))o[a]=c.bind(o);return o}class X{static cache;constructor(){return ht(this)}}const Yt=Object.entries,rt=Object.keys;function At(e){return typeof e=="number"?e|d.UNDEFINED:e instanceof _?(e.mask&d.UNDEFINED)!==0?e:_.cloneWith(e,d.UNDEFINED):e}function Oe(e){return e instanceof _&&(e.mask&d.OBJECT)!==0&&(e.mask&(d.ENTITY|d.ARRAY|d.UNION|d.RECORD|d.LIVE))===0}function Gt(e,t,i){const n=new Set;for(const r of e)if(r!==void 0)for(const o of Object.keys(r))n.add(o);const s={};for(const r of n){let o=0,a;const c=[];let f=!0;for(const l of e){const u=l?.[r];u!==void 0?(o++,a===void 0&&(a=u),Oe(u)?c.push(u.shape):(f=!1,c.push(void 0))):(f=!1,c.push(void 0))}if(f&&o>0){const l=Gt(c,t),u=new _(d.OBJECT,l);s[r]=o<t?At(u):u}else s[r]=o<t?At(a):a}return s}class _{mask;shape;typenameField=void 0;typenameValue=void 0;idField=void 0;values=void 0;_methods=void 0;_entityConfig=void 0;_entityClass=void 0;_entityCache=void 0;_liveConfig=void 0;constructor(t,i,n,s,r,o){this.mask=t,this.shape=i,this.values=n,this.typenameField=s,this.typenameValue=r,this.idField=o}static merge(t){if(t.length===1)return t[0];const i=t.length,n=t.map(c=>c.shape);t[0].typenameValue;const s=Gt(n,i);let r,o,a;for(const c of t){if(r===void 0&&c.idField!==void 0)r=c.idField;else if(r!==void 0&&c.idField!==void 0&&c.idField!==r)throw new Error(`[fetchium] Entity typename '${c.typenameValue}' has conflicting id fields: '${String(r)}' vs '${String(c.idField)}'`);o===void 0&&(o=c.typenameField),a===void 0&&(a=c.typenameValue)}return new _(d.ENTITY|d.OBJECT,s,void 0,o,a,r)}static cloneWith(t,i){const n=new _(i|t.mask,t.shape,t.values,t.typenameField,t.typenameValue,t.idField);return n._methods=t._methods,n._entityConfig=t._entityConfig,n._entityClass=t._entityClass,n._entityCache=t._entityCache,n._liveConfig=t._liveConfig,n}}class Z extends Set{lowercaseMap;constructor(t){super(t),this.lowercaseMap=new Map;for(const i of t)if(typeof i=="string"){const n=i.toLowerCase(),s=this.lowercaseMap.get(n);if(s!==void 0)throw new Error(`Case-insensitive enum cannot have multiple values with the same lowercase form: '${s}' and '${i}' both become '${n}'`);this.lowercaseMap.set(n,i)}}has(t){return this.get(t)!==void 0}get(t){if(typeof t=="string")return this.lowercaseMap.get(t.toLowerCase());if(super.has(t))return t}}const Re=1128875347;S.registerCustomHash(Z,e=>{let t=Re;for(const i of e)t+=S.hashValue(i);return t>>>0});function pt(e,t){return new _(e,t)}function Se(e){return pt(d.ARRAY,e)}function Ae(e){return pt(d.RECORD|d.OBJECT,e)}function De(e){return pt(d.PARSE_RESULT,e)}function Wt(e,t){let i=e,n,s,r;for(const[o,a]of Yt(t))switch(typeof a){case"number":if((a&d.ID)!==0){if(n!==void 0)throw new Error(`Duplicate id field: ${o}`);n=o}break;case"string":if(s!==void 0&&s!==o)throw new Error(`Duplicate typename field: ${o}`);s=o,r=a;break;case"object":if(a instanceof Z||a instanceof Set)break;a.mask&d.LIVE&&(i|=d.LIVE);break}return new _(i,t,void 0,s,r,n)}function Ne(e){return Wt(d.OBJECT,e)}function Dt(e,t,i){const n=e.mask;if((n&d.UNION)!==0){const s=e;if(s.typenameField!==void 0){if(i!==void 0&&i!==s.typenameField)throw new Error(`Union typename field conflict: Cannot merge unions with different typename fields ('${i}' vs '${s.typenameField}')`);i=s.typenameField}const r=s.shape;if(r!==void 0)for(const o of[...rt(r),U,V]){const a=r[o];if(t[o]!==void 0&&t[o]!==a)throw new Error(`Union merge conflict: Duplicate typename value '${String(o)}' found when merging nested unions (${String(t[o])} vs ${String(a)})`);t[o]=a}}else if((n&d.ARRAY)!==0){if(t[U]!==void 0)throw new Error("Array shape already defined");t[U]=e.shape}else if((n&d.RECORD)!==0){if(t[V]!==void 0)throw new Error("Record shape already defined");t[V]=e.shape}else{const s=e.typenameField,r=e.typenameValue;if(r===void 0)throw new Error("Object definitions must have a typename to be in a union with other objects, records, or arrays");if(i!==void 0&&s!==i)throw new Error("Object definitions must have the same typename field to be in the same union");i=s,t[r]=e}return i}function gt(...e){const t=e;let i=0,n=0,s,r,o,a,c=0;for(const l of t){if(typeof l=="number"){i|=l;continue}if(l instanceof Set){if(r===void 0)r=new Set(l);else for(const u of l)r.add(u);continue}if(n++,c|=l.mask,n===1){s=l;continue}n===2&&(o=Object.create(null),a=Dt(s,o,a)),a=Dt(l,o,a)}if(n===0)return r===void 0?i:i===0?r:new _(i|d.UNION,void 0,r);if(n===1)return _.cloneWith(s,i);const f=i|c|d.UNION;return new _(f,o,r,a)}function vt(e,t,i){const n=e;if(typeof n=="number")return n|t;if(n instanceof Set)return gt(e,t);let s=i.get(n);return s===void 0&&(s=_.cloneWith(n,t),i.set(n,s)),s}const Ie=new WeakMap,Me=new WeakMap,ke=new WeakMap;function Fe(e){return vt(e,d.UNDEFINED|d.NULL,ke)}function Te(e){return vt(e,d.UNDEFINED,Ie)}function Pe(e){return vt(e,d.NULL,Me)}function je(e){return e}function Le(e){return new Set([e])}const zt=((...e)=>new Set(e));zt.caseInsensitive=(...e)=>new Z(e);const Ht=16;let qe=0;const ot=[],Jt=[],Xt=new Map,tt=new WeakSet;class ${_raw;_formatted;_parsed;_formatId;constructor(t,i,n){this._raw=t,this._formatId=i,n?(this._formatted=ot[i](t),this._parsed=!0):this._parsed=!1,tt.add(this)}getValue(){return this._parsed||(this._formatted=ot[this._formatId](this._raw),this._parsed=!0),this._formatted}toJSON(){return this._parsed?Jt[this._formatId](this._formatted):this._raw}}function Ue(e){const t=Xt.get(e);if(t===void 0)throw new Error(`Format ${e} not registered`);return t}function _t(e,t,i,n,s){const r=qe++;ot[r]=i,Jt[r]=n;const o=s?.eager??!0,c=r<<Ht|t|d.HAS_FORMAT|(o?d.IS_EAGER_FORMAT:0);Xt.set(e,c)}_t("date",d.STRING,e=>{const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)throw new Error(`Invalid date string: ${e}. Expected YYYY-MM-DD format.`);const[,i,n,s]=t,r=new Date(Date.UTC(parseInt(i,10),parseInt(n,10)-1,parseInt(s,10)));if(isNaN(r.getTime()))throw new Error(`Invalid date string: ${e}`);return r},e=>{const t=e.getUTCFullYear(),i=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0");return`${t}-${i}-${n}`});_t("date-time",d.STRING,e=>{const t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date-time string: ${e}`);return t},e=>e.toISOString());const Nt=new WeakMap;function L(e){let t=Nt.get(e);if(t===void 0){const i=new e,n=i[lt]??i;i[z]&&i[z]();const s={};for(const[f,l]of Yt(n))s[f]=l;const r=Object.getPrototypeOf(e.prototype);if(r!=null){const f=r.constructor;if(f!==X&&typeof f=="function"){const u=L(f).shape;for(const y of rt(u))if(y in s&&s[y]!==u[y])throw new Error(`Cannot extend: field '${y}' already exists in type definition`)}}const o={},a=e.prototype;for(const f of Object.getOwnPropertyNames(a))f!=="constructor"&&typeof a[f]=="function"&&(o[f]=a[f]);t=Wt(d.ENTITY|d.OBJECT,s),t._entityClass=e,rt(o).length>0&&(t._methods=o),typeof o.__subscribe=="function"&&(t._entityConfig={hasSubscribe:!0});const c=e;c.cache&&(t._entityCache=c.cache),Nt.set(e,t)}return t}function Ve(e){return L(e)}function Zt(e,t){if(t==null)return;const i=new Map;if(Array.isArray(t))for(const n of t){const[s,r]=n,a=L(s).typenameValue;if(a===void 0)continue;const c=[];for(const[f,l]of Object.entries(r))c.push([f,l]);c.length>0&&i.set(a,c)}else{const s=Object.entries(t);if(s.length===0)return;const r=s.map(([o,a])=>[o,a]);for(const o of e){const a=o.typenameValue;a!==void 0&&i.set(a,r)}}return i.size>0?i:void 0}function te(e){return Array.isArray(e)?e.map(t=>L(t)):[L(e)]}function Ke(e,t){const i=te(e),n=i.length===1?i[0]:gt(...i.map(o=>o)),s=d.ARRAY|d.LIVE,r=new _(s,n);return r._liveConfig=j.array(i,Zt(i,t?.constraints),t?.sort),r}function $e(e,t,i){const n=te(t),s=e,r=d.LIVE,o=new _(r,void 0);return o._liveConfig=j.value(n,Zt(n,i?.constraints),s,i.onCreate,i.onUpdate,i.onDelete),o}const ee={format:Ue,typename:je,const:Le,enum:zt,id:d.ID|d.STRING|d.NUMBER,string:d.STRING,number:d.NUMBER,boolean:d.BOOLEAN,null:d.NULL,undefined:d.UNDEFINED,array:Se,object:Ne,record:Ae,union:gt,nullish:Fe,optional:Te,nullable:Pe,result:De,entity:Ve,liveArray:Ke,liveValue:$e};function q(e,t,i){return new TypeError(`Validation error at ${e}`)}const ie=Array.isArray;function It(e){if(e===null)return d.NULL;switch(typeof e){case"number":return d.NUMBER;case"string":return d.STRING;case"boolean":return d.BOOLEAN;case"undefined":return d.UNDEFINED;case"object":return ie(e)?d.ARRAY:d.OBJECT;default:throw new Error(`Invalid type: ${typeof e}`)}}function Qe(e){return T(e)}function T(e){if(e===null||typeof e!="object")return e;if(ie(e))return e.map(i=>T(i));if(e instanceof Date)return new Date(e.getTime());if(e instanceof Map){const i=new Map;for(const[n,s]of e)i.set(T(n),T(s));return i}if(e instanceof Set){const i=new Set;for(const n of e)i.add(T(n));return i}const t={};for(const i of Object.keys(e))t[i]=T(e[i]);return t}const mt=Object.entries,Be=()=>{};class at{queryClient=void 0;preloadedEntities=void 0;warn=Be;isPartialEvent=!1;seen=void 0;seenByKey=void 0;reset(t,i,n,s=!1){this.queryClient=t,this.preloadedEntities=i,this.warn=n,this.isPartialEvent=s,t!==void 0&&(this.seen===void 0?(this.seen=new Map,this.seenByKey=new Map):(this.seen.clear(),this.seenByKey.clear()))}}function ne(e,t,i){return k(e,t,i,"")}function Ye(e,t,i){return wt(e,t,i)}function Mt(e,t,i,n){const s=e>>Ht;if((e&d.IS_EAGER_FORMAT)!==0)try{return new $(t,s,!0)}catch(o){if((e&d.UNDEFINED)!==0){i.warn("Invalid formatted value for optional type, defaulting to undefined",{value:t,path:n,error:o instanceof Error?o.message:String(o)});return}throw o}return new $(t,s,!1)}function k(e,t,i,n){const s=t;if(s instanceof Z){const c=s.get(e);if(c===void 0)throw q(n);return c}if(s instanceof Set){if(!s.has(e))throw q(n);return e}if(typeof s=="string"){if(e==null)return s;if(e!==s)throw q(n);return e}if(typeof s=="number"){const c=It(e);if((s&c)===0){if((s&d.UNDEFINED)!==0){i.warn("Invalid value for optional type, defaulting to undefined",{value:e,path:n});return}throw q(n)}return(s&d.HAS_FORMAT)!==0&&e!==null&&e!==void 0?Mt(s,e,i,n):e}const r=s.mask,o=s._liveConfig;if(o!==void 0&&o.type===H.Value)return o.valueType!==void 0?k(e,o.valueType,i,n):e;if((r&d.PARSE_RESULT)!==0)try{return{success:!0,value:k(e,s.shape,i,n)}}catch(c){return{success:!1,error:c instanceof Error?c:new Error(String(c))}}const a=It(e);if((r&a)===0&&!s.values?.has(e)){if((r&d.UNDEFINED)!==0){i.warn("Invalid value for optional type, defaulting to undefined",{value:e,path:n});return}throw q(n)}return a<d.OBJECT?(r&d.HAS_FORMAT)!==0&&e!==null&&e!==void 0?Mt(r,e,i,n):e:(r&d.UNION)!==0?Ge(a,e,s,i,n):a===d.ARRAY?se(e,s.shape,i,n):(r&d.RECORD)!==0?re(e,s.shape,i,n):(r&d.ENTITY)!==0&&i.queryClient!==void 0?wt(e,s,i):oe(e,s,i,n)}function Ge(e,t,i,n,s){if(e===d.ARRAY){const r=i.shape[U];return r===void 0||typeof r=="number"?t:se(t,r,n,s)}else{const r=i.typenameField,o=r?t[r]:void 0;if(o===void 0||typeof o!="string"){const c=i.shape[V];if(c===void 0)throw new Error(`Typename field '${r}' is required for union discrimination but was not found in the data`);return re(t,c,n,s)}const a=i.shape[o];if(a===void 0||typeof a=="number")throw new Error(`Unknown typename '${o}' in union`);return a.mask&d.ENTITY&&n.queryClient!==void 0?wt(t,a,n):oe(t,a,n,s)}}function se(e,t,i,n){const s=[];for(let r=0;r<e.length;r++)try{s.push(k(e[r],t,i,`${n}[${r}]`))}catch(o){i.warn("Failed to parse array item, filtering out",{index:r,value:e[r],error:o instanceof Error?o.message:String(o)})}return s}function re(e,t,i,n){for(const[s,r]of mt(e))e[s]=k(r,t,i,`${n}["${s}"]`);return e}function oe(e,t,i,n){if(O.has(e))return e;const s=t.shape;for(const[r,o]of mt(s))e[r]=k(e[r],o,i,`${n}.${r}`);return e}function wt(e,t,i){const n=i.queryClient,s=i.preloadedEntities;let r,o;if(s!==void 0)r=e.__entityRef,o=r;else{const p=e[t.idField];if(p==null||typeof p!="string"&&typeof p!="number")throw new Error(`Entity id must be a string or number: ${t.typenameValue} (got ${typeof p})`);o=p,r=S.hashValue([t.typenameValue,o])}const a=i.seenByKey.get(r);if(a!==void 0)return a.data;if(s!==void 0){const g=n.entityMap.getEntity(r)?.data??s.get(r);if(g===void 0)throw new Error(`Cached entity ${r} not found in preloaded map`);e=g}const c={};typeof t.idField=="symbol"&&(c[t.idField]=o);const f=n.entityMap.getEntity(r),l=i.isPartialEvent&&f!==void 0,u={key:r,shape:t,data:c,rawKeys:l?new Set(Object.keys(e)):void 0};i.seen.set(c,u),i.seenByKey.set(r,u);const y=`[[${t.typenameValue}:${o}]]`,v=t.shape;for(const[p,g]of mt(v))l&&!(p in e)||(c[p]=k(e[p],g,i,`${y}.${p}`));return c}function We(e,t){return ze(e,t.shape,t.typenameField)}function ze(e,t,i){if(t===void 0)return!0;for(const n of Object.keys(t)){if(n===i)continue;const s=t[n];if(s instanceof _){if((s.mask&d.UNDEFINED)!==0)continue;if(!(n in e)||e[n]===void 0)return!1}else if(typeof s=="number"){if((s&d.UNDEFINED)!==0)continue;if(!(n in e)||e[n]===void 0)return!1}else if(!(n in e)||e[n]===void 0)return!1}return!0}const He=Object.prototype,G=new WeakMap;function N(e){if(typeof e!="object"||e===null)return e;if(tt.has(e))return N(e.getValue());if(O.has(e))return e;if(Array.isArray(e)){let t=G.get(e);return t===void 0&&(t=new Proxy(e,Je),G.set(e,t)),t}if(Object.getPrototypeOf(e)===He){let t=G.get(e);return t===void 0&&(t=new Proxy(e,Xe),G.set(e,t)),t}return e}const Je={get(e,t,i){if(typeof t=="string"){const n=Number(t);if(Number.isInteger(n)&&n>=0&&n<e.length)return N(e[n])}return Reflect.get(e,t,i)},set(){return!1},deleteProperty(){return!1}},Xe={get(e,t,i){return typeof t=="string"?N(e[t]):Reflect.get(e,t,i)},set(){return!1},deleteProperty(){return!1},has(e,t){return t in e},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)}},Ze=(e,t,i)=>{const n=e,s=Object.keys(n),r=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0;let o=!r||Object.keys(r).length!==s.length;const a={};for(let c=0;c<s.length;c++){const f=s[c],l=n[f];let u;typeof l=="function"?u=l:u=i(l,r?.[f]),a[f]=u,!o&&u!==r?.[f]&&(o=!0)}return o?a:r},kt=new WeakSet;function ae(e){const t=e.prototype;kt.has(t)||(kt.add(t),S.registerCustomSnapshot(e,Ze))}ae(X);class ti{_notifier;_queryClient;_proxies=new Map;key;typename;id;idField;data;refCount=0;entityRefs;liveCollections=[];satisfiedDefs=new WeakSet;parseId=-1;_entityCache;_extraMethods;_extraGetters;constructor(t,i,n,s,r,o){this._notifier=C.notifier(),this._queryClient=o,this.key=t,this.typename=i,this.id=n,this.idField=s,this.data=r,this.entityRefs=void 0}retain(){this.refCount++;const t=this._entityCache?.gcTime;t!==void 0&&this._queryClient.gcManager.cancel(this.key,t)}release(){if(--this.refCount>0||this.refCount<0)return;const t=this._entityCache?.gcTime;t!==void 0?this._queryClient.gcManager.schedule(this.key,t,J.Entity):this.evict()}evict(){const t=this.liveCollections.slice();this.liveCollections.length=0;for(const n of t)n.destroy();this._queryClient.entityMap.remove(this.key);const i=this.entityRefs;if(this.entityRefs=void 0,i)for(const n of i.keys())n.release()}setChildRefs(t,i){const n=this.entityRefs;if(t!==void 0&&t.size>0)for(const s of t.keys())(n===void 0||!n.has(s))&&s.retain();if(n!==void 0&&n.size>0)for(const s of n.keys())(t===void 0||!t.has(s))&&s.release();this.entityRefs=t,i&&this.save()}addChildRef(t){this.entityRefs===void 0&&(this.entityRefs=new Map);const i=this.entityRefs.get(t)??0;this.entityRefs.set(t,i+1),i===0&&t.retain(),this.save()}removeChildRef(t){if(this.entityRefs===void 0)return;const i=this.entityRefs.get(t);i!==void 0&&(i<=1?(this.entityRefs.delete(t),t.release()):this.entityRefs.set(t,i-1),this.save())}getProxy(t){const i=t;let n=this._proxies.get(i);return n===void 0&&(n=ii(this,this.key,t,this._notifier,this._queryClient),this._proxies.set(i,n)),n}get proxy(){return this._proxies.values().next().value}satisfiesDef(t){return this.satisfiedDefs.has(t)?!0:We(this.data,t)?(this.satisfiedDefs.add(t),!0):!1}save(){this._queryClient.entityMap.save(this)}notify(){this._notifier.notify()}consume(){this._notifier.consume()}}function ei(e,t,i){const n=[];for(const s of e){if(typeof s!="object"||s===null)continue;const r=O.get(s);if(r===void 0)continue;const o=i.entityMap.getEntity(r);o!==void 0&&o.satisfiesDef(t)&&n.push(s)}return n}function ii(e,t,i,n,s){const r=i.shape??{},o=i,a=o._methods,c=o._entityClass,f=o._entityConfig,l=c?c.prototype:X.prototype;c!==void 0&&ae(c),i.typenameField;const u=new Map,y=new Map,v=()=>({__entityRef:t});let p;f?.hasSubscribe&&a&&"__subscribe"in a&&(p=C.relay(E=>{const h=b=>{b.__eventSource=t,s.applyMutationEvent(b)},m=a.__subscribe.call(g,h);return E.value=g,m}));let g;const w=Object.keys(r);if(w.includes("__typename")||w.push("__typename"),a)for(const E of Object.keys(a))w.includes(E)||w.push(E);let I,R=w;function Y(){const E=e._extraMethods;if(E!==I){if(I=E,R=w.slice(),E!==void 0)for(const m of Object.keys(E))R.includes(m)||R.push(m);const h=e._extraGetters;if(h!==void 0)for(const m of Object.keys(h))R.includes(m)||R.push(m)}return R}const A={getPrototypeOf(){return l},get(E,h){if(typeof h=="symbol")return;if(h==="toJSON")return v;if(h==="__context")return s.getContext();if(h==="__typename")return e.typename;if(p?.value,n.consume(),typeof h=="string"){const b=e._extraGetters;if(b!==void 0&&h in b)return b[h]();const D=e._extraMethods;if(D!==void 0&&h in D){let x=u.get(h);return x||(x=D[h].bind(g),u.set(h,x)),x}if(a&&h in a){let x=u.get(h);return x||(x=C.reactiveMethod(g,a[h].bind(g)),u.set(h,x)),x}}const m=e.data[h];if(typeof m=="object"&&m!==null&&tt.has(m))return N(m.getValue());if(Array.isArray(m)&&typeof h=="string"){const b=r[h];if(b instanceof _&&(b.mask&d.ARRAY)!==0){const D=b.shape;if(D instanceof _&&(D.mask&d.ENTITY)!==0){const x=D.typenameValue;if(x!==void 0){const Ot=s.getEntityDefsForTypename(x);if(Ot!==void 0&&Ot.length>1){const et=y.get(h);if(et!==void 0&&et.source===m)return N(et.filtered);const Rt=ei(m,D,s);return y.set(h,{source:m,filtered:Rt}),N(Rt)}}}}return N(m)}return N(m)},set(){return!1},has(E,h){if(h==="__typename")return!0;if(typeof h=="string"){const m=e._extraGetters;if(m&&h in m)return!0;const b=e._extraMethods;if(b&&h in b||a&&h in a)return!0}return h in r},ownKeys(){return Y()},getOwnPropertyDescriptor(E,h){if(h==="__typename")return{enumerable:!0,configurable:!0,value:e.typename,writable:!1};if(h in r)return{enumerable:!0,configurable:!0,value:A.get(E,h,g),writable:!1};if(typeof h=="string"){const m=e._extraGetters;if(m&&h in m)return{enumerable:!0,configurable:!0,value:A.get(E,h,g),writable:!1};const b=e._extraMethods;if(b&&h in b)return{enumerable:!0,configurable:!0,value:A.get(E,h,g),writable:!1};if(a&&h in a)return{enumerable:!1,configurable:!0,value:A.get(E,h,g),writable:!1}}}};return g=new Proxy({},A),O.set(g,t),C.setScopeOwner(g,s),g}class ni{instances=new Map;persistEntity;constructor(t){this.persistEntity=t}hasEntity(t){return this.instances.has(t)}getEntity(t){return this.instances.get(t)}getOrCreateEntity(t,i,n,s){let r=this.instances.get(t);if(r===void 0){const o=n.idField;if(o===void 0)throw new Error(`Entity id field is required ${n.typenameValue}`);const a=i[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Entity id must be string or number: ${n.typenameValue}`);const c=n;r=new ti(t,n.typenameValue,a,o,i,s),r._entityCache=c._entityCache,this.instances.set(t,r)}return r.parseId=s.currentParseId,r}remove(t){this.instances.delete(t)}save(t){let i;if(t.entityRefs){i=new Set;for(const n of t.entityRefs.keys())i.add(n.key)}this.persistEntity(t.key,t.data,i)}}class Et{onlineSignal;manualOverride=void 0;eventListenersAttached=!1;constructor(t){const i=t??this.detectOnlineStatus();this.onlineSignal=C.signal(i),this.canAttachListeners()&&this.attachEventListeners()}get isOnline(){return this.manualOverride!==void 0?this.manualOverride:this.onlineSignal.value}setNetworkStatus(t){this.manualOverride=t,this.onlineSignal.value=t}clearManualOverride(){this.manualOverride=void 0,this.onlineSignal.value=this.detectOnlineStatus()}getOnlineSignal(){return this.onlineSignal}detectOnlineStatus(){return typeof navigator<"u"&&"onLine"in navigator?navigator.onLine:!0}canAttachListeners(){return typeof window<"u"&&typeof window.addEventListener=="function"}destroy(){this.eventListenersAttached&&this.handleOnline&&this.handleOffline&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline),this.eventListenersAttached=!1)}handleOnline=void 0;handleOffline=void 0;attachEventListeners(){this.eventListenersAttached||(this.handleOnline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!0)},this.handleOffline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!1)},window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.eventListenersAttached=!0)}}class bt{static onlineSignal=C.signal(!0);get isOnline(){return!0}setNetworkStatus(t){}clearManualOverride(){}getOnlineSignal(){return bt.onlineSignal}destroy(){}}const ce=new Et,si=C.context(ce);function Ct(e,t=typeof window>"u"){let i;e===!1?i=0:e===void 0||e===!0?i=t?0:3:typeof e=="number"?i=e:i=e.retries;const n=typeof e=="object"&&e.retryDelay?e.retryDelay:s=>1e3*Math.pow(2,s);return{retries:i,retryDelay:n}}class ri{static cache;static adapter;params;config;constructor(){return ht(this)}}const Ft=new WeakMap;class B{constructor(t,i){this.captured=i,this.statics=t}statics;createExecutionContext(t,i){return st(this.captured,t,i)}resolveOptions(t){const{methods:i}=this.captured,n=i.getConfig?i.getConfig.call(t):t.config,s=Ct(n?.retry);return{config:n,retryConfig:s}}static for(t){let i=Ft.get(t);if(i!==void 0)return i;const n=new t,s=Bt(n),r=String(s.methods.getIdentityKey.call(s.fields)),o=s.fields.result,a=o instanceof _?o:ee.object(o),c=(a.mask&d.ENTITY)!==0,f=t.cache,l=s.fields.fetchNext,u=t.adapter;if(!u)throw new Error(`Query class "${t.name}" must define a static \`adapter\` property. Extend RESTQuery (from fetchium/rest) or set \`static adapter = MyAdapter\` on your query class.`);const y=typeof u.prototype.sendNext=="function",v=c?a:new _(d.ENTITY|d.OBJECT,a.shape,void 0,void 0,r,dt);return i=new B({id:r,shape:v,cache:f,rawFetchNext:l,hasSendNext:y,isEntityResult:c,adapterClass:u},s),Ft.set(t,i),i}}const oi=(e,t)=>{const i=B.for(e);return xt(i,t)};function ai(e,...t){const i=B.for(e),n=C.getContext(we);if(n===void 0)throw new Error("QueryClient not found");const s=t[0];return n.getQuery(i,s)}function ct(e){if(e.reason!==void 0)return e.reason;if(typeof DOMException<"u")return new DOMException("The operation was aborted","AbortError");const t=new Error("The operation was aborted");return t.name="AbortError",t}function fe(e,t){return new Promise((i,n)=>{if(t?.aborted){n(ct(t));return}const s=setTimeout(i,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(ct(t))},{once:!0})})}async function ft(e,t,i){const n=Math.max(0,t.retries);let s;for(let r=0;r<=n;r++){if(i?.aborted)throw ct(i);try{return await e()}catch(o){if(s=o,r>=n)throw o;await fe(t.retryDelay(r),i)}}throw s}class ci{def;queryKey;storageKey=-1;relay;queryClient;initialized=!1;updatedAt=void 0;params=void 0;unsubscribe=void 0;_relayState=void 0;_isActive=!1;wasPaused=!1;currentParams=void 0;debounceTimer=void 0;config=void 0;retryConfig=Ct(void 0);_abortController=void 0;_executionCtx=void 0;_executionCtxKey=-1;rootEntity;_extraMethods={};_queryId=0;get key(){return this.queryKey}get relayState(){return this._relayState}constructor(t,i,n,s){this.def=t,this.queryClient=i,this.queryKey=n,this.params=s,this._extraMethods={__refetch:this.refetch},t.statics.hasSendNext&&(this._extraMethods.__fetchNext=this.fetchNext);const r=Lt(s);this._queryId=r!==void 0?S.hashValue(r):0,this.relay=C.relay(o=>{this._relayState=o;const a=()=>{this._isActive=!1,clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this._abortController?.abort(),this._abortController=void 0,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.unsubscribe?.(),this.unsubscribe=void 0;const f=this.config?.gcTime??qt.DEFAULT_GC_TIME;this.queryClient.gcManager.schedule(this.queryKey,f,J.Query)},c=(f=!1)=>{const{wasPaused:l,isPaused:u,initialized:y}=this;if(this.wasPaused=u,u&&!l&&y){a();return}this._isActive=!0;const v=Lt(this.params),p=xt(this.def,v),g=p!==this.storageKey;g&&(this.currentParams=v,this.storageKey=p),this.getOrCreateExecutionContext(),this.initialized?l||f?(this.queryClient.activateQuery(this),f&&this.updatedAt!==void 0&&this.setupSubscription(),this.relayState.isPending&&this._abortController===void 0?this.runQueryImmediately():(this.config?.refreshStaleOnReconnect??!0)&&this.isStale&&this.runDebounced()):g&&(this.setupSubscription(),this.runDebounced()):(this.queryClient.activateQuery(this),this.initialize())};return c(!0),{update:c,deactivate:a}},{desc:`Query(${t.statics.id})`})}applyData(t,i,n=!1,s){const r=this.def;return this.rootEntity=this.queryClient.parseAndApplyRootEntity(t,this._queryId,r.statics.shape,i,n,s),this.rootEntity._extraMethods===void 0&&(this.rootEntity._extraMethods=this._extraMethods,this.rootEntity._extraGetters={__hasNext:()=>this.hasNext,__isFetchingNext:()=>this._fetchNextPromise!==void 0}),this.rootEntity.getProxy(r.statics.shape)}saveQueryMetadata(){if(this.rootEntity===void 0||this.updatedAt===void 0)return;const t=new Map(this.rootEntity.entityRefs??[]);t.set(this.rootEntity,1),this.queryClient.saveQueryData(this.def,this.storageKey,{__entityRef:this.rootEntity.key},this.updatedAt,t)}async initialize(){const t=this.queryClient,i=this.relayState;this.initialized=!0;let n;try{n=await t.loadCachedQuery(this.def,this.storageKey),n!==void 0&&(this.updatedAt=n.updatedAt,i.value=this.applyData(n.value,!1,!1,n.preloadedEntities))}catch(s){t.store.deleteQuery(this.storageKey),t.getContext().log?.warn?.("Failed to initialize query, the query cache may be corrupted or invalid",s)}if(!this.isPaused)try{if(n!==void 0&&this.setupSubscription(),n===void 0||this.isStale){if(await fe(0),this.isPaused)return;this.runQueryImmediately()}}catch(s){i.setError(s)}}setupSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0;const t=this.config?.subscribe;if(!t)return;const i=this._executionCtx;this.unsubscribe=t.call(i,n=>{n.__eventSource=this.queryKey,this.queryClient.applyMutationEvent(n)})}getOrCreateExecutionContext(){return(this._executionCtx===void 0||this._executionCtxKey!==this.storageKey)&&(this._executionCtxKey=this.storageKey,this._executionCtx=this.def.createExecutionContext(this.currentParams??{},this.queryClient.getContext()),this._executionCtx.refetch=()=>this.refetch(),this._executionCtx.rawFetchNext=this.def.statics.rawFetchNext),this.resolveAndApplyOptions(),this._executionCtx}resolveAndApplyOptions(){const t=this.def.resolveOptions(this._executionCtx);this.config=t.config,this.retryConfig=t.retryConfig}async runQuery(){const t=this.def;if(this.isPaused)throw new Error("Query is paused due to network status");const i=this.getOrCreateExecutionContext(),n=this.queryClient.getAdapter(t.statics.adapterClass),s=this._abortController?.signal??new AbortController().signal;return ft(async()=>{const r=await n.send(i,s);this.updatedAt=Date.now();const o=this.applyData(r,!0);return this.saveQueryMetadata(),this.unsubscribe===void 0&&this.setupSubscription(),o},this.retryConfig,s)}runQueryImmediately(){this._abortController?.abort(),this._abortController=new AbortController,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.relayState.setPromise(this.runQuery())}runDebounced(){if(this.relayState.isPending)return;const t=this.config?.debounce??0;clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runQueryImmediately()},t)}refetch=()=>this.relayState.isPending?this.relay:(this.runQueryImmediately(),this.relay);markStale(){this.updatedAt=0,this._isActive&&!this.isPaused&&this.runDebounced()}get resolvedParams(){return this.currentParams}_fetchNextPromise=void 0;_fetchNextAbort=void 0;fetchNext=()=>{if(this.updatedAt===void 0)throw new Error("Cannot call __fetchNext before initial data has loaded");return this._fetchNextPromise!==void 0?this._fetchNextPromise:(queueMicrotask(()=>this.rootEntity?.notify()),this._fetchNextPromise=this.runFetchNext().then(t=>(this._fetchNextPromise=void 0,this.rootEntity?.notify(),t),t=>{throw this._fetchNextPromise=void 0,this.rootEntity?.notify(),t}),this._fetchNextPromise)};get hasNext(){if(this.rootEntity===void 0||!this._executionCtx)return!1;const t=this.queryClient.getAdapter(this.def.statics.adapterClass);return t.hasNext?(this._executionCtx.resultData=this.rootEntity.data,t.hasNext(this._executionCtx)):!1}async runFetchNext(){const t=this.def;this._fetchNextAbort=new AbortController;const i=this._fetchNextAbort.signal,n=this.getOrCreateExecutionContext();n.resultData=this.rootEntity.data;const s=this.queryClient.getAdapter(t.statics.adapterClass);return ft(async()=>{const r=await s.sendNext(n,i);this.updatedAt=Date.now();const o=this.applyData(r,!0,!0);return this.saveQueryMetadata(),o},this.retryConfig,i)}get isStale(){if(this.updatedAt===void 0)return!0;const t=this.config?.staleTime??0;return Date.now()-this.updatedAt>=t}get isPaused(){const t=this.config?.networkMode??P.Online;if(t===P.Always)return!1;const i=this.queryClient.networkManager.getOnlineSignal().value;switch(t){case P.Online:return!i;case P.OfflineFirst:return!i&&this.updatedAt===void 0;default:return!1}}}class fi{def;queryClient;_inFlight=!1;task;constructor(t,i){this.def=t,this.queryClient=i,this.task=this.createTask()}createTask(){return C.task(async t=>{if(this._inFlight)throw new Error("A mutation is already in progress. Await the previous call before starting a new one.");this._inFlight=!0;try{const i=await this.executeWithRetry(t),n=this.validateResponse(i);return this.processEffects(t,n),n}finally{this._inFlight=!1}},{desc:`Mutation(${this.def.id})`})}validateResponse(t){const i=this.def.responseShape;if(!(i instanceof _))return t;const n=this.queryClient.getContext().log?.warn??(()=>{}),s=new at;return s.reset(void 0,void 0,n),ne(t,i,s)}processEffects(t,i){let n;if(this.def.hasGetEffects){const r=st(this.def.captured,t??{},this.queryClient.getContext());r.result=i,n=r.getEffects()}else if(this.def.effects!==void 0){const r={params:t,result:i};n=K(this.def.effects,r)}if(n===void 0)return;const s=this.queryClient;it(n.creates,"create",s),it(n.updates,"update",s),it(n.deletes,"delete",s),n.invalidates&&s.invalidateQueries(n.invalidates)}executeWithRetry(t){const i=Ct(this.def.config?.retry,!0),n=this.queryClient.getAdapter(this.def.adapterClass);if(!n.sendMutation)throw new Error(`Adapter "${this.def.adapterClass.name}" does not implement sendMutation(). Add a sendMutation() method to handle mutations.`);return ft(async()=>{const s=new AbortController,r=st(this.def.captured,t??{},this.queryClient.getContext());return await n.sendMutation(r,s.signal)},i)}}function ui(e){return typeof e=="string"?e:L(e).typenameValue}function it(e,t,i){if(e)for(const[n,s]of e){const r=ui(n);r!==void 0&&i.applyMutationEvent({type:t,typename:r,data:s})}}const ue="__eventSource";function de(e){return{field:e,segments:e.indexOf(".")!==-1?e.split("."):void 0}}function di(e){return e.map(de)}function li(e,t){if(t.segments===void 0)return e[t.field];let i=e;for(const n of t.segments){if(i==null)return;i=i[n]}return i}function le(e,t){const i=[];for(let n=0;n<t.length;n++){const s=t[n],r=li(e,s);if(r===void 0)return;i.push(s.field,r)}return S.hashValue(i)}function hi(e,t){if(e===void 0)return;const i=new Map;for(const[n,s]of e){const r=s.slice().sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0),o=[];let a=!0;for(const[c,f]of r){let l;if($t(f)){const u=Qt(f);l=yt(u,t)}else l=f;if(l===void 0){a=!1;break}o.push(c,l)}a&&i.set(n,S.hashValue(o))}return i.size>0?i:void 0}function Tt(e,t){const i=e.get(t);if(i!==void 0)return i.map(([n])=>n).sort()}class yi{fields;fieldPaths;_bindings=new Map;constructor(t){this.fields=t,this.fieldPaths=t.map(de)}register(t,i){let n=this._bindings.get(t);n===void 0&&(n=new Set,this._bindings.set(t,n)),n.add(i)}unregister(t,i){const n=this._bindings.get(t);n!==void 0&&(n.delete(i),n.size===0&&this._bindings.delete(t))}getMatching(t){return this._bindings.get(t)}get isEmpty(){return this._bindings.size===0}}function Pt(e){return S.hashValue(e)}class pi{_groups=new Map;getOrCreateGroup(t){const i=Pt(t);let n=this._groups.get(i);return n===void 0&&(n=new yi(t),this._groups.set(i,n)),n}register(t,i,n){this.getOrCreateGroup(i).register(t,n)}unregister(t,i,n){const s=Pt(i),r=this._groups.get(s);r!==void 0&&(r.unregister(t,n),r.isEmpty&&this._groups.delete(s))}registerBinding(t,i){const n=t._constraintHashes.get(i);if(n===void 0)return;const s=Tt(t._constraintFieldRefs,i);s!==void 0&&this.register(n,s,t)}unregisterBinding(t,i){const n=t._constraintHashes.get(i);if(n===void 0)return;const s=Tt(t._constraintFieldRefs,i);s!==void 0&&this.unregister(n,s,t)}routeEvent(t,i,n,s,r,o){for(const a of this._groups.values()){const c=le(i,a.fieldPaths);if(c===void 0)continue;const f=a.getMatching(c);if(f!==void 0)for(const l of f)l.onEvent(t,n,s,r,o)}}}function jt(e){const t=new Set;for(const i of e)if(typeof i=="object"&&i!==null){const n=F(i);n!==void 0&&t.add(n)}return t}class he{_queryClient;_parent;_constraintHashes;_entityDefsByTypename;_constraintFieldRefs;instance;constructor(t,i,n,s,r,o){this._queryClient=n,this._parent=s,this._constraintHashes=r,this._constraintFieldRefs=i,this.instance=o,this._entityDefsByTypename=new Map;for(const a of t)a.typenameValue!==void 0&&this._entityDefsByTypename.set(a.typenameValue,a);tt.add(this)}getValue(){return this.instance.getValue()}toJSON(){return this.instance.getRawValue()}reset(t){this.instance.reset(t)}append(t){this.instance.append(t)}onEvent(t,i,n,s,r){const o=this._entityDefsByTypename.get(t);if(o===void 0)return;const a=this._queryClient.entityMap.getEntity(i);if(n==="delete"){const f=a!==void 0?a.getProxy(o):r;f!==void 0&&(this.instance.onEvent(i,f,r??a?.data??{},"delete"),s?.());return}if(a===void 0||!a.satisfiesDef(o))return;s?.();const c=a.getProxy(o);this.instance.onEvent(i,c,a.data,n)}destroy(){this._queryClient.unregisterLiveCollection(this);const t=this._parent.liveCollections,i=t.indexOf(this);i!==-1&&t.splice(i,1)}}class gi{_notifier;_items;_keys;_outputSignal;_queryClient;_parent;constructor(t,i,n,s,r,o){this._notifier=C.notifier(),this._items=n,this._keys=jt(n),this._queryClient=t,this._parent=i;const a=s!==void 0&&r!==void 0,c=o!==void 0;(a||c)&&(this._outputSignal=C.reactiveSignal(()=>{this._notifier.consume();let f=this._items;if(a){const l=[];for(const u of f){if(typeof u!="object"||u===null){l.push(u);continue}const y=F(u);if(y===void 0){l.push(u);continue}const v=t.entityMap.getEntity(y);if(v===void 0){l.push(u);continue}v.consume(),le(v.data,s)===r&&l.push(u)}f=l}return c&&(f=(f===this._items?f.slice():f).sort(o)),f}))}onEvent(t,i,n,s){switch(s){case"create":this.add(t,i);break;case"update":!this.has(t)&&i!==void 0&&this.add(t,i);break;case"delete":this.remove(t);break}}getValue(){return this._outputSignal!==void 0?this._outputSignal.value:(this._notifier.consume(),this._items)}getRawValue(){return this._items}add(t,i){if(this._keys.has(t))return!1;this._keys.add(t),this._items.push(i);const n=this._queryClient.entityMap.getEntity(t);return n!==void 0&&(this._parent.addChildRef(n),n.save()),this._notifier.notify(),!0}remove(t){if(!this._keys.has(t))return!1;this._keys.delete(t);const i=this._findIndex(t);i!==-1&&this._items.splice(i,1);const n=this._queryClient.entityMap.getEntity(t);return n!==void 0&&this._parent.removeChildRef(n),this._notifier.notify(),!0}has(t){return this._keys.has(t)}reset(t){const i=this._items,n=Array.isArray(t)?t:[];this._items=n,this._keys=jt(n);for(const s of n)if(typeof s=="object"&&s!==null){const r=F(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.addChildRef(o)}}for(const s of i)if(typeof s=="object"&&s!==null){const r=F(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.removeChildRef(o)}}this._notifier.notify()}append(t){if(Array.isArray(t))for(const i of t){if(typeof i!="object"||i===null)continue;const n=F(i);n!==void 0&&this.add(n,i)}}_findIndex(t){for(let i=0;i<this._items.length;i++){const n=this._items[i];if(typeof n=="object"&&n!==null&&F(n)===t)return i}return-1}}class vi{_notifier;_value;_createdKeys;_deletedKeys;_queryClient;_parent;_onCreate;_onUpdate;_onDelete;constructor(t,i,n,s,r,o){this._notifier=C.notifier(),this._value=n,this._createdKeys=new Set,this._deletedKeys=new Set,this._queryClient=t,this._parent=i,this._onCreate=s,this._onUpdate=r,this._onDelete=o}onEvent(t,i,n,s){switch(s){case"create":if(this._createdKeys.has(t))return;this._createdKeys.add(t),this._value=this._onCreate(this._value,i);break;case"update":this._value=this._onUpdate(this._value,i??n);break;case"delete":if(this._deletedKeys.has(t))return;this._deletedKeys.add(t),this._value=this._onDelete(this._value,i??n);break}this._notifier.notify()}getValue(){return this._notifier.consume(),this._value}getRawValue(){return this._value}reset(t){this._value=t,this._createdKeys.clear(),this._deletedKeys.clear(),this._notifier.notify()}append(t){}}function ye(e,t,i,n,s){let r=e.constraintFieldRefs;if(r===void 0){r=new Map;for(const f of e.entityDefs){const l=f.typenameValue;l!==void 0&&r.set(l,[[ue,i.key]])}}const o=hi(r,n)??new Map;let a;if(e.type===H.Array){let f,l;if(e.constraintFieldRefs!==void 0&&o.size>0&&o.size===1)for(const[u]of e.constraintFieldRefs){const y=o.get(u);if(y!==void 0){l=y;const v=e.constraintFieldRefs.get(u);v!==void 0&&(f=di(v.map(([p])=>p)));break}}a=new gi(s,i,Array.isArray(t)?t:[],f,l,e.sort)}else a=new vi(s,i,t,e.onCreate,e.onUpdate,e.onDelete);const c=new he(e.entityDefs,r,s,i,o,a);return i.liveCollections.push(c),s.registerLiveCollection(c),c}const pe=Object.entries,ge=Object.prototype;function nt(e,t,i,n=!1){const s=e.queryClient;s.currentParseId++;const r=e.seen,o=new Map;return{data:Q(t,r,s,i,o,n),entityRefs:o}}function Q(e,t,i,n,s,r){if(typeof e!="object"||e===null)return e;const o=t.get(e);if(o!==void 0)return _i(o,t,i,n,s,r);if(Array.isArray(e)){for(let a=0;a<e.length;a++){const c=e[a];typeof c=="object"&&c!==null&&!(c instanceof $)&&!O.has(c)&&(e[a]=Q(c,t,i,n,s,r))}return e}if(Object.getPrototypeOf(e)===ge&&!O.has(e)){const a=e;for(const c of Object.keys(a)){const f=a[c];typeof f=="object"&&f!==null&&!(f instanceof $)&&!O.has(f)&&(a[c]=Q(f,t,i,n,s,r))}}return e}function ve(e){return typeof e=="object"&&e!==null&&!(e instanceof $)&&!O.has(e)}function _i(e,t,i,n,s,r){const{key:o,data:a,shape:c,rawKeys:f}=e,l=c.shape,u=i.prepareEntity(o,a,c),y=u.data,v=y!==a,p=v&&f!==void 0&&u.entityRefs!==void 0?new Map(u.entityRefs):new Map;if(v?(_e(l,a,y,f,u,y,t,i,n,p,r),u.notify()):me(l,a,u,a,t,i,n,p,r),r&&u.liveCollections.length>0)for(const w of u.liveCollections){const I=w.instance.getRawValue();if(Array.isArray(I))for(const R of I){if(typeof R!="object"||R===null)continue;const Y=O.get(R);if(Y===void 0)continue;const A=i.entityMap.getEntity(Y);A!==void 0&&p.set(A,(p.get(A)??0)+1)}}u.setChildRefs(p.size>0?p:void 0,n);const g=u.getProxy(c);return s.set(u,(s.get(u)??0)+1),g}function _e(e,t,i,n,s,r,o,a,c,f,l){for(const[u,y]of pe(e))if(!(n!==void 0&&!n.has(u)))if(ve(t[u])&&(t[u]=Q(t[u],o,a,c,f,l)),y instanceof _&&y._liveConfig!==void 0){const v=i[u];v instanceof he?l?v.append(t[u]):v.reset(t[u]):i[u]=ye(y._liveConfig,t[u],s,r,a)}else{const v=t[u],p=i[u];if(ut(v)&&ut(p)){const g=y instanceof _&&y.shape!==void 0?y.shape:void 0;if(g!==void 0)_e(g,v,p,void 0,s,r,o,a,c,f,l);else for(const w of Object.keys(v))p[w]=v[w];i[u]=p}else i[u]=v}}function me(e,t,i,n,s,r,o,a,c){for(const[f,l]of pe(e))if(f in t)if(ve(t[f])&&(t[f]=Q(t[f],s,r,o,a,c)),l instanceof _&&l._liveConfig!==void 0)t[f]=ye(l._liveConfig,t[f],i,n,r);else{const u=t[f];if(ut(u)){const y=l instanceof _&&l.shape!==void 0?l.shape:void 0;y!==void 0&&me(y,u,i,n,s,r,o,a,c)}}}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===ge&&!O.has(e)}function mi(e){if(e!==void 0)return typeof e=="string"?e:typeof e=="function"?e():e.value}function wi(e){return C.isSignal(e)}function Lt(e){if(e===void 0)return;const t={};for(const[i,n]of Object.entries(e))wi(n)?t[i]=n.value:t[i]=n;return t}const xt=(e,t)=>S.hashValue([e.statics.id,t]);class Ei{entityMap;queryInstances=new Map;mutationInstances=new Map;gcManager;networkManager;isServer;store;currentParseId=0;context;typenameRegistry=new Map;constraintRegistry=new Map;mergedDefCache=new Map;adapters=new Map;networkUnsubscribe;constructor(t={}){const{store:i=new St.SyncQueryStore(new St.MemoryPersistentStore),log:n,evictionMultiplier:s,adapters:r,networkManager:o,gcManager:a,...c}=t;this.isServer=typeof window>"u",this.store=i,this.context={...c,log:n??console,evictionMultiplier:s},this.gcManager=t.gcManager??(this.isServer?new Vt:new Ut(this.handleEviction,s)),this.networkManager=t.networkManager??new Et,this.entityMap=new ni((u,y,v)=>this.store.saveEntity(u,y,v));for(const u of t.adapters??[])this.adapters.set(u.constructor,u),u.register(this);const f=this.networkManager.getOnlineSignal(),l=C.watcher(()=>f.value);this.networkUnsubscribe=l.addListener(()=>{const u=f.value;for(const y of this.adapters.values())y.onNetworkStatusChange?.(u)},{skipInitial:!0}),this.store.purgeStaleQueries?.()}getAdapter(t){const i=this.adapters.get(t);if(i)return i;let n;for(const r of this.adapters.values())r instanceof t&&(n??=r);if(n!==void 0)return this.adapters.set(t,n),n;let s;try{s=new t}catch{throw new Error(`No adapter registered for ${t.name} and auto-instantiation failed. Pass an instance via QueryClient config: new QueryClient({ store, adapters: [new ${t.name}(...)] })`)}return this.adapters.set(t,s),s.register(this),s}getContext(){return this.context}registerEntityDef(t){const i=t.typenameValue;if(i===void 0||t._entityClass===void 0)return;const n=this.typenameRegistry.get(i);if(n!==void 0){if(n.indexOf(t)!==-1)return;n.push(t),this.mergedDefCache.delete(i),this.getMergedDef(i)}else this.typenameRegistry.set(i,[t])}getEntityDefsForTypename(t){return this.typenameRegistry.get(t)}getMergedDef(t){let i=this.mergedDefCache.get(t);if(i!==void 0)return i;const n=this.typenameRegistry.get(t);if(n!==void 0)return i=_.merge(n),this.mergedDefCache.set(t,i),i}saveQueryData(t,i,n,s,r){const o=r!==void 0&&r.size>0?new Set([...r.keys()].map(a=>a.key)):void 0;this.store.saveQuery(t,i,n,s,o)}activateQuery(t){const{def:i,queryKey:n,storageKey:s,config:r}=t;this.store.activateQuery(i,s);const o=r?.gcTime??qt.DEFAULT_GC_TIME;this.gcManager.cancel(n,o)}loadCachedQuery(t,i){return this.store.loadQuery(t,i)}getQuery(t,i){const n=xt(t,i);let s=this.queryInstances.get(n);return s===void 0&&(s=new ci(t,this,n,i),this.queryInstances.set(n,s)),s.relay}getMutation(t){const i=t.id;let n=this.mutationInstances.get(i);return n===void 0&&(n=new fi(t,this),this.mutationInstances.set(i,n)),n.task}parseData(t,i,n){const s=this.context.log?.warn??(()=>{}),r=new at;return r.reset(this,n,s),{data:ne(t,i,r),ctx:r}}applyRefs(t,i=!0,n=!1){return nt(t.ctx,t.data,i,n)}parseAndApplyRootEntity(t,i,n,s,r=!1,o){typeof n.idField=="symbol"&&typeof t=="object"&&t!==null&&!("__entityRef"in t)&&(t[dt]=i);const a=this.parseData(t,n,o),c=nt(a.ctx,a.data,s,r),f=O.get(c.data);return this.entityMap.getEntity(f)}prepareEntity(t,i,n){return this.registerEntityDef(n),this.entityMap.getOrCreateEntity(t,i,n,this)}applyMutationEvent(t){const{type:i,typename:n}=t,s=this.getMergedDef(n);if(s===void 0)return;const r=s.idField;if(r===void 0||typeof r=="symbol")return;const o=t.data,a=t.id!==void 0?t.id:i==="delete"&&(typeof o=="string"||typeof o=="number")?o:o[r];if(a===void 0)return;const c=S.hashValue([n,a]),f=t.__eventSource,l=typeof o=="object"&&o!==null?o:{},u=this.entityMap.getEntity(c);if(i==="delete"){const g=u!==void 0?u.data:l;this.routeEvent(n,g,c,i,f,void 0,g);return}try{const g=this.context.log?.warn??(()=>{}),w=new at;w.reset(this,void 0,g,!0);const I=Ye(l,s,w);nt(w,I,!0)}catch(g){if(this.context.log?.warn?.("Failed to apply mutation event",g),u===void 0){const w=this.entityMap.getEntity(c);w!==void 0&&w.evict()}return}const y=this.entityMap.getEntity(c);if(y===void 0)return;this.entityMap.save(y);const v=u===void 0;let p=!1;this.routeEvent(n,y.data,c,i,f,()=>{p=!0}),v&&!p&&y.evict()}invalidateQueries(t){for(const i of t){const n=Array.isArray(i),s=n?i[0]:i,r=n?i[1]:void 0,a=B.for(s).statics.id;for(const[,c]of this.queryInstances)c.def.statics.id===a&&(r===void 0||bi(c.resolvedParams,r))&&c.markStale()}}handleEviction=(t,i)=>{if(i===J.Query){const s=this.queryInstances.get(t);if(s===void 0)return;s.rootEntity?.evict(),this.queryInstances.delete(t);return}const n=this.entityMap.getEntity(t);n!==void 0&&n.evict()};getOrCreateMatcher(t){let i=this.constraintRegistry.get(t);return i===void 0&&(i=new pi,this.constraintRegistry.set(t,i)),i}registerLiveCollection(t){for(const[i,n]of t._entityDefsByTypename)this.registerEntityDef(n),this.getOrCreateMatcher(i).registerBinding(t,i)}unregisterLiveCollection(t){for(const i of t._entityDefsByTypename.keys()){const n=this.constraintRegistry.get(i);n!==void 0&&n.unregisterBinding(t,i)}}routeEvent(t,i,n,s,r,o,a){const c=this.constraintRegistry.get(t);if(c===void 0)return;const f=r!==void 0?{...i,[ue]:r}:i;c.routeEvent(t,f,n,s,o,a)}destroy(){this.networkUnsubscribe?.(),this.gcManager.destroy(),this.networkManager.destroy();for(const t of this.adapters.values())t.destroy?.();this.adapters.clear(),this.queryInstances.clear(),this.mutationInstances.clear(),this.constraintRegistry.clear(),this.typenameRegistry.clear(),this.mergedDefCache.clear()}}const we=C.context(void 0);function bi(e,t){if(e===void 0)return!1;for(const i in t)if(e[i]!==t[i])return!1;return!0}exports.ARRAY_KEY=U;exports.Entity=X;exports.GcManager=Ut;exports.LiveFieldConfig=j;exports.LiveFieldType=H;exports.Mask=d;exports.NetworkManager=Et;exports.NetworkManagerContext=si;exports.NetworkMode=P;exports.NoOpGcManager=Vt;exports.NoOpNetworkManager=bt;exports.QUERY_ID=dt;exports.Query=ri;exports.QueryClient=Ei;exports.QueryClientContext=we;exports.RECORD_KEY=V;exports.ValidatorDef=_;exports.createDefinitionProxy=ht;exports.defaultNetworkManager=ce;exports.draft=Qe;exports.extractDefinition=Bt;exports.fetchQuery=ai;exports.queryKeyForClass=oi;exports.registerFormat=_t;exports.reifyValue=K;exports.resolveBaseUrl=mi;exports.t=ee;
2
- //# sourceMappingURL=QueryClient-DIAqDTHF.js.map