fetchium 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +6 -5
  2. package/dist/cjs/development/QueryClient-CLi3ONNM.js +2 -0
  3. package/dist/cjs/development/QueryClient-CLi3ONNM.js.map +1 -0
  4. package/dist/cjs/development/QueryController-BQA49OYU.js +2 -0
  5. package/dist/cjs/development/QueryController-BQA49OYU.js.map +1 -0
  6. package/dist/cjs/development/index.js +1 -1
  7. package/dist/cjs/development/index.js.map +1 -1
  8. package/dist/cjs/development/mutation-CikIl_6k.js +2 -0
  9. package/dist/cjs/development/mutation-CikIl_6k.js.map +1 -0
  10. package/dist/cjs/development/react/index.js +1 -1
  11. package/dist/cjs/development/rest/index.js +2 -0
  12. package/dist/cjs/development/rest/index.js.map +1 -0
  13. package/dist/cjs/development/topic/index.js +2 -0
  14. package/dist/cjs/development/topic/index.js.map +1 -0
  15. package/dist/cjs/production/QueryClient-N0MJmuHW.js +2 -0
  16. package/dist/cjs/production/QueryClient-N0MJmuHW.js.map +1 -0
  17. package/dist/cjs/production/QueryController-BQA49OYU.js +2 -0
  18. package/dist/cjs/production/QueryController-BQA49OYU.js.map +1 -0
  19. package/dist/cjs/production/index.js +1 -1
  20. package/dist/cjs/production/index.js.map +1 -1
  21. package/dist/cjs/production/mutation-P_Yb4LI9.js +2 -0
  22. package/dist/cjs/production/mutation-P_Yb4LI9.js.map +1 -0
  23. package/dist/cjs/production/react/index.js +1 -1
  24. package/dist/cjs/production/rest/index.js +2 -0
  25. package/dist/cjs/production/rest/index.js.map +1 -0
  26. package/dist/cjs/production/topic/index.js +2 -0
  27. package/dist/cjs/production/topic/index.js.map +1 -0
  28. package/dist/esm/MutationResult.d.ts +0 -1
  29. package/dist/esm/MutationResult.d.ts.map +1 -1
  30. package/dist/esm/QueryClient.d.ts +26 -4
  31. package/dist/esm/QueryClient.d.ts.map +1 -1
  32. package/dist/esm/QueryController.d.ts +49 -0
  33. package/dist/esm/QueryController.d.ts.map +1 -0
  34. package/dist/esm/QueryResult.d.ts +10 -10
  35. package/dist/esm/QueryResult.d.ts.map +1 -1
  36. package/dist/esm/development/QueryClient-Dtde3pss.js +2572 -0
  37. package/dist/esm/development/QueryClient-Dtde3pss.js.map +1 -0
  38. package/dist/esm/development/QueryController-Ch_ncxiI.js +14 -0
  39. package/dist/esm/development/QueryController-Ch_ncxiI.js.map +1 -0
  40. package/dist/esm/development/index.js +29 -100
  41. package/dist/esm/development/index.js.map +1 -1
  42. package/dist/esm/development/mutation-UZshUQAf.js +58 -0
  43. package/dist/esm/development/mutation-UZshUQAf.js.map +1 -0
  44. package/dist/esm/development/react/index.js +1 -1
  45. package/dist/esm/development/rest/index.js +142 -0
  46. package/dist/esm/development/rest/index.js.map +1 -0
  47. package/dist/esm/development/{shared-Dq2yW78d.js → shared-DcuVH8Pf.js} +5 -5
  48. package/dist/esm/development/{shared-Dq2yW78d.js.map → shared-DcuVH8Pf.js.map} +1 -1
  49. package/dist/esm/development/stores/async.js +6 -6
  50. package/dist/esm/development/stores/sync.js +5 -5
  51. package/dist/esm/development/topic/index.js +86 -0
  52. package/dist/esm/development/topic/index.js.map +1 -0
  53. package/dist/esm/index.d.ts +5 -4
  54. package/dist/esm/index.d.ts.map +1 -1
  55. package/dist/esm/mutation.d.ts +6 -19
  56. package/dist/esm/mutation.d.ts.map +1 -1
  57. package/dist/esm/production/{QueryClient-BP0Z1rQV.js → QueryClient-YqnBxFy1.js} +972 -968
  58. package/dist/esm/production/QueryClient-YqnBxFy1.js.map +1 -0
  59. package/dist/esm/production/QueryController-Ch_ncxiI.js +14 -0
  60. package/dist/esm/production/QueryController-Ch_ncxiI.js.map +1 -0
  61. package/dist/esm/production/index.js +29 -100
  62. package/dist/esm/production/index.js.map +1 -1
  63. package/dist/esm/production/mutation-pgFl1uIY.js +58 -0
  64. package/dist/esm/production/mutation-pgFl1uIY.js.map +1 -0
  65. package/dist/esm/production/react/index.js +1 -1
  66. package/dist/esm/production/rest/index.js +142 -0
  67. package/dist/esm/production/rest/index.js.map +1 -0
  68. package/dist/esm/production/{shared-Dq2yW78d.js → shared-DcuVH8Pf.js} +5 -5
  69. package/dist/esm/production/{shared-Dq2yW78d.js.map → shared-DcuVH8Pf.js.map} +1 -1
  70. package/dist/esm/production/stores/async.js +6 -6
  71. package/dist/esm/production/stores/sync.js +5 -5
  72. package/dist/esm/production/topic/index.js +86 -0
  73. package/dist/esm/production/topic/index.js.map +1 -0
  74. package/dist/esm/query-types.d.ts +2 -4
  75. package/dist/esm/query-types.d.ts.map +1 -1
  76. package/dist/esm/query.d.ts +17 -39
  77. package/dist/esm/query.d.ts.map +1 -1
  78. package/dist/esm/rest/RESTMutation.d.ts +18 -0
  79. package/dist/esm/rest/RESTMutation.d.ts.map +1 -0
  80. package/dist/esm/rest/RESTQuery.d.ts +24 -0
  81. package/dist/esm/rest/RESTQuery.d.ts.map +1 -0
  82. package/dist/esm/rest/RESTQueryController.d.ts +34 -0
  83. package/dist/esm/rest/RESTQueryController.d.ts.map +1 -0
  84. package/dist/esm/rest/index.d.ts +5 -0
  85. package/dist/esm/rest/index.d.ts.map +1 -0
  86. package/dist/esm/stores/shared.d.ts.map +1 -1
  87. package/dist/esm/testing/MockClient.d.ts +64 -0
  88. package/dist/esm/testing/MockClient.d.ts.map +1 -0
  89. package/dist/esm/testing/auto-generate.d.ts +20 -0
  90. package/dist/esm/testing/auto-generate.d.ts.map +1 -0
  91. package/dist/esm/testing/entity-factory.d.ts +13 -0
  92. package/dist/esm/testing/entity-factory.d.ts.map +1 -0
  93. package/dist/esm/testing/index.d.ts +6 -0
  94. package/dist/esm/testing/index.d.ts.map +1 -0
  95. package/dist/esm/testing/types.d.ts +37 -0
  96. package/dist/esm/testing/types.d.ts.map +1 -0
  97. package/dist/esm/topic/TopicQuery.d.ts +10 -0
  98. package/dist/esm/topic/TopicQuery.d.ts.map +1 -0
  99. package/dist/esm/topic/TopicQueryController.d.ts +43 -0
  100. package/dist/esm/topic/TopicQueryController.d.ts.map +1 -0
  101. package/dist/esm/topic/index.d.ts +3 -0
  102. package/dist/esm/topic/index.d.ts.map +1 -0
  103. package/dist/esm/typeDefs.d.ts +1 -1
  104. package/dist/esm/types.d.ts +9 -4
  105. package/dist/esm/types.d.ts.map +1 -1
  106. package/package.json +51 -4
  107. package/plugin/.claude-plugin/plugin.json +10 -0
  108. package/plugin/agents/fetchium.md +168 -0
  109. package/plugin/docs/api/fetchium-react.md +135 -0
  110. package/plugin/docs/api/fetchium.md +674 -0
  111. package/plugin/docs/api/stores-async.md +219 -0
  112. package/plugin/docs/api/stores-sync.md +133 -0
  113. package/plugin/docs/core/entities.md +351 -0
  114. package/plugin/docs/core/queries.md +600 -0
  115. package/plugin/docs/core/streaming.md +550 -0
  116. package/plugin/docs/core/types.md +374 -0
  117. package/plugin/docs/data/caching.md +298 -0
  118. package/plugin/docs/data/live-data.md +435 -0
  119. package/plugin/docs/data/mutations.md +465 -0
  120. package/plugin/docs/guides/auth.md +318 -0
  121. package/plugin/docs/guides/error-handling.md +351 -0
  122. package/plugin/docs/guides/offline.md +270 -0
  123. package/plugin/docs/guides/testing.md +301 -0
  124. package/plugin/docs/quickstart.md +170 -0
  125. package/plugin/docs/reference/pagination.md +519 -0
  126. package/plugin/docs/reference/rest-queries.md +107 -0
  127. package/plugin/docs/reference/why-signalium.md +364 -0
  128. package/plugin/docs/setup/project-setup.md +319 -0
  129. package/plugin/install.mjs +88 -0
  130. package/plugin/skills/design/SKILL.md +140 -0
  131. package/plugin/skills/teach/SKILL.md +105 -0
  132. package/dist/cjs/development/QueryClient-CpmwggOn.js +0 -2
  133. package/dist/cjs/development/QueryClient-CpmwggOn.js.map +0 -1
  134. package/dist/cjs/production/QueryClient-qi3bR0eD.js +0 -2
  135. package/dist/cjs/production/QueryClient-qi3bR0eD.js.map +0 -1
  136. package/dist/esm/development/QueryClient-DRZtPKFD.js +0 -2568
  137. package/dist/esm/development/QueryClient-DRZtPKFD.js.map +0 -1
  138. package/dist/esm/production/QueryClient-BP0Z1rQV.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";class r{queryClient;register(e){this.queryClient=e}}exports.QueryController=r;
