@open-pencil/cloud 0.16.0 → 0.17.0-beta.2

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 (54) hide show
  1. package/dist/listen.mjs +236 -117
  2. package/dist/listen.mjs.map +1 -1
  3. package/dist/runtime-node.d.mts +2937 -703
  4. package/dist/runtime-node.d.mts.map +1 -1
  5. package/dist/server.d.ts +3985 -941
  6. package/dist/server.d.ts.map +1 -1
  7. package/dist/server.js +833 -376
  8. package/dist/server.js.map +1 -1
  9. package/dist/server.mjs +665 -271
  10. package/dist/server.mjs.map +1 -1
  11. package/package.json +4 -2
  12. package/src/admin/api/routes.ts +44 -33
  13. package/src/runtime/cloudflare/environment.ts +16 -2
  14. package/src/runtime/cloudflare/relay/index.ts +128 -0
  15. package/src/runtime/cloudflare/relay/sockets.ts +112 -0
  16. package/src/runtime/cloudflare/worker.ts +56 -19
  17. package/src/runtime/node/bootstrap.ts +9 -4
  18. package/src/runtime/node/server.ts +40 -8
  19. package/src/runtime/posthog/errors.ts +48 -0
  20. package/src/runtime/s3/objects.ts +26 -0
  21. package/src/runtime/site/server.ts +5 -3
  22. package/src/server/api/router.ts +3 -2
  23. package/src/server/api/types.ts +7 -0
  24. package/src/server/app.ts +4 -0
  25. package/src/server/cleanup/objects.ts +10 -2
  26. package/src/server/cleanup/revisions.ts +8 -2
  27. package/src/server/collaboration/index.ts +3 -0
  28. package/src/server/collaboration/relay/connection.ts +195 -0
  29. package/src/server/collaboration/relay/hub.ts +199 -187
  30. package/src/server/collaboration/relay/index.ts +3 -1
  31. package/src/server/collaboration/relay/log.ts +76 -0
  32. package/src/server/collaboration/relay/persistence.ts +147 -22
  33. package/src/server/collaboration/relay/resume.ts +28 -0
  34. package/src/server/collaboration/routes.ts +27 -16
  35. package/src/server/config/deployment.ts +11 -0
  36. package/src/server/config/schema.ts +24 -2
  37. package/src/server/db/migrate.ts +3 -1
  38. package/src/server/db/migrations/028_collaboration_updates.ts +84 -0
  39. package/src/server/db/tables.ts +18 -4
  40. package/src/server/documents/routes.ts +106 -80
  41. package/src/server/documents/versions/routes.ts +36 -25
  42. package/src/server/documents/versions/service.ts +9 -0
  43. package/src/server/errors/index.ts +56 -0
  44. package/src/server/index.ts +11 -0
  45. package/src/server/internal/routes.ts +3 -8
  46. package/src/server/objects/types.ts +12 -0
  47. package/src/server/pictures/routes.ts +4 -2
  48. package/src/server/rate-limit/index.ts +4 -1
  49. package/src/server/rate-limit/middleware.ts +99 -11
  50. package/src/server/sharing/document-routes.ts +30 -22
  51. package/src/server/sharing/routes.ts +122 -83
  52. package/src/server/validation.ts +58 -2
  53. package/src/server/workspaces/routes.ts +63 -45
  54. package/src/runtime/cloudflare/relay.ts +0 -136
package/dist/server.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_DISCOVERY_PATH, CLOUD_PICTURE_MAX_BYTES, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, COLLAB_ACTIONS, MAX_COLLAB_MESSAGE_BYTES, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_SERVER_PEER, cloudAdminAuditFilterSchema, cloudAdminEmailFilterSchema, cloudAdminUserFilterSchema, cloudEditorVersionSchema, cloudInvitationURL, collaborationPrincipalSchema, createRelayClientAssembler, decodeRelayClientFrame, decodeRoomUpdate, documentPermissionSchema, encodeSyncReply, enrollmentStatusSchema as enrollmentStatusSchema$1, parseAcceptDocumentInvitation, parseCloudDiscovery, parseCloudEmailChange, parseCloudMFAEnable, parseCloudMFAVerify, parseCloudPasskeyDelete, parseCloudPasswordChange, parseCloudPictureUpload, parseCloudProfileUpdate, parseCloudSessionRevoke, parseCloudSocialLink, parseCloudUnlinkAuthenticationMethod, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateDocumentInvitation, parseCreateDocumentShare, parseCreateInvitationContinuation, parseCreateUpload, parseCreateWorkspace, parseCreateWorkspaceInvitation, parseDuplicateDocumentVersion, parseLookupCloudUser, parsePutDocumentGrant, parseRequestImageLinks, parseRequestImageUploads, parseRequestSharedImageLinks, parseResolveDocumentShare, parseSaveDocumentVersion, parseUpdateDocumentShare, parseUpdateDocumentVersion, parseUpdateWorkspace, parseUpdateWorkspaceMember, presenceName, relayServerMessages, workspaceRoleSchema } from "./contract2.js";
2
- import { toUint8Array } from "js-base64";
2
+ import { fromUint8Array, toUint8Array } from "js-base64";
3
3
  import * as v from "valibot";
4
- import { ValiError } from "valibot";
5
4
  import { clamp, compact, countBy, groupBy, isUndefined, keyBy, limitAsync, maxBy, omitBy, sumBy, uniq, uniqBy, zipObject } from "es-toolkit";
6
5
  import * as decoding from "lib0/decoding";
7
6
  import * as encoding from "lib0/encoding";
8
7
  import * as Y from "yjs";
9
8
  import { withQuery, withoutTrailingSlash } from "ufo";
10
9
  import { rateLimiter } from "hono-rate-limiter";
11
- import { matchedRoutes } from "hono/route";
10
+ import { every } from "hono/combine";
11
+ import { matchedRoutes, routePath } from "hono/route";
12
12
  import { sha256 } from "@noble/hashes/sha2.js";
13
13
  import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
14
14
  import { validator } from "hono/validator";
@@ -30,6 +30,7 @@ import { randomHex } from "@open-pencil/scene-graph/random";
30
30
  import { hkdf } from "@noble/hashes/hkdf.js";
31
31
  import { DefaultLogger, TypedInMemoryProvider } from "@openfeature/server-sdk";
32
32
  import { bodyLimit } from "hono/body-limit";
33
+ import { HTTPException } from "hono/http-exception";
33
34
  import { bearerAuth } from "hono/bearer-auth";
34
35
  import { cors } from "hono/cors";
35
36
  import { Migrator } from "kysely/migration";
@@ -77,9 +78,9 @@ function requireTrustedMutationOrigin(trustedOrigins) {
77
78
  }
78
79
  //#endregion
79
80
  //#region src/admin/schema.ts
80
- const uuidSchema$2 = v.pipe(v.string(), v.uuid());
81
+ const uuidSchema$1 = v.pipe(v.string(), v.uuid());
81
82
  /** Accounts and access requests are named by UUID; anything else names no row. */
82
- const isUUID = (value) => v.is(uuidSchema$2, value);
83
+ const isUUID = (value) => v.is(uuidSchema$1, value);
83
84
  const enrollmentStatusSchema = v.picklist([
84
85
  "pending",
85
86
  "approved",
@@ -190,12 +191,14 @@ const CLOUD_RATE_LIMITS = {
190
191
  collaborationTicket: {
191
192
  namespace: "collaboration-ticket",
192
193
  windowMs: 6e4,
193
- limit: 60
194
+ limit: 60,
195
+ actorLimit: 300
194
196
  },
195
197
  invitationMutation: {
196
198
  namespace: "invitation-mutation",
197
199
  windowMs: 6e4,
198
- limit: 30
200
+ limit: 30,
201
+ actorLimit: 60
199
202
  },
200
203
  workspaceCreation: {
201
204
  namespace: "workspace-creation",
@@ -205,12 +208,14 @@ const CLOUD_RATE_LIMITS = {
205
208
  documentCreation: {
206
209
  namespace: "document-creation",
207
210
  windowMs: 6e4,
208
- limit: 60
211
+ limit: 60,
212
+ actorLimit: 120
209
213
  },
210
214
  uploadCreation: {
211
215
  namespace: "upload-creation",
212
216
  windowMs: 6e4,
213
- limit: 120
217
+ limit: 120,
218
+ actorLimit: 600
214
219
  },
215
220
  authenticatedMutation: {
216
221
  namespace: "authenticated-mutation",
@@ -282,11 +287,58 @@ function createActorRateLimiter(database, secret, policy, skip, resource) {
282
287
  });
283
288
  }
284
289
  /**
285
- * A limiter a route mounts for its own budget, such as document creation; general limiters leave
290
+ * A limiter a route mounts for its own budget, such as workspace creation; general limiters leave
286
291
  * the requests it counts to it.
287
292
  */
288
- function createRouteRateLimiter(database, secret, policy, skip, resource) {
289
- return ownBudget(createActorRateLimiter(database, secret, policy, skip, resource), skip);
293
+ function createRouteRateLimiter(database, secret, policy, skip) {
294
+ return ownBudget(createActorRateLimiter(database, secret, policy, skip), skip);
295
+ }
296
+ /**
297
+ * A route's own budget counted per resource, such as uploads per document, and capped per actor
298
+ * across resources by `actorLimit`; general limiters leave the requests it counts to it.
299
+ */
300
+ function createResourceRateLimiter(database, secret, policy, resource, skip) {
301
+ const perResource = createActorRateLimiter(database, secret, policy, skip, resource);
302
+ const perActor = createActorRateLimiter(database, secret, {
303
+ namespace: `${policy.namespace}-actor`,
304
+ windowMs: policy.windowMs,
305
+ limit: policy.actorLimit
306
+ }, skip);
307
+ return ownBudget(every(perResource, keepResourceUse, perActor, reportTighterBudget(policy.windowMs)), skip);
308
+ }
309
+ /** Keeps the resource budget's use, which the actor-wide limiter would record over. */
310
+ const keepResourceUse = async (context, next) => {
311
+ context.set("resourceRateLimit", context.get("rateLimit"));
312
+ await next();
313
+ };
314
+ /**
315
+ * Reports whichever budget has fewer requests left in the `RateLimit` headers, as both limiters
316
+ * write them and the last would otherwise win. A refused request keeps the headers of the budget
317
+ * that refused it.
318
+ */
319
+ function reportTighterBudget(windowMs) {
320
+ return async (context, next) => {
321
+ const resource = context.get("resourceRateLimit");
322
+ const actor = context.get("rateLimit");
323
+ const tighter = resource && actor && resource.remaining < actor.remaining ? resource : actor;
324
+ if (tighter) setBudgetHeaders(context, tighter, windowMs);
325
+ await next();
326
+ };
327
+ }
328
+ /** The draft-7 `RateLimit` headers `hono-rate-limiter` writes, for one budget's use. */
329
+ function setBudgetHeaders(context, use, windowMs) {
330
+ const windowSeconds = Math.ceil(windowMs / 1e3);
331
+ const reset = use.resetTime ? Math.max(0, Math.ceil((use.resetTime.getTime() - Date.now()) / 1e3)) : windowSeconds;
332
+ context.header("RateLimit-Policy", `${use.limit};w=${windowSeconds}`);
333
+ context.header("RateLimit", `limit=${use.limit}, remaining=${use.remaining}, reset=${reset}`);
334
+ }
335
+ /**
336
+ * A limiter's resource named by a route parameter, such as the document a request uploads to. It
337
+ * runs before the route's param validator, and the value only names the limiter's counter, which
338
+ * `rateLimitKey` hashes; it never reaches a query.
339
+ */
340
+ function routeParamResource(name) {
341
+ return (context) => context.req.param(name)?.toLowerCase() ?? "unknown";
290
342
  }
291
343
  //#endregion
292
344
  //#region src/server/validation.ts
@@ -295,7 +347,7 @@ function parseOrReject(parse, value, context) {
295
347
  try {
296
348
  return parse(value);
297
349
  } catch (error) {
298
- if (error instanceof ValiError) return context.json({ error: { code: "invalid_request" } }, 400);
350
+ if (error instanceof v.ValiError) return context.json({ error: { code: "invalid_request" } }, 400);
299
351
  throw error;
300
352
  }
301
353
  }
@@ -306,6 +358,61 @@ function validatedJSON(parse) {
306
358
  function validatedQuery(parse) {
307
359
  return validator("query", (value, context) => parseOrReject(parse, value, context));
308
360
  }
361
+ /**
362
+ * A route parameter that names a row by UUID, in lowercase: the database matches any case, but an
363
+ * ID that also names something else, such as a document's relay, must have one spelling.
364
+ */
365
+ const uuidParamSchema = v.pipe(v.string(), v.uuid(), v.toLowerCase());
366
+ /**
367
+ * Route parameters through `schema`; handlers read them from `context.req.valid('param')`. A
368
+ * parameter that fails it names nothing, so the route answers 404 as for a missing row, and the
369
+ * value never reaches the database.
370
+ */
371
+ function validatedParams(schema) {
372
+ return validator("param", (value, context) => {
373
+ const parsed = v.safeParse(schema, value);
374
+ return parsed.success ? parsed.output : context.json({ error: { code: "not_found" } }, 404);
375
+ });
376
+ }
377
+ /** A route parameter the server takes as text, such as a user ID, which is not a UUID column. */
378
+ const textParamSchema = v.pipe(v.string(), v.minLength(1));
379
+ const documentParams = validatedParams(v.object({ documentId: uuidParamSchema }));
380
+ const documentVersionParams = validatedParams(v.object({
381
+ documentId: uuidParamSchema,
382
+ versionId: uuidParamSchema
383
+ }));
384
+ const documentShareParams = validatedParams(v.object({
385
+ documentId: uuidParamSchema,
386
+ shareId: uuidParamSchema
387
+ }));
388
+ const documentInvitationParams = validatedParams(v.object({
389
+ documentId: uuidParamSchema,
390
+ invitationId: uuidParamSchema
391
+ }));
392
+ const documentUserParams = validatedParams(v.object({
393
+ documentId: uuidParamSchema,
394
+ userId: textParamSchema
395
+ }));
396
+ const workspaceParams = validatedParams(v.object({ workspaceId: uuidParamSchema }));
397
+ const workspaceInvitationParams = validatedParams(v.object({
398
+ workspaceId: uuidParamSchema,
399
+ invitationId: uuidParamSchema
400
+ }));
401
+ const workspaceMemberParams = validatedParams(v.object({
402
+ workspaceId: uuidParamSchema,
403
+ userId: textParamSchema
404
+ }));
405
+ const shareParams = validatedParams(v.object({ shareId: uuidParamSchema }));
406
+ const invitationParams = validatedParams(v.object({ invitationId: uuidParamSchema }));
407
+ const invitationContinuationParams = validatedParams(v.object({ continuationId: textParamSchema }));
408
+ const uploadParams = validatedParams(v.object({ uploadId: uuidParamSchema }));
409
+ /** Admin records (enrollments, accounts, and messages), all named by UUID. */
410
+ const idParams = validatedParams(v.object({ id: uuidParamSchema }));
411
+ /** A picture's address names its owner and a prefix of its checksum, which the service checks. */
412
+ const pictureParams = validatedParams(v.object({
413
+ userId: textParamSchema,
414
+ version: textParamSchema
415
+ }));
309
416
  //#endregion
310
417
  //#region src/admin/api/routes.ts
311
418
  /**
@@ -349,9 +456,8 @@ function createCloudAdminRoutes(services, trustedOrigins, security) {
349
456
  if (error instanceof v.ValiError) return context.json({ error: { code: "invalid_request" } }, 400);
350
457
  if (error instanceof NoResultError) return context.json({ error: { code: "not_found" } }, 404);
351
458
  throw error;
352
- }).get("/enrollments", validatedQuery(parseEnrollmentQuery), async (context) => context.json(await services.enrollment.list(context.req.valid("query")))).post("/enrollments/:id/approve", validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.param("id"), "approved", context.req.valid("json")) })).post("/enrollments/:id/reject", validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.param("id"), "rejected", context.req.valid("json")) })).post("/enrollments/:id/revoke", validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.param("id"), "revoked", context.req.valid("json")) })).get("/users", validatedQuery(parseUserQuery), async (context) => context.json(await services.users.list(context.req.valid("query")))).get("/users/:id", async (context) => {
353
- const id = context.req.param("id");
354
- const detail = v.is(accountIdSchema, id) ? await services.users.detail(id) : null;
459
+ }).get("/enrollments", validatedQuery(parseEnrollmentQuery), async (context) => context.json(await services.enrollment.list(context.req.valid("query")))).post("/enrollments/:id/approve", idParams, validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.valid("param").id, "approved", context.req.valid("json")) })).post("/enrollments/:id/reject", idParams, validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.valid("param").id, "rejected", context.req.valid("json")) })).post("/enrollments/:id/revoke", idParams, validatedJSON(parseEnrollmentReview), async (context) => context.json({ enrollment: await services.enrollment.review(context.get("actor").userId, context.req.valid("param").id, "revoked", context.req.valid("json")) })).get("/users", validatedQuery(parseUserQuery), async (context) => context.json(await services.users.list(context.req.valid("query")))).get("/users/:id", idParams, async (context) => {
460
+ const detail = await services.users.detail(context.req.valid("param").id);
355
461
  if (!detail) return context.json({ error: { code: "not_found" } }, 404);
356
462
  return context.json(detail);
357
463
  }).post("/users/reset-two-step", validatedJSON(parseUserMutation), (context) => accountMutation(context, context.req.valid("json").userId, (actorId, userId) => services.users.resetTwoStep(actorId, userId))).post("/users/remove-picture", validatedJSON(parseUserMutation), (context) => accountMutation(context, context.req.valid("json").userId, (actorId, userId) => services.users.removePicture(actorId, userId))).post("/users/ban", validatedJSON(parseUserMutation), async (context) => {
@@ -370,8 +476,8 @@ function createCloudAdminRoutes(services, trustedOrigins, security) {
370
476
  const input = context.req.valid("json");
371
477
  await services.users.setAdmin(context.req.raw.headers, context.get("actor").userId, input.userId, input.enabled);
372
478
  return context.json({ ok: true });
373
- }).get("/email", validatedQuery(parseEmailQuery), async (context) => context.json(await services.email.list(context.req.valid("query")))).post("/email/:id/regenerate", async (context) => {
374
- await services.email.regenerate(context.get("actor").userId, context.req.param("id"));
479
+ }).get("/email", validatedQuery(parseEmailQuery), async (context) => context.json(await services.email.list(context.req.valid("query")))).post("/email/:id/regenerate", idParams, async (context) => {
480
+ await services.email.regenerate(context.get("actor").userId, context.req.valid("param").id);
375
481
  return context.json({ ok: true });
376
482
  }).get("/audit", validatedQuery(parseAuditQuery), async (context) => context.json(await services.audit.list(context.req.valid("query")))).get("/operations", async (context) => context.json(await services.operations.summary()));
377
483
  }
@@ -983,7 +1089,13 @@ const rawCloudServerConfigSchema = v.object({
983
1089
  aiTokenLifetimeSeconds: v.optional(v.pipe(v.number(), v.integer(), v.minValue(60), v.maxValue(3600)), 600),
984
1090
  billingPortalURL: v.optional(httpURLSchema),
985
1091
  /** The bearer token services such as billing present to the internal API. */
986
- internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32)))
1092
+ internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32))),
1093
+ /** Where server errors are reported; without it the server reports nothing. */
1094
+ errorTracking: v.optional(v.object({
1095
+ provider: v.literal("posthog"),
1096
+ host: httpURLSchema,
1097
+ projectAPIKey: v.pipe(v.string(), v.trim(), v.minLength(1))
1098
+ }))
987
1099
  });
