@live-state/sync 0.0.1-alpha.1 → 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 T=class extends o{encodeMutation(n,t,e){throw new Error("Method not implemented.")}mergeMutation(n,t,e){throw new Error("Method not implemented.")}},s=class extends o{constructor(){super(),this.optional=this.optional.bind(this);}optional(){return new T}},y=class a extends s{encodeMutation(n,t,e){return {value:t,_meta:{timestamp:e}}}mergeMutation(n,t,e){return e&&e._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[e,null]:[{value:Number(t.value),_meta:t._meta},t]}static create(){return new a}},M=y.create,c=class a extends s{encodeMutation(n,t,e){return {value:t,_meta:{timestamp:e}}}mergeMutation(n,t,e){return e&&e._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[e,null]:[t,t]}static create(){return new a}},h=c.create;var u=class a extends o{name;fields;relations;constructor(n,t,e){super(),this.name=n,this.fields=t,this.relations=e??{};}encodeMutation(n,t,e){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,e)]))}mergeMutation(n,t,e){let r={};return [{value:{...(e==null?void 0:e.value)??{},...Object.fromEntries(Object.entries(t).map(([i,d])=>{let[v,m]=(this.fields[i]??this.relations[i]).mergeMutation(n,d,e==null?void 0:e.value[i]);return m&&(r[i]=m),[i,v]}))}},r]}setRelations(n){return new a(this.name,this.fields,n)}static create(n,t){return new a(n,t)}},A=u.create,l=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(n,t,e,r,i){super(),this.entity=n,this.type=t,this.required=i??false,this.relationalColumn=e,this.foreignColumn=r;}encodeMutation(n,t,e){if(n!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:e}}}mergeMutation(n,t,e){if(this.type==="many")throw new Error("Many not implemented.");return e&&e._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[e,null]:[t,t]}static createOneFactory(){return (n,t,e)=>new a(n,"one",t,void 0,e??false)}static createManyFactory(){return (n,t,e)=>new a(n,"many",void 0,t,e??false)}},K=(a,n)=>({$type:"relations",objectName:a.name,relations:n({one:l.createOneFactory(),many:l.createManyFactory()})}),p=a=>Array.isArray(a.value)?a.value.map(n=>p(n)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([n,t])=>[n,p(t)])),E=a=>Object.fromEntries(Object.entries(a).flatMap(([n,t])=>{if(t.$type==="relations")return [];let e=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(e=e.setRelations(r.relations)),[[e.name,e]]}));exports.LiveNumber=y;exports.LiveObject=u;exports.LiveString=c;exports.LiveType=o;exports.Relation=l;exports.createRelations=K;exports.createSchema=E;exports.inferValue=p;exports.number=M;exports.object=A;exports.string=h;
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
@@ -1,2 +1,209 @@
1
- export { C as ClientMessage, t as InferIndex, I as InferLiveObject, c as InferLiveObjectWithRelationalIds, r as InferLiveType, j as LiveNumber, e as LiveObject, L as LiveObjectAny, d as LiveObjectMutationInput, k as LiveString, p as LiveType, q as LiveTypeAny, l as LiveTypeMeta, g as MaterializedLiveObject, M as MaterializedLiveType, m as MutationType, R as Relation, S as Schema, b as ServerMessage, f as createRelations, h as createSchema, i as inferValue, n as number, o as object, s as string } from './index-sSVirsfN.cjs';
2
- import 'zod';
1
+ type LiveTypeMeta = {};
2
+ type MutationType = "set";
3
+ type StorageFieldType = {
4
+ type: string;
5
+ nullable: boolean;
6
+ default?: any;
7
+ unique?: boolean;
8
+ index?: boolean;
9
+ primary?: boolean;
10
+ references?: string;
11
+ };
12
+ declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
13
+ value: Value;
14
+ _meta: keyof Meta extends never ? never : Meta;
15
+ }> {
16
+ readonly _value: Value;
17
+ readonly _meta: Meta;
18
+ readonly _encodeInput: EncodeInput;
19
+ readonly _decodeInput: DecodeInput;
20
+ abstract encodeMutation(mutationType: MutationType, input: EncodeInput, timestamp: string): DecodeInput;
21
+ /**
22
+ * Merges the materialized shape with the encoded mutation
23
+ * @param mutationType The type of mutation
24
+ * @param encodedMutation The encoded mutation
25
+ * @param materializedShape The materialized shape
26
+ * @returns A tuple of the new materialized shape and the accepted diff
27
+ */
28
+ abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
29
+ abstract getStorageFieldType(): StorageFieldType;
30
+ }
31
+ type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
32
+ type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
33
+ [K in keyof T["_value"]]: InferLiveType<T["_value"][K]>;
34
+ } : T["_value"];
35
+ type InferIndex<T extends LiveTypeAny> = string;
36
+
37
+ declare class OptionalLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | undefined, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
38
+ readonly inner: T;
39
+ constructor(inner: T);
40
+ encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): T["_decodeInput"];
41
+ mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>> | undefined): [
42
+ MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>>,
43
+ T["_decodeInput"] | null
44
+ ];
45
+ getStorageFieldType(): StorageFieldType;
46
+ }
47
+ type LiveAtomicTypeMeta = {
48
+ timestamp: string;
49
+ } & LiveTypeMeta;
50
+ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
51
+ value: Value;
52
+ _meta: LiveAtomicTypeMeta;
53
+ }> {
54
+ readonly storageType: string;
55
+ readonly convertFunc?: (value: any) => Value;
56
+ readonly isIndex: boolean;
57
+ readonly isUnique: boolean;
58
+ readonly defaultValue?: Value;
59
+ readonly foreignReference?: string;
60
+ readonly isPrimary: boolean;
61
+ constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: Value, references?: string, primary?: boolean);
62
+ encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
63
+ value: Value;
64
+ _meta: LiveAtomicTypeMeta;
65
+ };
66
+ mergeMutation(mutationType: MutationType, encodedMutation: {
67
+ value: Value;
68
+ _meta: LiveAtomicTypeMeta;
69
+ }, materializedShape?: MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
70
+ value: Value;
71
+ _meta: LiveAtomicTypeMeta;
72
+ }>>): [
73
+ MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
74
+ value: Value;
75
+ _meta: LiveAtomicTypeMeta;
76
+ }>>,
77
+ {
78
+ value: Value;
79
+ _meta: LiveAtomicTypeMeta;
80
+ } | null
81
+ ];
82
+ getStorageFieldType(): StorageFieldType;
83
+ unique(): LiveAtomicType<Value>;
84
+ index(): LiveAtomicType<Value>;
85
+ default(value: Value): LiveAtomicType<Value>;
86
+ primary(): LiveAtomicType<Value>;
87
+ optional(): OptionalLiveType<this>;
88
+ }
89
+ declare class LiveNumber extends LiveAtomicType<number> {
90
+ private constructor();
91
+ static create(): LiveNumber;
92
+ }
93
+ declare const number: typeof LiveNumber.create;
94
+ declare class LiveString extends LiveAtomicType<string> {
95
+ private constructor();
96
+ static create(): LiveString;
97
+ static createId(): LiveAtomicType<string>;
98
+ static createReference(foreignField: `${string}.${string}`): LiveString;
99
+ }
100
+ declare const string: typeof LiveString.create;
101
+ declare const id: typeof LiveString.createId;
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;
113
+
114
+ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
115
+ [K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
116
+ };
117
+ type InferLiveObject<T extends LiveObjectAny> = InferLiveObjectWithoutRelations<T> & {
118
+ [K in keyof T["relations"]]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
119
+ };
120
+ type InferRelationalColumns<T extends Record<string, RelationAny>> = {
121
+ [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;
122
+ };
123
+ type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
124
+ type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
125
+ 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>>> {
126
+ readonly name: TName;
127
+ readonly fields: TSchema;
128
+ readonly relations: TRelations;
129
+ constructor(name: TName, fields: TSchema, relations?: TRelations);
130
+ encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
131
+ mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
132
+ setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
133
+ getStorageFieldType(): StorageFieldType;
134
+ static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
135
+ }
136
+ declare const object: typeof LiveObject.create;
137
+ type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
138
+ 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>, {
139
+ timestamp: string;
140
+ } & LiveTypeMeta> {
141
+ readonly entity: TEntity;
142
+ readonly type: TType;
143
+ readonly required: TRequired;
144
+ readonly relationalColumn?: TRelationalColumn;
145
+ readonly foreignColumn?: TForeignColumn;
146
+ readonly sourceEntity: TSourceEntity;
147
+ private constructor();
148
+ encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
149
+ value: string;
150
+ _meta: {
151
+ timestamp: string;
152
+ };
153
+ };
154
+ mergeMutation(mutationType: MutationType, encodedMutation: {
155
+ value: string;
156
+ _meta: {
157
+ timestamp: string;
158
+ };
159
+ }, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
160
+ MaterializedLiveType<LiveString>,
161
+ {
162
+ value: string;
163
+ _meta: {
164
+ timestamp: string;
165
+ };
166
+ } | null
167
+ ];
168
+ getStorageFieldType(): StorageFieldType;
169
+ 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>;
170
+ 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>;
171
+ }
172
+ type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
173
+ declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
174
+ one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
175
+ many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
176
+ }) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
177
+ type MaterializedLiveType<T extends LiveTypeAny> = {
178
+ value: T["_value"] extends Record<string, LiveTypeAny> ? {
179
+ [K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
180
+ } : T["_value"];
181
+ _meta: T["_meta"];
182
+ };
183
+ declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
184
+ type ExtractObjectValues<T> = T[keyof T];
185
+ type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
186
+ $type: "relations";
187
+ objectName: TObjectName;
188
+ relations: TRelations;
189
+ };
190
+ type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
191
+ [K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
192
+ [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"]>;
193
+ } : never : never;
194
+ }>;
195
+ type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
196
+ [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;
197
+ }>;
198
+ type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
199
+ type Schema<TRawSchema extends RawSchema> = {
200
+ [K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
201
+ };
202
+ declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
203
+ type WhereClause<T extends LiveObjectAny> = {
204
+ [K in keyof T["fields"]]?: InferLiveType<T["fields"][K]>;
205
+ } & {
206
+ [K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
207
+ };
208
+
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 };