@hyper-fetch/db 0.0.0-stage → 10.2.0

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.
Files changed (141) hide show
  1. package/README.md +180 -2
  2. package/__tests__/e2e/db.e2e.spec.ts +269 -0
  3. package/__tests__/features/connection/connection.spec.ts +23 -0
  4. package/__tests__/features/model/live-query.model.spec.ts +320 -0
  5. package/__tests__/features/operators/operators.spec.ts +113 -0
  6. package/__tests__/features/runtime/runtime.spec.ts +185 -0
  7. package/__tests__/features/serializer/serializer.spec.ts +73 -0
  8. package/__tests__/features/store/store.spec.ts +147 -0
  9. package/__tests__/features/types/db.types.spec.ts +337 -0
  10. package/__tests__/integration/audit.spec.ts +639 -0
  11. package/__tests__/integration/competitors.spec.ts +393 -0
  12. package/__tests__/integration/convergence.model.spec.ts +162 -0
  13. package/__tests__/integration/edge-cases.spec.ts +465 -0
  14. package/__tests__/integration/errors.spec.ts +178 -0
  15. package/__tests__/integration/infinite.model.spec.ts +142 -0
  16. package/__tests__/integration/infinite.spec.ts +290 -0
  17. package/__tests__/integration/inspect.spec.ts +103 -0
  18. package/__tests__/integration/joins-many.spec.ts +177 -0
  19. package/__tests__/integration/joins.spec.ts +179 -0
  20. package/__tests__/integration/key-loaders.spec.ts +196 -0
  21. package/__tests__/integration/links.spec.ts +105 -0
  22. package/__tests__/integration/mutations.spec.ts +337 -0
  23. package/__tests__/integration/normalize.spec.ts +80 -0
  24. package/__tests__/integration/offline.spec.ts +479 -0
  25. package/__tests__/integration/queries.spec.ts +513 -0
  26. package/__tests__/integration/races.spec.ts +127 -0
  27. package/__tests__/integration/server-operators.spec.ts +123 -0
  28. package/__tests__/integration/ssr.spec.ts +111 -0
  29. package/__tests__/integration/syncs.spec.ts +564 -0
  30. package/__tests__/integration/transactions.spec.ts +344 -0
  31. package/__tests__/integration/windows.spec.ts +192 -0
  32. package/__tests__/tsconfig.json +11 -0
  33. package/__tests__/type-budget/budget.fixture.ts +2476 -0
  34. package/__tests__/type-budget/tsconfig.json +4 -0
  35. package/__tests__/utils/fixtures.ts +225 -0
  36. package/__tests__/utils/random.ts +19 -0
  37. package/__tests__/vitest.setup.ts +11 -0
  38. package/dist/collection/collection.d.ts +111 -0
  39. package/dist/collection/collection.d.ts.map +1 -0
  40. package/dist/collection/collection.types.d.ts +316 -0
  41. package/dist/collection/collection.types.d.ts.map +1 -0
  42. package/dist/collection/resource.types.d.ts +77 -0
  43. package/dist/collection/resource.types.d.ts.map +1 -0
  44. package/dist/db/collection.runtime.d.ts +98 -0
  45. package/dist/db/collection.runtime.d.ts.map +1 -0
  46. package/dist/db/db.d.ts +154 -0
  47. package/dist/db/db.d.ts.map +1 -0
  48. package/dist/db/db.runtime.d.ts +114 -0
  49. package/dist/db/db.runtime.d.ts.map +1 -0
  50. package/dist/db/db.types.d.ts +162 -0
  51. package/dist/db/db.types.d.ts.map +1 -0
  52. package/dist/graphql/connection.d.ts +25 -0
  53. package/dist/graphql/connection.d.ts.map +1 -0
  54. package/dist/index.d.ts +17 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.mjs +4220 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/mutation/mutation.d.ts +136 -0
  59. package/dist/mutation/mutation.d.ts.map +1 -0
  60. package/dist/mutation/mutation.errors.d.ts +6 -0
  61. package/dist/mutation/mutation.errors.d.ts.map +1 -0
  62. package/dist/mutation/mutation.utils.d.ts +35 -0
  63. package/dist/mutation/mutation.utils.d.ts.map +1 -0
  64. package/dist/operators/operators.d.ts +33 -0
  65. package/dist/operators/operators.d.ts.map +1 -0
  66. package/dist/operators/operators.types.d.ts +68 -0
  67. package/dist/operators/operators.types.d.ts.map +1 -0
  68. package/dist/operators/operators.utils.d.ts +19 -0
  69. package/dist/operators/operators.utils.d.ts.map +1 -0
  70. package/dist/persistence/persistence.d.ts +42 -0
  71. package/dist/persistence/persistence.d.ts.map +1 -0
  72. package/dist/persistence/serializer.d.ts +23 -0
  73. package/dist/persistence/serializer.d.ts.map +1 -0
  74. package/dist/persistence/snapshot.d.ts +29 -0
  75. package/dist/persistence/snapshot.d.ts.map +1 -0
  76. package/dist/persistence/tabs.d.ts +53 -0
  77. package/dist/persistence/tabs.d.ts.map +1 -0
  78. package/dist/query/infinite-query.d.ts +59 -0
  79. package/dist/query/infinite-query.d.ts.map +1 -0
  80. package/dist/query/live-query.d.ts +85 -0
  81. package/dist/query/live-query.d.ts.map +1 -0
  82. package/dist/query/planner.d.ts +57 -0
  83. package/dist/query/planner.d.ts.map +1 -0
  84. package/dist/query/query.d.ts +155 -0
  85. package/dist/query/query.d.ts.map +1 -0
  86. package/dist/query/query.types.d.ts +71 -0
  87. package/dist/query/query.types.d.ts.map +1 -0
  88. package/dist/schema/schema.types.d.ts +33 -0
  89. package/dist/schema/schema.types.d.ts.map +1 -0
  90. package/dist/store/store.d.ts +76 -0
  91. package/dist/store/store.d.ts.map +1 -0
  92. package/dist/store/store.types.d.ts +27 -0
  93. package/dist/store/store.types.d.ts.map +1 -0
  94. package/dist/subset/base-subset.d.ts +66 -0
  95. package/dist/subset/base-subset.d.ts.map +1 -0
  96. package/dist/subset/key-subset.d.ts +23 -0
  97. package/dist/subset/key-subset.d.ts.map +1 -0
  98. package/dist/subset/list-subset.d.ts +63 -0
  99. package/dist/subset/list-subset.d.ts.map +1 -0
  100. package/dist/sync/sync.d.ts +42 -0
  101. package/dist/sync/sync.d.ts.map +1 -0
  102. package/dist/utils/request.utils.d.ts +11 -0
  103. package/dist/utils/request.utils.d.ts.map +1 -0
  104. package/package.json +71 -4
  105. package/project.json +4 -0
  106. package/scripts/docs-typescript.mjs +24 -0
  107. package/scripts/type-budget.mjs +37 -0
  108. package/src/collection/collection.ts +330 -0
  109. package/src/collection/collection.types.ts +383 -0
  110. package/src/collection/resource.types.ts +114 -0
  111. package/src/db/collection.runtime.ts +572 -0
  112. package/src/db/db.runtime.ts +537 -0
  113. package/src/db/db.ts +451 -0
  114. package/src/db/db.types.ts +157 -0
  115. package/src/graphql/connection.ts +23 -0
  116. package/src/index.ts +16 -0
  117. package/src/mutation/mutation.errors.ts +7 -0
  118. package/src/mutation/mutation.ts +776 -0
  119. package/src/mutation/mutation.utils.ts +58 -0
  120. package/src/operators/operators.ts +90 -0
  121. package/src/operators/operators.types.ts +67 -0
  122. package/src/operators/operators.utils.ts +169 -0
  123. package/src/persistence/persistence.ts +168 -0
  124. package/src/persistence/serializer.ts +123 -0
  125. package/src/persistence/snapshot.ts +76 -0
  126. package/src/persistence/tabs.ts +86 -0
  127. package/src/query/infinite-query.ts +206 -0
  128. package/src/query/live-query.ts +552 -0
  129. package/src/query/planner.ts +199 -0
  130. package/src/query/query.ts +319 -0
  131. package/src/query/query.types.ts +90 -0
  132. package/src/schema/schema.types.ts +29 -0
  133. package/src/store/store.ts +300 -0
  134. package/src/store/store.types.ts +17 -0
  135. package/src/subset/base-subset.ts +169 -0
  136. package/src/subset/key-subset.ts +44 -0
  137. package/src/subset/list-subset.ts +328 -0
  138. package/src/sync/sync.ts +99 -0
  139. package/src/utils/request.utils.ts +67 -0
  140. package/tsconfig.json +12 -0
  141. package/vite.config.ts +71 -0