988
1100
  var CloudConfigError = class extends Error {
989
1101
  constructor(message) {
@@ -1042,6 +1154,8 @@ function parseCloudServerConfig(input) {
1042
1154
  validateObjectStorageConfig(config);
1043
1155
  return config;
1044
1156
  }
1157
+ /** PostHog's US Cloud ingestion host. */
1158
+ const POSTHOG_DEFAULT_HOST = "https://us.i.posthog.com";
1045
1159
  const DEFAULT_SECRET_NAMES = {
1046
1160
  databaseURL: "DATABASE_URL",
1047
1161
  authSecret: "BETTER_AUTH_SECRET",
@@ -1055,7 +1169,8 @@ const DEFAULT_SECRET_NAMES = {
1055
1169
  smtpPassword: "OPENPENCIL_CLOUD_SMTP_PASSWORD",
1056
1170
  turnstileSecretKey: "TURNSTILE_SECRET_KEY",
1057
1171
  aiSigningKey: "OPENPENCIL_CLOUD_AI_SIGNING_KEY",
1058
- internalServiceToken: "OPENPENCIL_CLOUD_SERVICE_TOKEN"
1172
+ internalServiceToken: "OPENPENCIL_CLOUD_SERVICE_TOKEN",
1173
+ posthogProjectAPIKey: "POSTHOG_PROJECT_API_KEY"
1059
1174
  };
1060
1175
  const urlSchema = v.pipe(v.string(), v.url());
1061
1176
  const textSchema = v.pipe(v.string(), v.trim(), v.minLength(1));
@@ -1231,7 +1346,13 @@ const cloudDeploymentConfigSchema = v.strictObject({
1231
1346
  token_lifetime_minutes: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(60)), 10)
1232
1347
  })),
1233
1348
  billing: v.optional(v.strictObject({ portal_url: urlSchema })),
1234
- internal_api: v.optional(v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) }))
1349
+ internal_api: v.optional(v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })),
1350
+ /** Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. */
1351
+ error_tracking: v.optional(v.strictObject({
1352
+ provider: v.literal("posthog"),
1353
+ host: v.optional(urlSchema, POSTHOG_DEFAULT_HOST),
1354
+ project_api_key: v.optional(configurableTextSchema, { from_env: DEFAULT_SECRET_NAMES.posthogProjectAPIKey })
1355
+ }))
1235
1356
  });
1236
1357
  //#endregion
1237
1358
  //#region src/server/config/deployment.ts
@@ -1306,6 +1427,15 @@ function serviceConfig(config, environment) {
1306
1427
  internalServiceToken: config.internal_api ? requiredSecret(environment, config.internal_api.service_token) : void 0
1307
1428
  };
1308
1429
  }
1430
+ function errorTrackingConfig(config, environment) {
1431
+ const tracking = config.error_tracking;
1432
+ if (!tracking) return void 0;
1433
+ return {
1434
+ provider: tracking.provider,
1435
+ host: tracking.host,
1436
+ projectAPIKey: configuredText(environment, tracking.project_api_key)
1437
+ };
1438
+ }
1309
1439
  /** Hard limits, whatever a plan allows; each lives in the section it limits. */
1310
1440
  function technicalLimits(config) {
1311
1441
  return {
@@ -1362,6 +1492,7 @@ function parseCloudDeploymentConfig(input, environment) {
1362
1492
  ...emailConfig(config, environment),
1363
1493
  ...workerConfig(config),
1364
1494
  ...serviceConfig(config, environment),
1495
+ errorTracking: errorTrackingConfig(config, environment),
1365
1496
  technicalLimits: technicalLimits(config)
1366
1497
  });
1367
1498
  }
