@hyper-fetch/db 0.0.0-stage → 1.0.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
@@ -0,0 +1,58 @@
1
+ import type { ClientInstance, ResponseType } from "@hyper-fetch/core";
2
+
3
+ import type { RowKey } from "../collection/collection.types";
4
+ import type { CollectionRuntime } from "../db/collection.runtime";
5
+ import type { MutationOperation, MutationResult, TransactionRecord } from "../db/db.types";
6
+ import type { Row } from "../store/store.types";
7
+
8
+ export type AnyResponse = ResponseType<unknown, unknown, any>;
9
+
10
+ /**
11
+ * A pending write: a promise of the write's result that never rejects, with the write's `id`. The `id`, or the
12
+ * transaction itself, can be passed to `dependsOn` of a later write, so the later write is dropped when this one is
13
+ * rejected.
14
+ */
15
+ export type Transaction = Promise<MutationResult> & { readonly id: string };
16
+
17
+ export const createTransaction = (id: string, result: Promise<MutationResult>): Transaction => {
18
+ return Object.assign(result, { id });
19
+ };
20
+
21
+ /** By default a 4xx response other than 408 and 429 is permanent, and everything else is retried */
22
+ export const isTemporaryFailure = (response: AnyResponse) => {
23
+ const status = Number(response.status);
24
+ if (!status) {
25
+ return true;
26
+ }
27
+ return status >= 500 || status === 408 || status === 429;
28
+ };
29
+
30
+ /** A write of a transaction, validated and ready to apply */
31
+ export type PreparedWrite = { collection: CollectionRuntime; op: MutationOperation; key: RowKey; values: Row };
32
+
33
+ /** The rows a record writes, as `collection:key` */
34
+ export const rowsOf = (record: TransactionRecord) => {
35
+ const writes = record.transaction?.writes ?? [record];
36
+ return writes.map((write) => `${write.collection}:${String(write.key)}`);
37
+ };
38
+
39
+ /** One result for several writes: the first failure, or every write's data */
40
+ export const combineResults = (results: MutationResult[]): MutationResult => {
41
+ const failed = results.find((result) => !result.success);
42
+ return failed ?? { success: true, data: results.map((result) => result.data), error: null };
43
+ };
44
+
45
+ export const defaultRetryDelay = (attempt: number) => Math.min(1000 * 2 ** (attempt - 1), 30_000);
46
+
47
+ /** Resolves once the client is online again. `cancel` stops listening, for `destroy`. */
48
+ export const waitForOnline = (client: ClientInstance) => {
49
+ let resolve!: () => void;
50
+ const promise = new Promise<void>((done) => {
51
+ resolve = done;
52
+ });
53
+ const cancel = client.appManager.events.onOnline(() => {
54
+ cancel();
55
+ resolve();
56
+ });
57
+ return { promise, cancel };
58
+ };
@@ -0,0 +1,90 @@
1
+ import type {
2
+ ComparableValue,
3
+ Condition,
4
+ ExtractConditionEq,
5
+ ExtractConditionTokens,
6
+ FieldRef,
7
+ LocalToken,
8
+ NoInferValue,
9
+ } from "./operators.types";
10
+
11
+ const comparison = (op: "eq" | "gt" | "gte" | "lt" | "lte" | "inArray", ref: FieldRef, value: unknown) => {
12
+ return { kind: "condition", node: { op, field: ref.field, value } } as const;
13
+ };
14
+
15
+ /** Matches rows whose field equals the value. Dates are equal when they are the same instant. */
16
+ export const eq = <Name extends string, Value>(
17
+ ref: FieldRef<Name, Value>,
18
+ value: NoInferValue<Value>,
19
+ ): Condition<`${Name}:eq`, Name> => comparison("eq", ref, value);
20
+
21
+ /** Matches rows whose field is greater than the value */
22
+ export const gt = <Name extends string, Value extends ComparableValue | null | undefined>(
23
+ ref: FieldRef<Name, Value>,
24
+ value: NoInferValue<NonNullable<Value>>,
25
+ ): Condition<`${Name}:gt`, never> => comparison("gt", ref, value);
26
+
27
+ /** Matches rows whose field is greater than or equal to the value */
28
+ export const gte = <Name extends string, Value extends ComparableValue | null | undefined>(
29
+ ref: FieldRef<Name, Value>,
30
+ value: NoInferValue<NonNullable<Value>>,
31
+ ): Condition<`${Name}:gte`, never> => comparison("gte", ref, value);
32
+
33
+ /** Matches rows whose field is less than the value */
34
+ export const lt = <Name extends string, Value extends ComparableValue | null | undefined>(
35
+ ref: FieldRef<Name, Value>,
36
+ value: NoInferValue<NonNullable<Value>>,
37
+ ): Condition<`${Name}:lt`, never> => comparison("lt", ref, value);
38
+
39
+ /** Matches rows whose field is less than or equal to the value */
40
+ export const lte = <Name extends string, Value extends ComparableValue | null | undefined>(
41
+ ref: FieldRef<Name, Value>,
42
+ value: NoInferValue<NonNullable<Value>>,
43
+ ): Condition<`${Name}:lte`, never> => comparison("lte", ref, value);
44
+
45
+ /** Matches rows whose field equals one of the values */
46
+ export const inArray = <Name extends string, Value>(
47
+ ref: FieldRef<Name, Value>,
48
+ values: readonly NoInferValue<Value>[],
49
+ ): Condition<`${Name}:inArray`, never> => comparison("inArray", ref, values);
50
+
51
+ /**
52
+ * A server-only operator, such as full-text search, which has no meaning on the client. A loader maps it under its
53
+ * name like any operator, as in `title: { search: (text: string) => ({ queryParams: { q: text } }) }`. A query that
54
+ * uses one must send it, or it does not compile. Its subset never answers other queries, and new rows never join it:
55
+ * an insert marks it stale instead.
56
+ *
57
+ * @example
58
+ * db.post.where((post) => op("search", post.title, "tea"));
59
+ */
60
+ export const op = <Operator extends string, Name extends string, Value>(
61
+ name: Operator,
62
+ ref: FieldRef<Name, unknown>,
63
+ value: Value,
64
+ ): Condition<`${Name}:${Operator}`, never> => ({
65
+ kind: "condition",
66
+ node: { op: "server", name, field: ref.field, value },
67
+ });
68
+
69
+ /**
70
+ * Matches rows that match every condition. Top-level `and` is where the db splits a query: the conditions a loader
71
+ * declares are sent to the backend and the rest run on the rows the db holds.
72
+ */
73
+ export const and = <Conditions extends readonly Condition<string, string>[]>(
74
+ ...conditions: Conditions
75
+ ): Condition<ExtractConditionTokens<Conditions[number]>, ExtractConditionEq<Conditions[number]>> => ({
76
+ kind: "condition",
77
+ node: { op: "and", items: conditions.map((condition) => condition.node) },
78
+ });
79
+
80
+ /** Matches rows that match at least one condition. It runs on the rows the db holds. */
81
+ export const or = (...conditions: readonly Condition<string, string>[]): Condition<LocalToken, never> => ({
82
+ kind: "condition",
83
+ node: { op: "or", items: conditions.map((condition) => condition.node) },
84
+ });
85
+
86
+ /** Matches rows that do not match the condition. It runs on the rows the db holds. */
87
+ export const not = (condition: Condition<string, string>): Condition<LocalToken, never> => ({
88
+ kind: "condition",
89
+ node: { op: "not", item: condition.node },
90
+ });
@@ -0,0 +1,67 @@
1
+ /** A comparison operator that loaders can map to their backend's notation */
2
+ export type ComparisonOperator = "eq" | "gt" | "gte" | "lt" | "lte" | "inArray";
3
+
4
+ /** Values that `gt`, `gte`, `lt`, `lte` and `orderBy` compare */
5
+ export type ComparableValue = string | number | bigint | Date;
6
+
7
+ /** A node of a filter expression. Operators build it, loaders translate it and the db evaluates it on rows. */
8
+ export type ExpressionNode =
9
+ | { readonly op: ComparisonOperator; readonly field: string; readonly value: unknown }
10
+ | { readonly op: "and"; readonly items: readonly ExpressionNode[] }
11
+ | { readonly op: "or"; readonly items: readonly ExpressionNode[] }
12
+ | { readonly op: "not"; readonly item: ExpressionNode }
13
+ | ServerNode;
14
+
15
+ /** A comparison node, which the db can evaluate on the rows it holds */
16
+ export type ComparisonNode = Extract<ExpressionNode, { op: ComparisonOperator }>;
17
+
18
+ /** A server-only operator, such as full-text search: the loader must send it, and the client never evaluates it */
19
+ export type ServerNode = {
20
+ readonly op: "server";
21
+ readonly name: string;
22
+ readonly field: string;
23
+ readonly value: unknown;
24
+ };
25
+
26
+ /** A condition a loader can send to its backend */
27
+ export type SendableNode = ComparisonNode | ServerNode;
28
+
29
+ /**
30
+ * A reference to one row field, received by query callbacks such as `where((post) => eq(post.teamId, 1))`.
31
+ * `Value` is the field's type, so operators accept only values of that type.
32
+ */
33
+ export type FieldRef<Name extends string = string, Value = unknown> = {
34
+ readonly kind: "field";
35
+ readonly field: Name;
36
+ /** Type-only marker, never set at runtime */
37
+ readonly __value?: Value;
38
+ };
39
+
40
+ /** The field references a query callback receives, one for every row field */
41
+ export type RowRefs<Row> = { readonly [Key in keyof Row & string]-?: FieldRef<Key, Row[Key]> };
42
+
43
+ /** Marks conditions that never reach a backend, such as `or` and `not` */
44
+ export type LocalToken = "~local";
45
+
46
+ /**
47
+ * A filter condition. `Tokens` lists what it asks a backend for, as `field:operator`, and `Eq` the fields it sets with
48
+ * `eq` at the top level. The types use both to check that a loader can serve the query.
49
+ */
50
+ export type Condition<Tokens extends string = string, Eq extends string = string> = {
51
+ readonly kind: "condition";
52
+ readonly node: ExpressionNode;
53
+ /** Type-only marker, never set at runtime */
54
+ readonly __tokens?: Tokens;
55
+ /** Type-only marker, never set at runtime */
56
+ readonly __eq?: Eq;
57
+ };
58
+
59
+ export type ExtractConditionTokens<C> = C extends Condition<infer Tokens, any> ? Tokens : never;
60
+
61
+ export type ExtractConditionEq<C> = C extends Condition<any, infer Eq> ? Eq : never;
62
+
63
+ /**
64
+ * Keeps a parameter out of type inference, so the field decides the type and the value is checked against it.
65
+ * TypeScript's own `NoInfer` needs 5.4, and the API docs and older consumers compile with earlier versions.
66
+ */
67
+ export type NoInferValue<T> = [T][T extends unknown ? 0 : never];
@@ -0,0 +1,169 @@
1
+ import type { ComparisonNode, ExpressionNode } from "./operators.types";
2
+
3
+ /** Turns a value into the form the db compares: dates become their instant */
4
+ const normalize = (value: unknown): unknown => (value instanceof Date ? value.getTime() : value);
5
+
6
+ /** Compares two strings by Unicode code point, so the order does not depend on the runtime's locale */
7
+ const compareStrings = (left: string, right: string): number => {
8
+ const leftPoints = [...left];
9
+ const rightPoints = [...right];
10
+ const length = Math.min(leftPoints.length, rightPoints.length);
11
+ for (let index = 0; index < length; index += 1) {
12
+ const difference = leftPoints[index].codePointAt(0)! - rightPoints[index].codePointAt(0)!;
13
+ if (difference !== 0) {
14
+ return difference < 0 ? -1 : 1;
15
+ }
16
+ }
17
+ if (leftPoints.length === rightPoints.length) {
18
+ return 0;
19
+ }
20
+ return leftPoints.length < rightPoints.length ? -1 : 1;
21
+ };
22
+
23
+ /** Two values are equal when they are the same value, or dates of the same instant */
24
+ export const isEqualValue = (left: unknown, right: unknown): boolean => {
25
+ return Object.is(normalize(left), normalize(right));
26
+ };
27
+
28
+ /**
29
+ * Orders two values. `null` and `undefined` sort before every other value. Strings compare by code point, dates by
30
+ * instant, and values of different types by their type name, so the order is always total.
31
+ */
32
+ export const compareValues = (left: unknown, right: unknown): number => {
33
+ const a = normalize(left);
34
+ const b = normalize(right);
35
+ const aEmpty = a === null || a === undefined;
36
+ const bEmpty = b === null || b === undefined;
37
+ if (aEmpty || bEmpty) {
38
+ if (aEmpty && bEmpty) {
39
+ return 0;
40
+ }
41
+ return aEmpty ? -1 : 1;
42
+ }
43
+ if (typeof a === "string" && typeof b === "string") {
44
+ return compareStrings(a, b);
45
+ }
46
+ if (typeof a !== typeof b) {
47
+ return compareStrings(typeof a, typeof b);
48
+ }
49
+ if (Object.is(a, b)) {
50
+ return 0;
51
+ }
52
+ // NaN sorts after every number, so the order stays consistent
53
+ if (Number.isNaN(a) || Number.isNaN(b)) {
54
+ return Number.isNaN(a) ? 1 : -1;
55
+ }
56
+ return (a as number) < (b as number) ? -1 : 1;
57
+ };
58
+
59
+ const isEmpty = (value: unknown) => value === null || value === undefined;
60
+
61
+ const evaluateComparison = (node: ComparisonNode, row: Record<string, unknown>): boolean => {
62
+ const value = row[node.field];
63
+ switch (node.op) {
64
+ case "eq": {
65
+ return isEqualValue(value, node.value);
66
+ }
67
+ case "inArray": {
68
+ return (node.value as unknown[]).some((item) => isEqualValue(value, item));
69
+ }
70
+ case "gt": {
71
+ return !isEmpty(value) && compareValues(value, node.value) > 0;
72
+ }
73
+ case "gte": {
74
+ return !isEmpty(value) && compareValues(value, node.value) >= 0;
75
+ }
76
+ case "lt": {
77
+ return !isEmpty(value) && compareValues(value, node.value) < 0;
78
+ }
79
+ default: {
80
+ return !isEmpty(value) && compareValues(value, node.value) <= 0;
81
+ }
82
+ }
83
+ };
84
+
85
+ /** Evaluates a filter expression on one row */
86
+ export const evaluate = (node: ExpressionNode, row: Record<string, unknown>): boolean => {
87
+ switch (node.op) {
88
+ case "and": {
89
+ return node.items.every((item) => evaluate(item, row));
90
+ }
91
+ case "or": {
92
+ return node.items.some((item) => evaluate(item, row));
93
+ }
94
+ case "not": {
95
+ return !evaluate(node.item, row);
96
+ }
97
+ case "server": {
98
+ // Only the server can tell, so the subset that loaded the row decides whether it belongs
99
+ return true;
100
+ }
101
+ default: {
102
+ return evaluateComparison(node, row);
103
+ }
104
+ }
105
+ };
106
+
107
+ /** Splits an expression at its top-level `and`, flattening nested `and` nodes */
108
+ export const splitAnd = (node: ExpressionNode | undefined): ExpressionNode[] => {
109
+ if (!node) {
110
+ return [];
111
+ }
112
+ if (node.op === "and") {
113
+ return node.items.flatMap((item) => splitAnd(item));
114
+ }
115
+ return [node];
116
+ };
117
+
118
+ /** The fields an expression reads */
119
+ export const getExpressionFields = (node: ExpressionNode): string[] => {
120
+ switch (node.op) {
121
+ case "and":
122
+ case "or": {
123
+ return node.items.flatMap((item) => getExpressionFields(item));
124
+ }
125
+ case "not": {
126
+ return getExpressionFields(node.item);
127
+ }
128
+ default: {
129
+ return [node.field];
130
+ }
131
+ }
132
+ };
133
+
134
+ /** A JSON value that identifies a value structurally. Dates keep their instant. */
135
+ export const toStableValue = (value: unknown): unknown => {
136
+ if (value instanceof Date) {
137
+ return { $date: value.getTime() };
138
+ }
139
+ // JSON cannot tell these apart from each other or from null, so two different queries would share a subset
140
+ if (typeof value === "bigint") {
141
+ return { $bigint: value.toString() };
142
+ }
143
+ if (typeof value === "number" && !Number.isFinite(value)) {
144
+ return { $number: String(value) };
145
+ }
146
+ if (value === undefined) {
147
+ return { $undefined: true };
148
+ }
149
+ if (value instanceof Map) {
150
+ return { $map: [...value.entries()].map(([key, item]) => [toStableValue(key), toStableValue(item)]) };
151
+ }
152
+ if (value instanceof Set) {
153
+ return { $set: [...value].map((item) => toStableValue(item)) };
154
+ }
155
+ if (Array.isArray(value)) {
156
+ return value.map((item) => toStableValue(item));
157
+ }
158
+ if (value && typeof value === "object") {
159
+ return Object.fromEntries(
160
+ Object.keys(value)
161
+ .toSorted()
162
+ .map((key) => [key, toStableValue((value as Record<string, unknown>)[key])]),
163
+ );
164
+ }
165
+ return value;
166
+ };
167
+
168
+ /** A string that is equal for structurally equal values */
169
+ export const stableStringify = (value: unknown): string => JSON.stringify(toStableValue(value));
@@ -0,0 +1,168 @@
1
+ import type { CollectionRuntime } from "../db/collection.runtime";
2
+ import type { DbRuntime } from "../db/db.runtime";
3
+ import type { DbPersistenceOptions, DbStorage, TransactionRecord } from "../db/db.types";
4
+ import type { Serializer } from "./serializer";
5
+ import type { CollectionSnapshot } from "./snapshot";
6
+ import { restoreSnapshot, snapshotCollection } from "./snapshot";
7
+
8
+ /** The outbox's own format version. It changes only when the stored shape of a transaction changes. */
9
+ export const OUTBOX_FORMAT = 1;
10
+
11
+ type PersistedCollection = CollectionSnapshot & { version: string | number };
12
+
13
+ type PersistedOutbox = { format: number; entries: TransactionRecord[] };
14
+
15
+ /**
16
+ * Persists server rows, loaded subsets and the outbox under a scope, such as the user id. Rows of another db version
17
+ * are cleared, because the server holds a copy. The outbox is never cleared with them.
18
+ */
19
+ export class Persistence {
20
+ readonly networkTimeout: number;
21
+ private readonly storage: DbStorage;
22
+ private readonly prefix: string;
23
+ private readonly version: string | number;
24
+ private readonly serializer: Serializer;
25
+ /** Set when the stored outbox cannot be read, so it is never written over */
26
+ private outboxLocked = false;
27
+ private scheduled = new Set<CollectionRuntime>();
28
+ private timer: ReturnType<typeof setTimeout> | undefined;
29
+
30
+ constructor(
31
+ private readonly db: DbRuntime,
32
+ options: DbPersistenceOptions,
33
+ serializer: Serializer,
34
+ ) {
35
+ this.storage = options.storage;
36
+ this.prefix = `hf-db:${options.scope ?? "default"}`;
37
+ this.version = options.version ?? 1;
38
+ this.networkTimeout = options.networkTimeout ?? 5000;
39
+ this.serializer = serializer;
40
+ }
41
+
42
+ /** Restores every collection and returns the persisted outbox */
43
+ restore = async (): Promise<TransactionRecord[]> => {
44
+ await Promise.all([...this.db.collections.values()].map((collection) => this.restoreCollection(collection)));
45
+ return this.loadOutbox();
46
+ };
47
+
48
+ /**
49
+ * Reads the outbox. An outbox this version cannot read, corrupt or of another format, is reported and never written
50
+ * over, because it may hold the only copy of writes another version of the app can replay.
51
+ */
52
+ loadOutbox = async (): Promise<TransactionRecord[]> => {
53
+ const key = `${this.prefix}:outbox`;
54
+ let raw: string | null;
55
+ try {
56
+ raw = await this.storage.getItem(key);
57
+ } catch (error) {
58
+ this.db.emitError({ type: "persistence", error });
59
+ return [];
60
+ }
61
+ if (!raw) {
62
+ return [];
63
+ }
64
+ let stored: PersistedOutbox;
65
+ try {
66
+ stored = this.serializer.parse(raw) as PersistedOutbox;
67
+ } catch (error) {
68
+ this.outboxLocked = true;
69
+ this.db.emitError({ type: "persistence", error });
70
+ return [];
71
+ }
72
+ if (stored.format !== OUTBOX_FORMAT) {
73
+ this.outboxLocked = true;
74
+ this.db.emitError({
75
+ type: "outbox",
76
+ error: new Error(`The persisted outbox has format ${stored.format}, which this version cannot replay`),
77
+ });
78
+ return [];
79
+ }
80
+ return stored.entries;
81
+ };
82
+
83
+ saveOutbox = (entries: TransactionRecord[]) => {
84
+ if (this.outboxLocked) {
85
+ return Promise.resolve();
86
+ }
87
+ const value: PersistedOutbox = { format: OUTBOX_FORMAT, entries };
88
+ return this.write(`${this.prefix}:outbox`, value);
89
+ };
90
+
91
+ /** Saves the collections whose rows changed, once the current tick is over */
92
+ scheduleSave = (collections: Iterable<CollectionRuntime>) => {
93
+ if (!this.db.isLeader || !this.db.isReady) {
94
+ return;
95
+ }
96
+ [...collections].forEach((collection) => this.scheduled.add(collection));
97
+ if (this.timer || this.scheduled.size === 0) {
98
+ return;
99
+ }
100
+ this.timer = setTimeout(() => {
101
+ this.timer = undefined;
102
+ const due = [...this.scheduled];
103
+ this.scheduled.clear();
104
+ due.forEach((collection) => this.saveCollection(collection));
105
+ }, 0);
106
+ };
107
+
108
+ saveCollection = (collection: CollectionRuntime) => {
109
+ const value: PersistedCollection = { version: this.version, ...snapshotCollection(collection) };
110
+ return this.write(`${this.prefix}:rows:${collection.name}`, value);
111
+ };
112
+
113
+ /** Removes everything this scope persisted */
114
+ clear = async () => {
115
+ clearTimeout(this.timer);
116
+ this.timer = undefined;
117
+ this.scheduled.clear();
118
+ await Promise.all([
119
+ this.remove(`${this.prefix}:outbox`),
120
+ ...[...this.db.collections.keys()].map((name) => this.remove(`${this.prefix}:rows:${name}`)),
121
+ ]);
122
+ };
123
+
124
+ destroy = () => {
125
+ clearTimeout(this.timer);
126
+ this.timer = undefined;
127
+ };
128
+
129
+ private restoreCollection = async (collection: CollectionRuntime) => {
130
+ const key = `${this.prefix}:rows:${collection.name}`;
131
+ const stored = await this.read<PersistedCollection>(key);
132
+ if (!stored) {
133
+ return;
134
+ }
135
+ if (stored.version !== this.version) {
136
+ await this.remove(key);
137
+ return;
138
+ }
139
+ // Restored load times are not trusted, because the app may have been closed for a long time
140
+ restoreSnapshot(collection, { ...stored, subsets: stored.subsets.map((subset) => ({ ...subset, loadedAt: 0 })) });
141
+ };
142
+
143
+ private read = async <T>(key: string): Promise<T | undefined> => {
144
+ try {
145
+ const raw = await this.storage.getItem(key);
146
+ return raw ? (this.serializer.parse(raw) as T) : undefined;
147
+ } catch (error) {
148
+ this.db.emitError({ type: "persistence", error });
149
+ return undefined;
150
+ }
151
+ };
152
+
153
+ private write = async (key: string, value: unknown) => {
154
+ try {
155
+ await this.storage.setItem(key, this.serializer.stringify(value));
156
+ } catch (error) {
157
+ this.db.emitError({ type: "persistence", error });
158
+ }
159
+ };
160
+
161
+ private remove = async (key: string) => {
162
+ try {
163
+ await this.storage.removeItem(key);
164
+ } catch (error) {
165
+ this.db.emitError({ type: "persistence", error });
166
+ }
167
+ };
168
+ }
@@ -0,0 +1,123 @@
1
+ /** A value type the db stores as tagged JSON, beyond the ones it knows */
2
+ export type DbCodec = {
3
+ /** The tag stored with encoded values. It must stay the same across releases. */
4
+ name: string;
5
+ /** Whether a value is of this type */
6
+ test: (value: unknown) => boolean;
7
+ /** Turns a value into one the serializer can store */
8
+ encode: (value: unknown) => unknown;
9
+ /** Turns a stored value back */
10
+ decode: (value: unknown) => unknown;
11
+ };
12
+
13
+ const TAG = "$hf";
14
+
15
+ type Tagged = { [TAG]: string; v?: unknown };
16
+
17
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
18
+ if (typeof value !== "object" || value === null) {
19
+ return false;
20
+ }
21
+ const prototype = Object.getPrototypeOf(value);
22
+ return prototype === Object.prototype || prototype === null;
23
+ };
24
+
25
+ const isTagged = (value: unknown): value is Tagged => isPlainObject(value) && typeof value[TAG] === "string";
26
+
27
+ /**
28
+ * Stores values as type-tagged JSON, so `Date`, `bigint`, `Map`, `Set`, `undefined`, `NaN` and the infinities come back
29
+ * as they were. Persistence, the outbox and server rendering use it.
30
+ */
31
+ export const createSerializer = (codecs: readonly DbCodec[] = []) => {
32
+ const encode = (value: unknown): unknown => {
33
+ const codec = codecs.find((item) => item.test(value));
34
+ if (codec) {
35
+ return { [TAG]: codec.name, v: encode(codec.encode(value)) };
36
+ }
37
+ if (value === undefined) {
38
+ return { [TAG]: "undefined" };
39
+ }
40
+ if (typeof value === "number" && !Number.isFinite(value)) {
41
+ return { [TAG]: "number", v: String(value) };
42
+ }
43
+ if (typeof value === "bigint") {
44
+ return { [TAG]: "bigint", v: value.toString() };
45
+ }
46
+ if (value instanceof Date) {
47
+ return { [TAG]: "Date", v: encode(value.getTime()) };
48
+ }
49
+ if (value instanceof Map) {
50
+ return { [TAG]: "Map", v: [...value.entries()].map(([key, item]) => [encode(key), encode(item)]) };
51
+ }
52
+ if (value instanceof Set) {
53
+ return { [TAG]: "Set", v: [...value].map(encode) };
54
+ }
55
+ if (Array.isArray(value)) {
56
+ return value.map(encode);
57
+ }
58
+ if (isPlainObject(value)) {
59
+ const encoded = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encode(item)]));
60
+ // An object that has the tag's key itself is wrapped, so it is never read as a tagged value
61
+ return TAG in value ? { [TAG]: "object", v: encoded } : encoded;
62
+ }
63
+ return value;
64
+ };
65
+
66
+ const decodeEntries = (value: Record<string, unknown>) =>
67
+ Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decode(item)]));
68
+
69
+ const decodeTagged = ({ [TAG]: tag, v }: Tagged): unknown => {
70
+ switch (tag) {
71
+ case "undefined": {
72
+ return undefined;
73
+ }
74
+ case "number": {
75
+ return Number(v);
76
+ }
77
+ case "bigint": {
78
+ return BigInt(v as string);
79
+ }
80
+ case "Date": {
81
+ return new Date(decode(v) as number);
82
+ }
83
+ case "Map": {
84
+ return new Map((v as [unknown, unknown][]).map(([key, item]) => [decode(key), decode(item)]));
85
+ }
86
+ case "Set": {
87
+ return new Set((v as unknown[]).map(decode));
88
+ }
89
+ case "object": {
90
+ return decodeEntries(v as Record<string, unknown>);
91
+ }
92
+ default: {
93
+ const codec = codecs.find((item) => item.name === tag);
94
+ if (!codec) {
95
+ throw new Error(`No codec decodes stored values tagged "${tag}"`);
96
+ }
97
+ return codec.decode(decode(v));
98
+ }
99
+ }
100
+ };
101
+
102
+ function decode(value: unknown): unknown {
103
+ if (Array.isArray(value)) {
104
+ return value.map(decode);
105
+ }
106
+ if (isTagged(value)) {
107
+ return decodeTagged(value);
108
+ }
109
+ if (isPlainObject(value)) {
110
+ return decodeEntries(value);
111
+ }
112
+ return value;
113
+ }
114
+
115
+ return {
116
+ encode,
117
+ decode,
118
+ stringify: (value: unknown) => JSON.stringify(encode(value)),
119
+ parse: (raw: string) => decode(JSON.parse(raw)),
120
+ };
121
+ };
122
+
123
+ export type Serializer = ReturnType<typeof createSerializer>;