@live-state/sync 0.0.5 → 0.0.6-beta-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.d.ts CHANGED
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { L as LiveObjectAny, W as WhereClause, S as Simplify, I as InferLiveObjectWithRelationalIds, M as MaterializedLiveType, a as Schema, b as IncludeClause, c as InferLiveObject, d as InferInsert, e as InferUpdate, f as Logger, g as LogLevel } from './index-BtsKDfTE.js';
3
3
  import * as z3 from 'zod/v3';
4
4
  import * as z4 from 'zod/v4/core';
5
- import { PostgresPool } from 'kysely';
5
+ import { PostgresPool, Kysely } from 'kysely';
6
6
  import { Application } from 'express-ws';
7
7
 
8
8
  declare const querySchema: z.ZodObject<{
@@ -30,7 +30,7 @@ declare const defaultMutationSchema: z.ZodObject<{
30
30
  UPDATE: "UPDATE";
31
31
  }>;
32
32
  payload: z.ZodRecord<z.ZodString, z.ZodObject<{
33
- value: z.ZodNullable<z.ZodUnion<[z.ZodUnion<[z.ZodUnion<[z.ZodString, z.ZodNumber]>, z.ZodBoolean]>, z.ZodDate]>>;
33
+ value: z.ZodNullable<z.ZodAny>;
34
34
  _meta: z.ZodOptional<z.ZodObject<{
35
35
  timestamp: z.ZodNullable<z.ZodOptional<z.ZodString>>;
36
36
  }, z.core.$strip>>;
@@ -40,7 +40,7 @@ type DefaultMutation = Omit<z.infer<typeof defaultMutationSchema>, "resourceId">
40
40
  resourceId: string;
41
41
  };
42
42
 
43
- type Awaitable<T> = T | Promise<T>;
43
+ type PromiseOrSync<T> = T | Promise<T>;
44
44
 
45
45
  /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
46
46
  /** biome-ignore-all lint/style/noNonNullAssertion: false positive */
@@ -48,10 +48,12 @@ type Awaitable<T> = T | Promise<T>;
48
48
  type RouteRecord = Record<string, AnyRoute>;
49
49
  declare class Router<TRoutes extends RouteRecord> {
50
50
  readonly routes: TRoutes;
51
+ readonly hooksRegistry: Map<string, Hooks<any>>;
51
52
  private constructor();
52
53
  static create<TRoutes extends RouteRecord>(opts: {
53
54
  routes: TRoutes;
54
55
  }): Router<TRoutes>;
56
+ getHooks(resourceName: string): Hooks<any> | undefined;
55
57
  }
56
58
  declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof TSchema, Route<any, any, any>>>(opts: {
57
59
  schema: TSchema;
@@ -59,13 +61,14 @@ declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof
59
61
  }) => Router<TRoutes>;
60
62
  type AnyRouter = Router<any>;
61
63
  type QueryResult<TShape extends LiveObjectAny> = {
62
- data: Record<string, MaterializedLiveType<TShape>>;
64
+ data: MaterializedLiveType<TShape>[];
65
+ unsubscribe?: () => void;
63
66
  };
64
67
  type MutationResult<TShape extends LiveObjectAny> = {
65
68
  data: MaterializedLiveType<TShape>;
66
69
  acceptedValues: Record<string, any> | null;
67
70
  };
68
- type Mutation<TInputValidator extends z3.ZodTypeAny | z4.$ZodType, // TODO use StandardSchema instead
71
+ type Mutation<TInputValidator extends z3.ZodTypeAny | z4.$ZodType | never, // TODO use StandardSchema instead
69
72
  TOutput> = {
70
73
  inputValidator: TInputValidator;
71
74
  handler: (opts: {
@@ -73,9 +76,21 @@ TOutput> = {
73
76
  db: Storage;
74
77
  }) => TOutput;
75
78
  };
76
- declare const mutationCreator: <TInputValidator extends z3.ZodTypeAny | z4.$ZodType>(validator?: TInputValidator) => {
77
- handler: <THandler extends Mutation<TInputValidator, any>["handler"]>(handler: THandler) => Mutation<TInputValidator, ReturnType<THandler>>;
79
+ type MutationCreator = {
80
+ (): {
81
+ handler: <TOutput>(handler: (opts: {
82
+ req: MutationRequest<undefined>;
83
+ db: Storage;
84
+ }) => TOutput) => Mutation<z.ZodUndefined, TOutput>;
85
+ };
86
+ <TInputValidator extends z3.ZodTypeAny | z4.$ZodType>(validator: TInputValidator): {
87
+ handler: <THandler extends (opts: {
88
+ req: MutationRequest<z.infer<TInputValidator>>;
89
+ db: Storage;
90
+ }) => any>(handler: THandler) => Mutation<TInputValidator, ReturnType<THandler>>;
91
+ };
78
92
  };
93
+ declare const mutationCreator: MutationCreator;
79
94
  type ReadAuthorizationHandler<TShape extends LiveObjectAny> = (opts: {
80
95
  ctx: BaseRequest["context"];
81
96
  }) => WhereClause<TShape> | boolean;
@@ -91,16 +106,47 @@ type Authorization<TShape extends LiveObjectAny> = {
91
106
  postMutation?: MutationAuthorizationHandler<TShape>;
92
107
  };
93
108
  };
109
+ type BeforeInsertHook<TShape extends LiveObjectAny> = (opts: {
110
+ ctx?: Record<string, any>;
111
+ value: MaterializedLiveType<TShape>;
112
+ db: Storage;
113
+ }) => Promise<MaterializedLiveType<TShape> | void> | MaterializedLiveType<TShape> | void;
114
+ type AfterInsertHook<TShape extends LiveObjectAny> = (opts: {
115
+ ctx?: Record<string, any>;
116
+ value: MaterializedLiveType<TShape>;
117
+ db: Storage;
118
+ }) => Promise<void> | void;
119
+ type BeforeUpdateHook<TShape extends LiveObjectAny> = (opts: {
120
+ ctx?: Record<string, any>;
121
+ value: MaterializedLiveType<TShape>;
122
+ previousValue?: MaterializedLiveType<TShape>;
123
+ db: Storage;
124
+ }) => Promise<MaterializedLiveType<TShape> | void> | MaterializedLiveType<TShape> | void;
125
+ type AfterUpdateHook<TShape extends LiveObjectAny> = (opts: {
126
+ ctx?: Record<string, any>;
127
+ value: MaterializedLiveType<TShape>;
128
+ previousValue?: MaterializedLiveType<TShape>;
129
+ db: Storage;
130
+ }) => Promise<void> | void;
131
+ type Hooks<TShape extends LiveObjectAny> = {
132
+ beforeInsert?: BeforeInsertHook<TShape>;
133
+ afterInsert?: AfterInsertHook<TShape>;
134
+ beforeUpdate?: BeforeUpdateHook<TShape>;
135
+ afterUpdate?: AfterUpdateHook<TShape>;
136
+ };
94
137
  declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends Middleware<any>, TCustomMutations extends Record<string, Mutation<any, any>>> {
95
138
  readonly resourceSchema: TResourceSchema;
96
139
  readonly middlewares: Set<TMiddleware>;
97
140
  readonly customMutations: TCustomMutations;
98
141
  readonly authorization?: Authorization<TResourceSchema>;
99
- constructor(resourceSchema: TResourceSchema, customMutations?: TCustomMutations, authorization?: Authorization<TResourceSchema>);
142
+ readonly hooks?: Hooks<TResourceSchema>;
143
+ constructor(resourceSchema: TResourceSchema, customMutations?: TCustomMutations, authorization?: Authorization<TResourceSchema>, hooks?: Hooks<TResourceSchema>);
100
144
  use(...middlewares: TMiddleware[]): this;
101
145
  withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
102
146
  mutation: typeof mutationCreator;
103
147
  }) => T): Route<TResourceSchema, TMiddleware, T>;
148
+ withHooks(hooks: Hooks<TResourceSchema>): Route<TResourceSchema, TMiddleware, TCustomMutations>;
149
+ getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
104
150
  private handleSet;
105
151
  private wrapInMiddlewares;
106
152
  }
@@ -116,16 +162,51 @@ type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
116
162
 
117
163
  /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
118
164
 