package/src/db/db.ts ADDED
@@ -0,0 +1,451 @@
1
+ import type { CollectionInstance } from "../collection/collection";
2
+ import type {
3
+ KeyFieldOf,
4
+ LoaderDescriptor,
5
+ MutationDescriptor,
6
+ RowKey,
7
+ SortDirection,
8
+ } from "../collection/collection.types";
9
+ import type { Transaction } from "../mutation/mutation";
10
+ import { createTransaction } from "../mutation/mutation";
11
+ import type {
12
+ Condition,
13
+ ExtractConditionEq,
14
+ ExtractConditionTokens,
15
+ FieldRef,
16
+ RowRefs,
17
+ } from "../operators/operators.types";
18
+ import { Query } from "../query/query";
19
+ import type { JoinSpec, JoinTarget, JoinedMatchOf } from "../query/query";
20
+ import type { Row as StoreRow } from "../store/store.types";
21
+ import { createId } from "../utils/request.utils";
22
+ import type { CollectionRuntime } from "./collection.runtime";
23
+ import { DbRuntime } from "./db.runtime";
24
+ import type {
25
+ DbErrorEvent,
26
+ DbInspection,
27
+ DbOptions,
28
+ DehydratedDb,
29
+ MutationOperation,
30
+ TransactionConfig,
31
+ } from "./db.types";
32
+
33
+ export type WriteOptions = {
34
+ /** Writes this one is built on. When one of them is rejected, this write is dropped too. */
35
+ dependsOn?: readonly (Transaction | string)[];
36
+ };
37
+
38
+ type InsertMethod<Mutations> = Mutations extends { insert: infer Input }
39
+ ? (row: Input, options?: WriteOptions) => Transaction
40
+ : never;
41
+
42
+ type UpdateMethod<Key, Mutations> = Mutations extends { update: infer Changes }
43
+ ? (key: Key, changes: Changes, options?: WriteOptions) => Transaction
44
+ : never;
45
+
46
+ type DeleteMethod<Key, Mutations> = Mutations extends { delete: true }
47
+ ? (key: Key, options?: WriteOptions) => Transaction
48
+ : never;
49
+
50
+ const TEMPORARY_KEY_PREFIX = "tmp:";
51
+
52
+ /** A collection inside a db: queries start here, and writes go through it */
53
+ export class CollectionHandle<
54
+ Row,
55
+ Input,
56
+ KeyField extends KeyFieldOf<Row>,
57
+ Loaders extends LoaderDescriptor,
58
+ Mutations extends MutationDescriptor,
59
+ > {
60
+ /** Type-only carrier of the handle's generics, never set at runtime */
61
+ declare readonly __types?: { row: Row; input: Input; key: KeyField; loaders: Loaders; mutations: Mutations };
62
+
63
+ /** The collection's name in `createDb` */
64
+ readonly collectionName: string;
65
+
66
+ /** Adds an optimistic insert and sends it. A row without a key gets a temporary one until the server assigns it. */
67
+ readonly insert: InsertMethod<Mutations>;
68
+ /** Adds an optimistic update and sends it */
69
+ readonly update: UpdateMethod<NonNullable<Row[KeyField]>, Mutations>;
70
+ /** Adds an optimistic delete and sends it */
71
+ readonly delete: DeleteMethod<NonNullable<Row[KeyField]>, Mutations>;
72
+
73
+ constructor(
74
+ private readonly runtime: DbRuntime,
75
+ private readonly name: string,
76
+ ) {
77
+ this.collectionName = name;
78
+ this.insert = ((row: StoreRow, options?: WriteOptions) =>
79
+ this.write({ op: "insert", key: undefined, input: row, options })) as never;
80
+ this.update = ((key: RowKey, changes: StoreRow, options?: WriteOptions) =>
81
+ this.write({ op: "update", key, input: changes, options })) as never;
82
+ this.delete = ((key: RowKey, options?: WriteOptions) =>
83
+ this.write({ op: "delete", key, input: {}, options })) as never;
84
+ }
85
+
86
+ where<C extends Condition<string, string>>(callback: (row: RowRefs<Row>) => C) {
87
+ return this.start().where(callback) as Query<Row, Loaders, Row, ExtractConditionTokens<C>, ExtractConditionEq<C>>;
88
+ }
89
+
90
+ orderBy<Name extends keyof Row & string>(
91
+ callback: (row: RowRefs<Row>) => FieldRef<Name, Row[Name]>,
92
+ direction?: SortDirection,
93
+ ) {
94
+ return this.start().orderBy(callback, direction);
95
+ }
96
+
97
+ select<Selection extends Record<string, FieldRef<string, unknown>>>(callback: (row: RowRefs<Row>) => Selection) {
98
+ return this.start().select(callback);
99
+ }
100
+
101
+ limit(limit: number) {
102
+ return this.start().limit(limit);
103
+ }
104
+
105
+ /** Adds the row of another collection whose key is the given field. See `Query.join`. */
106
+ join<Name extends string, Target extends JoinTarget, Field extends keyof Row & string, const On, const Type>(
107
+ name: Name,
108
+ collection: Target,
109
+ by: JoinSpec<Row, Field, JoinedMatchOf<Target, On>, On, Type>,
110
+ ) {
111
+ return this.start().join(name, collection, by);
112
+ }
113
+
114
+ /** Reads only the rows the db holds and never sends a request */
115
+ local() {
116
+ return this.start().local();
117
+ }
118
+
119
+ /** Reads one row by key */
120
+ findOne(key: NonNullable<Row[KeyField]>): Query<Row, Loaders, Row, never, never, never, "one"> {
121
+ return new Query(this.runtime, { collection: this.name, orderBy: [], local: false, one: { key: key as RowKey } });
122
+ }
123
+
124
+ /** The key to render a row with. It stays the same when a temporary key is swapped for the server's. */
125
+ renderKey(key: NonNullable<Row[KeyField]>): string {
126
+ return this.getRuntime().getRenderKey(key as RowKey);
127
+ }
128
+
129
+ private start() {
130
+ return new Query<Row, Loaders, Row>(this.runtime, { collection: this.name, orderBy: [], local: false });
131
+ }
132
+
133
+ private getRuntime() {
134
+ return this.runtime.collections.get(this.name)!;
135
+ }
136
+
137
+ private write({
138
+ op,
139
+ key: givenKey,
140
+ input,
141
+ options,
142
+ }: {
143
+ op: MutationOperation;
144
+ key: RowKey | undefined;
145
+ input: StoreRow;
146
+ options: WriteOptions | undefined;
147
+ }) {
148
+ const collection = this.getRuntime();
149
+ const { mutations } = this.runtime;
150
+ // A temporary key the server replaced still names the row, so writes made with it reach the server's key
151
+ const key = givenKey === undefined ? undefined : collection.resolveKey(givenKey);
152
+ const dependsOn = (options?.dependsOn ?? []).map((item) => (typeof item === "string" ? item : item.id));
153
+ const { key: keyField } = collection.config;
154
+
155
+ const id = createId();
156
+ const submit = (values: StoreRow) => {
157
+ if (op !== "insert") {
158
+ return mutations.submit({ collection, op, key: key!, values, dependsOn, id });
159
+ }
160
+ const rowKey = values[keyField] as RowKey | undefined;
161
+ if (rowKey !== undefined && rowKey !== null) {
162
+ return mutations.submit({ collection, op, key: rowKey, values, dependsOn, id });
163
+ }
164
+ const insertRequest = collection.config.mutations.insert?.request;
165
+ if (mutations.usesOutbox && insertRequest && !insertRequest.client.appManager.isOnline) {
166
+ return mutations.reject(new Error("An insert that leaves the key to the server cannot be made offline"), id);
167
+ }
168
+ const temporaryKey = `${TEMPORARY_KEY_PREFIX}${id}`;
169
+ return mutations.submit({
170
+ collection,
171
+ op,
172
+ key: temporaryKey,
173
+ values: { ...values, [keyField]: temporaryKey },
174
+ dependsOn,
175
+ id,
176
+ temporaryKey: true,
177
+ });
178
+ };
179
+
180
+ const mistake = findWriteMistake({ collection, op, key, input });
181
+ if (mistake) {
182
+ this.runtime.emitError({ type: "mutation", error: mistake, collection: this.name });
183
+ return mutations.reject(mistake, id);
184
+ }
185
+ const prepared = prepareWrite({ collection, op, key, input });
186
+ const finish = (result: PreparedValues) => {
187
+ if ("issues" in result) {
188
+ this.runtime.emitError({ type: "validation", error: result.issues, collection: this.name });
189
+ return mutations.reject(result.issues, id);
190
+ }
191
+ return submit(result.values);
192
+ };
193
+ if (prepared instanceof Promise) {
194
+ return createTransaction(id, prepared.then(finish));
195
+ }
196
+ return finish(prepared);
197
+ }
198
+ }
199
+
200
+ type PreparedValues = { values: StoreRow } | { issues: unknown };
201
+
202
+ /** A write that cannot be right whatever the server says: an insert of a key the db holds, or an update of the key */
203
+ const findWriteMistake = ({
204
+ collection,
205
+ op,
206
+ key,
207
+ input,
208
+ }: {
209
+ collection: CollectionRuntime;
210
+ op: MutationOperation;
211
+ key: RowKey | undefined;
212
+ input: StoreRow;
213
+ }): Error | undefined => {
214
+ const keyField = collection.config.key;
215
+ const insertedKey = input[keyField] as RowKey | undefined;
216
+ if (op === "insert" && insertedKey !== undefined && collection.store.get(insertedKey)) {
217
+ return new Error(`"${collection.name}" already holds a row with the key ${String(insertedKey)}`);
218
+ }
219
+ if (op === "update" && keyField in input && input[keyField] !== key) {
220
+ return new Error(`An update cannot change the key of a row in "${collection.name}"`);
221
+ }
222
+ return undefined;
223
+ };
224
+
225
+ /**
226
+ * Validates a write against the collection's schema. An insert is validated as a row; an update is validated merged
227
+ * with the current row, and only its changed fields are kept. A delete, a collection without a schema, and an update of
228
+ * a row the db does not hold pass as they are.
229
+ */
230
+ const prepareWrite = ({
231
+ collection,
232
+ op,
233
+ key,
234
+ input,
235
+ }: {
236
+ collection: CollectionRuntime;
237
+ op: MutationOperation;
238
+ key: RowKey | undefined;
239
+ input: StoreRow;
240
+ }): PreparedValues | Promise<PreparedValues> => {
241
+ const { schema } = collection.config;
242
+ const current = op === "update" ? collection.store.get(key!) : undefined;
243
+ // An update that carries `undefined` for a field leaves that field as it is; `null` clears it
244
+ const defined =
245
+ op === "update" ? Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)) : input;
246
+ if (!schema || op === "delete" || (op === "update" && !current)) {
247
+ return { values: defined };
248
+ }
249
+ const candidate = op === "update" ? { ...current, ...defined } : input;
250
+ const finish = (result: Awaited<ReturnType<(typeof schema)["~standard"]["validate"]>>): PreparedValues => {
251
+ if (result.issues) {
252
+ return { issues: result.issues };
253
+ }
254
+ const output = result.value as StoreRow;
255
+ return {
256
+ values:
257
+ op === "insert" ? output : Object.fromEntries(Object.keys(defined).map((field) => [field, output[field]])),
258
+ };
259
+ };
260
+ const validation = schema["~standard"].validate(candidate);
261
+ return validation instanceof Promise ? validation.then(finish) : finish(validation);
262
+ };
263
+
264
+ type HandleOf<C> = C extends {
265
+ __types?: {
266
+ row: infer Row;
267
+ input: infer Input;
268
+ key: infer KeyField;
269
+ loaders: infer Loaders;
270
+ mutations: infer Mutations;
271
+ };
272
+ }
273
+ ? [KeyField, Loaders, Mutations] extends [KeyFieldOf<Row>, LoaderDescriptor, MutationDescriptor]
274
+ ? CollectionHandle<
275
+ Row,
276
+ Input,
277
+ KeyField & KeyFieldOf<Row>,
278
+ Loaders & LoaderDescriptor,
279
+ Mutations & MutationDescriptor
280
+ >
281
+ : never
282
+ : never;
283
+
284
+ /** The writes a transaction can make to one collection. Named transactions can write any collection. */
285
+ type TransactionHandleOf<C, Named extends boolean> = C extends {
286
+ __types?: { row: infer Row; input: infer Input; key: infer KeyField; mutations: infer Mutations };
287
+ }
288
+ ? KeyField extends keyof Row
289
+ ? Named extends true
290
+ ? {
291
+ /** Needs its key, because one request cannot tell which key the server gave which row */
292
+ insert: (row: Input & { [Field in KeyField]: NonNullable<Row[KeyField]> }) => void;
293
+ update: (key: NonNullable<Row[KeyField]>, changes: Partial<Row>) => void;
294
+ delete: (key: NonNullable<Row[KeyField]>) => void;
295
+ }
296
+ : {
297
+ insert: Mutations extends { insert: infer Inserted }
298
+ ? (row: Inserted & { [Field in KeyField]: NonNullable<Row[KeyField]> }) => void
299
+ : never;
300
+ update: Mutations extends { update: infer Changes }
301
+ ? (key: NonNullable<Row[KeyField]>, changes: Changes) => void
302
+ : never;
303
+ delete: Mutations extends { delete: true } ? (key: NonNullable<Row[KeyField]>) => void : never;
304
+ }
305
+ : never
306
+ : never;
307
+
308
+ /** What a transaction callback receives: one handle per collection, which records writes instead of sending them */
309
+ export type TransactionHandles<Collections, Named extends boolean> = {
310
+ [Name in keyof Collections]: TransactionHandleOf<Collections[Name], Named>;
311
+ };
312
+
313
+ type TransactionMethod<Collections, Transactions> = {
314
+ /**
315
+ * Groups writes into one optimistic layer, kept or dropped as a whole. Each write goes through its collection's
316
+ * `mutate`, in order; when one fails, the writes after it are dropped and the subsets holding rows already written
317
+ * refetch.
318
+ */
319
+ (callback: (tx: TransactionHandles<Collections, false>) => void): Transaction;
320
+ /**
321
+ * Groups writes into one optimistic layer and sends them as one request, through the `mutationFn` of the named
322
+ * transaction in `createDb`. The name is stored in the outbox, so the transaction can be replayed after a restart.
323
+ */
324
+ <Name extends keyof Transactions & string>(
325
+ name: Name,
326
+ callback: (tx: TransactionHandles<Collections, true>) => void,
327
+ ): Transaction;
328
+ };
329
+
330
+ type ReservedName = "clear" | "destroy" | "ready" | "onError" | "transaction" | "dehydrate" | "inspect" | "onChange";
331
+
332
+ export type DbMethods = {
333
+ /** Resolves once persisted rows and the outbox are restored */
334
+ ready: Promise<void>;
335
+ /** Removes every row, loaded subset and pending write, and the persisted data of the scope, for example on sign-out */
336
+ clear: () => Promise<void>;
337
+ /** Stops every sync, timer and tab channel */
338
+ destroy: () => void;
339
+ /** Listens to failed writes, rejected validation, outbox and persistence errors */
340
+ onError: (listener: (event: DbErrorEvent) => void) => () => void;
341
+ /**
342
+ * The server rows and loaded subsets, as type-tagged JSON, for server rendering. Optimistic layers, the outbox and
343
+ * syncs are never included. Pass it to `createDb(collections, { state })` on the client.
344
+ */
345
+ dehydrate: () => DehydratedDb;
346
+ /** What the db holds right now: collections with their layers and subsets, live queries and the outbox */
347
+ inspect: () => DbInspection;
348
+ /** Listens to every change the db makes, once per batch of writes, load or outbox change */
349
+ onChange: (listener: () => void) => () => void;
350
+ };
351
+
352
+ export type Db<Collections extends Record<string, CollectionInstance>, Transactions = unknown> = {
353
+ [Name in keyof Collections]: HandleOf<Collections[Name]>;
354
+ } & DbMethods & { transaction: TransactionMethod<Collections, Transactions> };
355
+
356
+ type TransactionCallback = (tx: Record<string, Record<MutationOperation, (...args: never[]) => void>>) => void;
357
+
358
+ type RecordedWrite = { collection: string; op: MutationOperation; key: RowKey | undefined; input: StoreRow };
359
+
360
+ /** Records the writes a transaction callback makes, validates them, and submits them together */
361
+ const runTransaction = (runtime: DbRuntime, name: string | undefined, callback: TransactionCallback): Transaction => {
362
+ const id = createId();
363
+ const recorded: RecordedWrite[] = [];
364
+ const tx = Object.fromEntries(
365
+ [...runtime.collections.keys()].map((collection) => [
366
+ collection,
367
+ {
368
+ insert: (row: StoreRow) => recorded.push({ collection, op: "insert", key: undefined, input: row }),
369
+ update: (key: RowKey, changes: StoreRow) => recorded.push({ collection, op: "update", key, input: changes }),
370
+ delete: (key: RowKey) => recorded.push({ collection, op: "delete", key, input: {} }),
371
+ },
372
+ ]),
373
+ );
374
+ callback(tx as never);
375
+
376
+ const fail = (error: unknown) => runtime.mutations.reject(error, id);
377
+ const writes = recorded.map((write) => {
378
+ const collection = runtime.collections.get(write.collection)!;
379
+ const key = write.op === "insert" ? (write.input[collection.config.key] as RowKey | undefined) : write.key;
380
+ return {
381
+ collection,
382
+ op: write.op,
383
+ key,
384
+ prepared: prepareWrite({ collection, op: write.op, key, input: write.input }),
385
+ };
386
+ });
387
+ if (writes.some((write) => write.key === undefined || write.key === null)) {
388
+ return fail(new Error("An insert in a transaction needs its key, such as a UUID generated on the client"));
389
+ }
390
+ const submit = (results: PreparedValues[]) => {
391
+ const invalid = results.find((result): result is { issues: unknown } => "issues" in result);
392
+ if (invalid) {
393
+ runtime.emitError({ type: "validation", error: invalid.issues });
394
+ return fail(invalid.issues);
395
+ }
396
+ return runtime.mutations.submitTransaction({
397
+ id,
398
+ name,
399
+ writes: writes.map((write, index) => ({
400
+ collection: write.collection,
401
+ op: write.op,
402
+ key: write.key!,
403
+ values: (results[index] as { values: StoreRow }).values,
404
+ })),
405
+ });
406
+ };
407
+ const prepared = writes.map((write) => write.prepared);
408
+ if (prepared.some((item) => item instanceof Promise)) {
409
+ return createTransaction(id, Promise.all(prepared).then(submit));
410
+ }
411
+ return submit(prepared as PreparedValues[]);
412
+ };
413
+
414
+ /**
415
+ * Creates the db that queries and writes go through. The names given to it are the names on the db, as in `db.post`.
416
+ * Requests carry their Client and listeners carry their Socket, so it needs neither.
417
+ *
418
+ * @example
419
+ * const db = createDb({ post: Post, user: User });
420
+ */
421
+ export const createDb = <Collections extends Record<string, CollectionInstance>, Transactions>(
422
+ collections: Collections & { [Name in Extract<keyof Collections, ReservedName>]: never },
423
+ options?: DbOptions & {
424
+ /**
425
+ * Collections that hold the same records in different shapes, such as `["post", "postSummary"]`. A write, delete
426
+ * or optimistic change to one changes the fields the other has, for the same key.
427
+ */
428
+ links?: readonly (readonly [keyof Collections & string, keyof Collections & string])[];
429
+ /** Named transactions: each sends the writes of `db.transaction(name, ...)` as one request */
430
+ transactions?: Transactions & Record<string, TransactionConfig>;
431
+ },
432
+ ): Db<Collections, Transactions> => {
433
+ const runtime = new DbRuntime(collections, options);
434
+ const methods: DbMethods = {
435
+ ready: runtime.ready,
436
+ clear: runtime.clear,
437
+ destroy: runtime.destroy,
438
+ onError: runtime.onError,
439
+ dehydrate: runtime.dehydrate,
440
+ inspect: runtime.inspect,
441
+ onChange: runtime.onChange,
442
+ };
443
+ const handles = Object.fromEntries(
444
+ Object.keys(collections).map((name) => [name, new CollectionHandle(runtime, name)]),
445
+ );
446
+ const transaction = (first: string | TransactionCallback, second?: TransactionCallback) => {
447
+ const [name, callback] = typeof first === "string" ? [first, second!] : [undefined, first];
448
+ return runTransaction(runtime, name, callback);
449
+ };
450
+ return { ...handles, ...methods, transaction } as Db<Collections, Transactions>;
451
+ };
@@ -0,0 +1,157 @@
1
+ import type { RequestInstance, ResponseType } from "@hyper-fetch/core";
2
+
3
+ import type { Notation, RowKey } from "../collection/collection.types";
4
+ import type { DbCodec } from "../persistence/serializer";
5
+ import type { QueryExplanation } from "../query/query.types";
6
+
7
+ /** The db-wide notation that loaders use for operators and orders they declare with `true` */
8
+ export type DbNotation = Notation;
9
+
10
+ /** Storage for persisted rows and the outbox, such as `localStorage` or an async key-value store */
11
+ export type DbStorage = {
12
+ getItem: (key: string) => string | null | Promise<string | null>;
13
+ setItem: (key: string, value: string) => unknown;
14
+ removeItem: (key: string) => unknown;
15
+ };
16
+
17
+ /** The part of the Web Locks API the db uses to elect the tab that replays the outbox */
18
+ export type DbLockManager = {
19
+ request: (name: string, callback: () => Promise<unknown>) => Promise<unknown>;
20
+ };
21
+
22
+ /** The part of `BroadcastChannel` the db uses to talk to other tabs */
23
+ export type DbChannel = {
24
+ postMessage: (message: unknown) => void;
25
+ addEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
26
+ removeEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
27
+ close: () => void;
28
+ };
29
+
30
+ export type DbPersistenceOptions = {
31
+ storage: DbStorage;
32
+ /** Keeps one user's or tenant's data apart from another's, such as the user id */
33
+ scope?: string;
34
+ /** Persisted rows of another version are cleared. The outbox is kept, because it holds the only copy of writes. */
35
+ version?: string | number;
36
+ /** How long a query whose restore found no rows waits for the network before it shows an empty result */
37
+ networkTimeout?: number;
38
+ };
39
+
40
+ export type DbOfflineOptions = {
41
+ /**
42
+ * Whether a failed replay is temporary and retried, or permanent and dropped. By default a 4xx response other than
43
+ * 408 and 429 is permanent.
44
+ */
45
+ retryable?: (response: ResponseType<unknown, unknown, any>) => boolean;
46
+ /** Delay before retrying a temporary failure */
47
+ retryDelay?: (attempt: number) => number;
48
+ };
49
+
50
+ /** What the db holds right now, for devtools such as HyperFlow */
51
+ export type DbInspection = {
52
+ collections: {
53
+ name: string;
54
+ /** Rows with their optimistic layers applied */
55
+ rows: number;
56
+ layers: { id: string; key: RowKey; type: MutationOperation }[];
57
+ subsets: {
58
+ id: string;
59
+ kind: "list" | "key";
60
+ /** Index of the loader in the collection's chain */
61
+ loader: number;
62
+ rows: number;
63
+ fresh: boolean;
64
+ live: boolean;
65
+ loading: boolean;
66
+ error: unknown;
67
+ loadedAt: number;
68
+ /** Queries reading the subset */
69
+ observers: number;
70
+ }[];
71
+ }[];
72
+ queries: {
73
+ key: string;
74
+ collection: string;
75
+ subscribers: number;
76
+ status: "loading" | "ready" | "error";
77
+ rows: number | undefined;
78
+ plan: QueryExplanation;
79
+ }[];
80
+ outbox: TransactionRecord[];
81
+ };
82
+
83
+ /** What `db.dehydrate()` returns: the server rows and loaded subsets, as type-tagged JSON */
84
+ export type DehydratedDb = { readonly __dehydrated: true; readonly collections: unknown };
85
+
86
+ export type DbOptions = DbNotation & {
87
+ /**
88
+ * Value types to persist and dehydrate beyond `Date`, `bigint`, `Map`, `Set`, `undefined`, `NaN` and the
89
+ * infinities, which the db stores as type-tagged JSON on its own
90
+ */
91
+ codecs?: readonly DbCodec[];
92
+ /** Rows and loaded subsets a server rendered with, from `db.dehydrate()`. They show at once and refetch when used. */
93
+ state?: DehydratedDb;
94
+ /** How long a loaded subset no query uses is kept. Defaults to five minutes, like the core `cacheTime`. */
95
+ gcTime?: number;
96
+ /** How long a write with `onSuccess: "sync"` waits for a sync event before it refetches */
97
+ syncTimeout?: number;
98
+ /** Persists rows, loaded subsets and the outbox */
99
+ persistence?: DbPersistenceOptions;
100
+ /** Sends every write through the outbox, so writes made offline are replayed when the connection returns */
101
+ offline?: boolean | DbOfflineOptions;
102
+ /** How tabs agree on which one replays the outbox. Defaults to Web Locks and `BroadcastChannel`. */
103
+ tabs?: false | { locks?: DbLockManager; channel?: DbChannel };
104
+ };
105
+
106
+ export type MutationOperation = "insert" | "update" | "delete";
107
+
108
+ /** One write of a transaction, as a transaction's `mutationFn` receives it and the outbox keeps it */
109
+ export type TransactionWrite = {
110
+ collection: string;
111
+ op: MutationOperation;
112
+ key: RowKey;
113
+ /** The complete row of an insert, or the changed fields of an update. Empty for a delete. */
114
+ values: Record<string, unknown>;
115
+ };
116
+
117
+ /** A named transaction declared in `createDb`: one request sends all of its writes */
118
+ export type TransactionConfig = {
119
+ /** Returns the request that sends the writes. The transaction id is an idempotency key. */
120
+ mutationFn: (context: { id: string; mutations: TransactionWrite[] }) => RequestInstance;
121
+ /**
122
+ * What happens to the changes once the request succeeds: `keep` makes them the server state, which is the default,
123
+ * and `refetch` reloads the loaded subsets that hold the changed rows
124
+ */
125
+ onSuccess?: "keep" | "refetch";
126
+ };
127
+
128
+ /** A write as the outbox keeps it */
129
+ export type TransactionRecord = {
130
+ id: string;
131
+ collection: string;
132
+ op: MutationOperation;
133
+ key: RowKey;
134
+ values: Record<string, unknown>;
135
+ dependsOn: string[];
136
+ /** Set before the request goes out, so a restart sends it again with the same id */
137
+ sent: boolean;
138
+ /** The key is temporary until the server assigns one, so it is not sent */
139
+ temporaryKey?: boolean;
140
+ createdAt: number;
141
+ /** A named transaction: its writes go out through the transaction's `mutationFn`, as one request */
142
+ transaction?: { name: string; writes: TransactionWrite[] };
143
+ };
144
+
145
+ /** What a write resolves with. Like `send()`, a write never rejects. */
146
+ export type MutationResult = {
147
+ success: boolean;
148
+ data: unknown;
149
+ error: unknown;
150
+ };
151
+
152
+ export type DbErrorEvent = {
153
+ type: "mutation" | "outbox" | "validation" | "persistence" | "load" | "sync" | "subscriber";
154
+ error: unknown;
155
+ collection?: string;
156
+ transaction?: TransactionRecord;
157
+ };
@@ -0,0 +1,23 @@
1
+ /** A Relay connection, the shape many GraphQL APIs use for paginated lists */
2
+ export type RelayConnection<Node> = {
3
+ edges?: readonly ({ node: Node } | null)[] | null;
4
+ pageInfo: { hasNextPage: boolean; endCursor?: string | null };
5
+ };
6
+
7
+ /**
8
+ * Reads the rows and the next cursor of a Relay connection (`edges` / `node`), for a paginated GraphQL loader. Spread it
9
+ * into the loader options and add `page` to send the cursor.
10
+ *
11
+ * @example
12
+ * collection(PostSchema, { key: "id" }).load(getPosts, {
13
+ * ...relayConnection((response: PostsResponse) => response.posts),
14
+ * page: (after) => ({ payload: { after } }),
15
+ * });
16
+ */
17
+ export const relayConnection = <Response, Node>(select: (response: Response) => RelayConnection<Node>) => ({
18
+ rows: (response: Response): Node[] => (select(response).edges ?? []).flatMap((edge) => (edge ? [edge.node] : [])),
19
+ cursor: (response: Response): string | null => {
20
+ const { pageInfo } = select(response);
21
+ return pageInfo.hasNextPage ? (pageInfo.endCursor ?? null) : null;
22
+ },
23
+ });
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ export * from "./collection/collection";
2
+ export * from "./collection/collection.types";
3
+ export * from "./collection/resource.types";
4
+ export * from "./db/db";
5
+ export * from "./db/db.types";
6
+ export * from "./graphql/connection";
7
+ export * from "./mutation/mutation";
8
+ export * from "./mutation/mutation.errors";
9
+ export * from "./operators/operators";
10
+ export * from "./operators/operators.types";
11
+ export * from "./query/infinite-query";
12
+ export * from "./query/query";
13
+ export * from "./persistence/serializer";
14
+ export type { CollectionSnapshot, SubsetSnapshot } from "./persistence/snapshot";
15
+ export * from "./query/query.types";
16
+ export * from "./schema/schema.types";
@@ -0,0 +1,7 @@
1
+ /** Why a write was dropped: an earlier write it was built on failed */
2
+ export class DependencyError extends Error {
3
+ constructor(readonly transactionId: string) {
4
+ super(`An earlier write this one depends on (${transactionId}) failed`);
5
+ this.name = "DependencyError";
6
+ }
7
+ }