2
+ //# sourceMappingURL=QueryController-BQA49OYU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"QueryController-BQA49OYU.js","sources":["../../../src/QueryController.ts"],"sourcesContent":["import { type QueryContext } from './query-types.js';\nimport type { Query } from './query.js';\nimport type { Mutation } from './mutation.js';\n\n// ================================\n// IQueryClient — minimal interface QueryController needs from the client\n// (avoids circular import: QueryClient → QueryController → QueryClient)\n// ================================\n\nexport interface IQueryClientForController {\n getContext(): QueryContext;\n applyMutationEvent(event: import('./types.js').MutationEvent): void;\n}\n\n// ================================\n// QueryController base class\n// ================================\n\nexport abstract class QueryController {\n protected queryClient: IQueryClientForController | undefined;\n\n /**\n * Called once by QueryClient when this controller is registered.\n * Subclasses can override to do setup (e.g. open a WebSocket connection).\n */\n register(queryClient: IQueryClientForController): void {\n this.queryClient = queryClient;\n }\n\n /**\n * Called when the network comes online or goes offline.\n * Subclasses can override to reconnect persistent connections (e.g. WebSocket).\n */\n onNetworkStatusChange?(isOnline: boolean): void;\n\n /**\n * Called when the QueryClient is destroyed.\n * Subclasses can override to clean up connections or timers.\n */\n destroy?(): void;\n\n /**\n * Send the query and return the raw response data.\n * @param ctx The query execution context (a reified Query instance with params applied).\n * @param signal AbortSignal to cancel the in-flight request.\n */\n abstract send(ctx: Query, signal: AbortSignal): Promise<unknown>;\n\n /**\n * Fetch the next page of results. Only implement if the controller supports pagination.\n * @param ctx The query execution context. `ctx.resultData` contains the current page's data.\n * @param signal AbortSignal to cancel the in-flight request.\n */\n sendNext?(ctx: Query, signal: AbortSignal): Promise<unknown>;\n\n /**\n * Return true if more pages are available for the current result.\n * Called reactively — do not perform async work here.\n */\n hasNext?(ctx: Query): boolean;\n\n /**\n * Send a mutation and return the raw response data.\n * @param ctx The mutation execution context (a reified Mutation instance with params applied).\n * @param signal AbortSignal to cancel the in-flight request.\n */\n sendMutation?(ctx: Mutation, signal: AbortSignal): Promise<unknown>;\n}\n"],"names":["QueryController","queryClient"],"mappings":"aAkBO,MAAeA,CAAgB,CAC1B,YAMV,SAASC,EAA8C,CACrD,KAAK,YAAcA,CACrB,CAwCF"}
@@ -1,2 +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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./QueryClient-CLi3ONNM.js"),r=require("./QueryController-BQA49OYU.js"),t=require("./mutation-CikIl_6k.js");exports.ARRAY_KEY=e.ARRAY_KEY;exports.Entity=e.Entity;exports.GcManager=e.GcManager;exports.LiveFieldConfig=e.LiveFieldConfig;exports.LiveFieldType=e.LiveFieldType;exports.Mask=e.Mask;exports.NetworkManager=e.NetworkManager;exports.NetworkManagerContext=e.NetworkManagerContext;exports.NetworkMode=e.NetworkMode;exports.NoOpGcManager=e.NoOpGcManager;exports.NoOpNetworkManager=e.NoOpNetworkManager;exports.QUERY_ID=e.QUERY_ID;exports.Query=e.Query;exports.QueryClient=e.QueryClient;exports.QueryClientContext=e.QueryClientContext;exports.RECORD_KEY=e.RECORD_KEY;exports.defaultNetworkManager=e.defaultNetworkManager;exports.draft=e.draft;exports.fetchQuery=e.fetchQuery;exports.queryKeyForClass=e.queryKeyForClass;exports.registerFormat=e.registerFormat;exports.t=e.t;exports.QueryController=r.QueryController;exports.Mutation=t.Mutation;exports.getMutation=t.getMutation;exports.mutationKeyForClass=t.mutationKeyForClass;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +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,EAAUC,EAAAA,eAAeH,GAAgB,OAAO,GAAKG,iBAAe,KAAK,QAAQ,OAAO,EACxFC,EAAUF,EAAU,GAAGA,CAAO,GAAGL,CAAI,GAAKA,EAE1C,CAAE,QAASQ,EAAU,OAAQC,EAAS,GAAGC,CAAA,EAAiBP,GAAmB,CAAA,EAE7EQ,EAAuB,CAC3B,eAAgB,mBAChB,GAAI,KAAK,OAAA,EAGLC,EAAgB,MAAM,KAAK,QAAQ,MAAML,EAAS,CACtD,OAAAN,EACA,QAAAU,EACA,KAAM,KAAK,UAAUP,CAAQ,EAC7B,OAAQ,KAAK,OACb,GAAGM,CAAA,CACJ,EAED,YAAK,SAAWE,EACTA,EAAc,KAAA,CACvB,CACF,CAMA,MAAMC,MAAuB,QAEhBC,EAAuBC,GAAoC,CACtE,MAAMC,EAAiBH,EAAiB,IAAIE,CAAG,EAE/C,GAAIC,IAAmB,OACrB,MAAM,IAAI,MAAM,+BAA+B,EAGjD,OAAOA,IAAiB,EAC1B,EAMA,SAASC,EAAwBC,EAAuE,CACtG,IAAIC,EAASN,EAAiB,IAAIK,CAAa,EAE/C,GAAIC,IAAW,OACb,OAAOA,EAGT,IAAIC,EAEJ,MAAMC,EAAS,IAAoC,CACjD,GAAID,IAAuB,OACzB,OAAOA,EAGT,MAAME,EAAW,IAAIJ,EACfK,EAAWC,EAAAA,kBAAkBF,CAAQ,EACrC,CAAE,OAAAG,GAAWF,EAEbG,EAAK,YAAY,OAAOH,EAAS,QAAQ,cAAc,KAAKE,CAAM,CAAC,CAAC,GAEpEE,EAAaF,EAAO,QAAU,CAAA,EAC9BG,EAAgBD,aAAsBE,EAAAA,aACxCF,EACAG,EAAAA,EAAE,OAAOH,CAAU,EACjBI,EAAcN,EAAO,OACrBO,EACJD,IAAgB,OACVA,aAAuBF,EAAAA,aAAeE,EAAcD,IAAE,OAAOC,CAAW,EAC1E,OAEN,OAAAX,EAAqB,CACnB,GAAAM,EACA,aAAAE,EACA,cAAAI,EACA,SAAAT,EACA,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"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ "use strict";const g=require("signalium"),n=require("./QueryClient-CLi3ONNM.js");class y{static controller;params;result;optimisticUpdates;config;effects;constructor(){return n.createDefinitionProxy(this)}}const a=new WeakMap,h=t=>{const e=a.get(t);if(e===void 0)throw new Error("Mutation definition not found");return e().id};function D(t){let e=a.get(t);if(e!==void 0)return e;let o;const f=()=>{if(o!==void 0)return o;const l=new t,r=n.extractDefinition(l),{fields:i}=r,d=`mutation:${String(r.methods.getIdentityKey.call(i))}`,c=i.params??{},m=c instanceof n.ValidatorDef?c:n.t.object(c),s=i.result,p=s!==void 0?s instanceof n.ValidatorDef?s:n.t.object(s):void 0,u=t.controller;if(!u)throw new Error(`Mutation class "${t.name}" must define a static \`controller\` property. Extend RESTMutation (from fetchium/rest) or set \`static controller = MyController\` on your mutation class.`);return o={id:d,requestShape:m,responseShape:p,captured:r,optimisticUpdates:i.optimisticUpdates??!1,config:i.config,effects:i.effects,hasGetEffects:typeof r.methods.getEffects=="function",controllerClass:u},o};return a.set(t,f),f}function M(t){const e=D(t),o=g.getContext(n.QueryClientContext);if(o===void 0)throw new Error("QueryClient not found");return o.getMutation(e())}exports.Mutation=y;exports.getMutation=M;exports.mutationKeyForClass=h;
2
+ //# sourceMappingURL=mutation-CikIl_6k.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-CikIl_6k.js","sources":["../../../src/mutation.ts"],"sourcesContent":["import { getContext, ReactiveTask } from 'signalium';\nimport { ExtractType, InternalTypeDef, MutationEffects, TypeDef, RetryConfig, TypeDefShape } from './types.js';\nimport { QueryClientContext, type QueryContext } from './QueryClient.js';\nimport { ValidatorDef, t } from './typeDefs.js';\nimport { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.js';\nimport type { QueryController } from './QueryController.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 controllerClass: typeof QueryController;\n}\n\n// ================================\n// Mutation base class\n// ================================\n\nexport abstract class Mutation {\n static controller?: typeof QueryController;\n\n readonly params?: TypeDefShape;\n readonly result?: TypeDefShape;\n readonly optimisticUpdates?: boolean;\n readonly config?: MutationConfigOptions;\n readonly effects?: Readonly<MutationEffects>;\n\n declare context: QueryContext;\n\n abstract getIdentityKey(): unknown;\n\n getEffects?(): MutationEffects;\n\n constructor() {\n return createDefinitionProxy(this);\n }\n}\n\n// ================================\n// Mutation definition cache and lookup\n// ================================\n\nconst mutationDefCache = new WeakMap<new () => Mutation, () => MutationDefinition<any, any>>();\n\nexport const mutationKeyForClass = (cls: new () => Mutation): string => {\n const getMutationDef = mutationDefCache.get(cls);\n\n if (getMutationDef === undefined) {\n throw new Error('Mutation definition not found');\n }\n\n return getMutationDef().id;\n};\n\n// ================================\n// Internal: build mutation definition from class\n// ================================\n\nfunction buildMutationDefinition(MutationClass: new () => Mutation): () => MutationDefinition<any, any> {\n let cached = mutationDefCache.get(MutationClass);\n\n if (cached !== undefined) {\n return cached;\n }\n\n let mutationDefinition: MutationDefinition<any, any> | undefined;\n\n const getter = (): MutationDefinition<any, any> => {\n if (mutationDefinition !== undefined) {\n return mutationDefinition;\n }\n\n const instance = new MutationClass();\n const captured = extractDefinition(instance);\n const { fields } = captured;\n\n const id = `mutation:${String(captured.methods.getIdentityKey.call(fields))}`;\n\n const requestDef = fields.params ?? {};\n const requestShape = (requestDef instanceof ValidatorDef\n ? requestDef\n : t.object(requestDef)) as unknown as InternalTypeDef;\n const responseDef = fields.result;\n const responseShape =\n responseDef !== undefined\n ? ((responseDef instanceof ValidatorDef ? responseDef : t.object(responseDef)) as unknown as InternalTypeDef)\n : undefined;\n\n const controllerClass = (MutationClass as typeof Mutation).controller;\n if (!controllerClass) {\n throw new Error(\n `Mutation class \"${MutationClass.name}\" must define a static \\`controller\\` property. ` +\n `Extend RESTMutation (from fetchium/rest) or set \\`static controller = MyController\\` on your mutation class.`,\n );\n }\n\n mutationDefinition = {\n id,\n requestShape,\n responseShape,\n captured,\n optimisticUpdates: fields.optimisticUpdates ?? false,\n config: fields.config,\n effects: fields.effects,\n hasGetEffects: typeof captured.methods.getEffects === 'function',\n controllerClass,\n };\n\n return mutationDefinition;\n };\n\n mutationDefCache.set(MutationClass, getter);\n return getter;\n}\n\n// ================================\n// Public API\n// ================================\n\nexport function getMutation<T extends Mutation>(\n MutationClass: new () => T,\n): ReactiveTask<Readonly<ExtractType<T['result']>>, [ExtractType<T['params']>]> {\n const getMutationDef = buildMutationDefinition(MutationClass);\n\n const queryClient = getContext(QueryClientContext);\n\n if (queryClient === undefined) {\n throw new Error('QueryClient not found');\n }\n\n return queryClient.getMutation<any, any>(getMutationDef());\n}\n"],"names":["Mutation","createDefinitionProxy","mutationDefCache","mutationKeyForClass","cls","getMutationDef","buildMutationDefinition","MutationClass","cached","mutationDefinition","getter","instance","captured","extractDefinition","fields","id","requestDef","requestShape","ValidatorDef","t","responseDef","responseShape","controllerClass","getMutation","queryClient","getContext","QueryClientContext"],"mappings":"iFA+BO,MAAeA,CAAS,CAC7B,OAAO,WAEE,OACA,OACA,kBACA,OACA,QAQT,aAAc,CACZ,OAAOC,EAAAA,sBAAsB,IAAI,CACnC,CACF,CAMA,MAAMC,MAAuB,QAEhBC,EAAuBC,GAAoC,CACtE,MAAMC,EAAiBH,EAAiB,IAAIE,CAAG,EAE/C,GAAIC,IAAmB,OACrB,MAAM,IAAI,MAAM,+BAA+B,EAGjD,OAAOA,IAAiB,EAC1B,EAMA,SAASC,EAAwBC,EAAuE,CACtG,IAAIC,EAASN,EAAiB,IAAIK,CAAa,EAE/C,GAAIC,IAAW,OACb,OAAOA,EAGT,IAAIC,EAEJ,MAAMC,EAAS,IAAoC,CACjD,GAAID,IAAuB,OACzB,OAAOA,EAGT,MAAME,EAAW,IAAIJ,EACfK,EAAWC,EAAAA,kBAAkBF,CAAQ,EACrC,CAAE,OAAAG,GAAWF,EAEbG,EAAK,YAAY,OAAOH,EAAS,QAAQ,eAAe,KAAKE,CAAM,CAAC,CAAC,GAErEE,EAAaF,EAAO,QAAU,CAAA,EAC9BG,EAAgBD,aAAsBE,EAAAA,aACxCF,EACAG,EAAAA,EAAE,OAAOH,CAAU,EACjBI,EAAcN,EAAO,OACrBO,EACJD,IAAgB,OACVA,aAAuBF,EAAAA,aAAeE,EAAcD,IAAE,OAAOC,CAAW,EAC1E,OAEAE,EAAmBf,EAAkC,WAC3D,GAAI,CAACe,EACH,MAAM,IAAI,MACR,mBAAmBf,EAAc,IAAI,8JAAA,EAKzC,OAAAE,EAAqB,CACnB,GAAAM,EACA,aAAAE,EACA,cAAAI,EACA,SAAAT,EACA,kBAAmBE,EAAO,mBAAqB,GAC/C,OAAQA,EAAO,OACf,QAASA,EAAO,QAChB,cAAe,OAAOF,EAAS,QAAQ,YAAe,WACtD,gBAAAU,CAAA,EAGKb,CACT,EAEA,OAAAP,EAAiB,IAAIK,EAAeG,CAAM,EACnCA,CACT,CAMO,SAASa,EACdhB,EAC8E,CAC9E,MAAMF,EAAiBC,EAAwBC,CAAa,EAEtDiB,EAAcC,EAAAA,WAAWC,oBAAkB,EAEjD,GAAIF,IAAgB,OAClB,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAOA,EAAY,YAAsBnB,GAAgB,CAC3D"}
@@ -1,2 +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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("signalium/react"),i=require("signalium"),f=require("../QueryClient-CLi3ONNM.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
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../QueryClient-CLi3ONNM.js"),q=require("../QueryController-BQA49OYU.js"),T=require("../mutation-CikIl_6k.js");class f extends q.QueryController{_fetch;_baseUrl;constructor(e){super(),this._fetch=e?.fetch??globalThis.fetch,this._baseUrl=e?.baseUrl}async send(e,s){return this.executeRequest(e,s)}async sendNext(e,s){const t=this.resolveFetchNext(e);if(t===void 0)throw new Error("fetchNext is not configured for this query");return this.executeRequest(e,s,t)}hasNext(e){const s=this.resolveFetchNext(e);if(s===void 0)return!1;if(s.url!==void 0&&s.url!==null)return!0;if(s.searchParams!==void 0){const t=Object.keys(s.searchParams);if(t.length===0)return!1;for(const r of t)if(s.searchParams[r]===void 0||s.searchParams[r]===null)return!1;return!0}return!1}resolveFetchNext(e){const t=(e.getFetchNext?e.getFetchNext():void 0)??e.rawFetchNext;if(t===void 0)return;const r={params:e.params??{},result:e.resultData};return{url:t.url!==void 0?i.reifyValue(t.url,r):void 0,searchParams:t.searchParams!==void 0?i.reifyValue(t.searchParams,r):void 0}}buildUrl(e,s){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))return e;if(e.startsWith("/")){const t=i.resolveBaseUrl(s)??i.resolveBaseUrl(this._baseUrl)??globalThis.location?.origin;if(!t)throw new Error(`RESTQueryController: cannot resolve URL for path "${e}". Set \`baseUrl\` on the query/mutation, pass it to \`new RESTQueryController({ baseUrl })\`, or use an absolute URL.`);return`${t}${e}`}return e}async executeRequest(e,s,t){const r=t?.url??(e.getPath?e.getPath():e.path),h=e.getMethod?e.getMethod():e.method,o=e.getSearchParams?e.getSearchParams():e.searchParams,a=t?.searchParams?{...o,...t.searchParams}:o,n=e.getBody?e.getBody():e.body,l=e.getRequestOptions?e.getRequestOptions():e.requestOptions;if(!r)throw new Error("RESTQuery requires a path. Define `path` as a field or override `getPath()`.");let u=r;if(a){const m=new URLSearchParams;for(const U in a){const d=a[U];d!=null&&m.append(U,String(d))}const v=m.toString();v&&(u+="?"+v)}const g=l?.baseUrl??e.baseUrl,c=this.buildUrl(u,g),{baseUrl:p,signal:P,...R}=l??{},S=n||e.headers?{...n?{"Content-Type":"application/json"}:void 0,...e.headers}:void 0,b=await this._fetch(c,{method:h,headers:S,body:n?JSON.stringify(n):void 0,signal:s,...R});return e.response=b,b.json()}async sendMutation(e,s){const t=e,r=t.getPath?t.getPath():t.path,h=t.getMethod?t.getMethod():t.method,o=t.getBody?t.getBody():t.body,a=t.getRequestOptions?t.getRequestOptions():t.requestOptions;if(!r)throw new Error("RESTMutation requires a path. Define `path` as a field or override `getPath()`.");const n=a?.baseUrl??t.baseUrl,l=this.buildUrl(r,n),{baseUrl:u,signal:g,...c}=a??{},p={...o!==void 0?{"Content-Type":"application/json"}:{},...t.headers};return(await this._fetch(l,{method:h,headers:p,...o!==void 0?{body:JSON.stringify(o)}:{},signal:s,...c})).json()}}class O extends i.Query{static controller=f;method="GET";path;baseUrl;searchParams;body;headers;requestOptions;fetchNext;getIdentityKey(){return`${this.method??"GET"}:${this.path??""}`}}class E extends T.Mutation{static controller=f;path;baseUrl;method="POST";body;headers;requestOptions;getIdentityKey(){return`${this.method??"POST"}:${this.path??""}`}}exports.RESTMutation=E;exports.RESTQuery=O;exports.RESTQueryController=f;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/rest/RESTQueryController.ts","../../../../src/rest/RESTQuery.ts","../../../../src/rest/RESTMutation.ts"],"sourcesContent":["import { QueryController } from '../QueryController.js';\nimport { resolveBaseUrl } from '../query-types.js';\nimport { reifyValue } from '../fieldRef.js';\nimport type { Query } from '../query.js';\nimport type { Mutation } from '../mutation.js';\nimport type { FetchNextConfig } from '../query-types.js';\nimport type { RESTQuery } from './RESTQuery.js';\nimport type { RESTMutation } from './RESTMutation.js';\nimport type { QueryRequestInit, BaseUrlValue, QueryRequestOptions } from '../types.js';\n\n// ================================\n// ResolvedFetchNext\n// ================================\n\nexport interface ResolvedFetchNext {\n url?: string;\n searchParams?: Record<string, unknown>;\n}\n\n// ================================\n// RESTQueryController options\n// ================================\n\nexport interface RESTQueryControllerOptions {\n fetch?: (url: string, init?: QueryRequestInit) => Promise<Response>;\n baseUrl?: BaseUrlValue;\n}\n\n// ================================\n// RESTQueryController\n// ================================\n\nexport class RESTQueryController extends QueryController {\n private readonly _fetch: (url: string, init?: QueryRequestInit) => Promise<Response>;\n private readonly _baseUrl: BaseUrlValue | undefined;\n\n constructor(options?: RESTQueryControllerOptions) {\n super();\n this._fetch =\n options?.fetch ?? (globalThis.fetch as unknown as (url: string, init?: QueryRequestInit) => Promise<Response>);\n this._baseUrl = options?.baseUrl;\n }\n\n override async send(ctx: Query, signal: AbortSignal): Promise<unknown> {\n return this.executeRequest(ctx as RESTQuery, signal);\n }\n\n override async sendNext(ctx: Query, signal: AbortSignal): Promise<unknown> {\n const resolved = this.resolveFetchNext(ctx as RESTQuery);\n if (resolved === undefined) {\n throw new Error('fetchNext is not configured for this query');\n }\n return this.executeRequest(ctx as RESTQuery, signal, resolved);\n }\n\n override hasNext(ctx: Query): boolean {\n const resolved = this.resolveFetchNext(ctx as RESTQuery);\n if (resolved === undefined) return false;\n\n if (resolved.url !== undefined && resolved.url !== null) {\n return true;\n }\n\n if (resolved.searchParams !== undefined) {\n const keys = Object.keys(resolved.searchParams);\n if (keys.length === 0) return false;\n for (const key of keys) {\n if (resolved.searchParams[key] === undefined || resolved.searchParams[key] === null) {\n return false;\n }\n }\n return true;\n }\n\n return false;\n }\n\n private resolveFetchNext(ctx: RESTQuery): ResolvedFetchNext | undefined {\n const dynamicConfig = ctx.getFetchNext ? ctx.getFetchNext() : undefined;\n const fetchNextConfig: FetchNextConfig | undefined = dynamicConfig ?? ctx.rawFetchNext;\n if (fetchNextConfig === undefined) return undefined;\n\n const resolveRoot: Record<string, unknown> = {\n params: ctx.params ?? {},\n result: ctx.resultData,\n };\n\n return {\n url: fetchNextConfig.url !== undefined ? (reifyValue(fetchNextConfig.url, resolveRoot) as string) : undefined,\n searchParams:\n fetchNextConfig.searchParams !== undefined\n ? (reifyValue(fetchNextConfig.searchParams, resolveRoot) as Record<string, unknown>)\n : undefined,\n };\n }\n\n /**\n * Resolves a path to a full URL.\n *\n * - Absolute URLs (`https://...`, `//...`) are returned as-is.\n * - Root-relative paths (`/foo`) are prepended with the resolved baseUrl.\n * The baseUrl priority is: per-query/mutation > controller-level > `location.origin`.\n * If none is available and the path is root-relative, an error is thrown.\n * - Other paths (e.g. `example.com/foo`) are returned as-is.\n */\n private buildUrl(path: string, ctxBaseUrl: BaseUrlValue | undefined): string {\n // Absolute URL — use as-is regardless of any configured baseUrl\n if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('//')) {\n return path;\n }\n\n // Root-relative path — needs a base\n if (path.startsWith('/')) {\n const base = resolveBaseUrl(ctxBaseUrl) ?? resolveBaseUrl(this._baseUrl) ?? globalThis.location?.origin;\n\n if (!base) {\n throw new Error(\n `RESTQueryController: cannot resolve URL for path \"${path}\". ` +\n `Set \\`baseUrl\\` on the query/mutation, pass it to \\`new RESTQueryController({ baseUrl })\\`, ` +\n `or use an absolute URL.`,\n );\n }\n\n return `${base}${path}`;\n }\n\n // Relative path — use as-is\n return path;\n }\n\n private async executeRequest(\n ctx: RESTQuery,\n signal: AbortSignal,\n next?: { url?: string; searchParams?: Record<string, unknown> },\n ): Promise<unknown> {\n const path = next?.url ?? (ctx.getPath ? ctx.getPath() : ctx.path);\n const method = ctx.getMethod ? ctx.getMethod() : ctx.method;\n const baseSearchParams = ctx.getSearchParams ? ctx.getSearchParams() : ctx.searchParams;\n const searchParams = next?.searchParams ? { ...baseSearchParams, ...next.searchParams } : baseSearchParams;\n const body = ctx.getBody ? ctx.getBody() : ctx.body;\n const requestOptions = ctx.getRequestOptions ? ctx.getRequestOptions() : ctx.requestOptions;\n\n if (!path) {\n throw new Error('RESTQuery requires a path. Define `path` as a field or override `getPath()`.');\n }\n\n let url = path;\n\n if (searchParams) {\n const sp = new URLSearchParams();\n for (const key in searchParams) {\n const val = searchParams[key];\n if (val !== undefined && val !== null) {\n sp.append(key, String(val));\n }\n }\n const qs = sp.toString();\n if (qs) {\n url += '?' + qs;\n }\n }\n\n const ctxBaseUrl = requestOptions?.baseUrl ?? ctx.baseUrl;\n const fullUrl = this.buildUrl(url, ctxBaseUrl);\n\n const { baseUrl: _baseUrl, signal: _signal, ...fetchOptions } = requestOptions ?? ({} as Record<string, unknown>);\n\n const hasHeaders = body || ctx.headers;\n const headers: HeadersInit | undefined = hasHeaders\n ? {\n ...(body ? { 'Content-Type': 'application/json' } : undefined),\n ...(ctx.headers as Record<string, string>),\n }\n : undefined;\n\n const fetchResponse = await this._fetch(fullUrl, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal,\n ...fetchOptions,\n });\n\n ctx.response = fetchResponse as unknown as Response;\n\n return fetchResponse.json();\n }\n\n override async sendMutation(ctx: Mutation, signal: AbortSignal): Promise<unknown> {\n const restCtx = ctx as RESTMutation;\n const path = restCtx.getPath ? restCtx.getPath() : restCtx.path;\n const method = restCtx.getMethod ? restCtx.getMethod() : restCtx.method;\n const body = restCtx.getBody ? restCtx.getBody() : restCtx.body;\n const requestOptions = restCtx.getRequestOptions ? restCtx.getRequestOptions() : restCtx.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 ctxBaseUrl = (requestOptions as QueryRequestOptions | undefined)?.baseUrl ?? restCtx.baseUrl;\n const fullUrl = this.buildUrl(path, ctxBaseUrl);\n\n const { baseUrl: _baseUrl, signal: _signal, ...fetchOptions } = (requestOptions ?? {}) as Record<string, unknown>;\n\n const headers: HeadersInit = {\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...(restCtx.headers as Record<string, string>),\n };\n\n const fetchResponse = await this._fetch(fullUrl, {\n method,\n headers,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n signal,\n ...fetchOptions,\n });\n\n return fetchResponse.json();\n }\n}\n","import { Query } from '../query.js';\nimport { RESTQueryController } from './RESTQueryController.js';\nimport type { FetchNextConfig } from '../query-types.js';\nimport type { BaseUrlValue, QueryRequestOptions } from '../types.js';\n\n// ================================\n// RESTQuery — declarative HTTP query definition\n// ================================\n\nexport abstract class RESTQuery extends Query {\n static override controller = RESTQueryController;\n\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' = 'GET';\n path?: string;\n baseUrl?: BaseUrlValue;\n searchParams?: Record<string, unknown>;\n body?: Record<string, unknown>;\n headers?: HeadersInit;\n requestOptions?: QueryRequestOptions;\n fetchNext?: FetchNextConfig;\n\n declare response: Response | undefined;\n\n getIdentityKey(): string {\n return `${this.method ?? 'GET'}:${this.path ?? ''}`;\n }\n\n // User-overridable getters — the controller reads these from the execution context\n getPath?(): string | undefined;\n getMethod?(): string;\n getSearchParams?(): Record<string, unknown> | undefined;\n getBody?(): Record<string, unknown> | undefined;\n getRequestOptions?(): QueryRequestOptions | undefined;\n getFetchNext?(): FetchNextConfig | undefined;\n}\n","import { Mutation } from '../mutation.js';\nimport type { BaseUrlValue, QueryRequestOptions } from '../types.js';\nimport { RESTQueryController } from './RESTQueryController.js';\n\nexport abstract class RESTMutation extends Mutation {\n static override controller = RESTQueryController;\n\n path?: string;\n baseUrl?: BaseUrlValue;\n method: 'POST' | 'PUT' | 'DELETE' | 'PATCH' = 'POST';\n body?: Record<string, unknown>;\n headers?: HeadersInit;\n requestOptions?: QueryRequestOptions;\n\n getIdentityKey(): 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"],"names":["RESTQueryController","QueryController","options","ctx","signal","resolved","keys","key","fetchNextConfig","resolveRoot","reifyValue","path","ctxBaseUrl","base","resolveBaseUrl","next","method","baseSearchParams","searchParams","body","requestOptions","url","sp","val","qs","fullUrl","_baseUrl","_signal","fetchOptions","headers","fetchResponse","restCtx","RESTQuery","Query","RESTMutation","Mutation"],"mappings":"+MAgCO,MAAMA,UAA4BC,EAAAA,eAAgB,CACtC,OACA,SAEjB,YAAYC,EAAsC,CAChD,MAAA,EACA,KAAK,OACHA,GAAS,OAAU,WAAW,MAChC,KAAK,SAAWA,GAAS,OAC3B,CAEA,MAAe,KAAKC,EAAYC,EAAuC,CACrE,OAAO,KAAK,eAAeD,EAAkBC,CAAM,CACrD,CAEA,MAAe,SAASD,EAAYC,EAAuC,CACzE,MAAMC,EAAW,KAAK,iBAAiBF,CAAgB,EACvD,GAAIE,IAAa,OACf,MAAM,IAAI,MAAM,4CAA4C,EAE9D,OAAO,KAAK,eAAeF,EAAkBC,EAAQC,CAAQ,CAC/D,CAES,QAAQF,EAAqB,CACpC,MAAME,EAAW,KAAK,iBAAiBF,CAAgB,EACvD,GAAIE,IAAa,OAAW,MAAO,GAEnC,GAAIA,EAAS,MAAQ,QAAaA,EAAS,MAAQ,KACjD,MAAO,GAGT,GAAIA,EAAS,eAAiB,OAAW,CACvC,MAAMC,EAAO,OAAO,KAAKD,EAAS,YAAY,EAC9C,GAAIC,EAAK,SAAW,EAAG,MAAO,GAC9B,UAAWC,KAAOD,EAChB,GAAID,EAAS,aAAaE,CAAG,IAAM,QAAaF,EAAS,aAAaE,CAAG,IAAM,KAC7E,MAAO,GAGX,MAAO,EACT,CAEA,MAAO,EACT,CAEQ,iBAAiBJ,EAA+C,CAEtE,MAAMK,GADgBL,EAAI,aAAeA,EAAI,eAAiB,SACQA,EAAI,aAC1E,GAAIK,IAAoB,OAAW,OAEnC,MAAMC,EAAuC,CAC3C,OAAQN,EAAI,QAAU,CAAA,EACtB,OAAQA,EAAI,UAAA,EAGd,MAAO,CACL,IAAKK,EAAgB,MAAQ,OAAaE,EAAAA,WAAWF,EAAgB,IAAKC,CAAW,EAAe,OACpG,aACED,EAAgB,eAAiB,OAC5BE,EAAAA,WAAWF,EAAgB,aAAcC,CAAW,EACrD,MAAA,CAEV,CAWQ,SAASE,EAAcC,EAA8C,CAE3E,GAAID,EAAK,WAAW,SAAS,GAAKA,EAAK,WAAW,UAAU,GAAKA,EAAK,WAAW,IAAI,EACnF,OAAOA,EAIT,GAAIA,EAAK,WAAW,GAAG,EAAG,CACxB,MAAME,EAAOC,iBAAeF,CAAU,GAAKE,EAAAA,eAAe,KAAK,QAAQ,GAAK,WAAW,UAAU,OAEjG,GAAI,CAACD,EACH,MAAM,IAAI,MACR,qDAAqDF,CAAI,wHAAA,EAM7D,MAAO,GAAGE,CAAI,GAAGF,CAAI,EACvB,CAGA,OAAOA,CACT,CAEA,MAAc,eACZR,EACAC,EACAW,EACkB,CAClB,MAAMJ,EAAOI,GAAM,MAAQZ,EAAI,QAAUA,EAAI,QAAA,EAAYA,EAAI,MACvDa,EAASb,EAAI,UAAYA,EAAI,UAAA,EAAcA,EAAI,OAC/Cc,EAAmBd,EAAI,gBAAkBA,EAAI,gBAAA,EAAoBA,EAAI,aACrEe,EAAeH,GAAM,aAAe,CAAE,GAAGE,EAAkB,GAAGF,EAAK,YAAA,EAAiBE,EACpFE,EAAOhB,EAAI,QAAUA,EAAI,QAAA,EAAYA,EAAI,KACzCiB,EAAiBjB,EAAI,kBAAoBA,EAAI,kBAAA,EAAsBA,EAAI,eAE7E,GAAI,CAACQ,EACH,MAAM,IAAI,MAAM,8EAA8E,EAGhG,IAAIU,EAAMV,EAEV,GAAIO,EAAc,CAChB,MAAMI,EAAK,IAAI,gBACf,UAAWf,KAAOW,EAAc,CAC9B,MAAMK,EAAML,EAAaX,CAAG,EACHgB,GAAQ,MAC/BD,EAAG,OAAOf,EAAK,OAAOgB,CAAG,CAAC,CAE9B,CACA,MAAMC,EAAKF,EAAG,SAAA,EACVE,IACFH,GAAO,IAAMG,EAEjB,CAEA,MAAMZ,EAAaQ,GAAgB,SAAWjB,EAAI,QAC5CsB,EAAU,KAAK,SAASJ,EAAKT,CAAU,EAEvC,CAAE,QAASc,EAAU,OAAQC,EAAS,GAAGC,CAAA,EAAiBR,GAAmB,CAAA,EAG7ES,EADaV,GAAQhB,EAAI,QAE3B,CACE,GAAIgB,EAAO,CAAE,eAAgB,oBAAuB,OACpD,GAAIhB,EAAI,OAAA,EAEV,OAEE2B,EAAgB,MAAM,KAAK,OAAOL,EAAS,CAC/C,OAAAT,EACA,QAAAa,EACA,KAAMV,EAAO,KAAK,UAAUA,CAAI,EAAI,OACpC,OAAAf,EACA,GAAGwB,CAAA,CACJ,EAED,OAAAzB,EAAI,SAAW2B,EAERA,EAAc,KAAA,CACvB,CAEA,MAAe,aAAa3B,EAAeC,EAAuC,CAChF,MAAM2B,EAAU5B,EACVQ,EAAOoB,EAAQ,QAAUA,EAAQ,QAAA,EAAYA,EAAQ,KACrDf,EAASe,EAAQ,UAAYA,EAAQ,UAAA,EAAcA,EAAQ,OAC3DZ,EAAOY,EAAQ,QAAUA,EAAQ,QAAA,EAAYA,EAAQ,KACrDX,EAAiBW,EAAQ,kBAAoBA,EAAQ,kBAAA,EAAsBA,EAAQ,eAEzF,GAAI,CAACpB,EACH,MAAM,IAAI,MAAM,iFAAiF,EAGnG,MAAMC,EAAcQ,GAAoD,SAAWW,EAAQ,QACrFN,EAAU,KAAK,SAASd,EAAMC,CAAU,EAExC,CAAE,QAASc,EAAU,OAAQC,EAAS,GAAGC,CAAA,EAAkBR,GAAkB,CAAA,EAE7ES,EAAuB,CAC3B,GAAIV,IAAS,OAAY,CAAE,eAAgB,kBAAA,EAAuB,CAAA,EAClE,GAAIY,EAAQ,OAAA,EAWd,OARsB,MAAM,KAAK,OAAON,EAAS,CAC/C,OAAAT,EACA,QAAAa,EACA,GAAIV,IAAS,OAAY,CAAE,KAAM,KAAK,UAAUA,CAAI,CAAA,EAAM,CAAA,EAC1D,OAAAf,EACA,GAAGwB,CAAA,CACJ,GAEoB,KAAA,CACvB,CACF,CClNO,MAAeI,UAAkBC,EAAAA,KAAM,CAC5C,OAAgB,WAAajC,EAE7B,OAAsD,MACtD,KACA,QACA,aACA,KACA,QACA,eACA,UAIA,gBAAyB,CACvB,MAAO,GAAG,KAAK,QAAU,KAAK,IAAI,KAAK,MAAQ,EAAE,EACnD,CASF,CC9BO,MAAekC,UAAqBC,EAAAA,QAAS,CAClD,OAAgB,WAAanC,EAE7B,KACA,QACA,OAA8C,OAC9C,KACA,QACA,eAEA,gBAAyB,CACvB,MAAO,GAAG,KAAK,QAAU,MAAM,IAAI,KAAK,MAAQ,EAAE,EACpD,CAMF"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../QueryClient-CLi3ONNM.js"),d=require("../QueryController-BQA49OYU.js");class h extends a.Query{static controller;getIdentityKey(){return`topic:${this.topic}`}getConfig(){return{staleTime:0,subscribe:()=>()=>{this._topicController?.unsubscribe(this.topic)}}}}class f extends d.QueryController{_topics=new Map;fulfillTopic(e,s){const t=this._topics.get(e);if(t===void 0){this._topics.set(e,{status:"fulfilled",data:s});return}t.status==="pending"&&(t.status="fulfilled",t.data=s,t.resolve(s))}rejectTopic(e,s){const t=this._topics.get(e);if(t===void 0){this._topics.set(e,{status:"rejected",error:s});return}t.status==="pending"&&(t.status="rejected",t.error=s,t.reject(s))}clearTopic(e){this._topics.delete(e)}clearAll(){this._topics.clear()}async send(e,s){const t=e;t._topicController=this;const r=t.topic,i=this._topics.get(r);if(i)switch(i.status){case"fulfilled":return i.data;case"rejected":throw i.error;case"pending":return i.promise}let o,c;const n=new Promise((u,p)=>{o=u,c=p});return this._topics.set(r,{status:"pending",promise:n,resolve:o,reject:c}),this.subscribe(r),n}sendMutationEvent(e){this.queryClient.applyMutationEvent(e)}}exports.TopicQuery=h;exports.TopicQueryController=f;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/topic/TopicQuery.ts","../../../../src/topic/TopicQueryController.ts"],"sourcesContent":["import { Query } from '../query.js';\nimport type { TopicQueryController } from './TopicQueryController.js';\nimport type { QueryConfigOptions } from '../query-types.js';\n\n// ================================\n// TopicQuery — declarative topic-based query definition\n// ================================\n\nexport abstract class TopicQuery extends Query {\n static override controller: typeof TopicQueryController;\n\n abstract topic: string;\n\n getIdentityKey(): string {\n return `topic:${this.topic}`;\n }\n\n getConfig(): QueryConfigOptions {\n return {\n staleTime: 0,\n subscribe: () => {\n return () => {\n const controller = (this as Record<string, any>)._topicController as TopicQueryController | undefined;\n controller?.unsubscribe(this.topic);\n };\n },\n };\n }\n}\n","import { QueryController } from '../QueryController.js';\nimport type { Query } from '../query.js';\nimport type { MutationEvent } from '../types.js';\n\n// ================================\n// TopicQueryController — abstract controller for topic-based subscriptions\n// ================================\n\ninterface TopicCtx extends Query {\n topic: string;\n _topicController?: TopicQueryController;\n}\n\ninterface TopicState {\n status: 'pending' | 'fulfilled' | 'rejected';\n promise?: Promise<unknown>;\n resolve?: (data: unknown) => void;\n reject?: (error: unknown) => void;\n data?: unknown;\n error?: unknown;\n}\n\nexport abstract class TopicQueryController extends QueryController {\n private _topics = new Map<string, TopicState>();\n\n /**\n * Called when a query activates for a given topic.\n * Implementations should start delivering data for this topic,\n * calling `fulfillTopic()` when initial data is available and\n * `sendMutationEvent()` for ongoing updates.\n */\n abstract subscribe(topic: string): void;\n\n /**\n * Called when the query deactivates. Implementations should\n * tear down any resources for this topic.\n */\n abstract unsubscribe(topic: string): void;\n\n /**\n * Resolve the pending promise for a topic with initial data.\n * Can be called before `send()` — the data will be picked up\n * when the query activates.\n */\n protected fulfillTopic(topic: string, data: unknown): void {\n const state = this._topics.get(topic);\n\n if (state === undefined) {\n this._topics.set(topic, { status: 'fulfilled', data });\n return;\n }\n\n if (state.status === 'pending') {\n state.status = 'fulfilled';\n state.data = data;\n state.resolve!(data);\n }\n }\n\n /**\n * Reject the pending promise for a topic.\n * Can be called before `send()` — the error will be propagated\n * when the query activates.\n */\n protected rejectTopic(topic: string, error: unknown): void {\n const state = this._topics.get(topic);\n\n if (state === undefined) {\n this._topics.set(topic, { status: 'rejected', error });\n return;\n }\n\n if (state.status === 'pending') {\n state.status = 'rejected';\n state.error = error;\n state.reject!(error);\n }\n }\n\n /**\n * Clears internal state for a topic. Called automatically by\n * `unsubscribe` — subclasses generally don't need to call this.\n */\n protected clearTopic(topic: string): void {\n this._topics.delete(topic);\n }\n\n protected clearAll(): void {\n this._topics.clear();\n }\n\n override async send(ctx: Query, _signal: AbortSignal): Promise<unknown> {\n const topicCtx = ctx as TopicCtx;\n topicCtx._topicController = this;\n const topic = topicCtx.topic;\n\n const existing = this._topics.get(topic);\n\n if (existing) {\n switch (existing.status) {\n case 'fulfilled':\n return existing.data;\n case 'rejected':\n throw existing.error;\n case 'pending':\n return existing.promise;\n }\n }\n\n // No state yet — create a deferred and subscribe\n let resolve!: (data: unknown) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<unknown>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n this._topics.set(topic, { status: 'pending', promise, resolve, reject });\n this.subscribe(topic);\n\n return promise;\n }\n\n /**\n * Convenience wrapper — pushes a mutation event through the QueryClient\n * so that entities and live collections are updated reactively.\n */\n protected sendMutationEvent(event: MutationEvent): void {\n this.queryClient!.applyMutationEvent(event);\n }\n}\n"],"names":["TopicQuery","Query","TopicQueryController","QueryController","topic","data","state","error","ctx","_signal","topicCtx","existing","resolve","reject","promise","res","rej","event"],"mappings":"0KAQO,MAAeA,UAAmBC,EAAAA,KAAM,CAC7C,OAAgB,WAIhB,gBAAyB,CACvB,MAAO,SAAS,KAAK,KAAK,EAC5B,CAEA,WAAgC,CAC9B,MAAO,CACL,UAAW,EACX,UAAW,IACF,IAAM,CACS,KAA6B,kBACrC,YAAY,KAAK,KAAK,CACpC,CACF,CAEJ,CACF,CCNO,MAAeC,UAA6BC,EAAAA,eAAgB,CACzD,YAAc,IAqBZ,aAAaC,EAAeC,EAAqB,CACzD,MAAMC,EAAQ,KAAK,QAAQ,IAAIF,CAAK,EAEpC,GAAIE,IAAU,OAAW,CACvB,KAAK,QAAQ,IAAIF,EAAO,CAAE,OAAQ,YAAa,KAAAC,EAAM,EACrD,MACF,CAEIC,EAAM,SAAW,YACnBA,EAAM,OAAS,YACfA,EAAM,KAAOD,EACbC,EAAM,QAASD,CAAI,EAEvB,CAOU,YAAYD,EAAeG,EAAsB,CACzD,MAAMD,EAAQ,KAAK,QAAQ,IAAIF,CAAK,EAEpC,GAAIE,IAAU,OAAW,CACvB,KAAK,QAAQ,IAAIF,EAAO,CAAE,OAAQ,WAAY,MAAAG,EAAO,EACrD,MACF,CAEID,EAAM,SAAW,YACnBA,EAAM,OAAS,WACfA,EAAM,MAAQC,EACdD,EAAM,OAAQC,CAAK,EAEvB,CAMU,WAAWH,EAAqB,CACxC,KAAK,QAAQ,OAAOA,CAAK,CAC3B,CAEU,UAAiB,CACzB,KAAK,QAAQ,MAAA,CACf,CAEA,MAAe,KAAKI,EAAYC,EAAwC,CACtE,MAAMC,EAAWF,EACjBE,EAAS,iBAAmB,KAC5B,MAAMN,EAAQM,EAAS,MAEjBC,EAAW,KAAK,QAAQ,IAAIP,CAAK,EAEvC,GAAIO,EACF,OAAQA,EAAS,OAAA,CACf,IAAK,YACH,OAAOA,EAAS,KAClB,IAAK,WACH,MAAMA,EAAS,MACjB,IAAK,UACH,OAAOA,EAAS,OAAA,CAKtB,IAAIC,EACAC,EACJ,MAAMC,EAAU,IAAI,QAAiB,CAACC,EAAKC,IAAQ,CACjDJ,EAAUG,EACVF,EAASG,CACX,CAAC,EAED,YAAK,QAAQ,IAAIZ,EAAO,CAAE,OAAQ,UAAW,QAAAU,EAAS,QAAAF,EAAS,OAAAC,EAAQ,EACvE,KAAK,UAAUT,CAAK,EAEbU,CACT,CAMU,kBAAkBG,EAA4B,CACtD,KAAK,YAAa,mBAAmBA,CAAK,CAC5C,CACF"}
@@ -0,0 +1,2 @@
1
+ "use strict";const b=require("signalium"),D=require("signalium/utils"),Lt=require("./shared-Ct5zKrt4.js"),Rt=require("./stores/sync.js");var P=(n=>(n.Always="always",n.Online="online",n.OfflineFirst="offlineFirst",n))(P||{}),l=(n=>(n[n.UNDEFINED=1]="UNDEFINED",n[n.NULL=2]="NULL",n[n.NUMBER=4]="NUMBER",n[n.STRING=8]="STRING",n[n.BOOLEAN=16]="BOOLEAN",n[n.OBJECT=32]="OBJECT",n[n.ARRAY=64]="ARRAY",n[n.ID=128]="ID",n[n.RECORD=256]="RECORD",n[n.UNION=512]="UNION",n[n.ENTITY=1024]="ENTITY",n[n.HAS_FORMAT=4096]="HAS_FORMAT",n[n.IS_EAGER_FORMAT=8192]="IS_EAGER_FORMAT",n[n.PARSE_RESULT=16384]="PARSE_RESULT",n[n.LIVE=32768]="LIVE",n))(l||{});const U=Symbol("array"),V=Symbol("record"),ft=Symbol("QUERY_ID");var H=(n=>(n[n.Array=0]="Array",n[n.Value=1]="Value",n))(H||{});class L{type;entityDefs;constraintFieldRefs;sort;valueType;onCreate;onUpdate;onDelete;constructor(t,e,i,r,s,o,a,c){this.type=t,this.entityDefs=e,this.constraintFieldRefs=i,this.sort=r,this.valueType=s,this.onCreate=o,this.onUpdate=a,this.onDelete=c}static array(t,e,i){return new L(0,t,e,i,void 0,void 0,void 0,void 0)}static value(t,e,i,r,s,o){return new L(1,t,e,void 0,i,r,s,o)}}const O=new WeakMap;function F(n){return O.get(n)}var J=(n=>(n[n.Query=0]="Query",n[n.Entity=1]="Entity",n))(J||{});class _e{constructor(t,e,i){this._onEvict=e,this._intervalId=setInterval(this._tick,t*6e4*i)}_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:i}=this;for(const[r,s]of t)i(r,s);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,i){if(e===1/0)return;if(e===0){const{_nextTickEntries:o}=this;o.set(t,i),this._nextTickScheduled||(this._nextTickScheduled=!0,setTimeout(this._flushNextTick,0));return}const{_buckets:r}=this;let s=r.get(e);s||(s=new _e(e,this._onEvict,this._multiplier),r.set(e,s)),s.schedule(t,i)}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[i,r]of t)e(i,r);t.clear()};destroy(){const{_buckets:t,_nextTickEntries:e}=this;for(const i of t.values())i.destroy();t.clear(),e.clear()}}class jt{schedule(t,e,i){}cancel(t,e){}destroy(){}}const W=Symbol("fieldRef"),M=Symbol("fieldRefPath"),ut=Symbol("DEFINITION_TARGET"),z=Symbol("CANCEL_PROXY"),me=/\[([^\]]+)\]/g;function Ut(n){const t={[W]:!0,[M]:n};return new Proxy(t,we)}const we={get(n,t){if(t===W)return!0;if(t===M)return n[M];if(t===Symbol.toPrimitive||t==="toString"||t==="valueOf"){const i=n[M];return()=>`[${i.join(".")}]`}if(typeof t=="symbol")return;const e=n[M];return Ut([...e,t])},has(n,t){return t===W||t===M}};function Vt(n){return typeof n=="object"&&n!==null&&n[W]===!0}function Kt(n){return n[M]}function lt(n){return new Proxy(n,{set(t,e,i){return t[e]=i,!0},get(t,e){return e===ut?t:e===z?()=>{}:typeof e=="symbol"?t[e]:Ut([e])}})}function $t(n){const t=n[ut];n[z]();const e={};for(const s of Object.getOwnPropertyNames(t))e[s]=t[s];const i={};let r=Object.getPrototypeOf(t);for(;r&&r!==Object.prototype;){for(const s of Object.getOwnPropertyNames(r)){if(s==="constructor")continue;const o=Object.getOwnPropertyDescriptor(r,s);typeof o.value=="function"&&!(s in i)&&(i[s]=o.value)}r=Object.getPrototypeOf(r)}return{fields:e,methods:i}}function dt(n,t){let e=t;for(const i of n){if(e==null)return;e=e[i]}return e}function Ee(n,t){return n.replace(me,(e,i)=>{const r=i.split("."),s=dt(r,t);return s!=null?encodeURIComponent(String(s)):""})}function K(n,t){if(Vt(n))return dt(Kt(n),t);if(typeof n=="string")return Ee(n,t);if(Array.isArray(n))return n.map(e=>K(e,t));if(typeof n=="object"&&n!==null&&Object.getPrototypeOf(n)===Object.prototype){const e={};for(const i of Object.keys(n))e[i]=K(n[i],t);return e}return n}function it(n,t,e){const i=n.fields,r=n.methods,s={params:t},o={};for(const[a,c]of Object.entries(i))o[a]=K(c,s);o.params=t,o.context=e;for(const[a,c]of Object.entries(r))o[a]=c.bind(o);return o}class ht{static cache;constructor(){return lt(this)}}const Qt=Object.entries,rt=Object.keys;function St(n){return typeof n=="number"?n|l.UNDEFINED:n instanceof _?(n.mask&l.UNDEFINED)!==0?n:_.cloneWith(n,l.UNDEFINED):n}function Ce(n){return n instanceof _&&(n.mask&l.OBJECT)!==0&&(n.mask&(l.ENTITY|l.ARRAY|l.UNION|l.RECORD|l.LIVE))===0}function Bt(n,t,e){const i=new Set;for(const s of n)if(s!==void 0)for(const o of Object.keys(s))i.add(o);const r={};for(const s of i){let o=0,a;const c=[];let f=!0;for(const d of n){const u=d?.[s];u!==void 0?(o++,a===void 0&&(a=u),Ce(u)?c.push(u.shape):(f=!1,c.push(void 0))):(f=!1,c.push(void 0))}if(f&&o>0){const d=Bt(c,t),u=new _(l.OBJECT,d);r[s]=o<t?St(u):u}else r[s]=o<t?St(a):a}return r}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,i,r,s,o){this.mask=t,this.shape=e,this.values=i,this.typenameField=r,this.typenameValue=s,this.idField=o}static merge(t){if(t.length===1)return t[0];const e=t.length,i=t.map(c=>c.shape);t[0].typenameValue;const r=Bt(i,e);let s,o,a;for(const c of t){if(s===void 0&&c.idField!==void 0)s=c.idField;else if(s!==void 0&&c.idField!==void 0&&c.idField!==s)throw new Error(`[fetchium] Entity typename '${c.typenameValue}' has conflicting id fields: '${String(s)}' vs '${String(c.idField)}'`);o===void 0&&(o=c.typenameField),a===void 0&&(a=c.typenameValue)}return new _(l.ENTITY|l.OBJECT,r,void 0,o,a,s)}static cloneWith(t,e){const i=new _(e|t.mask,t.shape,t.values,t.typenameField,t.typenameValue,t.idField);return i._methods=t._methods,i._entityConfig=t._entityConfig,i._entityClass=t._entityClass,i._entityCache=t._entityCache,i._liveConfig=t._liveConfig,i}}class X extends Set{lowercaseMap;constructor(t){super(t),this.lowercaseMap=new Map;for(const e of t)if(typeof e=="string"){const i=e.toLowerCase(),r=this.lowercaseMap.get(i);if(r!==void 0)throw new Error(`Case-insensitive enum cannot have multiple values with the same lowercase form: '${r}' and '${e}' both become '${i}'`);this.lowercaseMap.set(i,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 be=1128875347;D.registerCustomHash(X,n=>{let t=be;for(const e of n)t+=D.hashValue(e);return t>>>0});function yt(n,t){return new _(n,t)}function xe(n){return yt(l.ARRAY,n)}function Oe(n){return yt(l.RECORD|l.OBJECT,n)}function Re(n){return yt(l.PARSE_RESULT,n)}function Yt(n,t){let e=n,i,r,s;for(const[o,a]of Qt(t))switch(typeof a){case"number":if((a&l.ID)!==0){if(i!==void 0)throw new Error(`Duplicate id field: ${o}`);i=o}break;case"string":if(r!==void 0&&r!==o)throw new Error(`Duplicate typename field: ${o}`);r=o,s=a;break;case"object":if(a instanceof X||a instanceof Set)break;a.mask&l.LIVE&&(e|=l.LIVE);break}return new _(e,t,void 0,r,s,i)}function Se(n){return Yt(l.OBJECT,n)}function Dt(n,t,e){const i=n.mask;if((i&l.UNION)!==0){const r=n;if(r.typenameField!==void 0){if(e!==void 0&&e!==r.typenameField)throw new Error(`Union typename field conflict: Cannot merge unions with different typename fields ('${e}' vs '${r.typenameField}')`);e=r.typenameField}const s=r.shape;if(s!==void 0)for(const o of[...rt(s),U,V]){const a=s[o];if(t[o]!==void 0&&t[o]!==a)throw new Error(`Union merge conflict: Duplicate typename value '${String(o)}' found when merging nested unions (${String(t[o])} vs ${String(a)})`);t[o]=a}}else if((i&l.ARRAY)!==0){if(t[U]!==void 0)throw new Error("Array shape already defined");t[U]=n.shape}else if((i&l.RECORD)!==0){if(t[V]!==void 0)throw new Error("Record shape already defined");t[V]=n.shape}else{const r=n.typenameField,s=n.typenameValue;if(s===void 0)throw new Error("Object definitions must have a typename to be in a union with other objects, records, or arrays");if(e!==void 0&&r!==e)throw new Error("Object definitions must have the same typename field to be in the same union");e=r,t[s]=n}return e}function gt(...n){const t=n;let e=0,i=0,r,s,o,a,c=0;for(const d of t){if(typeof d=="number"){e|=d;continue}if(d instanceof Set){if(s===void 0)s=new Set(d);else for(const u of d)s.add(u);continue}if(i++,c|=d.mask,i===1){r=d;continue}i===2&&(o=Object.create(null),a=Dt(r,o,a)),a=Dt(d,o,a)}if(i===0)return s===void 0?e:e===0?s:new _(e|l.UNION,void 0,s);if(i===1)return _.cloneWith(r,e);const f=e|c|l.UNION;return new _(f,o,s,a)}function pt(n,t,e){const i=n;if(typeof i=="number")return i|t;if(i instanceof Set)return gt(n,t);let r=e.get(i);return r===void 0&&(r=_.cloneWith(i,t),e.set(i,r)),r}const De=new WeakMap,Ae=new WeakMap,Ne=new WeakMap;function Ie(n){return pt(n,l.UNDEFINED|l.NULL,Ne)}function Me(n){return pt(n,l.UNDEFINED,De)}function ke(n){return pt(n,l.NULL,Ae)}function Fe(n){return n}function Te(n){return new Set([n])}const Gt=((...n)=>new Set(n));Gt.caseInsensitive=(...n)=>new X(n);const Wt=16;let Pe=0;const st=[],zt=[],Ht=new Map,Z=new WeakSet;class ${_raw;_formatted;_parsed;_formatId;constructor(t,e,i){this._raw=t,this._formatId=e,i?(this._formatted=st[e](t),this._parsed=!0):this._parsed=!1,Z.add(this)}getValue(){return this._parsed||(this._formatted=st[this._formatId](this._raw),this._parsed=!0),this._formatted}toJSON(){return this._parsed?zt[this._formatId](this._formatted):this._raw}}function Le(n){const t=Ht.get(n);if(t===void 0)throw new Error(`Format ${n} not registered`);return t}function vt(n,t,e,i,r){const s=Pe++;st[s]=e,zt[s]=i;const o=r?.eager??!0,c=s<<Wt|t|l.HAS_FORMAT|(o?l.IS_EAGER_FORMAT:0);Ht.set(n,c)}vt("date",l.STRING,n=>{const t=n.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)throw new Error(`Invalid date string: ${n}. Expected YYYY-MM-DD format.`);const[,e,i,r]=t,s=new Date(Date.UTC(parseInt(e,10),parseInt(i,10)-1,parseInt(r,10)));if(isNaN(s.getTime()))throw new Error(`Invalid date string: ${n}`);return s},n=>{const t=n.getUTCFullYear(),e=String(n.getUTCMonth()+1).padStart(2,"0"),i=String(n.getUTCDate()).padStart(2,"0");return`${t}-${e}-${i}`});vt("date-time",l.STRING,n=>{const t=new Date(n);if(isNaN(t.getTime()))throw new Error(`Invalid date-time string: ${n}`);return t},n=>n.toISOString());const At=new WeakMap;function q(n){let t=At.get(n);if(t===void 0){const e=new n,i=e[ut]??e;e[z]&&e[z]();const r={};for(const[f,d]of Qt(i))r[f]=d;const s=Object.getPrototypeOf(n.prototype);if(s!=null){const f=s.constructor;if(f!==ht&&typeof f=="function"){const u=q(f).shape;for(const y of rt(u))if(y in r&&r[y]!==u[y])throw new Error(`Cannot extend: field '${y}' already exists in type definition`)}}const o={},a=n.prototype;for(const f of Object.getOwnPropertyNames(a))f!=="constructor"&&typeof a[f]=="function"&&(o[f]=a[f]);t=Yt(l.ENTITY|l.OBJECT,r),t._entityClass=n,rt(o).length>0&&(t._methods=o),typeof o.__subscribe=="function"&&(t._entityConfig={hasSubscribe:!0});const c=n;c.cache&&(t._entityCache=c.cache),At.set(n,t)}return t}function qe(n){return q(n)}function Jt(n,t){if(t==null)return;const e=new Map;if(Array.isArray(t))for(const i of t){const[r,s]=i,a=q(r).typenameValue;if(a===void 0)continue;const c=[];for(const[f,d]of Object.entries(s))c.push([f,d]);c.length>0&&e.set(a,c)}else{const r=Object.entries(t);if(r.length===0)return;const s=r.map(([o,a])=>[o,a]);for(const o of n){const a=o.typenameValue;a!==void 0&&e.set(a,s)}}return e.size>0?e:void 0}function Xt(n){return Array.isArray(n)?n.map(t=>q(t)):[q(n)]}function je(n,t){const e=Xt(n),i=e.length===1?e[0]:gt(...e.map(o=>o)),r=l.ARRAY|l.LIVE,s=new _(r,i);return s._liveConfig=L.array(e,Jt(e,t?.constraints),t?.sort),s}function Ue(n,t,e){const i=Xt(t),r=n,s=l.LIVE,o=new _(s,void 0);return o._liveConfig=L.value(i,Jt(i,e?.constraints),r,e.onCreate,e.onUpdate,e.onDelete),o}const Zt={format:Le,typename:Fe,const:Te,enum:Gt,id:l.ID|l.STRING|l.NUMBER,string:l.STRING,number:l.NUMBER,boolean:l.BOOLEAN,null:l.NULL,undefined:l.UNDEFINED,array:xe,object:Se,record:Oe,union:gt,nullish:Ie,optional:Me,nullable:ke,result:Re,entity:qe,liveArray:je,liveValue:Ue};function j(n,t,e){return new TypeError(`Validation error at ${n}`)}const te=Array.isArray;function Nt(n){if(n===null)return l.NULL;switch(typeof n){case"number":return l.NUMBER;case"string":return l.STRING;case"boolean":return l.BOOLEAN;case"undefined":return l.UNDEFINED;case"object":return te(n)?l.ARRAY:l.OBJECT;default:throw new Error(`Invalid type: ${typeof n}`)}}function Ve(n){return T(n)}function T(n){if(n===null||typeof n!="object")return n;if(te(n))return n.map(e=>T(e));if(n instanceof Date)return new Date(n.getTime());if(n instanceof Map){const e=new Map;for(const[i,r]of n)e.set(T(i),T(r));return e}if(n instanceof Set){const e=new Set;for(const i of n)e.add(T(i));return e}const t={};for(const e of Object.keys(n))t[e]=T(n[e]);return t}const _t=Object.entries,Ke=()=>{};class ot{queryClient=void 0;preloadedEntities=void 0;warn=Ke;isPartialEvent=!1;seen=void 0;seenByKey=void 0;reset(t,e,i,r=!1){this.queryClient=t,this.preloadedEntities=e,this.warn=i,this.isPartialEvent=r,t!==void 0&&(this.seen===void 0?(this.seen=new Map,this.seenByKey=new Map):(this.seen.clear(),this.seenByKey.clear()))}}function ee(n,t,e){return k(n,t,e,"")}function $e(n,t,e){return mt(n,t,e)}function It(n,t,e,i){const r=n>>Wt;if((n&l.IS_EAGER_FORMAT)!==0)try{return new $(t,r,!0)}catch(o){if((n&l.UNDEFINED)!==0){e.warn("Invalid formatted value for optional type, defaulting to undefined",{value:t,path:i,error:o instanceof Error?o.message:String(o)});return}throw o}return new $(t,r,!1)}function k(n,t,e,i){const r=t;if(r instanceof X){const c=r.get(n);if(c===void 0)throw j(i);return c}if(r instanceof Set){if(!r.has(n))throw j(i);return n}if(typeof r=="string"){if(n==null)return r;if(n!==r)throw j(i);return n}if(typeof r=="number"){const c=Nt(n);if((r&c)===0){if((r&l.UNDEFINED)!==0){e.warn("Invalid value for optional type, defaulting to undefined",{value:n,path:i});return}throw j(i)}return(r&l.HAS_FORMAT)!==0&&n!==null&&n!==void 0?It(r,n,e,i):n}const s=r.mask,o=r._liveConfig;if(o!==void 0&&o.type===H.Value)return o.valueType!==void 0?k(n,o.valueType,e,i):n;if((s&l.PARSE_RESULT)!==0)try{return{success:!0,value:k(n,r.shape,e,i)}}catch(c){return{success:!1,error:c instanceof Error?c:new Error(String(c))}}const a=Nt(n);if((s&a)===0&&!r.values?.has(n)){if((s&l.UNDEFINED)!==0){e.warn("Invalid value for optional type, defaulting to undefined",{value:n,path:i});return}throw j(i)}return a<l.OBJECT?(s&l.HAS_FORMAT)!==0&&n!==null&&n!==void 0?It(s,n,e,i):n:(s&l.UNION)!==0?Qe(a,n,r,e,i):a===l.ARRAY?ne(n,r.shape,e,i):(s&l.RECORD)!==0?ie(n,r.shape,e,i):(s&l.ENTITY)!==0&&e.queryClient!==void 0?mt(n,r,e):re(n,r,e,i)}function Qe(n,t,e,i,r){if(n===l.ARRAY){const s=e.shape[U];return s===void 0||typeof s=="number"?t:ne(t,s,i,r)}else{const s=e.typenameField,o=s?t[s]:void 0;if(o===void 0||typeof o!="string"){const c=e.shape[V];if(c===void 0)throw new Error(`Typename field '${s}' is required for union discrimination but was not found in the data`);return ie(t,c,i,r)}const a=e.shape[o];if(a===void 0||typeof a=="number")throw new Error(`Unknown typename '${o}' in union`);return a.mask&l.ENTITY&&i.queryClient!==void 0?mt(t,a,i):re(t,a,i,r)}}function ne(n,t,e,i){const r=[];for(let s=0;s<n.length;s++)try{r.push(k(n[s],t,e,`${i}[${s}]`))}catch(o){e.warn("Failed to parse array item, filtering out",{index:s,value:n[s],error:o instanceof Error?o.message:String(o)})}return r}function ie(n,t,e,i){for(const[r,s]of _t(n))n[r]=k(s,t,e,`${i}["${r}"]`);return n}function re(n,t,e,i){if(O.has(n))return n;const r=t.shape;for(const[s,o]of _t(r))n[s]=k(n[s],o,e,`${i}.${s}`);return n}function mt(n,t,e){const i=e.queryClient,r=e.preloadedEntities;let s,o;if(r!==void 0)s=n.__entityRef,o=s;else{const g=n[t.idField];if(g==null||typeof g!="string"&&typeof g!="number")throw new Error(`Entity id must be a string or number: ${t.typenameValue} (got ${typeof g})`);o=g,s=D.hashValue([t.typenameValue,o])}const a=e.seenByKey.get(s);if(a!==void 0)return a.data;if(r!==void 0){const p=i.entityMap.getEntity(s)?.data??r.get(s);if(p===void 0)throw new Error(`Cached entity ${s} not found in preloaded map`);n=p}const c={};typeof t.idField=="symbol"&&(c[t.idField]=o);const f=i.entityMap.getEntity(s),d=e.isPartialEvent&&f!==void 0,u={key:s,shape:t,data:c,rawKeys:d?new Set(Object.keys(n)):void 0};e.seen.set(c,u),e.seenByKey.set(s,u);const y=`[[${t.typenameValue}:${o}]]`,v=t.shape;for(const[g,p]of _t(v))d&&!(g in n)||(c[g]=k(n[g],p,e,`${y}.${g}`));return c}function Be(n,t){return Ye(n,t.shape,t.typenameField)}function Ye(n,t,e){if(t===void 0)return!0;for(const i of Object.keys(t)){if(i===e)continue;const r=t[i];if(r instanceof _){if((r.mask&l.UNDEFINED)!==0)continue;if(!(i in n)||n[i]===void 0)return!1}else if(typeof r=="number"){if((r&l.UNDEFINED)!==0)continue;if(!(i in n)||n[i]===void 0)return!1}else if(!(i in n)||n[i]===void 0)return!1}return!0}const Ge=Object.prototype,G=new WeakMap;function N(n){if(typeof n!="object"||n===null)return n;if(Z.has(n))return N(n.getValue());if(O.has(n))return n;if(Array.isArray(n)){let t=G.get(n);return t===void 0&&(t=new Proxy(n,We),G.set(n,t)),t}if(Object.getPrototypeOf(n)===Ge){let t=G.get(n);return t===void 0&&(t=new Proxy(n,ze),G.set(n,t)),t}return n}const We={get(n,t,e){if(typeof t=="string"){const i=Number(t);if(Number.isInteger(i)&&i>=0&&i<n.length)return N(n[i])}return Reflect.get(n,t,e)},set(){return!1},deleteProperty(){return!1}},ze={get(n,t,e){return typeof t=="string"?N(n[t]):Reflect.get(n,t,e)},set(){return!1},deleteProperty(){return!1},has(n,t){return t in n},ownKeys(n){return Reflect.ownKeys(n)},getOwnPropertyDescriptor(n,t){return Object.getOwnPropertyDescriptor(n,t)}};class He{_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,i,r,s,o){this._notifier=b.notifier(),this._queryClient=o,this.key=t,this.typename=e,this.id=i,this.idField=r,this.data=s,this.entityRefs=void 0}retain(){this.refCount++;const t=this._entityCache?.gcTime;t!==void 0&&this._queryClient.gcManager.cancel(this.key,t)}release(){if(--this.refCount>0||this.refCount<0)return;const t=this._entityCache?.gcTime;t!==void 0?this._queryClient.gcManager.schedule(this.key,t,J.Entity):this.evict()}evict(){const t=this.liveCollections.slice();this.liveCollections.length=0;for(const i of t)i.destroy();this._queryClient.entityMap.remove(this.key);const e=this.entityRefs;if(this.entityRefs=void 0,e)for(const i of e.keys())i.release()}setChildRefs(t,e){const i=this.entityRefs;if(t!==void 0&&t.size>0)for(const r of t.keys())(i===void 0||!i.has(r))&&r.retain();if(i!==void 0&&i.size>0)for(const r of i.keys())(t===void 0||!t.has(r))&&r.release();this.entityRefs=t,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 i=this._proxies.get(e);return i===void 0&&(i=Xe(this,this.key,t,this._notifier,this._queryClient),this._proxies.set(e,i)),i}get proxy(){return this._proxies.values().next().value}satisfiesDef(t){return this.satisfiedDefs.has(t)?!0:Be(this.data,t)?(this.satisfiedDefs.add(t),!0):!1}save(){this._queryClient.entityMap.save(this)}notify(){this._notifier.notify()}consume(){this._notifier.consume()}}function Je(n,t,e){const i=[];for(const r of n){if(typeof r!="object"||r===null)continue;const s=O.get(r);if(s===void 0)continue;const o=e.entityMap.getEntity(s);o!==void 0&&o.satisfiesDef(t)&&i.push(r)}return i}function Xe(n,t,e,i,r){const s=e.shape??{},o=e,a=o._methods,c=o._entityClass,f=o._entityConfig,d=c?c.prototype:ht.prototype;e.typenameField;const u=new Map,y=new Map,v=()=>({__entityRef:t});let g;f?.hasSubscribe&&a&&"__subscribe"in a&&(g=b.relay(E=>{const h=C=>{C.__eventSource=t,r.applyMutationEvent(C)},m=a.__subscribe.call(p,h);return E.value=p,m}));let p;const w=Object.keys(s);if(w.includes("__typename")||w.push("__typename"),a)for(const E of Object.keys(a))w.includes(E)||w.push(E);let I,R=w;function Y(){const E=n._extraMethods;if(E!==I){if(I=E,R=w.slice(),E!==void 0)for(const m of Object.keys(E))R.includes(m)||R.push(m);const h=n._extraGetters;if(h!==void 0)for(const m of Object.keys(h))R.includes(m)||R.push(m)}return R}const S={getPrototypeOf(){return d},get(E,h){if(typeof h=="symbol")return;if(h==="toJSON")return v;if(h==="__context")return r.getContext();if(h==="__typename")return n.typename;if(g?.value,i.consume(),typeof h=="string"){const C=n._extraGetters;if(C!==void 0&&h in C)return C[h]();const A=n._extraMethods;if(A!==void 0&&h in A){let x=u.get(h);return x||(x=A[h].bind(p),u.set(h,x)),x}if(a&&h in a){let x=u.get(h);return x||(x=b.reactiveMethod(p,a[h].bind(p)),u.set(h,x)),x}}const m=n.data[h];if(typeof m=="object"&&m!==null&&Z.has(m))return N(m.getValue());if(Array.isArray(m)&&typeof h=="string"){const C=s[h];if(C instanceof _&&(C.mask&l.ARRAY)!==0){const A=C.shape;if(A instanceof _&&(A.mask&l.ENTITY)!==0){const x=A.typenameValue;if(x!==void 0){const xt=r.getEntityDefsForTypename(x);if(xt!==void 0&&xt.length>1){const tt=y.get(h);if(tt!==void 0&&tt.source===m)return N(tt.filtered);const Ot=Je(m,A,r);return y.set(h,{source:m,filtered:Ot}),N(Ot)}}}}return N(m)}return N(m)},set(){return!1},has(E,h){if(h==="__typename")return!0;if(typeof h=="string"){const m=n._extraGetters;if(m&&h in m)return!0;const C=n._extraMethods;if(C&&h in C||a&&h in a)return!0}return h in s},ownKeys(){return Y()},getOwnPropertyDescriptor(E,h){if(h==="__typename")return{enumerable:!0,configurable:!0,value:n.typename,writable:!1};if(h in s)return{enumerable:!0,configurable:!0,value:S.get(E,h,p),writable:!1};if(typeof h=="string"){const m=n._extraGetters;if(m&&h in m)return{enumerable:!0,configurable:!0,value:S.get(E,h,p),writable:!1};const C=n._extraMethods;if(C&&h in C)return{enumerable:!0,configurable:!0,value:S.get(E,h,p),writable:!1};if(a&&h in a)return{enumerable:!1,configurable:!0,value:S.get(E,h,p),writable:!1}}}};return p=new Proxy({},S),O.set(p,t),b.setScopeOwner(p,r),p}class Ze{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,i,r){let s=this.instances.get(t);if(s===void 0){const o=i.idField;if(o===void 0)throw new Error(`Entity id field is required ${i.typenameValue}`);const a=e[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Entity id must be string or number: ${i.typenameValue}`);const c=i;s=new He(t,i.typenameValue,a,o,e,r),s._entityCache=c._entityCache,this.instances.set(t,s)}return s.parseId=r.currentParseId,s}remove(t){this.instances.delete(t)}save(t){let e;if(t.entityRefs){e=new Set;for(const i of t.entityRefs.keys())e.add(i.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 Et{static onlineSignal=b.signal(!0);get isOnline(){return!0}setNetworkStatus(t){}clearManualOverride(){}getOnlineSignal(){return Et.onlineSignal}destroy(){}}const se=new wt,tn=b.context(se);function Ct(n,t=typeof window>"u"){let e;n===!1?e=0:n===void 0||n===!0?e=t?0:3:typeof n=="number"?e=n:e=n.retries;const i=typeof n=="object"&&n.retryDelay?n.retryDelay:r=>1e3*Math.pow(2,r);return{retries:e,retryDelay:i}}class en{static cache;static controller;params;config;constructor(){return lt(this)}}const Mt=new WeakMap;class B{constructor(t,e){this.captured=e,this.statics=t}statics;createExecutionContext(t,e){return it(this.captured,t,e)}resolveOptions(t){const{methods:e}=this.captured,i=e.getConfig?e.getConfig.call(t):t.config,r=Ct(i?.retry);return{config:i,retryConfig:r}}static for(t){let e=Mt.get(t);if(e!==void 0)return e;const i=new t,r=$t(i),s=String(r.methods.getIdentityKey.call(r.fields)),o=r.fields.result,a=o instanceof _?o:Zt.object(o),c=(a.mask&l.ENTITY)!==0,f=t.cache,d=r.fields.fetchNext,u=t.controller;if(!u)throw new Error(`Query class "${t.name}" must define a static \`controller\` property. Extend RESTQuery (from fetchium/rest) or set \`static controller = MyController\` on your query class.`);const y=typeof u.prototype.sendNext=="function",v=c?a:new _(l.ENTITY|l.OBJECT,a.shape,void 0,void 0,s,ft);return e=new B({id:s,shape:v,cache:f,rawFetchNext:d,hasSendNext:y,isEntityResult:c,controllerClass:u},r),Mt.set(t,e),e}}const nn=(n,t)=>{const e=B.for(n);return bt(e,t)};function rn(n,...t){const e=B.for(n),i=b.getContext(ve);if(i===void 0)throw new Error("QueryClient not found");const r=t[0];return i.getQuery(e,r)}function oe(n,t){return new Promise((e,i)=>{if(t?.aborted){i(t.reason);return}const r=setTimeout(e,n);t?.addEventListener("abort",()=>{clearTimeout(r),i(t.reason)},{once:!0})})}async function at(n,t,e){const i=Math.max(0,t.retries);let r;for(let s=0;s<=i;s++){e?.throwIfAborted();try{return await n()}catch(o){if(r=o,s>=i)throw o;await oe(t.retryDelay(s),e)}}throw r}class sn{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=Ct(void 0);_abortController=void 0;_executionCtx=void 0;_executionCtxKey=-1;rootEntity;_extraMethods={};_queryId=0;get key(){return this.queryKey}get relayState(){return this._relayState}constructor(t,e,i,r){this.def=t,this.queryClient=e,this.queryKey=i,this.params=r,this._extraMethods={__refetch:this.refetch},t.statics.hasSendNext&&(this._extraMethods.__fetchNext=this.fetchNext);const s=Pt(r);this._queryId=s!==void 0?D.hashValue(s):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._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.unsubscribe?.(),this.unsubscribe=void 0;const f=this.config?.gcTime??Lt.DEFAULT_GC_TIME;this.queryClient.gcManager.schedule(this.queryKey,f,J.Query)},c=(f=!1)=>{const{wasPaused:d,isPaused:u,initialized:y}=this;if(this.wasPaused=u,u&&!d&&y){a();return}const v=Pt(this.params),g=bt(this.def,v),p=g!==this.storageKey;p&&(this.currentParams=v,this.storageKey=g),this.getOrCreateExecutionContext(),this.initialized?d||f?(this.queryClient.activateQuery(this),f&&this.updatedAt!==void 0&&this.setupSubscription(),(this.config?.refreshStaleOnReconnect??!0)&&this.isStale&&this.runDebounced()):p&&(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,i=!1,r){const s=this.def;return this.rootEntity=this.queryClient.parseAndApplyRootEntity(t,this._queryId,s.statics.shape,e,i,r),this.rootEntity._extraMethods===void 0&&(this.rootEntity._extraMethods=this._extraMethods,this.rootEntity._extraGetters={__hasNext:()=>this.hasNext,__isFetchingNext:()=>this._fetchNextPromise!==void 0}),this.rootEntity.getProxy(s.statics.shape)}saveQueryMetadata(){if(this.rootEntity===void 0||this.updatedAt===void 0)return;const t=new Map(this.rootEntity.entityRefs??[]);t.set(this.rootEntity,1),this.queryClient.saveQueryData(this.def,this.storageKey,{__entityRef:this.rootEntity.key},this.updatedAt,t)}async initialize(){const t=this.queryClient,e=this.relayState;this.initialized=!0;let i;try{i=await t.loadCachedQuery(this.def,this.storageKey),i!==void 0&&(this.updatedAt=i.updatedAt,e.value=this.applyData(i.value,!1,!1,i.preloadedEntities))}catch(r){t.store.deleteQuery(this.storageKey),t.getContext().log?.warn?.("Failed to initialize query, the query cache may be corrupted or invalid",r)}if(!this.isPaused)try{if(i!==void 0&&this.setupSubscription(),i===void 0||this.isStale){if(await oe(0),this.isPaused)return;this.runQueryImmediately()}}catch(r){e.setError(r)}}setupSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0;const t=this.config?.subscribe;if(!t)return;const e=this._executionCtx;this.unsubscribe=t.call(e,i=>{i.__eventSource=this.queryKey,this.queryClient.applyMutationEvent(i)})}getOrCreateExecutionContext(){return(this._executionCtx===void 0||this._executionCtxKey!==this.storageKey)&&(this._executionCtxKey=this.storageKey,this._executionCtx=this.def.createExecutionContext(this.currentParams??{},this.queryClient.getContext()),this._executionCtx.refetch=()=>this.refetch(),this._executionCtx.rawFetchNext=this.def.statics.rawFetchNext),this.resolveAndApplyOptions(),this._executionCtx}resolveAndApplyOptions(){const t=this.def.resolveOptions(this._executionCtx);this.config=t.config,this.retryConfig=t.retryConfig}async runQuery(){const t=this.def;if(this.isPaused)throw new Error("Query is paused due to network status");const e=this.getOrCreateExecutionContext(),i=this.queryClient.getController(t.statics.controllerClass),r=this._abortController?.signal??new AbortController().signal;return at(async()=>{const s=await i.send(e,r);this.updatedAt=Date.now();const o=this.applyData(s,!0);return this.saveQueryMetadata(),this.unsubscribe===void 0&&this.setupSubscription(),o},this.retryConfig,r)}runQueryImmediately(){this._abortController?.abort(),this._abortController=new AbortController,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.relayState.setPromise(this.runQuery())}runDebounced(){if(this.relayState.isPending)return;const t=this.config?.debounce??0;clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runQueryImmediately()},t)}refetch=()=>this.relayState.isPending?this.relay:(this.runQueryImmediately(),this.relay);markStale(){this.updatedAt=0}get resolvedParams(){return this.currentParams}_fetchNextPromise=void 0;_fetchNextAbort=void 0;fetchNext=()=>{if(this.updatedAt===void 0)throw new Error("Cannot call __fetchNext before initial data has loaded");return this._fetchNextPromise!==void 0?this._fetchNextPromise:(queueMicrotask(()=>this.rootEntity?.notify()),this._fetchNextPromise=this.runFetchNext().then(t=>(this._fetchNextPromise=void 0,this.rootEntity?.notify(),t),t=>{throw this._fetchNextPromise=void 0,this.rootEntity?.notify(),t}),this._fetchNextPromise)};get hasNext(){if(this.rootEntity===void 0||!this._executionCtx)return!1;const t=this.queryClient.getController(this.def.statics.controllerClass);return t.hasNext?(this._executionCtx.resultData=this.rootEntity.data,t.hasNext(this._executionCtx)):!1}async runFetchNext(){const t=this.def;this._fetchNextAbort=new AbortController;const e=this._fetchNextAbort.signal,i=this.getOrCreateExecutionContext();i.resultData=this.rootEntity.data;const r=this.queryClient.getController(t.statics.controllerClass);return at(async()=>{const s=await r.sendNext(i,e);this.updatedAt=Date.now();const o=this.applyData(s,!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??P.Online;if(t===P.Always)return!1;const e=this.queryClient.networkManager.getOnlineSignal().value;switch(t){case P.Online:return!e;case P.OfflineFirst:return!e&&this.updatedAt===void 0;default:return!1}}}class on{def;queryClient;_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),i=this.validateResponse(e);return this.processEffects(t,i),i}finally{this._inFlight=!1}},{desc:`Mutation(${this.def.id})`})}validateResponse(t){const e=this.def.responseShape;if(!(e instanceof _))return t;const i=this.queryClient.getContext().log?.warn??(()=>{}),r=new ot;return r.reset(void 0,void 0,i),ee(t,e,r)}processEffects(t,e){let i;if(this.def.hasGetEffects){const s=it(this.def.captured,t??{},this.queryClient.getContext());s.result=e,i=s.getEffects()}else if(this.def.effects!==void 0){const s={params:t,result:e};i=K(this.def.effects,s)}if(i===void 0)return;const r=this.queryClient;et(i.creates,"create",r),et(i.updates,"update",r),et(i.deletes,"delete",r),i.invalidates&&r.invalidateQueries(i.invalidates)}executeWithRetry(t){const e=Ct(this.def.config?.retry,!0),i=this.queryClient.getController(this.def.controllerClass);if(!i.sendMutation)throw new Error(`Controller "${this.def.controllerClass.name}" does not implement sendMutation(). Add a sendMutation() method to handle mutations.`);return at(async()=>{const r=new AbortController,s=it(this.def.captured,t??{},this.queryClient.getContext());return await i.sendMutation(s,r.signal)},e)}}function an(n){return typeof n=="string"?n:q(n).typenameValue}function et(n,t,e){if(n)for(const[i,r]of n){const s=an(i);s!==void 0&&e.applyMutationEvent({type:t,typename:s,data:r})}}const ae="__eventSource";function ce(n){return{field:n,segments:n.indexOf(".")!==-1?n.split("."):void 0}}function cn(n){return n.map(ce)}function fn(n,t){if(t.segments===void 0)return n[t.field];let e=n;for(const i of t.segments){if(e==null)return;e=e[i]}return e}function fe(n,t){const e=[];for(let i=0;i<t.length;i++){const r=t[i],s=fn(n,r);if(s===void 0)return;e.push(r.field,s)}return D.hashValue(e)}function un(n,t){if(n===void 0)return;const e=new Map;for(const[i,r]of n){const s=r.slice().sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0),o=[];let a=!0;for(const[c,f]of s){let d;if(Vt(f)){const u=Kt(f);d=dt(u,t)}else d=f;if(d===void 0){a=!1;break}o.push(c,d)}a&&e.set(i,D.hashValue(o))}return e.size>0?e:void 0}function kt(n,t){const e=n.get(t);if(e!==void 0)return e.map(([i])=>i).sort()}class ln{fields;fieldPaths;_bindings=new Map;constructor(t){this.fields=t,this.fieldPaths=t.map(ce)}register(t,e){let i=this._bindings.get(t);i===void 0&&(i=new Set,this._bindings.set(t,i)),i.add(e)}unregister(t,e){const i=this._bindings.get(t);i!==void 0&&(i.delete(e),i.size===0&&this._bindings.delete(t))}getMatching(t){return this._bindings.get(t)}get isEmpty(){return this._bindings.size===0}}function Ft(n){return D.hashValue(n)}class dn{_groups=new Map;getOrCreateGroup(t){const e=Ft(t);let i=this._groups.get(e);return i===void 0&&(i=new ln(t),this._groups.set(e,i)),i}register(t,e,i){this.getOrCreateGroup(e).register(t,i)}unregister(t,e,i){const r=Ft(e),s=this._groups.get(r);s!==void 0&&(s.unregister(t,i),s.isEmpty&&this._groups.delete(r))}registerBinding(t,e){const i=t._constraintHashes.get(e);if(i===void 0)return;const r=kt(t._constraintFieldRefs,e);r!==void 0&&this.register(i,r,t)}unregisterBinding(t,e){const i=t._constraintHashes.get(e);if(i===void 0)return;const r=kt(t._constraintFieldRefs,e);r!==void 0&&this.unregister(i,r,t)}routeEvent(t,e,i,r,s,o){for(const a of this._groups.values()){const c=fe(e,a.fieldPaths);if(c===void 0)continue;const f=a.getMatching(c);if(f!==void 0)for(const d of f)d.onEvent(t,i,r,s,o)}}}function Tt(n){const t=new Set;for(const e of n)if(typeof e=="object"&&e!==null){const i=F(e);i!==void 0&&t.add(i)}return t}class ue{_queryClient;_parent;_constraintHashes;_entityDefsByTypename;_constraintFieldRefs;instance;constructor(t,e,i,r,s,o){this._queryClient=i,this._parent=r,this._constraintHashes=s,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);Z.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,i,r,s){const o=this._entityDefsByTypename.get(t);if(o===void 0)return;const a=this._queryClient.entityMap.getEntity(e);if(i==="delete"){const f=a!==void 0?a.getProxy(o):s;f!==void 0&&(this.instance.onEvent(e,f,s??a?.data??{},"delete"),r?.());return}if(a===void 0||!a.satisfiesDef(o))return;r?.();const c=a.getProxy(o);this.instance.onEvent(e,c,a.data,i)}destroy(){this._queryClient.unregisterLiveCollection(this);const t=this._parent.liveCollections,e=t.indexOf(this);e!==-1&&t.splice(e,1)}}class hn{_notifier;_items;_keys;_outputSignal;_queryClient;_parent;constructor(t,e,i,r,s,o){this._notifier=b.notifier(),this._items=i,this._keys=Tt(i),this._queryClient=t,this._parent=e;const a=r!==void 0&&s!==void 0,c=o!==void 0;(a||c)&&(this._outputSignal=b.reactiveSignal(()=>{this._notifier.consume();let f=this._items;if(a){const d=[];for(const u of f){if(typeof u!="object"||u===null){d.push(u);continue}const y=F(u);if(y===void 0){d.push(u);continue}const v=t.entityMap.getEntity(y);if(v===void 0){d.push(u);continue}v.consume(),fe(v.data,r)===s&&d.push(u)}f=d}return c&&(f=(f===this._items?f.slice():f).sort(o)),f}))}onEvent(t,e,i,r){switch(r){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 i=this._queryClient.entityMap.getEntity(t);return i!==void 0&&(this._parent.addChildRef(i),i.save()),this._notifier.notify(),!0}remove(t){if(!this._keys.has(t))return!1;this._keys.delete(t);const e=this._findIndex(t);e!==-1&&this._items.splice(e,1);const i=this._queryClient.entityMap.getEntity(t);return i!==void 0&&this._parent.removeChildRef(i),this._notifier.notify(),!0}has(t){return this._keys.has(t)}reset(t){const e=this._items,i=Array.isArray(t)?t:[];this._items=i,this._keys=Tt(i);for(const r of i)if(typeof r=="object"&&r!==null){const s=F(r);if(s!==void 0){const o=this._queryClient.entityMap.getEntity(s);o!==void 0&&this._parent.addChildRef(o)}}for(const r of e)if(typeof r=="object"&&r!==null){const s=F(r);if(s!==void 0){const o=this._queryClient.entityMap.getEntity(s);o!==void 0&&this._parent.removeChildRef(o)}}this._notifier.notify()}append(t){if(Array.isArray(t))for(const e of t){if(typeof e!="object"||e===null)continue;const i=F(e);i!==void 0&&this.add(i,e)}}_findIndex(t){for(let e=0;e<this._items.length;e++){const i=this._items[e];if(typeof i=="object"&&i!==null&&F(i)===t)return e}return-1}}class yn{_notifier;_value;_createdKeys;_deletedKeys;_queryClient;_parent;_onCreate;_onUpdate;_onDelete;constructor(t,e,i,r,s,o){this._notifier=b.notifier(),this._value=i,this._createdKeys=new Set,this._deletedKeys=new Set,this._queryClient=t,this._parent=e,this._onCreate=r,this._onUpdate=s,this._onDelete=o}onEvent(t,e,i,r){switch(r){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??i);break;case"delete":if(this._deletedKeys.has(t))return;this._deletedKeys.add(t),this._value=this._onDelete(this._value,e??i);break}this._notifier.notify()}getValue(){return this._notifier.consume(),this._value}getRawValue(){return this._value}reset(t){this._value=t,this._createdKeys.clear(),this._deletedKeys.clear(),this._notifier.notify()}append(t){}}function le(n,t,e,i,r){let s=n.constraintFieldRefs;if(s===void 0){s=new Map;for(const f of n.entityDefs){const d=f.typenameValue;d!==void 0&&s.set(d,[[ae,e.key]])}}const o=un(s,i)??new Map;let a;if(n.type===H.Array){let f,d;if(n.constraintFieldRefs!==void 0&&o.size>0&&o.size===1)for(const[u]of n.constraintFieldRefs){const y=o.get(u);if(y!==void 0){d=y;const v=n.constraintFieldRefs.get(u);v!==void 0&&(f=cn(v.map(([g])=>g)));break}}a=new hn(r,e,Array.isArray(t)?t:[],f,d,n.sort)}else a=new yn(r,e,t,n.onCreate,n.onUpdate,n.onDelete);const c=new ue(n.entityDefs,s,r,e,o,a);return e.liveCollections.push(c),r.registerLiveCollection(c),c}const de=Object.entries,he=Object.prototype;function nt(n,t,e,i=!1){const r=n.queryClient;r.currentParseId++;const s=n.seen,o=new Map;return{data:Q(t,s,r,e,o,i),entityRefs:o}}function Q(n,t,e,i,r,s){if(typeof n!="object"||n===null)return n;const o=t.get(n);if(o!==void 0)return gn(o,t,e,i,r,s);if(Array.isArray(n)){for(let a=0;a<n.length;a++){const c=n[a];typeof c=="object"&&c!==null&&!(c instanceof $)&&!O.has(c)&&(n[a]=Q(c,t,e,i,r,s))}return n}if(Object.getPrototypeOf(n)===he&&!O.has(n)){const a=n;for(const c of Object.keys(a)){const f=a[c];typeof f=="object"&&f!==null&&!(f instanceof $)&&!O.has(f)&&(a[c]=Q(f,t,e,i,r,s))}}return n}function ye(n){return typeof n=="object"&&n!==null&&!(n instanceof $)&&!O.has(n)}function gn(n,t,e,i,r,s){const{key:o,data:a,shape:c,rawKeys:f}=n,d=c.shape,u=e.prepareEntity(o,a,c),y=u.data,v=y!==a,g=v&&f!==void 0&&u.entityRefs!==void 0?new Map(u.entityRefs):new Map;if(v?(ge(d,a,y,f,u,y,t,e,i,g,s),u.notify()):pe(d,a,u,a,t,e,i,g,s),s&&u.liveCollections.length>0)for(const w of u.liveCollections){const I=w.instance.getRawValue();if(Array.isArray(I))for(const R of I){if(typeof R!="object"||R===null)continue;const Y=O.get(R);if(Y===void 0)continue;const S=e.entityMap.getEntity(Y);S!==void 0&&g.set(S,(g.get(S)??0)+1)}}u.setChildRefs(g.size>0?g:void 0,i);const p=u.getProxy(c);return r.set(u,(r.get(u)??0)+1),p}function ge(n,t,e,i,r,s,o,a,c,f,d){for(const[u,y]of de(n))if(!(i!==void 0&&!i.has(u)))if(ye(t[u])&&(t[u]=Q(t[u],o,a,c,f,d)),y instanceof _&&y._liveConfig!==void 0){const v=e[u];v instanceof ue?d?v.append(t[u]):v.reset(t[u]):e[u]=le(y._liveConfig,t[u],r,s,a)}else{const v=t[u],g=e[u];if(ct(v)&&ct(g)){const p=y instanceof _&&y.shape!==void 0?y.shape:void 0;if(p!==void 0)ge(p,v,g,void 0,r,s,o,a,c,f,d);else for(const w of Object.keys(v))g[w]=v[w];e[u]=g}else e[u]=v}}function pe(n,t,e,i,r,s,o,a,c){for(const[f,d]of de(n))if(f in t)if(ye(t[f])&&(t[f]=Q(t[f],r,s,o,a,c)),d instanceof _&&d._liveConfig!==void 0)t[f]=le(d._liveConfig,t[f],e,i,s);else{const u=t[f];if(ct(u)){const y=d instanceof _&&d.shape!==void 0?d.shape:void 0;y!==void 0&&pe(y,u,e,i,r,s,o,a,c)}}}function ct(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.getPrototypeOf(n)===he&&!O.has(n)}function pn(n){if(n!==void 0)return typeof n=="string"?n:typeof n=="function"?n():n.value}function vn(n){return b.isSignal(n)}function Pt(n){if(n===void 0)return;const t={};for(const[e,i]of Object.entries(n))vn(i)?t[e]=i.value:t[e]=i;return t}const bt=(n,t)=>D.hashValue([n.statics.id,t]);class _n{entityMap;queryInstances=new Map;mutationInstances=new Map;gcManager;networkManager;isServer;store;currentParseId=0;context;typenameRegistry=new Map;constraintRegistry=new Map;mergedDefCache=new Map;controllers=new Map;networkUnsubscribe;constructor(t={}){const{store:e=new Rt.SyncQueryStore(new Rt.MemoryPersistentStore),log:i,evictionMultiplier:r,controllers:s,networkManager:o,gcManager:a,...c}=t;this.isServer=typeof window>"u",this.store=e,this.context={...c,log:i??console,evictionMultiplier:r},this.gcManager=t.gcManager??(this.isServer?new jt:new qt(this.handleEviction,r)),this.networkManager=t.networkManager??new wt,this.entityMap=new Ze((u,y,v)=>this.store.saveEntity(u,y,v));for(const u of t.controllers??[])this.controllers.set(u.constructor,u),u.register(this);const f=this.networkManager.getOnlineSignal(),d=b.watcher(()=>f.value);this.networkUnsubscribe=d.addListener(()=>{const u=f.value;for(const y of this.controllers.values())y.onNetworkStatusChange?.(u)},{skipInitial:!0}),this.store.purgeStaleQueries?.()}getController(t){let e=this.controllers.get(t);if(!e){try{e=new t}catch{throw new Error(`No controller registered for ${t.name} and auto-instantiation failed. Pass an instance via QueryClient config: new QueryClient({ store, controllers: [new ${t.name}(...)] })`)}this.controllers.set(t,e),e.register(this)}return e}getContext(){return this.context}registerEntityDef(t){const e=t.typenameValue;if(e===void 0||t._entityClass===void 0)return;const i=this.typenameRegistry.get(e);if(i!==void 0){if(i.indexOf(t)!==-1)return;i.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 i=this.typenameRegistry.get(t);if(i!==void 0)return e=_.merge(i),this.mergedDefCache.set(t,e),e}saveQueryData(t,e,i,r,s){const o=s!==void 0&&s.size>0?new Set([...s.keys()].map(a=>a.key)):void 0;this.store.saveQuery(t,e,i,r,o)}activateQuery(t){const{def:e,queryKey:i,storageKey:r,config:s}=t;this.store.activateQuery(e,r);const o=s?.gcTime??Lt.DEFAULT_GC_TIME;this.gcManager.cancel(i,o)}loadCachedQuery(t,e){return this.store.loadQuery(t,e)}getQuery(t,e){const i=bt(t,e);let r=this.queryInstances.get(i);return r===void 0&&(r=new sn(t,this,i,e),this.queryInstances.set(i,r)),r.relay}getMutation(t){const e=t.id;let i=this.mutationInstances.get(e);return i===void 0&&(i=new on(t,this),this.mutationInstances.set(e,i)),i.task}parseData(t,e,i){const r=this.context.log?.warn??(()=>{}),s=new ot;return s.reset(this,i,r),{data:ee(t,e,s),ctx:s}}applyRefs(t,e=!0,i=!1){return nt(t.ctx,t.data,e,i)}parseAndApplyRootEntity(t,e,i,r,s=!1,o){typeof i.idField=="symbol"&&typeof t=="object"&&t!==null&&!("__entityRef"in t)&&(t[ft]=e);const a=this.parseData(t,i,o),c=nt(a.ctx,a.data,r,s),f=O.get(c.data);return this.entityMap.getEntity(f)}prepareEntity(t,e,i){return this.registerEntityDef(i),this.entityMap.getOrCreateEntity(t,e,i,this)}applyMutationEvent(t){const{type:e,typename:i}=t,r=this.getMergedDef(i);if(r===void 0)return;const s=r.idField;if(s===void 0||typeof s=="symbol")return;const o=t.data,a=t.id!==void 0?t.id:e==="delete"&&(typeof o=="string"||typeof o=="number")?o:o[s];if(a===void 0)return;const c=D.hashValue([i,a]),f=t.__eventSource,d=typeof o=="object"&&o!==null?o:{},u=this.entityMap.getEntity(c);if(e==="delete"){const p=u!==void 0?u.data:d;this.routeEvent(i,p,c,e,f,void 0,p);return}try{const p=this.context.log?.warn??(()=>{}),w=new ot;w.reset(this,void 0,p,!0);const I=$e(d,r,w);nt(w,I,!0)}catch(p){if(this.context.log?.warn?.("Failed to apply mutation event",p),u===void 0){const w=this.entityMap.getEntity(c);w!==void 0&&w.evict()}return}const y=this.entityMap.getEntity(c);if(y===void 0)return;this.entityMap.save(y);const v=u===void 0;let g=!1;this.routeEvent(i,y.data,c,e,f,()=>{g=!0}),v&&!g&&y.evict()}invalidateQueries(t){for(const e of t){const i=Array.isArray(e),r=i?e[0]:e,s=i?e[1]:void 0,a=B.for(r).statics.id;for(const[,c]of this.queryInstances)c.def.statics.id===a&&(s===void 0||mn(c.resolvedParams,s))&&c.markStale()}}handleEviction=(t,e)=>{if(e===J.Query){const r=this.queryInstances.get(t);if(r===void 0)return;r.rootEntity?.evict(),this.queryInstances.delete(t);return}const i=this.entityMap.getEntity(t);i!==void 0&&i.evict()};getOrCreateMatcher(t){let e=this.constraintRegistry.get(t);return e===void 0&&(e=new dn,this.constraintRegistry.set(t,e)),e}registerLiveCollection(t){for(const[e,i]of t._entityDefsByTypename)this.registerEntityDef(i),this.getOrCreateMatcher(e).registerBinding(t,e)}unregisterLiveCollection(t){for(const e of t._entityDefsByTypename.keys()){const i=this.constraintRegistry.get(e);i!==void 0&&i.unregisterBinding(t,e)}}routeEvent(t,e,i,r,s,o,a){const c=this.constraintRegistry.get(t);if(c===void 0)return;const f=s!==void 0?{...e,[ae]:s}:e;c.routeEvent(t,f,i,r,o,a)}destroy(){this.networkUnsubscribe?.(),this.gcManager.destroy(),this.networkManager.destroy();for(const t of this.controllers.values())t.destroy?.();this.controllers.clear(),this.queryInstances.clear(),this.mutationInstances.clear(),this.constraintRegistry.clear(),this.typenameRegistry.clear(),this.mergedDefCache.clear()}}const ve=b.context(void 0);function mn(n,t){if(n===void 0)return!1;for(const e in t)if(n[e]!==t[e])return!1;return!0}exports.ARRAY_KEY=U;exports.Entity=ht;exports.GcManager=qt;exports.LiveFieldConfig=L;exports.LiveFieldType=H;exports.Mask=l;exports.NetworkManager=wt;exports.NetworkManagerContext=tn;exports.NetworkMode=P;exports.NoOpGcManager=jt;exports.NoOpNetworkManager=Et;exports.QUERY_ID=ft;exports.Query=en;exports.QueryClient=_n;exports.QueryClientContext=ve;exports.RECORD_KEY=V;exports.ValidatorDef=_;exports.createDefinitionProxy=lt;exports.defaultNetworkManager=se;exports.draft=Ve;exports.extractDefinition=$t;exports.fetchQuery=rn;exports.queryKeyForClass=nn;exports.registerFormat=vt;exports.reifyValue=K;exports.resolveBaseUrl=pn;exports.t=Zt;
2
+ //# sourceMappingURL=QueryClient-N0MJmuHW.js.map