@engenty/wizards-runtime 0.9.8 → 0.11.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 (102) hide show
  1. package/apps/runtime/dist/app.js +34 -1
  2. package/apps/runtime/dist/auth/index.js +10 -1
  3. package/apps/runtime/dist/db/client.js +9 -1
  4. package/apps/runtime/dist/db/live-triggers.js +144 -0
  5. package/apps/runtime/dist/db/migrations/tenant/0022_sync.sql +247 -0
  6. package/apps/runtime/dist/db/migrations/tenant/0023_live_change.sql +167 -0
  7. package/apps/runtime/dist/db/migrations/tenant/0024_live_presence.sql +28 -0
  8. package/apps/runtime/dist/db/migrations/tenant/meta/0022_snapshot.json +3792 -0
  9. package/apps/runtime/dist/db/migrations/tenant/meta/0023_snapshot.json +3860 -0
  10. package/apps/runtime/dist/db/migrations/tenant/meta/0024_snapshot.json +3967 -0
  11. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +21 -0
  12. package/apps/runtime/dist/db/schema.js +101 -0
  13. package/apps/runtime/dist/docs/user-guide/cloud-sync.md +85 -0
  14. package/apps/runtime/dist/docs/user-guide/data.md +4 -4
  15. package/apps/runtime/dist/docs/user-guide/meta.json +2 -0
  16. package/apps/runtime/dist/docs/user-guide/test-and-share.md +4 -14
  17. package/apps/runtime/dist/docs/user-guide/together.md +60 -0
  18. package/apps/runtime/dist/files/blobs.js +13 -0
  19. package/apps/runtime/dist/index.js +11 -1
  20. package/apps/runtime/dist/live/feed.js +34 -0
  21. package/apps/runtime/dist/live/hub.js +200 -0
  22. package/apps/runtime/dist/live/origin.js +53 -0
  23. package/apps/runtime/dist/live/views.js +146 -0
  24. package/apps/runtime/dist/mcp/handler.js +7 -1
  25. package/apps/runtime/dist/mcp/tools.js +51 -2
  26. package/apps/runtime/dist/plugins/jobs.js +7 -0
  27. package/apps/runtime/dist/routes/api.js +177 -1
  28. package/apps/runtime/dist/routes/live.js +85 -0
  29. package/apps/runtime/dist/routes/studio.js +109 -85
  30. package/apps/runtime/dist/services/cloud.js +39 -5
  31. package/apps/runtime/dist/services/presence.js +132 -0
  32. package/apps/runtime/dist/services/projects.js +11 -0
  33. package/apps/runtime/dist/services/space-data.js +33 -6
  34. package/apps/runtime/dist/sync/apply.js +43 -0
  35. package/apps/runtime/dist/sync/client.js +973 -0
  36. package/apps/runtime/dist/sync/hub.js +324 -0
  37. package/apps/runtime/dist/sync/log.js +74 -0
  38. package/apps/runtime/dist/sync/records.js +943 -0
  39. package/apps/runtime/dist/sync/state.js +17 -0
  40. package/apps/runtime/dist/texts.js +2 -0
  41. package/apps/web/dist/assets/AboutDialog-9VcgySrQ.js +1 -0
  42. package/apps/web/dist/assets/{ChangelogDialog-BpEIbAZ8.js → ChangelogDialog-BXvT2VMU.js} +1 -1
  43. package/apps/web/dist/assets/EditorPage-Cvzd0nah.js +4 -0
  44. package/apps/web/dist/assets/{FlowPreview-APXdRflR.js → FlowPreview-BV1NJ0rF.js} +1 -1
  45. package/apps/web/dist/assets/{Harness-BsGXMlLg.js → Harness-DYviBlHB.js} +2 -2
  46. package/apps/web/dist/assets/Marketplace-DTSg7_U7.js +2 -0
  47. package/apps/web/dist/assets/{NewWizardChannels-0JrRdUFd.js → NewWizardChannels-DiujJzOR.js} +1 -1
  48. package/apps/web/dist/assets/NewWizardPage-CngUh9g-.js +7 -0
  49. package/apps/web/dist/assets/OnboardingPage-DFKJnWtw.js +1 -0
  50. package/apps/web/dist/assets/PreviewPane-C0E9OLzB.js +9 -0
  51. package/apps/web/dist/assets/ProjectPage-CYDX-JYc.js +1 -0
  52. package/apps/web/dist/assets/PublicRunner-CkRO_Pw-.js +1 -0
  53. package/apps/web/dist/assets/{ReadOnly-BraZbEG_.js → ReadOnly-E-h9y_QO.js} +1 -1
  54. package/apps/web/dist/assets/SettingsPage-BMgP3aRV.js +2 -0
  55. package/apps/web/dist/assets/SetupPage-DBO_rzj7.js +1 -0
  56. package/apps/web/dist/assets/{SharePage-Dk7zC5Zo.js → SharePage-BvvmYB5N.js} +1 -1
  57. package/apps/web/dist/assets/changelog-zllICQ4q.js +1 -0
  58. package/apps/web/dist/assets/{coins-391m1e4_.js → coins-DQ91VJAB.js} +1 -1
  59. package/apps/web/dist/assets/index-Bjn557f1.js +20 -0
  60. package/apps/web/dist/assets/index-DN0VMwsS.css +1 -0
  61. package/apps/web/dist/assets/{phone-DvgrtyNO.js → phone-jIuRIwyg.js} +1 -1
  62. package/apps/web/dist/assets/{runners-4OBelIgF.js → runners-DloOxEbh.js} +1 -1
  63. package/apps/web/dist/assets/session-BpsCkDv6.js +2 -0
  64. package/apps/web/dist/assets/{settings-menu-xK9A-gaP.js → settings-menu-CoLUNJGQ.js} +1 -1
  65. package/apps/web/dist/assets/theme-2XjIQXH3.js +11 -0
  66. package/apps/web/dist/assets/{ui-BVQk2DtW.js → ui-BIWmkPh6.js} +3 -3
  67. package/apps/web/dist/assets/{upload-BgXbzG6C.js → upload-BcOvBWHS.js} +1 -1
  68. package/apps/web/dist/assets/{useMutation-DkwSQWoD.js → useMutation-CD7HmAxR.js} +1 -1
  69. package/apps/web/dist/assets/{volume-2-DHGoe3Cg.js → volume-2-D2To9w5D.js} +1 -1
  70. package/apps/web/dist/assets/{wrench-Cf_aE3O0.js → wrench-B98ubRvB.js} +1 -1
  71. package/apps/web/dist/index.html +8 -8
  72. package/apps/web/dist/mcp/flow.html +2 -2
  73. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  74. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  75. package/node_modules/@engenty/wizards-shared/dist/live.d.ts +46 -0
  76. package/node_modules/@engenty/wizards-shared/dist/live.js +9 -0
  77. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +7 -0
  78. package/node_modules/@engenty/wizards-shared/dist/run.js +14 -0
  79. package/node_modules/@engenty/wizards-shared/dist/sync-merge.d.ts +55 -0
  80. package/node_modules/@engenty/wizards-shared/dist/sync-merge.js +214 -0
  81. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +166 -0
  82. package/node_modules/@engenty/wizards-shared/dist/sync.js +40 -0
  83. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +14 -0
  84. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +137 -0
  85. package/package.json +1 -1
  86. package/plugin/.claude-plugin/plugin.json +1 -1
  87. package/plugin/plugin.json +1 -1
  88. package/apps/web/dist/assets/AboutDialog-B_Ixp_Tb.js +0 -1
  89. package/apps/web/dist/assets/EditorPage-CKHY4hn4.js +0 -4
  90. package/apps/web/dist/assets/Marketplace-Dr-Qnb-F.js +0 -2
  91. package/apps/web/dist/assets/NewWizardPage-9igFL5O8.js +0 -7
  92. package/apps/web/dist/assets/OnboardingPage-BcK9FUnU.js +0 -1
  93. package/apps/web/dist/assets/PreviewPane-X4LBqA0D.js +0 -4
  94. package/apps/web/dist/assets/ProjectPage-CG0i-KhR.js +0 -1
  95. package/apps/web/dist/assets/PublicRunner-CZR1ziQ4.js +0 -1
  96. package/apps/web/dist/assets/SettingsPage-Bw4tdoV7.js +0 -2
  97. package/apps/web/dist/assets/SetupPage-CvkE2aKx.js +0 -1
  98. package/apps/web/dist/assets/changelog-DDXnAaHm.js +0 -1
  99. package/apps/web/dist/assets/index-BTUtot4r.js +0 -14
  100. package/apps/web/dist/assets/index-DcUL6teA.css +0 -1
  101. package/apps/web/dist/assets/session-DvnGHbDz.js +0 -2
  102. package/apps/web/dist/assets/theme-D3yDT4QT.js +0 -11