@@ -2027,8 +2158,9 @@ function createUserPictures(database, options) {
2027
2158
  * documents and workspaces with, and the desktop app shows them from another origin.
2028
2159
  */
2029
2160
  function createPictureRoutes(pictures) {
2030
- return new Hono().get(`${PICTURE_PATH}/:userId/:version`, async (context) => {
2031
- const picture = await pictures.read(context.req.param("userId"), context.req.param("version"));
2161
+ return new Hono().get(`${PICTURE_PATH}/:userId/:version`, pictureParams, async (context) => {
2162
+ const { userId, version } = context.req.valid("param");
2163
+ const picture = await pictures.read(userId, version);
2032
2164
  if (!picture) return context.json({ error: { code: "not_found" } }, 404);
2033
2165
  context.header("Cache-Control", "public, max-age=86400");
2034
2166
  context.header("Content-Type", `image/${picture.format}`);
@@ -3100,62 +3232,46 @@ async function documentResponse(context, respond) {
3100
3232
  function createDocumentRoutes(service, rateLimit) {
3101
3233
  const router = new Hono();
3102
3234
  if (rateLimit) {
3103
- router.use("/workspaces/:workspaceId/documents", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.documentCreation, (context) => context.req.method !== "POST", (context) => context.req.param("workspaceId") ?? "unknown"));
3104
- router.use("/documents/:documentId/images", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.uploadCreation, (context) => context.req.method !== "POST", (context) => context.req.param("documentId") ?? "unknown"));
3105
- router.use("/documents/:documentId/uploads", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.uploadCreation, (context) => context.req.method !== "POST", (context) => context.req.param("documentId") ?? "unknown"));
3235
+ router.use("/workspaces/:workspaceId/documents", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.documentCreation, routeParamResource("workspaceId"), (context) => context.req.method !== "POST"));
3236
+ router.use("/documents/:documentId/images", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.uploadCreation, routeParamResource("documentId"), (context) => context.req.method !== "POST"));
3237
+ router.use("/documents/:documentId/uploads", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.uploadCreation, routeParamResource("documentId"), (context) => context.req.method !== "POST"));
3106
3238
  }
3107
- return router.get("/shared-documents", async (context) => context.json({ documents: await service.listShared(context.get("actor").userId) })).get("/workspaces/:workspaceId/documents", async (context) => {
3108
- const documents = await service.list(context.get("actor").userId, context.req.param("workspaceId"));
3239
+ return router.get("/shared-documents", async (context) => context.json({ documents: await service.listShared(context.get("actor").userId) })).get("/workspaces/:workspaceId/documents", workspaceParams, async (context) => {
3240
+ const documents = await service.list(context.get("actor").userId, context.req.valid("param").workspaceId);
3109
3241
  if (!documents) return context.json({ error: { code: "not_found" } }, 404);
3110
3242
  return context.json({ documents });
3111
- }).get("/workspaces/:workspaceId/usage", async (context) => {
3243
+ }).get("/workspaces/:workspaceId/usage", workspaceParams, async (context) => {
3112
3244
  try {
3113
- return context.json({ usage: await service.usage(context.get("actor").userId, context.req.param("workspaceId")) });
3245
+ return context.json({ usage: await service.usage(context.get("actor").userId, context.req.valid("param").workspaceId) });
3114
3246
  } catch (error) {
3115
3247
  const response = documentDomainError(context, error);
3116
3248
  if (response) return response;
3117
3249
  throw error;
3118
3250
  }
3119
- }).post("/workspaces/:workspaceId/documents", validatedJSON(parseCreateDocument), async (context) => {
3251
+ }).post("/workspaces/:workspaceId/documents", workspaceParams, validatedJSON(parseCreateDocument), async (context) => {
3120
3252
  try {
3121
- const document = await service.create(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json"));
3253
+ const document = await service.create(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("json"));
3122
3254
  return context.json({ document }, 201);
3123
3255
  } catch (error) {
3124
3256
  const response = documentDomainError(context, error);
3125
3257
  if (response) return response;
3126
3258
  throw error;
3127
3259
  }
3128
- }).delete("/documents/:documentId", async (context) => {
3260
+ }).delete("/documents/:documentId", documentParams, async (context) => {
3129
3261
  try {
3130
- await service.remove(context.get("actor").userId, context.req.param("documentId"));
3262
+ await service.remove(context.get("actor").userId, context.req.valid("param").documentId);
3131
3263
  return context.body(null, 204);
3132
3264
  } catch (error) {
3133
3265
  const response = documentDomainError(context, error);
3134
3266
  if (response) return response;
3135
3267
  throw error;
3136
3268
  }
3137
- }).get("/documents/:documentId/access", async (context) => {
3138
- try {
3139
- return context.json({ access: await service.access(context.get("actor").userId, context.req.param("documentId")) });
3140
- } catch (error) {
3141
- const response = documentDomainError(context, error);
3142
- if (response) return response;
3143
- throw error;
3144
- }
3145
- }).get("/documents/:documentId", async (context) => {
3146
- try {
3147
- return context.json({ document: await service.download(context.get("actor").userId, context.req.param("documentId")) });
3148
- } catch (error) {
3149
- const response = documentDomainError(context, error);
3150
- if (response) return response;
3151
- throw error;
3152
- }
3153
- }).post("/documents/:documentId/uploads", validatedJSON(parseCreateUpload), (context) => documentResponse(context, async () => context.json(await service.createUpload(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/documents/:documentId/images/commit", validatedJSON(parseCommitImageUploads), (context) => documentResponse(context, async () => {
3154
- await service.commitImageUploads(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json").uploads);
3269
+ }).get("/documents/:documentId/access", documentParams, (context) => documentResponse(context, async () => context.json({ access: await service.access(context.get("actor").userId, context.req.valid("param").documentId) }))).get("/documents/:documentId", documentParams, (context) => documentResponse(context, async () => context.json({ document: await service.download(context.get("actor").userId, context.req.valid("param").documentId) }))).post("/documents/:documentId/uploads", documentParams, validatedJSON(parseCreateUpload), (context) => documentResponse(context, async () => context.json(await service.createUpload(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json")), 201))).post("/documents/:documentId/images/commit", documentParams, validatedJSON(parseCommitImageUploads), (context) => documentResponse(context, async () => {
3270
+ await service.commitImageUploads(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json").uploads);
3155
3271
  return context.body(null, 204);
3156
- })).post("/documents/:documentId/images/links", validatedJSON(parseRequestImageLinks), (context) => documentResponse(context, async () => context.json(await service.imageLinks(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json").checksums)))).post("/documents/:documentId/images", validatedJSON(parseRequestImageUploads), (context) => documentResponse(context, async () => context.json(await service.requestImageUploads(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/uploads/:uploadId/commit", validatedJSON(parseCommitUpload), async (context) => {
3272
+ })).post("/documents/:documentId/images/links", documentParams, validatedJSON(parseRequestImageLinks), (context) => documentResponse(context, async () => context.json(await service.imageLinks(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json").checksums)))).post("/documents/:documentId/images", documentParams, validatedJSON(parseRequestImageUploads), (context) => documentResponse(context, async () => context.json(await service.requestImageUploads(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json")), 201))).post("/uploads/:uploadId/commit", uploadParams, validatedJSON(parseCommitUpload), async (context) => {
3157
3273
  try {
3158
- const document = await service.commitUpload(context.get("actor").userId, context.req.param("uploadId"), context.req.valid("json"));
3274
+ const document = await service.commitUpload(context.get("actor").userId, context.req.valid("param").uploadId, context.req.valid("json"));
3159
3275
  return context.json({ document });
3160
3276
  } catch (error) {
3161
3277
  const response = documentDomainError(context, error);
@@ -3167,11 +3283,15 @@ function createDocumentRoutes(service, rateLimit) {
3167
3283
  //#endregion
3168
3284
  //#region src/server/cleanup/objects.ts
3169
3285
  /**
3170
- * No revision refers to the stored file any more, and no workspace keeps it as an image, so it
3171
- * can leave the object store.
3286
+ * No revision refers to the stored file any more, no workspace keeps it as an image, and no
3287
+ * collaboration room keeps it as its snapshot, so it can leave the object store.
3172
3288
  */
3173
3289
  function unreferencedObject(expression) {
3174
- return expression.and([expression.not(expression.exists(expression.selectFrom("documentRevision").select("documentRevision.id").whereRef("documentRevision.storageObjectId", "=", "storageObject.id"))), expression.not(expression.exists(expression.selectFrom("workspaceImage").select("workspaceImage.checksum").whereRef("workspaceImage.storageObjectId", "=", "storageObject.id")))]);
3290
+ return expression.and([
3291
+ expression.not(expression.exists(expression.selectFrom("documentRevision").select("documentRevision.id").whereRef("documentRevision.storageObjectId", "=", "storageObject.id"))),
3292
+ expression.not(expression.exists(expression.selectFrom("workspaceImage").select("workspaceImage.checksum").whereRef("workspaceImage.storageObjectId", "=", "storageObject.id"))),
3293
+ expression.not(expression.exists(expression.selectFrom("documentRoomSnapshot").select("documentRoomSnapshot.documentId").whereRef("documentRoomSnapshot.snapshotObjectId", "=", "storageObject.id")))
3294
+ ]);
3175
3295
  }
3176
3296
  //#endregion
3177
3297
  //#region src/server/cleanup/documents.ts
@@ -3514,6 +3634,11 @@ async function historyStart(policy, deploymentMode, workspaceId, now) {
3514
3634
  /** How long a save between versions is kept before compaction may delete it. */
3515
3635
  const REVISION_COMPACTION_GRACE_MS = 864e5;
3516
3636
  /**
3637
+ * How long a stored file nothing refers to is left alone: a collaboration room records its next
3638
+ * snapshot's file before writing it and points the room at it moments later.
3639
+ */
3640
+ const OBJECT_SWEEP_GRACE_MS = 9e5;
3641
+ /**
3517
3642
  * Keeps a document's stored history to its versions. A save that is neither the document's
3518
3643
  * current state nor kept by a version is deleted once it is older than the grace period, and its
3519
3644
  * file with it when nothing else uses it; a workspace without full history first loses the
@@ -3569,8 +3694,8 @@ function createRevisionCompactionService(database, objects, options = {}) {
3569
3694
  });
3570
3695
  }
3571
3696
  /** Deletes freed files from the object store, then their rows; a failure stays for next time. */
3572
- async function sweepObjects(batchSize, result) {
3573
- const freed = await unreferencedObjects(database).select(["id", "objectKey"]).limit(batchSize).execute();
3697
+ async function sweepObjects(now, batchSize, result) {
3698
+ const freed = await unreferencedObjects(database).select(["id", "objectKey"]).where("createdAt", "<", /* @__PURE__ */ new Date(now.getTime() - OBJECT_SWEEP_GRACE_MS)).limit(batchSize).execute();
3574
3699
  for (const object of freed) try {
3575
3700
  await objects.delete(object.objectKey);
3576
3701
  await database.deleteFrom("storageObject").where("id", "=", object.id).where(unreferencedObject).execute();
@@ -3611,7 +3736,7 @@ function createRevisionCompactionService(database, objects, options = {}) {
3611
3736
  } catch {
3612
3737
  result.failed++;
3613
3738
  }
3614
- await sweepObjects(input.batchSize, result);
3739
+ await sweepObjects(now, input.batchSize, result);
3615
3740
  return result;
3616
3741
  } };
3617
3742
  }
@@ -3838,7 +3963,7 @@ async function writableDocument(database, options, userId, documentId) {
3838
3963
  }
3839
3964
  //#endregion
3840
3965
  //#region src/server/documents/repository.ts
3841
- const uuidSchema$1 = v.pipe(v.string(), v.uuid());
3966
+ const uuidSchema = v.pipe(v.string(), v.uuid());
3842
3967
  async function workspaceRole(database, userId, workspaceId) {
3843
3968
  return (await database.selectFrom("workspaceMember").select("role").where("workspaceId", "=", workspaceId).where("userId", "=", userId).executeTakeFirst())?.role;
3844
3969
  }
@@ -3871,7 +3996,7 @@ async function listSharedDocuments(database, userId) {
3871
3996
  "documentGrant.createdAt as sharedAt",
3872
3997
  "documentGrant.createdBy"
3873
3998
  ]).where("documentGrant.userId", "=", userId).where("documentGrant.revokedAt", "is", null).where("document.deletedAt", "is", null).where((expression) => expression.not(expression.exists(expression.selectFrom("workspaceMember").select("workspaceMember.userId").whereRef("workspaceMember.workspaceId", "=", "document.workspaceId").where("workspaceMember.userId", "=", userId)))).orderBy("document.updatedAt", "desc").execute();
3874
- const granters = uniq(rows.map((row) => row.createdBy)).filter((id) => v.is(uuidSchema$1, id));
3999
+ const granters = uniq(rows.map((row) => row.createdBy)).filter((id) => v.is(uuidSchema, id));
3875
4000
  const names = new Map(granters.length === 0 ? [] : (await database.selectFrom("user").select(["id", "name"]).where("id", "in", granters).execute()).map((user) => [user.id, user.name]));
3876
4001
  return rows.map(({ workspaceName, permission, sharedAt, createdBy, ...row }) => {
3877
4002
  const sharedByName = names.get(createdBy);
@@ -5317,15 +5442,15 @@ async function shareActor(request, resolveSession) {
5317
5442
  //#endregion
5318
5443
  //#region src/server/sharing/document-routes.ts
5319
5444
  function createPublicDocumentRoutes(sharing, documents, resolveSession) {
5320
- return new Hono().post("/shares/:shareId/document", validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => {
5321
- const resolution = await sharing.resolveShare(context.req.param("shareId"), context.req.valid("json"), await shareActor(context.req.raw, resolveSession));
5445
+ return new Hono().post("/shares/:shareId/document", shareParams, validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => {
5446
+ const resolution = await sharing.resolveShare(context.req.valid("param").shareId, context.req.valid("json"), await shareActor(context.req.raw, resolveSession));
5322
5447
  return context.json({
5323
5448
  resolution,
5324
5449
  document: await documents.downloadShared(resolution.documentId)
5325
5450
  });
5326
- })).post("/shares/:shareId/images", validatedJSON(parseRequestSharedImageLinks), (context) => sharingRoute(context, async () => {
5451
+ })).post("/shares/:shareId/images", shareParams, validatedJSON(parseRequestSharedImageLinks), (context) => sharingRoute(context, async () => {
5327
5452
  const { checksums, ...share } = context.req.valid("json");
5328
- const resolution = await sharing.resolveShare(context.req.param("shareId"), share, await shareActor(context.req.raw, resolveSession));
5453
+ const resolution = await sharing.resolveShare(context.req.valid("param").shareId, share, await shareActor(context.req.raw, resolveSession));
5329
5454
  return context.json(await documents.imageLinksShared(resolution.documentId, checksums));
5330
5455
  }));
5331
5456
  }
@@ -5492,20 +5617,20 @@ function createInvitationService(database, options) {
5492
5617
  //#region src/server/sharing/routes.ts
5493
5618
  function createDocumentSharingRoutes(service, rateLimit) {
5494
5619
  const router = new Hono();
5495
- if (rateLimit) router.use("/documents/:documentId/invitations", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.method !== "POST", (context) => context.req.param("documentId") ?? "unknown"));
5496
- return router.post("/documents/:documentId/users/lookup", validatedJSON(parseLookupCloudUser), (context) => sharingRoute(context, async () => context.json({ user: await service.lookupUser(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")) }))).get("/documents/:documentId/users/:userId", (context) => sharingRoute(context, async () => context.json({ user: await service.userProfile(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId")) }))).get("/documents/:documentId/shares", (context) => sharingRoute(context, async () => context.json({ shares: await service.listShares(context.get("actor").userId, context.req.param("documentId")) }))).post("/documents/:documentId/shares", validatedJSON(parseCreateDocumentShare), (context) => sharingRoute(context, async () => context.json(await service.createShare(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).patch("/documents/:documentId/shares/:shareId", validatedJSON(parseUpdateDocumentShare), (context) => sharingRoute(context, async () => context.json({ share: await service.updateShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"), context.req.valid("json")) }))).post("/documents/:documentId/shares/:shareId/rotate", (context) => sharingRoute(context, async () => context.json(await service.rotateShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"))))).delete("/documents/:documentId/shares/:shareId", (context) => sharingRoute(context, async () => {
5497
- await service.revokeShare(context.get("actor").userId, context.req.param("documentId"), context.req.param("shareId"));
5620
+ if (rateLimit) router.use("/documents/:documentId/invitations", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, routeParamResource("documentId"), (context) => context.req.method !== "POST"));
5621
+ return router.post("/documents/:documentId/users/lookup", documentParams, validatedJSON(parseLookupCloudUser), (context) => sharingRoute(context, async () => context.json({ user: await service.lookupUser(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json")) }))).get("/documents/:documentId/users/:userId", documentUserParams, (context) => sharingRoute(context, async () => context.json({ user: await service.userProfile(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").userId) }))).get("/documents/:documentId/shares", documentParams, (context) => sharingRoute(context, async () => context.json({ shares: await service.listShares(context.get("actor").userId, context.req.valid("param").documentId) }))).post("/documents/:documentId/shares", documentParams, validatedJSON(parseCreateDocumentShare), (context) => sharingRoute(context, async () => context.json(await service.createShare(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json")), 201))).patch("/documents/:documentId/shares/:shareId", documentShareParams, validatedJSON(parseUpdateDocumentShare), (context) => sharingRoute(context, async () => context.json({ share: await service.updateShare(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").shareId, context.req.valid("json")) }))).post("/documents/:documentId/shares/:shareId/rotate", documentShareParams, (context) => sharingRoute(context, async () => context.json(await service.rotateShare(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").shareId)))).delete("/documents/:documentId/shares/:shareId", documentShareParams, (context) => sharingRoute(context, async () => {
5622
+ await service.revokeShare(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").shareId);
5498
5623
  return context.body(null, 204);
5499
- })).get("/documents/:documentId/grants", (context) => sharingRoute(context, async () => context.json({ grants: await service.listGrants(context.get("actor").userId, context.req.param("documentId")) }))).put("/documents/:documentId/grants/:userId", validatedJSON(parsePutDocumentGrant), (context) => sharingRoute(context, async () => context.json({ grant: await service.putGrant(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId"), context.req.valid("json")) }))).delete("/documents/:documentId/grants/:userId", (context) => sharingRoute(context, async () => {
5500
- await service.revokeGrant(context.get("actor").userId, context.req.param("documentId"), context.req.param("userId"));
5624
+ })).get("/documents/:documentId/grants", documentParams, (context) => sharingRoute(context, async () => context.json({ grants: await service.listGrants(context.get("actor").userId, context.req.valid("param").documentId) }))).put("/documents/:documentId/grants/:userId", documentUserParams, validatedJSON(parsePutDocumentGrant), (context) => sharingRoute(context, async () => context.json({ grant: await service.putGrant(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").userId, context.req.valid("json")) }))).delete("/documents/:documentId/grants/:userId", documentUserParams, (context) => sharingRoute(context, async () => {
5625
+ await service.revokeGrant(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").userId);
5501
5626
  return context.body(null, 204);
5502
- })).get("/documents/:documentId/invitations", (context) => sharingRoute(context, async () => context.json({ invitations: await service.listInvitations(context.get("actor").userId, context.req.param("documentId")) }))).post("/documents/:documentId/invitations", validatedJSON(parseCreateDocumentInvitation), (context) => sharingRoute(context, async () => context.json(await service.createInvitation(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")), 201))).post("/invitations/:invitationId/accept", validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ accepted: await service.acceptInvitation(context.get("actor"), context.req.param("invitationId"), context.req.valid("json")) }))).delete("/documents/:documentId/invitations/:invitationId", (context) => sharingRoute(context, async () => {
5503
- await service.revokeInvitation(context.get("actor").userId, context.req.param("documentId"), context.req.param("invitationId"));
5627
+ })).get("/documents/:documentId/invitations", documentParams, (context) => sharingRoute(context, async () => context.json({ invitations: await service.listInvitations(context.get("actor").userId, context.req.valid("param").documentId) }))).post("/documents/:documentId/invitations", documentParams, validatedJSON(parseCreateDocumentInvitation), (context) => sharingRoute(context, async () => context.json(await service.createInvitation(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json")), 201))).post("/invitations/:invitationId/accept", invitationParams, validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ accepted: await service.acceptInvitation(context.get("actor"), context.req.valid("param").invitationId, context.req.valid("json")) }))).delete("/documents/:documentId/invitations/:invitationId", documentInvitationParams, (context) => sharingRoute(context, async () => {
5628
+ await service.revokeInvitation(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").invitationId);
5504
5629
  return context.body(null, 204);
5505
5630
  }));
5506
5631
  }
5507
5632
  function createPublicSharingRoutes(service, resolveSession) {
5508
- return new Hono().post("/invitations/continuations", validatedJSON(parseCreateInvitationContinuation), (context) => sharingRoute(context, async () => context.json(await service.createInvitationContinuation(context.req.valid("json")), 201))).post("/invitations/continuations/:continuationId/consume", (context) => sharingRoute(context, async () => context.json(await service.consumeInvitationContinuation(context.req.param("continuationId"))))).post("/invitations/:invitationId/preview", validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ invitation: await service.previewInvitation(context.req.param("invitationId"), context.req.valid("json")) }))).post("/shares/:shareId/resolve", validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => context.json({ resolution: await service.resolveShare(context.req.param("shareId"), context.req.valid("json"), await shareActor(context.req.raw, resolveSession)) })));
5633
+ return new Hono().post("/invitations/continuations", validatedJSON(parseCreateInvitationContinuation), (context) => sharingRoute(context, async () => context.json(await service.createInvitationContinuation(context.req.valid("json")), 201))).post("/invitations/continuations/:continuationId/consume", invitationContinuationParams, (context) => sharingRoute(context, async () => context.json(await service.consumeInvitationContinuation(context.req.valid("param").continuationId)))).post("/invitations/:invitationId/preview", invitationParams, validatedJSON(parseAcceptDocumentInvitation), (context) => sharingRoute(context, async () => context.json({ invitation: await service.previewInvitation(context.req.valid("param").invitationId, context.req.valid("json")) }))).post("/shares/:shareId/resolve", shareParams, validatedJSON(parseResolveDocumentShare), (context) => sharingRoute(context, async () => context.json({ resolution: await service.resolveShare(context.req.valid("param").shareId, context.req.valid("json"), await shareActor(context.req.raw, resolveSession)) })));
5509
5634
  }
5510
5635
  //#endregion
5511
5636
  //#region src/server/sharing/service.ts
@@ -5552,10 +5677,10 @@ function notFound(context, error) {
5552
5677
  }
5553
5678
  function createCollaborationRoutes(service, rateLimit) {
5554
5679
  const router = new Hono();
5555
- if (rateLimit) router.use("/documents/:documentId/collaboration-ticket", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.collaborationTicket, void 0, (context) => context.req.param("documentId") ?? "unknown-document"));
5556
- return router.post("/documents/:documentId/collaboration-ticket", async (context) => {
5680
+ if (rateLimit) router.use("/documents/:documentId/collaboration-ticket", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.collaborationTicket, routeParamResource("documentId")));
5681
+ return router.post("/documents/:documentId/collaboration-ticket", documentParams, async (context) => {
5557
5682
  try {
5558
- return context.json({ ticket: await service.issueUserTicket(context.get("actor"), context.req.param("documentId")) });
5683
+ return context.json({ ticket: await service.issueUserTicket(context.get("actor"), context.req.valid("param").documentId) });
5559
5684
  } catch (error) {
5560
5685
  const response = notFound(context, error);
5561
5686
  if (response) return response;
@@ -5564,9 +5689,9 @@ function createCollaborationRoutes(service, rateLimit) {
5564
5689
  });
5565
5690
  }
5566
5691
  function createPublicCollaborationRoutes(service, resolveSession) {
5567
- return new Hono().post("/shares/:shareId/collaboration-ticket", validatedJSON(parseResolveDocumentShare), async (context) => {
5692
+ return new Hono().post("/shares/:shareId/collaboration-ticket", shareParams, validatedJSON(parseResolveDocumentShare), async (context) => {
5568
5693
  try {
5569
- return context.json({ ticket: await service.issueShareTicket(context.req.param("shareId"), context.req.valid("json"), resolveSession ? await resolveSession(context.req.raw) ?? void 0 : void 0) });
5694
+ return context.json({ ticket: await service.issueShareTicket(context.req.valid("param").shareId, context.req.valid("json"), resolveSession ? await resolveSession(context.req.raw) ?? void 0 : void 0) });
5570
5695
  } catch (error) {
5571
5696
  const response = notFound(context, error);
5572
5697
  if (response) return response;
@@ -5800,6 +5925,172 @@ function relayDocumentLookups(database, policy, deploymentMode) {
5800
5925
  };
5801
5926
  }
5802
5927
  //#endregion
5928
+ //#region src/server/collaboration/relay/connection.ts
5929
+ /**
5930
+ * A socket's connection: a new one, which presents a ticket before it joins, or one resumed with
5931
+ * the peer it already is. It joins fragmented frames, holds what arrives while a ticket is checked
5932
+ * or the room's document loads, and refreshes tickets.
5933
+ */
5934
+ function openRelayConnection(socket, resumed, relay) {
5935
+ let peer = resumed;
5936
+ /** Read through an object, since it changes across awaits and between messages. */
5937
+ const state = {
5938
+ closed: false,
5939
+ busy: false
5940
+ };
5941
+ const isClosed = () => state.closed;
5942
+ const queued = [];
5943
+ let queuedBytes = 0;
5944
+ const assembler = createRelayClientAssembler(() => peer?.authorization.permission === "edit" ? MAX_COLLAB_MESSAGE_BYTES : relay.maximumMessageBytes);
5945
+ const authTimer = resumed ? void 0 : setTimeout(() => socket.close(RELAY_CLOSE.unauthorized, "Expected a collaboration ticket"), relay.authTimeoutMs);
5946
+ async function authenticate(token) {
5947
+ let authorization;
5948
+ try {
5949
+ authorization = await authorizeRelayTicket(token, relay.authSecret);
5950
+ } catch {
5951
+ socket.close(RELAY_CLOSE.unauthorized, "Invalid collaboration ticket");
5952
+ return;
5953
+ }
5954
+ if (relay.documentId !== void 0 && authorization.documentId !== relay.documentId) {
5955
+ socket.close(RELAY_CLOSE.unauthorized, "Ticket is for a different document");
5956
+ return;
5957
+ }
5958
+ if (state.closed) return;
5959
+ if (peer) {
5960
+ const current = peer.authorization;
5961
+ if (authorization.roomId !== current.roomId || principalKey(authorization.principal) !== principalKey(current.principal)) {
5962
+ socket.close(RELAY_CLOSE.unauthorized, "Ticket is for a different room or person");
5963
+ return;
5964
+ }
5965
+ peer.authorization = authorization;
5966
+ relay.refreshed(peer);
5967
+ return;
5968
+ }
5969
+ clearTimeout(authTimer);
5970
+ const admitted = await relay.admit(socket, authorization);
5971
+ if (admitted && isClosed()) relay.depart(admitted);
5972
+ else peer = admitted;
5973
+ }
5974
+ function process(data) {
5975
+ if (data.byteLength > relay.maximumMessageBytes) {
5976
+ socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration message is too large");
5977
+ return;
5978
+ }
5979
+ const assembled = assembler.push(data);
5980
+ if (assembled.type === "partial") return;
5981
+ if (assembled.type === "too-large") {
5982
+ socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration message is too large");
5983
+ return;
5984
+ }
5985
+ const frame = assembled.type === "frame" ? decodeRelayClientFrame(assembled.data) : null;
5986
+ if (!frame) {
5987
+ socket.close(RELAY_CLOSE.protocol, "Malformed collaboration frame");
5988
+ return;
5989
+ }
5990
+ if (frame.type === "auth") {
5991
+ state.busy = true;
5992
+ authenticate(frame.token).catch((error) => {
5993
+ relay.report("Admitting a collaboration peer failed:", error);
5994
+ socket.close(RELAY_CLOSE.protocol, "Could not open the collaboration room");
5995
+ }).finally(() => {
5996
+ state.busy = false;
5997
+ flush();
5998
+ });
5999
+ return;
6000
+ }
6001
+ if (!peer) {
6002
+ socket.close(RELAY_CLOSE.unauthorized, "Expected a collaboration ticket");
6003
+ return;
6004
+ }
6005
+ const delivered = relay.deliver(peer, frame);
6006
+ if (!delivered) return;
6007
+ state.busy = true;
6008
+ delivered.finally(() => {
6009
+ state.busy = false;
6010
+ flush();
6011
+ });
6012
+ }
6013
+ function flush() {
6014
+ while (!state.busy && !state.closed && queued.length > 0) {
6015
+ const next = queued.shift();
6016
+ if (!next) continue;
6017
+ queuedBytes -= next.byteLength;
6018
+ process(next);
6019
+ }
6020
+ }
6021
+ return {
6022
+ receive(data) {
6023
+ if (state.closed) return;
6024
+ queuedBytes += data.byteLength;
6025
+ if (!peer && queuedBytes > relay.maximumMessageBytes) {
6026
+ queued.length = 0;
6027
+ queuedBytes = 0;
6028
+ socket.close(RELAY_CLOSE.messageTooLarge, "Too much sent before joining the room");
6029
+ return;
6030
+ }
6031
+ queued.push(data);
6032
+ flush();
6033
+ },
6034
+ closed() {
6035
+ state.closed = true;
6036
+ queued.length = 0;
6037
+ queuedBytes = 0;
6038
+ clearTimeout(authTimer);
6039
+ if (peer) relay.depart(peer);
6040
+ }
6041
+ };
6042
+ }
6043
+ //#endregion
6044
+ //#region src/server/collaboration/relay/log.ts
6045
+ /**
6046
+ * A room's document as its store saved it, its snapshot with the updates logged after it, and the
6047
+ * log its saves go to. Each room has one writer, the relay holding it, so sequences only grow.
6048
+ */
6049
+ async function openRoomLog(store, room, limits) {
6050
+ const saved = await store.load(room);
6051
+ const document = new Y.Doc();
6052
+ if (saved.snapshot) Y.applyUpdate(document, saved.snapshot);
6053
+ for (const update of saved.updates) Y.applyUpdate(document, update);
6054
+ /** Updates since the last save, which the next one logs. */
6055
+ let pending = [];
6056
+ document.on("update", (update) => pending.push(update));
6057
+ /** The last sequence a save may have written: an append that failed may still have landed. */
6058
+ let sequence = saved.sequence;
6059
+ let loggedCount = saved.updates.length;
6060
+ let loggedBytes = saved.updates.reduce((total, update) => total + update.byteLength, 0);
6061
+ /** Set by a failed save, after which only a snapshot is sure to hold the room. */
6062
+ let compactNext = false;
6063
+ /** The save in flight; the next one waits for it, so two never claim one sequence. */
6064
+ let saving = Promise.resolve();
6065
+ async function write(closing) {
6066
+ const compact = compactNext || loggedCount >= limits.updates || loggedBytes >= limits.bytes || closing && (loggedCount > 0 || pending.length > 0);
6067
+ const batch = pending;
6068
+ pending = [];
6069
+ if (compact) {
6070
+ await store.compact(room, sequence, Y.encodeStateAsUpdate(document));
6071
+ loggedCount = 0;
6072
+ loggedBytes = 0;
6073
+ compactNext = false;
6074
+ } else if (batch.length > 0) {
6075
+ const update = Y.mergeUpdates(batch);
6076
+ sequence += 1;
6077
+ await store.append(room, sequence, update);
6078
+ loggedCount += 1;
6079
+ loggedBytes += update.byteLength;
6080
+ }
6081
+ }
6082
+ return {
6083
+ document,
6084
+ log: { save({ closing = false } = {}) {
6085
+ const run = saving.then(() => write(closing));
6086
+ saving = run.catch(() => {
6087
+ compactNext = true;
6088
+ });
6089
+ return run;
6090
+ } }
6091
+ };
6092
+ }
6093
+ //#endregion
5803
6094
  //#region src/server/collaboration/relay/hub.ts
5804
6095
  /** Messages a viewer may send; their document writes never leave the relay. */
5805
6096
  const VIEWER_ACTIONS = /* @__PURE__ */ new Set([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness]);
@@ -5817,6 +6108,10 @@ function createCollaborationRelay(options) {
5817
6108
  let shuttingDown = false;
5818
6109
  const persistDelayMs = options.persistDelayMs ?? 2e3;
5819
6110
  const persistRetryMs = options.persistRetryMs ?? 3e4;
6111
+ const logLimits = {
6112
+ updates: options.compactAfterUpdates ?? 500,
6113
+ bytes: options.compactAfterBytes ?? 4194304
6114
+ };
5820
6115
  const authTimeoutMs = options.authTimeoutMs ?? 1e4;
5821
6116
  const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error));
5822
6117
  function send(socket, frame) {
@@ -5837,20 +6132,9 @@ function createCollaborationRelay(options) {
5837
6132
  };
5838
6133
  const created = (async () => {
5839
6134
  await closing.get(authorization.roomId);
5840
- const kept = rooms.get(authorization.roomId);
5841
- if (kept) return kept;
5842
- const document = new Y.Doc();
5843
- const state = await options.store.load(identity);
5844
- if (state) Y.applyUpdate(document, state);
5845
- const room = {
5846
- id: authorization.roomId,
5847
- identity,
5848
- document,
5849
- peers: /* @__PURE__ */ new Map(),
5850
- persistTimer: null
5851
- };
5852
- document.on("update", () => schedulePersist(room));
5853
- rooms.set(room.id, room);
6135
+ const room = rooms.get(authorization.roomId) ?? newRoom(authorization.roomId, identity);
6136
+ await contentOf(room);
6137
+ if (!rooms.has(room.id)) rooms.set(room.id, room);
5854
6138
  return room;
5855
6139
  })();
5856
6140
  opening.set(authorization.roomId, created);
@@ -5860,15 +6144,41 @@ function createCollaborationRelay(options) {
5860
6144
  opening.delete(authorization.roomId);
5861
6145
  }
5862
6146
  }
5863
- /** Saves the room's document; false when the store refused it. */
5864
- async function persist(room) {
6147
+ function newRoom(id, identity) {
6148
+ return {
6149
+ id,
6150
+ identity,
6151
+ peers: /* @__PURE__ */ new Map(),
6152
+ persistTimer: null,
6153
+ content: null,
6154
+ loading: null
6155
+ };
6156
+ }
6157
+ /** The room's document and log, loaded from the store the first time something needs them. */
6158
+ function contentOf(room) {
6159
+ if (room.content) return Promise.resolve(room.content);
6160
+ room.loading ??= openRoomLog(options.store, room.identity, logLimits).then((content) => {
6161
+ content.document.on("update", () => schedulePersist(room));
6162
+ room.content = content;
6163
+ return content;
6164
+ }, (error) => {
6165
+ room.loading = null;
6166
+ throw error;
6167
+ });
6168
+ return room.loading;
6169
+ }
6170
+ /** Saves what changed in the room since its last save; false when the store refused it. */
6171
+ async function persist(room, closing = false) {
5865
6172
  if (room.persistTimer) clearTimeout(room.persistTimer);
5866
6173
  room.persistTimer = null;
6174
+ if (!room.content && !closing) return true;
5867
6175
  try {
5868
- await options.store.store(room.identity, Y.encodeStateAsUpdate(room.document));
6176
+ const { log } = await contentOf(room);
6177
+ await log.save({ closing });
5869
6178
  return true;
5870
6179
  } catch (error) {
5871
6180
  report("Saving a collaboration room failed:", error);
6181
+ if (!closing && rooms.get(room.id) === room) room.persistTimer ??= setTimeout(() => void persist(room), persistRetryMs);
5872
6182
  return false;
5873
6183
  }
5874
6184
  }
@@ -5879,7 +6189,7 @@ function createCollaborationRelay(options) {
5879
6189
  * Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as
5880
6190
  * V1 updates; only what peers exchange is V2.
5881
6191
  */
5882
- function applyToRoom(room, peer, namespace, payload) {
6192
+ function applyToRoom(document, peer, namespace, payload) {
5883
6193
  try {
5884
6194
  const update = decodeRoomUpdate(payload, {
5885
6195
  limit: MAX_COLLAB_MESSAGE_BYTES,
@@ -5889,7 +6199,7 @@ function createCollaborationRelay(options) {
5889
6199
  peer.socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration update is too large");
5890
6200
  return false;
5891
6201
  }
5892
- Y.applyUpdateV2(room.document, update, peer.id);
6202
+ Y.applyUpdateV2(document, update, peer.id);
5893
6203
  return true;
5894
6204
  } catch {
5895
6205
  peer.socket.close(RELAY_CLOSE.protocol, "Malformed document update");
@@ -5903,13 +6213,13 @@ function createCollaborationRelay(options) {
5903
6213
  from: from.id,
5904
6214
  payload
5905
6215
  };
5906
- sendAll((target ? [room.peers.get(target)] : [...room.peers.values()].filter((peer) => peer !== from)).flatMap((peer) => peer ? [peer.socket] : []), frame);
6216
+ sendAll(deliverable((target ? [room.peers.get(target)] : [...room.peers.values()].filter((peer) => peer !== from)).flatMap((peer) => peer ? [peer] : [])), frame);
5907
6217
  }
5908
- function handleServerMessage(room, peer, namespace, payload) {
6218
+ function handleServerMessage(document, peer, namespace, payload) {
5909
6219
  if (namespace === COLLAB_ACTIONS.syncStep1) {
5910
6220
  let reply;
5911
6221
  try {
5912
- reply = encodeSyncReply(room.document, payload);
6222
+ reply = encodeSyncReply(document, payload);
5913
6223
  } catch {
5914
6224
  peer.socket.close(RELAY_CLOSE.protocol, "Malformed state vector");
5915
6225
  return;
@@ -5920,28 +6230,73 @@ function createCollaborationRelay(options) {
5920
6230
  from: RELAY_SERVER_PEER,
5921
6231
  payload: reply
5922
6232
  });
5923
- } else if (namespace === COLLAB_ACTIONS.syncReply) applyToRoom(room, peer, namespace, payload);
6233
+ } else if (namespace === COLLAB_ACTIONS.syncReply) applyToRoom(document, peer, namespace, payload);
6234
+ }
6235
+ /** Whether handling a message reads or writes the room's document. */
6236
+ function needsDocument(namespace, target) {
6237
+ if (namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply) return true;
6238
+ return target === "server" && namespace === COLLAB_ACTIONS.syncStep1;
5924
6239
  }
5925
- function handleMessage(room, peer, namespace, target, payload) {
6240
+ function handleMessage(room, document, peer, namespace, target, payload) {
5926
6241
  if (peer.authorization.permission === "view" && !VIEWER_ACTIONS.has(namespace)) return;
5927
6242
  if (namespace === COLLAB_ACTIONS.versions) return;
5928
6243
  let forwarded = payload;
5929
6244
  if (namespace === COLLAB_ACTIONS.awareness) {
5930
6245
  const stamped = stampAwareness(payload, peer.authorization, (clientId) => [...room.peers.values()].some((other) => other !== peer && other.presenceClients.has(clientId)));
6246
+ const known = peer.presenceClients.size;
5931
6247
  for (const clientId of stamped.claimed) peer.presenceClients.add(clientId);
6248
+ if (peer.presenceClients.size !== known) remember(peer);
5932
6249
  if (!stamped.update) return;
5933
6250
  forwarded = stamped.update;
5934
6251
  }
5935
6252
  if (target === "server") {
5936
- handleServerMessage(room, peer, namespace, payload);
6253
+ if (document) handleServerMessage(document, peer, namespace, payload);
5937
6254
  return;
5938
6255
  }
5939
- if ((namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply) && !applyToRoom(room, peer, namespace, payload)) return;
6256
+ if ((namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply) && !(document && applyToRoom(document, peer, namespace, payload))) return;
5940
6257
  forward(room, peer, namespace, target, forwarded);
5941
6258
  }
5942
- function scheduleExpiry(peer) {
5943
- clearTimeout(peer.expiry);
5944
- peer.expiry = setTimeout(() => peer.socket.close(RELAY_CLOSE.expired, "Collaboration ticket expired"), Math.max(0, peer.authorization.expiresAt - Date.now()));
6259
+ /**
6260
+ * Whether the peer's ticket still holds, closing its socket when it lapsed. It is checked when
6261
+ * the relay hears from the peer and before it sends the peer anything, never by a timer, so a
6262
+ * runtime can set an idle relay aside while sockets stay open.
6263
+ */
6264
+ function current(peer) {
6265
+ if (Date.now() < peer.authorization.expiresAt) return true;
6266
+ peer.socket.close(RELAY_CLOSE.expired, "Collaboration ticket expired");
6267
+ return false;
6268
+ }
6269
+ /** The sockets of peers whose tickets still hold. */
6270
+ function deliverable(peers) {
6271
+ return [...peers].filter(current).map((peer) => peer.socket);
6272
+ }
6273
+ function remember(peer) {
6274
+ peer.socket.remember?.({
6275
+ peerId: peer.id,
6276
+ authorization: peer.authorization,
6277
+ presenceClients: [...peer.presenceClients]
6278
+ });
6279
+ }
6280
+ /** Handles a room message from an admitted peer; a promise while the room's document loads. */
6281
+ function deliver(peer, frame) {
6282
+ const room = rooms.get(peer.authorization.roomId);
6283
+ if (!room) {
6284
+ peer.socket.close(RELAY_CLOSE.unauthorized, "Expected a collaboration ticket");
6285
+ return;
6286
+ }
6287
+ if (!current(peer)) return void 0;
6288
+ const { namespace, target, payload } = frame;
6289
+ if (room.content || !needsDocument(namespace, target)) {
6290
+ handleMessage(room, room.content?.document ?? null, peer, namespace, target, payload);
6291
+ return;
6292
+ }
6293
+ return contentOf(room).then(({ document }) => {
6294
+ if (room.peers.get(peer.id) !== peer) return void 0;
6295
+ handleMessage(room, document, peer, namespace, target, payload);
6296
+ }, (error) => {
6297
+ report("Loading a collaboration room failed:", error);
6298
+ peer.socket.close(RELAY_CLOSE.protocol, "Could not open the collaboration room");
6299
+ });
5945
6300
  }
5946
6301
  async function admit(socket, authorization) {
5947
6302
  const limit = await options.maximumParticipants?.(authorization.documentId);
@@ -5968,28 +6323,31 @@ function createCollaborationRelay(options) {
5968
6323
  authorization,
5969
6324
  presenceClients: /* @__PURE__ */ new Set()
5970
6325
  };
5971
- scheduleExpiry(peer);
6326
+ remember(peer);
5972
6327
  send(socket, {
5973
6328
  type: "welcome",
5974
6329
  peerId: peer.id,
5975
6330
  peers: [RELAY_SERVER_PEER, ...room.peers.keys()]
5976
6331
  });
5977
- for (const other of room.peers.values()) send(other.socket, {
6332
+ sendAll(deliverable(room.peers.values()), {
5978
6333
  type: "join",
5979
6334
  peerId: peer.id
5980
6335
  });
5981
6336
  room.peers.set(peer.id, peer);
5982
- if (authorization.permission === "edit") send(socket, {
5983
- type: "message",
5984
- namespace: COLLAB_ACTIONS.syncStep1,
5985
- from: RELAY_SERVER_PEER,
5986
- payload: Y.encodeStateVector(room.document)
5987
- });
6337
+ if (authorization.permission === "edit") {
6338
+ const { document } = await contentOf(room);
6339
+ send(socket, {
6340
+ type: "message",
6341
+ namespace: COLLAB_ACTIONS.syncStep1,
6342
+ from: RELAY_SERVER_PEER,
6343
+ payload: Y.encodeStateVector(document)
6344
+ });
6345
+ }
5988
6346
  return peer;
5989
6347
  }
5990
6348
  async function saveAndClose(room) {
5991
- if (await persist(room) || shuttingDown) {
5992
- room.document.destroy();
6349
+ if (await persist(room, true) || shuttingDown) {
6350
+ room.content?.document.destroy();
5993
6351
  return;
5994
6352
  }
5995
6353
  rooms.set(room.id, room);
@@ -6009,119 +6367,59 @@ function createCollaborationRelay(options) {
6009
6367
  }
6010
6368
  }
6011
6369
  function depart(peer) {
6012
- clearTimeout(peer.expiry);
6013
6370
  const room = rooms.get(peer.authorization.roomId);
6014
6371
  if (!room?.peers.delete(peer.id)) return;
6015
- for (const other of room.peers.values()) send(other.socket, {
6372
+ sendAll(deliverable(room.peers.values()), {
6016
6373
  type: "leave",
6017
6374
  peerId: peer.id
6018
6375
  });
6019
6376
  leaveRoom(room);
6020
6377
  }
6378
+ /**
6379
+ * A socket's connection: a new one, which presents a ticket before it joins, or one resumed with
6380
+ * the peer it already is.
6381
+ */
6382
+ const connectionRelay = {
6383
+ authSecret: options.authSecret,
6384
+ documentId: options.documentId,
6385
+ maximumMessageBytes: options.maximumMessageBytes,
6386
+ authTimeoutMs,
6387
+ admit,
6388
+ refreshed: remember,
6389
+ deliver,
6390
+ depart,
6391
+ report
6392
+ };
6021
6393
  return {
6022
6394
  connect(socket) {
6023
- let peer = null;
6024
- /** Read through an object, since it changes across awaits and between messages. */
6025
- const state = {
6026
- closed: false,
6027
- authenticating: false
6395
+ return openRelayConnection(socket, null, connectionRelay);
6396
+ },
6397
+ /**
6398
+ * Takes back a socket whose peer was admitted before the runtime set the relay aside, as the
6399
+ * peer it was, without loading the room's document until a message needs it. A peer whose
6400
+ * ticket lapsed meanwhile is closed.
6401
+ */
6402
+ resume(socket, saved) {
6403
+ const { authorization } = saved;
6404
+ const identity = {
6405
+ documentId: authorization.documentId,
6406
+ roomEpoch: authorization.roomEpoch
6028
6407
  };
6029
- const isClosed = () => state.closed;
6030
- const queued = [];
6031
- let queuedBytes = 0;
6032
- const assembler = createRelayClientAssembler(() => peer?.authorization.permission === "edit" ? MAX_COLLAB_MESSAGE_BYTES : options.maximumMessageBytes);
6033
- const authTimer = setTimeout(() => socket.close(RELAY_CLOSE.unauthorized, "Expected a collaboration ticket"), authTimeoutMs);
6034
- async function authenticate(token) {
6035
- let authorization;
6036
- try {
6037
- authorization = await authorizeRelayTicket(token, options.authSecret);
6038
- } catch {
6039
- socket.close(RELAY_CLOSE.unauthorized, "Invalid collaboration ticket");
6040
- return;
6041
- }
6042
- if (options.documentId !== void 0 && authorization.documentId !== options.documentId) {
6043
- socket.close(RELAY_CLOSE.unauthorized, "Ticket is for a different document");
6044
- return;
6045
- }
6046
- if (state.closed) return;
6047
- if (peer) {
6048
- const current = peer.authorization;
6049
- if (authorization.roomId !== current.roomId || principalKey(authorization.principal) !== principalKey(current.principal)) {
6050
- socket.close(RELAY_CLOSE.unauthorized, "Ticket is for a different room or person");
6051
- return;
6052
- }
6053
- peer.authorization = authorization;
6054
- scheduleExpiry(peer);
6055
- return;
6056
- }
6057
- clearTimeout(authTimer);
6058
- const admitted = await admit(socket, authorization);
6059
- if (admitted && isClosed()) depart(admitted);
6060
- else peer = admitted;
6408
+ let room = rooms.get(authorization.roomId);
6409
+ if (!room) {
6410
+ room = newRoom(authorization.roomId, identity);
6411
+ rooms.set(room.id, room);
6061
6412
  }
6062
- function process(data) {
6063
- if (data.byteLength > options.maximumMessageBytes) {
6064
- socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration message is too large");
6065
- return;
6066
- }
6067
- const assembled = assembler.push(data);
6068
- if (assembled.type === "partial") return;
6069
- if (assembled.type === "too-large") {
6070
- socket.close(RELAY_CLOSE.messageTooLarge, "Collaboration message is too large");
6071
- return;
6072
- }
6073
- const frame = assembled.type === "frame" ? decodeRelayClientFrame(assembled.data) : null;
6074
- if (!frame) {
6075
- socket.close(RELAY_CLOSE.protocol, "Malformed collaboration frame");
6076
- return;
6077
- }
6078
- if (frame.type === "auth") {
6079
- state.authenticating = true;
6080
- authenticate(frame.token).catch((error) => {
6081
- report("Admitting a collaboration peer failed:", error);
6082
- socket.close(RELAY_CLOSE.protocol, "Could not open the collaboration room");
6083
- }).finally(() => {
6084
- state.authenticating = false;
6085
- flush();
6086
- });
6087
- return;
6088
- }
6089
- const room = peer && rooms.get(peer.authorization.roomId);
6090
- if (!peer || !room) {
6091
- socket.close(RELAY_CLOSE.unauthorized, "Expected a collaboration ticket");
6092
- return;
6093
- }
6094
- handleMessage(room, peer, frame.namespace, frame.target, frame.payload);
6095
- }
6096
- function flush() {
6097
- while (!state.authenticating && !state.closed && queued.length > 0) {
6098
- const next = queued.shift();
6099
- if (!next) continue;
6100
- queuedBytes -= next.byteLength;
6101
- process(next);
6102
- }
6103
- }
6104
- return {
6105
- receive(data) {
6106
- if (state.closed) return;
6107
- queuedBytes += data.byteLength;
6108
- if (!peer && queuedBytes > options.maximumMessageBytes) {
6109
- queued.length = 0;
6110
- queuedBytes = 0;
6111
- socket.close(RELAY_CLOSE.messageTooLarge, "Too much sent before joining the room");
6112
- return;
6113
- }
6114
- queued.push(data);
6115
- flush();
6116
- },
6117
- closed() {
6118
- state.closed = true;
6119
- queued.length = 0;
6120
- queuedBytes = 0;
6121
- clearTimeout(authTimer);
6122
- if (peer) depart(peer);
6123
- }
6413
+ const peer = {
6414
+ id: saved.peerId,
6415
+ socket,
6416
+ authorization,
6417
+ presenceClients: new Set(saved.presenceClients)
6124
6418
  };
6419
+ room.peers.set(peer.id, peer);
6420
+ const connection = openRelayConnection(socket, peer, connectionRelay);
6421
+ queueMicrotask(() => current(peer));
6422
+ return connection;
6125
6423
  },
6126
6424
  /**
6127
6425
  * Ends a restored document's rooms: everyone in them is told the document was restored, and
@@ -6132,12 +6430,9 @@ function createCollaborationRelay(options) {
6132
6430
  if (room.identity.documentId !== documentId) continue;
6133
6431
  rooms.delete(room.id);
6134
6432
  if (room.persistTimer) clearTimeout(room.persistTimer);
6135
- for (const peer of room.peers.values()) {
6136
- clearTimeout(peer.expiry);
6137
- peer.socket.close(RELAY_CLOSE.restored, "The document was restored");
6138
- }
6433
+ for (const peer of room.peers.values()) peer.socket.close(RELAY_CLOSE.restored, "The document was restored");
6139
6434
  room.peers.clear();
6140
- room.document.destroy();
6435
+ room.content?.document.destroy();
6141
6436
  }
6142
6437
  },
6143
6438
  /** Tells everyone in a document's rooms that its version history changed. */
@@ -6148,16 +6443,13 @@ function createCollaborationRelay(options) {
6148
6443
  from: RELAY_SERVER_PEER,
6149
6444
  payload: /* @__PURE__ */ new Uint8Array()
6150
6445
  };
6151
- sendAll([...rooms.values()].filter((room) => room.identity.documentId === documentId).flatMap((room) => [...room.peers.values()].map((peer) => peer.socket)), frame);
6446
+ sendAll(deliverable([...rooms.values()].filter((room) => room.identity.documentId === documentId).flatMap((room) => [...room.peers.values()])), frame);
6152
6447
  },
6153
6448
  /** Saves every open room and closes its sockets, as the runtime shuts down. */
6154
6449
  async close() {
6155
6450
  shuttingDown = true;
6156
6451
  await Promise.all([...rooms.values()].map(async (room) => {
6157
- for (const peer of room.peers.values()) {
6158
- clearTimeout(peer.expiry);
6159
- peer.socket.close(1001, "Server shutting down");
6160
- }
6452
+ for (const peer of room.peers.values()) peer.socket.close(1001, "Server shutting down");
6161
6453
  room.peers.clear();
6162
6454
  await leaveRoom(room);
6163
6455
  }));
@@ -6167,27 +6459,107 @@ function createCollaborationRelay(options) {
6167
6459
  }
6168
6460
  //#endregion
6169
6461
  //#region src/server/collaboration/relay/persistence.ts
6170
- function createCollaborationStateStore(database) {
6462
+ /**
6463
+ * Whether the document is still at the room's epoch, holding its row so a restore, which advances
6464
+ * the epoch and deletes the replaced rooms' rows, waits for this write or this write sees it.
6465
+ */
6466
+ async function holdsEpoch(transaction, room) {
6467
+ return (await transaction.selectFrom("document").select("collaborationEpoch").where("id", "=", room.documentId).forShare().executeTakeFirst())?.collaborationEpoch === room.roomEpoch;
6468
+ }
6469
+ /** A snapshot is a Yjs update, as the store hands it back. */
6470
+ const SNAPSHOT_CONTENT_TYPE = "application/octet-stream";
6471
+ /**
6472
+ * Where a room's snapshots go. Each compaction writes a new file and points the room at it; the one
6473
+ * it replaced is no longer referenced, and the object sweep removes it as it does a deleted
6474
+ * revision's file.
6475
+ */
6476
+ function snapshotKey(room) {
6477
+ return `collaboration/${room.documentId}/${room.roomEpoch}/${crypto.randomUUID()}.yjs`;
6478
+ }
6479
+ /**
6480
+ * A store keeping each room's snapshot as a file in the object store and the updates logged after
6481
+ * it in the database, so the database holds only what changed since the last snapshot.
6482
+ */
6483
+ function createCollaborationStateStore(database, objects) {
6171
6484
  return {
6172
6485
  async load(room) {
6173
- const row = await database.selectFrom("documentCollaborationState").select("state").where("documentId", "=", room.documentId).where("roomEpoch", "=", room.roomEpoch).executeTakeFirst();
6174
- return row ? new Uint8Array(row.state) : null;
6175
- },
6176
- async store(room, state) {
6177
- await database.insertInto("documentCollaborationState").values({
6178
- documentId: room.documentId,
6179
- roomEpoch: room.roomEpoch,
6180
- state,
6181
- updatedAt: /* @__PURE__ */ new Date()
6182
- }).onConflict((conflict) => conflict.columns(["documentId", "roomEpoch"]).doUpdateSet({
6183
- state,
6184
- version: (expression) => expression("documentCollaborationState.version", "+", 1),
6185
- updatedAt: /* @__PURE__ */ new Date()
6186
- })).execute();
6486
+ const snapshot = await database.selectFrom("documentRoomSnapshot").innerJoin("storageObject", "storageObject.id", "documentRoomSnapshot.snapshotObjectId").select(["storageObject.objectKey", "documentRoomSnapshot.throughSequence"]).where("documentRoomSnapshot.documentId", "=", room.documentId).where("documentRoomSnapshot.roomEpoch", "=", room.roomEpoch).executeTakeFirst();
6487
+ const state = snapshot ? await objects.read(snapshot.objectKey) : null;
6488
+ if (snapshot && !state) throw new Error(`The snapshot of room ${room.documentId}:${room.roomEpoch} is missing`);
6489
+ const through = snapshot?.throughSequence ?? 0;
6490
+ const updates = await database.selectFrom("documentRoomUpdate").select(["sequence", "data"]).where("documentId", "=", room.documentId).where("roomEpoch", "=", room.roomEpoch).where("sequence", ">", through).orderBy("sequence").execute();
6491
+ return {
6492
+ snapshot: state,
6493
+ updates: updates.map((row) => new Uint8Array(row.data)),
6494
+ sequence: updates.at(-1)?.sequence ?? through
6495
+ };
6496
+ },
6497
+ async append(room, sequence, update) {
6498
+ await database.transaction().execute(async (transaction) => {
6499
+ if (!await holdsEpoch(transaction, room)) return;
6500
+ await transaction.insertInto("documentRoomUpdate").values({
6501
+ documentId: room.documentId,
6502
+ roomEpoch: room.roomEpoch,
6503
+ sequence,
6504
+ data: update
6505
+ }).execute();
6506
+ });
6507
+ },
6508
+ async compact(room, sequence, state) {
6509
+ const snapshotObjectId = crypto.randomUUID();
6510
+ const objectKey = snapshotKey(room);
6511
+ const checksum = fromUint8Array(sha256(state));
6512
+ await database.insertInto("storageObject").values({
6513
+ id: snapshotObjectId,
6514
+ objectKey,
6515
+ checksum,
6516
+ byteSize: state.byteLength,
6517
+ contentType: SNAPSHOT_CONTENT_TYPE
6518
+ }).execute();
6519
+ await objects.write({
6520
+ key: objectKey,
6521
+ bytes: state,
6522
+ contentType: SNAPSHOT_CONTENT_TYPE,
6523
+ checksum
6524
+ });
6525
+ await database.transaction().execute(async (transaction) => {
6526
+ if (!await holdsEpoch(transaction, room)) return;
6527
+ await transaction.insertInto("documentRoomSnapshot").values({
6528
+ documentId: room.documentId,
6529
+ roomEpoch: room.roomEpoch,
6530
+ snapshotObjectId,
6531
+ throughSequence: sequence,
6532
+ updatedAt: /* @__PURE__ */ new Date()
6533
+ }).onConflict((conflict) => conflict.columns(["documentId", "roomEpoch"]).doUpdateSet({
6534
+ snapshotObjectId,
6535
+ throughSequence: sequence,
6536
+ updatedAt: /* @__PURE__ */ new Date()
6537
+ })).execute();
6538
+ await transaction.deleteFrom("documentRoomUpdate").where("documentId", "=", room.documentId).where("roomEpoch", "=", room.roomEpoch).where("sequence", "<=", sequence).execute();
6539
+ });
6187
6540
  }
6188
6541
  };
6189
6542
  }
6190
6543
  //#endregion
6544
+ //#region src/server/collaboration/relay/resume.ts
6545
+ const peerStateSchema = v.object({
6546
+ peerId: v.pipe(v.string(), v.uuid()),
6547
+ authorization: v.object({
6548
+ roomId: v.string(),
6549
+ documentId: v.pipe(v.string(), v.uuid()),
6550
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
6551
+ permission: v.picklist(["view", "edit"]),
6552
+ principal: collaborationPrincipalSchema,
6553
+ expiresAt: v.number()
6554
+ }),
6555
+ presenceClients: v.array(v.pipe(v.number(), v.integer()))
6556
+ });
6557
+ /** A peer's kept state, or null when what the runtime kept is not one. */
6558
+ function readRelayPeerState(value) {
6559
+ const parsed = v.safeParse(peerStateSchema, value);
6560
+ return parsed.success ? parsed.output : null;
6561
+ }
6562
+ //#endregion
6191
6563
  //#region src/server/documents/versions/routes.ts
6192
6564
  const pageSchema = v.object({
6193
6565
  before: v.optional(v.pipe(v.string(), v.uuid())),
@@ -6205,7 +6577,7 @@ async function answer(context, run) {
6205
6577
  }
6206
6578
  /** A document's version history: listing, naming, opening, restoring, and duplicating versions. */
6207
6579
  function createDocumentVersionRoutes(service) {
6208
- return new Hono().get("/documents/:documentId/versions", validatedQuery(parsePage), (context) => answer(context, async () => context.json(await service.list(context.get("actor").userId, context.req.param("documentId"), context.req.valid("query"))))).post("/documents/:documentId/versions", validatedJSON(parseSaveDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.save(context.get("actor").userId, context.req.param("documentId"), context.req.valid("json")) }, 201))).patch("/documents/:documentId/versions/:versionId", validatedJSON(parseUpdateDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.update(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"), context.req.valid("json")) }))).get("/documents/:documentId/versions/:versionId", (context) => answer(context, async () => context.json(await service.download(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"))))).post("/documents/:documentId/versions/:versionId/restore", (context) => answer(context, async () => context.json(await service.restore(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"))))).post("/documents/:documentId/versions/:versionId/duplicate", validatedJSON(parseDuplicateDocumentVersion), (context) => answer(context, async () => context.json({ document: await service.duplicate(context.get("actor").userId, context.req.param("documentId"), context.req.param("versionId"), context.req.valid("json")) }, 201)));
6580
+ return new Hono().get("/documents/:documentId/versions", documentParams, validatedQuery(parsePage), (context) => answer(context, async () => context.json(await service.list(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("query"))))).post("/documents/:documentId/versions", documentParams, validatedJSON(parseSaveDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.save(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("json")) }, 201))).patch("/documents/:documentId/versions/:versionId", documentVersionParams, validatedJSON(parseUpdateDocumentVersion), (context) => answer(context, async () => context.json({ version: await service.update(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").versionId, context.req.valid("json")) }))).get("/documents/:documentId/versions/:versionId", documentVersionParams, (context) => answer(context, async () => context.json(await service.download(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").versionId)))).post("/documents/:documentId/versions/:versionId/restore", documentVersionParams, (context) => answer(context, async () => context.json(await service.restore(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").versionId)))).post("/documents/:documentId/versions/:versionId/duplicate", documentVersionParams, validatedJSON(parseDuplicateDocumentVersion), (context) => answer(context, async () => context.json({ document: await service.duplicate(context.get("actor").userId, context.req.valid("param").documentId, context.req.valid("param").versionId, context.req.valid("json")) }, 201)));
6209
6581
  }
6210
6582
  //#endregion
6211
6583
  //#region src/server/documents/versions/service.ts
@@ -6392,6 +6764,8 @@ function createDocumentVersionService(database, objects, options = {}) {
6392
6764
  version: (expression) => expression("version", "+", 1),
6393
6765
  collaborationEpoch: (expression) => expression("collaborationEpoch", "+", 1)
6394
6766
  }).where("id", "=", documentId).execute();
6767
+ await transaction.deleteFrom("documentRoomUpdate").where("documentId", "=", documentId).execute();
6768
+ await transaction.deleteFrom("documentRoomSnapshot").where("documentId", "=", documentId).execute();
6395
6769
  await keepRevision(transaction, {
6396
6770
  documentId,
6397
6771
  revisionId,
@@ -6540,8 +6914,8 @@ function createWorkspaceRoutes(service, members, rateLimit) {
6540
6914
  const router = new Hono();
6541
6915
  if (rateLimit) {
6542
6916
  router.use("/", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.workspaceCreation, (context) => context.req.method !== "POST"));
6543
- router.use("/:workspaceId/invitations/:invitationId/resend", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, () => false, (context) => context.req.param("workspaceId") ?? "unknown"));
6544
- router.use("/:workspaceId/invitations", createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, (context) => context.req.method !== "POST", (context) => context.req.param("workspaceId") ?? "unknown"));
6917
+ router.use("/:workspaceId/invitations/:invitationId/resend", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, routeParamResource("workspaceId"), () => false));
6918
+ router.use("/:workspaceId/invitations", createResourceRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.invitationMutation, routeParamResource("workspaceId"), (context) => context.req.method !== "POST"));
6545
6919
  }
6546
6920
  return router.get("/", async (context) => {
6547
6921
  const workspaces = await service.list(context.get("actor").userId);
@@ -6554,21 +6928,21 @@ function createWorkspaceRoutes(service, members, rateLimit) {
6554
6928
  if (error instanceof WorkspaceSlugConflictError) return context.json({ error: { code: "slug_conflict" } }, 409);
6555
6929
  throw error;
6556
6930
  }
6557
- }).get("/:workspaceId", async (context) => {
6558
- const workspace = await service.get(context.get("actor").userId, context.req.param("workspaceId"));
6931
+ }).get("/:workspaceId", workspaceParams, async (context) => {
6932
+ const workspace = await service.get(context.get("actor").userId, context.req.valid("param").workspaceId);
6559
6933
  if (!workspace) return context.json({ error: { code: "not_found" } }, 404);
6560
6934
  return context.json({ workspace });
6561
- }).patch("/:workspaceId", validatedJSON(parseUpdateWorkspace), (context) => memberRoute(context, async () => context.json({ workspace: await members.rename(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json").name) }))).delete("/:workspaceId", (context) => memberRoute(context, async () => {
6562
- await members.delete(context.get("actor").userId, context.req.param("workspaceId"));
6935
+ }).patch("/:workspaceId", workspaceParams, validatedJSON(parseUpdateWorkspace), (context) => memberRoute(context, async () => context.json({ workspace: await members.rename(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("json").name) }))).delete("/:workspaceId", workspaceParams, (context) => memberRoute(context, async () => {
6936
+ await members.delete(context.get("actor").userId, context.req.valid("param").workspaceId);
6563
6937
  return context.body(null, 204);
6564
- })).get("/:workspaceId/members", (context) => memberRoute(context, async () => context.json(await members.list(context.get("actor").userId, context.req.param("workspaceId"))))).post("/:workspaceId/invitations", validatedJSON(parseCreateWorkspaceInvitation), (context) => memberRoute(context, async () => context.json(await members.invite(context.get("actor").userId, context.req.param("workspaceId"), context.req.valid("json")), 201))).post("/:workspaceId/invitations/:invitationId/resend", (context) => memberRoute(context, async () => context.json(await members.resendInvitation(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("invitationId"))))).delete("/:workspaceId/invitations/:invitationId", (context) => memberRoute(context, async () => {
6565
- await members.revokeInvitation(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("invitationId"));
6938
+ })).get("/:workspaceId/members", workspaceParams, (context) => memberRoute(context, async () => context.json(await members.list(context.get("actor").userId, context.req.valid("param").workspaceId)))).post("/:workspaceId/invitations", workspaceParams, validatedJSON(parseCreateWorkspaceInvitation), (context) => memberRoute(context, async () => context.json(await members.invite(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("json")), 201))).post("/:workspaceId/invitations/:invitationId/resend", workspaceInvitationParams, (context) => memberRoute(context, async () => context.json(await members.resendInvitation(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("param").invitationId)))).delete("/:workspaceId/invitations/:invitationId", workspaceInvitationParams, (context) => memberRoute(context, async () => {
6939
+ await members.revokeInvitation(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("param").invitationId);
6566
6940
  return context.body(null, 204);
6567
- })).patch("/:workspaceId/members/:userId", validatedJSON(parseUpdateWorkspaceMember), (context) => memberRoute(context, async () => {
6568
- await members.updateRole(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("userId"), context.req.valid("json").role);
6941
+ })).patch("/:workspaceId/members/:userId", workspaceMemberParams, validatedJSON(parseUpdateWorkspaceMember), (context) => memberRoute(context, async () => {
6942
+ await members.updateRole(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("param").userId, context.req.valid("json").role);
6569
6943
  return context.body(null, 204);
6570
- })).delete("/:workspaceId/members/:userId", (context) => memberRoute(context, async () => {
6571
- await members.remove(context.get("actor").userId, context.req.param("workspaceId"), context.req.param("userId"));
6944
+ })).delete("/:workspaceId/members/:userId", workspaceMemberParams, (context) => memberRoute(context, async () => {
6945
+ await members.remove(context.get("actor").userId, context.req.valid("param").workspaceId, context.req.valid("param").userId);
6572
6946
  return context.body(null, 204);
6573
6947
  }));
6574
6948
  }
@@ -6578,9 +6952,9 @@ function createPublicCloudAPIRouter(services) {
6578
6952
  return new Hono().route("/", createPublicSharingRoutes(services.sharing, services.resolveSession)).route("/", createPublicDocumentRoutes(services.sharing, services.documents, services.resolveSession)).route("/", createPublicCollaborationRoutes(services.collaboration, services.resolveSession));
6579
6953
  }
6580
6954
  function createCloudAPIRouter(services) {
6581
- return new Hono().route("/public", createPublicCloudAPIRouter(services)).get("/workspaces/:workspaceId/entitlements", async (context) => {
6955
+ return new Hono().route("/public", createPublicCloudAPIRouter(services)).get("/workspaces/:workspaceId/entitlements", workspaceParams, async (context) => {
6582
6956
  if (!services.entitlements) return context.json({ error: { code: "not_found" } }, 404);
6583
- return context.json({ entitlements: await services.entitlements.workspace(context.get("actor").userId, context.req.param("workspaceId")) });
6957
+ return context.json({ entitlements: await services.entitlements.workspace(context.get("actor").userId, context.req.valid("param").workspaceId) });
6584
6958
  }).get("/session", (context) => context.json({ user: context.get("actor") })).route("/", createAIRoutes(services.aiTokens, services.database && services.rateLimitSecret ? {
6585
6959
  database: services.database,
6586
6960
  secret: services.rateLimitSecret
@@ -6757,6 +7131,41 @@ function createAccountRoutes(services) {
6757
7131
  });
6758
7132
  }
6759
7133
  //#endregion
7134
+ //#region src/server/errors/index.ts
7135
+ /** Where the server caught an error. */
7136
+ const CLOUD_ERROR_SOURCES = [
7137
+ "request",
7138
+ "background",
7139
+ "cleanup",
7140
+ "email",
7141
+ "relay",
7142
+ "scheduled",
7143
+ "setup"
7144
+ ];
7145
+ /** Logs a caught error and reports it, when the deployment reports errors. */
7146
+ function reportCloudError(reporter, message, error, context) {
7147
+ console.error(`[Cloud] ${message}`, error);
7148
+ return reporter ? reporter(error, context) : Promise.resolve();
7149
+ }
7150
+ function requestContext(context) {
7151
+ return {
7152
+ source: "request",
7153
+ method: context.req.method,
7154
+ route: routePath(context)
7155
+ };
7156
+ }
7157
+ /**
7158
+ * The app's last error handler, as Hono's default: an `HTTPException` answers with its response,
7159
+ * anything else is logged, reported, and answered with a 500.
7160
+ */
7161
+ function cloudErrorHandler(reporter) {
7162
+ return (error, context) => {
7163
+ if (error instanceof HTTPException) return error.getResponse();
7164
+ reportCloudError(reporter, "Request failed:", error, requestContext(context));
7165
+ return context.text("Internal Server Error", 500);
7166
+ };
7167
+ }
7168
+ //#endregion
6760
7169
  //#region src/server/internal/schema.ts
6761
7170
  const setWorkspaceEntitlementsSchema = v.object({
6762
7171
  values: staticEntitlementsSchema,
@@ -6793,7 +7202,6 @@ async setWorkspaceEntitlements(workspaceId, input) {
6793
7202
  }
6794
7203
  //#endregion
6795
7204
  //#region src/server/internal/routes.ts
6796
- const uuidSchema = v.pipe(v.string(), v.uuid());
6797
7205
  /** The internal API on HTTP, for runtimes without a private transport to their services. */
6798
7206
  function createInternalRoutes(service, serviceToken) {
6799
7207
  const digest = hashCapability(serviceToken);
@@ -6803,9 +7211,8 @@ function createInternalRoutes(service, serviceToken) {
6803
7211
  noAuthenticationHeader: { message: unauthorized },
6804
7212
  invalidAuthenticationHeader: { message: unauthorized },
6805
7213
  invalidToken: { message: unauthorized }
6806
- })).put("/workspaces/:workspaceId/entitlements", validatedJSON(parseSetWorkspaceEntitlements), async (context) => {
6807
- const workspaceId = context.req.param("workspaceId");
6808
- if (!v.is(uuidSchema, workspaceId)) return context.json({ error: { code: "not_found" } }, 404);
7214
+ })).put("/workspaces/:workspaceId/entitlements", workspaceParams, validatedJSON(parseSetWorkspaceEntitlements), async (context) => {
7215
+ const { workspaceId } = context.req.valid("param");
6809
7216
  const result = await service.setWorkspaceEntitlements(workspaceId, context.req.valid("json"));
6810
7217
  if (!result.found) return context.json({ error: { code: "not_found" } }, 404);
6811
7218
  return context.json({ applied: result.applied });
@@ -6964,7 +7371,7 @@ function createCloudApp(services) {
6964
7371
  resolveSession
6965
7372
  });
6966
7373
  const internalAPI = services.config.internalServiceToken ? createInternalRoutes(createInternalService(services.database), services.config.internalServiceToken) : new Hono();
6967
- return new Hono().use(CLOUD_DISCOVERY_PATH, cloudCORS).use("/api/*", cloudCORS).use("*", async (context, next) => {
7374
+ return new Hono().onError(cloudErrorHandler(services.reportError)).use(CLOUD_DISCOVERY_PATH, cloudCORS).use("/api/*", cloudCORS).use("*", async (context, next) => {
6968
7375
  await next();
6969
7376
  if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) context.header("X-Robots-Tag", "noindex, nofollow, noarchive");
6970
7377
  }).get("/robots.txt", (context) => {
@@ -7032,11 +7439,11 @@ function addInvitationColumns(table, access) {
7032
7439
  //#endregion
7033
7440
  //#region src/server/db/migrations/001_foundation.ts
7034
7441
  var _001_foundation_exports = /* @__PURE__ */ __exportAll({
7035
- down: () => down$26,
7036
- up: () => up$26
7442
+ down: () => down$27,
7443
+ up: () => up$27
7037
7444
  });
7038
7445
  const UPDATED_AT_TRIGGER = "openpencil_set_updated_at";
7039
- async function up$26(database) {
7446
+ async function up$27(database) {
7040
7447
  await database.schema.createTable("workspace").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("name", "text", (column) => column.notNull()).addColumn("slug", "text", (column) => column.notNull().unique()).addColumn("created_by", "text", (column) => column.notNull()).execute();
7041
7448
  await addCurrentTimestampColumns(database, "workspace", ["created_at", "updated_at"]);
7042
7449
  await database.schema.createTable("workspace_member").addColumn("workspace_id", "uuid", (column) => column.references("workspace.id").onDelete("cascade").notNull()).addColumn("user_id", "text", (column) => column.notNull()).addColumn("role", "text", (column) => column.notNull()).addPrimaryKeyConstraint("workspace_member_primary", ["workspace_id", "user_id"]).addCheckConstraint("workspace_member_role_check", checkColumnIn("role", [
@@ -7073,7 +7480,7 @@ async function up$26(database) {
7073
7480
  for each row execute function ${sql.id(UPDATED_AT_TRIGGER)}()
7074
7481
  `.execute(database);
7075
7482
  }
7076
- async function down$26(database) {
7483
+ async function down$27(database) {
7077
7484
  await database.schema.dropTable("upload").ifExists().execute();
7078
7485
  await database.schema.alterTable("document").dropConstraint("document_current_revision_foreign").execute();
7079
7486
  await database.schema.dropTable("document_revision").ifExists().execute();
@@ -7086,10 +7493,10 @@ async function down$26(database) {
7086
7493
  //#endregion
7087
7494
  //#region src/server/db/migrations/002_upload_cleanup_claims.ts
7088
7495
  var _002_upload_cleanup_claims_exports = /* @__PURE__ */ __exportAll({
7089
- down: () => down$25,
7090
- up: () => up$25
7496
+ down: () => down$26,
7497
+ up: () => up$26
7091
7498
  });
7092
- async function up$25(database) {
7499
+ async function up$26(database) {
7093
7500
  await database.schema.alterTable("upload").addColumn("cleanup_claim_id", "uuid").addColumn("cleanup_claimed_at", "timestamptz").execute();
7094
7501
  await database.schema.alterTable("upload").dropConstraint("upload_status_check").execute();
7095
7502
  await database.schema.alterTable("upload").addCheckConstraint("upload_status_check", checkColumnIn("status", [
@@ -7099,7 +7506,7 @@ async function up$25(database) {
7099
7506
  "abandoned"
7100
7507
  ])).execute();
7101
7508
  }
7102
- async function down$25(database) {
7509
+ async function down$26(database) {
7103
7510
  await database.schema.alterTable("upload").dropConstraint("upload_status_check").execute();
7104
7511
  await database.schema.alterTable("upload").addCheckConstraint("upload_status_check", checkColumnIn("status", [
7105
7512
  "pending",
@@ -7111,24 +7518,24 @@ async function down$25(database) {
7111
7518
  //#endregion
7112
7519
  //#region src/server/db/migrations/003_document_cleanup_claims.ts
7113
7520
  var _003_document_cleanup_claims_exports = /* @__PURE__ */ __exportAll({
7114
- down: () => down$24,
7115
- up: () => up$24
7521
+ down: () => down$25,
7522
+ up: () => up$25
7116
7523
  });
7117
- async function up$24(database) {
7524
+ async function up$25(database) {
7118
7525
  await database.schema.alterTable("document").addColumn("cleanup_claim_id", "uuid").addColumn("cleanup_claimed_at", "timestamptz").execute();
7119
7526
  await database.schema.createIndex("document_cleanup_index").on("document").columns(["deleted_at", "cleanup_claimed_at"]).execute();
7120
7527
  }
7121
- async function down$24(database) {
7528
+ async function down$25(database) {
7122
7529
  await database.schema.dropIndex("document_cleanup_index").ifExists().execute();
7123
7530
  await database.schema.alterTable("document").dropColumn("cleanup_claimed_at").dropColumn("cleanup_claim_id").execute();
7124
7531
  }
7125
7532
  //#endregion
7126
7533
  //#region src/server/db/migrations/004_document_sharing.ts
7127
7534
  var _004_document_sharing_exports = /* @__PURE__ */ __exportAll({
7128
- down: () => down$23,
7129
- up: () => up$23
7535
+ down: () => down$24,
7536
+ up: () => up$24
7130
7537
  });
7131
- async function up$23(database) {
7538
+ async function up$24(database) {
7132
7539
  await database.schema.createTable("document_share").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("document_id", "uuid", (column) => column.references("document.id").onDelete("cascade").notNull()).addColumn("permission", "text", (column) => column.notNull()).addColumn("secret_hash", "text", (column) => column.notNull()).addColumn("room_epoch", "integer", (column) => column.notNull().defaultTo(0)).addColumn("created_by", "text", (column) => column.notNull()).addColumn("expires_at", "timestamptz").addColumn("revoked_at", "timestamptz").addColumn("last_used_at", "timestamptz").addCheckConstraint("document_share_permission_check", checkColumnIn("permission", ["view", "edit"])).execute();
7133
7540
  await addCurrentTimestampColumns(database, "document_share", ["created_at", "updated_at"]);
7134
7541
  await database.schema.createTable("document_grant").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("document_id", "uuid", (column) => column.references("document.id").onDelete("cascade").notNull()).addColumn("user_id", "text", (column) => column.notNull()).addColumn("permission", "text", (column) => column.notNull()).addColumn("created_by", "text", (column) => column.notNull()).addColumn("revoked_at", "timestamptz").addUniqueConstraint("document_grant_document_user_unique", ["document_id", "user_id"]).addCheckConstraint("document_grant_permission_check", checkColumnIn("permission", ["view", "edit"])).execute();
@@ -7139,7 +7546,7 @@ async function up$23(database) {
7139
7546
  await database.schema.createIndex("document_grant_user_index").on("document_grant").columns(["user_id", "document_id"]).execute();
7140
7547
  await database.schema.createIndex("document_invitation_document_index").on("document_invitation").columns(["document_id", "revoked_at"]).execute();
7141
7548
  }
7142
- async function down$23(database) {
7549
+ async function down$24(database) {
7143
7550
  await database.schema.dropTable("document_invitation").ifExists().execute();
7144
7551
  await database.schema.dropTable("document_grant").ifExists().execute();
7145
7552
  await database.schema.dropTable("document_share").ifExists().execute();
@@ -7147,73 +7554,73 @@ async function down$23(database) {
7147
7554
  //#endregion
7148
7555
  //#region src/server/db/migrations/005_document_collaboration_epoch.ts
7149
7556
  var _005_document_collaboration_epoch_exports = /* @__PURE__ */ __exportAll({
7150
- down: () => down$22,
7151
- up: () => up$22
7557
+ down: () => down$23,
7558
+ up: () => up$23
7152
7559
  });
7153
- async function up$22(database) {
7560
+ async function up$23(database) {
7154
7561
  await database.schema.alterTable("document").addColumn("collaborationEpoch", "integer", (column) => column.notNull().defaultTo(0)).execute();
7155
7562
  }
7156
- async function down$22(database) {
7563
+ async function down$23(database) {
7157
7564
  await database.schema.alterTable("document").dropColumn("collaborationEpoch").execute();
7158
7565
  }
7159
7566
  //#endregion
7160
7567
  //#region src/server/db/migrations/006_invitation_continuation.ts
7161
7568
  var _006_invitation_continuation_exports = /* @__PURE__ */ __exportAll({
7162
- down: () => down$21,
7163
- up: () => up$21
7569
+ down: () => down$22,
7570
+ up: () => up$22
7164
7571
  });
7165
- async function up$21(database) {
7572
+ async function up$22(database) {
7166
7573
  await database.schema.createTable("invitationContinuation").addColumn("id", "text", (column) => column.primaryKey()).addColumn("invitationId", "uuid", (column) => column.notNull().references("documentInvitation.id").onDelete("cascade")).addColumn("tokenEncrypted", "text", (column) => column.notNull()).addColumn("expiresAt", "timestamptz", (column) => column.notNull()).addColumn("consumedAt", "timestamptz").addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).execute();
7167
7574
  await database.schema.createIndex("invitationContinuationExpiryIndex").on("invitationContinuation").column("expiresAt").execute();
7168
7575
  }
7169
- async function down$21(database) {
7576
+ async function down$22(database) {
7170
7577
  await database.schema.dropTable("invitationContinuation").execute();
7171
7578
  }
7172
7579
  //#endregion
7173
7580
  //#region src/server/db/migrations/007_collaboration_state.ts
7174
7581
  var _007_collaboration_state_exports = /* @__PURE__ */ __exportAll({
7175
- down: () => down$20,
7176
- up: () => up$20
7582
+ down: () => down$21,
7583
+ up: () => up$21
7177
7584
  });
7178
- async function up$20(database) {
7585
+ async function up$21(database) {
7179
7586
  await database.schema.createTable("documentCollaborationState").addColumn("documentId", "uuid", (column) => column.notNull().references("document.id").onDelete("cascade")).addColumn("roomEpoch", "integer", (column) => column.notNull()).addColumn("state", "bytea", (column) => column.notNull()).addColumn("version", "integer", (column) => column.notNull().defaultTo(1)).addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).addColumn("updatedAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).addPrimaryKeyConstraint("documentCollaborationStatePrimary", ["documentId", "roomEpoch"]).execute();
7180
7587
  }
7181
- async function down$20(database) {
7588
+ async function down$21(database) {
7182
7589
  await database.schema.dropTable("documentCollaborationState").execute();
7183
7590
  }
7184
7591
  //#endregion
7185
7592
  //#region src/server/db/migrations/008_storage_reservations.ts
7186
7593
  var _008_storage_reservations_exports = /* @__PURE__ */ __exportAll({
7187
- down: () => down$19,
7188
- up: () => up$19
7594
+ down: () => down$20,
7595
+ up: () => up$20
7189
7596
  });
7190
- async function up$19(database) {
7597
+ async function up$20(database) {
7191
7598
  await database.schema.createTable("workspaceStorageUsage").addColumn("workspaceId", "uuid", (column) => column.primaryKey().references("workspace.id").onDelete("cascade")).addColumn("committedBytes", "bigint", (column) => column.notNull().defaultTo(0)).addColumn("updatedAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).execute();
7192
7599
  await database.schema.createTable("uploadStorageReservation").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("workspaceId", "uuid", (column) => column.notNull().references("workspace.id").onDelete("cascade")).addColumn("uploadId", "uuid", (column) => column.notNull().unique().references("upload.id").onDelete("cascade")).addColumn("bytes", "bigint", (column) => column.notNull()).addColumn("expiresAt", "timestamptz", (column) => column.notNull()).addColumn("committedAt", "timestamptz").addColumn("releasedAt", "timestamptz").addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).execute();
7193
7600
  }
7194
- async function down$19(database) {
7601
+ async function down$20(database) {
7195
7602
  await database.schema.dropTable("uploadStorageReservation").execute();
7196
7603
  await database.schema.dropTable("workspaceStorageUsage").execute();
7197
7604
  }
7198
7605
  //#endregion
7199
7606
  //#region src/server/db/migrations/009_workspace_entitlements.ts
7200
7607
  var _009_workspace_entitlements_exports = /* @__PURE__ */ __exportAll({
7201
- down: () => down$18,
7202
- up: () => up$18
7608
+ down: () => down$19,
7609
+ up: () => up$19
7203
7610
  });
7204
- async function up$18(database) {
7611
+ async function up$19(database) {
7205
7612
  await database.schema.createTable("workspaceEntitlement").addColumn("workspaceId", "uuid", (column) => column.primaryKey().references("workspace.id").onDelete("cascade")).addColumn("values", "jsonb", (column) => column.notNull()).addColumn("source", "text", (column) => column.notNull()).addColumn("revision", "integer", (column) => column.notNull().defaultTo(1)).addColumn("updatedAt", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
7206
7613
  }
7207
- async function down$18(database) {
7614
+ async function down$19(database) {
7208
7615
  await database.schema.dropTable("workspaceEntitlement").execute();
7209
7616
  }
7210
7617
  //#endregion
7211
7618
  //#region src/server/db/migrations/010_upload_finalization.ts
7212
7619
  var _010_upload_finalization_exports = /* @__PURE__ */ __exportAll({
7213
- down: () => down$17,
7214
- up: () => up$17
7620
+ down: () => down$18,
7621
+ up: () => up$18
7215
7622
  });
7216
- async function up$17(database) {
7623
+ async function up$18(database) {
7217
7624
  await replaceCheckConstraint(database, "upload", "upload_status_check", "status", [
7218
7625
  "pending",
7219
7626
  "finalizing",
@@ -7222,7 +7629,7 @@ async function up$17(database) {
7222
7629
  "abandoned"
7223
7630
  ]);
7224
7631
  }
7225
- async function down$17(database) {
7632
+ async function down$18(database) {
7226
7633
  await replaceCheckConstraint(database, "upload", "upload_status_check", "status", [
7227
7634
  "pending",
7228
7635
  "cleaning",
@@ -7233,22 +7640,22 @@ async function down$17(database) {
7233
7640
  //#endregion
7234
7641
  //#region src/server/db/migrations/011_upload_finalization_lease.ts
7235
7642
  var _011_upload_finalization_lease_exports = /* @__PURE__ */ __exportAll({
7236
- down: () => down$16,
7237
- up: () => up$16
7643
+ down: () => down$17,
7644
+ up: () => up$17
7238
7645
  });
7239
- async function up$16(database) {
7646
+ async function up$17(database) {
7240
7647
  await database.schema.alterTable("upload").addColumn("finalization_started_at", "timestamptz").execute();
7241
7648
  }
7242
- async function down$16(database) {
7649
+ async function down$17(database) {
7243
7650
  await database.schema.alterTable("upload").dropColumn("finalization_started_at").execute();
7244
7651
  }
7245
7652
  //#endregion
7246
7653
  //#region src/server/db/migrations/012_transactional_email.ts
7247
7654
  var _012_transactional_email_exports = /* @__PURE__ */ __exportAll({
7248
- down: () => down$15,
7249
- up: () => up$15
7655
+ down: () => down$16,
7656
+ up: () => up$16
7250
7657
  });
7251
- async function up$15(database) {
7658
+ async function up$16(database) {
7252
7659
  await database.schema.createTable("transactional_email").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("idempotency_key", "text", (column) => column.notNull().unique()).addColumn("kind", "text", (column) => column.notNull()).addColumn("recipient_email_normalized", "text", (column) => column.notNull()).addColumn("payload_encrypted", "text").addColumn("status", "text", (column) => column.notNull().defaultTo("pending")).addColumn("attempt_count", "integer", (column) => column.notNull().defaultTo(0)).addColumn("next_attempt_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("claim_id", "uuid").addColumn("claimed_at", "timestamptz").addColumn("transport", "text").addColumn("transport_message_id", "text").addColumn("last_error_code", "text").addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("updated_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("accepted_at", "timestamptz").addCheckConstraint("transactional_email_kind_check", checkColumnIn("kind", ["document-invitation"])).addCheckConstraint("transactional_email_status_check", checkColumnIn("status", [
7253
7660
  "pending",
7254
7661
  "sending",
@@ -7258,16 +7665,16 @@ async function up$15(database) {
7258
7665
  ])).execute();
7259
7666
  await database.schema.createIndex("transactional_email_delivery_index").on("transactional_email").columns(["status", "next_attempt_at"]).execute();
7260
7667
  }
7261
- async function down$15(database) {
7668
+ async function down$16(database) {
7262
7669
  await database.schema.dropTable("transactional_email").ifExists().execute();
7263
7670
  }
7264
7671
  //#endregion
7265
7672
  //#region src/server/db/migrations/013_admin_enrollment.ts
7266
7673
  var _013_admin_enrollment_exports = /* @__PURE__ */ __exportAll({
7267
- down: () => down$14,
7268
- up: () => up$14
7674
+ down: () => down$15,
7675
+ up: () => up$15
7269
7676
  });
7270
- async function up$14(database) {
7677
+ async function up$15(database) {
7271
7678
  await database.schema.createTable("cloud_enrollment").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("email_normalized", "text", (column) => column.notNull().unique()).addColumn("name", "text").addColumn("reason", "text").addColumn("status", "text", (column) => column.notNull().defaultTo("pending")).addColumn("requested_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addColumn("reviewed_at", "timestamptz").addColumn("reviewed_by", "text").addColumn("review_note", "text").addColumn("approved_user_id", "text").addCheckConstraint("cloud_enrollment_status_check", checkColumnIn("status", [
7272
7679
  "pending",
7273
7680
  "approved",
@@ -7278,17 +7685,17 @@ async function up$14(database) {
7278
7685
  await database.schema.createTable("cloud_admin_audit_event").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("actor_user_id", "text", (column) => column.notNull()).addColumn("action", "text", (column) => column.notNull()).addColumn("subject_type", "text", (column) => column.notNull()).addColumn("subject_id", "text", (column) => column.notNull()).addColumn("metadata", "jsonb", (column) => column.notNull().defaultTo(EMPTY_JSON_OBJECT)).addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
7279
7686
  await database.schema.createIndex("cloud_admin_audit_created_index").on("cloud_admin_audit_event").column("created_at").execute();
7280
7687
  }
7281
- async function down$14(database) {
7688
+ async function down$15(database) {
7282
7689
  await database.schema.dropTable("cloud_admin_audit_event").ifExists().execute();
7283
7690
  await database.schema.dropTable("cloud_enrollment").ifExists().execute();
7284
7691
  }
7285
7692
  //#endregion
7286
7693
  //#region src/server/db/migrations/014_enrollment_email_kinds.ts
7287
7694
  var _014_enrollment_email_kinds_exports = /* @__PURE__ */ __exportAll({
7288
- down: () => down$13,
7289
- up: () => up$13
7695
+ down: () => down$14,
7696
+ up: () => up$14
7290
7697
  });
7291
- async function up$13(database) {
7698
+ async function up$14(database) {
7292
7699
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", [
7293
7700
  "document-invitation",
7294
7701
  "enrollment-requested",
@@ -7298,42 +7705,42 @@ async function up$13(database) {
7298
7705
  "enrollment-revoked"
7299
7706
  ]);
7300
7707
  }
7301
- async function down$13(database) {
7708
+ async function down$14(database) {
7302
7709
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", ["document-invitation"]);
7303
7710
  }
7304
7711
  //#endregion
7305
7712
  //#region src/server/db/migrations/015_cloud_rate_limit.ts
7306
7713
  var _015_cloud_rate_limit_exports = /* @__PURE__ */ __exportAll({
7307
- down: () => down$12,
7308
- up: () => up$12
7714
+ down: () => down$13,
7715
+ up: () => up$13
7309
7716
  });
7310
- async function up$12(database) {
7717
+ async function up$13(database) {
7311
7718
  await database.schema.alterTable("cloud_enrollment").addColumn("request_revision", "integer", (column) => column.notNull().defaultTo(1)).execute();
7312
7719
  await database.schema.createTable("cloud_rate_limit").addColumn("key_hash", "text", (column) => column.primaryKey()).addColumn("window_started_at", "timestamptz", (column) => column.notNull()).addColumn("request_count", "integer", (column) => column.notNull().defaultTo(1)).execute();
7313
7720
  await addCurrentTimestampColumns(database, "cloud_rate_limit", ["updated_at"]);
7314
7721
  }
7315
- async function down$12(database) {
7722
+ async function down$13(database) {
7316
7723
  await database.schema.dropTable("cloud_rate_limit").ifExists().execute();
7317
7724
  await database.schema.alterTable("cloud_enrollment").dropColumn("request_revision").execute();
7318
7725
  }
7319
7726
  //#endregion
7320
7727
  //#region src/server/db/migrations/016_auth_schema.ts
7321
7728
  var _016_auth_schema_exports = /* @__PURE__ */ __exportAll({
7322
- down: () => down$11,
7323
- up: () => up$11
7729
+ down: () => down$12,
7730
+ up: () => up$12
7324
7731
  });
7325
- async function up$11(database) {
7732
+ async function up$12(database) {
7326
7733
  await database.schema.createTable("cloud_auth_schema").addColumn("id", "text", (column) => column.primaryKey()).addColumn("version", "text", (column) => column.notNull()).execute();
7327
7734
  await addCurrentTimestampColumns(database, "cloud_auth_schema", ["updated_at"]);
7328
7735
  }
7329
- async function down$11(database) {
7736
+ async function down$12(database) {
7330
7737
  await database.schema.dropTable("cloud_auth_schema").ifExists().execute();
7331
7738
  }
7332
7739
  //#endregion
7333
7740
  //#region src/server/db/migrations/017_authentication_email_kinds.ts
7334
7741
  var _017_authentication_email_kinds_exports = /* @__PURE__ */ __exportAll({
7335
- down: () => down$10,
7336
- up: () => up$10
7742
+ down: () => down$11,
7743
+ up: () => up$11
7337
7744
  });
7338
7745
  const kinds = [
7339
7746
  "document-invitation",
@@ -7343,7 +7750,7 @@ const kinds = [
7343
7750
  "enrollment-rejected",
7344
7751
  "enrollment-revoked"
7345
7752
  ];
7346
- async function up$10(database) {
7753
+ async function up$11(database) {
7347
7754
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", [
7348
7755
  ...kinds,
7349
7756
  "email-verification",
@@ -7351,19 +7758,19 @@ async function up$10(database) {
7351
7758
  "password-changed"
7352
7759
  ]);
7353
7760
  }
7354
- async function down$10(database) {
7761
+ async function down$11(database) {
7355
7762
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", kinds);
7356
7763
  }
7357
7764
  //#endregion
7358
7765
  //#region src/server/db/migrations/018_authentication_mfa.ts
7359
7766
  var _018_authentication_mfa_exports = /* @__PURE__ */ __exportAll({
7360
- down: () => down$9,
7361
- up: () => up$9
7767
+ down: () => down$10,
7768
+ up: () => up$10
7362
7769
  });
7363
7770
  async function tableNames(database) {
7364
7771
  return new Set((await database.introspection.getTables()).map((table) => table.name));
7365
7772
  }
7366
- async function up$9(database) {
7773
+ async function up$10(database) {
7367
7774
  const cloud = database;
7368
7775
  const tables = await tableNames(database);
7369
7776
  await database.schema.createTable("cloud_mfa_assurance").addColumn("session_id", "uuid", (column) => column.primaryKey()).addColumn("user_id", "uuid", (column) => column.notNull()).addColumn("method", "text", (column) => column.notNull()).addColumn("verified_at", "timestamptz", (column) => column.notNull()).execute();
@@ -7378,7 +7785,7 @@ async function up$9(database) {
7378
7785
  updatedAt: /* @__PURE__ */ new Date()
7379
7786
  }).where("id", "=", "better-auth").where("version", "=", "1.7.2").execute();
7380
7787
  }
7381
- async function down$9(database) {
7788
+ async function down$10(database) {
7382
7789
  await database.schema.dropTable("cloud_mfa_assurance").ifExists().execute();
7383
7790
  await database.schema.dropTable("passkey").ifExists().execute();
7384
7791
  await database.schema.dropTable("two_factor").ifExists().execute();
@@ -7387,8 +7794,8 @@ async function down$9(database) {
7387
7794
  //#endregion
7388
7795
  //#region src/server/db/migrations/019_better_auth_account_issuer.ts
7389
7796
  var _019_better_auth_account_issuer_exports = /* @__PURE__ */ __exportAll({
7390
- down: () => down$8,
7391
- up: () => up$8
7797
+ down: () => down$9,
7798
+ up: () => up$9
7392
7799
  });
7393
7800
  /** The unique index Better Auth 1.7.0 through 1.7.2 created on `account (issuer, accountId)`. */
7394
7801
  const ISSUER_INDEX = "account_issuer_accountId_uidx";
@@ -7398,7 +7805,7 @@ const ISSUER_INDEX = "account_issuer_accountId_uidx";
7398
7805
  * Better Auth's 1.7 upgrade guide, the column becomes optional and its unique index goes; the
7399
7806
  * column itself is left for a later cleanup.
7400
7807
  */
7401
- async function up$8(database) {
7808
+ async function up$9(database) {
7402
7809
  const cloud = database;
7403
7810
  if ((await database.introspection.getTables()).find((table) => table.name === "account")?.columns.some((column) => column.name === "issuer")) {
7404
7811
  await database.schema.dropIndex(ISSUER_INDEX).ifExists().execute();
@@ -7409,7 +7816,7 @@ async function up$8(database) {
7409
7816
  updatedAt: /* @__PURE__ */ new Date()
7410
7817
  }).where("id", "=", "better-auth").where("version", "=", "1.7.2+mfa.1").execute();
7411
7818
  }
7412
- async function down$8(database) {
7819
+ async function down$9(database) {
7413
7820
  await database.updateTable("cloudAuthSchema").set({
7414
7821
  version: "1.7.2+mfa.1",
7415
7822
  updatedAt: /* @__PURE__ */ new Date()
@@ -7418,8 +7825,8 @@ async function down$8(database) {
7418
7825
  //#endregion
7419
7826
  //#region src/server/db/migrations/020_workspace_invitations.ts
7420
7827
  var _020_workspace_invitations_exports = /* @__PURE__ */ __exportAll({
7421
- down: () => down$7,
7422
- up: () => up$7
7828
+ down: () => down$8,
7829
+ up: () => up$8
7423
7830
  });
7424
7831
  const emailKinds$1 = [
7425
7832
  "document-invitation",
@@ -7432,7 +7839,7 @@ const emailKinds$1 = [
7432
7839
  "password-reset",
7433
7840
  "password-changed"
7434
7841
  ];
7435
- async function up$7(database) {
7842
+ async function up$8(database) {
7436
7843
  await addInvitationColumns(database.schema.createTable("workspace_invitation").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("workspace_id", "uuid", (column) => column.references("workspace.id").onDelete("cascade").notNull()), "role").addCheckConstraint("workspace_invitation_role_check", checkColumnIn("role", [
7437
7844
  "admin",
7438
7845
  "editor",
@@ -7442,22 +7849,22 @@ async function up$7(database) {
7442
7849
  await database.schema.createIndex("workspace_invitation_workspace_index").on("workspace_invitation").columns(["workspace_id", "revoked_at"]).execute();
7443
7850
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", [...emailKinds$1, "workspace-invitation"]);
7444
7851
  }
7445
- async function down$7(database) {
7852
+ async function down$8(database) {
7446
7853
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", emailKinds$1);
7447
7854
  await database.schema.dropTable("workspace_invitation").execute();
7448
7855
  }
7449
7856
  //#endregion
7450
7857
  //#region src/server/db/migrations/021_document_versions.ts
7451
7858
  var _021_document_versions_exports = /* @__PURE__ */ __exportAll({
7452
- down: () => down$6,
7859
+ down: () => down$7,
7453
7860
  keepCurrentRevisions: () => keepCurrentRevisions,
7454
- up: () => up$6
7861
+ up: () => up$7
7455
7862
  });
7456
7863
  /**
7457
7864
  * A document's version history: the revisions kept as checkpoints or named versions. Saves in
7458
7865
  * between are compacted away, so a version is what keeps a revision and its stored file.
7459
7866
  */
7460
- async function up$6(database) {
7867
+ async function up$7(database) {
7461
7868
  await database.schema.createTable("document_version").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("document_id", "uuid", (column) => column.references("document.id").onDelete("cascade").notNull()).addColumn("revision_id", "uuid", (column) => column.references("document_revision.id").onDelete("cascade").notNull().unique()).addColumn("kind", "text", (column) => column.notNull()).addColumn("name", "text").addColumn("description", "text").addColumn("created_by", "text", (column) => column.notNull()).addColumn("restored_from_version_id", "uuid", (column) => column.references("document_version.id").onDelete("set null")).addCheckConstraint("document_version_kind_check", checkColumnIn("kind", ["checkpoint", "named"])).execute();
7462
7869
  await addCurrentTimestampColumns(database, "document_version", ["created_at"]);
7463
7870
  await database.schema.createIndex("document_version_document_index").on("document_version").columns([
@@ -7467,7 +7874,7 @@ async function up$6(database) {
7467
7874
  ]).execute();
7468
7875
  await keepCurrentRevisions(database);
7469
7876
  }
7470
- async function down$6(database) {
7877
+ async function down$7(database) {
7471
7878
  await database.schema.dropTable("document_version").execute();
7472
7879
  }
7473
7880
  /** Keeps each document's current revision as the first checkpoint of its history. */
@@ -7491,24 +7898,24 @@ async function keepCurrentRevisions(database) {
7491
7898
  //#endregion
7492
7899
  //#region src/server/db/migrations/022_entitlement_external_version.ts
7493
7900
  var _022_entitlement_external_version_exports = /* @__PURE__ */ __exportAll({
7494
- down: () => down$5,
7495
- up: () => up$5
7901
+ down: () => down$6,
7902
+ up: () => up$6
7496
7903
  });
7497
7904
  /**
7498
7905
  * The version an external writer, such as a billing service, attached to a workspace's
7499
7906
  * entitlements. Writers deliver out of order, so a write older than the stored one is refused.
7500
7907
  */
7501
- async function up$5(database) {
7908
+ async function up$6(database) {
7502
7909
  await database.schema.alterTable("workspaceEntitlement").addColumn("externalVersion", "bigint").execute();
7503
7910
  }
7504
- async function down$5(database) {
7911
+ async function down$6(database) {
7505
7912
  await database.schema.alterTable("workspaceEntitlement").dropColumn("externalVersion").execute();
7506
7913
  }
7507
7914
  //#endregion
7508
7915
  //#region src/server/db/migrations/023_document_images.ts
7509
7916
  var _023_document_images_exports = /* @__PURE__ */ __exportAll({
7510
- down: () => down$4,
7511
- up: () => up$4
7917
+ down: () => down$5,
7918
+ up: () => up$5
7512
7919
  });
7513
7920
  /**
7514
7921
  * Images live once per workspace, keyed by the SHA-256 the object store verifies, each a stored
@@ -7516,7 +7923,7 @@ var _023_document_images_exports = /* @__PURE__ */ __exportAll({
7516
7923
  * the images it uses under the names its file gives them. An image upload is an upload of its own
7517
7924
  * kind, so reservations, commits, and expired-upload cleanup cover it.
7518
7925
  */
7519
- async function up$4(database) {
7926
+ async function up$5(database) {
7520
7927
  await database.schema.alterTable("upload").addColumn("kind", "text", (column) => column.notNull().defaultTo("revision")).execute();
7521
7928
  await addCheckConstraint(database, "upload", "upload_kind_check", "kind", ["revision", "image"]);
7522
7929
  await database.schema.createTable("workspace_image").addColumn("workspace_id", "uuid", (column) => column.references("workspace.id").onDelete("cascade").notNull()).addColumn("checksum", "text", (column) => column.notNull()).addColumn("storage_object_id", "uuid", (column) => column.references("storage_object.id").notNull().unique()).addPrimaryKeyConstraint("workspace_image_pkey", ["workspace_id", "checksum"]).execute();
@@ -7524,7 +7931,7 @@ async function up$4(database) {
7524
7931
  await database.schema.createTable("revision_image").addColumn("revision_id", "uuid", (column) => column.references("document_revision.id").onDelete("cascade").notNull()).addColumn("name", "text", (column) => column.notNull()).addColumn("workspace_id", "uuid", (column) => column.notNull()).addColumn("checksum", "text", (column) => column.notNull()).addPrimaryKeyConstraint("revision_image_pkey", ["revision_id", "name"]).addForeignKeyConstraint("revision_image_image_fkey", ["workspace_id", "checksum"], "workspace_image", ["workspace_id", "checksum"]).execute();
7525
7932
  await database.schema.createIndex("revision_image_image_index").on("revision_image").columns(["workspace_id", "checksum"]).execute();
7526
7933
  }
7527
- async function down$4(database) {
7934
+ async function down$5(database) {
7528
7935
  await database.schema.dropTable("revision_image").execute();
7529
7936
  await database.schema.dropTable("workspace_image").execute();
7530
7937
  await database.schema.alterTable("upload").dropConstraint("upload_kind_check").execute();
@@ -7533,8 +7940,8 @@ async function down$4(database) {
7533
7940
  //#endregion
7534
7941
  //#region src/server/db/migrations/024_account_activity.ts
7535
7942
  var _024_account_activity_exports = /* @__PURE__ */ __exportAll({
7536
- down: () => down$3,
7537
- up: () => up$3
7943
+ down: () => down$4,
7944
+ up: () => up$4
7538
7945
  });
7539
7946
  const emailKinds = [
7540
7947
  "document-invitation",
@@ -7553,7 +7960,7 @@ const emailKinds = [
7553
7960
  * an address it never signed in from; a session keeps the row of the sign-in that made it, which
7554
7961
  * names how it was made. The security notices that follow get their own email kinds.
7555
7962
  */
7556
- async function up$3(database) {
7963
+ async function up$4(database) {
7557
7964
  await database.schema.createTable("sign_in").addColumn("id", "uuid", (column) => column.primaryKey()).addColumn("user_id", "uuid", (column) => column.notNull()).addColumn("session_id", "uuid").addColumn("method", "text", (column) => column.notNull()).addColumn("ip_address", "text").addColumn("user_agent", "text").addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).execute();
7558
7965
  await database.schema.createIndex("sign_in_user_index").on("sign_in").columns(["user_id", "created_at"]).execute();
7559
7966
  await database.schema.createIndex("sign_in_session_index").on("sign_in").column("session_id").execute();
@@ -7564,15 +7971,15 @@ async function up$3(database) {
7564
7971
  "two-step-changed"
7565
7972
  ]);
7566
7973
  }
7567
- async function down$3(database) {
7974
+ async function down$4(database) {
7568
7975
  await replaceCheckConstraint(database, "transactional_email", "transactional_email_kind_check", "kind", emailKinds);
7569
7976
  await database.schema.dropTable("sign_in").execute();
7570
7977
  }
7571
7978
  //#endregion
7572
7979
  //#region src/server/db/migrations/025_table_names.ts
7573
7980
  var _025_table_names_exports = /* @__PURE__ */ __exportAll({
7574
- down: () => down$2,
7575
- up: () => up$2
7981
+ down: () => down$3,
7982
+ up: () => up$3
7576
7983
  });
7577
7984
  /**
7578
7985
  * OpenPencil's tables beside Better Auth's lose the `cloud_` prefix the rest never had; only the
@@ -7586,7 +7993,7 @@ const TABLES = [
7586
7993
  ["cloud_auth_schema", "auth_schema_version"],
7587
7994
  ["cloud_rate_limit", "api_rate_limit"]
7588
7995
  ];
7589
- const CONSTRAINTS = [
7996
+ const CONSTRAINTS$1 = [
7590
7997
  [
7591
7998
  "enrollment",
7592
7999
  "cloud_enrollment_pkey",
@@ -7627,53 +8034,102 @@ const INDEXES = [["cloud_enrollment_status_index", "enrollment_status_index"], [
7627
8034
  async function rename(database, direction) {
7628
8035
  const forward = direction === "up";
7629
8036
  if (forward) for (const [from, to] of TABLES) await database.schema.alterTable(from).renameTo(to).execute();
7630
- for (const [table, from, to] of CONSTRAINTS) await database.schema.alterTable(table).renameConstraint(forward ? from : to, forward ? to : from).execute();
8037
+ for (const [table, from, to] of CONSTRAINTS$1) await database.schema.alterTable(table).renameConstraint(forward ? from : to, forward ? to : from).execute();
7631
8038
  for (const [from, to] of INDEXES) {
7632
8039
  const [source, target] = forward ? [from, to] : [to, from];
7633
8040
  await sql`alter index ${sql.id(source)} rename to ${sql.id(target)}`.execute(database);
7634
8041
  }
7635
8042
  if (!forward) for (const [from, to] of TABLES) await database.schema.alterTable(to).renameTo(from).execute();
7636
8043
  }
7637
- async function up$2(database) {
8044
+ async function up$3(database) {
7638
8045
  await rename(database, "up");
7639
8046
  }
7640
- async function down$2(database) {
8047
+ async function down$3(database) {
7641
8048
  await rename(database, "down");
7642
8049
  }
7643
8050
  //#endregion
7644
8051
  //#region src/server/db/migrations/026_user_picture.ts
7645
8052
  var _026_user_picture_exports = /* @__PURE__ */ __exportAll({
7646
- down: () => down$1,
7647
- up: () => up$1
8053
+ down: () => down$2,
8054
+ up: () => up$2
7648
8055
  });
7649
8056
  /**
7650
8057
  * The picture each account shows, kept by the server so pages never load one from another
7651
8058
  * service: one uploaded by its owner, or the one a linked Google account gave it, copied at sign-in.
7652
8059
  */
7653
- async function up$1(database) {
8060
+ async function up$2(database) {
7654
8061
  await database.schema.createTable("user_picture").addColumn("user_id", "uuid", (column) => column.primaryKey()).addColumn("bytes", "bytea", (column) => column.notNull()).addColumn("format", "text", (column) => column.notNull()).addColumn("checksum", "text", (column) => column.notNull()).addColumn("source", "text", (column) => column.notNull()).addColumn("created_at", "timestamptz", (column) => column.notNull().defaultTo(CURRENT_TIMESTAMP)).addCheckConstraint("user_picture_format_check", checkColumnIn("format", ["png", "jpeg"])).addCheckConstraint("user_picture_source_check", checkColumnIn("source", ["upload", "provider"])).execute();
7655
8062
  }
7656
- async function down$1(database) {
8063
+ async function down$2(database) {
7657
8064
  await database.schema.dropTable("user_picture").execute();
7658
8065
  }
7659
8066
  //#endregion
7660
8067
  //#region src/server/db/migrations/027_document_kind.ts
7661
8068
  var _027_document_kind_exports = /* @__PURE__ */ __exportAll({
7662
- down: () => down,
7663
- up: () => up
8069
+ down: () => down$1,
8070
+ up: () => up$1
7664
8071
  });
7665
8072
  /**
7666
8073
  * Whether each document is a Figma design or a FigJam board, so lists can tell them apart
7667
8074
  * without opening the file. Documents stored before this are designs; a board's next save says so.
7668
8075
  */
7669
- async function up(database) {
8076
+ async function up$1(database) {
7670
8077
  await database.schema.alterTable("document").addColumn("kind", "text", (column) => column.notNull().defaultTo("design")).execute();
7671
8078
  await addCheckConstraint(database, "document", "document_kind_check", "kind", ["design", "board"]);
7672
8079
  }
7673
- async function down(database) {
8080
+ async function down$1(database) {
7674
8081
  await database.schema.alterTable("document").dropColumn("kind").execute();
7675
8082
  }
7676
8083
  //#endregion
8084
+ //#region src/server/db/migrations/028_collaboration_updates.ts
8085
+ var _028_collaboration_updates_exports = /* @__PURE__ */ __exportAll({
8086
+ down: () => down,
8087
+ startRoomsOver: () => startRoomsOver,
8088
+ up: () => up
8089
+ });
8090
+ /** The renamed table's constraints, whose names spelled its old name. */
8091
+ const CONSTRAINTS = [["documentCollaborationStatePrimary", "documentRoomSnapshotPrimary"], ["documentCollaborationStateDocumentIdFkey", "documentRoomSnapshotDocumentIdFkey"]];
8092
+ async function renameConstraints(database, direction) {
8093
+ for (const [old, current] of CONSTRAINTS) {
8094
+ const [from, to] = direction === "up" ? [old, current] : [current, old];
8095
+ await database.schema.alterTable("documentRoomSnapshot").renameConstraint(from, to).execute();
8096
+ }
8097
+ }
8098
+ /** Moves every document with a saved room to a new epoch, and drops the saved rooms. */
8099
+ async function startRoomsOver(database) {
8100
+ await database.updateTable("document").set((expression) => ({ collaborationEpoch: expression("collaborationEpoch", "+", 1) })).where("id", "in", database.selectFrom("documentRoomSnapshot").select("documentId")).execute();
8101
+ await database.deleteFrom("documentRoomSnapshot").execute();
8102
+ }
8103
+ /**
8104
+ * A room's edits as an append-only log beside a snapshot kept in the object store, so a save
8105
+ * writes what changed instead of the whole room, and the room's bulk lives with the documents'
8106
+ * files rather than in the database. The snapshot row names its stored file and the last logged
8107
+ * update it holds; compaction points it at a new file and drops the updates it covers.
8108
+ *
8109
+ * Rooms saved before held their snapshots in the row itself. Those rows go, and each such
8110
+ * document moves to a new collaboration epoch, so its next room starts from its last saved
8111
+ * revision and no tab's local copy of the earlier room joins it.
8112
+ */
8113
+ async function up(database) {
8114
+ await database.schema.alterTable("documentCollaborationState").renameTo("documentRoomSnapshot").execute();
8115
+ await renameConstraints(database, "up");
8116
+ await startRoomsOver(database);
8117
+ await database.schema.alterTable("documentRoomSnapshot").dropColumn("state").dropColumn("version").addColumn("snapshotObjectId", "uuid", (column) => column.notNull().references("storageObject.id")).addColumn("throughSequence", "integer", (column) => column.notNull()).execute();
8118
+ await database.schema.createTable("documentRoomUpdate").addColumn("documentId", "uuid", (column) => column.notNull().references("document.id").onDelete("cascade")).addColumn("roomEpoch", "integer", (column) => column.notNull()).addColumn("sequence", "integer", (column) => column.notNull()).addColumn("data", "bytea", (column) => column.notNull()).addColumn("createdAt", "timestamptz", (column) => column.notNull().defaultTo(database.fn("now"))).addPrimaryKeyConstraint("documentRoomUpdatePrimary", [
8119
+ "documentId",
8120
+ "roomEpoch",
8121
+ "sequence"
8122
+ ]).execute();
8123
+ }
8124
+ /** Back to snapshots in rows; the rooms saved meanwhile start over, as they did going up. */
8125
+ async function down(database) {
8126
+ await database.schema.dropTable("documentRoomUpdate").execute();
8127
+ await database.deleteFrom("documentRoomSnapshot").execute();
8128
+ await database.schema.alterTable("documentRoomSnapshot").dropColumn("snapshotObjectId").dropColumn("throughSequence").addColumn("state", "bytea", (column) => column.notNull()).addColumn("version", "integer", (column) => column.notNull().defaultTo(1)).execute();
8129
+ await renameConstraints(database, "down");
8130
+ await database.schema.alterTable("documentRoomSnapshot").renameTo("documentCollaborationState").execute();
8131
+ }
8132
+ //#endregion
7677
8133
  //#region src/server/db/migrate.ts
7678
8134
  const migrations = {
7679
8135
  "001_foundation": _001_foundation_exports,
@@ -7702,7 +8158,8 @@ const migrations = {
7702
8158
  "024_account_activity": _024_account_activity_exports,
7703
8159
  "025_table_names": _025_table_names_exports,
7704
8160
  "026_user_picture": _026_user_picture_exports,
7705
- "027_document_kind": _027_document_kind_exports
8161
+ "027_document_kind": _027_document_kind_exports,
8162
+ "028_collaboration_updates": _028_collaboration_updates_exports
7706
8163
  };
7707
8164
  var CloudMigrationProvider = class {
7708
8165
  async getMigrations() {
@@ -8470,6 +8927,6 @@ function startTransactionalEmailWorker(email, options) {
8470
8927
  //#region src/server/invitations/types.ts
8471
8928
  const noOpInvitationDelivery = { async sendDocumentInvitation() {} };
8472
8929
  //#endregion
8473
- export { AINotEntitledError, AdminDomainError, CHECKPOINT_INTERVAL_MS, CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES, CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM, CLOUD_FEATURE_KEYS, CLOUD_RATE_LIMITS, CloudConfigError, CloudPolicy, DatabaseEntitlementSource, DocumentConflictError, DocumentForbiddenError, DocumentNotFoundError, DocumentShareInvalidError, DocumentShareSignInRequiredError, EntitlementOpenFeatureProvider, LIMITED_HISTORY_DAYS, PostgresRateLimitStore, REVISION_COMPACTION_GRACE_MS, StaticEntitlementSource, StorageQuotaExceededError, TransactionalEmailTransportError, UploadInvalidError, WorkspaceSlugConflictError, adminErrorStatus, authorizeRelayTicket, canEditDocument, capabilityHashMatches, cleanupPassOptions, cloudDeploymentConfigSchema, cloudDiscoveryFromConfig, configuredSocialProviders, createAIRoutes, createAITokenService, createAccountAuthenticationService, createActorRateLimiter, createAdminAuditService, createAdminEmailService, createAdminOperationsService, createAdminUserService, createAuthenticationEmailService, createBetterAuthAdapter, createCleanupServices, createCloudAPIRouter, createCloudAdminRoutes, createCloudApp, createCloudAuthenticationRuntime, createCloudDatabase, createCloudIdentityResolver, createCloudRateLimiter, createCloudSessionResolver, createCollaborationRelay, createCollaborationRoutes, createCollaborationStateStore, createCollaborationTicketService, createConfiguredCloudPolicy, createDefaultCloudPolicy, createDocumentCleanupService, createDocumentRoutes, createDocumentService, createDocumentSharingRoutes, createDocumentSharingService, createDocumentVersionRoutes, createDocumentVersionService, createEnrollmentService, createEntitlementService, createInternalRoutes, createInternalService, createInvitationOutbox, createPublicCloudAPIRouter, createPublicCollaborationRoutes, createPublicDocumentRoutes, createPublicSharingRoutes, createRateLimitCleanupService, createRevisionCompactionService, createStorageQuotaService, createStorageReconciliationService, createTransactionalEmailService, createTrustedIPRateLimiter, createUploadCleanupService, createWorkspaceEntitlementRepository, createWorkspaceRoutes, createWorkspaceService, decryptContinuationToken, decryptTransactionalEmailPayload, encryptContinuationToken, encryptTransactionalEmailPayload, hashCapability, importAISigningKey, loadAISigningKey, migrateCloudDatabase, noOpInvitationDelivery, normalizeEnrollmentEmail, parseCloudDeploymentConfig, parseCloudDeploymentSource, parseCloudDeploymentTOML, parseCloudServerConfig, parseSetWorkspaceEntitlements, parseStaticEntitlementsTOML, rateLimitKey, relayDocumentLookups, resolveDocumentAccess, runCleanup, setWorkspaceEntitlementsSchema, shouldPreventIndexing, signCollaborationTicket, stampAwareness, startCleanupWorker, startTransactionalEmailWorker, staticEntitlementValues, staticEntitlementsSchema, trustedClientIP, withIndexingPolicy, workspaceAccessControl, workspaceRoles, workspaceStatements };
8930
+ export { AINotEntitledError, AdminDomainError, CHECKPOINT_INTERVAL_MS, CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES, CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM, CLOUD_ERROR_SOURCES, CLOUD_FEATURE_KEYS, CLOUD_RATE_LIMITS, CloudConfigError, CloudPolicy, DatabaseEntitlementSource, DocumentConflictError, DocumentForbiddenError, DocumentNotFoundError, DocumentShareInvalidError, DocumentShareSignInRequiredError, EntitlementOpenFeatureProvider, LIMITED_HISTORY_DAYS, PostgresRateLimitStore, REVISION_COMPACTION_GRACE_MS, StaticEntitlementSource, StorageQuotaExceededError, TransactionalEmailTransportError, UploadInvalidError, WorkspaceSlugConflictError, adminErrorStatus, authorizeRelayTicket, canEditDocument, capabilityHashMatches, cleanupPassOptions, cloudDeploymentConfigSchema, cloudDiscoveryFromConfig, cloudErrorHandler, configuredSocialProviders, createAIRoutes, createAITokenService, createAccountAuthenticationService, createActorRateLimiter, createAdminAuditService, createAdminEmailService, createAdminOperationsService, createAdminUserService, createAuthenticationEmailService, createBetterAuthAdapter, createCleanupServices, createCloudAPIRouter, createCloudAdminRoutes, createCloudApp, createCloudAuthenticationRuntime, createCloudDatabase, createCloudIdentityResolver, createCloudRateLimiter, createCloudSessionResolver, createCollaborationRelay, createCollaborationRoutes, createCollaborationStateStore, createCollaborationTicketService, createConfiguredCloudPolicy, createDefaultCloudPolicy, createDocumentCleanupService, createDocumentRoutes, createDocumentService, createDocumentSharingRoutes, createDocumentSharingService, createDocumentVersionRoutes, createDocumentVersionService, createEnrollmentService, createEntitlementService, createInternalRoutes, createInternalService, createInvitationOutbox, createPublicCloudAPIRouter, createPublicCollaborationRoutes, createPublicDocumentRoutes, createPublicSharingRoutes, createRateLimitCleanupService, createRevisionCompactionService, createStorageQuotaService, createStorageReconciliationService, createTransactionalEmailService, createTrustedIPRateLimiter, createUploadCleanupService, createWorkspaceEntitlementRepository, createWorkspaceRoutes, createWorkspaceService, decryptContinuationToken, decryptTransactionalEmailPayload, encryptContinuationToken, encryptTransactionalEmailPayload, hashCapability, importAISigningKey, loadAISigningKey, migrateCloudDatabase, noOpInvitationDelivery, normalizeEnrollmentEmail, parseCloudDeploymentConfig, parseCloudDeploymentSource, parseCloudDeploymentTOML, parseCloudServerConfig, parseSetWorkspaceEntitlements, parseStaticEntitlementsTOML, rateLimitKey, readRelayPeerState, relayDocumentLookups, reportCloudError, resolveDocumentAccess, runCleanup, setWorkspaceEntitlementsSchema, shouldPreventIndexing, signCollaborationTicket, stampAwareness, startCleanupWorker, startTransactionalEmailWorker, staticEntitlementValues, staticEntitlementsSchema, trustedClientIP, withIndexingPolicy, workspaceAccessControl, workspaceRoles, workspaceStatements };
8474
8931
 
8475
8932
  //# sourceMappingURL=server.js.map