@nichoth/simple-sync 0.0.0-stage → 0.0.5

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 (67) hide show
  1. package/README.md +469 -2
  2. package/dist/client/db.d.ts +67 -0
  3. package/dist/client/db.d.ts.map +1 -0
  4. package/dist/client/db.js +1 -0
  5. package/dist/client/db.js.map +7 -0
  6. package/dist/client/idb.d.ts +12 -0
  7. package/dist/client/idb.d.ts.map +1 -0
  8. package/dist/client/idb.js +72 -0
  9. package/dist/client/idb.js.map +7 -0
  10. package/dist/client/index.d.ts +143 -0
  11. package/dist/client/index.d.ts.map +1 -0
  12. package/dist/client/index.js +362 -0
  13. package/dist/client/index.js.map +7 -0
  14. package/dist/client/sqlite-opfs-rpc.d.ts +21 -0
  15. package/dist/client/sqlite-opfs-rpc.d.ts.map +1 -0
  16. package/dist/client/sqlite-opfs-rpc.js +55 -0
  17. package/dist/client/sqlite-opfs-rpc.js.map +7 -0
  18. package/dist/client/sqlite-opfs.d.ts +15 -0
  19. package/dist/client/sqlite-opfs.d.ts.map +1 -0
  20. package/dist/client/sqlite-opfs.js +31 -0
  21. package/dist/client/sqlite-opfs.js.map +7 -0
  22. package/dist/client/sqlite-opfs.worker.d.ts +6 -0
  23. package/dist/client/sqlite-opfs.worker.d.ts.map +1 -0
  24. package/dist/client/sqlite-opfs.worker.js +47 -0
  25. package/dist/client/sqlite-opfs.worker.js.map +7 -0
  26. package/dist/client/sqlite.d.ts +25 -0
  27. package/dist/client/sqlite.d.ts.map +1 -0
  28. package/dist/client/sqlite.js +117 -0
  29. package/dist/client/sqlite.js.map +7 -0
  30. package/dist/client.d.ts +6 -0
  31. package/dist/client.d.ts.map +1 -0
  32. package/dist/client.js +11 -0
  33. package/dist/client.js.map +7 -0
  34. package/dist/hash.d.ts +23 -0
  35. package/dist/hash.d.ts.map +1 -0
  36. package/dist/hash.js +29 -0
  37. package/dist/hash.js.map +7 -0
  38. package/dist/index.d.ts +10 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +18 -0
  41. package/dist/index.js.map +7 -0
  42. package/dist/meta.json +511 -0
  43. package/dist/op.d.ts +41 -0
  44. package/dist/op.d.ts.map +1 -0
  45. package/dist/op.js +46 -0
  46. package/dist/op.js.map +7 -0
  47. package/dist/reduce.d.ts +55 -0
  48. package/dist/reduce.d.ts.map +1 -0
  49. package/dist/reduce.js +173 -0
  50. package/dist/reduce.js.map +7 -0
  51. package/dist/server/errors.d.ts +16 -0
  52. package/dist/server/errors.d.ts.map +1 -0
  53. package/dist/server/errors.js +14 -0
  54. package/dist/server/errors.js.map +7 -0
  55. package/dist/server/index.d.ts +75 -0
  56. package/dist/server/index.d.ts.map +1 -0
  57. package/dist/server/index.js +324 -0
  58. package/dist/server/index.js.map +7 -0
  59. package/dist/server.d.ts +2 -0
  60. package/dist/server.d.ts.map +1 -0
  61. package/dist/server.js +5 -0
  62. package/dist/server.js.map +7 -0
  63. package/dist/types.d.ts +105 -0
  64. package/dist/types.d.ts.map +1 -0
  65. package/dist/types.js +1 -0
  66. package/dist/types.js.map +7 -0
  67. package/package.json +118 -4
