@live-state/sync 0.0.3 → 0.0.4-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-E7NFSHVD.js +1 -0
- package/dist/chunk-GUSCESQZ.js +1 -0
- package/dist/client.d.ts +3 -1
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +4 -13
- package/dist/fetch-client.js +1 -1
- package/dist/{index-4Y_YcJTJ.d.ts → index-C5AAiO4g.d.ts} +151 -145
- package/dist/index-COp5Ib0a.d.cts +282 -0
- package/dist/index-COp5Ib0a.d.ts +282 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -236
- package/dist/index.d.ts +1 -236
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +119 -122
- package/dist/server.d.ts +119 -122
- package/dist/server.js +2 -2
- package/package.json +2 -2
- package/dist/chunk-G5SVBG4B.js +0 -1
- package/dist/chunk-LLHCJUB6.js +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,236 +1 @@
|
|
|
1
|
-
|
|
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 NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | null, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
|
|
38
|
-
readonly inner: T;
|
|
39
|
-
constructor(inner: T);
|
|
40
|
-
encodeMutation(mutationType: MutationType, input: T["_value"] | null, timestamp: string): T["_decodeInput"];
|
|
41
|
-
mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>> | undefined): [
|
|
42
|
-
MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>>,
|
|
43
|
-
T["_decodeInput"] | null
|
|
44
|
-
];
|
|
45
|
-
getStorageFieldType(): StorageFieldType;
|
|
46
|
-
}
|
|
47
|
-
type LiveAtomicTypeMeta = {
|
|
48
|
-
timestamp: string | null;
|
|
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
|
-
nullable(): NullableLiveType<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
|
-
/** biome-ignore-all lint/complexity/noBannedTypes: false positive */
|
|
115
|
-
|
|
116
|
-
type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
117
|
-
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
118
|
-
};
|
|
119
|
-
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
120
|
-
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
121
|
-
} : {});
|
|
122
|
-
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
123
|
-
[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;
|
|
124
|
-
};
|
|
125
|
-
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
126
|
-
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
127
|
-
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>>> {
|
|
128
|
-
readonly name: TName;
|
|
129
|
-
readonly fields: TSchema;
|
|
130
|
-
readonly relations: TRelations;
|
|
131
|
-
constructor(name: TName, fields: TSchema, relations?: TRelations);
|
|
132
|
-
encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
|
|
133
|
-
mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
|
|
134
|
-
setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
|
|
135
|
-
getStorageFieldType(): StorageFieldType;
|
|
136
|
-
static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
|
|
137
|
-
}
|
|
138
|
-
declare const object: typeof LiveObject.create;
|
|
139
|
-
type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
|
|
140
|
-
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>, {
|
|
141
|
-
timestamp: string | null;
|
|
142
|
-
} & LiveTypeMeta> {
|
|
143
|
-
readonly entity: TEntity;
|
|
144
|
-
readonly type: TType;
|
|
145
|
-
readonly required: TRequired;
|
|
146
|
-
readonly relationalColumn?: TRelationalColumn;
|
|
147
|
-
readonly foreignColumn?: TForeignColumn;
|
|
148
|
-
readonly sourceEntity: TSourceEntity;
|
|
149
|
-
private constructor();
|
|
150
|
-
encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
|
|
151
|
-
value: string;
|
|
152
|
-
_meta: {
|
|
153
|
-
timestamp: string;
|
|
154
|
-
};
|
|
155
|
-
};
|
|
156
|
-
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
157
|
-
value: string;
|
|
158
|
-
_meta: {
|
|
159
|
-
timestamp: string;
|
|
160
|
-
};
|
|
161
|
-
}, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
|
|
162
|
-
MaterializedLiveType<LiveString>,
|
|
163
|
-
{
|
|
164
|
-
value: string;
|
|
165
|
-
_meta: {
|
|
166
|
-
timestamp: string;
|
|
167
|
-
};
|
|
168
|
-
} | null
|
|
169
|
-
];
|
|
170
|
-
getStorageFieldType(): StorageFieldType;
|
|
171
|
-
toJSON(): {
|
|
172
|
-
entityName: string;
|
|
173
|
-
type: TType;
|
|
174
|
-
required: TRequired;
|
|
175
|
-
relationalColumn: TRelationalColumn | undefined;
|
|
176
|
-
foreignColumn: TForeignColumn | undefined;
|
|
177
|
-
};
|
|
178
|
-
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>;
|
|
179
|
-
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>;
|
|
180
|
-
}
|
|
181
|
-
type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
|
|
182
|
-
declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
|
|
183
|
-
one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
|
|
184
|
-
many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
|
|
185
|
-
}) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
|
|
186
|
-
type MaterializedLiveType<T extends LiveTypeAny> = {
|
|
187
|
-
value: T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
188
|
-
[K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
|
|
189
|
-
} : T["_value"];
|
|
190
|
-
_meta: T["_meta"];
|
|
191
|
-
};
|
|
192
|
-
declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
|
|
193
|
-
type ExtractObjectValues<T> = T[keyof T];
|
|
194
|
-
type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
|
|
195
|
-
$type: "relations";
|
|
196
|
-
objectName: TObjectName;
|
|
197
|
-
relations: TRelations;
|
|
198
|
-
};
|
|
199
|
-
type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
200
|
-
[K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
|
|
201
|
-
[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"]>;
|
|
202
|
-
} : never : never;
|
|
203
|
-
}>;
|
|
204
|
-
type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
205
|
-
[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;
|
|
206
|
-
}>;
|
|
207
|
-
type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
|
|
208
|
-
type Schema<TRawSchema extends RawSchema> = {
|
|
209
|
-
[K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
|
|
210
|
-
};
|
|
211
|
-
declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
|
|
212
|
-
type WhereClause<T extends LiveObjectAny> = ({
|
|
213
|
-
[K in keyof T["fields"]]?: InferLiveType<T["fields"][K]> | ({
|
|
214
|
-
$eq?: InferLiveType<T["fields"][K]>;
|
|
215
|
-
$in?: InferLiveType<T["fields"][K]>[];
|
|
216
|
-
$not?: InferLiveType<T["fields"][K]> | {
|
|
217
|
-
$in?: InferLiveType<T["fields"][K]>[];
|
|
218
|
-
$eq?: InferLiveType<T["fields"][K]>;
|
|
219
|
-
};
|
|
220
|
-
} & (InferLiveType<T["fields"][K]> extends number ? {
|
|
221
|
-
$gt?: InferLiveType<T["fields"][K]>;
|
|
222
|
-
$gte?: InferLiveType<T["fields"][K]>;
|
|
223
|
-
$lt?: InferLiveType<T["fields"][K]>;
|
|
224
|
-
$lte?: InferLiveType<T["fields"][K]>;
|
|
225
|
-
} : {}));
|
|
226
|
-
} & {
|
|
227
|
-
[K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
|
|
228
|
-
}) | {
|
|
229
|
-
$and?: WhereClause<T>[];
|
|
230
|
-
$or?: WhereClause<T>[];
|
|
231
|
-
};
|
|
232
|
-
type IncludeClause<T extends LiveObjectAny> = {
|
|
233
|
-
[K in keyof T["relations"]]?: boolean;
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
export { type IncludeClause, 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 };
|
|
1
|
+
export { b as IncludeClause, F as InferIndex, d as InferInsert, c as InferLiveObject, I as InferLiveObjectWithRelationalIds, h as InferLiveObjectWithoutRelations, E as InferLiveType, e as InferUpdate, n as LiveAtomicType, v as LiveBoolean, p as LiveNumber, j as LiveObject, L as LiveObjectAny, i as LiveObjectMutationInput, r as LiveString, x as LiveTimestamp, C as LiveType, D as LiveTypeAny, z as LiveTypeMeta, g as LogLevel, M as MaterializedLiveType, A as MutationType, N as NullableLiveType, R as Relation, a as Schema, B as StorageFieldType, W as WhereClause, w as boolean, k as createRelations, m as createSchema, t as id, l as inferValue, q as number, o as object, u as reference, s as string, y as timestamp } from './index-COp5Ib0a.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,236 +1 @@
|
|
|
1
|
-
|
|
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 NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | null, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
|
|
38
|
-
readonly inner: T;
|
|
39
|
-
constructor(inner: T);
|
|
40
|
-
encodeMutation(mutationType: MutationType, input: T["_value"] | null, timestamp: string): T["_decodeInput"];
|
|
41
|
-
mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>> | undefined): [
|
|
42
|
-
MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>>,
|
|
43
|
-
T["_decodeInput"] | null
|
|
44
|
-
];
|
|
45
|
-
getStorageFieldType(): StorageFieldType;
|
|
46
|
-
}
|
|
47
|
-
type LiveAtomicTypeMeta = {
|
|
48
|
-
timestamp: string | null;
|
|
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
|
-
nullable(): NullableLiveType<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
|
-
/** biome-ignore-all lint/complexity/noBannedTypes: false positive */
|
|
115
|
-
|
|
116
|
-
type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
117
|
-
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
118
|
-
};
|
|
119
|
-
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
120
|
-
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
121
|
-
} : {});
|
|
122
|
-
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
123
|
-
[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;
|
|
124
|
-
};
|
|
125
|
-
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
126
|
-
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
127
|
-
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>>> {
|
|
128
|
-
readonly name: TName;
|
|
129
|
-
readonly fields: TSchema;
|
|
130
|
-
readonly relations: TRelations;
|
|
131
|
-
constructor(name: TName, fields: TSchema, relations?: TRelations);
|
|
132
|
-
encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
|
|
133
|
-
mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
|
|
134
|
-
setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
|
|
135
|
-
getStorageFieldType(): StorageFieldType;
|
|
136
|
-
static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
|
|
137
|
-
}
|
|
138
|
-
declare const object: typeof LiveObject.create;
|
|
139
|
-
type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
|
|
140
|
-
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>, {
|
|
141
|
-
timestamp: string | null;
|
|
142
|
-
} & LiveTypeMeta> {
|
|
143
|
-
readonly entity: TEntity;
|
|
144
|
-
readonly type: TType;
|
|
145
|
-
readonly required: TRequired;
|
|
146
|
-
readonly relationalColumn?: TRelationalColumn;
|
|
147
|
-
readonly foreignColumn?: TForeignColumn;
|
|
148
|
-
readonly sourceEntity: TSourceEntity;
|
|
149
|
-
private constructor();
|
|
150
|
-
encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
|
|
151
|
-
value: string;
|
|
152
|
-
_meta: {
|
|
153
|
-
timestamp: string;
|
|
154
|
-
};
|
|
155
|
-
};
|
|
156
|
-
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
157
|
-
value: string;
|
|
158
|
-
_meta: {
|
|
159
|
-
timestamp: string;
|
|
160
|
-
};
|
|
161
|
-
}, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
|
|
162
|
-
MaterializedLiveType<LiveString>,
|
|
163
|
-
{
|
|
164
|
-
value: string;
|
|
165
|
-
_meta: {
|
|
166
|
-
timestamp: string;
|
|
167
|
-
};
|
|
168
|
-
} | null
|
|
169
|
-
];
|
|
170
|
-
getStorageFieldType(): StorageFieldType;
|
|
171
|
-
toJSON(): {
|
|
172
|
-
entityName: string;
|
|
173
|
-
type: TType;
|
|
174
|
-
required: TRequired;
|
|
175
|
-
relationalColumn: TRelationalColumn | undefined;
|
|
176
|
-
foreignColumn: TForeignColumn | undefined;
|
|
177
|
-
};
|
|
178
|
-
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>;
|
|
179
|
-
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>;
|
|
180
|
-
}
|
|
181
|
-
type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
|
|
182
|
-
declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
|
|
183
|
-
one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
|
|
184
|
-
many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
|
|
185
|
-
}) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
|
|
186
|
-
type MaterializedLiveType<T extends LiveTypeAny> = {
|
|
187
|
-
value: T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
188
|
-
[K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
|
|
189
|
-
} : T["_value"];
|
|
190
|
-
_meta: T["_meta"];
|
|
191
|
-
};
|
|
192
|
-
declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
|
|
193
|
-
type ExtractObjectValues<T> = T[keyof T];
|
|
194
|
-
type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
|
|
195
|
-
$type: "relations";
|
|
196
|
-
objectName: TObjectName;
|
|
197
|
-
relations: TRelations;
|
|
198
|
-
};
|
|
199
|
-
type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
200
|
-
[K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
|
|
201
|
-
[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"]>;
|
|
202
|
-
} : never : never;
|
|
203
|
-
}>;
|
|
204
|
-
type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
205
|
-
[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;
|
|
206
|
-
}>;
|
|
207
|
-
type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
|
|
208
|
-
type Schema<TRawSchema extends RawSchema> = {
|
|
209
|
-
[K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
|
|
210
|
-
};
|
|
211
|
-
declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
|
|
212
|
-
type WhereClause<T extends LiveObjectAny> = ({
|
|
213
|
-
[K in keyof T["fields"]]?: InferLiveType<T["fields"][K]> | ({
|
|
214
|
-
$eq?: InferLiveType<T["fields"][K]>;
|
|
215
|
-
$in?: InferLiveType<T["fields"][K]>[];
|
|
216
|
-
$not?: InferLiveType<T["fields"][K]> | {
|
|
217
|
-
$in?: InferLiveType<T["fields"][K]>[];
|
|
218
|
-
$eq?: InferLiveType<T["fields"][K]>;
|
|
219
|
-
};
|
|
220
|
-
} & (InferLiveType<T["fields"][K]> extends number ? {
|
|
221
|
-
$gt?: InferLiveType<T["fields"][K]>;
|
|
222
|
-
$gte?: InferLiveType<T["fields"][K]>;
|
|
223
|
-
$lt?: InferLiveType<T["fields"][K]>;
|
|
224
|
-
$lte?: InferLiveType<T["fields"][K]>;
|
|
225
|
-
} : {}));
|
|
226
|
-
} & {
|
|
227
|
-
[K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
|
|
228
|
-
}) | {
|
|
229
|
-
$and?: WhereClause<T>[];
|
|
230
|
-
$or?: WhereClause<T>[];
|
|
231
|
-
};
|
|
232
|
-
type IncludeClause<T extends LiveObjectAny> = {
|
|
233
|
-
[K in keyof T["relations"]]?: boolean;
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
export { type IncludeClause, 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 };
|
|
1
|
+
export { b as IncludeClause, F as InferIndex, d as InferInsert, c as InferLiveObject, I as InferLiveObjectWithRelationalIds, h as InferLiveObjectWithoutRelations, E as InferLiveType, e as InferUpdate, n as LiveAtomicType, v as LiveBoolean, p as LiveNumber, j as LiveObject, L as LiveObjectAny, i as LiveObjectMutationInput, r as LiveString, x as LiveTimestamp, C as LiveType, D as LiveTypeAny, z as LiveTypeMeta, g as LogLevel, M as MaterializedLiveType, A as MutationType, N as NullableLiveType, R as Relation, a as Schema, B as StorageFieldType, W as WhereClause, w as boolean, k as createRelations, m as createSchema, t as id, l as inferValue, q as number, o as object, u as reference, s as string, y as timestamp } from './index-COp5Ib0a.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{e as LiveAtomicType,l as LiveBoolean,f as LiveNumber,p as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,x as LogLevel,d as NullableLiveType,r as Relation,m as boolean,s as createRelations,u as createSchema,j as id,t as inferValue,g as number,q as object,k as reference,i as string,o as timestamp}from'./chunk-GUSCESQZ.js';
|
package/dist/server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var je=require('qs'),zod=require('zod'),j=require('crypto'),kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var je__default=/*#__PURE__*/_interopDefault(je);var j__default=/*#__PURE__*/_interopDefault(j);var pe=Object.create;var Q=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var ge=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Re=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Te(e))!he.call(n,a)&&a!==t&&Q(n,a,{get:()=>e[a],enumerable:!(r=me(e,a))||r.enumerable});return n};var B=(n,e,t)=>(t=n!=null?pe(fe(n)):{},Re(Q(t,"default",{value:n,enumerable:true}),n));var P=ge(E=>{Object.defineProperty(E,"__esModule",{value:true});E.parse=Ie;E.serialize=Le;var ve=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,xe=/^[\u0021-\u003A\u003C-\u007E]*$/,be=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,we=/^[\u0020-\u003A\u003D-\u007E]*$/,Me=Object.prototype.toString,Se=(()=>{let n=function(){};return n.prototype=Object.create(null),n})();function Ie(n,e){let t=new Se,r=n.length;if(r<2)return t;let a=(e==null?void 0:e.decode)||Ae,i=0;do{let o=n.indexOf("=",i);if(o===-1)break;let c=n.indexOf(";",i),s=c===-1?r:c;if(o>s){i=n.lastIndexOf(";",o-1)+1;continue}let T=J(n,i,o),m=Y(n,o,T),d=n.slice(T,m);if(t[d]===void 0){let y=J(n,o+1,s),u=Y(n,s,y),l=a(n.slice(y,u));t[d]=l;}i=s+1;}while(i<r);return t}function J(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Y(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function Le(n,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!ve.test(n))throw new TypeError(`argument name is invalid: ${n}`);let a=r(e);if(!xe.test(a))throw new TypeError(`argument val is invalid: ${e}`);let i=n+"="+a;if(!t)return i;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);i+="; Max-Age="+t.maxAge;}if(t.domain){if(!be.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);i+="; Domain="+t.domain;}if(t.path){if(!we.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);i+="; Path="+t.path;}if(t.expires){if(!Ee(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);i+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(i+="; HttpOnly"),t.secure&&(i+="; Secure"),t.partitioned&&(i+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":i+="; Priority=Low";break;case "medium":i+="; Priority=Medium";break;case "high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":i+="; SameSite=Strict";break;case "lax":i+="; SameSite=Lax";break;case "none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return i}function Ae(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}function Ee(n){return Me.call(n)==="[object Date]"}});var te=B(P());var O=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.any()).optional(),include:zod.z.record(zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),V=zod.z.record(zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})).superRefine((n,e)=>{n.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),X=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string()}),S=X.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),I=X.extend({resourceId:zod.z.string(),payload:V});zod.z.union([S,I]);var ee=O.omit({resource:true}),N=S.omit({id:true,type:true,resource:true,procedure:true}),F=I.omit({id:true,type:true,resource:true});zod.z.union([F,N]);var ne=n=>async e=>{var t;try{let r=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,a={headers:r,cookies:r.cookie?te.default.parse(r.cookie):{}},i=new URL(e.url),o=i.pathname.split("/"),c=i.searchParams,s=je__default.default.parse(c.toString()),T=await((t=n.contextProvider)==null?void 0:t.call(n,{transport:"HTTP",headers:a.headers,cookies:a.cookies,query:s}))??{};if(e.method==="GET"){let m=o[o.length-1],{success:d,data:y,error:u}=ee.safeParse(s);if(!d)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:u},{status:400});let l=await n.handleRequest({req:{...a,type:"QUERY",resourceName:m,context:T,where:y.where,include:y.include,query:s}});return !l||!l.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(l.data)}if(e.method==="POST")try{let m=o[o.length-1],d=o[o.length-2],y=e.body?await e.json():{},u;if(m==="set"){let{success:w,data:M,error:_}=F.safeParse(y);if(!w)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:_},{status:400});u=M;}else {let{success:w,data:M,error:_}=N.safeParse(y);if(!w)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:_},{status:400});u=M;}let l=await n.handleRequest({req:{...a,type:"MUTATE",resourceName:d,input:u.payload,context:T,resourceId:u.resourceId,procedure:m!=="set"?m:void 0,query:{}}});return Response.json(l)}catch(m){return console.error("Error parsing mutation from the client:",m),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return console.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var ue=B(P());var x=zod.z.string(),Ce=zod.z.object({id:x,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),_e=O.extend({id:x,type:zod.z.literal("QUERY")}),re=I.extend({id:x}),Pe=S.extend({id:x}),Ve=zod.z.union([Pe,re]),ae=zod.z.union([Ce,_e,Ve]),Ne=zod.z.object({id:x,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),Fe=zod.z.object({id:x,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Ne,Fe,re]);zod.z.object({resource:zod.z.string(),data:zod.z.record(V)});var oe="0123456789ABCDEFGHJKMNPQRSTVWXYZ",L=32;var $e=16,se=10,ie=0xffffffffffff;var h;(function(n){n.Base32IncorrectEncoding="B32_ENC_INVALID",n.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",n.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",n.EncodeTimeNegative="ENC_TIME_NEG",n.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",n.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",n.PRNGDetectFailure="PRNG_DETECT",n.ULIDInvalid="ULID_INVALID",n.Unexpected="UNEXPECTED",n.UUIDInvalid="UUID_INVALID";})(h||(h={}));var g=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Ke(n){let e=Math.floor(n()*L);return e===L&&(e=L-1),oe.charAt(e)}function De(n){var r;let e=qe(),t=e&&(e.crypto||e.msCrypto)||(typeof j__default.default<"u"?j__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let a=new Uint8Array(1);return t.getRandomValues(a),a[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=j__default.default)!=null&&r.randomBytes)return ()=>j__default.default.randomBytes(1).readUInt8()/255;throw new g(h.PRNGDetectFailure,"Failed to find a reliable PRNG")}function qe(){return ze()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ue(n,e){let t="";for(;n>0;n--)t=Ke(e)+t;return t}function ke(n,e=se){if(isNaN(n))throw new g(h.EncodeTimeValueMalformed,`Time must be a number: ${n}`);if(n>ie)throw new g(h.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ie}: ${n}`);if(n<0)throw new g(h.EncodeTimeNegative,`Time must be positive: ${n}`);if(Number.isInteger(n)===false)throw new g(h.EncodeTimeValueMalformed,`Time must be an integer: ${n}`);let t,r="";for(let a=e;a>0;a--)t=n%L,r=oe.charAt(t)+r,n=(n-t)/L;return r}function ze(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ce(n,e){let t=De(),r=Date.now();return ke(r,se)+Ue($e,t)}var $=()=>ce().toLowerCase();var le=n=>{let e={},t={};return n.subscribeToMutations(r=>{let a=r;!a.resourceId||!a.payload||(console.log("Mutation propagated:",a),Object.entries(t[a.resource]??{}).forEach(([i,o])=>{var c;(c=e[i])==null||c.send(JSON.stringify({...a,id:a.id??$()}));}));}),(r,a)=>{var m;let i=d=>{r.send(JSON.stringify(d));},o=$(),c={headers:a.headers,cookies:typeof a.headers.cookie=="string"?ue.default.parse(a.headers.cookie):{}},s=je.parse(a.url.split("?")[1]),T=(m=n.contextProvider)==null?void 0:m.call(n,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,query:s});e[o]=r,console.log("Client connected:",o),r.on("message",async d=>{try{console.log("Message received from the client:",d);let y=ae.parse(JSON.parse(d.toString()));if(y.type==="SUBSCRIBE"){let{resource:u}=y;t[u]||(t[u]={}),t[u][o]={};}else if(y.type==="QUERY"){let{resource:u}=y,l=await n.handleRequest({req:{...c,type:"QUERY",resourceName:u,context:await T??{},query:s}});if(!l||!l.data)throw new Error("Invalid resource");i({id:y.id,type:"REPLY",data:{resource:u,data:Object.fromEntries(Object.entries(l.data??{}).map(([w,M])=>[w,M.value]))}});}else if(y.type==="MUTATE"){let{resource:u}=y;console.log("Received mutation from client:",y);try{let l=await n.handleRequest({req:{...c,type:"MUTATE",resourceName:u,input:y.payload,context:{messageId:y.id,...await T??{}},resourceId:y.resourceId,procedure:y.procedure,query:s}});y.procedure&&i({id:y.id,type:"REPLY",data:l});}catch(l){i({id:y.id,type:"REJECT",resource:u,message:l.message}),console.error("Error parsing mutation from the client:",l);}}}catch(y){console.error("Error handling message from the client:",y);}}),r.on("close",()=>{console.log("Connection closed",o),delete e[o];for(let d of Object.values(t))delete d[o];});}};function de(n){let e=`${n.protocol}://${n.hostname}${n.url}`,t=new Headers;return Object.entries(n.headers).forEach(([r,a])=>{a&&t.set(r,Array.isArray(a)?a.join(","):a);}),new Request(e,{method:n.method,headers:t,body:n.body&&n.method!=="GET"?JSON.stringify(n.body):void 0})}var It=(n,e,t)=>{n.ws(`${(t==null?void 0:t.basePath)??""}/ws`,le(e)),n.use(`${(t==null?void 0:t.basePath)??""}/`,(r,a)=>{ne(e)(de(r)).then(o=>o.json().then(c=>a.status(o.status).send(c)));});};var K=class n{routes;constructor(e){this.routes=e.routes;}static create(e){return new n(e)}},Et=n=>K.create({...n}),He=n=>({handler:e=>({inputValidator:n??zod.z.undefined(),handler:e})}),D=class n{_resourceSchema;resourceName;middlewares;customMutations;constructor(e,t){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{};}handleFind=async({req:e,db:t})=>({data:await t.rawFind(e.resourceName,e.where,e.include),acceptedValues:null});handleSet=async({req:e,db:t,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resourceName,e.resourceId),[i,o]=r[this.resourceName].mergeMutation("set",e.input,a);if(!o)throw new Error("Mutation rejected");return {data:await t.rawUpsert(e.resourceName,e.resourceId,i),acceptedValues:o}};async handleRequest(e){let t=r=>(()=>{if(r.type==="QUERY")return this.handleFind({req:r,db:e.db,schema:e.schema});if(r.type==="MUTATE")if(r.procedure){if(this.customMutations[r.procedure]){let a=this.customMutations[r.procedure].inputValidator.parse(r.input);return r.input=a,this.customMutations[r.procedure].handler({req:r,db:e.db,schema:e.schema})}}else return this.handleSet({req:r,db:e.db,schema:e.schema});throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((r,a)=>i=>a({req:i,next:r}),async r=>t(r))(e.req)}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new n(this.resourceName,e({mutation:He}))}},q=class n{middlewares;constructor(e=[]){this.middlewares=e;}createBasicRoute(e){return new D(e.name).use(...this.middlewares)}use(...e){return new n([...this.middlewares,...e])}static create(){return new n}},Ot=q.create;var v=n=>{if(n)return Array.isArray(n.value)?n.value.map(e=>v(e)):typeof n.value!="object"||n.value===null||n.value instanceof Date?n.value:Object.fromEntries(Object.entries(n.value).map(([e,t])=>[e,v(t)]))};var H=class{async insert(e,t){let r=new Date().toISOString();return v(await this.rawUpsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([a,i])=>[a,{value:i,_meta:{timestamp:r}}]))}))}async update(e,t,r){let a=new Date().toISOString(),{id:i,...o}=r;return v(await this.rawUpsert(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([c,s])=>[c,{value:s,_meta:{timestamp:a}}]))}))}},ye=class extends H{db;schema;constructor(e){super(),this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})});}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[r,a]of Object.entries(e)){let i=t.find(s=>s.name===r);i||await this.db.schema.createTable(r).ifNotExists().execute();let o=`${r}_meta`,c=t.find(s=>s.name===o);c||await this.db.schema.createTable(o).ifNotExists().execute();for(let[s,T]of Object.entries(a.fields)){let m=i==null?void 0:i.columns.find(u=>u.name===s),d=T.getStorageFieldType();m?m.dataType!==d.type&&console.error("Column type mismatch:",s,"expected to have type:",d.type,"but has type:",m.dataType):(await this.db.schema.alterTable(r).addColumn(s,d.type,u=>{let l=u;return d.unique&&(l=l.unique()),d.nullable||(l=l.notNull()),d.references&&(l=l.references(d.references)),d.primary&&(l=l.primaryKey()),d.default!==void 0&&(l=l.defaultTo(d.default)),l}).execute().catch(u=>{throw console.error("Error adding column",s,u),u}),d.index&&await this.db.schema.createIndex(`${r}_${s}_index`).on(r).column(s).execute().catch(u=>{})),(c==null?void 0:c.columns.find(u=>u.name===s))||await this.db.schema.alterTable(o).addColumn(s,"varchar",u=>{let l=u;return d.primary&&(l=l.primaryKey().references(`${r}.${s}`)),l}).execute();}}}async rawFindById(e,t,r){let a=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(o=>postgres.jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));a=this.applyInclude(e,a,r);let i=await a.executeTakeFirst();if(i)return this.convertToMaterializedLiveType(i)}async findOne(e,t,r){let a=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(a)return v(a)}async rawFind(e,t,r){let a=this.db.selectFrom(e).selectAll(e).select(s=>postgres.jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));a=this.applyWhere(e,a,t),a=this.applyInclude(e,a,r);let i=await a.execute(),o=Object.fromEntries(i.map(s=>{let{id:T,...m}=s;return [T,m]}));return Object.keys(o).length===0?{}:Object.entries(o).reduce((s,[T,m])=>(s[T]=this.convertToMaterializedLiveType(m),s),{})}async find(e,t){let r=await this.rawFind(e.name,t==null?void 0:t.where,t==null?void 0:t.include);return Object.fromEntries(Object.entries(r).map(([a,i])=>[a,v(i)]))}async rawUpsert(e,t,r){return await this.db.transaction().execute(async a=>{var s;let i=!!await a.selectFrom(e).select("id").where("id","=",t).executeTakeFirst(),o={},c={};for(let[T,m]of Object.entries(r.value)){let d=(s=m._meta)==null?void 0:s.timestamp;d&&(o[T]=m.value,c[T]=d);}i?await Promise.all([a.updateTable(e).set(o).where("id","=",t).execute(),a.updateTable(`${e}_meta`).set(c).where("id","=",t).execute()]):await Promise.all([a.insertInto(e).values({...o,id:t}).execute(),a.insertInto(`${e}_meta`).values({...c,id:t}).execute()]);}),r}convertToMaterializedLiveType(e){if(!e._meta)throw new Error("Missing _meta");return {value:Object.entries(e).reduce((t,[r,a])=>{var i,o,c;return r==="_meta"||(r==="id"?t[r]={value:a}:Array.isArray(a)?t[r]={value:a.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(i=e==null?void 0:e._meta)==null?void 0:i[r]}}:typeof a=="object"&&a!==null&&!(a instanceof Date)?t[r]={...this.convertToMaterializedLiveType(a),_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[r]}}:t[r]={value:a,_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[r]}}),t},{})}}applyWhere(e,t,r){if(!r)return t;if(!this.schema)throw new Error("Schema not initialized");let a=this.schema[e];if(!a)throw new Error("Resource not found");for(let[i,o]of Object.entries(r))if(a.fields[i])t=t.where(`${e}.${i}`,"=",o);else if(a.relations[i]){let c=a.relations[i],s=c.entity.name,T=c.type==="one"?"id":c.foreignColumn,m=c.type==="one"?c.relationalColumn:"id";t=t.leftJoin(s,`${s}.${T}`,`${e}.${m}`),t=this.applyWhere(s,t,o);}return t}applyInclude(e,t,r){if(!r)return t;if(!this.schema)throw new Error("Schema not initialized");let a=this.schema[e];if(!a)throw new Error(`Resource not found: ${e}`);for(let[i,o]of Object.entries(r)){if(!a.relations[i])throw new Error(`Relation ${i} not found in resource ${e}`);let c=a.relations[i],s=c.entity.name,T=c.type==="one"?"id":c.foreignColumn,m=c.type==="one"?c.relationalColumn:"id",d=c.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom;t=t.select(y=>d(y.selectFrom(s).selectAll(s).whereRef(`${s}.${T}`,"=",`${e}.${m}`).select(u=>postgres.jsonObjectFrom(u.selectFrom(`${s}_meta`).selectAll(`${s}_meta`).whereRef(`${s}_meta.id`,"=",`${s}.id`)).as("_meta"))).as(i));}return t}};var G=class n{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.updateSchema(this.schema),this.contextProvider=e.contextProvider;}static create(e){return new n(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((r,a)=>i=>a({req:i,next:r}),async r=>this.router.routes[e.req.resourceName].handleRequest({req:r,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&this.mutationSubscriptions.forEach(r=>{r({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},Bt=G.create;
|
|
2
|
-
exports.Route=
|
|
1
|
+
'use strict';require('js-xxhash');var V=require('crypto'),rt=require('qs'),zod=require('zod'),kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var V__default=/*#__PURE__*/_interopDefault(V);var rt__default=/*#__PURE__*/_interopDefault(rt);var je=Object.create;var ce=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var Ne=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ze=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $e(e))!Pe.call(i,n)&&n!==t&&ce(i,n,{get:()=>e[n],enumerable:!(r=Ee(e,n))||r.enumerable});return i};var ue=(i,e,t)=>(t=i!=null?je(Ce(i)):{},ze(ce(t,"default",{value:i,enumerable:true}),i));var Q=Ne(W=>{Object.defineProperty(W,"__esModule",{value:true});W.parse=He;W.serialize=Je;var Ue=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ke=/^[\u0021-\u003A\u003C-\u007E]*$/,Be=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Qe=/^[\u0020-\u003A\u003D-\u007E]*$/,Ge=Object.prototype.toString,Ze=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function He(i,e){let t=new Ze,r=i.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||Ye,a=0;do{let c=i.indexOf("=",a);if(c===-1)break;let o=i.indexOf(";",a),s=o===-1?r:o;if(c>s){a=i.lastIndexOf(";",c-1)+1;continue}let m=fe(i,a,c),l=he(i,c,m),d=i.slice(m,l);if(t[d]===void 0){let y=fe(i,c+1,s),u=he(i,s,y),h=n(i.slice(y,u));t[d]=h;}a=s+1;}while(a<r);return t}function fe(i,e,t){do{let r=i.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function he(i,e,t){for(;e>t;){let r=i.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function Je(i,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!Ue.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(e);if(!ke.test(n))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+n;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!Be.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Qe.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!Xe(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return a}function Ye(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Xe(i){return Ge.call(i)==="[object Date]"}});var E=(i,e,t)=>{let r={},n=t[e];if(!n)return r;let a=c=>{c.$and?c.$and.forEach(a):c.$or?c.$or.forEach(a):Object.entries(c).forEach(([o,s])=>{var m;if((m=n.relations)!=null&&m[o]&&(r[o]=true,typeof s=="object"&&s!==null&&!Array.isArray(s))){let l=E(s,n.relations[o].entity.name,t);Object.keys(l).length>0&&(r[o]=l);}});};return a(i),r},w=(i,e,t=false)=>Object.entries(e).every(([r,n])=>{if(r==="$and")return n.every(c=>w(i,c,t));if(r==="$or")return n.some(c=>w(i,c,t));let a=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let o=i[r];return o===void 0?false:t?!n.$in.includes(o):n.$in.includes(o)}if(n.$not!==void 0&&!t)return w(i,{[r]:n.$not},true);if(n.$gt!==void 0){let o=i[r];return typeof o!="number"?false:t?o<=n.$gt:o>n.$gt}if(n.$gte!==void 0){let o=i[r];return typeof o!="number"?false:t?o<n.$gte:o>=n.$gte}if(n.$lt!==void 0){let o=i[r];return typeof o!="number"?false:t?o>=n.$lt:o<n.$lt}if(n.$lte!==void 0){let o=i[r];return typeof o!="number"?false:t?o>n.$lte:o<=n.$lte}let c=i[r];return !c||typeof c!="object"&&!Array.isArray(c)?false:Array.isArray(c)?t?!c.some(o=>w(o,n,false)):c.some(o=>w(o,n,false)):w(c,n,t)}return t?i[r]!==a:i[r]===a}),S={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},k=class{level;prefix;constructor(e={}){this.level=e.level??S.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=S.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=S.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=S.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=S.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=S.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},le=i=>new k(i);var ye="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$=32;var Ve=16,pe=10,de=0xffffffffffff;var L;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(L||(L={}));var M=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function _e(i){let e=Math.floor(i()*$);return e===$&&(e=$-1),ye.charAt(e)}function Fe(i){var r;let e=We(),t=e&&(e.crypto||e.msCrypto)||(typeof V__default.default<"u"?V__default.default: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;if((r=V__default.default)!=null&&r.randomBytes)return ()=>V__default.default.randomBytes(1).readUInt8()/255;throw new M(L.PRNGDetectFailure,"Failed to find a reliable PRNG")}function We(){return De()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function qe(i,e){let t="";for(;i>0;i--)t=_e(e)+t;return t}function Ke(i,e=pe){if(isNaN(i))throw new M(L.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>de)throw new M(L.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${de}: ${i}`);if(i<0)throw new M(L.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new M(L.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,r="";for(let n=e;n>0;n--)t=i%$,r=ye.charAt(t)+r,i=(i-t)/$;return r}function De(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function me(i,e){let t=Fe(),r=Date.now();return Ke(r,pe)+qe(Ve,t)}var B=()=>me().toLowerCase();var _=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var F=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...n}){return new Promise((a,c)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...n}),s={resource:e,commonWhere:t,uniqueWhere:r,...n,resolve:a,reject:c};this.queue.has(o)||this.queue.set(o,[]);let m=this.queue.get(o);m&&m.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...n}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(r){t.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(e){var y,u;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:n,include:a,sort:c}=t,o=e.length===1?t.limit:void 0,s=e.map(h=>h.uniqueWhere).filter(h=>h!==void 0),m=n,l=(y=Object.entries(s[0]??{})[0])==null?void 0:y[0];if(s.length>0){let h=s.map(p=>p[l]).filter(p=>p!=null);h.length>0&&(m=_(n,{[l]:{$in:h}}));}let d=await this.storage.rawFind({resource:r,where:m,include:a,sort:c,limit:o});for(let h of e){let p={};if(h.uniqueWhere){let[f,g]=Object.entries(h.uniqueWhere)[0];for(let[x,v]of Object.entries(d))((u=v.value[f])==null?void 0:u.value)===g&&(p[x]=v);}else Object.assign(p,d);h.resolve(p);}}};var Re=ue(Q());var q=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),G=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),et=G.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Te=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),C=Te.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),P=Te.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:et});zod.z.union([P,C]);var ge=q.omit({resource:true}),Z=C.omit({id:true,type:true,resource:true,procedure:true}),H=P.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([H,Z]);var xe=i=>{let e=i.logger;return async t=>{var r;try{let n=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,a={headers:n,cookies:n.cookie?Re.default.parse(n.cookie):{}},c=new URL(t.url),o=c.pathname.split("/"),s=c.searchParams,m=rt__default.default.parse(s.toString()),l=await((r=i.contextProvider)==null?void 0:r.call(i,{transport:"HTTP",headers:a.headers,cookies:a.cookies,queryParams:m}))??{};if(t.method==="GET"){let d=o[o.length-1],{success:y,data:u,error:h}=ge.safeParse(m);if(!y)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:h},{status:400});let p=await i.handleQuery({req:{...a,...u,type:"QUERY",resource:d,context:l,queryParams:m}});return !p||!p.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(p.data)}if(t.method==="POST")try{let d=o[o.length-1],y=o[o.length-2],u=t.body?await t.json():{},h;if(d==="insert"||d==="update"){let{success:f,data:g,error:x}=H.safeParse(u);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:x},{status:400});h=g;}else {let{success:f,data:g,error:x}=Z.safeParse(u);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:x},{status:400});h=g;}let p=await i.handleMutation({req:{...a,type:"MUTATE",resource:y,input:h.payload,context:l,resourceId:h.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{}}});return Response.json(p)}catch(d){return e.error("Error parsing mutation from the client:",d),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return e.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var we=ue(Q());var A=zod.z.string(),nt=zod.z.object({id:A,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),it=q.extend({id:A,type:zod.z.literal("QUERY")}),be=P.extend({id:A}),at=C.extend({id:A}),ot=zod.z.union([at,be]),ve=zod.z.union([nt,it,ot]),st=zod.z.object({id:A,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),ct=zod.z.object({id:A,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([st,ct,be]);zod.z.object({resource:zod.z.string(),data:zod.z.record(zod.z.string(),G)});var Se=i=>{let e={},t={},r=i.logger;return i.subscribeToMutations(n=>{let a=n;!a.resourceId||!a.payload||(r.debug("Mutation propagated:",a),Object.entries(t[a.resource]??{}).forEach(([c,o])=>{var s;(s=e[c])==null||s.send(JSON.stringify({...a,id:a.id??B()}));}));}),(n,a)=>{var d;let c=y=>{n.send(JSON.stringify(y));},o=B(),s={headers:a.headers,cookies:typeof a.headers.cookie=="string"?we.default.parse(a.headers.cookie):{}},m=rt.parse(a.url.split("?")[1]),l=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:m});e[o]=n,r.info("Client connected:",o),n.on("message",async y=>{try{r.debug("Message received from the client:",y);let u=ve.parse(JSON.parse(y.toString()));if(u.type==="SUBSCRIBE"){let{resource:h}=u;t[h]||(t[h]={}),t[h][o]={};}else if(u.type==="QUERY"){let{resource:h}=u,p=await i.handleQuery({req:{...s,type:"QUERY",resource:h,context:await l??{},queryParams:m}});if(!p||!p.data)throw new Error("Invalid resource");c({id:u.id,type:"REPLY",data:{resource:h,data:Object.fromEntries(Object.entries(p.data??{}).map(([f,g])=>[f,g.value]))}});}else if(u.type==="MUTATE"){let{resource:h}=u;r.debug("Received mutation from client:",u);try{let p=await i.handleMutation({req:{...s,type:"MUTATE",resource:h,input:u.payload,context:{messageId:u.id,...await l??{}},resourceId:u.resourceId,procedure:u.procedure,queryParams:m}});u.procedure&&u.procedure!=="INSERT"&&u.procedure!=="UPDATE"&&c({id:u.id,type:"REPLY",data:p});}catch(p){c({id:u.id,type:"REJECT",resource:h,message:p.message}),r.error("Error parsing mutation from the client:",p);}}}catch(u){r.error("Error handling message from the client:",u);}}),n.on("close",()=>{r.info("Connection closed",o),delete e[o];for(let y of Object.values(t))delete y[o];});}};function Ie(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Zt=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Se(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{xe(e)(Ie(r)).then(c=>c.json().then(o=>n.status(c.status).send(o)));});};var b=i=>i?Array.isArray(i.value)?i.value.map(t=>b(t)):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([t,r])=>Array.isArray(r)?[t,r.map(n=>b(n))]:[t,b(r)])):void 0;var re=class i{routes;constructor(e){this.routes=e.routes;}static create(e){return new i(e)}},fr=i=>re.create({...i}),dt=i=>({handler:e=>({inputValidator:i??zod.z.undefined(),handler:e})}),ne=class i{resourceSchema;middlewares;customMutations;authorization;constructor(e,t,r){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=r;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new i(this.resourceSchema,e({mutation:dt}),this.authorization)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async r=>{var a,c;let n=(c=(a=this.authorization)==null?void 0:a.read)==null?void 0:c.call(a,{ctx:r.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await t.rawFind({resource:r.resource,commonWhere:_(r.where,typeof n=="object"?n:void 0),uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort})}})(e);handleMutation=async({req:e,db:t,schema:r})=>await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[n.procedure];if(a){let c=a.inputValidator.parse(n.input);return n.input=c,a.handler({req:n,db:t})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:t,operation:n.procedure,schema:r});throw new Error(`Unknown procedure: ${n.procedure}`)}})(e);handleSet=async({req:e,db:t,operation:r,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&a)throw new Error("Resource already exists");if(r==="UPDATE"&&!a)throw new Error("Resource not found");return t.transaction(async({trx:c})=>{var l,d,y,u,h;let[o,s]=this.resourceSchema.mergeMutation("set",e.input,a);if(!s)throw new Error("Mutation rejected");if(r==="INSERT"){let p=await c.rawInsert(e.resource,e.resourceId,o),f=b(p);if(f.id=f.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let g=this.authorization.insert({ctx:e.context,value:f});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let x=E(g,e.resource,n),v=Object.keys(x).length>0?await c.rawFindById(e.resource,e.resourceId,x):p,I=b(v);if(I.id=I.id??e.resourceId,!w(I,g))throw new Error("Not authorized")}}return {data:p,acceptedValues:s}}if((y=(d=this.authorization)==null?void 0:d.update)!=null&&y.preMutation){let p=b(a);p.id=p.id??e.resourceId;let f=this.authorization.update.preMutation({ctx:e.context,value:p});if(typeof f=="boolean"){if(!f)throw new Error("Not authorized")}else {let g=E(f,e.resource,n),x=Object.keys(g).length>0?await c.rawFindById(e.resource,e.resourceId,g):a,v=b(x);if(v.id=v.id??e.resourceId,!w(v,f))throw new Error("Not authorized")}}let m=await c.rawUpdate(e.resource,e.resourceId,o);if((h=(u=this.authorization)==null?void 0:u.update)!=null&&h.postMutation){let p=b(m);p.id=p.id??e.resourceId;let f=this.authorization.update.postMutation({ctx:e.context,value:p});if(typeof f=="boolean"){if(!f)throw new Error("Not authorized")}else {let g=E(f,e.resource,n),x=Object.keys(g).length>0?await c.rawFindById(e.resource,e.resourceId,g):m,v=b(x);if(v.id=v.id??e.resourceId,!w(v,f))throw new Error("Not authorized")}}return {data:m,acceptedValues:s}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),e)(t)}},ie=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new ne(e,void 0,t).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},hr=ie.create;var z=class{async insert(e,t){let r=new Date().toISOString();return b(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([n,a])=>[n,{value:a,_meta:{timestamp:r}}]))}))}async update(e,t,r){let n=new Date().toISOString(),{id:a,...c}=r;return b(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(c).map(([o,s])=>[o,{value:s,_meta:{timestamp:n}}]))}))}};function K(i,e,t,r){if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error("Resource not found");let a=r.$or,c=r.$and;return (a?t.or:t.and)(a?r.$or.map(o=>K(i,e,t,o)):c?r.$and.map(o=>K(i,e,t,o)):Object.entries(r).map(([o,s])=>{var m,l;if(n.fields[o])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${o}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${o}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((m=s==null?void 0:s.$not)==null?void 0:m.$in)!==void 0?t(`${e}.${o}`,"not in",s.$not.$in):((l=s==null?void 0:s.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${o}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${o}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${o}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${o}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${o}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${o}`,"<=",s.$lte):t(`${e}.${o}`,s===null?"is":"=",s);if(n.relations[o]){let d=n.relations[o],y=d.entity.name;return d.type==="many"?t.exists(ae(i,y,t.selectFrom(y).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),s)):K(i,y,t,s)}return null}).filter(Boolean))}function D(i,e,t,r){let n=i[e];if(!n)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let a of r.$and)t=D(i,e,t,a);return t}else if(r.$or){for(let a of r.$or)t=D(i,e,t,a);return t}for(let[a,c]of Object.entries(r)){if(!n.relations[a])continue;let o=n.relations[a],s=o.entity.name,m=o.type==="one"?"id":o.foreignColumn,l=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(s,`${s}.${m}`,`${e}.${l}`),c instanceof Object&&!Array.isArray(c)&&c!==null&&(t=D(i,s,t,c));}return t}function ae(i,e,t,r){return !r||Object.keys(r).length===0?t:(t=D(i,e,t,r),t.where(n=>K(i,e,n,r)))}function U(i,e,t,r){if(!r)return t;if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(r)){if(!n.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let c=n.relations[a],o=c.entity.name,s=r[a],m=c.type==="one"?"id":c.foreignColumn,l=c.type==="one"?c.relationalColumn:"id",d=c.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom,y=typeof s=="object"&&s!==null;t=t.select(u=>{let h=u.selectFrom(o).selectAll(o).whereRef(`${o}.${m}`,"=",`${e}.${l}`).select(p=>postgres.jsonObjectFrom(p.selectFrom(`${o}_meta`).selectAll(`${o}_meta`).whereRef(`${o}_meta.id`,"=",`${o}.id`)).as("_meta"));return y&&(h=U(i,o,h,s)),d(h).as(a)});}return t}var oe=class i extends z{db;schema;logger;constructor(e,t,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.logger=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t){var n;this.schema=e,this.logger=t;let r=await this.db.introspection.getTables();for(let[a,c]of Object.entries(e)){let o=r.find(l=>l.name===a);o||await this.db.schema.createTable(a).ifNotExists().execute();let s=`${a}_meta`,m=r.find(l=>l.name===s);m||await this.db.schema.createTable(s).ifNotExists().execute();for(let[l,d]of Object.entries(c.fields)){let y=o==null?void 0:o.columns.find(p=>p.name===l),u=d.getStorageFieldType();y?y.dataType!==u.type&&((n=this.logger)==null||n.warn("Column type mismatch:",l,"expected to have type:",u.type,"but has type:",y.dataType)):(await this.db.schema.alterTable(a).addColumn(l,u.type,p=>{let f=p;return u.unique&&(f=f.unique()),u.nullable||(f=f.notNull()),u.references&&(f=f.references(u.references)),u.primary&&(f=f.primaryKey()),u.default!==void 0&&(f=f.defaultTo(u.default)),f}).execute().catch(p=>{var f;throw (f=this.logger)==null||f.error("Error adding column",l,p),p}),u.index&&await this.db.schema.createIndex(`${a}_${l}_index`).on(a).column(l).execute().catch(()=>{})),(m==null?void 0:m.columns.find(p=>p.name===l))||await this.db.schema.alterTable(s).addColumn(l,"varchar",p=>{let f=p;return u.primary&&(f=f.primaryKey().references(`${a}.${l}`)),f}).execute();}}}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(c=>postgres.jsonObjectFrom(c.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));n=U(this.schema,e,n,r);let a=await n.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,r){let n=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(n)return b(n)}async rawFind(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:n,limit:a,sort:c}=e,o=this.db.selectFrom(t).selectAll(t).select(d=>postgres.jsonObjectFrom(d.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));o=ae(this.schema,t,o,r),o=U(this.schema,t,o,n),a!==void 0&&(o=o.limit(a)),c!==void 0&&c.forEach(d=>{o=o.orderBy(d.key,d.direction);});let s=await o.execute(),m=Object.fromEntries(s.map(d=>{let{id:y}=d;return [y,d]}));return Object.keys(m).length===0?{}:Object.entries(m).reduce((d,[y,u])=>(d[y]=this.convertToMaterializedLiveType(u),d),{})}async find(e,t){let r=await this.rawFind({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort});return Object.fromEntries(Object.entries(r).map(([n,a])=>[n,b(a)]))}async rawInsert(e,t,r){var c;let n={},a={};for(let[o,s]of Object.entries(r.value)){let m=(c=s._meta)==null?void 0:c.timestamp;m&&(n[o]=s.value,a[o]=m);}return await this.db.insertInto(e).values({...n,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),r}async rawUpdate(e,t,r){var c;let n={},a={};for(let[o,s]of Object.entries(r.value)){let m=(c=s._meta)==null?void 0:c.timestamp;m&&(n[o]=s.value,a[o]=m);}return await Promise.all([this.db.updateTable(e).set(n).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(o=>o.column("id").doUpdateSet(a)).execute()]),r}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let r=Math.random().toString(36).substring(2,15),n=await this.db.savepoint(r).execute();try{return await e({trx:this,commit:()=>n.releaseSavepoint(r).execute().then(()=>{}),rollback:()=>n.rollbackToSavepoint(r).execute().then(()=>{})}).then(a=>n.isCommitted||n.isRolledBack?a:n.releaseSavepoint(r).execute().then(()=>a))}catch(a){throw await n.rollbackToSavepoint(r).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new i(t,this.schema,this.logger),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(r=>t.isCommitted||t.isRolledBack?r:t.commit().execute().then(()=>r))}catch(r){throw await t.rollback().execute(),r}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[r,n])=>{var a,c,o;return r==="_meta"||(r==="id"?t[r]={value:n}:Array.isArray(n)?t[r]={value:n.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?t[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[r]}}:t[r]={value:n,_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[r]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",c=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||a&&c}};var se=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=le({level:e.logLevel??S.INFO}),(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger),this.contextProvider=e.contextProvider;}static create(e){return new i(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}handleQuery(e){let t=new F(this.storage);return this.wrapInMiddlewares(async r=>{var m;let n=Ae(r,this.schema,{stepId:"query",collectionName:r.resource,included:Object.keys(r.include??{})}),a={headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context},c={};for(let l=0;l<n.length;l++){let d=n[l],y=this.router.routes[d.resource];if(!y)throw new Error("Invalid resource");let u=d.getWhere&&d.referenceGetter?d.referenceGetter(c).map(d.getWhere):[void 0],h=(m=c[d.prevStepId??""])==null?void 0:m.flatMap(g=>{var x;return Object.keys(((x=g==null?void 0:g.result)==null?void 0:x.data)??{})}),f=(await Promise.allSettled(u.map(async(g,x)=>{let v=h==null?void 0:h[x],I=await y.handleQuery({req:{type:"QUERY",...d,...a,where:d.where,relationalWhere:g},batcher:t});return {includedBy:v,result:I}}))).flatMap(g=>g.status==="fulfilled"?[g.value]:[]);c[d.stepId]=f;}let o=Object.fromEntries(Object.entries(c).flatMap(([l,d],y)=>d.flatMap(u=>Object.entries(u.result.data).map(([h,p])=>[`${l}.${h}`,{data:p,includedBy:l!=="query"&&u.includedBy?`${l.split(".").slice(0,-1).join(".")}.${u.includedBy}`:void 0,path:l.split(".").slice(-1)[0],isMany:n[y].isMany,collectionName:n[y].collectionName,included:n[y].included}]))));return Object.keys(o).reduceRight((l,d)=>{var h,p;let y=o[d],u=y.path;if(u==="query"&&(l.data[d.replace("query.","")]=y.data),y.included.length)for(let f of y.included)y.data.value[f]??=((p=(h=this.schema[y.collectionName])==null?void 0:h.relations[f])==null?void 0:p.type)==="many"?{value:[]}:{value:null};if(y.includedBy){let f=o[y.includedBy];if(!f)return l;y.isMany?(f.data.value[u]??={value:[]},f.data.value[u].value.push(y.data)):f.data.value[u]=y.data;}return l},{data:{}})})(e.req)}async handleMutation(e){let t=await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req);if(t&&e.req.type==="MUTATE"&&t.acceptedValues&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&e.req.resourceId){let n=t.acceptedValues??{},a=e.req,c=a.resourceId;Object.keys(n).length&&c&&this.mutationSubscriptions.forEach(o=>{o({id:e.req.context.messageId,type:"MUTATE",resource:a.resource,payload:n,resourceId:c,procedure:a.procedure});});}return t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),e)(t)}},Cr=se.create;function Ae(i,e,t){let{include:r,...n}=i,{stepId:a}=t,c=[{...n,...t}];if(r&&typeof r=="object"&&Object.keys(r).length>0){let o=e[n.resource];if(!o)throw new Error(`Resource ${n.resource} not found`);c.push(...Object.entries(r).flatMap(([s,m])=>{let l=o.relations[s];if(!l)throw new Error(`Relation ${s} not found for resource ${n.resource}`);let d=l.entity.name;return Ae({...n,resource:d,include:m},e,{getWhere:l.type==="one"?y=>({id:y}):y=>({[l.foreignColumn]:y}),referenceGetter:y=>y[a].flatMap(u=>u.result.data?l.type==="one"?Object.values(u.result.data).map(h=>{var p,f;return (f=(p=h.value)==null?void 0:p[l.relationalColumn])==null?void 0:f.value}):Object.keys(u.result.data):[]),stepId:`${a}.${s}`,prevStepId:a,isMany:l.type==="many",collectionName:d,included:typeof m=="object"?Object.keys(m):[]})}));}return c}
|
|
2
|
+
exports.Route=ne;exports.RouteFactory=ie;exports.Router=re;exports.SQLStorage=oe;exports.Server=se;exports.Storage=z;exports.expressAdapter=Zt;exports.routeFactory=hr;exports.router=fr;exports.server=Cr;
|