@live-state/sync 0.0.4-beta.9 → 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
@@ -1,8 +1,8 @@
1
1
  import { z } from 'zod';
2
- import { LiveObjectAny, WhereClause, InferLiveObjectWithRelationalIds, MaterializedLiveType, Schema, IncludeClause, InferLiveObject, InferInsert, InferUpdate } from './index.js';
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,11 +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>;
44
-
45
- type Simplify<T> = T extends Record<string, unknown> ? {
46
- [K in keyof T]: Simplify<T[K]>;
47
- } : T extends Array<infer U> ? Array<Simplify<U>> : T;
43
+ type PromiseOrSync<T> = T | Promise<T>;
48
44
 
49
45
  /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
50
46
  /** biome-ignore-all lint/style/noNonNullAssertion: false positive */
@@ -52,10 +48,12 @@ type Simplify<T> = T extends Record<string, unknown> ? {
52
48
  type RouteRecord = Record<string, AnyRoute>;
53
49
  declare class Router<TRoutes extends RouteRecord> {
54
50
  readonly routes: TRoutes;
51
+ readonly hooksRegistry: Map<string, Hooks<any>>;
55
52
  private constructor();
56
53
  static create<TRoutes extends RouteRecord>(opts: {
57
54
  routes: TRoutes;
58
55
  }): Router<TRoutes>;
56
+ getHooks(resourceName: string): Hooks<any> | undefined;
59
57
  }
60
58
  declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof TSchema, Route<any, any, any>>>(opts: {
61
59
  schema: TSchema;
@@ -63,13 +61,14 @@ declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof
63
61
  }) => Router<TRoutes>;
64
62
  type AnyRouter = Router<any>;
65
63
  type QueryResult<TShape extends LiveObjectAny> = {
66
- data: Record<string, MaterializedLiveType<TShape>>;
64
+ data: MaterializedLiveType<TShape>[];
65
+ unsubscribe?: () => void;
67
66
  };
68
67
  type MutationResult<TShape extends LiveObjectAny> = {
69
68
  data: MaterializedLiveType<TShape>;
70
69
  acceptedValues: Record<string, any> | null;
71
70
  };
72
- 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
73
72
  TOutput> = {
74
73
  inputValidator: TInputValidator;
75
74
  handler: (opts: {
@@ -77,9 +76,21 @@ TOutput> = {
77
76
  db: Storage;
78
77
  }) => TOutput;
79
78
  };
80
- declare const mutationCreator: <TInputValidator extends z3.ZodTypeAny | z4.$ZodType>(validator?: TInputValidator) => {
81
- 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
+ };
82
92
  };
93
+ declare const mutationCreator: MutationCreator;
83
94
  type ReadAuthorizationHandler<TShape extends LiveObjectAny> = (opts: {
84
95
  ctx: BaseRequest["context"];
85
96
  }) => WhereClause<TShape> | boolean;
@@ -95,16 +106,47 @@ type Authorization<TShape extends LiveObjectAny> = {
95
106
  postMutation?: MutationAuthorizationHandler<TShape>;
96
107
  };
97
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
+ };
98
137
  declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends Middleware<any>, TCustomMutations extends Record<string, Mutation<any, any>>> {
99
138
  readonly resourceSchema: TResourceSchema;
100
139
  readonly middlewares: Set<TMiddleware>;
101
140
  readonly customMutations: TCustomMutations;
102
141
  readonly authorization?: Authorization<TResourceSchema>;
103
- 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>);
104
144
  use(...middlewares: TMiddleware[]): this;
105
145
  withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
106
146
  mutation: typeof mutationCreator;
107
147
  }) => T): Route<TResourceSchema, TMiddleware, T>;
148
+ withHooks(hooks: Hooks<TResourceSchema>): Route<TResourceSchema, TMiddleware, TCustomMutations>;
149
+ getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
108
150
  private handleSet;
109
151
  private wrapInMiddlewares;
110
152
  }
@@ -120,16 +162,51 @@ type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
120
162
 
121
163
  /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
122
164
 
123
- declare abstract class Storage {
124
- abstract findOne<T extends LiveObjectAny>(resource: T, id: string, options?: {
125
- include?: IncludeClause<T>;
126
- }): Promise<InferLiveObject<T> | undefined>;
127
- 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?: {
128
200
  where?: WhereClause<T>;
129
- include?: IncludeClause<T>;
130
- }): 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>[]>;
131
208
  insert<T extends LiveObjectAny>(resource: T, value: Simplify<InferInsert<T>>): Promise<InferLiveObject<T>>;
