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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Pedro Costa
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ var g=Object.create;var f=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var m=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b,a,c,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of i(a))!k.call(b,d)&&d!==c&&f(b,d,{get:()=>a[d],enumerable:!(e=h(a,d))||e.enumerable});return b};var n=(b,a,c)=>(c=b!=null?g(j(b)):{},l(a||!b||!b.__esModule?f(c,"default",{value:b,enumerable:true}):c,b));export{m as a,n as b};
package/dist/client.d.ts CHANGED
@@ -1,7 +1,19 @@
1
+ import { ZodTypeAny, z } from 'zod';
1
2
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
3
 
4
+ type Promisify<T> = T extends Promise<any> ? T : Promise<T>;
5
+
3
6
  type LiveTypeMeta = {};
4
7
  type MutationType = "set";
8
+ type StorageFieldType = {
9
+ type: string;
10
+ nullable: boolean;
11
+ default?: any;
12
+ unique?: boolean;
13
+ index?: boolean;
14
+ primary?: boolean;
15
+ references?: string;
16
+ };
5
17
  declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
6
18
  value: Value;
7
19
  _meta: keyof Meta extends never ? never : Meta;
@@ -19,6 +31,7 @@ declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTyp
19
31
  * @returns A tuple of the new materialized shape and the accepted diff
20
32
  */
21
33
  abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
34
+ abstract getStorageFieldType(): StorageFieldType;
22
35
  }
23
36
  type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
24
37
  type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
@@ -27,41 +40,62 @@ type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, L
27
40
  type InferIndex<T extends LiveTypeAny> = string;
28
41
 
29
42
  declare class OptionalLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | undefined, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
30
- encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): string;
43
+ readonly inner: T;
44
+ constructor(inner: T);
45
+ encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): T["_decodeInput"];
31
46
  mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>> | undefined): [
32
47
  MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>>,
33
48
  T["_decodeInput"] | null
34
49
  ];
50
+ getStorageFieldType(): StorageFieldType;
35
51
  }
36
52
  type LiveAtomicTypeMeta = {
37
53
  timestamp: string;
38
54
  } & LiveTypeMeta;
39
- declare abstract class LiveAtomicType<Value = any, Meta extends LiveAtomicTypeMeta = LiveAtomicTypeMeta, EncodeInput = Partial<Value> | Value> extends LiveType<Value, Meta, EncodeInput> {
40
- constructor();
41
- optional(): OptionalLiveType<this>;
42
- }
43
- declare class LiveString extends LiveAtomicType<string> {
44
- encodeMutation(mutationType: MutationType, input: Partial<string>, timestamp: string): {
45
- value: string;
46
- _meta: {
47
- timestamp: string;
48
- };
55
+ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
56
+ value: Value;
57
+ _meta: LiveAtomicTypeMeta;
58
+ }> {
59
+ readonly storageType: string;
60
+ readonly convertFunc?: (value: any) => Value;
61
+ readonly isIndex: boolean;
62
+ readonly isUnique: boolean;
63
+ readonly defaultValue?: Value;
64
+ readonly foreignReference?: string;
65
+ readonly isPrimary: boolean;
66
+ constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: Value, references?: string, primary?: boolean);
67
+ encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
68
+ value: Value;
69
+ _meta: LiveAtomicTypeMeta;
49
70
  };
50
71
  mergeMutation(mutationType: MutationType, encodedMutation: {
51
- value: string;
52
- _meta: {
53
- timestamp: string;
54
- };
55
- }, materializedShape?: MaterializedLiveType<LiveString>): [
56
- MaterializedLiveType<LiveString>,
72
+ value: Value;
73
+ _meta: LiveAtomicTypeMeta;
74
+ }, materializedShape?: MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
75
+ value: Value;
76
+ _meta: LiveAtomicTypeMeta;
77
+ }>>): [
78
+ MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
79
+ value: Value;
80
+ _meta: LiveAtomicTypeMeta;
81
+ }>>,
57
82
  {
58
- value: string;
59
- _meta: {
60
- timestamp: string;
61
- };
83
+ value: Value;
84
+ _meta: LiveAtomicTypeMeta;
62
85
  } | null
63
86
  ];
87
+ getStorageFieldType(): StorageFieldType;
88
+ unique(): LiveAtomicType<Value>;
89
+ index(): LiveAtomicType<Value>;
90
+ default(value: Value): LiveAtomicType<Value>;
91
+ primary(): LiveAtomicType<Value>;
92
+ optional(): OptionalLiveType<this>;
93
+ }
94
+ declare class LiveString extends LiveAtomicType<string> {
95
+ private constructor();
64
96
  static create(): LiveString;
97
+ static createId(): LiveAtomicType<string>;
98
+ static createReference(foreignField: `${string}.${string}`): LiveString;
65
99
  }