119
- declare abstract class Storage {
120
- abstract findOne<T extends LiveObjectAny>(resource: T, id: string, options?: {
121
- include?: IncludeClause<T>;
122
- }): Promise<InferLiveObject<T> | undefined>;
123
- abstract find<T extends LiveObjectAny>(resource: T, options?: {
165
+ declare class Batcher {
166
+ private storage;
167
+ private queue;
168
+ private scheduled;
169
+ constructor(storage: Storage);
170
+ rawFind<T extends LiveObjectAny>({ resource, commonWhere, uniqueWhere, ...rest }: {
171
+ resource: string;
172
+ commonWhere?: Record<string, any>;
173
+ uniqueWhere?: Record<string, any>;
174
+ include?: Record<string, any>;
175
+ limit?: number;
176
+ sort?: {
177
+ key: string;
178
+ direction: "asc" | "desc";
179
+ }[];
180
+ }): Promise<MaterializedLiveType<T>[]>;
181
+ private getBatchKey;
182
+ private processBatch;
183
+ private executeBatchedRequests;
184
+ }
185
+
186
+ interface DataSource {
187
+ get(query: RawQueryRequest, extra?: {
188
+ context?: any;
189
+ batcher?: Batcher;
190
+ }): PromiseOrSync<any[]>;
191
+ }
192
+
193
+ /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
194
+
195
+ declare abstract class Storage implements DataSource {
196
+ abstract findOne<T extends LiveObjectAny, TInclude extends IncludeClause<T> | undefined = undefined>(resource: T, id: string, options?: {
197
+ include?: TInclude;
198
+ }): Promise<InferLiveObject<T, TInclude> | undefined>;
199
+ abstract find<T extends LiveObjectAny, TInclude extends IncludeClause<T> | undefined = undefined>(resource: T, options?: {
124
200
  where?: WhereClause<T>;
125
- include?: IncludeClause<T>;
126
- }): Promise<Record<string, InferLiveObject<T>>>;
201
+ include?: TInclude;
202
+ limit?: number;
203
+ sort?: {
204
+ key: string;
205
+ direction: "asc" | "desc";
206
+ }[];
207
+ }): Promise<InferLiveObject<T, TInclude>[]>;
127
208
  insert<T extends LiveObjectAny>(resource: T, value: Simplify<InferInsert<T>>): Promise<InferLiveObject<T>>;
128
- update<T extends LiveObjectAny>(resource: T, resourceId: string, value: InferUpdate<T>): Promise<InferLiveObject<T>>;
209
+ update<T extends LiveObjectAny>(resource: T, resourceId: string, value: InferUpdate<T>): Promise<Partial<InferLiveObject<T>>>;
129
210
  abstract transaction<T>(fn: (opts: {
130
211
  trx: Storage;
131
212
  commit: () => Promise<void>;
@@ -136,37 +217,58 @@ declare abstract class Storage {
136
217
  /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
137
218
 
138
219
  declare class SQLStorage extends Storage {
139
- private db;
220
+ private readonly db;
221
+ private readonly dialectHelpers;
140
222
  private schema?;
141
223
  private logger?;
224
+ private server?;
225
+ private mutationStack;
142
226
  constructor(pool: PostgresPool);
143
- findOne<T extends LiveObjectAny>(resource: T, id: string, options?: {
144
- include?: IncludeClause<T>;
145
- }): Promise<InferLiveObject<T> | undefined>;
146
- find<T extends LiveObjectAny>(resource: T, options?: {
227
+ private selectMetaColumns;
228
+ findOne<T extends LiveObjectAny, TInclude extends IncludeClause<T> | undefined = undefined>(resource: T, id: string, options?: {
229
+ include?: TInclude;
230
+ }): Promise<InferLiveObject<T, TInclude> | undefined>;
231
+ find<T extends LiveObjectAny, TInclude extends IncludeClause<T> | undefined = undefined>(resource: T, options?: {
147
232
  where?: WhereClause<T>;
148
- include?: IncludeClause<T>;
233
+ include?: TInclude;
149
234
  limit?: number;
150
235
  sort?: {
151
236
  key: string;
152
237
  direction: "asc" | "desc";
153
238
  }[];
154
- }): Promise<Record<string, InferLiveObject<T>>>;
239
+ }): Promise<InferLiveObject<T, TInclude>[]>;
155
240
  transaction<T>(fn: (opts: {
156
241
  trx: Storage;
157
242
  commit: () => Promise<void>;
158
243
  rollback: () => Promise<void>;
159
244
  }) => Promise<T>): Promise<T>;
245
+ /**
246
+ * Provides direct access to the underlying Kysely database instance.
247
+ *
248
+ * ⚠️ Warning: Direct database operations bypass mutation tracking and
249
+ * subscriber notifications. Use this only when you need to execute
250
+ * queries not supported by the Storage API.
251
+ *
252
+ * @returns The Kysely database instance
253
+ */
254
+ get internalDB(): Kysely<{
255
+ [x: string]: {
256
+ [x: string]: any;
257
+ };
258
+ }>;
259
+ private isRelationalField;
260
+ private parseRelationalJsonStrings;
160
261
  private convertToMaterializedLiveType;
161
262
  private isKyselyLike;
263
+ private buildMutation;
264
+ private trackMutation;
265
+ private notifyMutations;
162
266
  }
163
267
 
164
268
  declare const expressAdapter: (app: Application, server: Server<AnyRouter>, options?: {
165
269
  basePath?: string;
166
270
  }) => void;
167
271
 
168
- /** biome-ignore-all lint/suspicious/noExplicitAny: any's are actually used correctly */
169
-
170
272
  interface BaseRequest {
171
273
  headers: Record<string, string>;
172
274
  cookies: Record<string, string>;
@@ -187,8 +289,7 @@ type Request = QueryRequest | MutationRequest;
187
289
  type ContextProvider = (req: Omit<BaseRequest, "context"> & {
188
290
  transport: "HTTP" | "WEBSOCKET";
189
291
  }) => Record<string, any>;
190
- type MutationHandler = (mutation: DefaultMutation) => void;
191
- type NextFunction<O, R = Request> = (req: R) => Awaitable<O>;
292
+ type NextFunction<O, R = Request> = (req: R) => PromiseOrSync<O>;
192
293
  type Middleware<T = any> = (opts: {
193
294
  req: Request;
194
295
  next: NextFunction<T>;
@@ -200,7 +301,6 @@ declare class Server<TRouter extends AnyRouter> {
200
301
  readonly middlewares: Set<Middleware<any>>;
201
302
  readonly logger: Logger;
202
303
  contextProvider?: ContextProvider;
203
- private mutationSubscriptions;
204
304
  private constructor();
205
305
  static create<TRouter extends AnyRouter>(opts: {
206
306
  router: TRouter;
@@ -210,9 +310,9 @@ declare class Server<TRouter extends AnyRouter> {
210
310
  contextProvider?: ContextProvider;
211
311
  logLevel?: LogLevel;
212
312
  }): Server<TRouter>;
213
- subscribeToMutations(handler: MutationHandler): () => void;
214
313
  handleQuery(opts: {
215
314
  req: QueryRequest;
315
+ subscription?: (mutation: DefaultMutation) => void;
216
316
  }): Promise<QueryResult<any>>;
217
317
  handleMutation(opts: {
218
318
  req: MutationRequest;
@@ -223,4 +323,4 @@ declare class Server<TRouter extends AnyRouter> {
223
323
  }
224
324
  declare const server: typeof Server.create;
225
325
 
226
- export { type AnyRoute, type AnyRouter, type Authorization, type BaseRequest, type ContextProvider, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationHandler, type MutationRequest, type MutationResult, type NextFunction, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, Storage, expressAdapter, routeFactory, router, server };
326
+ export { type AfterInsertHook, type AfterUpdateHook, type AnyRoute, type AnyRouter, type Authorization, type BaseRequest, type BeforeInsertHook, type BeforeUpdateHook, type ContextProvider, type Hooks, type Middleware, type Mutation, type MutationAuthorizationHandler, type MutationRequest, type MutationResult, type NextFunction, type QueryRequest, type QueryResult, type ReadAuthorizationHandler, type Request, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, Storage, expressAdapter, routeFactory, router, server };
package/dist/server.js CHANGED
@@ -1,2 +1,6 @@
1
- import {a,b,t,v as v$1,w,y,x}from'./chunk-NJ7LXJAY.js';import C from'node:crypto';import Be,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect}from'kysely';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/postgres';var _=a(N=>{Object.defineProperty(N,"__esModule",{value:true});N.parse=Pe;N.serialize=ze;var Ae=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Oe=/^[\u0021-\u003A\u003C-\u007E]*$/,je=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Le=/^[\u0020-\u003A\u003D-\u007E]*$/,$e=Object.prototype.toString,Ce=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Pe(i,t){let e=new Ce,r=i.length;if(r<2)return e;let n=(t==null?void 0:t.decode)||Ne,o=0;do{let c=i.indexOf("=",o);if(c===-1)break;let a=i.indexOf(";",o),s=a===-1?r:a;if(c>s){o=i.lastIndexOf(";",c-1)+1;continue}let h=oe(i,o,c),y=ae(i,c,h),d=i.slice(h,y);if(e[d]===void 0){let p=oe(i,c+1,s),u=ae(i,s,p),f=n(i.slice(p,u));e[d]=f;}o=s+1;}while(o<r);return e}function oe(i,t,e){do{let r=i.charCodeAt(t);if(r!==32&&r!==9)return t}while(++t<e);return e}function ae(i,t,e){for(;t>e;){let r=i.charCodeAt(--t);if(r!==32&&r!==9)return t+1}return e}function ze(i,t,e){let r=(e==null?void 0:e.encode)||encodeURIComponent;if(!Ae.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(t);if(!Oe.test(n))throw new TypeError(`argument val is invalid: ${t}`);let o=i+"="+n;if(!e)return o;if(e.maxAge!==void 0){if(!Number.isInteger(e.maxAge))throw new TypeError(`option maxAge is invalid: ${e.maxAge}`);o+="; Max-Age="+e.maxAge;}if(e.domain){if(!je.test(e.domain))throw new TypeError(`option domain is invalid: ${e.domain}`);o+="; Domain="+e.domain;}if(e.path){if(!Le.test(e.path))throw new TypeError(`option path is invalid: ${e.path}`);o+="; Path="+e.path;}if(e.expires){if(!Ue(e.expires)||!Number.isFinite(e.expires.valueOf()))throw new TypeError(`option expires is invalid: ${e.expires}`);o+="; Expires="+e.expires.toUTCString();}if(e.httpOnly&&(o+="; HttpOnly"),e.secure&&(o+="; Secure"),e.partitioned&&(o+="; Partitioned"),e.priority)switch(typeof e.priority=="string"?e.priority.toLowerCase():void 0){case "low":o+="; Priority=Low";break;case "medium":o+="; Priority=Medium";break;case "high":o+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${e.priority}`)}if(e.sameSite)switch(typeof e.sameSite=="string"?e.sameSite.toLowerCase():e.sameSite){case true:case "strict":o+="; SameSite=Strict";break;case "lax":o+="; SameSite=Lax";break;case "none":o+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${e.sameSite}`)}return o}function Ne(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Ue(i){return $e.call(i)==="[object Date]"}});var re="0123456789ABCDEFGHJKMNPQRSTVWXYZ",E=32;var we=16,ne=10,te=0xffffffffffff;var I;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(I||(I={}));var M=class extends Error{constructor(t,e){super(`${e} (${t})`),this.name="ULIDError",this.code=t;}};function xe(i){let t=Math.floor(i()*E);return t===E&&(t=E-1),re.charAt(t)}function Se(i){var r;let t=Ie(),e=t&&(t.crypto||t.msCrypto)||(typeof C<"u"?C:null);if(typeof(e==null?void 0:e.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return e.getRandomValues(n),n[0]/255};if(typeof(e==null?void 0:e.randomBytes)=="function")return ()=>e.randomBytes(1).readUInt8()/255;if((r=C)!=null&&r.randomBytes)return ()=>C.randomBytes(1).readUInt8()/255;throw new M(I.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ie(){return Ee()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Me(i,t){let e="";for(;i>0;i--)e=xe(t)+e;return e}function ve(i,t=ne){if(isNaN(i))throw new M(I.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>te)throw new M(I.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${te}: ${i}`);if(i<0)throw new M(I.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new M(I.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let e,r="";for(let n=t;n>0;n--)e=i%E,r=re.charAt(e)+r,i=(i-e)/E;return r}function Ee(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ie(i,t){let e=Se(),r=Date.now();return ve(r,ne)+Me(we,e)}var D=()=>ie().toLowerCase();var P=(...i)=>{let t=i.filter(e=>!!e);return t.length===0?{}:t.length===1?t[0]:{$and:t}};var z=class{storage;queue=new Map;scheduled=false;constructor(t){this.storage=t;}async rawFind({resource:t,commonWhere:e,uniqueWhere:r,...n}){return new Promise((o,c)=>{let a=this.getBatchKey({resource:t,commonWhere:e,...n}),s={resource:t,commonWhere:e,uniqueWhere:r,...n,resolve:o,reject:c};this.queue.has(a)||this.queue.set(a,[]);let h=this.queue.get(a);h&&h.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(t){let{resource:e,commonWhere:r,...n}=t;return `${e}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let t=Array.from(this.queue.entries());this.queue.clear();for(let[,e]of t)try{await this.executeBatchedRequests(e);}catch(r){e.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(t){var p,u;if(t.length===0)return;let e=t[0],{resource:r,commonWhere:n,include:o,sort:c}=e,a=t.length===1?e.limit:void 0,s=t.map(f=>f.uniqueWhere).filter(f=>f!==void 0),h=n,y=(p=Object.entries(s[0]??{})[0])==null?void 0:p[0];if(s.length>0){let f=s.map(l=>l[y]).filter(l=>l!=null);f.length>0&&(h=P(n,{[y]:{$in:f}}));}let d=await this.storage.rawFind({resource:r,where:h,include:o,sort:c,limit:a});for(let f of t){let l={};if(f.uniqueWhere){let[m,T]=Object.entries(f.uniqueWhere)[0];for(let[b,w]of Object.entries(d))((u=w.value[m])==null?void 0:u.value)===T&&(l[b]=w);}else Object.assign(l,d);f.resolve(l);}}};var ue=b(_(),1);var U=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),F=z$1.record(z$1.string(),z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()).nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),We=F.superRefine((i,t)=>{i.id&&t.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),se=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),A=se.extend({procedure:z$1.string(),payload:z$1.any().optional()}),O=se.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:We});z$1.union([O,A]);var ce=U.omit({resource:true}),V=A.omit({id:true,type:true,resource:true,procedure:true}),q=O.omit({id:true,type:true,resource:true,procedure:true});z$1.union([q,V]);var de=i=>{let t=i.logger;return async e=>{var r;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,o={headers:n,cookies:n.cookie?ue.default.parse(n.cookie):{}},c=new URL(e.url),a=c.pathname.split("/"),s=c.searchParams,h=Be.parse(s.toString()),y=await((r=i.contextProvider)==null?void 0:r.call(i,{transport:"HTTP",headers:o.headers,cookies:o.cookies,queryParams:h}))??{};if(e.method==="GET"){let d=a[a.length-1],{success:p,data:u,error:f}=ce.safeParse(h);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:f},{status:400});let l=await i.handleQuery({req:{...o,...u,type:"QUERY",resource:d,context:y,queryParams:h}});return !l||!l.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(l.data)}if(e.method==="POST")try{let d=a[a.length-1],p=a[a.length-2],u=e.body?await e.json():{},f;if(d==="insert"||d==="update"){let{success:m,data:T,error:b}=q.safeParse(u);if(!m)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});f=T;}else {let{success:m,data:T,error:b}=V.safeParse(u);if(!m)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});f=T;}let l=await i.handleMutation({req:{...o,type:"MUTATE",resource:p,input:f.payload,context:y,resourceId:f.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{}}});return Response.json(l)}catch(d){return t.error("Error parsing mutation from the client:",d),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return t.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var me=b(_(),1);var v=z$1.string(),De=z$1.object({id:v,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),_e=U.extend({id:v,type:z$1.literal("QUERY")}),le=O.extend({id:v}),Fe=A.extend({id:v}),Ve=z$1.union([Fe,le]),pe=z$1.union([De,_e,Ve]),qe=z$1.object({id:v,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),Qe=z$1.object({id:v,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([qe,Qe,le]);z$1.object({resource:z$1.string(),data:z$1.record(z$1.string(),F)});var ye=i=>{let t={},e={},r=i.logger;return i.subscribeToMutations(n=>{let o=n;!o.resourceId||!o.payload||(r.debug("Mutation propagated:",o),Object.entries(e[o.resource]??{}).forEach(([c,a])=>{var s;(s=t[c])==null||s.send(JSON.stringify({...o,id:o.id??D()}));}));}),(n,o)=>{var d;let c=p=>{n.send(JSON.stringify(p));},a=D(),s={headers:o.headers,cookies:typeof o.headers.cookie=="string"?me.default.parse(o.headers.cookie):{}},h=parse(o.url.split("?")[1]),y=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:h});t[a]=n,r.info("Client connected:",a),n.on("message",async p=>{try{r.debug("Message received from the client:",p);let u=pe.parse(JSON.parse(p.toString()));if(u.type==="SUBSCRIBE"){let{resource:f}=u;e[f]||(e[f]={}),e[f][a]={};}else if(u.type==="QUERY"){let{resource:f}=u,l=await i.handleQuery({req:{...s,type:"QUERY",resource:f,context:await y??{},queryParams:h}});if(!l||!l.data)throw new Error("Invalid resource");c({id:u.id,type:"REPLY",data:{resource:f,data:Object.fromEntries(Object.entries(l.data??{}).map(([m,T])=>[m,T.value]))}});}else if(u.type==="MUTATE"){let{resource:f}=u;r.debug("Received mutation from client:",u);try{let l=await i.handleMutation({req:{...s,type:"MUTATE",resource:f,input:u.payload,context:{messageId:u.id,...await y??{}},resourceId:u.resourceId,procedure:u.procedure,queryParams:h}});u.procedure&&u.procedure!=="INSERT"&&u.procedure!=="UPDATE"&&c({id:u.id,type:"REPLY",data:l});}catch(l){c({id:u.id,type:"REJECT",resource:f,message:l.message}),r.error("Error parsing mutation from the client:",l);}}}catch(u){r.error("Error handling message from the client:",u);}}),n.on("close",()=>{r.info("Connection closed",a),delete t[a];for(let p of Object.values(e))delete p[a];});}};function fe(i){let t=`${i.protocol}://${i.hostname}${i.url}`,e=new Headers;return Object.entries(i.headers).forEach(([r,n])=>{n&&e.set(r,Array.isArray(n)?n.join(","):n);}),new Request(t,{method:i.method,headers:e,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Ot=(i,t,e)=>{i.ws(`${(e==null?void 0:e.basePath)??""}/ws`,ye(t)),i.use(`${(e==null?void 0:e.basePath)??""}/`,(r,n)=>{de(t)(fe(r)).then(c=>c.json().then(a=>n.status(c.status).send(a)));});};var Q=class i{routes;constructor(t){this.routes=t.routes;}static create(t){return new i(t)}},zt=i=>Q.create({...i}),He=i=>({handler:t=>({inputValidator:i??z$1.undefined(),handler:t})}),Z=class i{resourceSchema;middlewares;customMutations;authorization;constructor(t,e,r){this.resourceSchema=t,this.middlewares=new Set,this.customMutations=e??{},this.authorization=r;}use(...t){for(let e of t)this.middlewares.add(e);return this}withMutations(t){return new i(this.resourceSchema,t({mutation:He}),this.authorization)}handleQuery=async({req:t,batcher:e})=>await this.wrapInMiddlewares(async r=>{var o,c;let n=(c=(o=this.authorization)==null?void 0:o.read)==null?void 0:c.call(o,{ctx:r.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await e.rawFind({resource:r.resource,commonWhere:P(r.where,typeof n=="object"?n:void 0),uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort})}})(t);handleMutation=async({req:t,db:e,schema:r})=>await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let o=this.customMutations[n.procedure];if(o){let c=o.inputValidator.parse(n.input);return n.input=c,o.handler({req:n,db:e})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:e,operation:n.procedure,schema:r});throw new Error(`Unknown procedure: ${n.procedure}`)}})(t);handleSet=async({req:t$1,db:e,operation:r,schema:n})=>{if(!t$1.input)throw new Error("Payload is required");if(!t$1.resourceId)throw new Error("ResourceId is required");let o=await e.rawFindById(t$1.resource,t$1.resourceId);if(r==="INSERT"&&o)throw new Error("Resource already exists");if(r==="UPDATE"&&!o)throw new Error("Resource not found");return e.transaction(async({trx:c})=>{var y,d,p,u,f;let[a,s]=this.resourceSchema.mergeMutation("set",t$1.input,o);if(!s)throw new Error("Mutation rejected");if(r==="INSERT"){let l=await c.rawInsert(t$1.resource,t$1.resourceId,a),m=t(l);if(m.id=m.id??t$1.resourceId,(y=this.authorization)!=null&&y.insert){let T=this.authorization.insert({ctx:t$1.context,value:m});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let b=v$1(T,t$1.resource,n),w$1=Object.keys(b).length>0?await c.rawFindById(t$1.resource,t$1.resourceId,b):l,S=t(w$1);if(S.id=S.id??t$1.resourceId,!w(S,T))throw new Error("Not authorized")}}return {data:l,acceptedValues:s}}if((p=(d=this.authorization)==null?void 0:d.update)!=null&&p.preMutation){let l=t(o);l.id=l.id??t$1.resourceId;let m=this.authorization.update.preMutation({ctx:t$1.context,value:l});if(typeof m=="boolean"){if(!m)throw new Error("Not authorized")}else {let T=v$1(m,t$1.resource,n),b=Object.keys(T).length>0?await c.rawFindById(t$1.resource,t$1.resourceId,T):o,w$1=t(b);if(w$1.id=w$1.id??t$1.resourceId,!w(w$1,m))throw new Error("Not authorized")}}let h=await c.rawUpdate(t$1.resource,t$1.resourceId,a);if((f=(u=this.authorization)==null?void 0:u.update)!=null&&f.postMutation){let l=t(h);l.id=l.id??t$1.resourceId;let m=this.authorization.update.postMutation({ctx:t$1.context,value:l});if(typeof m=="boolean"){if(!m)throw new Error("Not authorized")}else {let T=v$1(m,t$1.resource,n),b=Object.keys(T).length>0?await c.rawFindById(t$1.resource,t$1.resourceId,T):h,w$1=t(b);if(w$1.id=w$1.id??t$1.resourceId,!w(w$1,m))throw new Error("Not authorized")}}return {data:h,acceptedValues:s}})};wrapInMiddlewares(t){return e=>Array.from(this.middlewares.values()).reduceRight((r,n)=>o=>n({req:o,next:r}),t)(e)}},G=class i{middlewares;constructor(t=[]){this.middlewares=t;}collectionRoute(t,e){return new Z(t,void 0,e).use(...this.middlewares)}use(...t){return new i([...this.middlewares,...t])}static create(){return new i}},Nt=G.create;var j=class{async insert(t$1,e){let r=new Date().toISOString();return t(await this.rawInsert(t$1.name,e.id,{value:Object.fromEntries(Object.entries(e).map(([n,o])=>[n,{value:o,_meta:{timestamp:r}}]))}))}async update(t$1,e,r){let n=new Date().toISOString(),{id:o,...c}=r;return t(await this.rawUpdate(t$1.name,e,{value:Object.fromEntries(Object.entries(c).map(([a,s])=>[a,{value:s,_meta:{timestamp:n}}]))}))}};function W(i,t,e,r){if(!i)throw new Error("Schema not initialized");let n=i[t];if(!n)throw new Error("Resource not found");let o=r.$or,c=r.$and;return (o?e.or:e.and)(o?r.$or.map(a=>W(i,t,e,a)):c?r.$and.map(a=>W(i,t,e,a)):Object.entries(r).map(([a,s])=>{var h,y;if(n.fields[a])return (s==null?void 0:s.$eq)!==void 0?e(`${t}.${a}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?e(`${t}.${a}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((h=s==null?void 0:s.$not)==null?void 0:h.$in)!==void 0?e(`${t}.${a}`,"not in",s.$not.$in):((y=s==null?void 0:s.$not)==null?void 0:y.$eq)!==void 0?e(`${t}.${a}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):e(`${t}.${a}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?e(`${t}.${a}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?e(`${t}.${a}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?e(`${t}.${a}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?e(`${t}.${a}`,"<=",s.$lte):e(`${t}.${a}`,s===null?"is":"=",s);if(n.relations[a]){let d=n.relations[a],p=d.entity.name;return d.type==="many"?e.exists(H(i,p,e.selectFrom(p).select("id").whereRef(d.foreignColumn,"=",`${t}.id`),s)):W(i,p,e,s)}return null}).filter(Boolean))}function k(i,t,e,r){let n=i[t];if(!n)throw new Error("Resource not found");if(!r)return e;if(r.$and){for(let o of r.$and)e=k(i,t,e,o);return e}else if(r.$or){for(let o of r.$or)e=k(i,t,e,o);return e}for(let[o,c]of Object.entries(r)){if(!n.relations[o])continue;let a=n.relations[o],s=a.entity.name,h=a.type==="one"?"id":a.foreignColumn,y=a.type==="one"?a.relationalColumn:"id";e=e.leftJoin(s,`${s}.${h}`,`${t}.${y}`),c instanceof Object&&!Array.isArray(c)&&c!==null&&(e=k(i,s,e,c));}return e}function H(i,t,e,r){return !r||Object.keys(r).length===0?e:(e=k(i,t,e,r),e.where(n=>W(i,t,n,r)))}function B(i,t,e,r){if(!r)return e;if(!i)throw new Error("Schema not initialized");let n=i[t];if(!n)throw new Error(`Resource not found: ${t}`);for(let o of Object.keys(r)){if(!n.relations[o])throw new Error(`Relation ${o} not found in resource ${t}`);let c=n.relations[o],a=c.entity.name,s=r[o],h=c.type==="one"?"id":c.foreignColumn,y=c.type==="one"?c.relationalColumn:"id",d=c.type==="one"?jsonObjectFrom:jsonArrayFrom,p=typeof s=="object"&&s!==null;e=e.select(u=>{let f=u.selectFrom(a).selectAll(a).whereRef(`${a}.${h}`,"=",`${t}.${y}`).select(l=>jsonObjectFrom(l.selectFrom(`${a}_meta`).selectAll(`${a}_meta`).whereRef(`${a}_meta.id`,"=",`${a}.id`)).as("_meta"));return p&&(f=B(i,a,f,s)),d(f).as(o)});}return e}var K=class i extends j{db;schema;logger;constructor(t,e,r){super(),this.isKyselyLike(t)?this.db=t:this.db=new Kysely({dialect:new PostgresDialect({pool:t})}),this.schema=e,this.logger=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(t,e){var n;this.schema=t,this.logger=e;let r=await this.db.introspection.getTables();for(let[o,c]of Object.entries(t)){let a=r.find(y=>y.name===o);a||await this.db.schema.createTable(o).ifNotExists().execute();let s=`${o}_meta`,h=r.find(y=>y.name===s);h||await this.db.schema.createTable(s).ifNotExists().execute();for(let[y,d]of Object.entries(c.fields)){let p=a==null?void 0:a.columns.find(l=>l.name===y),u=d.getStorageFieldType();p?p.dataType!==u.type&&((n=this.logger)==null||n.warn("Column type mismatch:",y,"expected to have type:",u.type,"but has type:",p.dataType)):(await this.db.schema.alterTable(o).addColumn(y,u.type,l=>{let m=l;return u.unique&&(m=m.unique()),u.nullable||(m=m.notNull()),u.references&&(m=m.references(u.references)),u.primary&&(m=m.primaryKey()),u.default!==void 0&&(m=m.defaultTo(u.default)),m}).execute().catch(l=>{var m;throw (m=this.logger)==null||m.error("Error adding column",y,l),l}),u.index&&await this.db.schema.createIndex(`${o}_${y}_index`).on(o).column(y).execute().catch(()=>{})),(h==null?void 0:h.columns.find(l=>l.name===y))||await this.db.schema.alterTable(s).addColumn(y,"varchar",l=>{let m=l;return u.primary&&(m=m.primaryKey().references(`${o}.${y}`)),m}).execute();}}}async rawFindById(t,e,r){if(!this.schema)throw new Error("Schema not initialized");let n=await this.db.selectFrom(t).where("id","=",e).selectAll(t).select(c=>jsonObjectFrom(c.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));n=B(this.schema,t,n,r);let o=await n.executeTakeFirst();if(o)return this.convertToMaterializedLiveType(o)}async findOne(t$1,e,r){let n=await this.rawFindById(t$1.name,e,r==null?void 0:r.include);if(n)return t(n)}async rawFind(t){if(!this.schema)throw new Error("Schema not initialized");let{resource:e,where:r,include:n,limit:o,sort:c}=t,a=this.db.selectFrom(e).selectAll(e).select(d=>jsonObjectFrom(d.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));a=H(this.schema,e,a,r),a=B(this.schema,e,a,n),o!==void 0&&(a=a.limit(o)),c!==void 0&&c.forEach(d=>{a=a.orderBy(d.key,d.direction);});let s=await a.execute(),h=Object.fromEntries(s.map(d=>{let{id:p}=d;return [p,d]}));return Object.keys(h).length===0?{}:Object.entries(h).reduce((d,[p,u])=>(d[p]=this.convertToMaterializedLiveType(u),d),{})}async find(t$1,e){let r=await this.rawFind({resource:t$1.name,where:e==null?void 0:e.where,include:e==null?void 0:e.include,limit:e==null?void 0:e.limit,sort:e==null?void 0:e.sort});return Object.fromEntries(Object.entries(r).map(([n,o])=>[n,t(o)]))}async rawInsert(t,e,r){var c;let n={},o={};for(let[a,s]of Object.entries(r.value)){let h=(c=s._meta)==null?void 0:c.timestamp;h&&(n[a]=s.value,o[a]=h);}return await this.db.insertInto(t).values({...n,id:e}).execute().then(()=>{this.db.insertInto(`${t}_meta`).values({...o,id:e}).execute();}),r}async rawUpdate(t,e,r){var c;let n={},o={};for(let[a,s]of Object.entries(r.value)){let h=(c=s._meta)==null?void 0:c.timestamp;h&&(n[a]=s.value,o[a]=h);}return await Promise.all([this.db.updateTable(t).set(n).where("id","=",e).execute(),this.db.insertInto(`${t}_meta`).values({...o,id:e}).onConflict(a=>a.column("id").doUpdateSet(o)).execute()]),r}async transaction(t){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let r=Math.random().toString(36).substring(2,15),n=await this.db.savepoint(r).execute();try{return await t({trx:this,commit:()=>n.releaseSavepoint(r).execute().then(()=>{}),rollback:()=>n.rollbackToSavepoint(r).execute().then(()=>{})}).then(o=>n.isCommitted||n.isRolledBack?o:n.releaseSavepoint(r).execute().then(()=>o))}catch(o){throw await n.rollbackToSavepoint(r).execute().catch(()=>{}),o}}let e=await this.db.startTransaction().execute();try{return await t({trx:new i(e,this.schema,this.logger),commit:()=>e.commit().execute(),rollback:()=>e.rollback().execute()}).then(r=>e.isCommitted||e.isRolledBack?r:e.commit().execute().then(()=>r))}catch(r){throw await e.rollback().execute(),r}}convertToMaterializedLiveType(t){return {value:Object.entries(t).reduce((e,[r,n])=>{var o,c,a;return r==="_meta"||(r==="id"?e[r]={value:n}:Array.isArray(n)?e[r]={value:n.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(o=t==null?void 0:t._meta)==null?void 0:o[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?e[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(c=t==null?void 0:t._meta)==null?void 0:c[r]}}:e[r]={value:n,_meta:{timestamp:(a=t==null?void 0:t._meta)==null?void 0:a[r]}}),e},{})}}isKyselyLike(t){if(t instanceof Kysely)return true;if(!t||typeof t!="object")return false;let e=t,r=typeof e.selectFrom=="function",n=typeof e.startTransaction=="function",o=typeof e.savepoint=="function",c=typeof e.isTransaction=="boolean"||typeof e.isTransaction=="function";return r&&n||o&&c}};var J=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;mutationSubscriptions=new Set;constructor(t){var e;this.router=t.router,this.storage=t.storage,this.schema=t.schema,this.logger=y({level:t.logLevel??x.INFO}),(e=t.middlewares)==null||e.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger),this.contextProvider=t.contextProvider;}static create(t){return new i(t)}subscribeToMutations(t){return this.mutationSubscriptions.add(t),()=>{this.mutationSubscriptions.delete(t);}}handleQuery(t){let e=new z(this.storage);return this.wrapInMiddlewares(async r=>{var h;let n=Re(r,this.schema,{stepId:"query",collectionName:r.resource,included:Object.keys(r.include??{})}),o={headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context},c={};for(let y=0;y<n.length;y++){let d=n[y],p=this.router.routes[d.resource];if(!p)throw new Error("Invalid resource");let u=d.getWhere&&d.referenceGetter?d.referenceGetter(c).map(d.getWhere):[void 0],f=(h=c[d.prevStepId??""])==null?void 0:h.flatMap(T=>{var b;return Object.keys(((b=T==null?void 0:T.result)==null?void 0:b.data)??{})}),m=(await Promise.allSettled(u.map(async(T,b)=>{let w=f==null?void 0:f[b],S=await p.handleQuery({req:{type:"QUERY",...d,...o,where:d.where,relationalWhere:T},batcher:e});return {includedBy:w,result:S}}))).flatMap(T=>T.status==="fulfilled"?[T.value]:[]);c[d.stepId]=m;}let a=Object.fromEntries(Object.entries(c).flatMap(([y,d],p)=>d.flatMap(u=>Object.entries(u.result.data).map(([f,l])=>[`${y}.${f}`,{data:l,includedBy:y!=="query"&&u.includedBy?`${y.split(".").slice(0,-1).join(".")}.${u.includedBy}`:void 0,path:y.split(".").slice(-1)[0],isMany:n[p].isMany,collectionName:n[p].collectionName,included:n[p].included}]))));return Object.keys(a).reduceRight((y,d)=>{var f,l;let p=a[d],u=p.path;if(u==="query"&&(y.data[d.replace("query.","")]=p.data),p.included.length)for(let m of p.included)p.data.value[m]??=((l=(f=this.schema[p.collectionName])==null?void 0:f.relations[m])==null?void 0:l.type)==="many"?{value:[]}:{value:null};if(p.includedBy){let m=a[p.includedBy];if(!m)return y;p.isMany?(m.data.value[u]??={value:[]},m.data.value[u].value.push(p.data)):m.data.value[u]=p.data;}return y},{data:{}})})(t.req)}async handleMutation(t){let e=await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(t.req);if(e&&t.req.type==="MUTATE"&&e.acceptedValues&&(t.req.procedure==="INSERT"||t.req.procedure==="UPDATE")&&t.req.resourceId){let n=e.acceptedValues??{},o=t.req,c=o.resourceId;Object.keys(n).length&&c&&this.mutationSubscriptions.forEach(a=>{a({id:t.req.context.messageId,type:"MUTATE",resource:o.resource,payload:n,resourceId:c,procedure:o.procedure});});}return e}use(t){return this.middlewares.add(t),this}context(t){return this.contextProvider=t,this}wrapInMiddlewares(t){return e=>Array.from(this.middlewares.values()).reduceRight((r,n)=>o=>n({req:o,next:r}),t)(e)}},Xt=J.create;function Re(i,t,e){let{include:r,where:n,...o}=i,{stepId:c}=e,a=[{...o,...e,where:n}];if(r&&typeof r=="object"&&Object.keys(r).length>0){let s=t[o.resource];if(!s)throw new Error(`Resource ${o.resource} not found`);a.push(...Object.entries(r).flatMap(([h,y])=>{let d=s.relations[h];if(!d)throw new Error(`Relation ${h} not found for resource ${o.resource}`);let p=d.entity.name;return Re({...o,resource:p,include:y},t,{getWhere:d.type==="one"?u=>({id:u}):u=>({[d.foreignColumn]:u}),referenceGetter:u=>u[c].flatMap(f=>f.result.data?d.type==="one"?Object.values(f.result.data).map(l=>{var m,T;return (T=(m=l.value)==null?void 0:m[d.relationalColumn])==null?void 0:T.value}):Object.keys(f.result.data):[]),stepId:`${c}.${h}`,prevStepId:c,isMany:d.type==="many",collectionName:p,included:typeof y=="object"?Object.keys(y):[]})}));}return a}
2
- export{Z as Route,G as RouteFactory,Q as Router,K as SQLStorage,J as Server,j as Storage,Ot as expressAdapter,Nt as routeFactory,zt as router,Xt as server};
1
+ import {a,b,v,t,w,x,z as z$2,y}from'./chunk-IT5UC7TA.js';import B from'crypto';import et,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect,sql}from'kysely';import {jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from'kysely/helpers/mysql';import {jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from'kysely/helpers/postgres';import {jsonArrayFrom,jsonObjectFrom}from'kysely/helpers/sqlite';var X=a(_=>{Object.defineProperty(_,"__esModule",{value:true});_.parse=Ke;_.serialize=Je;var Be=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Ue=/^[\u0021-\u003A\u003C-\u007E]*$/,We=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,He=/^[\u0020-\u003A\u003D-\u007E]*$/,Ve=Object.prototype.toString,_e=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function Ke(c,e){let t=new _e,n=c.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Ge,i=0;do{let o=c.indexOf("=",i);if(o===-1)break;let a=c.indexOf(";",i),s=a===-1?n:a;if(o>s){i=c.lastIndexOf(";",o-1)+1;continue}let u=be(c,i,o),d=Te(c,o,u),l=c.slice(u,d);if(t[l]===void 0){let h=be(c,o+1,s),y=Te(c,s,h),p=r(c.slice(h,y));t[l]=p;}i=s+1;}while(i<n);return t}function be(c,e,t){do{let n=c.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function Te(c,e,t){for(;e>t;){let n=c.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Je(c,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Be.test(c))throw new TypeError(`argument name is invalid: ${c}`);let r=n(e);if(!Ue.test(r))throw new TypeError(`argument val is invalid: ${e}`);let i=c+"="+r;if(!t)return i;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);i+="; Max-Age="+t.maxAge;}if(t.domain){if(!We.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);i+="; Domain="+t.domain;}if(t.path){if(!He.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);i+="; Path="+t.path;}if(t.expires){if(!Ze(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);i+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(i+="; HttpOnly"),t.secure&&(i+="; Secure"),t.partitioned&&(i+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":i+="; Priority=Low";break;case "medium":i+="; Priority=Medium";break;case "high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":i+="; SameSite=Strict";break;case "lax":i+="; SameSite=Lax";break;case "none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return i}function Ge(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function Ze(c){return Ve.call(c)==="[object Date]"}});var pe="0123456789ABCDEFGHJKMNPQRSTVWXYZ",z=32;var $e=16,me=10,fe=0xffffffffffff;var A;(function(c){c.Base32IncorrectEncoding="B32_ENC_INVALID",c.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",c.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",c.EncodeTimeNegative="ENC_TIME_NEG",c.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",c.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",c.PRNGDetectFailure="PRNG_DETECT",c.ULIDInvalid="ULID_INVALID",c.Unexpected="UNEXPECTED",c.UUIDInvalid="UUID_INVALID";})(A||(A={}));var O=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function ze(c){let e=Math.floor(c()*z);return e===z&&(e=z-1),pe.charAt(e)}function ke(c){var n;let e=Qe(),t=e&&(e.crypto||e.msCrypto)||(typeof B<"u"?B:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=B)!=null&&n.randomBytes)return ()=>B.randomBytes(1).readUInt8()/255;throw new O(A.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Qe(){return De()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function qe(c,e){let t="";for(;c>0;c--)t=ze(e)+t;return t}function Fe(c,e=me){if(isNaN(c))throw new O(A.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>fe)throw new O(A.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${fe}: ${c}`);if(c<0)throw new O(A.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new O(A.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,n="";for(let r=e;r>0;r--)t=c%z,n=pe.charAt(t)+n,c=(c-t)/z;return n}function De(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ge(c,e){let t=ke(),n=Date.now();return Fe(n,me)+qe($e,t)}var W=()=>ge().toLowerCase(),U=c=>({then(e,t){try{if(e){let n=e(c);return n instanceof Promise?n:U(n)}return U(c)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:U(r)}throw n}}}),Z=c=>c instanceof Promise?c:U(c);var N=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var H=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((i,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...r}),s={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:i,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:i,sort:o}=t,a=e.length===1?t.limit:void 0,s=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),u=r,d=(h=Object.entries(s[0]??{})[0])==null?void 0:h[0];if(s.length>0){let y=s.map(p=>p[d]).filter(p=>p!=null);y.length>0&&(u=N(r,{[d]:{$in:y}}));}let l=await this.storage.get({resource:n,where:u,include:i,sort:o,limit:a});for(let y of e){let p=l;if(y.uniqueWhere){let[f,b]=Object.entries(y.uniqueWhere)[0];p=l.filter(g=>{var m;return ((m=g.value[f])==null?void 0:m.value)===b});}y.resolve(p);}}};function Y(c){return v({resource:c.query.resource,where:c.query.where,include:c.query.include,stepPath:c.stepPath,isMany:c.isMany,relationName:c.relationName})}var V=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,i]of Object.entries(n.relations))i.type==="one"&&i.relationalColumn&&t.set(String(i.relationalColumn),{relationName:r,targetResource:i.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let i=this.objectNodes.get(e),o=this.objectNodes.get(t);if(i&&i.referencesObjects.set(n,t),o&&r){let a=o.referencedByObjects.get(r);a||(a=new Set,o.referencedByObjects.set(r,a)),a.add(e);}}removeRelation(e,t,n,r){let i=this.objectNodes.get(e),o=this.objectNodes.get(t);if(i&&i.referencesObjects.delete(n),o&&r){let a=o.referencedByObjects.get(r);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let i=r.relations[n];if(!i)return;let o=this.schema[t];if(o!=null&&o.relations){if(i.type==="many"&&i.foreignColumn){for(let[a,s]of Object.entries(o.relations))if(s.entity.name===e&&s.type==="one"&&s.relationalColumn===i.foreignColumn)return a}if(i.type==="one"&&i.relationalColumn){for(let[a,s]of Object.entries(o.relations))if(s.entity.name===e&&s.type==="many"&&s.foreignColumn===i.relationalColumn)return a}}}updateRelationsFromMutation(e,t,n,r){let i=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:s,targetResource:u}]of Array.from(i)){if(!(r&&a in r))continue;let l=this.getInverseRelationName(e,u,s),h=o.referencesObjects.get(s),y=n[a];h!==y&&(h&&this.removeRelation(t,h,s,l),y&&(this.ensureObjectNode(y,u),this.storeRelation(t,y,s,l)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new H(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),i={},o=[];for(let a of r){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let s=Y(a),u=i[a.stepPath.at(-2)??""],d=a.stepPath.at(-1)??"",l=this.queryNodes.get(s);if(l)l.subscriptions.add(t);else if(l={hash:s,queryStep:a,relationName:d,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:u,childQueries:new Set},this.queryNodes.set(l.hash,l),u){let h=this.queryNodes.get(u);h&&h.childQueries.add(l.hash);}i[d]=s,o.push(()=>{let h=this.queryNodes.get(s);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(s));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var b;let{query:t,stepPath:n=[],context:r={},parentResource:i}=e,{include:o}=t,a=n.length===0,s=n.at(-1),u,d,l;if(!a&&i&&s){let g=this.schema[i],m=(b=g==null?void 0:g.relations)==null?void 0:b[s];m&&(l=m.type==="many",m.type==="one"?(u=T=>({id:T}),d=T=>T.map(S=>{var w,M;return (M=(w=S.value)==null?void 0:w[m.relationalColumn])==null?void 0:M.value}).filter(S=>S!==void 0)):(u=T=>({[m.foreignColumn]:T}),d=T=>T.map(S=>{var w,M;return (M=(w=S.value)==null?void 0:w.id)==null?void 0:M.value}).filter(S=>S!==void 0)));}let{include:h,...y}=t,f=[this.router.incrementQueryStep({query:y,stepPath:[...n],getWhere:u,referenceGetter:d,isMany:l,relationName:s},r)];if(o&&typeof o=="object"&&Object.keys(o).length>0){let g=this.schema[t.resource];if(!g)throw new Error(`Resource ${t.resource} not found`);f.push(...Object.entries(o).flatMap(([m,T])=>{let S=g.relations[m];if(!S)throw new Error(`Relation ${m} not found for resource ${t.resource}`);let w=S.entity.name;return this.breakdownQuery({query:{resource:w,include:typeof T=="object"?T:void 0},stepPath:[...n,m],context:r,parentResource:t.resource})}));}return f}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(i=>i.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(i=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",i.length),n[e[0].stepPath.join(".")]=[{data:i}];});for(let i=1;i<e.length;i++){let o=e[i],a=o.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var u,d;let s=n[a];if(!s){n[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let l=new Map;for(let p of s)for(let f of p.data){let b=(d=(u=f==null?void 0:f.value)==null?void 0:u.id)==null?void 0:d.value;if(!b)continue;let m=o.referenceGetter([f])[0];if(m){l.has(m)||l.set(m,new Set);let T=l.get(m);T&&T.add(b);}}let h=Array.from(l.keys());if(h.length===0){n[o.stepPath.join(".")]=[];return}let y=[];for(let p of h){let f=o.getWhere(p),b={...o,relationalWhere:f},g=await this.resolveStep(b,t),m=l.get(p);if(m)for(let T of Array.from(m))y.push({includedBy:T,data:g});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",y.reduce((p,f)=>p+f.data.length,0)),n[o.stepPath.join(".")]=y;}else {let l=await this.resolveStep(o,t);n[o.stepPath.join(".")]=[{data:l}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var o,a,s,u,d;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let n=new Map;for(let l of e){let h=l.stepPath.join("."),y=t[h]??[],p=Object.keys(l.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:l.query.resource,includedRelations:p,resultGroups:y.length,isMany:l.isMany,relationName:l.relationName});for(let f of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:f.data.length,includedBy:f.includedBy});for(let b of f.data){let g=(a=(o=b==null?void 0:b.value)==null?void 0:o.id)==null?void 0:a.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${h}"`);continue}let m=h?`${h}.${g}`:g,T=[];if(l.stepPath.length>0&&f.includedBy){let w=l.stepPath.slice(0,-1).join(".");T=[w?`${w}.${f.includedBy}`:f.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${m}" has parent keys:`,T,{stepPath:h,parentStepPath:w,includedBy:f.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${m}" (no parent)`);let S=n.get(m);if(S){this.logger.debug(`[QueryEngine] assembleResults: Entity "${m}" already exists, adding parent keys:`,T);for(let w of T)S.includedBy.add(w);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${m}"`,{resource:l.query.resource,path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,includedRelations:p,parentKeys:T}),n.set(m,{data:b,includedBy:new Set(T),path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,resourceName:l.query.resource,includedRelations:p});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),i=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let l=r.length-1;l>=0;l--){let[h,y]=r[l],p=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${h}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let f of y.includedRelations){let b=(u=(s=p==null?void 0:p.relations)==null?void 0:s[f])==null?void 0:u.type,g=!!y.data.value[f];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${f}" for "${h}"`,{relationType:b,hasRelation:g,resourceHasRelation:!!((d=p==null?void 0:p.relations)!=null&&d[f])}),y.data.value[f])this.logger.debug(`[QueryEngine] assembleResults: Relation "${f}" already exists for "${h}"`,y.data.value[f]);else {let m=b==="many"?{value:[]}:{value:null};y.data.value[f]=m,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${f}" for "${h}" with`,m);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${h}" to resultData`),i.push(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to ${y.includedBy.size} parent(s)`);for(let f of Array.from(y.includedBy)){let b=n.get(f);if(!b){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${f}" not found in entriesMap for child "${h}"`);continue}let g=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${f}" via relation "${g}"`,{isMany:y.isMany,parentHasRelation:!!b.data.value[g]}),y.isMany?(b.data.value[g]??={value:[]},b.data.value[g].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${g}" on parent "${f}"`,{arrayLength:b.data.value[g].value.length})):(b.data.value[g]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${f}" to "${h}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${i.length} root items`),i}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:n,relationalWhere:r}=e,i=n.where&&r?N(n.where,r):r??n.where,o=i?{...n,where:i}:n;return Z(this.router.get(o,t)).then(a=>(this.loadStepResults(e,a),a))}loadStepResults(e,t$1){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t$1,null,2));let n=Y(e),r=this.queryNodes.get(n),i=e.query.resource;if(!r)return;let o=this.getRelationalColumns(i);for(let a of t$1){let s=t(a),u=s.id;this.ensureObjectNode(u,i,n),r.trackedObjects.add(u);for(let[d,{relationName:l,targetResource:h}]of Array.from(o)){let y=s[d];if(y){this.ensureObjectNode(y,h);let p=this.getInverseRelationName(i,h,l);this.storeRelation(u,y,l,p);}}this.loadNestedRelations(i,u,s),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[i,o]of Object.entries(r.relations)){let a=n[i];if(!a)continue;let s=o.entity.name,u=this.getInverseRelationName(e,s,i);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,s),this.storeRelation(t,a.id,i,u),this.loadNestedRelations(s,a.id,a));else if(o.type==="many"&&Array.isArray(a)){for(let d of a)if(d&&typeof d=="object"&&d.id){this.ensureObjectNode(d.id,s);let l=this.getInverseRelationName(s,e,i);l&&this.storeRelation(d.id,t,l,i),this.loadNestedRelations(s,d.id,d);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let i=this.queryNodes.get(r);if(!i||!i.relationName)continue;let o=this.buildIncludeFromChildQueries(r);n[i.relationName]=Object.keys(o).length>0?o:true;}return n}sendInsertsForTree(e,t,n){var a,s;let r=(s=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:s.value;if(!r)return;let i={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let u of Array.from(e.subscriptions))try{u(i);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let u of Array.from(e.childQueries)){let d=this.queryNodes.get(u);if(!d||!d.relationName)continue;let l=d.relationName,h=d.queryStep.query.resource,y=t.value[l];if(!y)continue;let p=y.value;if(Array.isArray(p))for(let f of p)this.sendInsertsForTree(d,f,h);else p&&typeof p=="object"&&this.sendInsertsForTree(d,p,h);}}handleMutation(e,t$1){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=t(t$1);if(!n)return;let r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,r);let i=this.getRelationalColumns(e.resource);for(let[a,{relationName:s,targetResource:u}]of Array.from(i)){let d=n[a];if(d){this.ensureObjectNode(d,u);let l=this.getInverseRelationName(e.resource,u,s);this.storeRelation(e.resourceId,d,s,l);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(a=>{for(let s of a){let u=this.queryNodes.get(s);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(s);for(let d of Array.from(u.subscriptions))try{d(e);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:l,queryHash:u.hash,resource:e.resource,resourceId:e.resourceId,stepPath:u.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=t(t$1);if(!n)return;let r=this.objectNodes.get(e.resourceId),i=new Set((r==null?void 0:r.matchedQueries)??[]);r||(r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,r)),this.updateRelationsFromMutation(e.resource,e.resourceId,n,e.payload),this.getMatchingQueries(e,n).then(o=>{let a=new Set(o),s=[],u=[],d=[];for(let h of o)i.has(h)?d.push(h):s.push(h);for(let h of Array.from(i))a.has(h)||u.push(h);for(let h of s){let y=this.queryNodes.get(h);y&&y.trackedObjects.add(e.resourceId);}for(let h of u){let y=this.queryNodes.get(h);y&&y.trackedObjects.delete(e.resourceId);}let l=this.objectNodes.get(e.resourceId);if(l){for(let h of s)l.matchedQueries.add(h);for(let h of u)l.matchedQueries.delete(h);}for(let h of [...u,...d]){let y=this.queryNodes.get(h);if(y)for(let p of Array.from(y.subscriptions))try{p(e);}catch(f){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:f,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(s.length>0)for(let h of s){let y=this.queryNodes.get(h);if(!y)continue;let p=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(p).length>0?p:void 0}).then(f=>{!f||f.length===0||this.sendInsertsForTree(y,f[0],e.resource);});}});return}}getMatchingQueries(e,t$1){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?Z([]):Promise.all(n.map(async r=>{let i=r.queryStep.query.where,o=r.queryStep.query.resource,a=e.resourceId,s=this.objectNodes.get(a);if(!s)return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,p=y==null?void 0:y.queryStep.query.resource,f=p?this.getInverseRelationName(p,o,r.relationName):void 0,b=f?s.referencesObjects.get(f):void 0;if(!b)return {hash:r.hash,matches:false};let g=this.objectNodes.get(b);return !g||!y||!g.matchedQueries.has(y.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!i)return {hash:r.hash,matches:true};let u=w(i,o,this.schema),d=Object.keys(u).length>0;if(!d&&t$1!==void 0)return {hash:r.hash,matches:x(t$1,i)};let l=await this.storage.get({resource:o,where:{id:a},include:d?u:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let h=t(l[0]);return h?{hash:r.hash,matches:x(h,i)}:{hash:r.hash,matches:false}})).then(r=>r.filter(i=>i.matches).map(i=>i.hash))}};var we=b(X(),1);var C=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),ee=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),Ye=ee.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Re=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),k=Re.extend({procedure:z$1.string(),payload:z$1.any().optional()}),Q=Re.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:Ye});z$1.union([Q,k]);var Se=C.omit({resource:true}),te=k.omit({id:true,type:true,resource:true,procedure:true}),re=Q.omit({id:true,type:true,resource:true,procedure:true});z$1.union([re,te]);var ne=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(ne);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,n]of Object.entries(c))e[t]=ne(n);return e}return c},ve=c=>{let e=c.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,i={headers:r,cookies:r.cookie?we.default.parse(r.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),s=o.searchParams,u=ne(et.parse(s.toString())),d=await((n=c.contextProvider)==null?void 0:n.call(c,{transport:"HTTP",headers:i.headers,cookies:i.cookies,queryParams:u}))??{};if(t.method==="GET"){let l=a[a.length-1],{success:h,data:y,error:p}=Se.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let f=await c.handleQuery({req:{...i,...y,type:"QUERY",resource:l,context:d,queryParams:u}});return !f||!f.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(f.data)}if(t.method==="POST")try{let l=a[a.length-1],h=a[a.length-2],y=t.body?await t.json():{},p;if(l==="insert"||l==="update"){let{success:b,data:g,error:m}=re.safeParse(y);if(!b)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:m},{status:400});p=g;}else {let{success:b,data:g,error:m}=te.safeParse(y);if(!b)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:m},{status:400});p=g;}let f=await c.handleMutation({req:{...i,type:"MUTATE",resource:h,input:p.payload,context:d,resourceId:p.resourceId,procedure:l==="insert"||l==="update"?l.toUpperCase():l,queryParams:{}}});return Response.json(f)}catch(l){return e.error("Error parsing mutation from the client:",l),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var Ie=b(X(),1);var E=z$1.string(),tt=C.extend({id:E,type:z$1.literal("SUBSCRIBE")}),rt=C.extend({id:E,type:z$1.literal("UNSUBSCRIBE")}),nt=C.extend({id:E,type:z$1.literal("QUERY")}),xe=Q.extend({id:E}),st=k.extend({id:E}),it=z$1.union([st,xe]),Me=z$1.union([tt,nt,it,rt]),ot=z$1.object({id:E,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),at=z$1.object({id:E,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([ot,at,xe]);z$1.object({resource:z$1.string(),data:z$1.array(ee)});var je=c=>{let e={},t=c.logger;return (n,r)=>{var l;let i=h=>{n.send(JSON.stringify(h));},o=W(),a=new Map,s={headers:r.headers,cookies:typeof r.headers.cookie=="string"?Ie.default.parse(r.headers.cookie):{}},u=parse(r.url.split("?")[1]),d=(l=c.contextProvider)==null?void 0:l.call(c,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:u});e[o]=n,t.info("Client connected:",o),n.on("message",async h=>{try{t.debug("Message received from the client:",h);let y=Me.parse(JSON.parse(h.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:p,id:f,...b}=y,g=p==="SUBSCRIBE",m=await c.handleQuery({req:{...s,...b,type:"QUERY",context:await d??{},queryParams:u},subscription:g?T=>{var S;!T.resourceId||!T.payload||!Object.keys(T.payload).length||(S=e[o])==null||S.send(JSON.stringify(T));}:void 0});if(!m||!m.data)throw new Error("Invalid resource");g&&m.unsubscribe&&a.set(v(b),m.unsubscribe),i({id:f,type:"REPLY",data:{resource:b.resource,data:(m.data??[]).map(T=>T.value)}});}else if(y.type==="UNSUBSCRIBE"){let{type:p,id:f,...b}=y,g=a.get(v(b));g&&(g(),a.delete(v(b)));}else if(y.type==="MUTATE"){let{resource:p}=y;t.debug("Received mutation from client:",y);try{let f=await c.handleMutation({req:{...s,type:"MUTATE",resource:p,input:y.payload,context:{messageId:y.id,...await d??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:u}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&i({id:y.id,type:"REPLY",data:f});}catch(f){i({id:y.id,type:"REJECT",resource:p,message:f.message}),t.error("Error parsing mutation from the client:",f);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let h of Array.from(a.values()))h();});}};function Ae(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var pr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,je(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{ve(e)(Ae(n)).then(o=>o.json().then(a=>r.status(o.status).send(a)));});};var se=class c{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){let n=t;n.hooks&&this.hooksRegistry.set(n.resourceSchema.name,n.hooks);}}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}},Rr=c=>se.create({...c}),lt=(c=>({handler:e=>({inputValidator:c??z$1.undefined(),handler:e})})),ie=class c{resourceSchema;middlewares;customMutations;authorization;hooks;constructor(e,t,n,r){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n,this.hooks=r;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new c(this.resourceSchema,e({mutation:lt}),this.authorization,this.hooks)}withHooks(e){return new c(this.resourceSchema,this.customMutations,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},i=v(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:i}})(e);handleMutation=async({req:e,db:t,schema:n})=>await this.wrapInMiddlewares(async r=>{if(!r.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[r.procedure];if(i){let o=i.inputValidator.parse(r.input);return r.input=o,i.handler({req:r,db:t})}else {if(r.procedure==="INSERT"||r.procedure==="UPDATE")return this.handleSet({req:r,db:t,operation:r.procedure,schema:n});throw new Error(`Unknown procedure: ${r.procedure}`)}})(e);getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t$1,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let i=await t$1.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&i)throw new Error("Resource already exists");if(n==="UPDATE"&&!i)throw new Error("Resource not found");return t$1.transaction(async({trx:o})=>{var d,l,h,y,p,f,b;let[a,s]=this.resourceSchema.mergeMutation("set",e.input,i);if(!s)throw new Error("Mutation rejected");if(n==="INSERT"){let g=await o.rawInsert(e.resource,e.resourceId,a,(d=e.context)==null?void 0:d.messageId,e.context),m=t(g);if(m.id=m.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let T=this.authorization.insert({ctx:e.context,value:m});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let S=w(T,e.resource,r),w$1=Object.keys(S).length>0?await o.rawFindById(e.resource,e.resourceId,S):g,M=t(w$1);if(M.id=M.id??e.resourceId,!x(M,T))throw new Error("Not authorized")}}return {data:g,acceptedValues:s}}if((y=(h=this.authorization)==null?void 0:h.update)!=null&&y.preMutation){let g=t(i);g.id=g.id??e.resourceId;let m=this.authorization.update.preMutation({ctx:e.context,value:g});if(typeof m=="boolean"){if(!m)throw new Error("Not authorized")}else {let T=w(m,e.resource,r),S=Object.keys(T).length>0?await o.rawFindById(e.resource,e.resourceId,T):i,w$1=t(S);if(w$1.id=w$1.id??e.resourceId,!x(w$1,m))throw new Error("Not authorized")}}let u=await o.rawUpdate(e.resource,e.resourceId,a,(p=e.context)==null?void 0:p.messageId,e.context);if((b=(f=this.authorization)==null?void 0:f.update)!=null&&b.postMutation){let g=t(u);g.id=g.id??e.resourceId;let m=this.authorization.update.postMutation({ctx:e.context,value:g});if(typeof m=="boolean"){if(!m)throw new Error("Not authorized")}else {let T=w(m,e.resource,r),S=Object.keys(T).length>0?await o.rawFindById(e.resource,e.resourceId,T):u,w$1=t(S);if(w$1.id=w$1.id??e.resourceId,!x(w$1,m))throw new Error("Not authorized")}}return {data:u,acceptedValues:s}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>i=>r({req:i,next:n}),e)(t)}},oe=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new ie(e,void 0,t,void 0).use(...this.middlewares)}use(...e){return new c([...this.middlewares,...e])}static create(){return new c}},Sr=oe.create;var q=class{async insert(e,t$1){let n=new Date().toISOString();return t(await this.rawInsert(e.name,t$1.id,{value:Object.fromEntries(Object.entries(t$1).map(([r,i])=>[r,{value:i,_meta:{timestamp:n}}]))}))}async update(e,t$1,n){let r=new Date().toISOString(),{id:i,...o}=n;return t(await this.rawUpdate(e.name,t$1,{value:Object.fromEntries(Object.entries(o).map(([a,s])=>[a,{value:s,_meta:{timestamp:r}}]))}))}};var gt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function L(c){var r,i,o;let e=(r=c.getExecutor)==null?void 0:r.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((o=(i=t.constructor)==null?void 0:i.name)==null?void 0:o.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function Oe(c){let e=L(c);return gt[e]}var bt="42701";function F(c){var t;if(c.code===bt)return true;let e=((t=c.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function D(c,e){return c.some(t=>t.name===e)}function Tt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function ae(c,e){let[t]=e.split(".");return D(c,t)}function Ee(c,e,t,n=false){let r=c;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&ae(t,e.references)&&(r=r.references(e.references)),r}function Rt(c,e,t,n,r){let i=[];for(let[o,a]of Object.entries(c.fields)){let s=e==null?void 0:e.columns.find(d=>d.name===o),u=a.getStorageFieldType();s?(s.dataType,u.type):(i.push({name:o,storageFieldType:u}),u.references&&!ae(t,u.references)&&n.push({tableName:r,columnName:o,references:u.references}));}return i}async function St(c,e,t,n,r){if(t.length===0)return;let i=c.schema.createTable(e);for(let{name:o,storageFieldType:a}of t)i=i.addColumn(o,a.type,s=>Ee(s,a,n));await i.execute().catch(o=>{if(!F(o))throw r==null||r.error("Error creating table",e,o),o});}async function wt(c,e,t,n,r,i){for(let{name:o,storageFieldType:a}of t){let s=a.references?ae(n,a.references):false;await c.schema.alterTable(e).addColumn(o,a.type,u=>Ee(u,a,n,!s)).execute().catch(u=>{if(!F(u))throw i==null||i.error("Error adding column",o,u),u}),a.references&&!s&&!r.some(u=>u.tableName===e&&u.columnName===o)&&r.push({tableName:e,columnName:o,references:a.references}),a.index&&await c.schema.createIndex(`${e}_${o}_index`).on(e).column(o).execute().catch(()=>{});}}async function vt(c,e,t,n,r,i){let o=`${e}_meta`,a=[];for(let[s,u]of Object.entries(t.fields)){let d=u.getStorageFieldType();Tt(n,s)||a.push({name:s,storageFieldType:d});}if(!n&&a.length>0){let s=c.schema.createTable(o);for(let{name:u,storageFieldType:d}of a)s=s.addColumn(u,"varchar",l=>{let h=l;return d.primary&&(h=h.primaryKey(),D(r,e)&&(h=h.references(`${e}.${u}`))),h});await s.execute().catch(u=>{if(!F(u))throw i==null||i.error("Error creating meta table",o,u),u});}else if(n)for(let{name:s,storageFieldType:u}of a)await c.schema.alterTable(o).addColumn(s,"varchar",d=>{let l=d;return u.primary&&(l=l.primaryKey(),D(r,e)&&(l=l.references(`${e}.${s}`))),l}).execute().catch(d=>{if(!F(d))throw i==null||i.error("Error adding meta column",s,d),d});}async function Le(c,e,t,n,r){let[i,o]=n.split("."),a=`${e}_${t}_fk`;try{await sql`
2
+ ALTER TABLE ${sql.raw(e)}
3
+ ADD CONSTRAINT ${sql.raw(a)}
4
+ FOREIGN KEY (${sql.raw(t)})
5
+ REFERENCES ${sql.raw(i)} (${sql.raw(o)})
6
+ `.execute(c);}catch(s){F(s)||r==null||r.warn("Could not add foreign key constraint",e,t,n,s);}}async function xt(c,e,t,n){for(let{tableName:r,columnName:i,references:o}of e){let a=t.find(d=>d.name===r),s=a==null?void 0:a.columns.find(d=>d.name===i),[u]=o.split(".");a&&s&&D(t,u)&&await Le(c,r,i,o,n);}}async function Mt(c,e,t,n){for(let[r,i]of Object.entries(e)){let o=`${r}_meta`,a=t.find(s=>s.name===o);if(a)for(let[s,u]of Object.entries(i.fields)){let d=u.getStorageFieldType(),l=a.columns.find(h=>h.name===s);d.primary&&l&&D(t,r)&&await Le(c,o,s,`${r}.${s}`,n);}}}async function Pe(c,e,t){let n=await c.introspection.getTables(),r=[];for(let[o,a]of Object.entries(e)){let s=n.find(l=>l.name===o),u=n.find(l=>l.name===`${o}_meta`),d=Rt(a,s,n,r,o);if(s)for(let[l,h]of Object.entries(a.fields)){let y=s.columns.find(f=>f.name===l),p=h.getStorageFieldType();y&&y.dataType!==p.type&&(t==null||t.warn("Column type mismatch:",l,"expected to have type:",p.type,"but has type:",y.dataType));}!s&&d.length>0?await St(c,o,d,n,t):s&&await wt(c,o,d,n,r,t),await vt(c,o,a,u,n,t);}let i=await c.introspection.getTables();await xt(c,r,i,t),await Mt(c,e,i,t);}function K(c,e,t,n){if(!c)throw new Error("Schema not initialized");let r=c[e];if(!r)throw new Error("Resource not found");let i=n.$or,o=n.$and;return (i?t.or:t.and)(i?n.$or.map(a=>K(c,e,t,a)):o?n.$and.map(a=>K(c,e,t,a)):Object.entries(n).map(([a,s])=>{var u,d;if(r.fields[a])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${a}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${a}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((u=s==null?void 0:s.$not)==null?void 0:u.$in)!==void 0?t(`${e}.${a}`,"not in",s.$not.$in):((d=s==null?void 0:s.$not)==null?void 0:d.$eq)!==void 0?t(`${e}.${a}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${a}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${a}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${a}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${a}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${a}`,"<=",s.$lte):t(`${e}.${a}`,s===null?"is":"=",s);if(r.relations[a]){let l=r.relations[a],h=l.entity.name;return l.type==="many"?t.exists(ce(c,h,t.selectFrom(h).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),s)):K(c,h,t,s)}return null}).filter(Boolean))}function J(c,e,t,n){let r=c[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let i of n.$and)t=J(c,e,t,i);return t}else if(n.$or){for(let i of n.$or)t=J(c,e,t,i);return t}for(let[i,o]of Object.entries(n)){if(!r.relations[i])continue;let a=r.relations[i],s=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,d=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(s,`${s}.${u}`,`${e}.${d}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=J(c,s,t,o));}return t}function ce(c,e,t,n){return !n||Object.keys(n).length===0?t:(t=J(c,e,t,n),t.where(r=>K(c,e,r,n)))}function It(c,e,t,n,r){let i=L(r),o=e[t];if(i==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),s=c.selectFrom(n);for(let u of a)s=s.select(`${n}.${u}`);return s}return c.selectFrom(n).selectAll(n)}function jt(c,e,t,n,r){let i=L(r),o=e[t];if(i==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),s=c.selectFrom(n);for(let u of a)s=s.select(`${n}.${u}`);return s}return c.selectFrom(n).selectAll(n)}function G(c,e,t,n,r,i){if(!n)return t;if(!c)throw new Error("Schema not initialized");let o=c[e];if(!o)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:a,jsonArrayFrom:s}=r;for(let u of Object.keys(n)){if(!o.relations[u])throw new Error(`Relation ${u} not found in resource ${e}`);let d=o.relations[u],l=d.entity.name,h=n[u],y=d.type==="one"?"id":d.foreignColumn,p=d.type==="one"?d.relationalColumn:"id",f=d.type==="one"?a:s,b=typeof h=="object"&&h!==null;t=t.select(g=>{let m=`${l}_meta`,T=jt(g,c,l,l,i).whereRef(`${l}.${y}`,"=",`${e}.${p}`).select(S=>a(It(S,c,l,m,i).whereRef(`${m}.id`,"=",`${l}.id`)).as("_meta"));return b&&(T=G(c,l,T,h,r,i)),f(T).as(u)});}return t}var ue=class c extends q{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=Oe(this.db),this.schema=t,this.logger=n,this.server=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){this.schema=e,this.logger=t,this.server=n,await Pe(this.db,e,t);}selectMetaColumns(e,t,n){var o;let r=L(this.db),i=(o=this.schema)==null?void 0:o[t];if(r==="sqlite"&&(i!=null&&i.fields)){let a=Object.keys(i.fields),s=e.selectFrom(n);for(let u of a)s=s.select(`${n}.${u}`);return s}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,i=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(s,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));i=G(this.schema,e,i,n,this.dialectHelpers,this.db);let o=await i.executeTakeFirst();if(!o)return;let a=this.parseRelationalJsonStrings(o,e);return this.convertToMaterializedLiveType(a)}async findOne(e,t$1,n){let r=await this.rawFindById(e.name,t$1,n==null?void 0:n.include);if(r)return t(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:i,sort:o}=e,a=`${t}_meta`,s=this.db.selectFrom(t).selectAll(t).select(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,a).whereRef(`${a}.id`,"=",`${t}.id`)).as("_meta"));s=ce(this.schema,t,s,n),s=G(this.schema,t,s,r,this.dialectHelpers,this.db),i!==void 0&&(s=s.limit(i)),o!==void 0&&o.forEach(d=>{s=s.orderBy(d.key,d.direction);});let u=await s.execute();return u.length===0?[]:u.map(d=>{let l=this.parseRelationalJsonStrings(d,t);return this.convertToMaterializedLiveType(l)})}async find(e,t$1){return (await this.get({resource:e.name,where:t$1==null?void 0:t$1.where,include:t$1==null?void 0:t$1.include,limit:t$1==null?void 0:t$1.limit,sort:t$1==null?void 0:t$1.sort})).map(r=>t(r))}async rawInsert(e,t,n,r,i){var l,h,y;let o=(h=(l=this.server)==null?void 0:l.router)==null?void 0:h.getHooks(e),a=n;if(o!=null&&o.beforeInsert){let p=await o.beforeInsert({ctx:i,value:a,db:this});p&&(a=p);}let s={},u={};for(let[p,f]of Object.entries(a.value)){let b=(y=f._meta)==null?void 0:y.timestamp;b&&(s[p]=f.value,u[p]=b);}await this.db.insertInto(e).values({...s,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...u,id:t}).execute();});let d=this.buildMutation(e,t,"INSERT",a,r);return d&&this.trackMutation(d,a),o!=null&&o.afterInsert&&await o.afterInsert({ctx:i,value:a,db:this}),a}async rawUpdate(e,t,n,r,i){var h,y,p;let o=(y=(h=this.server)==null?void 0:h.router)==null?void 0:y.getHooks(e),a;(o!=null&&o.beforeUpdate||o!=null&&o.afterUpdate)&&(a=await this.rawFindById(e,t));let s=n;if(o!=null&&o.beforeUpdate){let f=await o.beforeUpdate({ctx:i,value:s,previousValue:a,db:this});f&&(s=f);}let u={},d={};for(let[f,b]of Object.entries(s.value)){let g=(p=b._meta)==null?void 0:p.timestamp;g&&(u[f]=b.value,d[f]=g);}await Promise.all([this.db.updateTable(e).set(u).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...d,id:t}).onConflict(f=>f.column("id").doUpdateSet(d)).execute()]);let l=this.buildMutation(e,t,"UPDATE",s,r);if(l){let f=await this.rawFindById(e,t);f&&this.trackMutation(l,f);}if(o!=null&&o.afterUpdate){let f=await this.rawFindById(e,t);f&&await o.afterUpdate({ctx:i,value:f,previousValue:a,db:this});}return s}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let i=Math.random().toString(36).substring(2,15),o=this.mutationStack,a=[];this.mutationStack=a;let s=await this.db.savepoint(i).execute(),u=false,d=false;try{return await e({trx:this,commit:async()=>{await s.releaseSavepoint(i).execute(),u=!0,o.push(...a);},rollback:async()=>{await s.rollbackToSavepoint(i).execute(),d=!0,a.length=0;}}).then(l=>s.isCommitted||s.isRolledBack||u||d?l:s.releaseSavepoint(i).execute().then(()=>(o.push(...a),l)))}catch(l){throw d||await s.rollbackToSavepoint(i).execute().catch(()=>{}),a.length=0,l}finally{this.mutationStack=o;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let i=new c(r,this.schema,this.logger,this.server);return i.mutationStack=t,await e({trx:i,commit:async()=>{await r.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(o=>r.isCommitted||r.isRolledBack?o:r.commit().execute().then(()=>(this.notifyMutations(t),o)))}catch(i){throw await r.rollback().execute(),t.length=0,i}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var i,o;if(L(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(a=>this.parseRelationalJsonStrings(a,t));let r={};for(let[a,s]of Object.entries(e))if(a==="_meta"&&typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{r[a]=JSON.parse(s);}catch{r[a]=s;}else r[a]=s;else if(this.isRelationalField(t,a))if(typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{let u=JSON.parse(s);if(this.schema){let d=this.schema[t],l=(i=d==null?void 0:d.relations)==null?void 0:i[a];if(l){let h=l.entity.name;r[a]=this.parseRelationalJsonStrings(u,h);}else r[a]=u;}else r[a]=u;}catch{r[a]=s;}else r[a]=s;else if(typeof s=="object"&&s!==null&&!Array.isArray(s))if(this.schema){let u=this.schema[t],d=(o=u==null?void 0:u.relations)==null?void 0:o[a];if(d){let l=d.entity.name;r[a]=this.parseRelationalJsonStrings(s,l);}else r[a]=s;}else r[a]=s;else Array.isArray(s)?r[a]=s.map(u=>{var d,l;if(typeof u=="string")try{let h=JSON.parse(u);if(this.schema){let y=this.schema[t],p=(d=y==null?void 0:y.relations)==null?void 0:d[a];if(p){let f=p.entity.name;return this.parseRelationalJsonStrings(h,f)}}return h}catch{return u}if(typeof u=="object"&&u!==null&&this.schema){let h=this.schema[t],y=(l=h==null?void 0:h.relations)==null?void 0:l[a];if(y){let p=y.entity.name;return this.parseRelationalJsonStrings(u,p)}}return u}):r[a]=s;else r[a]=s;return r}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,r])=>{var i,o,a;return n==="_meta"||(n==="id"?t[n]={value:r}:Array.isArray(r)?t[n]={value:r.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(i=e==null?void 0:e._meta)==null?void 0:i[n]}}:typeof r=="object"&&r!==null&&!(r instanceof Date)?t[n]={...this.convertToMaterializedLiveType(r),_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[n]}}:t[n]={value:r,_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[n]}}),t},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",i=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||i&&o}buildMutation(e,t,n,r,i){var a;let o={};for(let[s,u]of Object.entries(r.value)){if(s==="id")continue;let d=(a=u._meta)==null?void 0:a.timestamp;d&&(o[s]={value:u.value,_meta:{timestamp:d}});}return Object.keys(o).length===0?null:{id:i??W(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:o}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:i}of n)this.server.notifySubscribers(r,i);}}};var le=class c{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=z$2({level:e.logLevel??y.INFO}),(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new V({router:{get:async(n,r)=>{var l;let{headers:i,cookies:o,queryParams:a,context:s}=(r==null?void 0:r.context)??{};if(!(r!=null&&r.batcher))throw new Error("Batcher is required");let u={...n,type:"QUERY",headers:i,cookies:o,queryParams:a,context:s},d=await((l=this.router.routes[n.resource])==null?void 0:l.handleQuery({req:u,batcher:r.batcher}));return (d==null?void 0:d.data)??[]},incrementQueryStep:(n,r={})=>{var a;let i=(a=this.router.routes[n.query.resource])==null?void 0:a.getAuthorizationClause({...n.query,type:"QUERY",headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context});if(typeof i=="boolean"&&!i)throw new Error("Not authorized");let o=N(n.query.where,typeof i=="object"?i:void 0);return {...n,query:{...n.query,where:o}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:i,context:o,...a}=t,s={headers:n,cookies:r,queryParams:i,context:o},u=e.subscription?this.queryEngine.subscribe(a,l=>{var h;(h=e.subscription)==null||h.call(e,l);},s):void 0;return {data:await this.queryEngine.get(a,{context:s}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>i=>r({req:i,next:n}),e)(t)}},_r=le.create;export{ie as Route,oe as RouteFactory,se as Router,ue as SQLStorage,le as Server,q as Storage,pr as expressAdapter,Sr as routeFactory,Rr as router,_r as server};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@live-state/sync",
3
- "version": "0.0.5",
3
+ "version": "0.0.6-beta-1",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -21,23 +21,30 @@
21
21
  ],
22
22
  "type": "module",
23
23
  "devDependencies": {
24
+ "@codspeed/vitest-plugin": "5.0.1",
24
25
  "@testing-library/jest-dom": "^6.8.0",
25
26
  "@testing-library/react": "^16.3.0",
26
27
  "@testing-library/react-hooks": "^8.0.1",
28
+ "@types/better-sqlite3": "^7.6.13",
27
29
  "@types/express": "^4.17.21",
28
30
  "@types/express-ws": "^3.0.5",
29
31
  "@types/node": "^20.11.24",
32
+ "@types/pg": "^8.15.1",
30
33
  "@types/qs": "^6.14.0",
31
34
  "@types/react": "^18.2.62",
32
35
  "@types/react-dom": "^18.2.19",
33
36
  "@types/ws": "^8.5.13",
34
37
  "@vitest/coverage-v8": "3.2.4",
38
+ "better-sqlite3": "^12.5.0",
35
39
  "cookie": "^1.0.2",
36
40
  "express": "^4.21.2",
41
+ "express-ws": "^5.0.2",
37
42
  "jsdom": "^26.1.0",
43
+ "pg": "^8.15.6",
38
44
  "react": "18.0.0",
39
45
  "react-dom": "^18.2.0",
40
- "tsup": "^8.0.2",
46
+ "tsup": "^8.5.1",
47
+ "tsx": "^4.19.2",
41
48
  "typescript": "5.5.4",
42
49
  "ulid": "^3.0.0",
43
50
  "vitest": "^3.2.4",
@@ -92,6 +99,8 @@
92
99
  "lint": "biome lint",
93
100
  "typecheck": "tsc --noEmit --project . && tsc --noEmit --project src/client",
94
101
  "test": "vitest run",
95
- "test:watch": "vitest"
102
+ "test:watch": "vitest",
103
+ "benchmark": "tsx benchmark/benchmark.ts",
104
+ "bench": "vitest bench --run"
96
105
  }
97
106
  }
@@ -1 +0,0 @@
1
- import'js-xxhash';var O=Object.create;var I=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var S=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of A(e))!M.call(t,a)&&a!==n&&I(t,a,{get:()=>e[a],enumerable:!(i=K(e,a))||i.enumerable});return t};var V=(t,e,n)=>(n=t!=null?O(j(t)):{},S(e||!t||!t.__esModule?I(n,"default",{value:t,enumerable:true}):n,t));var o=class{_value;_meta;_encodeInput;_decodeInput};var m=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,n,i){return this.inner.encodeMutation(e,n,i)}mergeMutation(e,n,i){return this.inner.mergeMutation(e,n,i)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},y=class t extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,n,i,a,s,l,r){super(),this.storageType=e,this.convertFunc=n,this.isIndex=i??false,this.isUnique=a??false,this.defaultValue=s,this.foreignReference=l,this.isPrimary=r??false;}encodeMutation(e,n,i){return {value:n,_meta:{timestamp:i}}}mergeMutation(e,n,i){return i&&i._meta.timestamp&&n._meta.timestamp&&i._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[i,null]:[{value:this.convertFunc?this.convertFunc(n.value):n.value,_meta:n._meta},n]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new t(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new t(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}nullable(){return new m(this)}},v=class t extends y{constructor(){super("integer",e=>Number(e));}static create(){return new t}},F=v.create,p=class t extends y{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new t}static createId(){return new t().index().unique().primary()}static createReference(e){return new t(e)}},q=p.create,N=p.createId,D=p.createReference,L=class t extends y{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},W=L.create,h=class t extends y{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},P=h.create;var g=class t extends o{name;fields;relations;constructor(e,n,i){super(),this.name=e,this.fields=n,this.relations=i??{};}encodeMutation(e,n,i){return Object.fromEntries(Object.entries(n).map(([a,s])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",s,i)]))}mergeMutation(e,n,i){let a={};return [{value:{...(i==null?void 0:i.value)??{},...Object.fromEntries(Object.entries(n).map(([s,l])=>{let r=this.fields[s]??this.relations[s];if(!r)return [s,l];let[u,d]=r.mergeMutation(e,l,i==null?void 0:i.value[s]);return d&&(a[s]=d),[s,u]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,n){return new t(e,n)}},z=g.create,f=class t extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,n,i,a,s){super(),this.entity=e,this.type=n,this.required=s??false,this.relationalColumn=i,this.foreignColumn=a;}encodeMutation(e,n,i){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:n,_meta:{timestamp:i}}}mergeMutation(e,n,i){if(this.type==="many")throw new Error("Many not implemented.");return i&&i._meta.timestamp&&n._meta.timestamp&&i._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[i,null]:[n,n]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,n,i)=>new t(e,"one",n,void 0,i??false)}static createManyFactory(){return (e,n,i)=>new t(e,"many",void 0,n,i??false)}},G=(t,e)=>({$type:"relations",objectName:t.name,relations:e({one:f.createOneFactory(),many:f.createManyFactory()})}),x=t=>t?Array.isArray(t.value)?t.value.map(n=>x(n)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([n,i])=>Array.isArray(i)?[n,i.map(a=>x(a))]:[n,x(i)])):void 0,H=t=>Object.fromEntries(Object.entries(t).flatMap(([e,n])=>{if(n.$type==="relations")return [];let i=n,a=Object.values(t).find(s=>s.$type==="relations"&&s.objectName===n.name);return a&&(i=i.setRelations(a.relations)),[[i.name,i]]}));var w=(t,e,n)=>{let i={},a=n[e];if(!a)return i;let s=l=>{l.$and?l.$and.forEach(s):l.$or?l.$or.forEach(s):Object.entries(l).forEach(([r,u])=>{var d;if((d=a.relations)!=null&&d[r]&&(i[r]=true,typeof u=="object"&&u!==null&&!Array.isArray(u))){let b=w(u,a.relations[r].entity.name,n);Object.keys(b).length>0&&(i[r]=b);}});};return s(t),i},c=(t,e,n=false)=>Object.entries(e).every(([i,a])=>{if(i==="$and")return a.every(l=>c(t,l,n));if(i==="$or")return a.some(l=>c(t,l,n));let s=(a==null?void 0:a.$eq)!==void 0?a==null?void 0:a.$eq:a;if(typeof a=="object"&&a!==null&&(a==null?void 0:a.$eq)===void 0){if(a.$in!==void 0){let r=t[i];return r===void 0?false:n?!a.$in.includes(r):a.$in.includes(r)}if(a.$not!==void 0&&!n)return c(t,{[i]:a.$not},true);if(a.$gt!==void 0){let r=t[i];return typeof r!="number"?false:n?r<=a.$gt:r>a.$gt}if(a.$gte!==void 0){let r=t[i];return typeof r!="number"?false:n?r<a.$gte:r>=a.$gte}if(a.$lt!==void 0){let r=t[i];return typeof r!="number"?false:n?r>=a.$lt:r<a.$lt}if(a.$lte!==void 0){let r=t[i];return typeof r!="number"?false:n?r>a.$lte:r<=a.$lte}let l=t[i];return !l||typeof l!="object"&&!Array.isArray(l)?false:Array.isArray(l)?n?!l.some(r=>c(r,a,false)):l.some(r=>c(r,a,false)):c(l,a,n)}return n?t[i]!==s:t[i]===s}),T={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},R=class{level;prefix;constructor(e={}){this.level=e.level??T.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=T.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=T.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=T.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=T.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=T.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Z=t=>new R(t);export{C as a,V as b,o as c,m as d,y as e,v as f,F as g,p as h,q as i,N as j,D as k,L as l,W as m,h as n,P as o,g as p,z as q,f as r,G as s,x as t,H as u,w as v,c as w,T as x,Z as y};
@@ -1 +0,0 @@
1
- var b="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var l;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID";})(l||(l={}));var u=class extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e;}};function _(t){let e=Math.floor(t()*32);return e===32&&(e=31),b.charAt(e)}function R(t){let e=w(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return n.getRandomValues(i),i[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return ()=>n.randomBytes(1).readUInt8()/255;throw new u(l.PRNGDetectFailure,"Failed to find a reliable PRNG")}function w(){return E()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function A(t,e){let n="";for(;t>0;t--)n=_(e)+n;return n}function M(t,e=10){if(isNaN(t))throw new u(l.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>0xffffffffffff)throw new u(l.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${t}`);if(t<0)throw new u(l.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===false)throw new u(l.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,i="";for(let r=e;r>0;r--)n=t%32,i=b.charAt(n)+i,t=(t-n)/32;return i}function E(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function I(t,e){let n=R(),i=Date.now();return M(i,10)+A(16,n)}var N=()=>I().toLowerCase(),j=(t,e)=>typeof t=="function"?t(e):t;var L=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,r,a,s,o,d){this._collection=e,this._client=n,this._where=i??{},this._include=r??{},this._limit=a,this._single=s,this._sort=o,this._shouldAwait=d,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new t(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new t(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}get(){let e=this._client.get({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort});return this._shouldAwait?Promise.resolve(e).then(n=>this._single?n[0]:n):this._single?e[0]:e}subscribe(e){return this._client.subscribe({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort},n=>{if(this._single)return e(n[0]);e(n);})}limit(e){return new t(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new t(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,n="asc"){let i=[...this._sort??[],{key:e,direction:n}];return new t(this._collection,this._client,this._where,this._include,this._limit,this._single,i,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}static _init(e,n,i){return new t(e,n,void 0,void 0,void 0,void 0,void 0,i??false)}};var O=(t,e,n=[])=>new Proxy(t,{get:(i,r)=>{var d,y;if(r==="__isProxy__")return true;let a=(d=e.get)==null?void 0:d.call(e,i,[...n,r]);if(a!==void 0)return a;let s=i,o=r;return (y=s[o])!=null&&y.__isProxy__||(s[o]=O(typeof s[o]=="object"?s[o]:()=>{},e,[...n,r])),s[o]},apply:(i,r,a)=>{var s;return (s=e.apply)==null?void 0:s.call(e,i,n,a)}}),D=(t,e,n)=>{let i=[],r=0;for(let a=0;a<t.length&&(n===void 0||r<n);a++)e(t[a],a)&&(i.push(t[a]),r++);return i};var g=t=>t?Array.isArray(t.value)?t.value.map(n=>g(n)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([n,i])=>Array.isArray(i)?[n,i.map(r=>g(r))]:[n,g(i)])):void 0;export{N as a,j as b,L as c,O as d,D as e,g as f};