@@ -0,0 +1,324 @@
1
+ import { note } from "@engenty/wizards-shared/run";
2
+ import { count, eq } from "drizzle-orm";
3
+ import { db, schema, tenantSchemaVersion } from "../db/client.js";
4
+ import { getBlob, hasBlob, putBlobOf } from "../files/blobs.js";
5
+ import { managed, tenantInfo } from "../manage.js";
6
+ import { currentRole, isAdminRole, MEMBERS_EDIT_ONLY, mayBuild } from "../services/access.js";
7
+ import { ServiceError } from "../services/errors.js";
8
+ import { projectLimit } from "../services/projects.js";
9
+ import { publishWizard, rotateShareLink, shareUrl } from "../services/wizards.js";
10
+ import { codeOf } from "../tenants/control.js";
11
+ import { currentTenant } from "../tenants/tenant.js";
12
+ import { applyItems } from "./apply.js";
13
+ import { changedSince, compactLog, lastSeqs, seqKey, spaceSeq } from "./log.js";
14
+ import { canonical, KIND_ORDER, KINDS } from "./records.js";
15
+ /**
16
+ * The cloud's half of the two-way sync (docs/manage-contract.md, "Two-way sync of a space"): it
17
+ * takes what an install changed when it was made on the cloud's latest version of the item, and
18
+ * hands out what changed after a number. It writes through the same records as the install, as
19
+ * the person behind the token, in their role.
20
+ */
21
+ const PAGE = 300;
22
+ /** The tenant schema of both sides must be the same; refused otherwise, with ours named. */
23
+ function requireSchema(theirs) {
24
+ if (theirs !== tenantSchemaVersion) {
25
+ const order = (tag) => Number.parseInt(tag, 10) || 0;
26
+ throw new ServiceError("refused", order(theirs) < order(tenantSchemaVersion) ? note("syncUpdateHere") : note("syncUpdateCloud"), { reason: "schema_mismatch", schema: tenantSchemaVersion });
27
+ }
28
+ }
29
+ /** The organization as an install meets it: its schema, its number of spaces, its spaces. */
30
+ export async function syncOverview() {
31
+ const spaces = await db.query.project.findMany({
32
+ where: eq(schema.project.tenantId, currentTenant()),
33
+ columns: { id: true, name: true, origin: true },
34
+ orderBy: [schema.project.createdAt],
35
+ });
36
+ const info = managed ? await tenantInfo(currentTenant()).catch(() => null) : null;
37
+ const limit = await projectLimit();
38
+ return {
39
+ tenantId: currentTenant(),
40
+ schema: tenantSchemaVersion,
41
+ role: currentRole(),
42
+ limits: {
43
+ projects: info?.limits.projects === null || !Number.isFinite(limit) ? null : limit,
44
+ },
45
+ spaces: await Promise.all(spaces.map(async (s) => ({ id: s.id, name: s.name, seq: await spaceSeq(s.id) }))),
46
+ };
47
+ }
48
+ /**
49
+ * What changed in a space after `since`. From 0 it is every item of the space, a page at a
50
+ * time (`cursor`); `next` then is the number the log stood at when the listing began.
51
+ */
52
+ export async function pullChanges(projectId, since, cursor) {
53
+ if (since > 0) {
54
+ const logged = await changedSince(projectId, since, PAGE);
55
+ const changes = [];
56
+ for (const x of logged) {
57
+ const def = KINDS[x.kind];
58
+ if (!def) {
59
+ continue;
60
+ }
61
+ const read = await def.read(x.item);
62
+ if (read === "skip") {
63
+ continue;
64
+ }
65
+ changes.push({ kind: x.kind, item: x.item, seq: x.seq, record: read?.record ?? null });
66
+ }
67
+ return {
68
+ changes,
69
+ next: logged.at(-1)?.seq ?? since,
70
+ more: logged.length === PAGE,
71
+ };
72
+ }
73
+ const [offsetText, topText] = (cursor ?? "").split(".");
74
+ const offset = Number.parseInt(offsetText ?? "", 10) || 0;
75
+ const top = cursor ? Number.parseInt(topText ?? "", 10) || 0 : await spaceSeq(projectId);
76
+ const project = await db.query.project.findFirst({
77
+ where: eq(schema.project.id, projectId),
78
+ columns: { tenantId: true },
79
+ });
80
+ if (!project || project.tenantId !== currentTenant()) {
81
+ throw new ServiceError("not_found", note("syncSpaceNotInCloud"));
82
+ }
83
+ const all = [];
84
+ for (const kind of KIND_ORDER) {
85
+ for (const item of await KINDS[kind].list(projectId)) {
86
+ all.push({ kind, item });
87
+ }
88
+ }
89
+ const page = all.slice(offset, offset + PAGE);
90
+ const seqs = await lastSeqs(page);
91
+ const changes = [];
92
+ for (const x of page) {
93
+ const read = await KINDS[x.kind].read(x.item);
94
+ if (read && read !== "skip") {
95
+ changes.push({ ...x, seq: seqs.get(seqKey(x.kind, x.item)) ?? 0, record: read.record });
96
+ }
97
+ }
98
+ const more = offset + PAGE < all.length;
99
+ return {
100
+ changes,
101
+ next: more ? 0 : top,
102
+ more,
103
+ ...(more ? { cursor: `${offset + PAGE}.${top}` } : {}),
104
+ };
105
+ }
106
+ /** Whether the person may make or change this; members edit, owners and admins make and delete. */
107
+ function mayChange(x, exists) {
108
+ if (!managed || isAdminRole(currentRole())) {
109
+ return true;
110
+ }
111
+ if (x.kind === "space" || x.kind === "connector") {
112
+ return false;
113
+ }
114
+ if (x.kind === "wizard") {
115
+ return exists && x.record !== null;
116
+ }
117
+ return true;
118
+ }
119
+ async function requireRoomForSpace() {
120
+ const [{ n }] = await db
121
+ .select({ n: count() })
122
+ .from(schema.project)
123
+ .where(eq(schema.project.tenantId, currentTenant()));
124
+ const limit = await projectLimit();
125
+ if (n >= limit) {
126
+ throw new ServiceError("refused", limit === 1 ? note("onlyOneSpaceAllowed") : note("mostSpaces", { count: limit }), { reason: "space_limit", limit });
127
+ }
128
+ }
129
+ const refused = (x, reason, message) => ({
130
+ kind: x.kind,
131
+ item: x.item,
132
+ status: "refused",
133
+ reason,
134
+ message,
135
+ });
136
+ /**
137
+ * Takes what an install changed in one space. Each item is taken when the cloud's version has
138
+ * not changed after the one the install changed (`base`); else the answer is the cloud's
139
+ * version, to merge with. What is taken is written in one transaction, and gets its number.
140
+ */
141
+ export async function pushChanges(projectId, input) {
142
+ requireSchema(input.schema);
143
+ if (!(await mayBuild())) {
144
+ throw new ServiceError("read_only", note("wizardsRunOncePublished"), { reason: "read_only" });
145
+ }
146
+ const project = await db.query.project.findFirst({
147
+ where: eq(schema.project.id, projectId),
148
+ columns: { tenantId: true },
149
+ });
150
+ if (project && project.tenantId !== currentTenant()) {
151
+ throw new ServiceError("refused", note("spaceIdAlreadyExists"), { reason: "id_taken" });
152
+ }
153
+ const makesSpace = input.items.some((x) => x.kind === "space" && x.item === projectId && x.record !== null);
154
+ if (!project && !makesSpace) {
155
+ throw new ServiceError("not_found", note("syncSpaceNotInCloud"), { reason: "not_found" });
156
+ }
157
+ const seqs = await lastSeqs(input.items);
158
+ const results = [];
159
+ const taking = [];
160
+ // Refusals carry a `reason` the install says in its own words; `message` is for the log.
161
+ for (const x of input.items) {
162
+ const def = KINDS[x.kind];
163
+ const current = await def.read(x.item);
164
+ if (current === "skip") {
165
+ results.push(refused(x, "not_synced", "This item does not sync."));
166
+ continue;
167
+ }
168
+ if (current && current.projectId !== projectId) {
169
+ results.push(refused(x, "id_taken", "In the cloud this belongs to another space."));
170
+ continue;
171
+ }
172
+ if (x.record && x.kind !== "space" && x.record.projectId !== projectId) {
173
+ results.push(refused(x, "invalid", "The item names another space."));
174
+ continue;
175
+ }
176
+ if (!mayChange(x, current !== null)) {
177
+ results.push(refused(x, "forbidden", "Only the organization's owners and admins make and delete this."));
178
+ continue;
179
+ }
180
+ const seq = seqs.get(seqKey(x.kind, x.item)) ?? 0;
181
+ if (seq > x.base) {
182
+ results.push({
183
+ kind: x.kind,
184
+ item: x.item,
185
+ status: "conflict",
186
+ seq,
187
+ record: current?.record ?? null,
188
+ });
189
+ continue;
190
+ }
191
+ if (canonical(current?.record ?? null) === canonical(x.record)) {
192
+ results.push({ kind: x.kind, item: x.item, status: "taken", seq });
193
+ continue;
194
+ }
195
+ if (x.record) {
196
+ const missing = [];
197
+ for (const hash of def.blobs?.(x.record) ?? []) {
198
+ if (!(await hasBlob(hash))) {
199
+ missing.push(hash);
200
+ }
201
+ }
202
+ if (missing.length) {
203
+ results.push(refused(x, "blob_missing", "A file of this change has not arrived yet."));
204
+ continue;
205
+ }
206
+ }
207
+ if (x.kind === "space" && !current && x.record) {
208
+ try {
209
+ await requireRoomForSpace();
210
+ }
211
+ catch (err) {
212
+ results.push(refused(x, "space_limit", err.message || "No room for another space."));
213
+ continue;
214
+ }
215
+ }
216
+ taking.push({ x, apply: { kind: x.kind, item: x.item, projectId, record: x.record } });
217
+ }
218
+ const taken = await applyEach(taking.map((t) => t.apply));
219
+ const after = await lastSeqs(taking.map((t) => t.x));
220
+ for (const { x } of taking) {
221
+ const failed = taken.get(seqKey(x.kind, x.item));
222
+ results.push(failed
223
+ ? refused(x, "invalid", failed)
224
+ : {
225
+ kind: x.kind,
226
+ item: x.item,
227
+ status: "taken",
228
+ seq: after.get(seqKey(x.kind, x.item)) ?? 0,
229
+ });
230
+ }
231
+ await compactLog(projectId);
232
+ return { results, seq: await spaceSeq(projectId) };
233
+ }
234
+ /**
235
+ * Writes the batch in one transaction; when it fails, item by item, so one bad item does not
236
+ * hold back the others. Answers the items that could not be written, with why.
237
+ */
238
+ async function applyEach(items) {
239
+ const failed = new Map();
240
+ try {
241
+ await applyItems(items, { quiet: false });
242
+ return failed;
243
+ }
244
+ catch {
245
+ for (const item of items) {
246
+ try {
247
+ await applyItems([item], { quiet: false });
248
+ }
249
+ catch (err) {
250
+ failed.set(seqKey(item.kind, item.item), err.message || "invalid");
251
+ }
252
+ }
253
+ }
254
+ return failed;
255
+ }
256
+ // --- bytes ---------------------------------------------------------------------------------
257
+ export async function missingBlobs(hashes) {
258
+ const out = [];
259
+ for (const hash of hashes) {
260
+ if (!(await hasBlob(hash))) {
261
+ out.push(hash);
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+ export const takeBlob = putBlobOf;
267
+ export const blobBytes = getBlob;
268
+ // --- publishing and links ------------------------------------------------------------------
269
+ async function wizardInSpace(projectId, wizardId) {
270
+ const w = await db.query.wizard.findFirst({
271
+ where: eq(schema.wizard.id, wizardId),
272
+ columns: { projectId: true, tenantId: true },
273
+ });
274
+ if (!w || w.projectId !== projectId || w.tenantId !== currentTenant()) {
275
+ throw new ServiceError("not_found", note("syncSpaceNotInCloud"));
276
+ }
277
+ }
278
+ /** Publishes the cloud's draft of a wizard, which the install pushed before it asked. */
279
+ export async function publishSynced(userId, projectId, wizardId) {
280
+ await wizardInSpace(projectId, wizardId);
281
+ const published = await publishWizard(userId, wizardId);
282
+ const w = await db.query.wizard.findFirst({ where: eq(schema.wizard.id, wizardId) });
283
+ if (!w) {
284
+ throw new ServiceError("not_found", note("syncSpaceNotInCloud"));
285
+ }
286
+ return {
287
+ wizardId,
288
+ shareUrl: shareUrl(w.shareToken),
289
+ code: await codeOf(w.shareToken),
290
+ shareEnabled: w.shareEnabled,
291
+ publishedVersion: published.version,
292
+ runnable: true,
293
+ problems: [],
294
+ };
295
+ }
296
+ /** A new link for the cloud's copy of a wizard; the old one stops answering. */
297
+ export async function rotateSynced(userId, projectId, wizardId) {
298
+ await wizardInSpace(projectId, wizardId);
299
+ const { shareToken } = await rotateShareLink(userId, wizardId);
300
+ return { shareUrl: shareUrl(shareToken), code: await codeOf(shareToken) };
301
+ }
302
+ /**
303
+ * A space a local install synced one way (`origin = "local"`) becomes a space of the cloud's
304
+ * own, which the studio here edits: from now on it syncs both ways.
305
+ */
306
+ export async function adoptSpace(projectId) {
307
+ if (managed && !isAdminRole(currentRole())) {
308
+ throw new ServiceError("forbidden", MEMBERS_EDIT_ONLY);
309
+ }
310
+ const project = await db.query.project.findFirst({
311
+ where: eq(schema.project.id, projectId),
312
+ columns: { tenantId: true, origin: true },
313
+ });
314
+ if (!project || project.tenantId !== currentTenant()) {
315
+ return { adopted: false };
316
+ }
317
+ if (project.origin === "local") {
318
+ await db
319
+ .update(schema.project)
320
+ .set({ origin: null, syncedAt: new Date() })
321
+ .where(eq(schema.project.id, projectId));
322
+ }
323
+ return { adopted: true };
324
+ }
@@ -0,0 +1,74 @@
1
+ import { and, eq, gt, inArray, max, sql } from "drizzle-orm";
2
+ import { db, schema } from "../db/client.js";
3
+ /** The last number of each of these items; 0 for one the log has not seen. */
4
+ export async function lastSeqs(items) {
5
+ const out = new Map();
6
+ for (let i = 0; i < items.length; i += 200) {
7
+ const part = items.slice(i, i + 200);
8
+ const rows = await db
9
+ .select({
10
+ kind: schema.syncChange.kind,
11
+ item: schema.syncChange.item,
12
+ seq: max(schema.syncChange.seq),
13
+ })
14
+ .from(schema.syncChange)
15
+ .where(inArray(schema.syncChange.item, part.map((x) => x.item)))
16
+ .groupBy(schema.syncChange.kind, schema.syncChange.item);
17
+ for (const r of rows) {
18
+ out.set(`${r.kind}|${r.item}`, r.seq ?? 0);
19
+ }
20
+ }
21
+ return out;
22
+ }
23
+ export const seqKey = (kind, item) => `${kind}|${item}`;
24
+ /** The last number of the space's log; 0 when nothing of it changed yet. */
25
+ export async function spaceSeq(projectId) {
26
+ const [row] = await db
27
+ .select({ seq: max(schema.syncChange.seq) })
28
+ .from(schema.syncChange)
29
+ .where(eq(schema.syncChange.projectId, projectId));
30
+ return row?.seq ?? 0;
31
+ }
32
+ /** The items of a space that changed after `since`, by their last change, oldest first. */
33
+ export async function changedSince(projectId, since, limit) {
34
+ const seq = max(schema.syncChange.seq);
35
+ const rows = await db
36
+ .select({ kind: schema.syncChange.kind, item: schema.syncChange.item, seq })
37
+ .from(schema.syncChange)
38
+ .where(and(eq(schema.syncChange.projectId, projectId), gt(schema.syncChange.seq, since)))
39
+ .groupBy(schema.syncChange.kind, schema.syncChange.item)
40
+ .orderBy(seq)
41
+ .limit(limit);
42
+ return rows.map((r) => ({
43
+ kind: r.kind,
44
+ item: r.item,
45
+ projectId,
46
+ seq: r.seq ?? 0,
47
+ }));
48
+ }
49
+ /** Keeps only each item's last change: what a pull or a push needs. */
50
+ export async function compactLog(projectId) {
51
+ await db.run(projectId
52
+ ? sql `DELETE FROM sync_change WHERE project_id = ${projectId} AND seq NOT IN (SELECT MAX(seq) FROM sync_change WHERE project_id = ${projectId} GROUP BY kind, item)`
53
+ : sql `DELETE FROM sync_change WHERE seq NOT IN (SELECT MAX(seq) FROM sync_change GROUP BY kind, item)`);
54
+ }
55
+ /** Drops what was pushed: changes of the space up to `seq`. */
56
+ export async function dropPushed(projectId, seq) {
57
+ await db
58
+ .delete(schema.syncChange)
59
+ .where(and(eq(schema.syncChange.projectId, projectId), sql `${schema.syncChange.seq} <= ${seq}`));
60
+ }
61
+ /** Notes an item as changed here, though no write did: a version kept by the person's choice. */
62
+ export async function notePending(projectId, kind, item) {
63
+ await db.insert(schema.syncChange).values({ projectId, kind, item });
64
+ }
65
+ /** Runs `fn` with the triggers quiet: what it writes is not noted as a change of this side. */
66
+ export async function quietly(fn) {
67
+ await db.update(schema.syncGuard).set({ applying: 1 }).where(eq(schema.syncGuard.id, 1));
68
+ try {
69
+ return await fn();
70
+ }
71
+ finally {
72
+ await db.update(schema.syncGuard).set({ applying: 0 }).where(eq(schema.syncGuard.id, 1));
73
+ }
74
+ }