fetchium 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/README.md +287 -0
  3. package/dist/cjs/development/QueryClient-CpmwggOn.js +2 -0
  4. package/dist/cjs/development/QueryClient-CpmwggOn.js.map +1 -0
  5. package/dist/cjs/development/index.js +2 -0
  6. package/dist/cjs/development/index.js.map +1 -0
  7. package/dist/cjs/development/package.json +3 -0
  8. package/dist/cjs/development/react/index.js +2 -0
  9. package/dist/cjs/development/react/index.js.map +1 -0
  10. package/dist/cjs/development/shared-Ct5zKrt4.js +2 -0
  11. package/dist/cjs/development/shared-Ct5zKrt4.js.map +1 -0
  12. package/dist/cjs/development/stores/async.js +2 -0
  13. package/dist/cjs/development/stores/async.js.map +1 -0
  14. package/dist/cjs/development/stores/sync.js +2 -0
  15. package/dist/cjs/development/stores/sync.js.map +1 -0
  16. package/dist/cjs/development/subscriptions/polling.js +2 -0
  17. package/dist/cjs/development/subscriptions/polling.js.map +1 -0
  18. package/dist/cjs/production/QueryClient-qi3bR0eD.js +2 -0
  19. package/dist/cjs/production/QueryClient-qi3bR0eD.js.map +1 -0
  20. package/dist/cjs/production/index.js +2 -0
  21. package/dist/cjs/production/index.js.map +1 -0
  22. package/dist/cjs/production/package.json +3 -0
  23. package/dist/cjs/production/react/index.js +2 -0
  24. package/dist/cjs/production/react/index.js.map +1 -0
  25. package/dist/cjs/production/shared-Ct5zKrt4.js +2 -0
  26. package/dist/cjs/production/shared-Ct5zKrt4.js.map +1 -0
  27. package/dist/cjs/production/stores/async.js +2 -0
  28. package/dist/cjs/production/stores/async.js.map +1 -0
  29. package/dist/cjs/production/stores/sync.js +2 -0
  30. package/dist/cjs/production/stores/sync.js.map +1 -0
  31. package/dist/cjs/production/subscriptions/polling.js +2 -0
  32. package/dist/cjs/production/subscriptions/polling.js.map +1 -0
  33. package/dist/esm/ConstraintMatcher.d.ts +42 -0
  34. package/dist/esm/ConstraintMatcher.d.ts.map +1 -0
  35. package/dist/esm/EntityInstance.d.ts +38 -0
  36. package/dist/esm/EntityInstance.d.ts.map +1 -0
  37. package/dist/esm/EntityStore.d.ts +14 -0
  38. package/dist/esm/EntityStore.d.ts.map +1 -0
  39. package/dist/esm/GcManager.d.ts +38 -0
  40. package/dist/esm/GcManager.d.ts.map +1 -0
  41. package/dist/esm/LiveCollection.d.ts +86 -0
  42. package/dist/esm/LiveCollection.d.ts.map +1 -0
  43. package/dist/esm/MutationResult.d.ts +23 -0
  44. package/dist/esm/MutationResult.d.ts.map +1 -0
  45. package/dist/esm/NetworkManager.d.ts +62 -0
  46. package/dist/esm/NetworkManager.d.ts.map +1 -0
  47. package/dist/esm/QueryClient.d.ts +76 -0
  48. package/dist/esm/QueryClient.d.ts.map +1 -0
  49. package/dist/esm/QueryResult.d.ts +67 -0
  50. package/dist/esm/QueryResult.d.ts.map +1 -0
  51. package/dist/esm/applyEntities.d.ts +12 -0
  52. package/dist/esm/applyEntities.d.ts.map +1 -0
  53. package/dist/esm/development/QueryClient-DRZtPKFD.js +2568 -0
  54. package/dist/esm/development/QueryClient-DRZtPKFD.js.map +1 -0
  55. package/dist/esm/development/index.js +103 -0
  56. package/dist/esm/development/index.js.map +1 -0
  57. package/dist/esm/development/react/index.js +40 -0
  58. package/dist/esm/development/react/index.js.map +1 -0
  59. package/dist/esm/development/shared-Dq2yW78d.js +15 -0
  60. package/dist/esm/development/shared-Dq2yW78d.js.map +1 -0
  61. package/dist/esm/development/stores/async.js +214 -0
  62. package/dist/esm/development/stores/async.js.map +1 -0
  63. package/dist/esm/development/stores/sync.js +149 -0
  64. package/dist/esm/development/stores/sync.js.map +1 -0
  65. package/dist/esm/development/subscriptions/polling.js +25 -0
  66. package/dist/esm/development/subscriptions/polling.js.map +1 -0
  67. package/dist/esm/errors.d.ts +4 -0
  68. package/dist/esm/errors.d.ts.map +1 -0
  69. package/dist/esm/fieldRef.d.ts +15 -0
  70. package/dist/esm/fieldRef.d.ts.map +1 -0
  71. package/dist/esm/index.d.ts +14 -0
  72. package/dist/esm/index.d.ts.map +1 -0
  73. package/dist/esm/mutation.d.ts +47 -0
  74. package/dist/esm/mutation.d.ts.map +1 -0
  75. package/dist/esm/parseEntities.d.ts +44 -0
  76. package/dist/esm/parseEntities.d.ts.map +1 -0
  77. package/dist/esm/production/QueryClient-BP0Z1rQV.js +2453 -0
  78. package/dist/esm/production/QueryClient-BP0Z1rQV.js.map +1 -0
  79. package/dist/esm/production/index.js +103 -0
  80. package/dist/esm/production/index.js.map +1 -0
  81. package/dist/esm/production/react/index.js +40 -0
  82. package/dist/esm/production/react/index.js.map +1 -0
  83. package/dist/esm/production/shared-Dq2yW78d.js +15 -0
  84. package/dist/esm/production/shared-Dq2yW78d.js.map +1 -0
  85. package/dist/esm/production/stores/async.js +214 -0
  86. package/dist/esm/production/stores/async.js.map +1 -0
  87. package/dist/esm/production/stores/sync.js +149 -0
  88. package/dist/esm/production/stores/sync.js.map +1 -0
  89. package/dist/esm/production/subscriptions/polling.js +25 -0
  90. package/dist/esm/production/subscriptions/polling.js.map +1 -0
  91. package/dist/esm/proxy.d.ts +20 -0
  92. package/dist/esm/proxy.d.ts.map +1 -0
  93. package/dist/esm/proxyId.d.ts +8 -0
  94. package/dist/esm/proxyId.d.ts.map +1 -0
  95. package/dist/esm/query-types.d.ts +62 -0
  96. package/dist/esm/query-types.d.ts.map +1 -0
  97. package/dist/esm/query.d.ts +86 -0
  98. package/dist/esm/query.d.ts.map +1 -0
  99. package/dist/esm/react/index.d.ts +2 -0
  100. package/dist/esm/react/index.d.ts.map +1 -0
  101. package/dist/esm/react/use-query.d.ts +5 -0
  102. package/dist/esm/react/use-query.d.ts.map +1 -0
  103. package/dist/esm/retry.d.ts +4 -0
  104. package/dist/esm/retry.d.ts.map +1 -0
  105. package/dist/esm/stores/async.d.ts +80 -0
  106. package/dist/esm/stores/async.d.ts.map +1 -0
  107. package/dist/esm/stores/shared.d.ts +12 -0
  108. package/dist/esm/stores/shared.d.ts.map +1 -0
  109. package/dist/esm/stores/sync.d.ts +41 -0
  110. package/dist/esm/stores/sync.d.ts.map +1 -0
  111. package/dist/esm/subscriptions/polling.d.ts +6 -0
  112. package/dist/esm/subscriptions/polling.d.ts.map +1 -0
  113. package/dist/esm/type-utils.d.ts +16 -0
  114. package/dist/esm/type-utils.d.ts.map +1 -0
  115. package/dist/esm/typeDefs.d.ts +86 -0
  116. package/dist/esm/typeDefs.d.ts.map +1 -0
  117. package/dist/esm/types.d.ts +272 -0
  118. package/dist/esm/types.d.ts.map +1 -0
  119. package/dist/esm/utils.d.ts +38 -0
  120. package/dist/esm/utils.d.ts.map +1 -0
  121. package/index.d.ts +1 -0
  122. package/package.json +134 -5
  123. package/stores/async.d.ts +1 -0
  124. package/stores/async.js +15 -0
  125. package/stores/sync.d.ts +1 -0
  126. package/stores/sync.js +15 -0
  127. package/index.js +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./QueryClient-CpmwggOn.js"),y=require("signalium");class p{params;result;optimisticUpdates;config;effects;constructor(){return t.createDefinitionProxy(this)}}class M extends p{path;method="POST";body;headers;requestOptions;getStorageKey(){return`${this.method??"POST"}:${this.path??""}`}async send(){const e=this.getPath?this.getPath():this.path,n=this.getMethod?this.getMethod():this.method,a=this.getBody?this.getBody():this.body,c=this.getRequestOptions?this.getRequestOptions():this.requestOptions;if(!e)throw new Error("RESTMutation requires a path. Define `path` as a field or override `getPath()`.");const s=a??this.params,i=t.resolveBaseUrl(c?.baseUrl)??t.resolveBaseUrl(this.context.baseUrl),f=i?`${i}${e}`:e,{baseUrl:u,signal:g,...r}=c??{},d={"Content-Type":"application/json",...this.headers},l=await this.context.fetch(f,{method:n,headers:d,body:JSON.stringify(s),signal:this.signal,...r});return this.response=l,l.json()}}const h=new WeakMap,C=o=>{const e=h.get(o);if(e===void 0)throw new Error("Mutation definition not found");return e().id};function m(o){let e=h.get(o);if(e!==void 0)return e;let n;const a=()=>{if(n!==void 0)return n;const c=new o,s=t.extractDefinition(c),{fields:i}=s,f=`mutation:${String(s.methods.getStorageKey.call(i))}`,u=i.params??{},g=u instanceof t.ValidatorDef?u:t.t.object(u),r=i.result,d=r!==void 0?r instanceof t.ValidatorDef?r:t.t.object(r):void 0;return n={id:f,requestShape:g,responseShape:d,captured:s,optimisticUpdates:i.optimisticUpdates??!1,config:i.config,effects:i.effects,hasGetEffects:typeof s.methods.getEffects=="function"},n};return h.set(o,a),a}function E(o){const e=m(o),n=y.getContext(t.QueryClientContext);if(n===void 0)throw new Error("QueryClient not found");return n.getMutation(e())}exports.ARRAY_KEY=t.ARRAY_KEY;exports.Entity=t.Entity;exports.GcManager=t.GcManager;exports.LiveFieldConfig=t.LiveFieldConfig;exports.LiveFieldType=t.LiveFieldType;exports.Mask=t.Mask;exports.NetworkManager=t.NetworkManager;exports.NetworkManagerContext=t.NetworkManagerContext;exports.NetworkMode=t.NetworkMode;exports.NoOpGcManager=t.NoOpGcManager;exports.NoOpNetworkManager=t.NoOpNetworkManager;exports.QUERY_ID=t.QUERY_ID;exports.Query=t.Query;exports.QueryClient=t.QueryClient;exports.QueryClientContext=t.QueryClientContext;exports.RECORD_KEY=t.RECORD_KEY;exports.RESTQuery=t.RESTQuery;exports.defaultNetworkManager=t.defaultNetworkManager;exports.draft=t.draft;exports.fetchQuery=t.fetchQuery;exports.queryKeyForClass=t.queryKeyForClass;exports.registerFormat=t.registerFormat;exports.t=t.t;exports.Mutation=p;exports.RESTMutation=M;exports.getMutation=E;exports.mutationKeyForClass=C;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../src/mutation.ts"],"sourcesContent":["import { getContext, ReactiveTask } from 'signalium';\nimport {\n ExtractType,\n InternalTypeDef,\n MutationEffects,\n TypeDef,\n RetryConfig,\n TypeDefShape,\n QueryRequestOptions,\n} from './types.js';\nimport { QueryClientContext, QueryContext, resolveBaseUrl } from './QueryClient.js';\nimport { ValidatorDef, t } from './typeDefs.js';\nimport { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.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}\n\n// ================================\n// Mutation base class\n// ================================\n\nexport abstract class Mutation {\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 declare response: Response | undefined;\n declare signal: AbortSignal;\n\n abstract send(): Promise<unknown>;\n abstract getStorageKey(): unknown;\n\n getEffects?(): MutationEffects;\n\n constructor() {\n return createDefinitionProxy(this);\n }\n}\n\n// ================================\n// RESTMutation\n// ================================\n\nexport abstract class RESTMutation extends Mutation {\n path?: string;\n method: 'POST' | 'PUT' | 'DELETE' | 'PATCH' = 'POST';\n body?: Record<string, unknown>;\n headers?: HeadersInit;\n requestOptions?: QueryRequestOptions;\n\n getStorageKey(): string {\n return `${this.method ?? 'POST'}:${this.path ?? ''}`;\n }\n\n getPath?(): string | undefined;\n getMethod?(): string;\n getBody?(): Record<string, unknown> | undefined;\n getRequestOptions?(): QueryRequestOptions | undefined;\n\n async send(): Promise<unknown> {\n const path = this.getPath ? this.getPath() : this.path;\n const method = this.getMethod ? this.getMethod() : this.method;\n const body = this.getBody ? this.getBody() : this.body;\n const requestOptions = this.getRequestOptions ? this.getRequestOptions() : this.requestOptions;\n\n if (!path) {\n throw new Error('RESTMutation requires a path. Define `path` as a field or override `getPath()`.');\n }\n\n const bodyData = body ?? (this.params as Record<string, unknown>);\n\n const baseUrl = resolveBaseUrl(requestOptions?.baseUrl) ?? resolveBaseUrl(this.context.baseUrl);\n const fullUrl = baseUrl ? `${baseUrl}${path}` : path;\n\n const { baseUrl: _baseUrl, signal: _signal, ...fetchOptions } = requestOptions ?? ({} as Record<string, unknown>);\n\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...(this.headers as Record<string, string>),\n };\n\n const fetchResponse = await this.context.fetch(fullUrl, {\n method,\n headers,\n body: JSON.stringify(bodyData),\n signal: this.signal,\n ...fetchOptions,\n });\n\n this.response = fetchResponse;\n return fetchResponse.json();\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.getStorageKey.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 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 };\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","RESTMutation","path","method","body","requestOptions","bodyData","baseUrl","resolveBaseUrl","fullUrl","_baseUrl","_signal","fetchOptions","headers","fetchResponse","mutationDefCache","mutationKeyForClass","cls","getMutationDef","buildMutationDefinition","MutationClass","cached","mutationDefinition","getter","instance","captured","extractDefinition","fields","id","requestDef","requestShape","ValidatorDef","t","responseDef","responseShape","getMutation","queryClient","getContext","QueryClientContext"],"mappings":"oJAqCO,MAAeA,CAAS,CACpB,OACA,OACA,kBACA,OACA,QAWT,aAAc,CACZ,OAAOC,EAAAA,sBAAsB,IAAI,CACnC,CACF,CAMO,MAAeC,UAAqBF,CAAS,CAClD,KACA,OAA8C,OAC9C,KACA,QACA,eAEA,eAAwB,CACtB,MAAO,GAAG,KAAK,QAAU,MAAM,IAAI,KAAK,MAAQ,EAAE,EACpD,CAOA,MAAM,MAAyB,CAC7B,MAAMG,EAAO,KAAK,QAAU,KAAK,QAAA,EAAY,KAAK,KAC5CC,EAAS,KAAK,UAAY,KAAK,UAAA,EAAc,KAAK,OAClDC,EAAO,KAAK,QAAU,KAAK,QAAA,EAAY,KAAK,KAC5CC,EAAiB,KAAK,kBAAoB,KAAK,kBAAA,EAAsB,KAAK,eAEhF,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,iFAAiF,EAGnG,MAAMI,EAAWF,GAAS,KAAK,OAEzBG,EA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,kBAAmBE,EAAO,mBAAqB,GAC/C,OAAQA,EAAO,OACf,QAASA,EAAO,QAChB,cAAe,OAAOF,EAAS,QAAQ,YAAe,UAAA,EAGjDH,CACT,EAEA,OAAAP,EAAiB,IAAIK,EAAeG,CAAM,EACnCA,CACT,CAMO,SAASY,EACdf,EAC8E,CAC9E,MAAMF,EAAiBC,EAAwBC,CAAa,EAEtDgB,EAAcC,EAAAA,WAAWC,oBAAkB,EAEjD,GAAIF,IAAgB,OAClB,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAOA,EAAY,YAAsBlB,GAAgB,CAC3D"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("signalium/react"),i=require("signalium"),f=require("../QueryClient-CpmwggOn.js");function n(e){if(Array.isArray(e))return e.map(n);if(e&&typeof e=="object"){if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);if(e instanceof Map)return new Map(Array.from(e.entries()).map(([t,c])=>[n(t),n(c)]));if(e instanceof Set)return new Set(Array.from(e).map(n));const r=Object.create(Object.getPrototypeOf(e));for(const t of Object.keys(e))r[t]=n(e[t]);return r}return e}const y=i.reactive(e=>n(e.value)),a=i.reactive((e,...r)=>{const t=f.fetchQuery(e,...r);return new Proxy(t,{get(c,o,u){return o==="value"?y(c):Reflect.get(c,o,u)}})}),p=i.reactive(e=>e.value);function g(e,...r){const t=s.useReactive(a,e,...r);return s.useReactive(p,t),t}exports.useQuery=g;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/react/use-query.ts"],"sourcesContent":["import { useReactive } from 'signalium/react';\nimport { reactive } from 'signalium';\nimport { ExtractType, QueryPromise } from '../types.js';\nimport { ExtractQueryParams, fetchQuery, Query } from '../query.js';\nimport { HasRequiredKeys, Optionalize, Signalize } from '../type-utils.js';\n\nfunction cloneDeep<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as unknown as T;\n }\n if (value && typeof value === 'object') {\n if (value instanceof Date) {\n return new Date(value) as unknown as T;\n }\n if (value instanceof RegExp) {\n return new RegExp(value) as unknown as T;\n }\n if (value instanceof Map) {\n return new Map(Array.from(value.entries()).map(([k, v]) => [cloneDeep(k), cloneDeep(v)])) as unknown as T;\n }\n if (value instanceof Set) {\n return new Set(Array.from(value).map(cloneDeep)) as unknown as T;\n }\n const result: any = Object.create(Object.getPrototypeOf(value));\n for (const key of Object.keys(value)) {\n result[key] = cloneDeep((value as any)[key]);\n }\n return result as T;\n }\n return value;\n}\n\nconst clonedResult = reactive((result: QueryPromise<Query>) => cloneDeep(result.value));\n\nconst reifiedQuery = reactive(\n <T extends Query>(\n QueryClass: new () => T,\n ...args: HasRequiredKeys<ExtractType<T['params']>> extends true\n ? [params: Optionalize<Signalize<ExtractType<T['params']>>>]\n : [params?: Optionalize<Signalize<ExtractType<T['params']>>> | undefined]\n ): QueryPromise<T> => {\n const queryResult = fetchQuery(QueryClass, ...args);\n\n return new Proxy(queryResult, {\n get(target, prop, receiver) {\n if (prop === 'value') {\n return clonedResult(target);\n }\n\n return Reflect.get(target, prop, receiver);\n },\n });\n },\n);\n\nconst resultValue = reactive((result: QueryPromise<Query>) => result.value);\n\nexport function useQuery<T extends Query>(\n QueryClass: new () => T,\n ...args: HasRequiredKeys<ExtractType<T['params']>> extends true\n ? [params: Optionalize<Signalize<ExtractType<T['params']>>>]\n : [params?: Optionalize<Signalize<ExtractType<T['params']>>> | undefined]\n): QueryPromise<T> {\n const result = useReactive(reifiedQuery, QueryClass, ...args);\n\n useReactive(resultValue, result);\n\n return result;\n}\n"],"names":["cloneDeep","value","k","v","result","key","clonedResult","reactive","reifiedQuery","QueryClass","args","queryResult","fetchQuery","target","prop","receiver","resultValue","useQuery","useReactive"],"mappings":"kLAMA,SAASA,EAAaC,EAAa,CACjC,GAAI,MAAM,QA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:doc:value:${e}`,s=e=>`sq:doc:refCount:${e}`,c=e=>`sq:doc:refIds:${e}`,t=e=>`sq:doc:updatedAt:${e}`,F=e=>`sq:doc:queue:${e}`,T=e=>`sq:doc:lastUsed:${e}`,E=e=>`sq:doc:cacheTime:${e}`,_="sq:doc:lastUsed:";exports.DEFAULT_CACHE_TIME=1440;exports.DEFAULT_GC_TIME=5;exports.DEFAULT_MAX_COUNT=50;exports.LAST_USED_PREFIX=_;exports.cacheTimeKeyFor=E;exports.lastUsedKeyFor=T;exports.queueKeyFor=F;exports.refCountKeyFor=s;exports.refIdsKeyFor=c;exports.updatedAtKeyFor=t;exports.valueKeyFor=o;
2
+ //# sourceMappingURL=shared-Ct5zKrt4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared-Ct5zKrt4.js","sources":["../../../src/stores/shared.ts"],"sourcesContent":["// Query Instance keys\nexport const valueKeyFor = (id: number) => `sq:doc:value:${id}`;\nexport const refCountKeyFor = (id: number) => `sq:doc:refCount:${id}`;\nexport const refIdsKeyFor = (id: number) => `sq:doc:refIds:${id}`;\nexport const updatedAtKeyFor = (id: number) => `sq:doc:updatedAt:${id}`;\n// Query Type keys\nexport const queueKeyFor = (queryDefId: string) => `sq:doc:queue:${queryDefId}`;\n// Query Type metadata keys (used for stale cache cleanup)\nexport const lastUsedKeyFor = (queryDefId: string) => `sq:doc:lastUsed:${queryDefId}`;\nexport const cacheTimeKeyFor = (queryDefId: string) => `sq:doc:cacheTime:${queryDefId}`;\n\nexport const LAST_USED_PREFIX = 'sq:doc:lastUsed:';\n\n// Default values\nexport const DEFAULT_MAX_COUNT = 50;\nexport const DEFAULT_CACHE_TIME = 60 * 24; // 24 hours in minutes\nexport const DEFAULT_GC_TIME = 5; // 5 minutes - in-memory eviction default\n"],"names":["valueKeyFor","id","refCountKeyFor","refIdsKeyFor","updatedAtKeyFor","queueKeyFor","queryDefId","lastUsedKeyFor","cacheTimeKeyFor","LAST_USED_PREFIX"],"mappings":"aACO,MAAMA,EAAeC,GAAe,gBAAgBA,CAAE,GAChDC,EAAkBD,GAAe,mBAAmBA,CAAE,GACtDE,EAAgBF,GAAe,iBAAiBA,CAAE,GAClDG,EAAmBH,GAAe,oBAAoBA,CAAE,GAExDI,EAAeC,GAAuB,gBAAgBA,CAAU,GAEhEC,EAAkBD,GAAuB,mBAAmBA,CAAU,GACtEE,EAAmBF,GAAuB,oBAAoBA,CAAU,GAExEG,EAAmB"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../shared-Ct5zKrt4.js");class d{isWriter;delegate;sendMessage;messageQueue=[];queues=new Map;queueProcessorPromise;resolveQueueWait;constructor(e){this.isWriter=e.isWriter,this.delegate=e.delegate;const{sendMessage:t}=e.connect(this.handleMessage.bind(this));if(this.sendMessage=t,this.isWriter){if(!this.delegate)throw new Error("Writer must have a delegate");this.startQueueProcessor()}}handleMessage(e){this.isWriter&&this.enqueueMessage(e)}enqueueMessage(e){this.messageQueue.push(e),this.resolveQueueWait&&(this.resolveQueueWait(),this.resolveQueueWait=void 0)}dispatch(e){this.isWriter?this.enqueueMessage(e):this.sendMessage(e)}startQueueProcessor(){this.queueProcessorPromise=this.processQueue()}async processQueue(){for(;;){for(;this.messageQueue.length===0;)await new Promise(t=>{this.resolveQueueWait=t});const e=this.messageQueue.shift();try{await this.processMessage(e)}catch(t){console.error("Error processing message:",t)}}}async processMessage(e){switch(e.type){case 0:await this.writerSaveQuery(e.queryDefId,e.queryKey,e.value,e.updatedAt,e.cacheTime,e.refIds);break;case 1:await this.writerSaveEntity(e.entityKey,e.value,e.refIds);break;case 2:await this.writerActivateQuery(e.queryDefId,e.queryKey,e.cacheTime);break;case 3:await this.writerDeleteValue(e.queryKey);break}}async loadQuery(e,t){if(!this.delegate)return;const s=await this.delegate.getNumber(r.updatedAtKeyFor(t)),a=(e.statics.cache?.cacheTime??r.DEFAULT_CACHE_TIME)*60*1e3;if(s===void 0||s<Date.now()-a)return;const i=await this.delegate.getString(r.valueKeyFor(t));if(i===void 0)return;const o=await this.delegate.getBuffer(r.refIdsKeyFor(t));let n;return o!==void 0&&(n=new Map,await this.preloadEntities(o,n)),this.activateQuery(e,t),{value:JSON.parse(i),refIds:o===void 0?void 0:new Set(o??[]),updatedAt:s,preloadedEntities:n}}async preloadEntities(e,t){if(this.delegate)for(const s of e){const a=await this.delegate.getString(r.valueKeyFor(s));if(a===void 0)continue;t.set(s,JSON.parse(a));const i=await this.delegate.getBuffer(r.refIdsKeyFor(s));i!==void 0&&await this.preloadEntities(i,t)}}saveQuery(e,t,s,a,i){const o={type:0,queryDefId:e.statics.id,queryKey:t,value:s,updatedAt:a,cacheTime:e.statics.cache?.cacheTime??r.DEFAULT_CACHE_TIME,refIds:i?Array.from(i):void 0};this.dispatch(o)}saveEntity(e,t,s){const a={type:1,entityKey:e,value:t,refIds:s?Array.from(s):void 0};this.dispatch(a)}activateQuery(e,t){const s={type:2,queryDefId:e.statics.id,queryKey:t,cacheTime:e.statics.cache?.cacheTime??r.DEFAULT_CACHE_TIME};this.dispatch(s)}deleteQuery(e){const t={type:3,queryKey:e};this.dispatch(t)}async writerSaveQuery(e,t,s,a,i,o){await this.setValue(t,s,o?new Set(o):void 0),await this.delegate.setNumber(r.updatedAtKeyFor(t),a),await this.writerActivateQuery(e,t,i)}async writerSaveEntity(e,t,s){await this.setValue(e,t,s?new Set(s):void 0)}async writerActivateQuery(e,t,s){if(!await this.delegate.has(r.valueKeyFor(t)))return;const a=r.queueKeyFor(e);let i=this.queues.get(e);if(i===void 0){const u=r.DEFAULT_MAX_COUNT;i=await this.delegate.getBuffer(a),i===void 0?(i=new Uint32Array(u),await this.delegate.setBuffer(a,i)):i.length!==u&&(i=new Uint32Array(i.buffer,0,u),await this.delegate.setBuffer(a,i)),this.queues.set(e,i)}await this.delegate.setNumber(r.lastUsedKeyFor(e),Date.now()),await this.delegate.setNumber(r.cacheTimeKeyFor(e),s);const o=i.indexOf(t);if(o>=0){if(o===0)return;i.copyWithin(1,0,o),i[0]=t;return}const n=i[i.length-1];i.copyWithin(1,0,i.length-1),i[0]=t,n!==0&&(await this.writerDeleteValue(n),await this.delegate.delete(r.updatedAtKeyFor(n)))}async purgeStaleQueries(){if(!this.delegate)return;const e=await this.delegate.getAllKeys(),t=Date.now();for(const s of e){if(!s.startsWith(r.LAST_USED_PREFIX))continue;const a=s.slice(r.LAST_USED_PREFIX.length),i=await this.delegate.getNumber(s),n=(await this.delegate.getNumber(r.cacheTimeKeyFor(a))??r.DEFAULT_CACHE_TIME)*60*1e3;if(i===void 0||t-i>n){const u=await this.delegate.getBuffer(r.queueKeyFor(a));if(u!==void 0)for(const c of u)c!==0&&(await this.writerDeleteValue(c),await this.delegate.delete(r.updatedAtKeyFor(c)));await this.delegate.delete(r.queueKeyFor(a)),await this.delegate.delete(s),await this.delegate.delete(r.cacheTimeKeyFor(a)),this.queues.delete(a)}}}async setValue(e,t,s){const a=this.delegate;await a.setString(r.valueKeyFor(e),JSON.stringify(t));const i=r.refIdsKeyFor(e),o=await a.getBuffer(i);if(s===void 0||s.size===0){if(await a.delete(i),o!==void 0)for(let n=0;n<o.length;n++){const u=o[n];await this.decrementRefCount(u)}}else{const n=new Uint32Array([...s]);if(o!==void 0)for(let u=0;u<o.length;u++){const c=o[u];s.has(c)?s.delete(c):await this.decrementRefCount(c)}for(const u of s)await this.incrementRefCount(u);await a.setBuffer(i,n)}}async writerDeleteValue(e){const t=this.delegate,s=r.refIdsKeyFor(e);await t.delete(r.valueKeyFor(e)),await t.delete(r.refCountKeyFor(e));const a=await t.getBuffer(s);if(await t.delete(s),a!==void 0)for(const i of a)i!==0&&await this.decrementRefCount(i)}async incrementRefCount(e){const t=this.delegate,s=r.refCountKeyFor(e),i=(await t.getNumber(s)??0)+1;await t.setNumber(s,i)}async decrementRefCount(e){const t=this.delegate,s=r.refCountKeyFor(e),a=await t.getNumber(s);if(a===void 0)return;const i=a-1;i===0?await this.writerDeleteValue(e):await t.setNumber(s,i)}}exports.AsyncQueryStore=d;
2
+ //# sourceMappingURL=async.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async.js","sources":["../../../../src/stores/async.ts"],"sourcesContent":["import { QueryDefinition } from '../query.js';\nimport { CachedQuery, QueryStore, type PreloadedEntityMap } from '../QueryClient.js';\nimport {\n cacheTimeKeyFor,\n DEFAULT_CACHE_TIME,\n DEFAULT_MAX_COUNT,\n LAST_USED_PREFIX,\n lastUsedKeyFor,\n queueKeyFor,\n refCountKeyFor,\n refIdsKeyFor,\n updatedAtKeyFor,\n valueKeyFor,\n} from './shared.js';\n\n// -----------------------------------------------------------------------------\n// Async QueryStore Interfaces\n// -----------------------------------------------------------------------------\n\nexport interface AsyncPersistentStore {\n has(key: string): Promise<boolean>;\n\n getString(key: string): Promise<string | undefined>;\n setString(key: string, value: string): Promise<void>;\n\n getNumber(key: string): Promise<number | undefined>;\n setNumber(key: string, value: number): Promise<void>;\n\n getBuffer(key: string): Promise<Uint32Array | undefined>;\n setBuffer(key: string, value: Uint32Array): Promise<void>;\n\n delete(key: string): Promise<void>;\n\n getAllKeys(): Promise<string[]>;\n}\n\nconst enum StoreMessageType {\n SaveQuery = 0,\n SaveEntity = 1,\n ActivateQuery = 2,\n DeleteQuery = 3,\n}\n\nexport type StoreMessage =\n | {\n type: StoreMessageType.SaveQuery;\n queryDefId: string;\n queryKey: number;\n value: unknown;\n updatedAt: number;\n cacheTime: number;\n refIds?: number[];\n }\n | { type: StoreMessageType.SaveEntity; entityKey: number; value: unknown; refIds?: number[] }\n | { type: StoreMessageType.ActivateQuery; queryDefId: string; queryKey: number; cacheTime: number }\n | { type: StoreMessageType.DeleteQuery; queryKey: number };\n\nexport interface AsyncQueryStoreConfig {\n isWriter: boolean;\n connect: (handleMessage: (msg: StoreMessage) => void) => {\n sendMessage: (msg: StoreMessage) => void;\n };\n delegate?: AsyncPersistentStore; // Only provided for writer\n}\n// -----------------------------------------------------------------------------\n// Async QueryStore Implementation\n// -----------------------------------------------------------------------------\n\nexport class AsyncQueryStore implements QueryStore {\n private readonly isWriter: boolean;\n private readonly delegate?: AsyncPersistentStore;\n private readonly sendMessage: (msg: StoreMessage) => void;\n private readonly messageQueue: StoreMessage[] = [];\n private readonly queues: Map<string, Uint32Array> = new Map();\n private queueProcessorPromise?: Promise<void>;\n private resolveQueueWait?: () => void;\n\n constructor(config: AsyncQueryStoreConfig) {\n this.isWriter = config.isWriter;\n this.delegate = config.delegate;\n\n // Connect and get sendMessage function\n const { sendMessage } = config.connect(this.handleMessage.bind(this));\n this.sendMessage = sendMessage;\n\n // Start queue processor if this is a writer\n if (this.isWriter) {\n if (!this.delegate) {\n throw new Error('Writer must have a delegate');\n }\n this.startQueueProcessor();\n }\n }\n\n private handleMessage(msg: StoreMessage): void {\n if (this.isWriter) {\n // Enqueue the message for serial processing\n this.enqueueMessage(msg);\n }\n // Readers don't handle incoming messages\n }\n\n private enqueueMessage(msg: StoreMessage): void {\n this.messageQueue.push(msg);\n // Wake up the queue processor if it's waiting\n if (this.resolveQueueWait) {\n this.resolveQueueWait();\n this.resolveQueueWait = undefined;\n }\n }\n\n private dispatch(msg: StoreMessage): void {\n if (this.isWriter) {\n this.enqueueMessage(msg);\n } else {\n this.sendMessage(msg);\n }\n }\n\n private startQueueProcessor(): void {\n this.queueProcessorPromise = this.processQueue();\n }\n\n private async processQueue(): Promise<void> {\n while (true) {\n // Wait for messages if queue is empty\n while (this.messageQueue.length === 0) {\n await new Promise<void>(resolve => {\n this.resolveQueueWait = resolve;\n });\n }\n\n // Process one message at a time\n const msg = this.messageQueue.shift()!;\n\n try {\n await this.processMessage(msg);\n } catch (error) {\n console.error('Error processing message:', error);\n }\n }\n }\n\n private async processMessage(msg: StoreMessage): Promise<void> {\n switch (msg.type) {\n case StoreMessageType.SaveQuery:\n await this.writerSaveQuery(msg.queryDefId, msg.queryKey, msg.value, msg.updatedAt, msg.cacheTime, msg.refIds);\n break;\n case StoreMessageType.SaveEntity:\n await this.writerSaveEntity(msg.entityKey, msg.value, msg.refIds);\n break;\n case StoreMessageType.ActivateQuery:\n await this.writerActivateQuery(msg.queryDefId, msg.queryKey, msg.cacheTime);\n break;\n case StoreMessageType.DeleteQuery:\n await this.writerDeleteValue(msg.queryKey);\n break;\n }\n }\n\n async loadQuery(queryDef: QueryDefinition<any, any, any>, queryKey: number): Promise<CachedQuery | undefined> {\n if (!this.delegate) {\n return undefined;\n }\n\n const updatedAt = await this.delegate.getNumber(updatedAtKeyFor(queryKey));\n\n const cacheTimeMs = (queryDef.statics.cache?.cacheTime ?? DEFAULT_CACHE_TIME) * 60 * 1000;\n if (updatedAt === undefined || updatedAt < Date.now() - cacheTimeMs) {\n return undefined;\n }\n\n const valueStr = await this.delegate.getString(valueKeyFor(queryKey));\n\n if (valueStr === undefined) {\n return undefined;\n }\n\n const entityIds = await this.delegate.getBuffer(refIdsKeyFor(queryKey));\n\n let preloadedEntities: PreloadedEntityMap | undefined;\n if (entityIds !== undefined) {\n preloadedEntities = new Map();\n await this.preloadEntities(entityIds, preloadedEntities);\n }\n\n this.activateQuery(queryDef, queryKey);\n\n return {\n value: JSON.parse(valueStr) as Record<string, unknown>,\n refIds: entityIds === undefined ? undefined : new Set(entityIds ?? []),\n updatedAt,\n preloadedEntities,\n };\n }\n\n private async preloadEntities(entityIds: Uint32Array, preloaded: PreloadedEntityMap): Promise<void> {\n if (!this.delegate) {\n return;\n }\n\n for (const entityId of entityIds) {\n const entityValue = await this.delegate.getString(valueKeyFor(entityId));\n\n if (entityValue === undefined) {\n continue;\n }\n\n preloaded.set(entityId, JSON.parse(entityValue) as Record<string, unknown>);\n\n const childIds = await this.delegate.getBuffer(refIdsKeyFor(entityId));\n\n if (childIds === undefined) {\n continue;\n }\n\n await this.preloadEntities(childIds, preloaded);\n }\n }\n\n saveQuery(\n queryDef: QueryDefinition<any, any, any>,\n queryKey: number,\n value: unknown,\n updatedAt: number,\n refIds?: Set<number>,\n ): void {\n const message: StoreMessage = {\n type: StoreMessageType.SaveQuery,\n queryDefId: queryDef.statics.id,\n queryKey,\n value,\n updatedAt,\n cacheTime: queryDef.statics.cache?.cacheTime ?? DEFAULT_CACHE_TIME,\n refIds: refIds ? Array.from(refIds) : undefined,\n };\n\n this.dispatch(message);\n }\n\n saveEntity(entityKey: number, value: unknown, refIds?: Set<number>): void {\n const message: StoreMessage = {\n type: StoreMessageType.SaveEntity,\n entityKey,\n value,\n refIds: refIds ? Array.from(refIds) : undefined,\n };\n\n this.dispatch(message);\n }\n\n activateQuery(queryDef: QueryDefinition<any, any, any>, queryKey: number): void {\n const message: StoreMessage = {\n type: StoreMessageType.ActivateQuery,\n queryDefId: queryDef.statics.id,\n queryKey,\n cacheTime: queryDef.statics.cache?.cacheTime ?? DEFAULT_CACHE_TIME,\n };\n\n this.dispatch(message);\n }\n\n deleteQuery(queryKey: number): void {\n const message: StoreMessage = {\n type: StoreMessageType.DeleteQuery,\n queryKey,\n };\n\n this.dispatch(message);\n }\n\n // Writer-specific methods below\n\n private async writerSaveQuery(\n queryDefId: string,\n queryKey: number,\n value: unknown,\n updatedAt: number,\n cacheTime: number,\n refIds?: number[],\n ): Promise<void> {\n await this.setValue(queryKey, value, refIds ? new Set(refIds) : undefined);\n await this.delegate!.setNumber(updatedAtKeyFor(queryKey), updatedAt);\n await this.writerActivateQuery(queryDefId, queryKey, cacheTime);\n }\n\n private async writerSaveEntity(entityKey: number, value: unknown, refIds?: number[]): Promise<void> {\n await this.setValue(entityKey, value, refIds ? new Set(refIds) : undefined);\n }\n\n private async writerActivateQuery(queryDefId: string, queryKey: number, cacheTime: number): Promise<void> {\n if (!(await this.delegate!.has(valueKeyFor(queryKey)))) {\n return;\n }\n\n const queueKey = queueKeyFor(queryDefId);\n let queue = this.queues.get(queryDefId);\n\n if (queue === undefined) {\n const maxCount = DEFAULT_MAX_COUNT;\n queue = await this.delegate!.getBuffer(queueKey);\n\n if (queue === undefined) {\n queue = new Uint32Array(maxCount);\n await this.delegate!.setBuffer(queueKey, queue);\n } else if (queue.length !== maxCount) {\n queue = new Uint32Array(queue.buffer, 0, maxCount);\n await this.delegate!.setBuffer(queueKey, queue);\n }\n\n this.queues.set(queryDefId, queue);\n }\n\n await this.delegate!.setNumber(lastUsedKeyFor(queryDefId), Date.now());\n await this.delegate!.setNumber(cacheTimeKeyFor(queryDefId), cacheTime);\n\n const indexOfKey = queue.indexOf(queryKey);\n\n if (indexOfKey >= 0) {\n if (indexOfKey === 0) {\n return;\n }\n queue.copyWithin(1, 0, indexOfKey);\n queue[0] = queryKey;\n return;\n }\n\n const evicted = queue[queue.length - 1];\n queue.copyWithin(1, 0, queue.length - 1);\n queue[0] = queryKey;\n\n if (evicted !== 0) {\n await this.writerDeleteValue(evicted);\n await this.delegate!.delete(updatedAtKeyFor(evicted));\n }\n }\n\n async purgeStaleQueries(): Promise<void> {\n if (!this.delegate) return;\n\n const allKeys = await this.delegate.getAllKeys();\n const now = Date.now();\n\n for (const key of allKeys) {\n if (!key.startsWith(LAST_USED_PREFIX)) continue;\n\n const queryDefId = key.slice(LAST_USED_PREFIX.length);\n const lastUsedAt = await this.delegate.getNumber(key);\n const cacheTime = (await this.delegate.getNumber(cacheTimeKeyFor(queryDefId))) ?? DEFAULT_CACHE_TIME;\n const cacheTimeMs = cacheTime * 60 * 1000;\n\n if (lastUsedAt === undefined || now - lastUsedAt > cacheTimeMs) {\n const queue = await this.delegate.getBuffer(queueKeyFor(queryDefId));\n\n if (queue !== undefined) {\n for (const queryKey of queue) {\n if (queryKey !== 0) {\n await this.writerDeleteValue(queryKey);\n await this.delegate.delete(updatedAtKeyFor(queryKey));\n }\n }\n }\n\n await this.delegate.delete(queueKeyFor(queryDefId));\n await this.delegate.delete(key);\n await this.delegate.delete(cacheTimeKeyFor(queryDefId));\n this.queues.delete(queryDefId);\n }\n }\n }\n\n private async setValue(id: number, value: unknown, refIds?: Set<number>): Promise<void> {\n const delegate = this.delegate!;\n\n await delegate.setString(valueKeyFor(id), JSON.stringify(value));\n\n const refIdsKey = refIdsKeyFor(id);\n\n const prevRefIds = await delegate.getBuffer(refIdsKey);\n\n if (refIds === undefined || refIds.size === 0) {\n await delegate.delete(refIdsKey);\n\n // Decrement all previous refs\n if (prevRefIds !== undefined) {\n for (let i = 0; i < prevRefIds.length; i++) {\n const refId = prevRefIds[i];\n await this.decrementRefCount(refId);\n }\n }\n } else {\n // Convert the set to a Uint32Array and capture all the refIds before we\n // delete previous ones from the set\n // NOTE: Using spread operator because Hermes (React Native) doesn't correctly\n // handle new Uint32Array(Set) - it produces an empty array instead of converting\n const newRefIds = new Uint32Array([...refIds]);\n\n if (prevRefIds !== undefined) {\n // Process new refs: increment if not in old\n for (let i = 0; i < prevRefIds.length; i++) {\n const refId = prevRefIds[i];\n\n if (refIds.has(refId)) {\n refIds.delete(refId);\n } else {\n await this.decrementRefCount(refId);\n }\n }\n }\n\n // No previous refs, increment all unique new refs\n for (const refId of refIds) {\n await this.incrementRefCount(refId);\n }\n\n await delegate.setBuffer(refIdsKey, newRefIds);\n }\n }\n\n private async writerDeleteValue(id: number): Promise<void> {\n const delegate = this.delegate!;\n const refIdsKey = refIdsKeyFor(id);\n\n await delegate.delete(valueKeyFor(id));\n await delegate.delete(refCountKeyFor(id));\n\n const refIds = await delegate.getBuffer(refIdsKey);\n await delegate.delete(refIdsKey); // Clean up the refIds key\n\n if (refIds === undefined) {\n return;\n }\n\n // Decrement ref counts for all referenced entities\n for (const refId of refIds) {\n if (refId !== 0) {\n await this.decrementRefCount(refId);\n }\n }\n }\n\n private async incrementRefCount(refId: number): Promise<void> {\n const delegate = this.delegate!;\n const refCountKey = refCountKeyFor(refId);\n const currentCount = (await delegate.getNumber(refCountKey)) ?? 0;\n const newCount = currentCount + 1;\n await delegate.setNumber(refCountKey, newCount);\n }\n\n private async decrementRefCount(refId: number): Promise<void> {\n const delegate = this.delegate!;\n const refCountKey = refCountKeyFor(refId);\n const currentCount = await delegate.getNumber(refCountKey);\n\n if (currentCount === undefined) {\n // Already deleted or never existed\n return;\n }\n\n const newCount = currentCount - 1;\n\n if (newCount === 0) {\n // Entity exists, cascade delete it\n await this.writerDeleteValue(refId);\n } else {\n await delegate.setNumber(refCountKey, newCount);\n }\n }\n}\n"],"names":["AsyncQueryStore","config","sendMessage","msg","resolve","error","queryDef","queryKey","updatedAt","updatedAtKeyFor","cacheTimeMs","DEFAULT_CACHE_TIME","valueStr","valueKeyFor","entityIds","refIdsKeyFor","preloadedEntities","preloaded","entityId","entityValue","childIds","value","refIds","message","entityKey","queryDefId","cacheTime","queueKey","queueKeyFor","queue","maxCount","DEFAULT_MAX_COUNT","lastUsedKeyFor","cacheTimeKeyFor","indexOfKey","evicted","allKeys","now","key","LAST_USED_PREFIX","lastUsedAt","id","delegate","refIdsKey","prevRefIds","i","refId","newRefIds","refCountKeyFor","refCountKey","newCount","currentCount"],"mappings":"yHAoEO,MAAMA,CAAsC,CAChC,SACA,SACA,YACA,aAA+B,CAAA,EAC/B,WAAuC,IAChD,sBACA,iBAER,YAAYC,EAA+B,CACzC,KAAK,SAAWA,EAAO,SACvB,KAAK,SAAWA,EAAO,SAGvB,KAAM,CAAE,YAAAC,GAAgBD,EAAO,QAAQ,KAAK,cAAc,KAAK,IAAI,CAAC,EAIpE,GAHA,KAAK,YAAcC,EAGf,KAAK,SAAU,CACjB,GAAI,CAAC,KAAK,SACR,MAAM,IAAI,MAAM,6BAA6B,EAE/C,KAAK,oBAAA,CACP,CACF,CAEQ,cAAcC,EAAyB,CACzC,KAAK,UAEP,KAAK,eAAeA,CAAG,CAG3B,CAEQ,eAAeA,EAAyB,CAC9C,KAAK,aAAa,KAAKA,CAAG,EAEtB,KAAK,mBACP,KAAK,iBAAA,EACL,KAAK,iBAAmB,OAE5B,CAEQ,SAASA,EAAyB,CACpC,KAAK,SACP,KAAK,eAAeA,CAAG,EAEvB,KAAK,YAAYA,CAAG,CAExB,CAEQ,qBAA4B,CAClC,KAAK,sBAAwB,KAAK,aAAA,CACpC,CAEA,MAAc,cAA8B,CAC1C,OAAa,CAE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CI,GADgB,MAAMR,EAAS,UAAUO,CAAW,GAAM,GAChC,EAChC,MAAMP,EAAS,UAAUO,EAAaC,CAAQ,CAChD,CAEA,MAAc,kBAAkBJ,EAA8B,CAC5D,MAAMJ,EAAW,KAAK,SAChBO,EAAcD,EAAAA,eAAeF,CAAK,EAClCK,EAAe,MAAMT,EAAS,UAAUO,CAAW,EAEzD,GAAIE,IAAiB,OAEnB,OAGF,MAAMD,EAAWC,EAAe,EAE5BD,IAAa,EAEf,MAAM,KAAK,kBAAkBJ,CAAK,EAElC,MAAMJ,EAAS,UAAUO,EAAaC,CAAQ,CAElD,CACF"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../shared-Ct5zKrt4.js");class v{kv=Object.create(null);has(e){return e in this.kv}getString(e){return this.kv[e]}setString(e,s){this.kv[e]=s}getNumber(e){return this.kv[e]}setNumber(e,s){this.kv[e]=s}getBuffer(e){return this.kv[e]}setBuffer(e,s){this.kv[e]=s}delete(e){delete this.kv[e]}getAllKeys(){return Object.keys(this.kv)}}class a{constructor(e){this.kv=e}queues=new Map;loadQuery(e,s){const i=this.kv.getNumber(r.updatedAtKeyFor(s)),t=(e.statics.cache?.cacheTime??r.DEFAULT_CACHE_TIME)*60*1e3;if(i===void 0||i<Date.now()-t)return;const n=this.kv.getString(r.valueKeyFor(s));if(n===void 0)return;const o=this.kv.getBuffer(r.refIdsKeyFor(s));let u;return o!==void 0&&(u=new Map,this.preloadEntities(o,u)),this.activateQuery(e,s),{value:JSON.parse(n),refIds:o===void 0?void 0:new Set(o??[]),updatedAt:i,preloadedEntities:u}}preloadEntities(e,s){for(const i of e){const t=this.kv.getString(r.valueKeyFor(i));if(t===void 0)continue;s.set(i,JSON.parse(t));const n=this.kv.getBuffer(r.refIdsKeyFor(i));n!==void 0&&this.preloadEntities(n,s)}}saveQuery(e,s,i,t,n){this.setValue(s,i,n),this.kv.setNumber(r.updatedAtKeyFor(s),t),this.activateQuery(e,s)}saveEntity(e,s,i){this.setValue(e,s,i)}activateQuery(e,s){if(!this.kv.has(r.valueKeyFor(s)))return;const i=e.statics.id;let t=this.queues.get(i);if(t===void 0){const u=e.statics.cache?.maxCount??r.DEFAULT_MAX_COUNT;t=this.kv.getBuffer(r.queueKeyFor(i)),t===void 0?(t=new Uint32Array(u),this.kv.setBuffer(r.queueKeyFor(i),t)):t.length!==u&&(t=new Uint32Array(t.buffer,0,u),this.kv.setBuffer(r.queueKeyFor(i),t)),this.queues.set(i,t)}this.kv.setNumber(r.lastUsedKeyFor(i),Date.now()),this.kv.setNumber(r.cacheTimeKeyFor(i),e.statics.cache?.cacheTime??r.DEFAULT_CACHE_TIME);const n=t.indexOf(s);if(n>=0){if(n===0)return;t.copyWithin(1,0,n),t[0]=s;return}const o=t[t.length-1];t.copyWithin(1,0,t.length-1),t[0]=s,o!==0&&(this.deleteQuery(o),this.kv.delete(r.updatedAtKeyFor(o)))}purgeStaleQueries(){const e=this.kv.getAllKeys(),s=Date.now();for(const i of e){if(!i.startsWith(r.LAST_USED_PREFIX))continue;const t=i.slice(r.LAST_USED_PREFIX.length),n=this.kv.getNumber(i),u=(this.kv.getNumber(r.cacheTimeKeyFor(t))??r.DEFAULT_CACHE_TIME)*60*1e3;if(n===void 0||s-n>u){const c=this.kv.getBuffer(r.queueKeyFor(t));if(c!==void 0)for(const f of c)f!==0&&(this.deleteQuery(f),this.kv.delete(r.updatedAtKeyFor(f)));this.kv.delete(r.queueKeyFor(t)),this.kv.delete(i),this.kv.delete(r.cacheTimeKeyFor(t)),this.queues.delete(t)}}}setValue(e,s,i){const t=this.kv;t.setString(r.valueKeyFor(e),JSON.stringify(s));const n=r.refIdsKeyFor(e),o=t.getBuffer(n);if(i===void 0||i.size===0){if(t.delete(n),o!==void 0)for(let u=0;u<o.length;u++){const c=o[u];this.decrementRefCount(c)}}else{const u=new Uint32Array([...i]);if(o!==void 0)for(let c=0;c<o.length;c++){const f=o[c];i.has(f)?i.delete(f):this.decrementRefCount(f)}for(const c of i)this.incrementRefCount(c);t.setBuffer(n,u)}}deleteQuery(e){const s=this.kv;s.delete(r.valueKeyFor(e)),s.delete(r.refCountKeyFor(e));const i=s.getBuffer(r.refIdsKeyFor(e));if(s.delete(r.refIdsKeyFor(e)),i!==void 0)for(const t of i)t!==0&&this.decrementRefCount(t)}incrementRefCount(e){const s=r.refCountKeyFor(e),t=(this.kv.getNumber(s)??0)+1;this.kv.setNumber(s,t)}decrementRefCount(e){const s=r.refCountKeyFor(e),i=this.kv.getNumber(s);if(i===void 0)return;const t=i-1;t===0?this.deleteQuery(e):this.kv.setNumber(s,t)}}exports.MemoryPersistentStore=v;exports.SyncQueryStore=a;
2
+ //# sourceMappingURL=sync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.js","sources":["../../../../src/stores/sync.ts"],"sourcesContent":["import { CachedQuery, QueryStore, type PreloadedEntityMap } from '../QueryClient.js';\nimport { QueryDefinition } from '../query.js';\nimport {\n cacheTimeKeyFor,\n DEFAULT_CACHE_TIME,\n DEFAULT_MAX_COUNT,\n LAST_USED_PREFIX,\n lastUsedKeyFor,\n queueKeyFor,\n refCountKeyFor,\n refIdsKeyFor,\n updatedAtKeyFor,\n valueKeyFor,\n} from './shared.js';\n\nexport interface SyncPersistentStore {\n has(key: string): boolean;\n\n getString(key: string): string | undefined;\n setString(key: string, value: string): void;\n\n getNumber(key: string): number | undefined;\n setNumber(key: string, value: number): void;\n\n getBuffer(key: string): Uint32Array | undefined;\n setBuffer(key: string, value: Uint32Array): void;\n\n delete(key: string): void;\n\n getAllKeys(): string[];\n}\n\nexport class MemoryPersistentStore implements SyncPersistentStore {\n private readonly kv: Record<string, unknown> = Object.create(null);\n\n has(key: string): boolean {\n return key in this.kv;\n }\n\n getString(key: string): string | undefined {\n return this.kv[key] as string | undefined;\n }\n\n setString(key: string, value: string): void {\n this.kv[key] = value;\n }\n\n getNumber(key: string): number | undefined {\n return this.kv[key] as number | undefined;\n }\n\n setNumber(key: string, value: number): void {\n this.kv[key] = value;\n }\n\n getBuffer(key: string): Uint32Array | undefined {\n return this.kv[key] as Uint32Array | undefined;\n }\n\n setBuffer(key: string, value: Uint32Array): void {\n this.kv[key] = value;\n }\n\n delete(key: string): void {\n delete this.kv[key];\n }\n\n getAllKeys(): string[] {\n return Object.keys(this.kv);\n }\n}\n\nexport class SyncQueryStore implements QueryStore {\n queues: Map<string, Uint32Array> = new Map();\n\n constructor(private readonly kv: SyncPersistentStore) {}\n\n loadQuery(queryDef: QueryDefinition<any, any, any>, queryKey: number): CachedQuery | undefined {\n const updatedAt = this.kv.getNumber(updatedAtKeyFor(queryKey));\n\n const cacheTimeMs = (queryDef.statics.cache?.cacheTime ?? DEFAULT_CACHE_TIME) * 60 * 1000;\n if (updatedAt === undefined || updatedAt < Date.now() - cacheTimeMs) {\n return;\n }\n\n const valueStr = this.kv.getString(valueKeyFor(queryKey));\n\n if (valueStr === undefined) {\n return;\n }\n\n const entityIds = this.kv.getBuffer(refIdsKeyFor(queryKey));\n\n let preloadedEntities: PreloadedEntityMap | undefined;\n if (entityIds !== undefined) {\n preloadedEntities = new Map();\n this.preloadEntities(entityIds, preloadedEntities);\n }\n\n this.activateQuery(queryDef, queryKey);\n\n return {\n value: JSON.parse(valueStr) as Record<string, unknown>,\n refIds: entityIds === undefined ? undefined : new Set(entityIds ?? []),\n updatedAt,\n preloadedEntities,\n };\n }\n\n private preloadEntities(entityIds: Uint32Array, preloaded: PreloadedEntityMap): void {\n for (const entityId of entityIds) {\n const entityValue = this.kv.getString(valueKeyFor(entityId));\n\n if (entityValue === undefined) {\n continue;\n }\n\n preloaded.set(entityId, JSON.parse(entityValue) as Record<string, unknown>);\n\n const childIds = this.kv.getBuffer(refIdsKeyFor(entityId));\n\n if (childIds === undefined) {\n continue;\n }\n\n this.preloadEntities(childIds, preloaded);\n }\n }\n\n saveQuery(\n queryDef: QueryDefinition<any, any, any>,\n queryKey: number,\n value: unknown,\n updatedAt: number,\n refIds?: Set<number>,\n ): void {\n this.setValue(queryKey, value, refIds);\n this.kv.setNumber(updatedAtKeyFor(queryKey), updatedAt);\n this.activateQuery(queryDef, queryKey);\n }\n\n saveEntity(entityKey: number, value: unknown, refIds?: Set<number>): void {\n this.setValue(entityKey, value, refIds);\n }\n\n activateQuery(queryDef: QueryDefinition<any, any, any>, queryKey: number): void {\n if (!this.kv.has(valueKeyFor(queryKey))) {\n return;\n }\n\n const queryDefId = queryDef.statics.id;\n let queue = this.queues.get(queryDefId);\n\n if (queue === undefined) {\n const maxCount = queryDef.statics.cache?.maxCount ?? DEFAULT_MAX_COUNT;\n queue = this.kv.getBuffer(queueKeyFor(queryDefId));\n\n if (queue === undefined) {\n queue = new Uint32Array(maxCount);\n this.kv.setBuffer(queueKeyFor(queryDefId), queue);\n } else if (queue.length !== maxCount) {\n queue = new Uint32Array(queue.buffer, 0, maxCount);\n this.kv.setBuffer(queueKeyFor(queryDefId), queue);\n }\n\n this.queues.set(queryDefId, queue);\n }\n\n this.kv.setNumber(lastUsedKeyFor(queryDefId), Date.now());\n this.kv.setNumber(cacheTimeKeyFor(queryDefId), queryDef.statics.cache?.cacheTime ?? DEFAULT_CACHE_TIME);\n\n const indexOfKey = queue.indexOf(queryKey);\n\n if (indexOfKey >= 0) {\n if (indexOfKey === 0) {\n return;\n }\n queue.copyWithin(1, 0, indexOfKey);\n queue[0] = queryKey;\n return;\n }\n\n const evicted = queue[queue.length - 1];\n queue.copyWithin(1, 0, queue.length - 1);\n queue[0] = queryKey;\n\n if (evicted !== 0) {\n this.deleteQuery(evicted);\n this.kv.delete(updatedAtKeyFor(evicted));\n }\n }\n\n purgeStaleQueries(): void {\n const allKeys = this.kv.getAllKeys();\n const now = Date.now();\n\n for (const key of allKeys) {\n if (!key.startsWith(LAST_USED_PREFIX)) continue;\n\n const queryDefId = key.slice(LAST_USED_PREFIX.length);\n const lastUsedAt = this.kv.getNumber(key);\n const cacheTime = this.kv.getNumber(cacheTimeKeyFor(queryDefId)) ?? DEFAULT_CACHE_TIME;\n const cacheTimeMs = cacheTime * 60 * 1000;\n\n if (lastUsedAt === undefined || now - lastUsedAt > cacheTimeMs) {\n const queue = this.kv.getBuffer(queueKeyFor(queryDefId));\n\n if (queue !== undefined) {\n for (const queryKey of queue) {\n if (queryKey !== 0) {\n this.deleteQuery(queryKey);\n this.kv.delete(updatedAtKeyFor(queryKey));\n }\n }\n }\n\n this.kv.delete(queueKeyFor(queryDefId));\n this.kv.delete(key);\n this.kv.delete(cacheTimeKeyFor(queryDefId));\n this.queues.delete(queryDefId);\n }\n }\n }\n\n private setValue(id: number, value: unknown, refIds?: Set<number>): void {\n const kv = this.kv;\n\n kv.setString(valueKeyFor(id), JSON.stringify(value));\n\n const refIdsKey = refIdsKeyFor(id);\n\n const prevRefIds = kv.getBuffer(refIdsKey);\n\n if (refIds === undefined || refIds.size === 0) {\n kv.delete(refIdsKey);\n\n // Decrement all previous refs\n if (prevRefIds !== undefined) {\n for (let i = 0; i < prevRefIds.length; i++) {\n const refId = prevRefIds[i];\n this.decrementRefCount(refId);\n }\n }\n } else {\n // Convert the set to a Uint32Array and capture all the refIds before we\n // delete previous ones from the set\n // NOTE: Using spread operator because Hermes (React Native) doesn't correctly\n // handle new Uint32Array(Set) - it produces an empty array instead of converting\n const newRefIds = new Uint32Array([...refIds]);\n\n if (prevRefIds !== undefined) {\n // Process new refs: increment if not in old\n for (let i = 0; i < prevRefIds.length; i++) {\n const refId = prevRefIds[i];\n\n if (refIds.has(refId)) {\n refIds.delete(refId);\n } else {\n this.decrementRefCount(refId);\n }\n }\n }\n\n // No previous refs, increment all unique new refs\n for (const refId of refIds) {\n this.incrementRefCount(refId);\n }\n\n kv.setBuffer(refIdsKey, newRefIds);\n }\n }\n\n deleteQuery(id: number): void {\n const kv = this.kv;\n\n kv.delete(valueKeyFor(id));\n kv.delete(refCountKeyFor(id));\n\n const refIds = kv.getBuffer(refIdsKeyFor(id));\n kv.delete(refIdsKeyFor(id)); // Clean up the refIds key\n\n if (refIds === undefined) {\n return;\n }\n\n // Decrement ref counts for all referenced entities\n for (const refId of refIds) {\n if (refId !== 0) {\n this.decrementRefCount(refId);\n }\n }\n }\n\n private incrementRefCount(refId: number): void {\n const refCountKey = refCountKeyFor(refId);\n const currentCount = this.kv.getNumber(refCountKey) ?? 0;\n const newCount = currentCount + 1;\n this.kv.setNumber(refCountKey, newCount);\n }\n\n private decrementRefCount(refId: number): void {\n const refCountKey = refCountKeyFor(refId);\n const currentCount = this.kv.getNumber(refCountKey);\n\n if (currentCount === undefined) {\n // Already deleted or never existed\n return;\n }\n\n const newCount = currentCount - 1;\n\n if (newCount === 0) {\n // Entity exists, cascade delete it\n this.deleteQuery(refId);\n } else {\n this.kv.setNumber(refCountKey, newCount);\n }\n }\n}\n"],"names":["MemoryPersistentStore","key","value","SyncQueryStore","kv","queryDef","queryKey","updatedAt","updatedAtKeyFor","cacheTimeMs","DEFAULT_CACHE_TIME","valueStr","valueKeyFor","entityIds","refIdsKeyFor","preloadedEntities","preloaded","entityId","entityValue","childIds","refIds","entityKey","queryDefId","queue","maxCount","DEFAULT_MAX_COUNT","queueKeyFor","lastUsedKeyFor","cacheTimeKeyFor","indexOfKey","evicted","allKeys","now","LAST_USED_PREFIX","lastUsedAt","id","refIdsKey","prevRefIds","i","refId","newRefIds","refCountKeyFor","refCountKey","newCount","currentCount"],"mappings":"yHAgCO,MAAMA,CAAqD,CAC/C,GAA8B,OAAO,OAAO,IAAI,EAEjE,IAAIC,EAAsB,CACxB,OAAOA,KAAO,KAAK,EACrB,CAEA,UAAUA,EAAiC,CACzC,OAAO,KAAK,GAAGA,CAAG,CACpB,CAEA,UAAUA,EAAaC,EAAqB,CAC1C,KAAK,GAAGD,CAAG,EAAIC,CACjB,CAEA,UAAUD,EAAiC,CACzC,OAAO,KAAK,GAAGA,CAAG,CACpB,CAEA,UAAUA,EAAaC,EAAqB,CAC1C,KAAK,GAAGD,CAAG,EAAIC,CACjB,CAEA,UAAUD,EAAsC,CAC9C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AGF,MAAMD,EAAWC,EAAe,EAE5BD,IAAa,EAEf,KAAK,YAAYJ,CAAK,EAEtB,KAAK,GAAG,UAAUG,EAAaC,CAAQ,CAE3C,CACF"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=100;function u(t){return!Number.isFinite(t)||t<n?((Number.isNaN(t)||t<0)&&console.warn(`poll: invalid interval ${t}, clamping to ${n}ms`),n):t}function s(t){const o=u(t.interval);return function(a){let i=!0,e;const c=this.refetch,r=async()=>{if(i){try{await c()}catch{}i&&(e=setTimeout(r,o))}};return e=setTimeout(r,o),()=>{i=!1,e!==void 0&&(clearTimeout(e),e=void 0)}}}exports.poll=s;
2
+ //# sourceMappingURL=polling.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"polling.js","sources":["../../../../src/subscriptions/polling.ts"],"sourcesContent":["import type { MutationEvent } from '../types.js';\n\nconst MIN_INTERVAL = 100;\n\nexport interface PollConfig {\n interval: number;\n}\n\nfunction clampInterval(interval: number): number {\n if (!Number.isFinite(interval) || interval < MIN_INTERVAL) {\n if (IS_DEV && (Number.isNaN(interval) || interval < 0)) {\n console.warn(`poll: invalid interval ${interval}, clamping to ${MIN_INTERVAL}ms`);\n }\n return MIN_INTERVAL;\n }\n return interval;\n}\n\nexport function poll(config: PollConfig): (this: any, onEvent: (event: MutationEvent) => void) => () => void {\n const interval = clampInterval(config.interval);\n\n return function subscribe(this: any, _onEvent: (event: MutationEvent) => void): () => void {\n let active = true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const refetch = this.refetch as () => Promise<unknown>;\n\n const tick = async () => {\n if (!active) return;\n try {\n await refetch();\n } catch {\n // Keep polling after errors\n }\n if (active) {\n timer = setTimeout(tick, interval);\n }\n };\n\n timer = setTimeout(tick, interval);\n\n return () => {\n active = false;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n };\n}\n"],"names":["MIN_INTERVAL","clampInterval","interval","poll","config","_onEvent","active","timer","refetch","tick"],"mappings":"gFAEA,MAAMA,EAAe,IAMrB,SAASC,EAAcC,EAA0B,CAC/C,MAAI,CAAC,OAAO,SAASA,CAAQ,GAAKA,EAAWF,IAC5B,OAAO,MAAME,CAAQ,GAAKA,EAAW,IAClD,QAAQ,KAAK,0BAA0BA,CAAQ,iBAAiBF,CAAY,IAAI,EAE3EA,GAEFE,CACT,CAEO,SAASC,EAAKC,EAAwF,CAC3G,MAAMF,EAAWD,EAAcG,EAAO,QAAQ,EAE9C,OAAO,SAA8BC,EAAsD,CACzF,IAAIC,EAAS,GACTC,EAEJ,MAAMC,EAAU,KAAK,QAEfC,EAAO,SAAY,CACvB,GAAKH,EACL,IAAI,CACF,MAAME,EAAA,CACR,MAAQ,CAER,CACIF,IACFC,EAAQ,WAAWE,EAAMP,CAAQ,GAErC,EAEA,OAAAK,EAAQ,WAAWE,EAAMP,CAAQ,EAE1B,IAAM,CACXI,EAAS,GACLC,IAAU,SACZ,aAAaA,CAAK,EAClBA,EAAQ,OAEZ,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ "use strict";const b=require("signalium"),D=require("signalium/utils"),Lt=require("./shared-Ct5zKrt4.js");var L=(i=>(i.Always="always",i.Online="online",i.OfflineFirst="offlineFirst",i))(L||{}),u=(i=>(i[i.UNDEFINED=1]="UNDEFINED",i[i.NULL=2]="NULL",i[i.NUMBER=4]="NUMBER",i[i.STRING=8]="STRING",i[i.BOOLEAN=16]="BOOLEAN",i[i.OBJECT=32]="OBJECT",i[i.ARRAY=64]="ARRAY",i[i.ID=128]="ID",i[i.RECORD=256]="RECORD",i[i.UNION=512]="UNION",i[i.ENTITY=1024]="ENTITY",i[i.HAS_FORMAT=4096]="HAS_FORMAT",i[i.IS_EAGER_FORMAT=8192]="IS_EAGER_FORMAT",i[i.PARSE_RESULT=16384]="PARSE_RESULT",i[i.LIVE=32768]="LIVE",i))(u||{});const K=Symbol("array"),$=Symbol("record"),ut=Symbol("QUERY_ID");var H=(i=>(i[i.Array=0]="Array",i[i.Value=1]="Value",i))(H||{});class q{type;entityDefs;constraintFieldRefs;sort;valueType;onCreate;onUpdate;onDelete;constructor(t,e,n,s,r,o,a,c){this.type=t,this.entityDefs=e,this.constraintFieldRefs=n,this.sort=s,this.valueType=r,this.onCreate=o,this.onUpdate=a,this.onDelete=c}static array(t,e,n){return new q(0,t,e,n,void 0,void 0,void 0,void 0)}static value(t,e,n,s,r,o){return new q(1,t,e,void 0,n,s,r,o)}}const S=new WeakMap;function k(i){return S.get(i)}var z=(i=>(i[i.Query=0]="Query",i[i.Entity=1]="Entity",i))(z||{});class me{constructor(t,e,n){this._onEvict=e,this._intervalId=setInterval(this._tick,t*6e4*n)}_currentFlush=new Map;_nextFlush=new Map;_intervalId;schedule(t,e){this._nextFlush.set(t,e)}cancel(t){this._currentFlush.delete(t),this._nextFlush.delete(t)}_tick=()=>{const{_currentFlush:t,_nextFlush:e,_onEvict:n}=this;for(const[s,r]of t)n(s,r);this._currentFlush=e,this._nextFlush=new Map};destroy(){clearInterval(this._intervalId)}}class qt{_buckets=new Map;_nextTickEntries=new Map;_nextTickScheduled=!1;_onEvict;_multiplier;constructor(t,e=1){this._onEvict=t,this._multiplier=e}schedule(t,e,n){if(e===1/0)return;if(e===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(e);r||(r=new me(e,this._onEvict,this._multiplier),s.set(e,r)),r.schedule(t,n)}cancel(t,e){if(e!==1/0){if(e===0){this._nextTickEntries.delete(t);return}this._buckets.get(e)?.cancel(t)}}_flushNextTick=()=>{const{_nextTickEntries:t,_onEvict:e}=this;this._nextTickScheduled=!1;for(const[n,s]of t)e(n,s);t.clear()};destroy(){const{_buckets:t,_nextTickEntries:e}=this;for(const n of t.values())n.destroy();t.clear(),e.clear()}}class jt{schedule(t,e,n){}cancel(t,e){}destroy(){}}const G=Symbol("fieldRef"),F=Symbol("fieldRefPath"),dt=Symbol("DEFINITION_TARGET"),W=Symbol("CANCEL_PROXY"),Ee=/\[([^\]]+)\]/g;function Ut(i){const t={[G]:!0,[F]:i};return new Proxy(t,we)}const we={get(i,t){if(t===G)return!0;if(t===F)return i[F];if(t===Symbol.toPrimitive||t==="toString"||t==="valueOf"){const n=i[F];return()=>`[${n.join(".")}]`}if(typeof t=="symbol")return;const e=i[F];return Ut([...e,t])},has(i,t){return t===G||t===F}};function Vt(i){return typeof i=="object"&&i!==null&&i[G]===!0}function Kt(i){return i[F]}function lt(i){return new Proxy(i,{set(t,e,n){return t[e]=n,!0},get(t,e){return e===dt?t:e===W?()=>{}:typeof e=="symbol"?t[e]:Ut([e])}})}function $t(i){const t=i[dt];i[W]();const e={};for(const r of Object.getOwnPropertyNames(t))e[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:e,methods:n}}function ht(i,t){let e=t;for(const n of i){if(e==null)return;e=e[n]}return e}function Ce(i,t){return i.replace(Ee,(e,n)=>{const s=n.split("."),r=ht(s,t);return r!=null?encodeURIComponent(String(r)):""})}function j(i,t){if(Vt(i))return ht(Kt(i),t);if(typeof i=="string")return Ce(i,t);if(Array.isArray(i))return i.map(e=>j(e,t));if(typeof i=="object"&&i!==null&&Object.getPrototypeOf(i)===Object.prototype){const e={};for(const n of Object.keys(i))e[n]=j(i[n],t);return e}return i}function nt(i,t,e){const n=i.fields,s=i.methods,r={params:t},o={};for(const[a,c]of Object.entries(n))o[a]=j(c,r);o.params=t,o.context=e;for(const[a,c]of Object.entries(s))o[a]=c.bind(o);return o}class yt{static cache;constructor(){return lt(this)}}const Bt=Object.entries,st=Object.keys;function St(i){return typeof i=="number"?i|u.UNDEFINED:i instanceof _?(i.mask&u.UNDEFINED)!==0?i:_.cloneWith(i,u.UNDEFINED):i}function be(i){return i instanceof _&&(i.mask&u.OBJECT)!==0&&(i.mask&(u.ENTITY|u.ARRAY|u.UNION|u.RECORD|u.LIVE))===0}function Qt(i,t,e){const n=new Set;for(const r of i)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 i){const d=l?.[r];d!==void 0?(o++,a===void 0&&(a=d),be(d)?c.push(d.shape):(f=!1,c.push(void 0))):(f=!1,c.push(void 0))}if(f&&o>0){const l=Qt(c,t),d=new _(u.OBJECT,l);s[r]=o<t?St(d):d}else s[r]=o<t?St(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,e,n,s,r,o){this.mask=t,this.shape=e,this.values=n,this.typenameField=s,this.typenameValue=r,this.idField=o}static merge(t){if(t.length===1)return t[0];const e=t.length,n=t.map(c=>c.shape);t[0].typenameValue;const s=Qt(n,e);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 _(u.ENTITY|u.OBJECT,s,void 0,o,a,r)}static cloneWith(t,e){const n=new _(e|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 J extends Set{lowercaseMap;constructor(t){super(t),this.lowercaseMap=new Map;for(const e of t)if(typeof e=="string"){const n=e.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 '${e}' both become '${n}'`);this.lowercaseMap.set(n,e)}}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 xe=1128875347;D.registerCustomHash(J,i=>{let t=xe;for(const e of i)t+=D.hashValue(e);return t>>>0});function pt(i,t){return new _(i,t)}function Re(i){return pt(u.ARRAY,i)}function Oe(i){return pt(u.RECORD|u.OBJECT,i)}function Se(i){return pt(u.PARSE_RESULT,i)}function Yt(i,t){let e=i,n,s,r;for(const[o,a]of Bt(t))switch(typeof a){case"number":if((a&u.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 J||a instanceof Set)break;a.mask&u.LIVE&&(e|=u.LIVE);break}return new _(e,t,void 0,s,r,n)}function Ne(i){return Yt(u.OBJECT,i)}function Nt(i,t,e){const n=i.mask;if((n&u.UNION)!==0){const s=i;if(s.typenameField!==void 0){if(e!==void 0&&e!==s.typenameField)throw new Error(`Union typename field conflict: Cannot merge unions with different typename fields ('${e}' vs '${s.typenameField}')`);e=s.typenameField}const r=s.shape;if(r!==void 0)for(const o of[...st(r),K,$]){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&u.ARRAY)!==0){if(t[K]!==void 0)throw new Error("Array shape already defined");t[K]=i.shape}else if((n&u.RECORD)!==0){if(t[$]!==void 0)throw new Error("Record shape already defined");t[$]=i.shape}else{const s=i.typenameField,r=i.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(e!==void 0&&s!==e)throw new Error("Object definitions must have the same typename field to be in the same union");e=s,t[r]=i}return e}function gt(...i){const t=i;let e=0,n=0,s,r,o,a,c=0;for(const l of t){if(typeof l=="number"){e|=l;continue}if(l instanceof Set){if(r===void 0)r=new Set(l);else for(const d of l)r.add(d);continue}if(n++,c|=l.mask,n===1){s=l;continue}n===2&&(o=Object.create(null),a=Nt(s,o,a)),a=Nt(l,o,a)}if(n===0)return r===void 0?e:e===0?r:new _(e|u.UNION,void 0,r);if(n===1)return _.cloneWith(s,e);const f=e|c|u.UNION;return new _(f,o,r,a)}function vt(i,t,e){const n=i;if(typeof n=="number")return n|t;if(n instanceof Set)return gt(i,t);let s=e.get(n);return s===void 0&&(s=_.cloneWith(n,t),e.set(n,s)),s}const De=new WeakMap,Ae=new WeakMap,Ie=new WeakMap;function Me(i){return vt(i,u.UNDEFINED|u.NULL,Ie)}function Fe(i){return vt(i,u.UNDEFINED,De)}function Te(i){return vt(i,u.NULL,Ae)}function ke(i){return i}function Pe(i){return new Set([i])}const Gt=((...i)=>new Set(i));Gt.caseInsensitive=(...i)=>new J(i);const Wt=16;let Le=0;const rt=[],Ht=[],zt=new Map,X=new WeakSet;class B{_raw;_formatted;_parsed;_formatId;constructor(t,e,n){this._raw=t,this._formatId=e,n?(this._formatted=rt[e](t),this._parsed=!0):this._parsed=!1,X.add(this)}getValue(){return this._parsed||(this._formatted=rt[this._formatId](this._raw),this._parsed=!0),this._formatted}toJSON(){return this._parsed?Ht[this._formatId](this._formatted):this._raw}}function qe(i){const t=zt.get(i);if(t===void 0)throw new Error(`Format ${i} not registered`);return t}function _t(i,t,e,n,s){const r=Le++;rt[r]=e,Ht[r]=n;const o=s?.eager??!0,c=r<<Wt|t|u.HAS_FORMAT|(o?u.IS_EAGER_FORMAT:0);zt.set(i,c)}_t("date",u.STRING,i=>{const t=i.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)throw new Error(`Invalid date string: ${i}. Expected YYYY-MM-DD format.`);const[,e,n,s]=t,r=new Date(Date.UTC(parseInt(e,10),parseInt(n,10)-1,parseInt(s,10)));if(isNaN(r.getTime()))throw new Error(`Invalid date string: ${i}`);return r},i=>{const t=i.getUTCFullYear(),e=String(i.getUTCMonth()+1).padStart(2,"0"),n=String(i.getUTCDate()).padStart(2,"0");return`${t}-${e}-${n}`});_t("date-time",u.STRING,i=>{const t=new Date(i);if(isNaN(t.getTime()))throw new Error(`Invalid date-time string: ${i}`);return t},i=>i.toISOString());const Dt=new WeakMap;function U(i){let t=Dt.get(i);if(t===void 0){const e=new i,n=e[dt]??e;e[W]&&e[W]();const s={};for(const[f,l]of Bt(n))s[f]=l;const r=Object.getPrototypeOf(i.prototype);if(r!=null){const f=r.constructor;if(f!==yt&&typeof f=="function"){const d=U(f).shape;for(const y of st(d))if(y in s&&s[y]!==d[y])throw new Error(`Cannot extend: field '${y}' already exists in type definition`)}}const o={},a=i.prototype;for(const f of Object.getOwnPropertyNames(a))f!=="constructor"&&typeof a[f]=="function"&&(o[f]=a[f]);t=Yt(u.ENTITY|u.OBJECT,s),t._entityClass=i,st(o).length>0&&(t._methods=o),typeof o.__subscribe=="function"&&(t._entityConfig={hasSubscribe:!0});const c=i;c.cache&&(t._entityCache=c.cache),Dt.set(i,t)}return t}function je(i){return U(i)}function Jt(i,t){if(t==null)return;const e=new Map;if(Array.isArray(t))for(const n of t){const[s,r]=n,a=U(s).typenameValue;if(a===void 0)continue;const c=[];for(const[f,l]of Object.entries(r))c.push([f,l]);c.length>0&&e.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 i){const a=o.typenameValue;a!==void 0&&e.set(a,r)}}return e.size>0?e:void 0}function Xt(i){return Array.isArray(i)?i.map(t=>U(t)):[U(i)]}function Ue(i,t){const e=Xt(i),n=e.length===1?e[0]:gt(...e.map(o=>o)),s=u.ARRAY|u.LIVE,r=new _(s,n);return r._liveConfig=q.array(e,Jt(e,t?.constraints),t?.sort),r}function Ve(i,t,e){const n=Xt(t),s=i,r=u.LIVE,o=new _(r,void 0);return o._liveConfig=q.value(n,Jt(n,e?.constraints),s,e.onCreate,e.onUpdate,e.onDelete),o}const Zt={format:qe,typename:ke,const:Pe,enum:Gt,id:u.ID|u.STRING|u.NUMBER,string:u.STRING,number:u.NUMBER,boolean:u.BOOLEAN,null:u.NULL,undefined:u.UNDEFINED,array:Re,object:Ne,record:Oe,union:gt,nullish:Me,optional:Fe,nullable:Te,result:Se,entity:je,liveArray:Ue,liveValue:Ve};function V(i,t,e){return new TypeError(`Validation error at ${i}`)}const te=Array.isArray;function At(i){if(i===null)return u.NULL;switch(typeof i){case"number":return u.NUMBER;case"string":return u.STRING;case"boolean":return u.BOOLEAN;case"undefined":return u.UNDEFINED;case"object":return te(i)?u.ARRAY:u.OBJECT;default:throw new Error(`Invalid type: ${typeof i}`)}}function Ke(i){return P(i)}function P(i){if(i===null||typeof i!="object")return i;if(te(i))return i.map(e=>P(e));if(i instanceof Date)return new Date(i.getTime());if(i instanceof Map){const e=new Map;for(const[n,s]of i)e.set(P(n),P(s));return e}if(i instanceof Set){const e=new Set;for(const n of i)e.add(P(n));return e}const t={};for(const e of Object.keys(i))t[e]=P(i[e]);return t}const mt=Object.entries,$e=()=>{};class ot{queryClient=void 0;preloadedEntities=void 0;warn=$e;isPartialEvent=!1;seen=void 0;seenByKey=void 0;reset(t,e,n,s=!1){this.queryClient=t,this.preloadedEntities=e,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 ee(i,t,e){return T(i,t,e,"")}function Be(i,t,e){return Et(i,t,e)}function It(i,t,e,n){const s=i>>Wt;if((i&u.IS_EAGER_FORMAT)!==0)try{return new B(t,s,!0)}catch(o){if((i&u.UNDEFINED)!==0){e.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 B(t,s,!1)}function T(i,t,e,n){const s=t;if(s instanceof J){const c=s.get(i);if(c===void 0)throw V(n);return c}if(s instanceof Set){if(!s.has(i))throw V(n);return i}if(typeof s=="string"){if(i==null)return s;if(i!==s)throw V(n);return i}if(typeof s=="number"){const c=At(i);if((s&c)===0){if((s&u.UNDEFINED)!==0){e.warn("Invalid value for optional type, defaulting to undefined",{value:i,path:n});return}throw V(n)}return(s&u.HAS_FORMAT)!==0&&i!==null&&i!==void 0?It(s,i,e,n):i}const r=s.mask,o=s._liveConfig;if(o!==void 0&&o.type===H.Value)return o.valueType!==void 0?T(i,o.valueType,e,n):i;if((r&u.PARSE_RESULT)!==0)try{return{success:!0,value:T(i,s.shape,e,n)}}catch(c){return{success:!1,error:c instanceof Error?c:new Error(String(c))}}const a=At(i);if((r&a)===0&&!s.values?.has(i)){if((r&u.UNDEFINED)!==0){e.warn("Invalid value for optional type, defaulting to undefined",{value:i,path:n});return}throw V(n)}return a<u.OBJECT?(r&u.HAS_FORMAT)!==0&&i!==null&&i!==void 0?It(r,i,e,n):i:(r&u.UNION)!==0?Qe(a,i,s,e,n):a===u.ARRAY?ie(i,s.shape,e,n):(r&u.RECORD)!==0?ne(i,s.shape,e,n):(r&u.ENTITY)!==0&&e.queryClient!==void 0?Et(i,s,e):se(i,s,e,n)}function Qe(i,t,e,n,s){if(i===u.ARRAY){const r=e.shape[K];return r===void 0||typeof r=="number"?t:ie(t,r,n,s)}else{const r=e.typenameField,o=r?t[r]:void 0;if(o===void 0||typeof o!="string"){const c=e.shape[$];if(c===void 0)throw new Error(`Typename field '${r}' is required for union discrimination but was not found in the data`);return ne(t,c,n,s)}const a=e.shape[o];if(a===void 0||typeof a=="number")throw new Error(`Unknown typename '${o}' in union`);return a.mask&u.ENTITY&&n.queryClient!==void 0?Et(t,a,n):se(t,a,n,s)}}function ie(i,t,e,n){const s=[];for(let r=0;r<i.length;r++)try{s.push(T(i[r],t,e,`${n}[${r}]`))}catch(o){e.warn("Failed to parse array item, filtering out",{index:r,value:i[r],error:o instanceof Error?o.message:String(o)})}return s}function ne(i,t,e,n){for(const[s,r]of mt(i))i[s]=T(r,t,e,`${n}["${s}"]`);return i}function se(i,t,e,n){if(S.has(i))return i;const s=t.shape;for(const[r,o]of mt(s))i[r]=T(i[r],o,e,`${n}.${r}`);return i}function Et(i,t,e){const n=e.queryClient,s=e.preloadedEntities;let r,o;if(s!==void 0)r=i.__entityRef,o=r;else{const p=i[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=D.hashValue([t.typenameValue,o])}const a=e.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`);i=g}const c={};typeof t.idField=="symbol"&&(c[t.idField]=o);const f=n.entityMap.getEntity(r),l=e.isPartialEvent&&f!==void 0,d={key:r,shape:t,data:c,rawKeys:l?new Set(Object.keys(i)):void 0};e.seen.set(c,d),e.seenByKey.set(r,d);const y=`[[${t.typenameValue}:${o}]]`,v=t.shape;for(const[p,g]of mt(v))l&&!(p in i)||(c[p]=T(i[p],g,e,`${y}.${p}`));return c}function Ye(i,t){return Ge(i,t.shape,t.typenameField)}function Ge(i,t,e){if(t===void 0)return!0;for(const n of Object.keys(t)){if(n===e)continue;const s=t[n];if(s instanceof _){if((s.mask&u.UNDEFINED)!==0)continue;if(!(n in i)||i[n]===void 0)return!1}else if(typeof s=="number"){if((s&u.UNDEFINED)!==0)continue;if(!(n in i)||i[n]===void 0)return!1}else if(!(n in i)||i[n]===void 0)return!1}return!0}const We=Object.prototype,Y=new WeakMap;function I(i){if(typeof i!="object"||i===null)return i;if(X.has(i))return I(i.getValue());if(S.has(i))return i;if(Array.isArray(i)){let t=Y.get(i);return t===void 0&&(t=new Proxy(i,He),Y.set(i,t)),t}if(Object.getPrototypeOf(i)===We){let t=Y.get(i);return t===void 0&&(t=new Proxy(i,ze),Y.set(i,t)),t}return i}const He={get(i,t,e){if(typeof t=="string"){const n=Number(t);if(Number.isInteger(n)&&n>=0&&n<i.length)return I(i[n])}return Reflect.get(i,t,e)},set(){return!1},deleteProperty(){return!1}},ze={get(i,t,e){return typeof t=="string"?I(i[t]):Reflect.get(i,t,e)},set(){return!1},deleteProperty(){return!1},has(i,t){return t in i},ownKeys(i){return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,t){return Object.getOwnPropertyDescriptor(i,t)}};class Je{_notifier;_queryClient;_proxies=new Map;key;typename;id;idField;data;refCount=0;entityRefs;liveCollections=[];satisfiedDefs=new WeakSet;parseId=-1;_entityCache;_extraMethods;_extraGetters;constructor(t,e,n,s,r,o){this._notifier=b.notifier(),this._queryClient=o,this.key=t,this.typename=e,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,z.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 e=this.entityRefs;if(this.entityRefs=void 0,e)for(const n of e.keys())n.release()}setChildRefs(t,e){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,e&&this.save()}addChildRef(t){this.entityRefs===void 0&&(this.entityRefs=new Map);const e=this.entityRefs.get(t)??0;this.entityRefs.set(t,e+1),e===0&&t.retain(),this.save()}removeChildRef(t){if(this.entityRefs===void 0)return;const e=this.entityRefs.get(t);e!==void 0&&(e<=1?(this.entityRefs.delete(t),t.release()):this.entityRefs.set(t,e-1),this.save())}getProxy(t){const e=t;let n=this._proxies.get(e);return n===void 0&&(n=Ze(this,this.key,t,this._notifier,this._queryClient),this._proxies.set(e,n)),n}get proxy(){return this._proxies.values().next().value}satisfiesDef(t){return this.satisfiedDefs.has(t)?!0:Ye(this.data,t)?(this.satisfiedDefs.add(t),!0):!1}save(){this._queryClient.entityMap.save(this)}notify(){this._notifier.notify()}consume(){this._notifier.consume()}}function Xe(i,t,e){const n=[];for(const s of i){if(typeof s!="object"||s===null)continue;const r=S.get(s);if(r===void 0)continue;const o=e.entityMap.getEntity(r);o!==void 0&&o.satisfiesDef(t)&&n.push(s)}return n}function Ze(i,t,e,n,s){const r=e.shape??{},o=e,a=o._methods,c=o._entityClass,f=o._entityConfig,l=c?c.prototype:yt.prototype;e.typenameField;const d=new Map,y=new Map,v=()=>({__entityRef:t});let p;f?.hasSubscribe&&a&&"__subscribe"in a&&(p=b.relay(w=>{const h=C=>{C.__eventSource=t,s.applyMutationEvent(C)},m=a.__subscribe.call(g,h);return w.value=g,m}));let g;const E=Object.keys(r);if(E.includes("__typename")||E.push("__typename"),a)for(const w of Object.keys(a))E.includes(w)||E.push(w);let N,x=E;function M(){const w=i._extraMethods;if(w!==N){if(N=w,x=E.slice(),w!==void 0)for(const m of Object.keys(w))x.includes(m)||x.push(m);const h=i._extraGetters;if(h!==void 0)for(const m of Object.keys(h))x.includes(m)||x.push(m)}return x}const R={getPrototypeOf(){return l},get(w,h){if(typeof h=="symbol")return;if(h==="toJSON")return v;if(h==="__context")return s.getContext();if(h==="__typename")return i.typename;if(p?.value,n.consume(),typeof h=="string"){const C=i._extraGetters;if(C!==void 0&&h in C)return C[h]();const A=i._extraMethods;if(A!==void 0&&h in A){let O=d.get(h);return O||(O=A[h].bind(g),d.set(h,O)),O}if(a&&h in a){let O=d.get(h);return O||(O=b.reactiveMethod(g,a[h].bind(g)),d.set(h,O)),O}}const m=i.data[h];if(typeof m=="object"&&m!==null&&X.has(m))return I(m.getValue());if(Array.isArray(m)&&typeof h=="string"){const C=r[h];if(C instanceof _&&(C.mask&u.ARRAY)!==0){const A=C.shape;if(A instanceof _&&(A.mask&u.ENTITY)!==0){const O=A.typenameValue;if(O!==void 0){const Rt=s.getEntityDefsForTypename(O);if(Rt!==void 0&&Rt.length>1){const tt=y.get(h);if(tt!==void 0&&tt.source===m)return I(tt.filtered);const Ot=Xe(m,A,s);return y.set(h,{source:m,filtered:Ot}),I(Ot)}}}}return I(m)}return I(m)},set(){return!1},has(w,h){if(h==="__typename")return!0;if(typeof h=="string"){const m=i._extraGetters;if(m&&h in m)return!0;const C=i._extraMethods;if(C&&h in C||a&&h in a)return!0}return h in r},ownKeys(){return M()},getOwnPropertyDescriptor(w,h){if(h==="__typename")return{enumerable:!0,configurable:!0,value:i.typename,writable:!1};if(h in r)return{enumerable:!0,configurable:!0,value:R.get(w,h,g),writable:!1};if(typeof h=="string"){const m=i._extraGetters;if(m&&h in m)return{enumerable:!0,configurable:!0,value:R.get(w,h,g),writable:!1};const C=i._extraMethods;if(C&&h in C)return{enumerable:!0,configurable:!0,value:R.get(w,h,g),writable:!1};if(a&&h in a)return{enumerable:!1,configurable:!0,value:R.get(w,h,g),writable:!1}}}};return g=new Proxy({},R),S.set(g,t),b.setScopeOwner(g,s),g}class ti{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,e,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=e[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 Je(t,n.typenameValue,a,o,e,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 e;if(t.entityRefs){e=new Set;for(const n of t.entityRefs.keys())e.add(n.key)}this.persistEntity(t.key,t.data,e)}}class wt{onlineSignal;manualOverride=void 0;eventListenersAttached=!1;constructor(t){const e=t??this.detectOnlineStatus();this.onlineSignal=b.signal(e),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 Ct{static onlineSignal=b.signal(!0);get isOnline(){return!0}setNetworkStatus(t){}clearManualOverride(){}getOnlineSignal(){return Ct.onlineSignal}destroy(){}}const re=new wt,ei=b.context(re);function bt(i,t=typeof window>"u"){let e;i===!1?e=0:i===void 0||i===!0?e=t?0:3:typeof i=="number"?e=i:e=i.retries;const n=typeof i=="object"&&i.retryDelay?i.retryDelay:s=>1e3*Math.pow(2,s);return{retries:e,retryDelay:n}}class oe{static cache;params;config;constructor(){return lt(this)}}class ii extends oe{method="GET";path;searchParams;body;headers;requestOptions;loadNext;getStorageKey(){return`${this.method??"GET"}:${this.path??""}`}async send(){return this.executeRequest()}resolveLoadNext(){const e=(this.getLoadNext?this.getLoadNext():void 0)??this.rawLoadNext;if(e===void 0)return;const n={params:this.params??{},result:this.resultData};return{url:e.url!==void 0?j(e.url,n):void 0,searchParams:e.searchParams!==void 0?j(e.searchParams,n):void 0}}hasNext(){const t=this.resolveLoadNext();if(t===void 0)return!1;if(t.url!==void 0&&t.url!==null)return!0;if(t.searchParams!==void 0){const e=Object.keys(t.searchParams);if(e.length===0)return!1;for(const n of e)if(t.searchParams[n]===void 0||t.searchParams[n]===null)return!1;return!0}return!1}async sendNext(){const t=this.resolveLoadNext();if(t===void 0)throw new Error("loadNext is not configured for this query");return this.executeRequest(t)}async executeRequest(t){const e=t?.url??(this.getPath?this.getPath():this.path),n=this.getMethod?this.getMethod():this.method,s=this.getSearchParams?this.getSearchParams():this.searchParams,r=t?.searchParams?{...s,...t.searchParams}:s,o=this.getBody?this.getBody():this.body,a=this.getRequestOptions?this.getRequestOptions():this.requestOptions;if(!e)throw new Error("RESTQuery requires a path. Define `path` as a field or override `getPath()`.");let c=e;if(r){const N=new URLSearchParams;for(const M in r){const R=r[M];R!=null&&N.append(M,String(R))}const x=N.toString();x&&(c+="?"+x)}const f=ft(a?.baseUrl)??ft(this.context.baseUrl),l=f?`${f}${c}`:c,{baseUrl:d,signal:y,...v}=a??{},g=o||this.headers?{...o?{"Content-Type":"application/json"}:void 0,...this.headers}:void 0,E=await this.context.fetch(l,{method:n,headers:g,body:o?JSON.stringify(o):void 0,signal:this.signal,...v});return this.response=E,E.json()}}const Mt=new WeakMap;class Z{constructor(t,e){this.captured=e,this.statics=t}statics;createExecutionContext(t,e){return nt(this.captured,t,e)}resolveOptions(t){const{methods:e}=this.captured,n=e.getConfig?e.getConfig.call(t):t.config,s=bt(n?.retry);return{config:n,retryConfig:s}}static for(t){let e=Mt.get(t);if(e!==void 0)return e;const n=new t,s=$t(n),r=String(s.methods.getStorageKey.call(s.fields)),o=s.fields.result,a=o instanceof _?o:Zt.object(o),c=(a.mask&u.ENTITY)!==0,f=t.cache,l=s.fields.loadNext,d=typeof s.methods.sendNext=="function",y=c?a:new _(u.ENTITY|u.OBJECT,a.shape,void 0,void 0,r,ut);return e=new Z({id:r,shape:y,cache:f,rawLoadNext:l,hasSendNext:d,isEntityResult:c},s),Mt.set(t,e),e}}const ni=(i,t)=>{const e=Z.for(i);return xt(e,t)};function si(i,...t){const e=Z.for(i),n=b.getContext(_e);if(n===void 0)throw new Error("QueryClient not found");const s=t[0];return n.getQuery(e,s)}function ae(i,t){return new Promise((e,n)=>{if(t?.aborted){n(t.reason);return}const s=setTimeout(e,i);t?.addEventListener("abort",()=>{clearTimeout(s),n(t.reason)},{once:!0})})}async function at(i,t,e){const n=Math.max(0,t.retries);let s;for(let r=0;r<=n;r++){e?.throwIfAborted();try{return await i()}catch(o){if(s=o,r>=n)throw o;await ae(t.retryDelay(r),e)}}throw s}class ri{def;queryKey;storageKey=-1;relay;queryClient;initialized=!1;updatedAt=void 0;params=void 0;unsubscribe=void 0;_relayState=void 0;wasPaused=!1;currentParams=void 0;debounceTimer=void 0;config=void 0;retryConfig=bt(void 0);_lastResponse=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,e,n,s){this.def=t,this.queryClient=e,this.queryKey=n,this.params=s,this._extraMethods={__refetch:this.refetch},t.statics.hasSendNext&&(this._extraMethods.__loadNext=this.loadNext);const r=Pt(s);this._queryId=r!==void 0?D.hashValue(r):0,this.relay=b.relay(o=>{this._relayState=o;const a=()=>{clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this._abortController?.abort(),this._abortController=void 0,this._loadNextAbort?.abort(),this._loadNextAbort=void 0,this._loadNextPromise=void 0,this.unsubscribe?.(),this.unsubscribe=void 0;const f=this.config?.gcTime??Lt.DEFAULT_GC_TIME;this.queryClient.gcManager.schedule(this.queryKey,f,z.Query)},c=(f=!1)=>{const{wasPaused:l,isPaused:d,initialized:y}=this;if(this.wasPaused=d,d&&!l&&y){a();return}const v=Pt(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.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,e,n=!1,s){const r=this.def;return this.rootEntity=this.queryClient.parseAndApplyRootEntity(t,this._queryId,r.statics.shape,e,n,s),this.rootEntity._extraMethods===void 0&&(this.rootEntity._extraMethods=this._extraMethods,this.rootEntity._extraGetters={__hasNext:()=>this.hasNext,__isLoadingNext:()=>this._loadNextPromise!==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,e=this.relayState;this.initialized=!0;let n;try{n=await t.loadCachedQuery(this.def,this.storageKey),n!==void 0&&(this.updatedAt=n.updatedAt,e.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 ae(0),this.isPaused)return;this.runQueryImmediately()}}catch(s){e.setError(s)}}setupSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0;const t=this.config?.subscribe;if(!t)return;const e=this._executionCtx;this.unsubscribe=t.call(e,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.rawLoadNext=this.def.statics.rawLoadNext),this._executionCtx.response=this._lastResponse,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 e=this.getOrCreateExecutionContext(),{send:n}=t.captured.methods,s=this._abortController?.signal;return e.signal=s,at(async()=>{const r=await n.call(e);this._lastResponse=e.response,this._executionCtx.response=this._lastResponse,this.resolveAndApplyOptions(),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._loadNextAbort?.abort(),this._loadNextAbort=void 0,this._loadNextPromise=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);_loadNextPromise=void 0;_loadNextAbort=void 0;loadNext=()=>{if(this.updatedAt===void 0)throw new Error("Cannot call __loadNext before initial data has loaded");return this._loadNextPromise!==void 0?this._loadNextPromise:(queueMicrotask(()=>this.rootEntity?.notify()),this._loadNextPromise=this.runLoadNext().then(t=>(this._loadNextPromise=void 0,this.rootEntity?.notify(),t),t=>{throw this._loadNextPromise=void 0,this.rootEntity?.notify(),t}),this._loadNextPromise)};get hasNext(){if(this.rootEntity===void 0||!this._executionCtx)return!1;const t=this.def.captured.methods.hasNext;return t?(this._executionCtx.resultData=this.rootEntity.data,t.call(this._executionCtx)):!1}async runLoadNext(){const t=this.def;this._loadNextAbort=new AbortController;const e=this._loadNextAbort.signal,n=this.getOrCreateExecutionContext();n.signal=e,n.resultData=this.rootEntity.data;const s=t.captured.methods.sendNext;return at(async()=>{const r=await s.call(n);this._lastResponse=n.response,this._executionCtx.response=this._lastResponse,this.resolveAndApplyOptions(),this.updatedAt=Date.now();const o=this.applyData(r,!0,!0);return this.saveQueryMetadata(),o},this.retryConfig,e)}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??L.Online;if(t===L.Always)return!1;const e=this.queryClient.networkManager.getOnlineSignal().value;switch(t){case L.Online:return!e;case L.OfflineFirst:return!e&&this.updatedAt===void 0;default:return!1}}}class oi{def;queryClient;_lastResponse;_inFlight=!1;task;constructor(t,e){this.def=t,this.queryClient=e,this.task=this.createTask()}createTask(){return b.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 e=await this.executeWithRetry(t),n=this.validateResponse(e);return this.processEffects(t,n),n}finally{this._inFlight=!1}},{desc:`Mutation(${this.def.id})`})}validateResponse(t){const e=this.def.responseShape;if(!(e instanceof _))return t;const n=this.queryClient.getContext().log?.warn??(()=>{}),s=new ot;return s.reset(void 0,void 0,n),ee(t,e,s)}processEffects(t,e){let n;if(this.def.hasGetEffects){const r=nt(this.def.captured,t??{},this.queryClient.getContext());r.result=e,r.response=this._lastResponse,n=r.getEffects()}else if(this.def.effects!==void 0){const r={params:t,result:e};n=j(this.def.effects,r)}if(n===void 0)return;const s=this.queryClient;et(n.creates,"create",s),et(n.updates,"update",s),et(n.deletes,"delete",s)}executeWithRetry(t){const e=bt(this.def.config?.retry,!0);return at(async()=>{const n=nt(this.def.captured,t??{},this.queryClient.getContext()),s=await this.def.captured.methods.send.call(n);return this._lastResponse=n.response,s},e)}}function ai(i){return typeof i=="string"?i:U(i).typenameValue}function et(i,t,e){if(i)for(const[n,s]of i){const r=ai(n);r!==void 0&&e.applyMutationEvent({type:t,typename:r,data:s})}}const ce="__eventSource";function fe(i){return{field:i,segments:i.indexOf(".")!==-1?i.split("."):void 0}}function ci(i){return i.map(fe)}function fi(i,t){if(t.segments===void 0)return i[t.field];let e=i;for(const n of t.segments){if(e==null)return;e=e[n]}return e}function ue(i,t){const e=[];for(let n=0;n<t.length;n++){const s=t[n],r=fi(i,s);if(r===void 0)return;e.push(s.field,r)}return D.hashValue(e)}function ui(i,t){if(i===void 0)return;const e=new Map;for(const[n,s]of i){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(Vt(f)){const d=Kt(f);l=ht(d,t)}else l=f;if(l===void 0){a=!1;break}o.push(c,l)}a&&e.set(n,D.hashValue(o))}return e.size>0?e:void 0}function Ft(i,t){const e=i.get(t);if(e!==void 0)return e.map(([n])=>n).sort()}class di{fields;fieldPaths;_bindings=new Map;constructor(t){this.fields=t,this.fieldPaths=t.map(fe)}register(t,e){let n=this._bindings.get(t);n===void 0&&(n=new Set,this._bindings.set(t,n)),n.add(e)}unregister(t,e){const n=this._bindings.get(t);n!==void 0&&(n.delete(e),n.size===0&&this._bindings.delete(t))}getMatching(t){return this._bindings.get(t)}get isEmpty(){return this._bindings.size===0}}function Tt(i){return D.hashValue(i)}class li{_groups=new Map;getOrCreateGroup(t){const e=Tt(t);let n=this._groups.get(e);return n===void 0&&(n=new di(t),this._groups.set(e,n)),n}register(t,e,n){this.getOrCreateGroup(e).register(t,n)}unregister(t,e,n){const s=Tt(e),r=this._groups.get(s);r!==void 0&&(r.unregister(t,n),r.isEmpty&&this._groups.delete(s))}registerBinding(t,e){const n=t._constraintHashes.get(e);if(n===void 0)return;const s=Ft(t._constraintFieldRefs,e);s!==void 0&&this.register(n,s,t)}unregisterBinding(t,e){const n=t._constraintHashes.get(e);if(n===void 0)return;const s=Ft(t._constraintFieldRefs,e);s!==void 0&&this.unregister(n,s,t)}routeEvent(t,e,n,s,r,o){for(const a of this._groups.values()){const c=ue(e,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 kt(i){const t=new Set;for(const e of i)if(typeof e=="object"&&e!==null){const n=k(e);n!==void 0&&t.add(n)}return t}class de{_queryClient;_parent;_constraintHashes;_entityDefsByTypename;_constraintFieldRefs;instance;constructor(t,e,n,s,r,o){this._queryClient=n,this._parent=s,this._constraintHashes=r,this._constraintFieldRefs=e,this.instance=o,this._entityDefsByTypename=new Map;for(const a of t)a.typenameValue!==void 0&&this._entityDefsByTypename.set(a.typenameValue,a);X.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,e,n,s,r){const o=this._entityDefsByTypename.get(t);if(o===void 0)return;const a=this._queryClient.entityMap.getEntity(e);if(n==="delete"){const f=a!==void 0?a.getProxy(o):r;f!==void 0&&(this.instance.onEvent(e,f,r??a?.data??{},"delete"),s?.());return}if(a===void 0||!a.satisfiesDef(o))return;s?.();const c=a.getProxy(o);this.instance.onEvent(e,c,a.data,n)}destroy(){this._queryClient.unregisterLiveCollection(this);const t=this._parent.liveCollections,e=t.indexOf(this);e!==-1&&t.splice(e,1)}}class hi{_notifier;_items;_keys;_outputSignal;_queryClient;_parent;constructor(t,e,n,s,r,o){this._notifier=b.notifier(),this._items=n,this._keys=kt(n),this._queryClient=t,this._parent=e;const a=s!==void 0&&r!==void 0,c=o!==void 0;(a||c)&&(this._outputSignal=b.reactiveSignal(()=>{this._notifier.consume();let f=this._items;if(a){const l=[];for(const d of f){if(typeof d!="object"||d===null){l.push(d);continue}const y=k(d);if(y===void 0){l.push(d);continue}const v=t.entityMap.getEntity(y);if(v===void 0){l.push(d);continue}v.consume(),ue(v.data,s)===r&&l.push(d)}f=l}return c&&(f=(f===this._items?f.slice():f).sort(o)),f}))}onEvent(t,e,n,s){switch(s){case"create":this.add(t,e);break;case"update":!this.has(t)&&e!==void 0&&this.add(t,e);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,e){if(this._keys.has(t))return!1;this._keys.add(t),this._items.push(e);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 e=this._findIndex(t);e!==-1&&this._items.splice(e,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 e=this._items,n=Array.isArray(t)?t:[];this._items=n,this._keys=kt(n);for(const s of n)if(typeof s=="object"&&s!==null){const r=k(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.addChildRef(o)}}for(const s of e)if(typeof s=="object"&&s!==null){const r=k(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 e of t){if(typeof e!="object"||e===null)continue;const n=k(e);n!==void 0&&this.add(n,e)}}_findIndex(t){for(let e=0;e<this._items.length;e++){const n=this._items[e];if(typeof n=="object"&&n!==null&&k(n)===t)return e}return-1}}class yi{_notifier;_value;_createdKeys;_deletedKeys;_queryClient;_parent;_onCreate;_onUpdate;_onDelete;constructor(t,e,n,s,r,o){this._notifier=b.notifier(),this._value=n,this._createdKeys=new Set,this._deletedKeys=new Set,this._queryClient=t,this._parent=e,this._onCreate=s,this._onUpdate=r,this._onDelete=o}onEvent(t,e,n,s){switch(s){case"create":if(this._createdKeys.has(t))return;this._createdKeys.add(t),this._value=this._onCreate(this._value,e);break;case"update":this._value=this._onUpdate(this._value,e??n);break;case"delete":if(this._deletedKeys.has(t))return;this._deletedKeys.add(t),this._value=this._onDelete(this._value,e??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 le(i,t,e,n,s){let r=i.constraintFieldRefs;if(r===void 0){r=new Map;for(const f of i.entityDefs){const l=f.typenameValue;l!==void 0&&r.set(l,[[ce,e.key]])}}const o=ui(r,n)??new Map;let a;if(i.type===H.Array){let f,l;if(i.constraintFieldRefs!==void 0&&o.size>0&&o.size===1)for(const[d]of i.constraintFieldRefs){const y=o.get(d);if(y!==void 0){l=y;const v=i.constraintFieldRefs.get(d);v!==void 0&&(f=ci(v.map(([p])=>p)));break}}a=new hi(s,e,Array.isArray(t)?t:[],f,l,i.sort)}else a=new yi(s,e,t,i.onCreate,i.onUpdate,i.onDelete);const c=new de(i.entityDefs,r,s,e,o,a);return e.liveCollections.push(c),s.registerLiveCollection(c),c}const he=Object.entries,ye=Object.prototype;function it(i,t,e,n=!1){const s=i.queryClient;s.currentParseId++;const r=i.seen,o=new Map;return{data:Q(t,r,s,e,o,n),entityRefs:o}}function Q(i,t,e,n,s,r){if(typeof i!="object"||i===null)return i;const o=t.get(i);if(o!==void 0)return pi(o,t,e,n,s,r);if(Array.isArray(i)){for(let a=0;a<i.length;a++){const c=i[a];typeof c=="object"&&c!==null&&!(c instanceof B)&&!S.has(c)&&(i[a]=Q(c,t,e,n,s,r))}return i}if(Object.getPrototypeOf(i)===ye&&!S.has(i)){const a=i;for(const c of Object.keys(a)){const f=a[c];typeof f=="object"&&f!==null&&!(f instanceof B)&&!S.has(f)&&(a[c]=Q(f,t,e,n,s,r))}}return i}function pe(i){return typeof i=="object"&&i!==null&&!(i instanceof B)&&!S.has(i)}function pi(i,t,e,n,s,r){const{key:o,data:a,shape:c,rawKeys:f}=i,l=c.shape,d=e.prepareEntity(o,a,c),y=d.data,v=y!==a,p=v&&f!==void 0&&d.entityRefs!==void 0?new Map(d.entityRefs):new Map;if(v?(ge(l,a,y,f,d,y,t,e,n,p,r),d.notify()):ve(l,a,d,a,t,e,n,p,r),r&&d.liveCollections.length>0)for(const E of d.liveCollections){const N=E.instance.getRawValue();if(Array.isArray(N))for(const x of N){if(typeof x!="object"||x===null)continue;const M=S.get(x);if(M===void 0)continue;const R=e.entityMap.getEntity(M);R!==void 0&&p.set(R,(p.get(R)??0)+1)}}d.setChildRefs(p.size>0?p:void 0,n);const g=d.getProxy(c);return s.set(d,(s.get(d)??0)+1),g}function ge(i,t,e,n,s,r,o,a,c,f,l){for(const[d,y]of he(i))if(!(n!==void 0&&!n.has(d)))if(pe(t[d])&&(t[d]=Q(t[d],o,a,c,f,l)),y instanceof _&&y._liveConfig!==void 0){const v=e[d];v instanceof de?l?v.append(t[d]):v.reset(t[d]):e[d]=le(y._liveConfig,t[d],s,r,a)}else{const v=t[d],p=e[d];if(ct(v)&&ct(p)){const g=y instanceof _&&y.shape!==void 0?y.shape:void 0;if(g!==void 0)ge(g,v,p,void 0,s,r,o,a,c,f,l);else for(const E of Object.keys(v))p[E]=v[E];e[d]=p}else e[d]=v}}function ve(i,t,e,n,s,r,o,a,c){for(const[f,l]of he(i))if(f in t)if(pe(t[f])&&(t[f]=Q(t[f],s,r,o,a,c)),l instanceof _&&l._liveConfig!==void 0)t[f]=le(l._liveConfig,t[f],e,n,r);else{const d=t[f];if(ct(d)){const y=l instanceof _&&l.shape!==void 0?l.shape:void 0;y!==void 0&&ve(y,d,e,n,s,r,o,a,c)}}}function ct(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.getPrototypeOf(i)===ye&&!S.has(i)}function ft(i){if(i!==void 0)return typeof i=="string"?i:typeof i=="function"?i():i.value}function gi(i){return b.isSignal(i)}function Pt(i){if(i===void 0)return;const t={};for(const[e,n]of Object.entries(i))gi(n)?t[e]=n.value:t[e]=n;return t}const xt=(i,t)=>D.hashValue([i.statics.id,t]);class vi{constructor(t,e={fetch,log:console},n,s){this.context=e,this.isServer=typeof window>"u",this.store=t,this.gcManager=s??(this.isServer?new jt:new qt(this.handleEviction,this.context.evictionMultiplier)),this.networkManager=n??new wt,this.entityMap=new ti((r,o,a)=>this.store.saveEntity(r,o,a)),this.store.purgeStaleQueries?.()}entityMap;queryInstances=new Map;mutationInstances=new Map;gcManager;networkManager;isServer;store;currentParseId=0;typenameRegistry=new Map;constraintRegistry=new Map;mergedDefCache=new Map;getContext(){return this.context}registerEntityDef(t){const e=t.typenameValue;if(e===void 0||t._entityClass===void 0)return;const n=this.typenameRegistry.get(e);if(n!==void 0){if(n.indexOf(t)!==-1)return;n.push(t),this.mergedDefCache.delete(e),this.getMergedDef(e)}else this.typenameRegistry.set(e,[t])}getEntityDefsForTypename(t){return this.typenameRegistry.get(t)}getMergedDef(t){let e=this.mergedDefCache.get(t);if(e!==void 0)return e;const n=this.typenameRegistry.get(t);if(n!==void 0)return e=_.merge(n),this.mergedDefCache.set(t,e),e}saveQueryData(t,e,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,e,n,s,o)}activateQuery(t){const{def:e,queryKey:n,storageKey:s,config:r}=t;this.store.activateQuery(e,s);const o=r?.gcTime??Lt.DEFAULT_GC_TIME;this.gcManager.cancel(n,o)}loadCachedQuery(t,e){return this.store.loadQuery(t,e)}getQuery(t,e){const n=xt(t,e);let s=this.queryInstances.get(n);return s===void 0&&(s=new ri(t,this,n,e),this.queryInstances.set(n,s)),s.relay}getMutation(t){const e=t.id;let n=this.mutationInstances.get(e);return n===void 0&&(n=new oi(t,this),this.mutationInstances.set(e,n)),n.task}parseData(t,e,n){const s=this.context.log?.warn??(()=>{}),r=new ot;return r.reset(this,n,s),{data:ee(t,e,r),ctx:r}}applyRefs(t,e=!0,n=!1){return it(t.ctx,t.data,e,n)}parseAndApplyRootEntity(t,e,n,s,r=!1,o){typeof n.idField=="symbol"&&typeof t=="object"&&t!==null&&!("__entityRef"in t)&&(t[ut]=e);const a=this.parseData(t,n,o),c=it(a.ctx,a.data,s,r),f=S.get(c.data);return this.entityMap.getEntity(f)}prepareEntity(t,e,n){return this.registerEntityDef(n),this.entityMap.getOrCreateEntity(t,e,n,this)}applyMutationEvent(t){const{type:e,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:e==="delete"&&(typeof o=="string"||typeof o=="number")?o:o[r];if(a===void 0)return;const c=D.hashValue([n,a]),f=t.__eventSource,l=typeof o=="object"&&o!==null?o:{},d=this.entityMap.getEntity(c);if(e==="delete"){const g=d!==void 0?d.data:l;this.routeEvent(n,g,c,e,f,void 0,g);return}try{const g=this.context.log?.warn??(()=>{}),E=new ot;E.reset(this,void 0,g,!0);const N=Be(l,s,E);it(E,N,!0)}catch(g){if(this.context.log?.warn?.("Failed to apply mutation event",g),d===void 0){const E=this.entityMap.getEntity(c);E!==void 0&&E.evict()}return}const y=this.entityMap.getEntity(c);if(y===void 0)return;this.entityMap.save(y);const v=d===void 0;let p=!1;this.routeEvent(n,y.data,c,e,f,()=>{p=!0}),v&&!p&&y.evict()}handleEviction=(t,e)=>{if(e===z.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 e=this.constraintRegistry.get(t);return e===void 0&&(e=new li,this.constraintRegistry.set(t,e)),e}registerLiveCollection(t){for(const[e,n]of t._entityDefsByTypename)this.registerEntityDef(n),this.getOrCreateMatcher(e).registerBinding(t,e)}unregisterLiveCollection(t){for(const e of t._entityDefsByTypename.keys()){const n=this.constraintRegistry.get(e);n!==void 0&&n.unregisterBinding(t,e)}}routeEvent(t,e,n,s,r,o,a){const c=this.constraintRegistry.get(t);if(c===void 0)return;const f=r!==void 0?{...e,[ce]:r}:e;c.routeEvent(t,f,n,s,o,a)}destroy(){this.gcManager.destroy(),this.networkManager.destroy(),this.queryInstances.clear(),this.mutationInstances.clear(),this.constraintRegistry.clear(),this.typenameRegistry.clear(),this.mergedDefCache.clear()}}const _e=b.context(void 0);exports.ARRAY_KEY=K;exports.Entity=yt;exports.GcManager=qt;exports.LiveFieldConfig=q;exports.LiveFieldType=H;exports.Mask=u;exports.NetworkManager=wt;exports.NetworkManagerContext=ei;exports.NetworkMode=L;exports.NoOpGcManager=jt;exports.NoOpNetworkManager=Ct;exports.QUERY_ID=ut;exports.Query=oe;exports.QueryClient=vi;exports.QueryClientContext=_e;exports.RECORD_KEY=$;exports.RESTQuery=ii;exports.ValidatorDef=_;exports.createDefinitionProxy=lt;exports.defaultNetworkManager=re;exports.draft=Ke;exports.extractDefinition=$t;exports.fetchQuery=si;exports.queryKeyForClass=ni;exports.registerFormat=_t;exports.resolveBaseUrl=ft;exports.t=Zt;
2
+ //# sourceMappingURL=QueryClient-qi3bR0eD.js.map