66
100
 
67
101
  type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
@@ -74,7 +108,7 @@ type InferRelationalColumns<T extends Record<string, RelationAny>> = {
74
108
  [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;
75
109
  };
76
110
  type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
77
- type LiveObjectMutationInput<TSchema extends LiveObjectAny> = InferLiveObjectWithRelationalIds<TSchema>;
111
+ type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
78
112
  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>>> {
79
113
  readonly name: TName;
80
114
  readonly fields: TSchema;
@@ -83,6 +117,7 @@ declare class LiveObject<TName extends string, TSchema extends Record<string, Li
83
117
  encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
84
118
  mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
85
119
  setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
120
+ getStorageFieldType(): StorageFieldType;
86
121
  static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
87
122
  }
88
123
  type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
@@ -116,23 +151,17 @@ declare class Relation<TEntity extends LiveObjectAny, TSourceEntity extends Live
116
151
  };
117
152
  } | null
118
153
  ];
154
+ getStorageFieldType(): StorageFieldType;
119
155
  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>;
120
156
  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>;
121
157
  }
122
158
  type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
123
- type MaterializedLiveType<T extends LiveTypeAny> = keyof T["_meta"] extends never ? {
124
- value: T["_value"] extends Record<string, LiveTypeAny> ? {
125
- [K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
126
- } : T["_value"];
127
- } : {
159
+ type MaterializedLiveType<T extends LiveTypeAny> = {
128
160
  value: T["_value"] extends Record<string, LiveTypeAny> ? {
129
161
  [K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
130
162
  } : T["_value"];
131
163
  _meta: T["_meta"];
132
164
  };
133
- type MaterializedLiveObject<T extends LiveObjectAny> = MaterializedLiveType<T> & {
134
- [K in keyof T["relations"]]: InferIndex<T["relations"][K]["entity"]>;
135
- };
136
165
  type ExtractObjectValues<T> = T[keyof T];
137
166
  type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
138
167
  $type: "relations";
@@ -152,50 +181,71 @@ type Schema<TRawSchema extends RawSchema> = {
152
181
  [K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
153
182
  };
154
183
 
155
- declare abstract class Storage {
156
- abstract updateSchema(opts: Schema<any>): Promise<void>;
157
- abstract findById<T extends LiveObjectAny>(resourceName: string, id: string): Promise<MaterializedLiveType<T> | undefined>;
158
- abstract find<T extends LiveObjectAny>(resourceName: string, where?: Record<string, any>): Promise<Record<string, MaterializedLiveType<T>>>;
159
- abstract upsert<T extends LiveObjectAny>(resourceName: string, resourceId: string, value: MaterializedLiveType<T>): Promise<MaterializedLiveType<T>>;
160
- }
161
-
162
- type RequestBase = {
163
- resourceName: string;
164
- context: Record<string, any>;
165
- where?: Record<string, any>;
166
- };
167
- type FindRequest = RequestBase & {
168
- type: "FIND";
169
- };
170
- type SetRequest = RequestBase & {
171
- type: "SET";
172
- resourceId: string;
173
- payload: Record<string, any>;
174
- };
175
- type Request = FindRequest | SetRequest;
176
- type RouteRecord = Record<string, Route<LiveObjectAny>>;
177
- declare class Router<TSchema extends Schema<any>, TRoutes extends RouteRecord> {
184
+ type RouteRecord = Record<string, AnyRoute>;
185
+ declare class Router<TRoutes extends RouteRecord> {
178
186
  readonly routes: TRoutes;
179
187
  private constructor();
180
- static create<TSchema extends Schema<any>, TRoutes extends RouteRecord>(opts: {
188
+ static create<TRoutes extends RouteRecord>(opts: {
181
189
  routes: TRoutes;
182
- }): Router<TSchema, TRoutes>;
190
+ }): Router<TRoutes>;
183
191
  }
184
- type AnyRouter = Router<Schema<any>, RouteRecord>;
185
- type RouteResult<TShape extends LiveObjectAny> = {
186
- data: MaterializedLiveType<TShape> | Record<string, MaterializedLiveType<TShape>>;
187
- acceptedValues: Record<string, any> | null;
192
+ type AnyRouter = Router<RouteRecord>;
193
+ type RequestHandler<TInput, TResult, TSchema extends Schema<any> = Schema<any>> = (opts: {
194
+ req: Request<TInput>;
195
+ db: Storage;
196
+ schema: TSchema;
197
+ }) => Promise<TResult>;
198
+ type Mutation<TInputValidator extends ZodTypeAny, // TODO use StandardSchema instead
199
+ THandler extends RequestHandler<z.infer<TInputValidator>, any, any>> = {
200
+ inputValidator: TInputValidator;
201
+ handler: THandler;
188
202
  };
189
- declare class Route<TShape extends LiveObjectAny> {
190
- readonly shape: TShape;
191
- constructor(shape: TShape);
203
+ declare const mutationCreator: <TInputValidator extends ZodTypeAny>(validator?: TInputValidator) => {
204
+ handler: <THandler extends RequestHandler<z.infer<TInputValidator>, any, any>>(handler: THandler) => Mutation<TInputValidator, THandler>;
205
+ };
206
+ declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends Middleware<any>, TCustomMutations extends Record<string, Mutation<any, RequestHandler<any, any>>>> {
207
+ readonly _resourceSchema: TResourceSchema;
208
+ readonly resourceName: TResourceSchema["name"];
209
+ readonly middlewares: Set<TMiddleware>;
210
+ readonly customMutations: TCustomMutations;
211
+ constructor(resourceName: TResourceSchema["name"], customMutations?: TCustomMutations);
192
212
  private handleFind;
193
213
  private handleSet;
194
214
  handleRequest(opts: {
195
215
  req: Request;
196
216
  db: Storage;
197
- }): Promise<RouteResult<TShape>>;
217
+ schema: Schema<any>;
218
+ }): Promise<any>;
219
+ use(middleware: TMiddleware): this;
220
+ withMutations<T extends Record<string, Mutation<any, RequestHandler<any, any>>>>(mutationFactory: (opts: {
221
+ mutation: typeof mutationCreator;
222
+ }) => T): Route<TResourceSchema, TMiddleware, T>;
198
223
  }
224
+ type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
225
+
226
+ declare abstract class Storage {
227
+ abstract updateSchema(opts: Schema<any>): Promise<void>;
228
+ abstract findById<T extends LiveObjectAny>(resourceName: string, id: string): Promise<MaterializedLiveType<T> | undefined>;
229
+ abstract find<T extends LiveObjectAny>(resourceName: string, where?: Record<string, any>): Promise<Record<string, MaterializedLiveType<T>>>;
230
+ abstract upsert<T extends LiveObjectAny>(resourceName: string, resourceId: string, value: MaterializedLiveType<T>): Promise<MaterializedLiveType<T>>;
231
+ }
232
+
233
+ type Request<TInput = any> = {
234
+ headers: Record<string, string>;
235
+ cookies: Record<string, string>;
236
+ resourceName: string;
237
+ procedure?: string;
238
+ context: Record<string, any>;
239
+ where?: Record<string, any>;
240
+ type: "QUERY" | "MUTATE";
241
+ resourceId?: string;
242
+ input?: TInput;
243
+ };
244
+ type NextFunction<T> = (req: Request) => Promise<T> | T;
245
+ type Middleware<T> = (opts: {
246
+ req: Request;
247
+ next: NextFunction<T>;
248
+ }) => ReturnType<NextFunction<T>>;
199
249
 
200
250
  type Simplify<T> = T extends Record<string, any> ? {
201
251
  [K in keyof T]: Simplify<T[K]>;
@@ -248,29 +298,29 @@ declare class WebSocketClient {
248
298
 
249
299
  declare const useLiveQuery: <T extends Observable<U>, U>(observable: T, opts?: {
250
300
  subscribeToRemote?: boolean;
251
- }) => ReturnType<T["get"]>;
301
+ }) => Simplify<ReturnType<T["get"]>>;
252
302
  declare const SubscriptionProvider: ({ children, client, }: {
253
303
  children: React.ReactNode;
254
304
  client: Client<AnyRouter>["client"];
255
305
  }) => react_jsx_runtime.JSX.Element;
256
306
 
257
- type RawObjPool<TRouter extends AnyRouter> = Record<keyof TRouter["routes"], Record<string, MaterializedLiveObject<TRouter["routes"][keyof TRouter["routes"]]["shape"]>> | undefined>;
307
+ type RawObjPool = Record<string, Record<string, MaterializedLiveType<LiveObjectAny> | undefined> | undefined>;
258
308
  type ClientState<TRouter extends AnyRouter> = {
259
- [K in keyof TRouter["routes"]]: Record<InferIndex<TRouter["routes"][K]["shape"]>, InferLiveObject<TRouter["routes"][K]["shape"]>> | undefined;
309
+ [K in keyof TRouter["routes"]]: Record<InferIndex<TRouter["routes"][K]["_resourceSchema"]>, InferLiveObject<TRouter["routes"][K]["_resourceSchema"]>> | undefined;
260
310
  };
261
311
  type Client<TRouter extends AnyRouter> = {
262
- /**
263
- * @internal
264
- */
265
- _router: TRouter;
266
312
  client: {
267
313
  ws: WebSocketClient;
268
314
  subscribeToRemote: (resourceType?: string[]) => () => void;
269
315
  };
270
316
  store: Observable<ClientState<TRouter>> & {
271
317
  [K in keyof TRouter["routes"]]: {
272
- insert: (input: Simplify<LiveObjectMutationInput<TRouter["routes"][K]["shape"]>>["value"]) => void;
273
- update: (id: string, value: Omit<Simplify<LiveObjectMutationInput<TRouter["routes"][K]["shape"]>>["value"], "id">) => void;
318
+ insert: (input: Simplify<LiveObjectMutationInput<TRouter["routes"][K]["_resourceSchema"]>>) => void;
319
+ update: (id: string, value: Omit<Simplify<LiveObjectMutationInput<TRouter["routes"][K]["_resourceSchema"]>>, "id">) => void;
320
+ };
321
+ } & {
322
+ [K in keyof TRouter["routes"]]: {
323
+ [K2 in keyof TRouter["routes"][K]["customMutations"]]: (input: z.infer<TRouter["routes"][K]["customMutations"][K2]["inputValidator"]>) => Promisify<ReturnType<TRouter["routes"][K]["customMutations"][K2]["handler"]>>;
274
324
  };
275
325
  };
276
326
  };
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import {nanoid}from'nanoid';import {z}from'zod';import {useState,useEffect}from'react';import {jsx,Fragment}from'react/jsx-runtime';var v=z.string().nanoid(),K=z.object({_id:v,type:z.literal("SUBSCRIBE"),resource:z.string()}),k=z.object({_id:v,type:z.literal("SYNC"),lastSyncedAt:z.string().optional(),resources:z.string().array().optional()}),I=z.record(z.object({value:z.string().or(z.number()).or(z.boolean()).or(z.date()),_meta:z.object({timestamp:z.string().optional()}).optional()})).superRefine((o,e)=>{o.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),A=z.object({_id:v,type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string(),payload:I});z.union([K,A,k]);var P=z.object({_id:v,type:z.literal("SYNC"),resource:z.string(),data:z.record(I)}),N=z.object({_id:v,type:z.literal("REJECT"),resource:z.string()}),C=z.union([A,P,N]);var b=o=>Array.isArray(o.value)?o.value.map(e=>b(e)):typeof o.value!="object"?o.value:Object.fromEntries(Object.entries(o.value).map(([e,t])=>[e,b(t)]));var R=class{nodes;constructor(){this.nodes=new Map;}createNode(e,t,n){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let i={id:e,type:t,referencedBy:new Map(n.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,i),i}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t,n){let i=this.nodes.get(e),r=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!r)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n,t);let s=r.referencedBy.get(n);s&&s instanceof Set?s.add(e):r.referencedBy.set(n,e),this.notifySubscribers(t);}removeLink(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);let i=n.references.get(t);if(!i)return;n.references.delete(t);let r=this.nodes.get(i);if(!r)return;let s=r.referencedBy.get(t);s&&(s instanceof Set?s.delete(e):r.referencedBy.delete(t),this.notifySubscribers(i)),this.notifySubscribers(e);}subscribe(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);return n.subscriptions.add(t),()=>{n.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([n,i])=>{(i instanceof Set?Array.from(i.values()):[i]).forEach(s=>{let c=this.nodes.get(s);!c||!c.references.get(n)||(c.references.delete(n),this.notifySubscribers(s));});}),this.nodes.delete(e));}updateNode(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);t(n),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(n=>{try{n(e);}catch(i){console.error(`Error in node subscription for node ${e}:`,i);}});}getAllNodes(){return Array.from(this.nodes.values())}};var x=(o,e,t=[])=>new Proxy(o,{get:(n,i)=>{var l,p;if(i==="__isProxy__")return true;let r=(l=e.get)==null?void 0:l.call(e,n,[...t,i]);if(r!==void 0)return r;let s=n,c=i;return (p=s[c])!=null&&p.__isProxy__||(s[c]=x(typeof s[c]=="object"?s[c]:Object.create(null),e,[...t,i])),s[c]}});var M=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}connect(){this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||(this.intentionallyDisconnected=false,this.ws=new WebSocket(this.url),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this)));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t);}removeEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).delete(t);}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){this.dispatchEvent("error",e);}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).forEach(n=>{n(t);});}};var pe=(o,e)=>{let[t,n]=useState(()=>o.get());return useEffect(()=>{if(e!=null&&e.subscribeToRemote)return o.subscribeToRemote()},[e==null?void 0:e.subscribeToRemote]),useEffect(()=>o.subscribe(()=>{let i=o.get();n(i);}),[]),t},ye=({children:o,client:e})=>(useEffect(()=>{e.subscribeToRemote();},[]),jsx(Fragment,{children:o}));var _=class{_router;url;ws;schema;rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new R;optimisticRawObjPool={};resourceTypeSubscriptions={};routeSubscriptions={};constructor(e){this.url=e.url,this.schema=e.schema,this.ws=new M({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{t.open&&(this.sendWsMessage({_id:nanoid(),type:"SYNC"}),Object.entries(this.routeSubscriptions).forEach(([n,i])=>{i>0&&this.sendWsMessage({_id:nanoid(),type:"SUBSCRIBE",resource:n});}),Object.values(this.optimisticMutationStack).forEach(n=>{n.forEach(i=>this.sendWsMessage(i));}));});}get(e){if(e.length===0)throw new Error("Path must not be empty");if(e.length===1)return Object.fromEntries(Object.entries(this.optimisticRawObjPool[e[0]]??{}).map(([n,i])=>[n,b(i)]));let t=this.getFullObject(e[0],e[1]);if(!t)throw new Error("Object of type "+e[0]+" not found with id "+e[1]);return b(t)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=C.parse(JSON.parse(e));if(console.log("Parsed message:",t),t.type==="MUTATE"){let{resource:n}=t;try{this.addMutation(n,t);}catch(i){console.error("Error parsing mutation from the server:",i);}}else if(t.type==="SYNC"){let{resource:n,data:i}=t;console.log("Syncing resource:",i,t),Object.entries(i).forEach(([r,s])=>{this.addMutation(n,{_id:r,type:"MUTATE",resource:n,resourceId:r,payload:s});});}else t.type;}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.routeSubscriptions[e]=(this.routeSubscriptions[e]??0)+1,this.sendWsMessage({_id:nanoid(),type:"SUBSCRIBE",resource:e}),()=>{this.routeSubscriptions[e]-=1,this.routeSubscriptions[e];}}subscribeToSlice(e,t){if(e.length===1)return this.resourceTypeSubscriptions[e[0]]||(this.resourceTypeSubscriptions[e[0]]=new Set),this.resourceTypeSubscriptions[e[0]].add(t),()=>{this.resourceTypeSubscriptions[e[0]].delete(t);};if(e.length===2){if(!this.optimisticObjGraph.getNode(e[1]))throw new Error("Node not found");return this.optimisticObjGraph.subscribe(e[1],t)}throw new Error("Not implemented")}mutate(e,t,n){let i={_id:nanoid(),type:"MUTATE",resource:e,payload:this.schema[e].encodeMutation("set",n,new Date().toISOString()),resourceId:t};this.addMutation(e,i,true),this.sendWsMessage(i);}sendWsMessage(e){this.ws&&this.ws.connected()&&this.ws.send(JSON.stringify(e));}addMutation(e,t,n=false){var c,l,p,f;let i=this.schema[e];if(console.log("Adding mutation",t),!i)throw new Error("Schema not found");n?(this.optimisticMutationStack[e]||(this.optimisticMutationStack[e]=[]),this.optimisticMutationStack[e].push(t)):this.optimisticMutationStack[e]&&(this.optimisticMutationStack[e]=this.optimisticMutationStack[e].filter(u=>u._id!==t._id)),this.optimisticObjGraph.getNode(t.resourceId)||this.optimisticObjGraph.createNode(t.resourceId,e,Object.values(i.relations).flatMap(u=>u.type==="many"?[u.foreignColumn]:[]));let r=((c=this.optimisticRawObjPool[e])==null?void 0:c[t.resourceId])??((l=this.rawObjPool[e])==null?void 0:l[t.resourceId]);n||(this.rawObjPool[e]??={},this.rawObjPool[e][t.resourceId]={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}}),this.optimisticRawObjPool[e]??={};let s=(this.optimisticMutationStack[e]??[]).reduce((u,d)=>d.resourceId!==d.resourceId?u:this.schema[e].mergeMutation("set",d.payload,u)[0],(p=this.rawObjPool[e])==null?void 0:p[t.resourceId]);if(s&&(this.optimisticRawObjPool[e][t.resourceId]={value:{...s.value,id:{value:t.resourceId}}}),Object.keys(i.relations).length>0){let u=Object.fromEntries(Object.entries(i.relations).flatMap(([d,T])=>T.type==="one"?[[T.relationalColumn,d]]:[]));Object.entries(t.payload).forEach(([d,T])=>{if(!u[d])return;let[,y]=i.relations[u[d]].mergeMutation("set",T,r==null?void 0:r.value[d]);y&&this.optimisticObjGraph.createLink(t.resourceId,y.value,d);});}(f=this.resourceTypeSubscriptions[e])==null||f.forEach(u=>u()),this.optimisticObjGraph.notifySubscribers(t.resourceId);}getFullObject(e,t){var r;let n=this.optimisticObjGraph.getNode(t);if(!n)return;let i=(r=this.optimisticRawObjPool[e])==null?void 0:r[t];if(i)return {value:{...i.value,...Object.fromEntries(Array.from(n.referencedBy.entries()).map(([s,c])=>{var T;let l=c instanceof Set,p=l?Array.from(c.values()).flatMap(y=>{let h=this.optimisticObjGraph.getNode(y);return h?[h]:[]}):this.optimisticObjGraph.getNode(c);if(!p)return [s,void 0];let[f,u]=Object.entries(this.schema[e].relations).find(y=>y[1].relationalColumn===s||y[1].foreignColumn===s)??[],d=u==null?void 0:u.entity.name;return !d||!u?[s,l?[]:void 0]:[f,{value:l?p.map(y=>{var h;return (h=this.optimisticRawObjPool[d])==null?void 0:h[y.id]}):(T=this.optimisticRawObjPool[d])==null?void 0:T[p.id]}]}))}}}},Ke=o=>{let e=new _(o);return {_router:e._router,client:{ws:e.ws,subscribeToRemote:t=>{let n=[];for(let i of t??Object.keys(e.schema))n.push(e.subscribeToRemote(i));return ()=>{n.forEach(i=>i());}}},store:x({},{get:(t,n)=>{let i=n.slice(0,-1),r=n[n.length-1];if(r==="get")return ()=>e.get(i);if(r==="subscribe")return s=>e.subscribeToSlice(i,s);if(r==="subscribeToRemote")return e.subscribeToRemote.bind(e,i[0]);if(i.length===1){if(r==="insert")return s=>{let{id:c,...l}=s;e.mutate(i[0],c,l);};if(r==="update")return (s,c)=>{e.mutate(i[0],s,c);}}}})}};export{ye as SubscriptionProvider,Ke as createClient,pe as useLiveQuery};
1
+ import {z as z$1}from'zod';import {useState,useEffect}from'react';import {jsx,Fragment}from'react/jsx-runtime';z$1.object({type:z$1.literal("QUERY"),resource:z$1.string(),where:z$1.record(z$1.any()).optional(),include:z$1.record(z$1.any()).optional()});var O=z$1.record(z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()),_meta:z$1.object({timestamp:z$1.string().optional()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),D=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string()}),I=D.extend({procedure:z$1.string(),payload:z$1.any()}),j=D.extend({resourceId:z$1.string(),payload:O});z$1.union([I,j]);var T=z$1.string(),G=z$1.object({id:T,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),W=z$1.object({id:T,type:z$1.literal("SYNC"),lastSyncedAt:z$1.string().optional(),resources:z$1.string().array().optional(),where:z$1.record(z$1.any()).optional()}),P=j.extend({id:T}),z=I.extend({id:T}),q=z$1.union([z,P]);z$1.union([G,W,q]);var Z=z$1.object({id:T,type:z$1.literal("SYNC"),resource:z$1.string(),data:z$1.record(O)}),$=z$1.object({id:T,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),B=z$1.object({id:T,type:z$1.literal("REPLY"),data:z$1.any()}),F=z$1.union([Z,$,B,P]);var k="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var h;(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";})(h||(h={}));var v=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function H(r){let e=Math.floor(r()*32);return e===32&&(e=31),k.charAt(e)}function X(r){let e=J(),t=e&&(e.crypto||e.msCrypto)||null;if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;throw new v(h.PRNGDetectFailure,"Failed to find a reliable PRNG")}function J(){return ee()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Y(r,e){let t="";for(;r>0;r--)t=H(e)+t;return t}function Q(r,e=10){if(isNaN(r))throw new v(h.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>0xffffffffffff)throw new v(h.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${r}`);if(r<0)throw new v(h.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new v(h.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%32,n=k.charAt(t)+n,r=(r-t)/32;return n}function ee(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function U(r,e){let t=X(),n=Date.now();return Q(n,10)+Y(16,t)}var g=()=>U().toLowerCase();var S=r=>{if(r)return Array.isArray(r.value)?r.value.map(e=>S(e)):typeof r.value!="object"?r.value:Object.fromEntries(Object.entries(r.value).map(([e,t])=>[e,S(t)]))};var x=class{nodes;constructor(){this.nodes=new Map;}createNode(e,t,n){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let i={id:e,type:t,referencedBy:new Map(n.map(o=>[o,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,i),i}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t,n){let i=this.nodes.get(e),o=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!o)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n,t);let s=o.referencedBy.get(n);s&&s instanceof Set?s.add(e):o.referencedBy.set(n,e),this.notifySubscribers(t);}removeLink(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);let i=n.references.get(t);if(!i)return;n.references.delete(t);let o=this.nodes.get(i);if(!o)return;let s=o.referencedBy.get(t);s&&(s instanceof Set?s.delete(e):o.referencedBy.delete(t),this.notifySubscribers(i)),this.notifySubscribers(e);}subscribe(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);return n.subscriptions.add(t),()=>{n.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([n,i])=>{(i instanceof Set?Array.from(i.values()):[i]).forEach(s=>{let a=this.nodes.get(s);!a||!a.references.get(n)||(a.references.delete(n),this.notifySubscribers(s));});}),this.nodes.delete(e));}updateNode(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);t(n),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(n=>{try{n(e);}catch(i){console.error(`Error in node subscription for node ${e}:`,i);}});}getAllNodes(){return Array.from(this.nodes.values())}};var C=(r,e,t=[])=>new Proxy(r,{get:(n,i)=>{var l,y;if(i==="__isProxy__")return true;let o=(l=e.get)==null?void 0:l.call(e,n,[...t,i]);if(o!==void 0)return o;let s=n,a=i;return (y=s[a])!=null&&y.__isProxy__||(s[a]=C(typeof s[a]=="object"?s[a]:function(){},e,[...t,i])),s[a]},apply:(n,i,o)=>{var s;return (s=e.apply)==null?void 0:s.call(e,n,t,o)}});var w=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}connect(){this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||(this.intentionallyDisconnected=false,this.ws=new WebSocket(this.url),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this)));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t);}removeEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).delete(t);}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){this.dispatchEvent("error",e);}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).forEach(n=>{n(t);});}};var Ue=(r,e)=>{let[t,n]=useState(()=>r.get());return useEffect(()=>{if(e!=null&&e.subscribeToRemote)return r.subscribeToRemote()},[e==null?void 0:e.subscribeToRemote]),useEffect(()=>r.subscribe(()=>{let i=r.get();n(i);}),[]),t},Ge=({children:r,client:e})=>(useEffect(()=>{e.subscribeToRemote();},[]),jsx(Fragment,{children:r}));var V=class{url;ws;schema;rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new x;optimisticRawObjPool={};resourceTypeSubscriptions={};routeSubscriptions={};replyHandlers={};constructor(e){this.url=e.url,this.schema=e.schema,this.ws=new w({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{t.open&&(this.sendWsMessage({id:g(),type:"SYNC"}),Object.entries(this.routeSubscriptions).forEach(([n,i])=>{i>0&&this.sendWsMessage({id:g(),type:"SUBSCRIBE",resource:n});}),Object.values(this.optimisticMutationStack).forEach(n=>{n.forEach(i=>this.sendWsMessage(i));}));});}get(e){if(e.length===0)throw new Error("Path must not be empty");if(e.length===1)return Object.fromEntries(Object.entries(this.optimisticRawObjPool[e[0]]??{}).map(([n,i])=>[n,S(i)]));let t=this.getFullObject(e[0],e[1]);if(!t)throw new Error("Object of type "+e[0]+" not found with id "+e[1]);return S(t)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=F.parse(JSON.parse(e));if(console.log("Parsed message:",t),t.type==="MUTATE"){let{resource:n}=t;try{this.addMutation(n,t);}catch(i){console.error("Error parsing mutation from the server:",i);}}else if(t.type==="SYNC"){let{resource:n,data:i}=t;console.log("Syncing resource:",i,t),Object.entries(i).forEach(([o,s])=>{this.addMutation(n,{id:o,type:"MUTATE",resource:n,resourceId:o,payload:s});});}else if(t.type!=="REJECT"){if(t.type==="REPLY"){let{id:n,data:i}=t;if(!this.replyHandlers[n])return;clearTimeout(this.replyHandlers[n].timeoutHandle),this.replyHandlers[n].handler(i);}}}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.routeSubscriptions[e]=(this.routeSubscriptions[e]??0)+1,this.sendWsMessage({id:g(),type:"SUBSCRIBE",resource:e}),()=>{this.routeSubscriptions[e]-=1,this.routeSubscriptions[e];}}subscribeToSlice(e,t){if(e.length===1)return this.resourceTypeSubscriptions[e[0]]||(this.resourceTypeSubscriptions[e[0]]=new Set),this.resourceTypeSubscriptions[e[0]].add(t),()=>{this.resourceTypeSubscriptions[e[0]].delete(t);};if(e.length===2){if(!this.optimisticObjGraph.getNode(e[1]))throw new Error("Node not found");return this.optimisticObjGraph.subscribe(e[1],t)}throw new Error("Not implemented")}mutate(e,t,n){let i={id:g(),type:"MUTATE",resource:e,payload:this.schema[e].encodeMutation("set",n,new Date().toISOString()),resourceId:t};this.addMutation(e,i,true),this.sendWsMessage(i);}genericMutate(e,t,n){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let i={id:g(),type:"MUTATE",resource:e,procedure:t,payload:n};return this.sendWsMessage(i),new Promise((o,s)=>{this.replyHandlers[i.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[i.id],s(new Error("Reply timeout"));},5e3),handler:a=>{delete this.replyHandlers[i.id],o(a);}};})}sendWsMessage(e){this.ws&&this.ws.connected()&&this.ws.send(JSON.stringify(e));}addMutation(e,t,n=false){var a,l,y,E;let i=this.schema[e];if(console.log("Adding mutation",t),!i)throw new Error("Schema not found");n?(this.optimisticMutationStack[e]||(this.optimisticMutationStack[e]=[]),this.optimisticMutationStack[e].push(t)):this.optimisticMutationStack[e]&&(this.optimisticMutationStack[e]=this.optimisticMutationStack[e].filter(d=>d.id!==t.id)),this.optimisticObjGraph.getNode(t.resourceId)||this.optimisticObjGraph.createNode(t.resourceId,e,Object.values(i.relations).flatMap(d=>d.type==="many"?[d.foreignColumn]:[]));let o=((a=this.optimisticRawObjPool[e])==null?void 0:a[t.resourceId])??((l=this.rawObjPool[e])==null?void 0:l[t.resourceId]);n||(this.rawObjPool[e]??={},this.rawObjPool[e][t.resourceId]={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}}),this.optimisticRawObjPool[e]??={};let s=(this.optimisticMutationStack[e]??[]).reduce((d,p)=>p.resourceId!==p.resourceId?d:this.schema[e].mergeMutation("set",p.payload,d)[0],(y=this.rawObjPool[e])==null?void 0:y[t.resourceId]);if(s&&(this.optimisticRawObjPool[e][t.resourceId]={value:{...s.value,id:{value:t.resourceId}}}),Object.keys(i.relations).length>0){let d=Object.fromEntries(Object.entries(i.relations).flatMap(([p,m])=>m.type==="one"?[[m.relationalColumn,p]]:[]));Object.entries(t.payload).forEach(([p,m])=>{if(!d[p])return;let[,f]=i.relations[d[p]].mergeMutation("set",m,o==null?void 0:o.value[p]);f&&this.optimisticObjGraph.createLink(t.resourceId,f.value,p);});}(E=this.resourceTypeSubscriptions[e])==null||E.forEach(d=>d()),this.optimisticObjGraph.notifySubscribers(t.resourceId);}getFullObject(e,t){var o;let n=this.optimisticObjGraph.getNode(t);if(!n)return;let i=(o=this.optimisticRawObjPool[e])==null?void 0:o[t];if(i)return {value:{...i.value,...Object.fromEntries(Array.from(n.referencedBy.entries()).map(([s,a])=>{var m;let l=a instanceof Set,y=l?Array.from(a.values()).flatMap(f=>{let M=this.optimisticObjGraph.getNode(f);return M?[M]:[]}):this.optimisticObjGraph.getNode(a);if(!y)return [s,void 0];let[E,d]=Object.entries(this.schema[e].relations).find(f=>f[1].relationalColumn===s||f[1].foreignColumn===s)??[],p=d==null?void 0:d.entity.name;return !p||!d?[s,l?[]:void 0]:[E,{value:l?y.map(f=>{var M;return (M=this.optimisticRawObjPool[p])==null?void 0:M[f.id]}):(m=this.optimisticRawObjPool[p])==null?void 0:m[y.id]}]}))}}}},dt=r=>{let e=new V(r);return {client:{ws:e.ws,subscribeToRemote:t=>{let n=[];for(let i of t??Object.keys(e.schema))n.push(e.subscribeToRemote(i));return ()=>{n.forEach(i=>i());}}},store:C(()=>{},{apply:(t,n,i)=>{let o=n.slice(0,-1),s=n[n.length-1];if(s==="get")return e.get(o);if(s==="subscribe")return e.subscribeToSlice(o,i[0]);if(s==="subscribeToRemote")return e.subscribeToRemote(o[0]);if(s==="insert"){let{id:a,...l}=i[0];return e.mutate(o[0],a,l)}if(s==="update"){let[a,l]=i;return e.mutate(o[0],a,l)}return e.genericMutate(o[0],s,i[0])}})}};export{Ge as SubscriptionProvider,dt as createClient,Ue as useLiveQuery};
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 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;