@live-state/sync 0.0.1-alpha.2 → 0.0.1-alpha.3

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.
@@ -0,0 +1,343 @@
1
+ import { ZodTypeAny, z } from 'zod';
2
+ import * as react_jsx_runtime from 'react/jsx-runtime';
3
+
4
+ type Promisify<T> = T extends Promise<any> ? T : Promise<T>;
5
+ type Awaitable<T> = T | Promise<T>;
6
+ type Generatable<T, Arg = never> = T | ((arg: Arg) => T);
7
+
8
+ type LiveTypeMeta = {};
9
+ type MutationType = "set";
10
+ type StorageFieldType = {
11
+ type: string;
12
+ nullable: boolean;
13
+ default?: any;
14
+ unique?: boolean;
15
+ index?: boolean;
16
+ primary?: boolean;
17
+ references?: string;
18
+ };
19
+ declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
20
+ value: Value;
21
+ _meta: keyof Meta extends never ? never : Meta;
22
+ }> {
23
+ readonly _value: Value;
24
+ readonly _meta: Meta;
25
+ readonly _encodeInput: EncodeInput;
26
+ readonly _decodeInput: DecodeInput;
27
+ abstract encodeMutation(mutationType: MutationType, input: EncodeInput, timestamp: string): DecodeInput;
28
+ /**
29
+ * Merges the materialized shape with the encoded mutation
30
+ * @param mutationType The type of mutation
31
+ * @param encodedMutation The encoded mutation
32
+ * @param materializedShape The materialized shape
33
+ * @returns A tuple of the new materialized shape and the accepted diff
34
+ */
35
+ abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
36
+ abstract getStorageFieldType(): StorageFieldType;
37
+ }
38
+ type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
39
+ type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
40
+ [K in keyof T["_value"]]: InferLiveType<T["_value"][K]>;
41
+ } : T["_value"];
42
+ type InferIndex<T extends LiveTypeAny> = string;
43
+
44
+ declare class OptionalLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | undefined, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
45
+ readonly inner: T;
46
+ constructor(inner: T);
47
+ encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): T["_decodeInput"];
48
+ mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>> | undefined): [
49
+ MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>>,
50
+ T["_decodeInput"] | null
51
+ ];
52
+ getStorageFieldType(): StorageFieldType;
53
+ }
54
+ type LiveAtomicTypeMeta = {
55
+ timestamp: string;
56
+ } & LiveTypeMeta;
57
+ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
58
+ value: Value;
59
+ _meta: LiveAtomicTypeMeta;
60
+ }> {
61
+ readonly storageType: string;
62
+ readonly convertFunc?: (value: any) => Value;
63
+ readonly isIndex: boolean;
64
+ readonly isUnique: boolean;
65
+ readonly defaultValue?: Value;
66
+ readonly foreignReference?: string;
67
+ readonly isPrimary: boolean;
68
+ constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: Value, references?: string, primary?: boolean);
69
+ encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
70
+ value: Value;
71
+ _meta: LiveAtomicTypeMeta;
72
+ };
73
+ mergeMutation(mutationType: MutationType, encodedMutation: {
74
+ value: Value;
75
+ _meta: LiveAtomicTypeMeta;
76
+ }, materializedShape?: MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
77
+ value: Value;
78
+ _meta: LiveAtomicTypeMeta;
79
+ }>>): [
80
+ MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
81
+ value: Value;
82
+ _meta: LiveAtomicTypeMeta;
83
+ }>>,
84
+ {
85
+ value: Value;
86
+ _meta: LiveAtomicTypeMeta;
87
+ } | null
88
+ ];
89
+ getStorageFieldType(): StorageFieldType;
90
+ unique(): LiveAtomicType<Value>;
91
+ index(): LiveAtomicType<Value>;
92
+ default(value: Value): LiveAtomicType<Value>;
93
+ primary(): LiveAtomicType<Value>;
94
+ optional(): OptionalLiveType<this>;
95
+ }
96
+ declare class LiveString extends LiveAtomicType<string> {
97
+ private constructor();
98
+ static create(): LiveString;
99
+ static createId(): LiveAtomicType<string>;
100
+ static createReference(foreignField: `${string}.${string}`): LiveString;
101
+ }
102
+
103
+ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
104
+ [K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
105
+ };
106
+ type InferLiveObject<T extends LiveObjectAny> = InferLiveObjectWithoutRelations<T> & {
107
+ [K in keyof T["relations"]]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
108
+ };
109
+ type InferRelationalColumns<T extends Record<string, RelationAny>> = {
110
+ [K in keyof T as T[K] extends Relation<any, any, any, infer ColumnName, any, any> ? ColumnName extends string ? ColumnName : never : never]: T[K]["type"] extends "one" ? T[K] extends Relation<infer Entity, any, any, any, any, any> ? T[K]["required"] extends true ? InferIndex<Entity> : InferIndex<Entity> | undefined : never : never;
111
+ };
112
+ type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
113
+ type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
114
+ declare class LiveObject<TName extends string, TSchema extends Record<string, LiveTypeAny>, TRelations extends Record<string, RelationAny>> extends LiveType<TSchema, LiveTypeMeta, LiveObjectMutationInput<any>, Record<string, MaterializedLiveType<LiveTypeAny>>> {
115
+ readonly name: TName;
116
+ readonly fields: TSchema;
117
+ readonly relations: TRelations;
118
+ constructor(name: TName, fields: TSchema, relations?: TRelations);
119
+ encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
120
+ mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
121
+ setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
122
+ getStorageFieldType(): StorageFieldType;
123
+ static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
124
+ }
125
+ type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
126
+ declare class Relation<TEntity extends LiveObjectAny, TSourceEntity extends LiveObjectAny, TType extends "one" | "many", TRelationalColumn extends keyof TSourceEntity["fields"], TForeignColumn extends keyof TEntity["fields"], TRequired extends boolean> extends LiveType<InferIndex<TEntity>, {
127
+ timestamp: string;
128
+ } & LiveTypeMeta> {
129
+ readonly entity: TEntity;
130
+ readonly type: TType;
131
+ readonly required: TRequired;
132
+ readonly relationalColumn?: TRelationalColumn;
133
+ readonly foreignColumn?: TForeignColumn;
134
+ readonly sourceEntity: TSourceEntity;
135
+ private constructor();
136
+ encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
137
+ value: string;
138
+ _meta: {
139
+ timestamp: string;
140
+ };
141
+ };
142
+ mergeMutation(mutationType: MutationType, encodedMutation: {
143
+ value: string;
144
+ _meta: {
145
+ timestamp: string;
146
+ };
147
+ }, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
148
+ MaterializedLiveType<LiveString>,
149
+ {
150
+ value: string;
151
+ _meta: {
152
+ timestamp: string;
153
+ };
154
+ } | null
155
+ ];
156
+ getStorageFieldType(): StorageFieldType;
157
+ static createOneFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TOriginEntity["fields"], TRequired extends boolean = false>(entity: TEntity, column: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "one", TColumn, never, TRequired>;
158
+ static createManyFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TEntity["fields"], TRequired extends boolean = false>(entity: TEntity, foreignColumn: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "many", never, TColumn, TRequired>;
159
+ }
160
+ type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
161
+ type MaterializedLiveType<T extends LiveTypeAny> = {
162
+ value: T["_value"] extends Record<string, LiveTypeAny> ? {
163
+ [K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
164
+ } : T["_value"];
165
+ _meta: T["_meta"];
166
+ };
167
+ type ExtractObjectValues<T> = T[keyof T];
168
+ type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
169
+ $type: "relations";
170
+ objectName: TObjectName;
171
+ relations: TRelations;
172
+ };
173
+ type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
174
+ [K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
175
+ [K2 in keyof TRawSchema[K]["relations"]]: Relation<ParseObjectFromSchema<TRawSchema, TRawSchema[K]["relations"][K2]["entity"]["name"]>, TRawSchema[K]["relations"][K2]["sourceEntity"], TRawSchema[K]["relations"][K2]["type"], Exclude<TRawSchema[K]["relations"][K2]["relationalColumn"], undefined>, Exclude<TRawSchema[K]["relations"][K2]["foreignColumn"], undefined>, TRawSchema[K]["relations"][K2]["required"]>;
176
+ } : never : never;
177
+ }>;
178
+ type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
179
+ [K in keyof TRawSchema]: TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] extends TObjectName ? LiveObject<TRawSchema[K]["name"], TRawSchema[K]["fields"], ParseRelationsFromSchema<TRawSchema, TRawSchema[K]["name"]>> : never : never;
180
+ }>;
181
+ type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
182
+ type Schema<TRawSchema extends RawSchema> = {
183
+ [K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
184
+ };
185
+ type WhereClause<T extends LiveObjectAny> = {
186
+ [K in keyof T["fields"]]?: InferLiveType<T["fields"][K]>;
187
+ } & {
188
+ [K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
189
+ };
190
+
191
+ type RouteRecord = Record<string, AnyRoute>;
192
+ declare class Router<TRoutes extends RouteRecord> {
193
+ readonly routes: TRoutes;
194
+ private constructor();
195
+ static create<TRoutes extends RouteRecord>(opts: {
196
+ routes: TRoutes;
197
+ }): Router<TRoutes>;
198
+ }
199
+ type AnyRouter = Router<RouteRecord>;
200
+ type RequestHandler<TInput, TResult, TSchema extends Schema<any> = Schema<any>> = (opts: {
201
+ req: ParsedRequest<TInput>;
202
+ db: Storage;
203
+ schema: TSchema;
204
+ }) => Promise<TResult>;
205
+ type Mutation<TInputValidator extends ZodTypeAny, // TODO use StandardSchema instead
206
+ THandler extends RequestHandler<z.infer<TInputValidator>, any, any>> = {
207
+ inputValidator: TInputValidator;
208
+ handler: THandler;
209
+ };
210
+ declare const mutationCreator: <TInputValidator extends ZodTypeAny>(validator?: TInputValidator) => {
211
+ handler: <THandler extends RequestHandler<z.infer<TInputValidator>, any, any>>(handler: THandler) => Mutation<TInputValidator, THandler>;
212
+ };
213
+ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends Middleware<any>, TCustomMutations extends Record<string, Mutation<any, RequestHandler<any, any>>>> {
214
+ readonly _resourceSchema: TResourceSchema;
215
+ readonly resourceName: TResourceSchema["name"];
216
+ readonly middlewares: Set<TMiddleware>;
217
+ readonly customMutations: TCustomMutations;
218
+ constructor(resourceName: TResourceSchema["name"], customMutations?: TCustomMutations);
219
+ private handleFind;
220
+ private handleSet;
221
+ handleRequest(opts: {
222
+ req: ParsedRequest;
223
+ db: Storage;
224
+ schema: Schema<any>;
225
+ }): Promise<any>;
226
+ use(...middlewares: TMiddleware[]): this;
227
+ withMutations<T extends Record<string, Mutation<any, RequestHandler<any, any>>>>(mutationFactory: (opts: {
228
+ mutation: typeof mutationCreator;
229
+ }) => T): Route<TResourceSchema, TMiddleware, T>;
230
+ }
231
+ type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
232
+
233
+ declare abstract class Storage {
234
+ abstract updateSchema(opts: Schema<any>): Promise<void>;
235
+ abstract findById<T extends LiveObjectAny>(resourceName: string, id: string): Promise<MaterializedLiveType<T> | undefined>;
236
+ abstract find<T extends LiveObjectAny>(resourceName: string, where?: Record<string, any>): Promise<Record<string, MaterializedLiveType<T>>>;
237
+ abstract upsert<T extends LiveObjectAny>(resourceName: string, resourceId: string, value: MaterializedLiveType<T>): Promise<MaterializedLiveType<T>>;
238
+ }
239
+
240
+ type ParsedRequest<TInput = any> = {
241
+ headers: Record<string, string>;
242
+ cookies: Record<string, string>;
243
+ query: Record<string, string>;
244
+ resourceName: string;
245
+ procedure?: string;
246
+ context: Record<string, any>;
247
+ where?: Record<string, any>;
248
+ type: "QUERY" | "MUTATE";
249
+ resourceId?: string;
250
+ input?: TInput;
251
+ };
252
+ type NextFunction<T> = (req: ParsedRequest) => Promise<T> | T;
253
+ type Middleware<T = any> = (opts: {
254
+ req: ParsedRequest;
255
+ next: NextFunction<T>;
256
+ }) => ReturnType<NextFunction<T>>;
257
+
258
+ type Simplify<T> = T extends Record<string, any> ? {
259
+ [K in keyof T]: Simplify<T[K]>;
260
+ } : T;
261
+
262
+ type WebSocketClientEventMap = WebSocketEventMap & {
263
+ connectionChange: {
264
+ open: boolean;
265
+ };
266
+ };
267
+ declare class WebSocketClient {
268
+ private ws;
269
+ private url;
270
+ private autoConnect;
271
+ private autoReconnect;
272
+ private reconnectTimeout;
273
+ private reconnectLimit?;
274
+ private reconnectAttempts;
275
+ private eventListeners;
276
+ private reconnectTimer;
277
+ private intentionallyDisconnected;
278
+ private credentials?;
279
+ constructor(options: {
280
+ url: string;
281
+ autoConnect?: boolean;
282
+ autoReconnect?: boolean;
283
+ reconnectTimeout?: number;
284
+ reconnectLimit?: number;
285
+ credentials?: ClientOptions["credentials"];
286
+ });
287
+ connected(): boolean;
288
+ connect(): Promise<void>;
289
+ disconnect(): void;
290
+ addEventListener<K extends keyof WebSocketClientEventMap>(event: K, callback: (event: WebSocketClientEventMap[K]) => void): void;
291
+ removeEventListener<K extends keyof WebSocketClientEventMap>(event: K, callback: (event: WebSocketClientEventMap[K]) => void): void;
292
+ send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
293
+ private handleOpen;
294
+ private handleClose;
295
+ private handleError;
296
+ private handleMessage;
297
+ private scheduleReconnect;
298
+ private dispatchEvent;
299
+ }
300
+
301
+ declare const useLiveQuery: <T extends ObservableClientState<U>, U>(observable: T, opts?: {
302
+ subscribeToRemote?: boolean;
303
+ }) => Simplify<ReturnType<T["get"]>>;
304
+ declare const SubscriptionProvider: ({ children, client, }: {
305
+ children: React.ReactNode;
306
+ client: Client<AnyRouter>["client"];
307
+ }) => react_jsx_runtime.JSX.Element;
308
+
309
+ type RawObjPool = Record<string, Record<string, MaterializedLiveType<LiveObjectAny> | undefined> | undefined>;
310
+ type ClientState<TRouter extends AnyRouter> = {
311
+ [K in keyof TRouter["routes"]]: Record<InferIndex<TRouter["routes"][K]["_resourceSchema"]>, InferLiveObject<TRouter["routes"][K]["_resourceSchema"]>> | undefined;
312
+ };
313
+ type ObservableClientState<T> = {
314
+ [K in keyof T]: ObservableClientState<T[K]>;
315
+ } & {
316
+ get: () => T;
317
+ subscribe: (callback: (value: T) => void) => () => void;
318
+ subscribeToRemote: () => () => void;
319
+ };
320
+ type Client<TRouter extends AnyRouter> = {
321
+ client: {
322
+ ws: WebSocketClient;
323
+ subscribeToRemote: (resourceType?: string[]) => () => void;
324
+ };
325
+ store: ObservableClientState<ClientState<TRouter>> & {
326
+ [K in keyof TRouter["routes"]]: {
327
+ insert: (input: Simplify<LiveObjectMutationInput<TRouter["routes"][K]["_resourceSchema"]>>) => void;
328
+ update: (id: string, value: Omit<Simplify<LiveObjectMutationInput<TRouter["routes"][K]["_resourceSchema"]>>, "id">) => void;
329
+ };
330
+ } & {
331
+ [K in keyof TRouter["routes"]]: {
332
+ [K2 in keyof TRouter["routes"][K]["customMutations"]]: (input: z.infer<TRouter["routes"][K]["customMutations"][K2]["inputValidator"]>) => Promisify<ReturnType<TRouter["routes"][K]["customMutations"][K2]["handler"]>>;
333
+ };
334
+ };
335
+ };
336
+ type ClientOptions = {
337
+ url: string;
338
+ schema: Schema<any>;
339
+ credentials?: Generatable<Awaitable<Record<string, string>>>;
340
+ };
341
+ declare const createClient: <TRouter extends AnyRouter>(opts: ClientOptions) => Client<TRouter>;
342
+
343
+ export { type AnyRouter as A, type ClientOptions as C, type InferLiveObject as I, type LiveObjectAny as L, type ObservableClientState as O, type RawObjPool as R, type Simplify as S, type WhereClause as W, type LiveObjectMutationInput as a, type ClientState as b, type Client as c, createClient as d, SubscriptionProvider as e, useLiveQuery as u };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var o=class{_value;_meta;_encodeInput;_decodeInput};var c=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,t,n){return this.inner.encodeMutation(e,t,n)}mergeMutation(e,t,n){return this.inner.mergeMutation(e,t,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class a extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,t,n,r,i,y,T){super(),this.storageType=e,this.convertFunc=t,this.isIndex=n??false,this.isUnique=r??false,this.defaultValue=i,this.foreignReference=y,this.isPrimary=T??false;}encodeMutation(e,t,n){return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(t.value):t.value,_meta:t._meta},t]}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 a(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new a(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}optional(){return new c(this)}},d=class a extends l{constructor(){super("integer",e=>Number(e));}static create(){return new a}},b=d.create,s=class a extends l{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new a}static createId(){return new a().index().unique().primary()}static createReference(e){return new a(e)}},M=s.create,O=s.createId,j=s.createReference;var p=class a extends o{name;fields;relations;constructor(e,t,n){super(),this.name=e,this.fields=t,this.relations=n??{};}encodeMutation(e,t,n){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,n)]))}mergeMutation(e,t,n){let r={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(t).map(([i,y])=>{let[T,m]=(this.fields[i]??this.relations[i]).mergeMutation(e,y,n==null?void 0:n.value[i]);return m&&(r[i]=m),[i,T]}))}},r]}setRelations(e){return new a(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,t){return new a(e,t)}},F=p.create,u=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,t,n,r,i){super(),this.entity=e,this.type=t,this.required=i??false,this.relationalColumn=n,this.foreignColumn=r;}encodeMutation(e,t,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){if(this.type==="many")throw new Error("Many not implemented.");return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[t,t]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}static createOneFactory(){return (e,t,n)=>new a(e,"one",t,void 0,n??false)}static createManyFactory(){return (e,t,n)=>new a(e,"many",void 0,t,n??false)}},C=(a,e)=>({$type:"relations",objectName:a.name,relations:e({one:u.createOneFactory(),many:u.createManyFactory()})}),v=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>v(e)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,v(t)]))},q=a=>Object.fromEntries(Object.entries(a).flatMap(([e,t])=>{if(t.$type==="relations")return [];let n=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(n=n.setRelations(r.relations)),[[n.name,n]]}));exports.LiveNumber=d;exports.LiveObject=p;exports.LiveString=s;exports.LiveType=o;exports.Relation=u;exports.createRelations=C;exports.createSchema=q;exports.id=O;exports.inferValue=v;exports.number=b;exports.object=F;exports.reference=j;exports.string=M;
1
+ 'use strict';var o=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,t,n){return this.inner.encodeMutation(e,t,n)}mergeMutation(e,t,n){return this.inner.mergeMutation(e,t,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},s=class a extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,t,n,r,i,y,c){super(),this.storageType=e,this.convertFunc=t,this.isIndex=n??false,this.isUnique=r??false,this.defaultValue=i,this.foreignReference=y,this.isPrimary=c??false;}encodeMutation(e,t,n){return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(t.value):t.value,_meta:t._meta},t]}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 a(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new a(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}optional(){return new T(this)}},d=class a extends s{constructor(){super("integer",e=>Number(e));}static create(){return new a}},O=d.create,l=class a extends s{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new a}static createId(){return new a().index().unique().primary()}static createReference(e){return new a(e)}},j=l.create,S=l.createId,w=l.createReference,p=class a extends s{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new a}},I=p.create,m=class a extends s{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new a}},A=m.create;var v=class a extends o{name;fields;relations;constructor(e,t,n){super(),this.name=e,this.fields=t,this.relations=n??{};}encodeMutation(e,t,n){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,n)]))}mergeMutation(e,t,n){let r={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(t).map(([i,y])=>{let[c,f]=(this.fields[i]??this.relations[i]).mergeMutation(e,y,n==null?void 0:n.value[i]);return f&&(r[i]=f),[i,c]}))}},r]}setRelations(e){return new a(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,t){return new a(e,t)}},P=v.create,u=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,t,n,r,i){super(),this.entity=e,this.type=t,this.required=i??false,this.relationalColumn=n,this.foreignColumn=r;}encodeMutation(e,t,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){if(this.type==="many")throw new Error("Many not implemented.");return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[t,t]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}static createOneFactory(){return (e,t,n)=>new a(e,"one",t,void 0,n??false)}static createManyFactory(){return (e,t,n)=>new a(e,"many",void 0,t,n??false)}},D=(a,e)=>({$type:"relations",objectName:a.name,relations:e({one:u.createOneFactory(),many:u.createManyFactory()})}),h=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>h(e)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,h(t)]))},k=a=>Object.fromEntries(Object.entries(a).flatMap(([e,t])=>{if(t.$type==="relations")return [];let n=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(n=n.setRelations(r.relations)),[[n.name,n]]}));exports.LiveBoolean=p;exports.LiveNumber=d;exports.LiveObject=v;exports.LiveString=l;exports.LiveTimestamp=m;exports.LiveType=o;exports.Relation=u;exports.boolean=I;exports.createRelations=D;exports.createSchema=k;exports.id=S;exports.inferValue=h;exports.number=O;exports.object=P;exports.reference=w;exports.string=j;exports.timestamp=A;
package/dist/index.d.cts CHANGED
@@ -100,6 +100,16 @@ declare class LiveString extends LiveAtomicType<string> {
100
100
  declare const string: typeof LiveString.create;
101
101
  declare const id: typeof LiveString.createId;
102
102
  declare const reference: typeof LiveString.createReference;
103
+ declare class LiveBoolean extends LiveAtomicType<boolean> {
104
+ private constructor();
105
+ static create(): LiveBoolean;
106
+ }
107
+ declare const boolean: typeof LiveBoolean.create;
108
+ declare class LiveTimestamp extends LiveAtomicType<Date> {
109
+ private constructor();
110
+ static create(): LiveTimestamp;
111
+ }
112
+ declare const timestamp: typeof LiveTimestamp.create;
103
113
 
104
114
  type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
105
115
  [K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
@@ -196,4 +206,4 @@ type WhereClause<T extends LiveObjectAny> = {
196
206
  [K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
197
207
  };
198
208
 
199
- export { type InferIndex, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, createRelations, createSchema, id, inferValue, number, object, reference, string };
209
+ export { type InferIndex, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
package/dist/index.d.ts CHANGED
@@ -100,6 +100,16 @@ declare class LiveString extends LiveAtomicType<string> {
100
100
  declare const string: typeof LiveString.create;
101
101
  declare const id: typeof LiveString.createId;
102
102
  declare const reference: typeof LiveString.createReference;
103
+ declare class LiveBoolean extends LiveAtomicType<boolean> {
104
+ private constructor();
105
+ static create(): LiveBoolean;
106
+ }
107
+ declare const boolean: typeof LiveBoolean.create;
108
+ declare class LiveTimestamp extends LiveAtomicType<Date> {
109
+ private constructor();
110
+ static create(): LiveTimestamp;
111
+ }
112
+ declare const timestamp: typeof LiveTimestamp.create;
103
113
 
104
114
  type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
105
115
  [K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
@@ -196,4 +206,4 @@ type WhereClause<T extends LiveObjectAny> = {
196
206
  [K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
197
207
  };
198
208
 
199
- export { type InferIndex, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, createRelations, createSchema, id, inferValue, number, object, reference, string };
209
+ export { type InferIndex, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import'./chunk-EK7ODJWE.js';var o=class{_value;_meta;_encodeInput;_decodeInput};var c=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,t,n){return this.inner.encodeMutation(e,t,n)}mergeMutation(e,t,n){return this.inner.mergeMutation(e,t,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class a extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,t,n,r,i,y,T){super(),this.storageType=e,this.convertFunc=t,this.isIndex=n??false,this.isUnique=r??false,this.defaultValue=i,this.foreignReference=y,this.isPrimary=T??false;}encodeMutation(e,t,n){return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(t.value):t.value,_meta:t._meta},t]}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 a(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new a(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}optional(){return new c(this)}},d=class a extends l{constructor(){super("integer",e=>Number(e));}static create(){return new a}},b=d.create,s=class a extends l{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new a}static createId(){return new a().index().unique().primary()}static createReference(e){return new a(e)}},M=s.create,O=s.createId,j=s.createReference;var p=class a extends o{name;fields;relations;constructor(e,t,n){super(),this.name=e,this.fields=t,this.relations=n??{};}encodeMutation(e,t,n){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,n)]))}mergeMutation(e,t,n){let r={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(t).map(([i,y])=>{let[T,m]=(this.fields[i]??this.relations[i]).mergeMutation(e,y,n==null?void 0:n.value[i]);return m&&(r[i]=m),[i,T]}))}},r]}setRelations(e){return new a(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,t){return new a(e,t)}},F=p.create,u=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,t,n,r,i){super(),this.entity=e,this.type=t,this.required=i??false,this.relationalColumn=n,this.foreignColumn=r;}encodeMutation(e,t,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){if(this.type==="many")throw new Error("Many not implemented.");return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[t,t]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}static createOneFactory(){return (e,t,n)=>new a(e,"one",t,void 0,n??false)}static createManyFactory(){return (e,t,n)=>new a(e,"many",void 0,t,n??false)}},C=(a,e)=>({$type:"relations",objectName:a.name,relations:e({one:u.createOneFactory(),many:u.createManyFactory()})}),v=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>v(e)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,v(t)]))},q=a=>Object.fromEntries(Object.entries(a).flatMap(([e,t])=>{if(t.$type==="relations")return [];let n=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(n=n.setRelations(r.relations)),[[n.name,n]]}));export{d as LiveNumber,p as LiveObject,s as LiveString,o as LiveType,u as Relation,C as createRelations,q as createSchema,O as id,v as inferValue,b as number,F as object,j as reference,M as string};
1
+ import'./chunk-EK7ODJWE.js';var o=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,t,n){return this.inner.encodeMutation(e,t,n)}mergeMutation(e,t,n){return this.inner.mergeMutation(e,t,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},s=class a extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,t,n,r,i,y,c){super(),this.storageType=e,this.convertFunc=t,this.isIndex=n??false,this.isUnique=r??false,this.defaultValue=i,this.foreignReference=y,this.isPrimary=c??false;}encodeMutation(e,t,n){return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(t.value):t.value,_meta:t._meta},t]}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 a(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new a(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}optional(){return new T(this)}},d=class a extends s{constructor(){super("integer",e=>Number(e));}static create(){return new a}},O=d.create,l=class a extends s{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new a}static createId(){return new a().index().unique().primary()}static createReference(e){return new a(e)}},j=l.create,S=l.createId,w=l.createReference,p=class a extends s{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new a}},I=p.create,m=class a extends s{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new a}},A=m.create;var v=class a extends o{name;fields;relations;constructor(e,t,n){super(),this.name=e,this.fields=t,this.relations=n??{};}encodeMutation(e,t,n){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,n)]))}mergeMutation(e,t,n){let r={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(t).map(([i,y])=>{let[c,f]=(this.fields[i]??this.relations[i]).mergeMutation(e,y,n==null?void 0:n.value[i]);return f&&(r[i]=f),[i,c]}))}},r]}setRelations(e){return new a(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,t){return new a(e,t)}},P=v.create,u=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,t,n,r,i){super(),this.entity=e,this.type=t,this.required=i??false,this.relationalColumn=n,this.foreignColumn=r;}encodeMutation(e,t,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){if(this.type==="many")throw new Error("Many not implemented.");return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[t,t]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}static createOneFactory(){return (e,t,n)=>new a(e,"one",t,void 0,n??false)}static createManyFactory(){return (e,t,n)=>new a(e,"many",void 0,t,n??false)}},D=(a,e)=>({$type:"relations",objectName:a.name,relations:e({one:u.createOneFactory(),many:u.createManyFactory()})}),h=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>h(e)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,h(t)]))},k=a=>Object.fromEntries(Object.entries(a).flatMap(([e,t])=>{if(t.$type==="relations")return [];let n=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(n=n.setRelations(r.relations)),[[n.name,n]]}));export{p as LiveBoolean,d as LiveNumber,v as LiveObject,l as LiveString,m as LiveTimestamp,o as LiveType,u as Relation,I as boolean,D as createRelations,k as createSchema,S as id,h as inferValue,O as number,P as object,w as reference,j as string,A as timestamp};
package/dist/server.cjs CHANGED
@@ -1 +1,2 @@
1
- 'use strict';var zod=require('zod'),kysely=require('kysely'),S=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var S__default=/*#__PURE__*/_interopDefault(S);var B=Object.create;var O=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var Y=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var J=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!K.call(r,i)&&i!==t&&O(r,i,{get:()=>e[i],enumerable:!(n=G(e,i))||n.enumerable});return r};var X=(r,e,t)=>(t=r!=null?B(Q(r)):{},J(O(t,"default",{value:r,enumerable:true}),r));var U=Y(M=>{Object.defineProperty(M,"__esModule",{value:true});M.parse=de;M.serialize=le;var ie=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ae=/^[\u0021-\u003A\u003C-\u007E]*$/,oe=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,se=/^[\u0020-\u003A\u003D-\u007E]*$/,ce=Object.prototype.toString,ue=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function de(r,e){let t=new ue,n=r.length;if(n<2)return t;let i=(e==null?void 0:e.decode)||pe,a=0;do{let c=r.indexOf("=",a);if(c===-1)break;let u=r.indexOf(";",a),o=u===-1?n:u;if(c>o){a=r.lastIndexOf(";",c-1)+1;continue}let s=z(r,a,c),p=P(r,c,s),m=r.slice(s,p);if(t[m]===void 0){let b=z(r,c+1,o),y=P(r,o,b),f=i(r.slice(b,y));t[m]=f;}a=o+1;}while(a<n);return t}function z(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function P(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function le(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!ie.test(r))throw new TypeError(`argument name is invalid: ${r}`);let i=n(e);if(!ae.test(i))throw new TypeError(`argument val is invalid: ${e}`);let a=r+"="+i;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!oe.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!se.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!me(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.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: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.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: ${t.sameSite}`)}return a}function pe(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function me(r){return ce.call(r)==="[object Date]"}});var w=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},Oe=r=>w.create({...r}),te=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),v=class r{_resourceSchema;resourceName;middlewares;customMutations;constructor(e,t){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{};}handleFind=async({req:e,db:t})=>({data:await t.find(e.resourceName,e.where),acceptedValues:null});handleSet=async({req:e,db:t,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let i=await t.findById(e.resourceName,e.resourceId),[a,c]=n[this.resourceName].mergeMutation("set",e.input,i);if(!c)throw new Error("Mutation rejected");return {data:await t.upsert(e.resourceName,e.resourceId,a),acceptedValues:c}};async handleRequest(e){let t=n=>(()=>{if(n.type==="QUERY")return this.handleFind({req:n,db:e.db,schema:e.schema});if(n.type==="MUTATE")if(n.procedure){if(this.customMutations[n.procedure]){let i=this.customMutations[n.procedure].inputValidator.parse(n.input);return n.input=i,this.customMutations[n.procedure].handler({req:n,db:e.db,schema:e.schema})}}else return this.handleSet({req:n,db:e.db,schema:e.schema});throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>t(n))(e.req)}use(e){return this.middlewares.add(e),this}withMutations(e){return new r(this.resourceName,e({mutation:te}))}},je=()=>r=>new v(r.name);var R=class{},j=class extends R{storage={};async updateSchema(e){this.storage=Object.entries(e).reduce((t,[n,i])=>(t[i.name]={},t),{});}async findById(e,t){var n;return (n=this.storage[e])==null?void 0:n[t]}async find(e,t){return this.storage[e]??{}}async upsert(e,t,n){return this.storage[e]??={},this.storage[e][t]=n,n}},C=class extends R{db;schema;constructor(e){super(),this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})});}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,i]of Object.entries(e)){let a=t.find(o=>o.name===n);a||await this.db.schema.createTable(n).ifNotExists().execute();let c=`${n}_meta`,u=t.find(o=>o.name===c);u||await this.db.schema.createTable(c).ifNotExists().execute();for(let[o,s]of Object.entries(i.fields)){let p=a==null?void 0:a.columns.find(y=>y.name===o),m=s.getStorageFieldType();p?p.dataType!==m.type&&console.error("Column type mismatch:",o,"expected to have type:",m.type,"but has type:",p.dataType):(await this.db.schema.alterTable(n).addColumn(o,m.type,y=>{let f=y;return m.unique&&(f=f.unique()),m.nullable||(f=f.notNull()),m.references&&(f=f.references(m.references)),m.primary&&(f=f.primaryKey()),f}).execute().catch(y=>{throw console.error("Error adding column",o,y),y}),m.index&&await this.db.schema.createIndex(`${n}_${o}_index`).on(n).column(o).execute().catch(y=>{})),(u==null?void 0:u.columns.find(y=>y.name===o))||await this.db.schema.alterTable(c).addColumn(o,"varchar",y=>{let f=y;return m.primary&&(f=f.primaryKey().references(`${n}.${o}`)),f}).execute();}}}async findById(e,t){let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).executeTakeFirst(),i=await this.db.selectFrom(`${e}_meta`).where("id","=",t).selectAll(`${e}_meta`).executeTakeFirst();if(!(!n||!i))return this.convertToMaterializedLiveType(n,i)}async find(e,t){let i=await this.applyWhere(e,this.db.selectFrom(e).selectAll(e),t).execute(),a=Object.fromEntries(i.map(o=>{let{id:s,...p}=o;return [s,p]}));if(Object.keys(a).length===0)return {};let c=Object.fromEntries((await this.db.selectFrom(`${e}_meta`).selectAll().where("id","in",Object.keys(a)).execute()).map(o=>{let{id:s,...p}=o;return [s,p]}));return Object.entries(a).reduce((o,[s,p])=>(c[s]&&(o[s]=this.convertToMaterializedLiveType(p,c[s])),o),{})}async upsert(e,t,n){return await this.db.transaction().execute(async i=>{let a=!!await i.selectFrom(e).select("id").where("id","=",t).executeTakeFirst(),c={},u={};for(let[o,s]of Object.entries(n.value))c[o]=s.value,u[o]=s._meta.timestamp;a?await Promise.all([i.updateTable(e).set(c).where("id","=",t).execute(),i.updateTable(`${e}_meta`).set(u).where("id","=",t).execute()]):await Promise.all([i.insertInto(e).values({...c,id:t}).execute(),i.insertInto(`${e}_meta`).values({...u,id:t}).execute()]);}),n}convertToMaterializedLiveType(e,t){return {value:Object.fromEntries(Object.entries(e).flatMap(([n,i])=>t?[[n,{value:i,_meta:{timestamp:t==null?void 0:t[n]}}]]:[]))}}applyWhere(e,t,n){if(!n)return t;if(!this.schema)throw new Error("Schema not initialized");let i=this.schema[e];if(!i)throw new Error("Resource not found");for(let[a,c]of Object.entries(n))if(i.fields[a])t=t.where(`${e}.${a}`,"=",c);else if(i.relations[a]){let u=i.relations[a],o=u.entity.name,s=u.type==="one"?"id":u.foreignColumn,p=u.type==="one"?u.relationalColumn:"id";t=t.leftJoin(o,`${o}.${s}`,`${e}.${p}`),t=this.applyWhere(o,t,c);}return t}};var q=X(U());zod.z.object({type:zod.z.literal("QUERY"),resource:zod.z.string(),where:zod.z.record(zod.z.any()).optional(),include:zod.z.record(zod.z.any()).optional()});var I=zod.z.record(zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()),_meta:zod.z.object({timestamp:zod.z.string().optional()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),D=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string()}),E=D.extend({procedure:zod.z.string(),payload:zod.z.any()}),A=D.extend({resourceId:zod.z.string(),payload:I});zod.z.union([E,A]);var h=zod.z.string(),ye=zod.z.object({id:h,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),fe=zod.z.object({id:h,type:zod.z.literal("SYNC"),lastSyncedAt:zod.z.string().optional(),resources:zod.z.string().array().optional(),where:zod.z.record(zod.z.any()).optional()}),V=A.extend({id:h}),he=E.extend({id:h}),ge=zod.z.union([he,V]),$=zod.z.union([ye,fe,ge]),Te=zod.z.object({id:h,type:zod.z.literal("SYNC"),resource:zod.z.string(),data:zod.z.record(I)}),be=zod.z.object({id:h,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),xe=zod.z.object({id:h,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Te,be,xe,V]);var _="0123456789ABCDEFGHJKMNPQRSTVWXYZ",x=32;var Re=16,F=10,k=0xffffffffffff;var g;(function(r){r.Base32IncorrectEncoding="B32_ENC_INVALID",r.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",r.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",r.EncodeTimeNegative="ENC_TIME_NEG",r.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",r.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",r.PRNGDetectFailure="PRNG_DETECT",r.ULIDInvalid="ULID_INVALID",r.Unexpected="UNEXPECTED",r.UUIDInvalid="UUID_INVALID";})(g||(g={}));var T=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Me(r){let e=Math.floor(r()*x);return e===x&&(e=x-1),_.charAt(e)}function Se(r){var n;let e=we(),t=e&&(e.crypto||e.msCrypto)||(typeof S__default.default<"u"?S__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return t.getRandomValues(i),i[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=S__default.default)!=null&&n.randomBytes)return ()=>S__default.default.randomBytes(1).readUInt8()/255;throw new T(g.PRNGDetectFailure,"Failed to find a reliable PRNG")}function we(){return Ee()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function ve(r,e){let t="";for(;r>0;r--)t=Me(e)+t;return t}function Ie(r,e=F){if(isNaN(r))throw new T(g.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>k)throw new T(g.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${k}: ${r}`);if(r<0)throw new T(g.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new T(g.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%x,n=_.charAt(t)+n,r=(r-t)/x;return n}function Ee(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Z(r,e){let t=Se(),n=Date.now();return Ie(n,F)+ve(Re,t)}var L=()=>Z().toLowerCase();var tt=r=>{let e={},t={};return r.subscribeToMutations(n=>{let i=n;!i.resourceId||!i.payload||(console.log("Mutation propagated:",i),Object.entries(t[i.resource]??{}).forEach(([a,c])=>{var u;(u=e[a])==null||u.send(JSON.stringify({...i,id:i.id??L()}));}));}),(n,i)=>{let a=o=>{n.send(JSON.stringify(o));},c=L(),u={headers:i.headers,cookies:typeof i.headers.cookie=="string"?q.default.parse(i.headers.cookie):{}};e[c]=n,console.log("Client connected:",c),n.on("message",async o=>{try{console.log("Message received from the client:",o);let s=$.parse(JSON.parse(o.toString()));if(s.type==="SUBSCRIBE"){let{resource:p}=s;t[p]||(t[p]={}),t[p][c]={};}else if(s.type==="SYNC"){let{resources:p}=s,m=p??Object.keys(r.schema);console.log("Syncing resources:",m),await Promise.all(m.map(async b=>{let y=await r.handleRequest({req:{...u,type:"QUERY",resourceName:b,context:{}}});if(!y||!y.data)throw new Error("Invalid resource");a({id:s.id,type:"SYNC",resource:b,data:Object.fromEntries(Object.entries(y.data??{}).map(([f,H])=>[f,H.value]))});}));}else if(s.type==="MUTATE"){let{resource:p}=s;console.log("Received mutation from client:",s);try{let m=await r.handleRequest({req:{...u,type:"MUTATE",resourceName:p,input:s.payload,context:{messageId:s.id},resourceId:s.resourceId,procedure:s.procedure}});s.procedure&&a({id:s.id,type:"REPLY",data:m});}catch(m){a({id:s.id,type:"REJECT",resource:p,message:m.message}),console.error("Error parsing mutation from the client:",m);}}}catch(s){console.error("Error handling message from the client:",s);}}),n.on("close",()=>{console.log("Connection closed",c),delete e[c];});}};var N=class r{router;storage;schema;middlewares=new Set;mutationSubscriptions=new Set;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.storage.updateSchema(this.schema);}static create(e){return new r(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>this.router.routes[e.req.resourceName].handleRequest({req:n,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&this.mutationSubscriptions.forEach(n=>{n({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId});}),t}use(e){return this.middlewares.add(e),this}},nt=N.create;exports.InMemoryStorage=j;exports.Route=v;exports.Router=w;exports.SQLStorage=C;exports.Server=N;exports.Storage=R;exports.routeFactory=je;exports.router=Oe;exports.server=nt;exports.webSocketAdapter=tt;
1
+ 'use strict';var Se=require('qs'),zod=require('zod'),I=require('crypto'),kysely=require('kysely');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Se__default=/*#__PURE__*/_interopDefault(Se);var I__default=/*#__PURE__*/_interopDefault(I);var oe=Object.create;var U=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty;var de=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var le=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of se(e))!ue.call(r,a)&&a!==t&&U(r,a,{get:()=>e[a],enumerable:!(n=ie(e,a))||n.enumerable});return r};var V=(r,e,t)=>(t=r!=null?oe(ce(r)):{},le(U(t,"default",{value:r,enumerable:true}),r));var P=de(E=>{Object.defineProperty(E,"__esModule",{value:true});E.parse=Te;E.serialize=Re;var pe=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,me=/^[\u0021-\u003A\u003C-\u007E]*$/,ye=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,fe=/^[\u0020-\u003A\u003D-\u007E]*$/,he=Object.prototype.toString,ge=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function Te(r,e){let t=new ge,n=r.length;if(n<2)return t;let a=(e==null?void 0:e.decode)||xe,o=0;do{let i=r.indexOf("=",o);if(i===-1)break;let u=r.indexOf(";",o),s=u===-1?n:u;if(i>s){o=r.lastIndexOf(";",i-1)+1;continue}let h=_(r,o,i),m=$(r,i,h),l=r.slice(h,m);if(t[l]===void 0){let p=_(r,i+1,s),d=$(r,s,p),c=a(r.slice(p,d));t[l]=c;}o=s+1;}while(o<n);return t}function _(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function $(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Re(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!pe.test(r))throw new TypeError(`argument name is invalid: ${r}`);let a=n(e);if(!me.test(a))throw new TypeError(`argument val is invalid: ${e}`);let o=r+"="+a;if(!t)return o;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);o+="; Max-Age="+t.maxAge;}if(t.domain){if(!ye.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!fe.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!be(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);o+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(o+="; HttpOnly"),t.secure&&(o+="; Secure"),t.partitioned&&(o+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":o+="; Priority=Low";break;case "medium":o+="; Priority=Medium";break;case "high":o+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":o+="; SameSite=Strict";break;case "lax":o+="; SameSite=Lax";break;case "none":o+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return o}function xe(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function be(r){return he.call(r)==="[object Date]"}});var H=V(P());var q=zod.z.object({type:zod.z.literal("QUERY"),resource:zod.z.string(),where:zod.z.record(zod.z.any()).optional(),include:zod.z.record(zod.z.any()).optional()}),L=zod.z.record(zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()),_meta:zod.z.object({timestamp:zod.z.string().optional()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),F=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string()}),S=F.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),M=F.extend({resourceId:zod.z.string(),payload:L});zod.z.union([S,M]);var Z=q.omit({type:true,resource:true}),N=S.omit({id:true,type:true,resource:true,procedure:true}),j=M.omit({id:true,type:true,resource:true});zod.z.union([j,N]);var G=r=>async e=>{var t;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,a={headers:n,cookies:n.cookie?H.default.parse(n.cookie):{}},o=new URL(e.url),i=o.pathname.split("/"),u=o.searchParams,s=Se__default.default.parse(u.toString()),h=await((t=r.contextProvider)==null?void 0:t.call(r,{transport:"HTTP",headers:a.headers,cookies:a.cookies,query:s}))??{};if(e.method==="GET"){let m=i[i.length-1],{success:l,data:p,error:d}=Z.safeParse(s);if(!l)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:d},{status:400});let c=await r.handleRequest({req:{...a,type:"QUERY",resourceName:m,context:h,where:p.where,query:s}});return !c||!c.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(c.data)}if(e.method==="POST")try{let m=i[i.length-1],l=i[i.length-2],p=e.body?await e.json():{},d;if(m==="set"){let{success:b,data:g,error:w}=j.safeParse(p);if(!b)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:w},{status:400});d=g;}else {let{success:b,data:g,error:w}=N.safeParse(p);if(!b)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:w},{status:400});d=g;}let c=await r.handleRequest({req:{...a,type:"MUTATE",resourceName:l,input:d.payload,context:h,resourceId:d.resourceId,procedure:m!=="set"?m:void 0,query:{}}});return Response.json(c)}catch(m){return console.error("Error parsing mutation from the client:",m),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return console.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var X=V(P());var T=zod.z.string(),Me=zod.z.object({id:T,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),ve=zod.z.object({id:T,type:zod.z.literal("SYNC"),lastSyncedAt:zod.z.string().optional(),resources:zod.z.string().array().optional(),where:zod.z.record(zod.z.any()).optional()}),B=M.extend({id:T}),Ee=S.extend({id:T}),Ie=zod.z.union([Ee,B]),Q=zod.z.union([Me,ve,Ie]),Ae=zod.z.object({id:T,type:zod.z.literal("SYNC"),resource:zod.z.string(),data:zod.z.record(L)}),Pe=zod.z.object({id:T,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),Le=zod.z.object({id:T,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Ae,Pe,Le,B]);var K="0123456789ABCDEFGHJKMNPQRSTVWXYZ",v=32;var Ne=16,Y=10,W=0xffffffffffff;var R;(function(r){r.Base32IncorrectEncoding="B32_ENC_INVALID",r.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",r.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",r.EncodeTimeNegative="ENC_TIME_NEG",r.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",r.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",r.PRNGDetectFailure="PRNG_DETECT",r.ULIDInvalid="ULID_INVALID",r.Unexpected="UNEXPECTED",r.UUIDInvalid="UUID_INVALID";})(R||(R={}));var x=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function je(r){let e=Math.floor(r()*v);return e===v&&(e=v-1),K.charAt(e)}function Oe(r){var n;let e=Ce(),t=e&&(e.crypto||e.msCrypto)||(typeof I__default.default<"u"?I__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let a=new Uint8Array(1);return t.getRandomValues(a),a[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=I__default.default)!=null&&n.randomBytes)return ()=>I__default.default.randomBytes(1).readUInt8()/255;throw new x(R.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ce(){return De()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function ze(r,e){let t="";for(;r>0;r--)t=je(e)+t;return t}function ke(r,e=Y){if(isNaN(r))throw new x(R.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>W)throw new x(R.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${W}: ${r}`);if(r<0)throw new x(R.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new x(R.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let a=e;a>0;a--)t=r%v,n=K.charAt(t)+n,r=(r-t)/v;return n}function De(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function J(r,e){let t=Oe(),n=Date.now();return ke(n,Y)+ze(Ne,t)}var O=()=>J().toLowerCase();var ee=r=>{let e={},t={};return r.subscribeToMutations(n=>{let a=n;!a.resourceId||!a.payload||(console.log("Mutation propagated:",a),Object.entries(t[a.resource]??{}).forEach(([o,i])=>{var u;(u=e[o])==null||u.send(JSON.stringify({...a,id:a.id??O()}));}));}),(n,a)=>{var m;let o=l=>{n.send(JSON.stringify(l));},i=O(),u={headers:a.headers,cookies:typeof a.headers.cookie=="string"?X.default.parse(a.headers.cookie):{}},s=Se.parse(a.url.split("?")[1]),h=(m=r.contextProvider)==null?void 0:m.call(r,{transport:"WEBSOCKET",headers:u.headers,cookies:u.cookies,query:s});e[i]=n,console.log("Client connected:",i),n.on("message",async l=>{try{console.log("Message received from the client:",l);let p=Q.parse(JSON.parse(l.toString()));if(p.type==="SUBSCRIBE"){let{resource:d}=p;t[d]||(t[d]={}),t[d][i]={};}else if(p.type==="SYNC"){let{resources:d}=p,c=d??Object.keys(r.schema);console.log("Syncing resources:",c),await Promise.all(c.map(async b=>{let g=await r.handleRequest({req:{...u,type:"QUERY",resourceName:b,context:await h??{},query:s}});if(!g||!g.data)throw new Error("Invalid resource");o({id:p.id,type:"SYNC",resource:b,data:Object.fromEntries(Object.entries(g.data??{}).map(([w,ae])=>[w,ae.value]))});}));}else if(p.type==="MUTATE"){let{resource:d}=p;console.log("Received mutation from client:",p);try{let c=await r.handleRequest({req:{...u,type:"MUTATE",resourceName:d,input:p.payload,context:{messageId:p.id,...await h??{}},resourceId:p.resourceId,procedure:p.procedure,query:s}});p.procedure&&o({id:p.id,type:"REPLY",data:c});}catch(c){o({id:p.id,type:"REJECT",resource:d,message:c.message}),console.error("Error parsing mutation from the client:",c);}}}catch(p){console.error("Error handling message from the client:",p);}}),n.on("close",()=>{console.log("Connection closed",i),delete e[i];for(let l of Object.values(t))delete l[i];});}};function te(r){let e=`${r.protocol}://${r.hostname}${r.url}`,t=new Headers;return Object.entries(r.headers).forEach(([n,a])=>{a&&t.set(n,Array.isArray(a)?a.join(","):a);}),new Request(e,{method:r.method,headers:t,body:r.body&&r.method!=="GET"?JSON.stringify(r.body):void 0})}var xt=(r,e,t)=>{r.ws(`${(t==null?void 0:t.basePath)??""}/ws`,ee(e)),r.use(`${(t==null?void 0:t.basePath)??""}/`,(n,a)=>{G(e)(te(n)).then(i=>i.json().then(u=>a.status(i.status).send(u)));});};var C=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},Mt=r=>C.create({...r}),_e=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),z=class r{_resourceSchema;resourceName;middlewares;customMutations;constructor(e,t){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{};}handleFind=async({req:e,db:t})=>({data:await t.find(e.resourceName,e.where),acceptedValues:null});handleSet=async({req:e,db:t,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.findById(e.resourceName,e.resourceId),[o,i]=n[this.resourceName].mergeMutation("set",e.input,a);if(!i)throw new Error("Mutation rejected");return {data:await t.upsert(e.resourceName,e.resourceId,o),acceptedValues:i}};async handleRequest(e){let t=n=>(()=>{if(n.type==="QUERY")return this.handleFind({req:n,db:e.db,schema:e.schema});if(n.type==="MUTATE")if(n.procedure){if(this.customMutations[n.procedure]){let a=this.customMutations[n.procedure].inputValidator.parse(n.input);return n.input=a,this.customMutations[n.procedure].handler({req:n,db:e.db,schema:e.schema})}}else return this.handleSet({req:n,db:e.db,schema:e.schema});throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((n,a)=>o=>a({req:o,next:n}),async n=>t(n))(e.req)}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new r(this.resourceName,e({mutation:_e}))}},k=class r{middlewares;constructor(e=[]){this.middlewares=e;}createBasicRoute(e){return new z(e.name).use(...this.middlewares)}use(...e){return new r([...this.middlewares,...e])}static create(){return new r}},vt=k.create;var A=class{},re=class extends A{storage={};async updateSchema(e){this.storage=Object.entries(e).reduce((t,[n,a])=>(t[a.name]={},t),{});}async findById(e,t){var n;return (n=this.storage[e])==null?void 0:n[t]}async find(e,t){return this.storage[e]??{}}async upsert(e,t,n){return this.storage[e]??={},this.storage[e][t]=n,n}},ne=class extends A{db;schema;constructor(e){super(),this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})});}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,a]of Object.entries(e)){let o=t.find(s=>s.name===n);o||await this.db.schema.createTable(n).ifNotExists().execute();let i=`${n}_meta`,u=t.find(s=>s.name===i);u||await this.db.schema.createTable(i).ifNotExists().execute();for(let[s,h]of Object.entries(a.fields)){let m=o==null?void 0:o.columns.find(d=>d.name===s),l=h.getStorageFieldType();m?m.dataType!==l.type&&console.error("Column type mismatch:",s,"expected to have type:",l.type,"but has type:",m.dataType):(await this.db.schema.alterTable(n).addColumn(s,l.type,d=>{let c=d;return l.unique&&(c=c.unique()),l.nullable||(c=c.notNull()),l.references&&(c=c.references(l.references)),l.primary&&(c=c.primaryKey()),l.default!==void 0&&(c=c.defaultTo(l.default)),c}).execute().catch(d=>{throw console.error("Error adding column",s,d),d}),l.index&&await this.db.schema.createIndex(`${n}_${s}_index`).on(n).column(s).execute().catch(d=>{})),(u==null?void 0:u.columns.find(d=>d.name===s))||await this.db.schema.alterTable(i).addColumn(s,"varchar",d=>{let c=d;return l.primary&&(c=c.primaryKey().references(`${n}.${s}`)),c}).execute();}}}async findById(e,t){let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).executeTakeFirst(),a=await this.db.selectFrom(`${e}_meta`).where("id","=",t).selectAll(`${e}_meta`).executeTakeFirst();if(!(!n||!a))return this.convertToMaterializedLiveType(n,a)}async find(e,t){let a=await this.applyWhere(e,this.db.selectFrom(e).selectAll(e),t).execute(),o=Object.fromEntries(a.map(s=>{let{id:h,...m}=s;return [h,m]}));if(Object.keys(o).length===0)return {};let i=Object.fromEntries((await this.db.selectFrom(`${e}_meta`).selectAll().where("id","in",Object.keys(o)).execute()).map(s=>{let{id:h,...m}=s;return [h,m]}));return Object.entries(o).reduce((s,[h,m])=>(i[h]&&(s[h]=this.convertToMaterializedLiveType(m,i[h])),s),{})}async upsert(e,t,n){return await this.db.transaction().execute(async a=>{let o=!!await a.selectFrom(e).select("id").where("id","=",t).executeTakeFirst(),i={},u={};for(let[s,h]of Object.entries(n.value))i[s]=h.value,u[s]=h._meta.timestamp;o?await Promise.all([a.updateTable(e).set(i).where("id","=",t).execute(),a.updateTable(`${e}_meta`).set(u).where("id","=",t).execute()]):await Promise.all([a.insertInto(e).values({...i,id:t}).execute(),a.insertInto(`${e}_meta`).values({...u,id:t}).execute()]);}),n}convertToMaterializedLiveType(e,t){return {value:Object.fromEntries(Object.entries(e).flatMap(([n,a])=>t?[[n,{value:a,_meta:{timestamp:t==null?void 0:t[n]}}]]:[]))}}applyWhere(e,t,n){if(!n)return t;if(!this.schema)throw new Error("Schema not initialized");let a=this.schema[e];if(!a)throw new Error("Resource not found");for(let[o,i]of Object.entries(n))if(a.fields[o])t=t.where(`${e}.${o}`,"=",i);else if(a.relations[o]){let u=a.relations[o],s=u.entity.name,h=u.type==="one"?"id":u.foreignColumn,m=u.type==="one"?u.relationalColumn:"id";t=t.leftJoin(s,`${s}.${h}`,`${e}.${m}`),t=this.applyWhere(s,t,i);}return t}};var D=class r{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,(t=e.middlewares)==null||t.forEach(n=>this.middlewares.add(n)),this.storage.updateSchema(this.schema),this.contextProvider=e.contextProvider;}static create(e){return new r(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((n,a)=>o=>a({req:o,next:n}),async n=>this.router.routes[e.req.resourceName].handleRequest({req:n,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&this.mutationSubscriptions.forEach(n=>{n({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},Nt=D.create;
2
+ exports.InMemoryStorage=re;exports.Route=z;exports.RouteFactory=k;exports.Router=C;exports.SQLStorage=ne;exports.Server=D;exports.Storage=A;exports.expressAdapter=xt;exports.routeFactory=vt;exports.router=Mt;exports.server=Nt;