package/dist/reduce.js ADDED
@@ -0,0 +1,173 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ import { hashState } from "./hash.js";
4
+ function parseOpId(opId) {
5
+ if (!opId.startsWith("op:")) return null;
6
+ const rest = opId.slice(3);
7
+ const lastColon = rest.lastIndexOf(":");
8
+ if (lastColon === -1) return null;
9
+ const deviceId = rest.slice(0, lastColon);
10
+ const seqStr = rest.slice(lastColon + 1);
11
+ const seq = Number(seqStr);
12
+ if (!Number.isInteger(seq) || seq < 1) return null;
13
+ if (deviceId === "") return null;
14
+ return { deviceId, seq };
15
+ }
16
+ __name(parseOpId, "parseOpId");
17
+ function parseStateId(id) {
18
+ const m = id.match(/^state:(.+):([0-9]+):([0-9]+(?:\.[0-9]+)?)$/);
19
+ if (m === null) return null;
20
+ const seq = Number(m[2]);
21
+ const ts = Number(m[3]);
22
+ if (!Number.isInteger(seq) || seq < 1) return null;
23
+ if (!Number.isFinite(ts)) return null;
24
+ if (m[1] === "") return null;
25
+ return { deviceId: m[1], seq, ts };
26
+ }
27
+ __name(parseStateId, "parseStateId");
28
+ function clockBeats(aTs, aAuthor, bTs, bAuthor) {
29
+ if (aTs !== bTs) return aTs > bTs;
30
+ return aAuthor > bAuthor;
31
+ }
32
+ __name(clockBeats, "clockBeats");
33
+ async function lastWriteWins(state, incomingOp) {
34
+ if (incomingOp.type === "delete" && incomingOp.value === null) {
35
+ return null;
36
+ }
37
+ if (incomingOp.type === "create") {
38
+ if (incomingOp.value === null || typeof incomingOp.value !== "object" || Array.isArray(incomingOp.value)) {
39
+ return state;
40
+ }
41
+ const parsed = parseOpId(incomingOp.id);
42
+ if (parsed === null) {
43
+ return state;
44
+ }
45
+ const id = `state:${parsed.deviceId}:${parsed.seq}:${incomingOp.ts}`;
46
+ const value = {};
47
+ const __ts = {};
48
+ const __author = {};
49
+ for (const [key, val] of Object.entries(incomingOp.value)) {
50
+ if (key !== "__ts") {
51
+ value[key] = val;
52
+ __ts[key] = incomingOp.ts;
53
+ __author[key] = parsed.deviceId;
54
+ }
55
+ }
56
+ const hash = await hashState(value);
57
+ return { id, hash, __ts, __author, value };
58
+ }
59
+ if (incomingOp.type === "patch") {
60
+ if (incomingOp.value === null || typeof incomingOp.value !== "object" || Array.isArray(incomingOp.value)) {
61
+ return state;
62
+ }
63
+ if (state === null) {
64
+ return null;
65
+ }
66
+ const next = { ...state.value };
67
+ const nextTs = { ...state.__ts };
68
+ const nextAuthor = { ...state.__author ?? {} };
69
+ const author = parseOpId(incomingOp.id)?.deviceId ?? "";
70
+ for (const [k, v] of Object.entries(incomingOp.value)) {
71
+ if (k === "__ts") {
72
+ continue;
73
+ }
74
+ const fieldTs = nextTs[k];
75
+ const fieldAuthor = nextAuthor[k] ?? "";
76
+ if (fieldTs === void 0 || !clockBeats(fieldTs, fieldAuthor, incomingOp.ts, author)) {
77
+ next[k] = v;
78
+ nextTs[k] = incomingOp.ts;
79
+ nextAuthor[k] = author;
80
+ }
81
+ }
82
+ const hash = await hashState(next);
83
+ return {
84
+ id: state.id,
85
+ hash,
86
+ __ts: nextTs,
87
+ __author: nextAuthor,
88
+ value: next
89
+ };
90
+ }
91
+ if (incomingOp.type === "delete") {
92
+ if (incomingOp.value === null || typeof incomingOp.value !== "object" || Array.isArray(incomingOp.value) || !("key" in incomingOp.value)) {
93
+ return state;
94
+ }
95
+ const { key } = incomingOp.value;
96
+ if (typeof key !== "string") {
97
+ return state;
98
+ }
99
+ if (key === "__ts") {
100
+ return state;
101
+ }
102
+ if (state === null) {
103
+ return null;
104
+ }
105
+ const author = parseOpId(incomingOp.id)?.deviceId ?? "";
106
+ const fieldTs = state.__ts[key];
107
+ const fieldAuthor = state.__author?.[key] ?? "";
108
+ if (fieldTs !== void 0 && clockBeats(fieldTs, fieldAuthor, incomingOp.ts, author)) {
109
+ return state;
110
+ }
111
+ const next = { ...state.value };
112
+ const nextTs = { ...state.__ts };
113
+ const nextAuthor = { ...state.__author ?? {} };
114
+ delete next[key];
115
+ nextTs[key] = incomingOp.ts;
116
+ nextAuthor[key] = author;
117
+ const hash = await hashState(next);
118
+ return {
119
+ id: state.id,
120
+ hash,
121
+ __ts: nextTs,
122
+ __author: nextAuthor,
123
+ value: next
124
+ };
125
+ }
126
+ return state;
127
+ }
128
+ __name(lastWriteWins, "lastWriteWins");
129
+ async function mergeReducedStates(local, incoming) {
130
+ if (local === null || local.id !== incoming.id) {
131
+ return incoming;
132
+ }
133
+ const value = {};
134
+ const nextTs = {};
135
+ const nextAuthor = {};
136
+ const keys = /* @__PURE__ */ new Set([
137
+ ...Object.keys(local.value),
138
+ ...Object.keys(local.__ts),
139
+ ...Object.keys(incoming.value),
140
+ ...Object.keys(incoming.__ts)
141
+ ]);
142
+ for (const key of keys) {
143
+ const lTs = local.__ts[key];
144
+ const iTs = incoming.__ts[key];
145
+ const lCmp = typeof lTs === "number" ? lTs : -Infinity;
146
+ const iCmp = typeof iTs === "number" ? iTs : -Infinity;
147
+ const lAuthor = local.__author?.[key] ?? "";
148
+ const iAuthor = incoming.__author?.[key] ?? "";
149
+ const localWins = clockBeats(lCmp, lAuthor, iCmp, iAuthor);
150
+ const winner = localWins ? local : incoming;
151
+ const winnerTs = localWins ? lTs : iTs;
152
+ const winnerAuthor = localWins ? lAuthor : iAuthor;
153
+ if (typeof winnerTs === "number") {
154
+ nextTs[key] = winnerTs;
155
+ }
156
+ if (winnerAuthor !== "") {
157
+ nextAuthor[key] = winnerAuthor;
158
+ }
159
+ if (Object.prototype.hasOwnProperty.call(winner.value, key)) {
160
+ value[key] = winner.value[key];
161
+ }
162
+ }
163
+ const hash = await hashState(value);
164
+ return { id: incoming.id, hash, __ts: nextTs, __author: nextAuthor, value };
165
+ }
166
+ __name(mergeReducedStates, "mergeReducedStates");
167
+ export {
168
+ lastWriteWins,
169
+ mergeReducedStates,
170
+ parseOpId,
171
+ parseStateId
172
+ };
173
+ //# sourceMappingURL=reduce.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/reduce.ts"],
4
+ "sourcesContent": ["/**\n * Reducer functions for state mutations in Simple Sync.\n * The default `lastWriteWins` resolver handles create, patch, and delete\n * operations with per-field timestamp tracking for conflict resolution.\n */\n\nimport type { Op, ReducedState } from './types.js'\nimport { hashState } from './hash.js'\n\n/**\n * Parse op.id to extract deviceId and seq.\n * Returns null if the id format is invalid.\n *\n * Expected format: op:${deviceId}:${seq}\n * Uses lastIndexOf(':') to support future deviceId schemes that\n * may contain colons.\n */\nexport function parseOpId (opId:string):{ deviceId:string, seq:number }|null {\n if (!opId.startsWith('op:')) return null\n const rest = opId.slice(3)\n const lastColon = rest.lastIndexOf(':')\n if (lastColon === -1) return null\n const deviceId = rest.slice(0, lastColon)\n const seqStr = rest.slice(lastColon + 1)\n const seq = Number(seqStr)\n if (!Number.isInteger(seq) || seq < 1) return null\n if (deviceId === '') return null\n return { deviceId, seq }\n}\n\n/**\n * Parse a reduced-state id of the form state:<deviceId>:<seq>:<ts>.\n * deviceId may contain any chars (incl. ':'), matching parseOpId.\n * ts may be fractional. Returns null if the shape is invalid.\n */\nexport function parseStateId (id:string):{\n deviceId:string, seq:number, ts:number\n} | null {\n const m = id.match(/^state:(.+):([0-9]+):([0-9]+(?:\\.[0-9]+)?)$/)\n if (m === null) return null\n const seq = Number(m[2])\n const ts = Number(m[3])\n if (!Number.isInteger(seq) || seq < 1) return null\n if (!Number.isFinite(ts)) return null\n if (m[1] === '') return null\n return { deviceId: m[1], seq, ts }\n}\n\n/**\n * Internal comparator: true iff (aTs, aAuthor) STRICTLY beats\n * (bTs, bAuthor). Higher ts wins; equal ts -> higher deviceId wins.\n * Equal ts AND equal deviceId is NOT a strict beat.\n * Missing author counts as '' (lowest).\n */\nfunction clockBeats (\n aTs:number, aAuthor:string, bTs:number, bAuthor:string\n):boolean {\n if (aTs !== bTs) return aTs > bTs\n return aAuthor > bAuthor\n}\n\n/**\n * Default reducer for Simple Sync. Pass directly to\n * `SyncServer.reduce` or use as a building block in your own\n * reducer.\n *\n * Handles create, patch, and delete operations with per-field\n * timestamp-based Last-Write-Wins conflict resolution.\n * Timestamps are stored in state.__ts (top-level, never in value).\n * State ids are constructed as state:${deviceId}:${seq}:${ts}.\n * Whole-state delete (op.value === null) returns null.\n *\n * @see https://github.com/substrate-system/simple-sync (v1)\n */\nexport async function lastWriteWins (\n state:ReducedState | null,\n incomingOp:Op\n):Promise<ReducedState | null> {\n // Whole-state delete: return null regardless of state existence\n if (incomingOp.type === 'delete' && incomingOp.value === null) {\n return null\n }\n\n // CREATE operation\n if (incomingOp.type === 'create') {\n // Reject non-object values\n if (\n incomingOp.value === null ||\n typeof incomingOp.value !== 'object' ||\n Array.isArray(incomingOp.value)\n ) {\n return state\n }\n\n // Parse op.id to extract deviceId and seq\n const parsed = parseOpId(incomingOp.id)\n if (parsed === null) {\n return state\n }\n\n // Construct canonical state id\n const id = `state:${parsed.deviceId}:${parsed.seq}:${incomingOp.ts}`\n\n // Build value, __ts, and __author from op payload\n const value:Record<string, unknown> = {}\n const __ts:Record<string, number> = {}\n const __author:Record<string, string> = {}\n for (const [key, val] of Object.entries(incomingOp.value as Record<string, unknown>)) {\n // Skip reserved keys (never write __ts into value)\n if (key !== '__ts') {\n value[key] = val\n __ts[key] = incomingOp.ts\n __author[key] = parsed.deviceId\n }\n }\n\n // Compute hash over value only\n const hash = await hashState(value)\n\n return { id, hash, __ts, __author, value }\n }\n\n // PATCH operation\n if (incomingOp.type === 'patch') {\n // Reject non-object values\n if (\n incomingOp.value === null ||\n typeof incomingOp.value !== 'object' ||\n Array.isArray(incomingOp.value)\n ) {\n return state\n }\n\n // Cannot patch null state\n if (state === null) {\n return null\n }\n\n // Shallow-merge patch fields with LWW per field\n const next:Record<string, unknown> = { ...state.value }\n const nextTs:Record<string, number> = { ...state.__ts }\n const nextAuthor:Record<string, string> = { ...(state.__author ?? {}) }\n\n const author = parseOpId(incomingOp.id)?.deviceId ?? ''\n\n for (const [k, v] of Object.entries(incomingOp.value)) {\n // Skip reserved keys (never write __ts into value)\n if (k === '__ts') {\n continue\n }\n // LWW: accept unless the existing field clock strictly beats\n const fieldTs = nextTs[k]\n const fieldAuthor = nextAuthor[k] ?? ''\n if (fieldTs === undefined ||\n !clockBeats(fieldTs, fieldAuthor, incomingOp.ts, author)) {\n next[k] = v\n nextTs[k] = incomingOp.ts\n nextAuthor[k] = author\n }\n }\n\n // Compute hash over updated value\n const hash = await hashState(next)\n\n return {\n id: state.id,\n hash,\n __ts: nextTs,\n __author: nextAuthor,\n value: next\n }\n }\n\n // DELETE operation (field delete, not whole-state)\n if (incomingOp.type === 'delete') {\n // Check if value has shape { key: string }\n if (\n incomingOp.value === null ||\n typeof incomingOp.value !== 'object' ||\n Array.isArray(incomingOp.value) ||\n !('key' in incomingOp.value)\n ) {\n return state\n }\n\n const { key } = incomingOp.value as { key:unknown }\n\n // Key must be a string\n if (typeof key !== 'string') {\n return state\n }\n\n // Cannot delete reserved keys\n if (key === '__ts') {\n return state\n }\n\n // Cannot delete from null state\n if (state === null) {\n return null\n }\n\n // Derive the writer deviceId for this op\n const author = parseOpId(incomingOp.id)?.deviceId ?? ''\n\n // LWW stale check: reject only when the existing field clock\n // strictly beats the incoming one\n const fieldTs = state.__ts[key]\n const fieldAuthor = state.__author?.[key] ?? ''\n if (fieldTs !== undefined &&\n clockBeats(fieldTs, fieldAuthor, incomingOp.ts, author)) {\n return state\n }\n\n // Build updated value, __ts, and __author\n const next:Record<string, unknown> = { ...state.value }\n const nextTs:Record<string, number> = { ...state.__ts }\n const nextAuthor:Record<string, string> = { ...(state.__author ?? {}) }\n delete next[key]\n nextTs[key] = incomingOp.ts\n nextAuthor[key] = author\n\n // Compute hash over updated value\n const hash = await hashState(next)\n\n return {\n id: state.id,\n hash,\n __ts: nextTs,\n __author: nextAuthor,\n value: next\n }\n }\n\n // Unknown operation type: return state unchanged\n return state\n}\n\n/**\n * Per-field last-write-wins merge of two reduced-state snapshots.\n * Used by the client to reconcile an inbound server `state` against\n * its local (possibly newer, un-synced) projection without losing a\n * newer local edit. The higher `__ts` wins per field; the winning\n * side's presence in `value` decides live vs tombstoned. Returns\n * `incoming` unchanged when there is no comparable local snapshot.\n *\n * @param local The local snapshot, or null if none is held.\n * @param incoming The authoritative server snapshot.\n */\nexport async function mergeReducedStates (\n local:ReducedState | null,\n incoming:Readonly<ReducedState>\n):Promise<ReducedState> {\n // No local snapshot, or a different state id: nothing to merge.\n if (local === null || local.id !== incoming.id) {\n return incoming\n }\n\n const value:Record<string, unknown> = {}\n const nextTs:Record<string, number> = {}\n const nextAuthor:Record<string, string> = {}\n\n const keys = new Set<string>([\n ...Object.keys(local.value),\n ...Object.keys(local.__ts),\n ...Object.keys(incoming.value),\n ...Object.keys(incoming.__ts)\n ])\n\n for (const key of keys) {\n const lTs = local.__ts[key]\n const iTs = incoming.__ts[key]\n // Missing clock entry counts as oldest.\n const lCmp = typeof lTs === 'number' ? lTs : -Infinity\n const iCmp = typeof iTs === 'number' ? iTs : -Infinity\n\n const lAuthor = local.__author?.[key] ?? ''\n const iAuthor = incoming.__author?.[key] ?? ''\n\n // Compare (ts, deviceId) tuples; tie still resolves to incoming.\n const localWins = clockBeats(lCmp, lAuthor, iCmp, iAuthor)\n const winner = localWins ? local : incoming\n const winnerTs = localWins ? lTs : iTs\n const winnerAuthor = localWins ? lAuthor : iAuthor\n\n if (typeof winnerTs === 'number') {\n nextTs[key] = winnerTs\n }\n // Carry the winning __author value only if it's not empty\n if (winnerAuthor !== '') {\n nextAuthor[key] = winnerAuthor\n }\n // Live iff the winner has the field in `value`; otherwise the\n // winner tombstoned it (retain the clock, omit the value).\n if (Object.prototype.hasOwnProperty.call(winner.value, key)) {\n value[key] = (winner.value as Record<string, unknown>)[key]\n }\n }\n\n const hash = await hashState(value)\n return { id: incoming.id, hash, __ts: nextTs, __author: nextAuthor, value }\n}\n"],
5
+ "mappings": ";;AAOA,SAAS,iBAAiB;AAUnB,SAAS,UAAW,MAAkD;AACzE,MAAI,CAAC,KAAK,WAAW,KAAK,EAAG,QAAO;AACpC,QAAM,OAAO,KAAK,MAAM,CAAC;AACzB,QAAM,YAAY,KAAK,YAAY,GAAG;AACtC,MAAI,cAAc,GAAI,QAAO;AAC7B,QAAM,WAAW,KAAK,MAAM,GAAG,SAAS;AACxC,QAAM,SAAS,KAAK,MAAM,YAAY,CAAC;AACvC,QAAM,MAAM,OAAO,MAAM;AACzB,MAAI,CAAC,OAAO,UAAU,GAAG,KAAK,MAAM,EAAG,QAAO;AAC9C,MAAI,aAAa,GAAI,QAAO;AAC5B,SAAO,EAAE,UAAU,IAAI;AAC3B;AAXgB;AAkBT,SAAS,aAAc,IAErB;AACL,QAAM,IAAI,GAAG,MAAM,6CAA6C;AAChE,MAAI,MAAM,KAAM,QAAO;AACvB,QAAM,MAAM,OAAO,EAAE,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;AAG5C,UAAM,YAAY,WAAW,MAAM,SAAS,MAAM,OAAO;AACzD,UAAM,SAAS,YAAY,QAAQ;AACnC,UAAM,WAAW,YAAY,MAAM;AACnC,UAAM,eAAe,YAAY,UAAU;AAE3C,QAAI,OAAO,aAAa,UAAU;AAC9B,aAAO,GAAG,IAAI;AAAA,IAClB;AAEA,QAAI,iBAAiB,IAAI;AACrB,iBAAW,GAAG,IAAI;AAAA,IACtB;AAGA,QAAI,OAAO,UAAU,eAAe,KAAK,OAAO,OAAO,GAAG,GAAG;AACzD,YAAM,GAAG,IAAK,OAAO,MAAkC,GAAG;AAAA,IAC9D;AAAA,EACJ;AAEA,QAAM,OAAO,MAAM,UAAU,KAAK;AAClC,SAAO,EAAE,IAAI,SAAS,IAAI,MAAM,MAAM,QAAQ,UAAU,YAAY,MAAM;AAC9E;AApDsB;",
6
+ "names": []
7
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Pure helpers for classifying connection errors surfaced by
3
+ * partyserver's WebSocket handling. Kept free of `cloudflare:workers`
4
+ * and `partyserver` imports so it can be unit-tested in the browser
5
+ * test runner without the Durable Object runtime.
6
+ */
7
+ /**
8
+ * True for transient transport drops that we treat as benign. A
9
+ * client closing its tab, a dropped network, or
10
+ * `SyncClient.disconnect()` all surface as retryable
11
+ * "Network connection lost" / "WebSocket peer disconnected" errors.
12
+ * Cloudflare marks them `retryable`; some also carry a recognizable
13
+ * message. Anything else is treated as unexpected.
14
+ */
15
+ export declare function isBenignConnectionError(error: unknown): boolean;
16
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/server/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAE,KAAK,EAAC,OAAO,GAAE,OAAO,CAS9D"}
@@ -0,0 +1,14 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ function isBenignConnectionError(error) {
4
+ if (!error || typeof error !== "object") return false;
5
+ const e = error;
6
+ if (e.retryable === true) return true;
7
+ const msg = typeof e.message === "string" ? e.message : "";
8
+ return msg.includes("Network connection lost") || msg.includes("WebSocket peer disconnected");
9
+ }
10
+ __name(isBenignConnectionError, "isBenignConnectionError");
11
+ export {
12
+ isBenignConnectionError
13
+ };
14
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/server/errors.ts"],
4
+ "sourcesContent": ["/**\n * Pure helpers for classifying connection errors surfaced by\n * partyserver's WebSocket handling. Kept free of `cloudflare:workers`\n * and `partyserver` imports so it can be unit-tested in the browser\n * test runner without the Durable Object runtime.\n */\n\n/**\n * True for transient transport drops that we treat as benign. A\n * client closing its tab, a dropped network, or\n * `SyncClient.disconnect()` all surface as retryable\n * \"Network connection lost\" / \"WebSocket peer disconnected\" errors.\n * Cloudflare marks them `retryable`; some also carry a recognizable\n * message. Anything else is treated as unexpected.\n */\nexport function isBenignConnectionError (error:unknown):boolean {\n if (!error || typeof error !== 'object') return false\n const e = error as { retryable?:unknown; message?:unknown }\n if (e.retryable === true) return true\n const msg = typeof e.message === 'string' ? e.message : ''\n return (\n msg.includes('Network connection lost') ||\n msg.includes('WebSocket peer disconnected')\n )\n}\n"],
5
+ "mappings": ";;AAeO,SAAS,wBAAyB,OAAuB;AAC5D,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,MAAI,EAAE,cAAc,KAAM,QAAO;AACjC,QAAM,MAAM,OAAO,EAAE,YAAY,WAAW,EAAE,UAAU;AACxD,SACI,IAAI,SAAS,yBAAyB,KACtC,IAAI,SAAS,6BAA6B;AAElD;AATgB;",
6
+ "names": []
7
+ }
@@ -0,0 +1,75 @@
1
+ import { Server, type Connection, type WSMessage } from 'partyserver';
2
+ import type { Op, ReducedState } from '../types.js';
3
+ /**
4
+ * Server-side base for Simple Sync. Subclass and assign a
5
+ * `reduce` method (or use the exported `lastWriteWins`).
6
+ *
7
+ * Subclass example:
8
+ *
9
+ * import { SyncServer, lastWriteWins } from '@substrate-system/simple-sync'
10
+ * export class Sync extends SyncServer {
11
+ * reduce = lastWriteWins
12
+ * }
13
+ *
14
+ * The DO must be declared as a SQLite class in wrangler.jsonc:
15
+ *
16
+ * "migrations": [
17
+ * { "tag": "vN", "new_sqlite_classes": ["Sync"] }
18
+ * ]
19
+ */
20
+ export declare abstract class SyncServer<Env extends Cloudflare.Env = Cloudflare.Env> extends Server<Env> {
21
+ /**
22
+ * Pure reducer. Subclass must provide one. The default
23
+ * `lastWriteWins` (exported from `@substrate-system/simple-sync`)
24
+ * is the usual choice. May return null to indicate whole-state
25
+ * delete; the server will delete the row from reductions,
26
+ * remove from _current, and broadcast kind:'state-deleted'.
27
+ */
28
+ abstract reduce(state: ReducedState | null, op: Op): Promise<ReducedState | null>;
29
+ /** Cached current state, keyed by state id. */
30
+ private _current;
31
+ /** True once onStart has finished rehydrating. */
32
+ private _ready;
33
+ /**
34
+ * Opt-in: when true, compact the `ops` table to the single
35
+ * highest-seq op per device after each write batch. Default false
36
+ * — existing workers keep their full op-log. LWW correctness is
37
+ * independent of the op-log (it reads `reductions.__ts`).
38
+ */
39
+ protected dropAppliedOps: boolean;
40
+ onStart(): Promise<void>;
41
+ onMessage(connection: Connection, message: WSMessage): Promise<void>;
42
+ /**
43
+ * Connection-level error handler. partyserver routes WebSocket
44
+ * transport errors here (via `webSocketError`). Routine drops — a
45
+ * client closing its tab, a dropped network, or
46
+ * `SyncClient.disconnect()` — surface as retryable
47
+ * "Network connection lost" / "WebSocket peer disconnected"
48
+ * errors, so swallow those quietly; anything else stays visible
49
+ * for debugging.
50
+ *
51
+ * This overrides partyserver's default `onError`, which logs
52
+ * every error plus an "Implement onError" hint regardless of
53
+ * cause. The DO does not enable hibernation, so the base's
54
+ * hibernate-only connection close is not relevant here;
55
+ * partyserver tears the socket down via `webSocketClose`.
56
+ */
57
+ onError(connection: Connection, error: unknown): void;
58
+ private _handleHello;
59
+ private _handleWrite;
60
+ private _validOpShape;
61
+ private _machineFromOpId;
62
+ /**
63
+ * Compact the ops table to the highest-seq op per device (Kafka
64
+ * "keep latest per key"). Safe: LWW reads `reductions.__ts`, and
65
+ * `_handleHello` only needs `MAX(seq)` per device, which the
66
+ * retained op preserves.
67
+ */
68
+ private _pruneOps;
69
+ /**
70
+ * Current op count per device in the ops table. Read seam for the
71
+ * example's op-count endpoint.
72
+ */
73
+ protected opCountsByDevice(): Record<string, number>;
74
+ }
75
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,UAAU,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAA;AACrE,OAAO,KAAK,EAAE,EAAE,EAAY,YAAY,EAAE,MAAM,aAAa,CAAA;AAI7D;;;;;;;;;;;;;;;;GAgBG;AACH,8BAAsB,UAAU,CAC5B,GAAG,SAAS,UAAU,CAAC,GAAG,GAAG,UAAU,CAAC,GAAG,CAC7C,SAAQ,MAAM,CAAC,GAAG,CAAC;IACjB;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,CACX,KAAK,EAAC,YAAY,GAAG,IAAI,EACzB,EAAE,EAAC,EAAE,GACP,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAE9B,+CAA+C;IAC/C,OAAO,CAAC,QAAQ,CAAsC;IACtD,kDAAkD;IAClD,OAAO,CAAC,MAAM,CAAQ;IACtB;;;;;OAKG;IACH,SAAS,CAAC,cAAc,EAAC,OAAO,CAAQ;IAElC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAwFxB,SAAS,CACX,UAAU,EAAC,UAAU,EACrB,OAAO,EAAC,SAAS,GACnB,OAAO,CAAC,IAAI,CAAC;IAyBf;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAE,UAAU,EAAC,UAAU,EAAE,KAAK,EAAC,OAAO,GAAE,IAAI;YASrC,YAAY;YAgEZ,YAAY;IAwK1B,OAAO,CAAC,aAAa;IA0BrB,OAAO,CAAC,gBAAgB;IAQxB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IAiBjB;;;OAGG;IACH,SAAS,CAAC,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;CAQvD"}
@@ -0,0 +1,324 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ import { Server } from "partyserver";
4
+ import { hashState } from "../hash.js";
5
+ import { isBenignConnectionError } from "./errors.js";
6
+ class SyncServer extends Server {
7
+ static {
8
+ __name(this, "SyncServer");
9
+ }
10
+ /** Cached current state, keyed by state id. */
11
+ _current = /* @__PURE__ */ new Map();
12
+ /** True once onStart has finished rehydrating. */
13
+ _ready = false;
14
+ /**
15
+ * Opt-in: when true, compact the `ops` table to the single
16
+ * highest-seq op per device after each write batch. Default false
17
+ * — existing workers keep their full op-log. LWW correctness is
18
+ * independent of the op-log (it reads `reductions.__ts`).
19
+ */
20
+ dropAppliedOps = false;
21
+ async onStart() {
22
+ this.ctx.storage.sql.exec(
23
+ `CREATE TABLE IF NOT EXISTS ops (
24
+ id TEXT PRIMARY KEY,
25
+ machine_id TEXT NOT NULL,
26
+ seq INTEGER NOT NULL,
27
+ type TEXT NOT NULL,
28
+ target TEXT,
29
+ value TEXT NOT NULL,
30
+ ts INTEGER NOT NULL
31
+ )`
32
+ );
33
+ this.ctx.storage.sql.exec(
34
+ `CREATE INDEX IF NOT EXISTS idx_ops_machine_seq
35
+ ON ops (machine_id, seq)`
36
+ );
37
+ this.ctx.storage.sql.exec(
38
+ `CREATE TABLE IF NOT EXISTS reductions (
39
+ id TEXT PRIMARY KEY,
40
+ hash TEXT NOT NULL,
41
+ ts_json TEXT NOT NULL DEFAULT '{}',
42
+ author_json TEXT NOT NULL DEFAULT '{}',
43
+ value TEXT NOT NULL
44
+ )`
45
+ );
46
+ try {
47
+ this.ctx.storage.sql.exec(
48
+ "ALTER TABLE reductions ADD COLUMN ts_json TEXT NOT NULL DEFAULT '{}'"
49
+ );
50
+ } catch {
51
+ }
52
+ try {
53
+ this.ctx.storage.sql.exec(
54
+ "ALTER TABLE reductions ADD COLUMN author_json TEXT NOT NULL DEFAULT '{}'"
55
+ );
56
+ } catch {
57
+ }
58
+ const rows = this.ctx.storage.sql.exec(
59
+ "SELECT id, hash, ts_json, author_json, value FROM reductions"
60
+ ).toArray();
61
+ this._current.clear();
62
+ for (const r of rows) {
63
+ try {
64
+ const parsed = JSON.parse(
65
+ r.author_json
66
+ );
67
+ this._current.set(r.id, {
68
+ id: r.id,
69
+ hash: r.hash,
70
+ __ts: JSON.parse(r.ts_json),
71
+ __author: Object.keys(parsed).length > 0 ? parsed : void 0,
72
+ value: JSON.parse(r.value)
73
+ });
74
+ } catch {
75
+ }
76
+ }
77
+ this._ready = true;
78
+ }
79
+ async onMessage(connection, message) {
80
+ let env;
81
+ try {
82
+ const text = typeof message === "string" ? message : new TextDecoder().decode(message);
83
+ env = JSON.parse(text);
84
+ } catch {
85
+ return;
86
+ }
87
+ if (!env || typeof env !== "object" || typeof env.kind !== "string") {
88
+ return;
89
+ }
90
+ if (env.kind === "hello") {
91
+ await this._handleHello(connection, env);
92
+ return;
93
+ }
94
+ if (env.kind === "write") {
95
+ await this._handleWrite(env);
96
+ }
97
+ }
98
+ /**
99
+ * Connection-level error handler. partyserver routes WebSocket
100
+ * transport errors here (via `webSocketError`). Routine drops — a
101
+ * client closing its tab, a dropped network, or
102
+ * `SyncClient.disconnect()` — surface as retryable
103
+ * "Network connection lost" / "WebSocket peer disconnected"
104
+ * errors, so swallow those quietly; anything else stays visible
105
+ * for debugging.
106
+ *
107
+ * This overrides partyserver's default `onError`, which logs
108
+ * every error plus an "Implement onError" hint regardless of
109
+ * cause. The DO does not enable hibernation, so the base's
110
+ * hibernate-only connection close is not relevant here;
111
+ * partyserver tears the socket down via `webSocketClose`.
112
+ */
113
+ onError(connection, error) {
114
+ if (isBenignConnectionError(error)) return;
115
+ console.error(
116
+ "[SyncServer] connection error",
117
+ connection.id,
118
+ error
119
+ );
120
+ }
121
+ async _handleHello(connection, env) {
122
+ const deviceId = env.deviceId;
123
+ if (typeof deviceId !== "string" || deviceId === "") return;
124
+ connection.setState({ deviceId });
125
+ const row = this.ctx.storage.sql.exec(
126
+ "SELECT MAX(seq) AS max FROM ops WHERE machine_id = ?",
127
+ deviceId
128
+ ).toArray();
129
+ const serverSeq = row[0]?.max ?? 0;
130
+ const ready = typeof env.lastSeq === "number" && env.lastSeq > serverSeq ? { kind: "ready", requestFrom: serverSeq } : { kind: "ready" };
131
+ connection.send(JSON.stringify(ready));
132
+ const known = /* @__PURE__ */ new Map();
133
+ if (Array.isArray(env.states)) {
134
+ for (const ks of env.states) {
135
+ if (ks && typeof ks === "object" && typeof ks.id === "string" && typeof ks.hash === "string") {
136
+ known.set(ks.id, ks.hash);
137
+ }
138
+ }
139
+ }
140
+ const ids = [...this._current.keys()].sort();
141
+ for (const id of ids) {
142
+ const state = this._current.get(id);
143
+ if (known.get(id) === state.hash) continue;
144
+ const env2 = { kind: "state", state };
145
+ connection.send(JSON.stringify(env2));
146
+ }
147
+ const knownIds = [...known.keys()].sort();
148
+ for (const id of knownIds) {
149
+ if (this._current.has(id)) continue;
150
+ const env3 = { kind: "state-deleted", id };
151
+ connection.send(JSON.stringify(env3));
152
+ }
153
+ }
154
+ async _handleWrite(env) {
155
+ if (!Array.isArray(env.ops)) return;
156
+ const deletedIds = [];
157
+ const changedIds = /* @__PURE__ */ new Set();
158
+ const appliedOpById = /* @__PURE__ */ new Map();
159
+ for (const op of env.ops) {
160
+ if (!this._validOpShape(op)) continue;
161
+ const machineId = this._machineFromOpId(op.id) ?? "";
162
+ if (machineId === "") continue;
163
+ const cursor = this.ctx.storage.sql.exec(
164
+ `INSERT OR IGNORE INTO ops
165
+ (id, machine_id, seq, type, target, value, ts)
166
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
167
+ op.id,
168
+ machineId,
169
+ op.seq,
170
+ op.type,
171
+ op.target,
172
+ JSON.stringify(op.value),
173
+ op.ts
174
+ );
175
+ if (cursor.rowsWritten === 0) continue;
176
+ let next;
177
+ let stateId;
178
+ if (op.type === "create") {
179
+ try {
180
+ next = await this.reduce(null, op);
181
+ if (next === null) {
182
+ continue;
183
+ }
184
+ } catch (err) {
185
+ console.warn("[SyncServer] reduce threw", err);
186
+ continue;
187
+ }
188
+ const expectedId = `state:${machineId}:${op.seq}:${op.ts}`;
189
+ if (next.id !== expectedId) {
190
+ console.warn(
191
+ "[SyncServer] reducer returned malformed state id",
192
+ next.id,
193
+ "for op",
194
+ op.id
195
+ );
196
+ continue;
197
+ }
198
+ stateId = next.id;
199
+ } else {
200
+ if (op.target === "" || typeof op.target === "string" && op.target.startsWith("state:pending:")) {
201
+ console.warn(
202
+ "[SyncServer] retarget no longer supported,",
203
+ "dropping op",
204
+ op.id
205
+ );
206
+ continue;
207
+ }
208
+ if (typeof op.target !== "string" || !this._current.has(op.target)) {
209
+ console.warn(
210
+ "[SyncServer] unknown target",
211
+ op.target,
212
+ "for op",
213
+ op.id
214
+ );
215
+ continue;
216
+ }
217
+ stateId = op.target;
218
+ const prior = this._current.get(stateId);
219
+ try {
220
+ next = await this.reduce(prior, op);
221
+ } catch (err) {
222
+ console.warn("[SyncServer] reduce threw", err);
223
+ continue;
224
+ }
225
+ }
226
+ if (next === null) {
227
+ this._current.delete(stateId);
228
+ this.ctx.storage.sql.exec(
229
+ "DELETE FROM reductions WHERE id = ?",
230
+ stateId
231
+ );
232
+ deletedIds.push(stateId);
233
+ } else {
234
+ if (typeof next.hash !== "string" || next.hash === "") {
235
+ next = {
236
+ ...next,
237
+ hash: await hashState(next.value)
238
+ };
239
+ }
240
+ this._current.set(next.id, next);
241
+ this.ctx.storage.sql.exec(
242
+ `INSERT OR REPLACE INTO reductions
243
+ (id, hash, ts_json, author_json, value)
244
+ VALUES (?, ?, ?, ?, ?)`,
245
+ next.id,
246
+ next.hash,
247
+ JSON.stringify(next.__ts),
248
+ JSON.stringify(next.__author ?? {}),
249
+ JSON.stringify(next.value)
250
+ );
251
+ changedIds.add(next.id);
252
+ appliedOpById.set(next.id, op.id);
253
+ }
254
+ }
255
+ for (const id of deletedIds) {
256
+ const outEnv = { kind: "state-deleted", id };
257
+ this.broadcast(JSON.stringify(outEnv));
258
+ }
259
+ for (const id of changedIds) {
260
+ const state = this._current.get(id);
261
+ if (state) {
262
+ const appliedOp = appliedOpById.get(id);
263
+ const outEnv = appliedOp ? { kind: "state", state, appliedOp } : { kind: "state", state };
264
+ this.broadcast(JSON.stringify(outEnv));
265
+ }
266
+ }
267
+ if (this.dropAppliedOps) this._pruneOps();
268
+ }
269
+ _validOpShape(op) {
270
+ if (!op || typeof op !== "object") return false;
271
+ const o = op;
272
+ if (typeof o.id !== "string" || typeof o.seq !== "number" || typeof o.ts !== "number" || o.target !== null && typeof o.target !== "string") {
273
+ return false;
274
+ }
275
+ if (o.type === "create") return true;
276
+ if (o.type === "patch") {
277
+ return !!(o.value && typeof o.value === "object");
278
+ }
279
+ if (o.type === "delete") {
280
+ if (o.value === null) return true;
281
+ const v = o.value;
282
+ return !!(v && typeof v === "object" && typeof v.key === "string");
283
+ }
284
+ return false;
285
+ }
286
+ _machineFromOpId(id) {
287
+ if (!id.startsWith("op:")) return null;
288
+ const rest = id.slice(3);
289
+ const colon = rest.lastIndexOf(":");
290
+ if (colon <= 0) return null;
291
+ return rest.slice(0, colon);
292
+ }
293
+ /**
294
+ * Compact the ops table to the highest-seq op per device (Kafka
295
+ * "keep latest per key"). Safe: LWW reads `reductions.__ts`, and
296
+ * `_handleHello` only needs `MAX(seq)` per device, which the
297
+ * retained op preserves.
298
+ */
299
+ _pruneOps() {
300
+ this.ctx.storage.sql.exec(
301
+ `DELETE FROM ops
302
+ WHERE seq < (
303
+ SELECT MAX(seq) FROM ops AS o2
304
+ WHERE o2.machine_id = ops.machine_id
305
+ )`
306
+ );
307
+ }
308
+ /**
309
+ * Current op count per device in the ops table. Read seam for the
310
+ * example's op-count endpoint.
311
+ */
312
+ opCountsByDevice() {
313
+ const rows = this.ctx.storage.sql.exec(
314
+ "SELECT machine_id, COUNT(*) AS n FROM ops GROUP BY machine_id"
315
+ ).toArray();
316
+ const out = {};
317
+ for (const r of rows) out[r.machine_id] = r.n;
318
+ return out;
319
+ }
320
+ }
321
+ export {
322
+ SyncServer
323
+ };
324
+ //# sourceMappingURL=index.js.map