132
- 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>>>;
133
210
  abstract transaction<T>(fn: (opts: {
134
211
  trx: Storage;
135
212
  commit: () => Promise<void>;
@@ -140,36 +217,58 @@ declare abstract class Storage {
140
217
  /** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
141
218
 
142
219
  declare class SQLStorage extends Storage {
143
- private db;
220
+ private readonly db;
221
+ private readonly dialectHelpers;
144
222
  private schema?;
223
+ private logger?;
224
+ private server?;
225
+ private mutationStack;
145
226
  constructor(pool: PostgresPool);
146
- findOne<T extends LiveObjectAny>(resource: T, id: string, options?: {
147
- include?: IncludeClause<T>;
148
- }): Promise<InferLiveObject<T> | undefined>;
149
- 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?: {
150
232
  where?: WhereClause<T>;
151
- include?: IncludeClause<T>;
233
+ include?: TInclude;
152
234
  limit?: number;
153
235
  sort?: {
154
236
  key: string;
155
237
  direction: "asc" | "desc";
156
238
  }[];
157
- }): Promise<Record<string, InferLiveObject<T>>>;
239
+ }): Promise<InferLiveObject<T, TInclude>[]>;
158
240
  transaction<T>(fn: (opts: {
159
241
  trx: Storage;
160
242
  commit: () => Promise<void>;
161
243
  rollback: () => Promise<void>;
162
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;
163
261
  private convertToMaterializedLiveType;
164
262
  private isKyselyLike;
263
+ private buildMutation;
264
+ private trackMutation;
265
+ private notifyMutations;
165
266
  }
166
267
 
167
268
  declare const expressAdapter: (app: Application, server: Server<AnyRouter>, options?: {
168
269
  basePath?: string;
169
270
  }) => void;
170
271
 
171
- /** biome-ignore-all lint/suspicious/noExplicitAny: any's are actually used correctly */
172
-
173
272
  interface BaseRequest {
174
273
  headers: Record<string, string>;
175
274
  cookies: Record<string, string>;
@@ -190,8 +289,7 @@ type Request = QueryRequest | MutationRequest;
190
289
  type ContextProvider = (req: Omit<BaseRequest, "context"> & {
191
290
  transport: "HTTP" | "WEBSOCKET";
192
291
  }) => Record<string, any>;
193
- type MutationHandler = (mutation: DefaultMutation) => void;
194
- type NextFunction<O, R = Request> = (req: R) => Awaitable<O>;
292
+ type NextFunction<O, R = Request> = (req: R) => PromiseOrSync<O>;
195
293
  type Middleware<T = any> = (opts: {
196
294
  req: Request;
197
295
  next: NextFunction<T>;
@@ -201,8 +299,8 @@ declare class Server<TRouter extends AnyRouter> {
201
299
  readonly storage: Storage;
202
300
  readonly schema: Schema<any>;
203
301
  readonly middlewares: Set<Middleware<any>>;
302
+ readonly logger: Logger;
204
303
  contextProvider?: ContextProvider;
205
- private mutationSubscriptions;
206
304
  private constructor();
207
305
  static create<TRouter extends AnyRouter>(opts: {
208
306
  router: TRouter;
@@ -210,10 +308,11 @@ declare class Server<TRouter extends AnyRouter> {
210
308
  schema: Schema<any>;
211
309
  middlewares?: Middleware<any>[];
212
310
  contextProvider?: ContextProvider;
311
+ logLevel?: LogLevel;
213
312
  }): Server<TRouter>;
214
- subscribeToMutations(handler: MutationHandler): () => void;
215
313
  handleQuery(opts: {
216
314
  req: QueryRequest;
315
+ subscription?: (mutation: DefaultMutation) => void;
217
316
  }): Promise<QueryResult<any>>;
218
317
  handleMutation(opts: {
219
318
  req: MutationRequest;
@@ -224,4 +323,4 @@ declare class Server<TRouter extends AnyRouter> {
224
323
  }
225
324
  declare const server: typeof Server.create;
226
325
 
227
- 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}from'./chunk-XNKBHWSC.js';import v from'node:crypto';import qe,{parse}from'qs';import {z as z$1}from'zod';import'js-xxhash';import {Kysely,PostgresDialect}from'kysely';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/postgres';var D=a(P=>{Object.defineProperty(P,"__esModule",{value:true});P.parse=ve;P.serialize=Le;var Ie=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Ee=/^[\u0021-\u003A\u003C-\u007E]*$/,Ae=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Oe=/^[\u0020-\u003A\u003D-\u007E]*$/,$e=Object.prototype.toString,je=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function ve(i,t){let e=new je,r=i.length;if(r<2)return e;let n=(t==null?void 0:t.decode)||Ce,a=0;do{let o=i.indexOf("=",a);if(o===-1)break;let c=i.indexOf(";",a),s=c===-1?r:c;if(o>s){a=i.lastIndexOf(";",o-1)+1;continue}let y=te(i,a,o),p=re(i,o,y),l=i.slice(y,p);if(e[l]===void 0){let d=te(i,o+1,s),m=re(i,s,d),u=n(i.slice(d,m));e[l]=u;}a=s+1;}while(a<r);return e}function te(i,t,e){do{let r=i.charCodeAt(t);if(r!==32&&r!==9)return t}while(++t<e);return e}function re(i,t,e){for(;t>e;){let r=i.charCodeAt(--t);if(r!==32&&r!==9)return t+1}return e}function Le(i,t,e){let r=(e==null?void 0:e.encode)||encodeURIComponent;if(!Ie.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(t);if(!Ee.test(n))throw new TypeError(`argument val is invalid: ${t}`);let a=i+"="+n;if(!e)return a;if(e.maxAge!==void 0){if(!Number.isInteger(e.maxAge))throw new TypeError(`option maxAge is invalid: ${e.maxAge}`);a+="; Max-Age="+e.maxAge;}if(e.domain){if(!Ae.test(e.domain))throw new TypeError(`option domain is invalid: ${e.domain}`);a+="; Domain="+e.domain;}if(e.path){if(!Oe.test(e.path))throw new TypeError(`option path is invalid: ${e.path}`);a+="; Path="+e.path;}if(e.expires){if(!Pe(e.expires)||!Number.isFinite(e.expires.valueOf()))throw new TypeError(`option expires is invalid: ${e.expires}`);a+="; Expires="+e.expires.toUTCString();}if(e.httpOnly&&(a+="; HttpOnly"),e.secure&&(a+="; Secure"),e.partitioned&&(a+="; Partitioned"),e.priority)switch(typeof e.priority=="string"?e.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; 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":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${e.sameSite}`)}return a}function Ce(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Pe(i){return $e.call(i)==="[object Date]"}});var Y="0123456789ABCDEFGHJKMNPQRSTVWXYZ",E=32;var ge=16,X=10,J=0xffffffffffff;var w;(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";})(w||(w={}));var S=class extends Error{constructor(t,e){super(`${e} (${t})`),this.name="ULIDError",this.code=t;}};function Re(i){let t=Math.floor(i()*E);return t===E&&(t=E-1),Y.charAt(t)}function be(i){var r;let t=xe(),e=t&&(t.crypto||t.msCrypto)||(typeof v<"u"?v: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=v)!=null&&r.randomBytes)return ()=>v.randomBytes(1).readUInt8()/255;throw new S(w.PRNGDetectFailure,"Failed to find a reliable PRNG")}function xe(){return Me()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function we(i,t){let e="";for(;i>0;i--)e=Re(t)+e;return e}function Se(i,t=X){if(isNaN(i))throw new S(w.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>J)throw new S(w.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${J}: ${i}`);if(i<0)throw new S(w.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new S(w.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let e,r="";for(let n=t;n>0;n--)e=i%E,r=Y.charAt(e)+r,i=(i-e)/E;return r}function Me(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ee(i,t){let e=be(),r=Date.now();return Se(r,X)+we(ge,e)}var W=()=>ee().toLowerCase();var L=(...i)=>{let t=i.filter(e=>!!e);return t.length===0?{}:t.length===1?t[0]:{$and:t}};var C=class{storage;queue=new Map;scheduled=false;constructor(t){this.storage=t;}async rawFind({resource:t,commonWhere:e,uniqueWhere:r,...n}){return new Promise((a,o)=>{let c=this.getBatchKey({resource:t,commonWhere:e,...n}),s={resource:t,commonWhere:e,uniqueWhere:r,...n,resolve:a,reject:o};this.queue.has(c)||this.queue.set(c,[]);let y=this.queue.get(c);y&&y.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 d,m;if(t.length===0)return;let e=t[0],{resource:r,commonWhere:n,include:a,sort:o}=e,c=t.length===1?e.limit:void 0,s=t.map(u=>u.uniqueWhere).filter(u=>u!==void 0),y=n,p=(d=Object.entries(s[0]??{})[0])==null?void 0:d[0];if(s.length>0){let u=s.map(f=>f[p]).filter(f=>f!=null);u.length>0&&(y=L(n,{[p]:{$in:u}}));}let l=await this.storage.rawFind({resource:r,where:y,include:a,sort:o,limit:c});for(let u of t){let f={};if(u.uniqueWhere){let[T,R]=Object.entries(u.uniqueWhere)[0];for(let[M,j]of Object.entries(l))((m=j.value[T])==null?void 0:m.value)===R&&(f[M]=j);}else Object.assign(f,l);u.resolve(f);}}};var ae=b(D(),1);var z=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()}),k=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()})),ze=k.superRefine((i,t)=>{i.id&&t.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),ne=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),A=ne.extend({procedure:z$1.string(),payload:z$1.any().optional()}),O=ne.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:ze});z$1.union([O,A]);var ie=z.omit({resource:true}),B=A.omit({id:true,type:true,resource:true,procedure:true}),_=O.omit({id:true,type:true,resource:true,procedure:true});z$1.union([_,B]);var oe=i=>async t=>{var e;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,n={headers:r,cookies:r.cookie?ae.default.parse(r.cookie):{}},a=new URL(t.url),o=a.pathname.split("/"),c=a.searchParams,s=qe.parse(c.toString()),y=await((e=i.contextProvider)==null?void 0:e.call(i,{transport:"HTTP",headers:n.headers,cookies:n.cookies,queryParams:s}))??{};if(t.method==="GET"){let p=o[o.length-1],{success:l,data:d,error:m}=ie.safeParse(s);if(!l)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:m},{status:400});let u=await i.handleQuery({req:{...n,...d,type:"QUERY",resource:p,context:y,queryParams:s}});return !u||!u.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(u.data)}if(t.method==="POST")try{let p=o[o.length-1],l=o[o.length-2],d=t.body?await t.json():{},m;if(p==="insert"||p==="update"){let{success:f,data:T,error:R}=_.safeParse(d);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});m=T;}else {let{success:f,data:T,error:R}=B.safeParse(d);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});m=T;}let u=await i.handleMutation({req:{...n,type:"MUTATE",resource:l,input:m.payload,context:y,resourceId:m.resourceId,procedure:p==="insert"||p==="update"?p.toUpperCase():p,queryParams:{}}});return Response.json(u)}catch(p){return console.error("Error parsing mutation from the client:",p),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 console.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var ue=b(D(),1);var I=z$1.string(),Ue=z$1.object({id:I,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),We=z.extend({id:I,type:z$1.literal("QUERY")}),se=O.extend({id:I}),De=A.extend({id:I}),ke=z$1.union([De,se]),ce=z$1.union([Ue,We,ke]),Be=z$1.object({id:I,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),_e=z$1.object({id:I,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([Be,_e,se]);z$1.object({resource:z$1.string(),data:z$1.record(z$1.string(),k)});var de=i=>{let t={},e={};return i.subscribeToMutations(r=>{let n=r;!n.resourceId||!n.payload||(console.log("Mutation propagated:",n),Object.entries(e[n.resource]??{}).forEach(([a,o])=>{var c;(c=t[a])==null||c.send(JSON.stringify({...n,id:n.id??W()}));}));}),(r,n)=>{var p;let a=l=>{r.send(JSON.stringify(l));},o=W(),c={headers:n.headers,cookies:typeof n.headers.cookie=="string"?ue.default.parse(n.headers.cookie):{}},s=parse(n.url.split("?")[1]),y=(p=i.contextProvider)==null?void 0:p.call(i,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,queryParams:s});t[o]=r,console.log("Client connected:",o),r.on("message",async l=>{try{console.log("Message received from the client:",l);let d=ce.parse(JSON.parse(l.toString()));if(d.type==="SUBSCRIBE"){let{resource:m}=d;e[m]||(e[m]={}),e[m][o]={};}else if(d.type==="QUERY"){let{resource:m}=d,u=await i.handleQuery({req:{...c,type:"QUERY",resource:m,context:await y??{},queryParams:s}});if(!u||!u.data)throw new Error("Invalid resource");a({id:d.id,type:"REPLY",data:{resource:m,data:Object.fromEntries(Object.entries(u.data??{}).map(([f,T])=>[f,T.value]))}});}else if(d.type==="MUTATE"){let{resource:m}=d;console.log("Received mutation from client:",d);try{let u=await i.handleMutation({req:{...c,type:"MUTATE",resource:m,input:d.payload,context:{messageId:d.id,...await y??{}},resourceId:d.resourceId,procedure:d.procedure,queryParams:s}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&a({id:d.id,type:"REPLY",data:u});}catch(u){a({id:d.id,type:"REJECT",resource:m,message:u.message}),console.error("Error parsing mutation from the client:",u);}}}catch(d){console.error("Error handling message from the client:",d);}}),r.on("close",()=>{console.log("Connection closed",o),delete t[o];for(let l of Object.values(e))delete l[o];});}};function le(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 It=(i,t,e)=>{i.ws(`${(e==null?void 0:e.basePath)??""}/ws`,de(t)),i.use(`${(e==null?void 0:e.basePath)??""}/`,(r,n)=>{oe(t)(le(r)).then(o=>o.json().then(c=>n.status(o.status).send(c)));});};var x=(i,t,e=false)=>Object.entries(t).every(([r,n])=>{if(r==="$and")return n.every(o=>x(i,o,e));if(r==="$or")return n.some(o=>x(i,o,e));let a=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let o=i[r];return o===void 0?false:e?!n.$in.includes(o):n.$in.includes(o)}if(n.$not!==void 0&&!e)return x(i,{[r]:n.$not},true);if(n.$gt!==void 0){let o=i[r];return typeof o!="number"?false:e?o<=n.$gt:o>n.$gt}if(n.$gte!==void 0){let o=i[r];return typeof o!="number"?false:e?o<n.$gte:o>=n.$gte}if(n.$lt!==void 0){let o=i[r];return typeof o!="number"?false:e?o>=n.$lt:o<n.$lt}if(n.$lte!==void 0){let o=i[r];return typeof o!="number"?false:e?o>n.$lte:o<=n.$lte}return !i[r]||typeof i[r]!="object"?false:x(i[r],n,e)}return e?i[r]!==a:i[r]===a});var V=class i{routes;constructor(t){this.routes=t.routes;}static create(t){return new i(t)}},Pt=i=>V.create({...i}),Fe=i=>({handler:t=>({inputValidator:i??z$1.undefined(),handler:t})}),Q=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:Fe}),this.authorization)}handleQuery=async({req:t,batcher:e})=>await this.wrapInMiddlewares(async r=>{var a,o;let n=(o=(a=this.authorization)==null?void 0:a.read)==null?void 0:o.call(a,{ctx:r.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await e.rawFind({resource:r.resource,commonWhere:L(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})=>await this.wrapInMiddlewares(async r=>{if(!r.procedure)throw new Error("Procedure is required for mutations");let n=this.customMutations[r.procedure];if(n){let a=n.inputValidator.parse(r.input);return r.input=a,n.handler({req:r,db:e})}else {if(r.procedure==="INSERT"||r.procedure==="UPDATE")return this.handleSet({req:r,db:e,operation:r.procedure});throw new Error(`Unknown procedure: ${r.procedure}`)}})(t);handleSet=async({req:t$1,db:e,operation:r})=>{if(!t$1.input)throw new Error("Payload is required");if(!t$1.resourceId)throw new Error("ResourceId is required");let n=await e.rawFindById(t$1.resource,t$1.resourceId);if(r==="INSERT"&&n)throw new Error("Resource already exists");if(r==="UPDATE"&&!n)throw new Error("Resource not found");return e.transaction(async({trx:a})=>{var y,p,l,d,m;let[o,c]=this.resourceSchema.mergeMutation("set",t$1.input,n);if(!c)throw new Error("Mutation rejected");if(r==="INSERT"){let u=await a.rawInsert(t$1.resource,t$1.resourceId,o);if((y=this.authorization)!=null&&y.insert){let f=t(u);f.id=f.id??t$1.resourceId;let T=this.authorization.insert({ctx:t$1.context,value:f});if(!(typeof T=="boolean"?T:x(f,T)))throw new Error("Not authorized")}return {data:u,acceptedValues:c}}if((l=(p=this.authorization)==null?void 0:p.update)!=null&&l.preMutation){let u=t(n);u.id=u.id??t$1.resourceId;let f=this.authorization.update.preMutation({ctx:t$1.context,value:u});if(!(typeof f=="boolean"?f:x(u,f)))throw new Error("Not authorized")}let s=await a.rawUpdate(t$1.resource,t$1.resourceId,o);if((m=(d=this.authorization)==null?void 0:d.update)!=null&&m.postMutation){let u=t(s);u.id=u.id??t$1.resourceId;let f=this.authorization.update.postMutation({ctx:t$1.context,value:u});if(!(typeof f=="boolean"?f:x(u,f)))throw new Error("Not authorized")}return {data:s,acceptedValues:c}})};wrapInMiddlewares(t){return e=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),t)(e)}},F=class i{middlewares;constructor(t=[]){this.middlewares=t;}collectionRoute(t,e){return new Q(t,void 0,e).use(...this.middlewares)}use(...t){return new i([...this.middlewares,...t])}static create(){return new i}},zt=F.create;var $=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,a])=>[n,{value:a,_meta:{timestamp:r}}]))}))}async update(t$1,e,r){let n=new Date().toISOString(),{id:a,...o}=r;return t(await this.rawUpdate(t$1.name,e,{value:Object.fromEntries(Object.entries(o).map(([c,s])=>[c,{value:s,_meta:{timestamp:n}}]))}))}};function N(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 a=r.$or,o=r.$and;return (a?e.or:e.and)(a?r.$or.map(c=>N(i,t,e,c)):o?r.$and.map(c=>N(i,t,e,c)):Object.entries(r).map(([c,s])=>{var y,p;if(n.fields[c])return (s==null?void 0:s.$eq)!==void 0?e(`${t}.${c}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?e(`${t}.${c}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((y=s==null?void 0:s.$not)==null?void 0:y.$in)!==void 0?e(`${t}.${c}`,"not in",s.$not.$in):((p=s==null?void 0:s.$not)==null?void 0:p.$eq)!==void 0?e(`${t}.${c}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):e(`${t}.${c}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?e(`${t}.${c}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?e(`${t}.${c}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?e(`${t}.${c}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?e(`${t}.${c}`,"<=",s.$lte):e(`${t}.${c}`,s===null?"is":"=",s);if(n.relations[c]){let l=n.relations[c],d=l.entity.name;return l.type==="many"?e.exists(Z(i,d,e.selectFrom(d).select("id").whereRef(l.foreignColumn,"=",`${t}.id`),s)):N(i,d,e,s)}return null}).filter(Boolean))}function q(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 a of r.$and)e=q(i,t,e,a);return e}else if(r.$or){for(let a of r.$or)e=q(i,t,e,a);return e}for(let[a,o]of Object.entries(r)){if(!n.relations[a])continue;let c=n.relations[a],s=c.entity.name,y=c.type==="one"?"id":c.foreignColumn,p=c.type==="one"?c.relationalColumn:"id";e=e.leftJoin(s,`${s}.${y}`,`${t}.${p}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(e=q(i,s,e,o));}return e}function Z(i,t,e,r){return !r||Object.keys(r).length===0?e:(e=q(i,t,e,r),e.where(n=>N(i,t,n,r)))}function U(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 a of Object.keys(r)){if(!n.relations[a])throw new Error(`Relation ${a} not found in resource ${t}`);let o=n.relations[a],c=o.entity.name,s=r[a],y=o.type==="one"?"id":o.foreignColumn,p=o.type==="one"?o.relationalColumn:"id",l=o.type==="one"?jsonObjectFrom:jsonArrayFrom,d=typeof s=="object"&&s!==null;e=e.select(m=>{let u=m.selectFrom(c).selectAll(c).whereRef(`${c}.${y}`,"=",`${t}.${p}`).select(f=>jsonObjectFrom(f.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"));return d&&(u=U(i,c,u,s)),l(u).as(a)});}return e}var G=class i extends ${db;schema;constructor(t,e){super(),this.isKyselyLike(t)?this.db=t:this.db=new Kysely({dialect:new PostgresDialect({pool:t})}),this.schema=e,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async updateSchema(t){this.schema=t;let e=await this.db.introspection.getTables();for(let[r,n]of Object.entries(t)){let a=e.find(s=>s.name===r);a||await this.db.schema.createTable(r).ifNotExists().execute();let o=`${r}_meta`,c=e.find(s=>s.name===o);c||await this.db.schema.createTable(o).ifNotExists().execute();for(let[s,y]of Object.entries(n.fields)){let p=a==null?void 0:a.columns.find(m=>m.name===s),l=y.getStorageFieldType();p?p.dataType!==l.type&&console.error("Column type mismatch:",s,"expected to have type:",l.type,"but has type:",p.dataType):(await this.db.schema.alterTable(r).addColumn(s,l.type,m=>{let u=m;return l.unique&&(u=u.unique()),l.nullable||(u=u.notNull()),l.references&&(u=u.references(l.references)),l.primary&&(u=u.primaryKey()),l.default!==void 0&&(u=u.defaultTo(l.default)),u}).execute().catch(m=>{throw console.error("Error adding column",s,m),m}),l.index&&await this.db.schema.createIndex(`${r}_${s}_index`).on(r).column(s).execute().catch(()=>{})),(c==null?void 0:c.columns.find(m=>m.name===s))||await this.db.schema.alterTable(o).addColumn(s,"varchar",m=>{let u=m;return l.primary&&(u=u.primaryKey().references(`${r}.${s}`)),u}).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(o=>jsonObjectFrom(o.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));n=U(this.schema,t,n,r);let a=await n.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}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:a,sort:o}=t,c=this.db.selectFrom(e).selectAll(e).select(l=>jsonObjectFrom(l.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));c=Z(this.schema,e,c,r),c=U(this.schema,e,c,n),a!==void 0&&(c=c.limit(a)),o!==void 0&&o.forEach(l=>{c=c.orderBy(l.key,l.direction);});let s=await c.execute(),y=Object.fromEntries(s.map(l=>{let{id:d}=l;return [d,l]}));return Object.keys(y).length===0?{}:Object.entries(y).reduce((l,[d,m])=>(l[d]=this.convertToMaterializedLiveType(m),l),{})}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,a])=>[n,t(a)]))}async rawInsert(t,e,r){var o;let n={},a={};for(let[c,s]of Object.entries(r.value)){let y=(o=s._meta)==null?void 0:o.timestamp;y&&(n[c]=s.value,a[c]=y);}return await this.db.insertInto(t).values({...n,id:e}).execute().then(()=>{this.db.insertInto(`${t}_meta`).values({...a,id:e}).execute();}),r}async rawUpdate(t,e,r){var o;let n={},a={};for(let[c,s]of Object.entries(r.value)){let y=(o=s._meta)==null?void 0:o.timestamp;y&&(n[c]=s.value,a[c]=y);}return await Promise.all([this.db.updateTable(t).set(n).where("id","=",e).execute(),this.db.insertInto(`${t}_meta`).values({...a,id:e}).onConflict(c=>c.column("id").doUpdateSet(a)).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(a=>n.isCommitted||n.isRolledBack?a:n.releaseSavepoint(r).execute().then(()=>a))}catch(a){throw await n.rollbackToSavepoint(r).execute().catch(()=>{}),a}}let e=await this.db.startTransaction().execute();try{return await t({trx:new i(e,this.schema),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 a,o,c;return r==="_meta"||(r==="id"?e[r]={value:n}:Array.isArray(n)?e[r]={value:n.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(a=t==null?void 0:t._meta)==null?void 0:a[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?e[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(o=t==null?void 0:t._meta)==null?void 0:o[r]}}:e[r]={value:n,_meta:{timestamp:(c=t==null?void 0:t._meta)==null?void 0:c[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",a=typeof e.savepoint=="function",o=typeof e.isTransaction=="boolean"||typeof e.isTransaction=="function";return r&&n||a&&o}};var H=class i{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(t){var e;this.router=t.router,this.storage=t.storage,this.schema=t.schema,(e=t.middlewares)==null||e.forEach(r=>{this.middlewares.add(r);}),this.storage.updateSchema(this.schema),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 C(this.storage);return this.wrapInMiddlewares(async r=>{var y;let n=fe(r,this.schema,{stepId:"query",collectionName:r.resource,included:Object.keys(r.include??{})}),a={headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context},o={};for(let p=0;p<n.length;p++){let l=n[p],d=this.router.routes[l.resource];if(!d)throw new Error("Invalid resource");let m=l.getWhere&&l.referenceGetter?l.referenceGetter(o).map(l.getWhere):[void 0],u=(y=o[l.prevStepId??""])==null?void 0:y.flatMap(R=>{var M;return Object.keys(((M=R==null?void 0:R.result)==null?void 0:M.data)??{})}),T=(await Promise.allSettled(m.map(async(R,M)=>{let j=u==null?void 0:u[M],he=await d.handleQuery({req:{type:"QUERY",...l,...a,where:l.where,relationalWhere:R},batcher:e});return {includedBy:j,result:he}}))).flatMap(R=>R.status==="fulfilled"?[R.value]:[]);o[l.stepId]=T;}let c=Object.fromEntries(Object.entries(o).flatMap(([p,l],d)=>l.flatMap(m=>Object.entries(m.result.data).map(([u,f])=>[`${p}.${u}`,{data:f,includedBy:p!=="query"&&m.includedBy?`${p.split(".").slice(0,-1).join(".")}.${m.includedBy}`:void 0,path:p.split(".").slice(-1)[0],isMany:n[d].isMany,collectionName:n[d].collectionName,included:n[d].included}]))));return Object.keys(c).reduceRight((p,l)=>{var u,f;let d=c[l],m=d.path;if(m==="query"&&(p.data[l.replace("query.","")]=d.data),d.included.length)for(let T of d.included)d.data.value[T]??=((f=(u=this.schema[d.collectionName])==null?void 0:u.relations[T])==null?void 0:f.type)==="many"?{value:[]}:{value:null};if(d.includedBy){let T=c[d.includedBy];if(!T)return p;d.isMany?(T.data.value[m]??={value:[]},T.data.value[m].value.push(d.data)):T.data.value[m]=d.data;}return p},{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})})(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??{},a=t.req,o=a.resourceId;Object.keys(n).length&&o&&this.mutationSubscriptions.forEach(c=>{c({id:t.req.context.messageId,type:"MUTATE",resource:a.resource,payload:n,resourceId:o,procedure:a.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)=>a=>n({req:a,next:r}),t)(e)}},Jt=H.create;function fe(i,t,e){let{include:r,...n}=i,{stepId:a}=e,o=[{...n,...e}];if(r&&typeof r=="object"&&Object.keys(r).length>0){let c=t[n.resource];if(!c)throw new Error(`Resource ${n.resource} not found`);o.push(...Object.entries(r).flatMap(([s,y])=>{let p=c.relations[s];if(!p)throw new Error(`Relation ${s} not found for resource ${n.resource}`);let l=p.entity.name;return fe({...n,resource:l,include:y},t,{getWhere:p.type==="one"?d=>({id:d}):d=>({[p.foreignColumn]:d}),referenceGetter:d=>d[a].flatMap(m=>m.result.data?p.type==="one"?Object.values(m.result.data).map(u=>{var f,T;return (T=(f=u.value)==null?void 0:f[p.relationalColumn])==null?void 0:T.value}):Object.keys(m.result.data):[]),stepId:`${a}.${s}`,prevStepId:a,isMany:p.type==="many",collectionName:l,included:typeof y=="object"?Object.keys(y):[]})}));}return o}
2
- export{Q as Route,F as RouteFactory,V as Router,G as SQLStorage,H as Server,$ as Storage,It as expressAdapter,zt as routeFactory,Pt as router,Jt 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.4-beta.9",
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
- var x="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 L(t){let e=Math.floor(t()*32);return e===32&&(e=31),x.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=L(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 a=e;a>0;a--)n=t%32,i=x.charAt(n)+i,t=(t-n)/32;return i}function E(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function b(t,e){let n=R(),i=Date.now();return M(i,10)+A(16,n)}var N=()=>b().toLowerCase(),j=(t,e)=>typeof t=="function"?t(e):t;var I=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,a,r,s,o,T){this._collection=e,this._client=n,this._where=i??{},this._include=a??{},this._limit=r,this._single=s,this._sort=o,this._shouldAwait=T,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,a)=>{var T,y;if(a==="__isProxy__")return true;let r=(T=e.get)==null?void 0:T.call(e,i,[...n,a]);if(r!==void 0)return r;let s=i,o=a;return (y=s[o])!=null&&y.__isProxy__||(s[o]=O(typeof s[o]=="object"?s[o]:()=>{},e,[...n,a])),s[o]},apply:(i,a,r)=>{var s;return (s=e.apply)==null?void 0:s.call(e,i,n,r)}}),D=(t,e,n)=>{let i=[],a=0;for(let r=0;r<t.length&&(n===void 0||a<n);r++)e(t[r],r)&&(i.push(t[r]),a++);return i};var _=t=>{if(t)return Array.isArray(t.value)?t.value.map(e=>_(e)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([e,n])=>[e,_(n)]))};export{N as a,j as b,I as c,O as d,D as e,_ as f};
@@ -1 +0,0 @@
1
- var R=Object.create;var x=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var O=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of g(e))!M.call(t,a)&&a!==n&&x(t,a,{get:()=>e[a],enumerable:!(i=b(e,a))||i.enumerable});return t};var K=(t,e,n)=>(n=t!=null?R(I(t)):{},O(e||!t||!t.__esModule?x(n,"default",{value:t,enumerable:true}):n,t));var s=class{_value;_meta;_encodeInput;_decodeInput};var c=class extends s{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}}},l=class t extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,n,i,a,r,u,y){super(),this.storageType=e,this.convertFunc=n,this.isIndex=i??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=u,this.isPrimary=y??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 c(this)}},d=class t extends l{constructor(){super("integer",e=>Number(e));}static create(){return new t}},V=d.create,o=class t extends l{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)}},_=o.create,E=o.createId,C=o.createReference,p=class t extends l{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},F=p.create,m=class t extends l{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},q=m.create;var f=class t extends s{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,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,i)]))}mergeMutation(e,n,i){let a={};return [{value:{...(i==null?void 0:i.value)??{},...Object.fromEntries(Object.entries(n).map(([r,u])=>{let y=this.fields[r]??this.relations[r];if(!y)return [r,u];let[L,v]=y.mergeMutation(e,u,i==null?void 0:i.value[r]);return v&&(a[r]=v),[r,L]}))}},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)}},P=f.create,T=class t extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,n,i,a,r){super(),this.entity=e,this.type=n,this.required=r??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)}},$=(t,e)=>({$type:"relations",objectName:t.name,relations:e({one:T.createOneFactory(),many:T.createManyFactory()})}),h=t=>{if(t)return Array.isArray(t.value)?t.value.map(e=>h(e)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([e,n])=>[e,h(n)]))},k=t=>Object.fromEntries(Object.entries(t).flatMap(([e,n])=>{if(n.$type==="relations")return [];let i=n,a=Object.values(t).find(r=>r.$type==="relations"&&r.objectName===n.name);return a&&(i=i.setRelations(a.relations)),[[i.name,i]]}));export{j as a,K as b,s as c,c as d,l as e,d as f,V as g,o as h,_ as i,E as j,C as k,p as l,F as m,m as n,q as o,f as p,P as q,T as r,$ as s,h as t,k as u};