@open-pencil/cloud 0.17.0-beta.5 → 0.17.0-beta.6

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 (187) hide show
  1. package/dist/client.d.ts +560 -93
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +1101 -186
  4. package/dist/client.js.map +1 -1
  5. package/dist/contract.d.ts +2 -2
  6. package/dist/contract.js +2 -2
  7. package/dist/contract2.js +390 -44
  8. package/dist/contract2.js.map +1 -1
  9. package/dist/email.d.ts +366 -3
  10. package/dist/email.d.ts.map +1 -1
  11. package/dist/email.js +1403 -556
  12. package/dist/email.js.map +1 -1
  13. package/dist/errors.js +16 -3
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +878 -37
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index2.d.ts +12 -2
  18. package/dist/index2.d.ts.map +1 -1
  19. package/dist/listen.mjs +589 -128
  20. package/dist/listen.mjs.map +1 -1
  21. package/dist/runtime-cloudflare.d.ts +4 -0
  22. package/dist/runtime-cloudflare.d.ts.map +1 -1
  23. package/dist/runtime-cloudflare.js +8689 -6324
  24. package/dist/runtime-cloudflare.js.map +1 -1
  25. package/dist/runtime-node.d.mts +10098 -5401
  26. package/dist/runtime-node.d.mts.map +1 -1
  27. package/dist/server.d.ts +14078 -7909
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +11723 -9412
  30. package/dist/server.js.map +1 -1
  31. package/dist/server.mjs +10658 -8649
  32. package/dist/server.mjs.map +1 -1
  33. package/dist/server2.mjs +79 -57
  34. package/dist/server2.mjs.map +1 -1
  35. package/package.json +13 -4
  36. package/src/admin/api/routes.ts +263 -190
  37. package/src/admin/audit/service.ts +9 -1
  38. package/src/admin/bootstrap.ts +86 -0
  39. package/src/admin/documents/service.ts +119 -4
  40. package/src/admin/email/service.ts +2 -1
  41. package/src/admin/enrollment/email.ts +17 -3
  42. package/src/admin/enrollment/service.ts +71 -10
  43. package/src/admin/errors.ts +5 -0
  44. package/src/admin/index.ts +1 -0
  45. package/src/admin/reports/service.ts +9 -3
  46. package/src/admin/schema.ts +6 -5
  47. package/src/admin/users/service.ts +173 -16
  48. package/src/client/api.ts +29 -2
  49. package/src/client/comments.ts +205 -0
  50. package/src/client/device-authorization.ts +4 -20
  51. package/src/client/discovery.ts +4 -2
  52. package/src/client/files/archive.ts +60 -0
  53. package/src/client/files/checksum.ts +7 -0
  54. package/src/client/files/download.ts +122 -0
  55. package/src/client/files/images.ts +89 -0
  56. package/src/client/files/index.ts +15 -0
  57. package/src/client/files/objects.ts +173 -0
  58. package/src/client/files/save.ts +79 -0
  59. package/src/client/index.ts +3 -6
  60. package/src/client/portal/account.ts +20 -2
  61. package/src/client/portal/administration.ts +52 -5
  62. package/src/client/portal/request.ts +4 -2
  63. package/src/client/tour.ts +44 -0
  64. package/src/client/versions.ts +7 -1
  65. package/src/contract/account.ts +61 -11
  66. package/src/contract/admin/index.ts +48 -3
  67. package/src/contract/billing.ts +73 -4
  68. package/src/contract/comments.ts +223 -0
  69. package/src/contract/discovery.ts +47 -19
  70. package/src/contract/index.ts +10 -0
  71. package/src/contract/links.ts +5 -0
  72. package/src/contract/relay.ts +3 -1
  73. package/src/contract/services.ts +44 -4
  74. package/src/contract/workspaces.ts +5 -0
  75. package/src/email/locales/ar.json +28 -0
  76. package/src/email/locales/de.json +28 -0
  77. package/src/email/locales/es.json +28 -0
  78. package/src/email/locales/fr.json +28 -0
  79. package/src/email/locales/it.json +28 -0
  80. package/src/email/locales/ja.json +28 -0
  81. package/src/email/locales/pl.json +28 -0
  82. package/src/email/locales/pt-br.json +28 -0
  83. package/src/email/locales/ru.json +28 -0
  84. package/src/email/locales/zh-cn.json +28 -0
  85. package/src/email/messages.ts +35 -0
  86. package/src/email/render.ts +18 -0
  87. package/src/email/samples.ts +28 -1
  88. package/src/email/schema.ts +29 -3
  89. package/src/email/templates/BrandEmail.vue +3 -1
  90. package/src/email/templates/CommentNotification.vue +39 -0
  91. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  92. package/src/email/templates/TwoStepChanged.vue +17 -2
  93. package/src/email/templates/brand.ts +6 -0
  94. package/src/errors/posthog.ts +28 -4
  95. package/src/runtime/cloudflare/email.ts +2 -0
  96. package/src/runtime/cloudflare/relay/index.ts +21 -6
  97. package/src/runtime/cloudflare/worker.ts +6 -0
  98. package/src/runtime/cloudflare/xml.ts +12 -0
  99. package/src/runtime/node/admin.ts +51 -47
  100. package/src/runtime/node/email/runtime.ts +1 -0
  101. package/src/runtime/node/email/transport.ts +1 -0
  102. package/src/runtime/node/server.ts +8 -2
  103. package/src/runtime/posthog/errors.ts +3 -1
  104. package/src/server/account/actions.ts +3 -1
  105. package/src/server/account/deletion.ts +38 -4
  106. package/src/server/account/routes.ts +67 -46
  107. package/src/server/account/tokens.ts +3 -3
  108. package/src/server/api/router.ts +22 -7
  109. package/src/server/app/checks.ts +6 -1
  110. package/src/server/app/cors.ts +44 -0
  111. package/src/server/app/index.ts +76 -76
  112. package/src/server/app/routes.ts +14 -5
  113. package/src/server/app/services.ts +49 -15
  114. package/src/server/auth/access-control.ts +13 -8
  115. package/src/server/auth/account.ts +13 -12
  116. package/src/server/auth/activity.ts +7 -2
  117. package/src/server/auth/adapter.ts +16 -3
  118. package/src/server/auth/email.ts +29 -17
  119. package/src/server/auth/endpoints.ts +4 -0
  120. package/src/server/auth/factory.ts +83 -64
  121. package/src/server/auth/index.ts +1 -1
  122. package/src/server/auth/methods.ts +162 -0
  123. package/src/server/auth/mfa-assurance.ts +147 -10
  124. package/src/server/auth/rate-limit.ts +31 -0
  125. package/src/server/auth/runtime.ts +19 -5
  126. package/src/server/auth/social-providers.ts +70 -24
  127. package/src/server/billing/index.ts +2 -0
  128. package/src/server/billing/notify.ts +55 -0
  129. package/src/server/billing/seats.ts +17 -0
  130. package/src/server/billing/tokens.ts +1 -1
  131. package/src/server/cleanup/documents.ts +5 -2
  132. package/src/server/cleanup/revisions.ts +6 -3
  133. package/src/server/cleanup/uploads.ts +2 -1
  134. package/src/server/collaboration/relay/connection.ts +7 -2
  135. package/src/server/collaboration/relay/hub.ts +55 -24
  136. package/src/server/collaboration/routes.ts +8 -5
  137. package/src/server/comments/index.ts +9 -0
  138. package/src/server/comments/notify.ts +277 -0
  139. package/src/server/comments/routes.ts +352 -0
  140. package/src/server/comments/rows.ts +249 -0
  141. package/src/server/comments/service.ts +570 -0
  142. package/src/server/community/routes.ts +6 -6
  143. package/src/server/config/deployment.ts +19 -6
  144. package/src/server/config/index.ts +1 -1
  145. package/src/server/config/public.ts +19 -6
  146. package/src/server/config/schema.ts +14 -2
  147. package/src/server/config/toml/schema.ts +27 -4
  148. package/src/server/db/index.ts +2 -1
  149. package/src/server/db/migrate.ts +21 -1
  150. package/src/server/db/migrations/015_comments.ts +57 -0
  151. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  152. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  153. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  154. package/src/server/db/tables.ts +92 -2
  155. package/src/server/documents/access.ts +17 -0
  156. package/src/server/documents/images.ts +6 -1
  157. package/src/server/documents/routes.ts +12 -12
  158. package/src/server/documents/service.ts +19 -5
  159. package/src/server/documents/summary.ts +15 -0
  160. package/src/server/documents/versions/routes.ts +7 -8
  161. package/src/server/documents/versions/service.ts +5 -2
  162. package/src/server/email/service.ts +8 -2
  163. package/src/server/email/types.ts +1 -0
  164. package/src/server/errors/index.ts +48 -3
  165. package/src/server/index.ts +15 -1
  166. package/src/server/internal/routes.ts +8 -2
  167. package/src/server/internal/service.ts +10 -0
  168. package/src/server/invitations/budget.ts +3 -1
  169. package/src/server/invitations/index.ts +1 -0
  170. package/src/server/invitations/links.ts +6 -0
  171. package/src/server/pictures/service.ts +3 -1
  172. package/src/server/policy/workspace.ts +5 -2
  173. package/src/server/reports/routes.ts +2 -2
  174. package/src/server/reports/service.ts +3 -1
  175. package/src/server/services/routes.ts +2 -2
  176. package/src/server/sharing/capabilities/service.ts +1 -1
  177. package/src/server/sharing/document-routes.ts +3 -3
  178. package/src/server/sharing/invitations/service.ts +3 -4
  179. package/src/server/sharing/routes.ts +15 -15
  180. package/src/server/validation.ts +33 -25
  181. package/src/server/workspaces/members.ts +50 -12
  182. package/src/server/workspaces/repository.ts +23 -12
  183. package/src/server/workspaces/routes.ts +8 -8
  184. package/src/services/app.ts +30 -19
  185. package/src/services/config.ts +47 -8
  186. package/src/services/metering.ts +15 -27
  187. package/src/client/billing.ts +0 -80
package/dist/client.js CHANGED
@@ -1,8 +1,13 @@
1
1
  import * as v from "valibot";
2
- import { isValid } from "js-base64";
3
- import { zipObject } from "es-toolkit";
2
+ import { fromUint8Array, isValid } from "js-base64";
3
+ import { limitAsync, retry, sumBy, zipObject } from "es-toolkit";
4
+ import compareVersions from "semver/functions/compare.js";
5
+ import parseVersion from "semver/functions/parse.js";
4
6
  import { joinURL, withQuery, withoutFragment, withoutTrailingSlash } from "ufo";
5
7
  import { hc } from "hono/client";
8
+ import { readStreamBytes, readZipDirectory, zipEntryContents, zipStream } from "@open-pencil/fig";
9
+ import { sha256 } from "@noble/hashes/sha2.js";
10
+ import { DEADLINE_MS, SECOND_MS, anySignal, backoffDelay, sleep } from "@open-pencil/std/timing";
6
11
  import { pickBy } from "es-toolkit/object";
7
12
  import { passkeyClient } from "@better-auth/passkey/client";
8
13
  import { createAuthClient } from "better-auth/client";
@@ -52,13 +57,15 @@ async function serviceJSON(response, schema, refused) {
52
57
  //#region src/contract/account.ts
53
58
  /**
54
59
  * Where an account stands: it may use the server, waits for an administrator, was refused or had
55
- * its access taken back, or has to accept the server's current terms first.
60
+ * its access taken back, has to prove its second step in this session, as after signing in through
61
+ * a linked account such as Google, or has to accept the server's current terms first.
56
62
  */
57
63
  const cloudAccountStateSchema = v.picklist([
58
64
  "active",
59
65
  "pending",
60
66
  "rejected",
61
67
  "revoked",
68
+ "two-step",
62
69
  "terms"
63
70
  ]);
64
71
  const cloudIdentitySchema = v.object({
@@ -74,27 +81,45 @@ const cloudAccountStatusResponseSchema = v.object({
74
81
  state: cloudAccountStateSchema
75
82
  });
76
83
  v.object({ version: v.pipe(v.string(), v.minLength(1)) });
77
- const cloudAuthenticationProviderSchema = v.picklist([
78
- "credential",
84
+ /**
85
+ * The providers a person can sign in with besides a password, which this editor has buttons for,
86
+ * in the order it shows them. Every list of providers in Cloud derives from this one.
87
+ */
88
+ const CLOUD_SOCIAL_PROVIDERS = [
79
89
  "google",
80
- "apple"
81
- ]);
90
+ "apple",
91
+ "github"
92
+ ];
93
+ const cloudSocialProviderSchema = v.picklist(CLOUD_SOCIAL_PROVIDERS);
94
+ const cloudAuthenticationProviderSchema = v.picklist(["credential", ...CLOUD_SOCIAL_PROVIDERS]);
82
95
  const cloudAuthenticationMethodSchema = v.object({
83
96
  id: v.string(),
84
97
  provider: cloudAuthenticationProviderSchema,
85
98
  createdAt: v.string(),
86
99
  canUnlink: v.boolean()
87
100
  });
101
+ /** Whether this editor knows `provider`, so a newer server's other providers can be left out. */
102
+ function isKnownSocialProvider(provider) {
103
+ return CLOUD_SOCIAL_PROVIDERS.includes(provider);
104
+ }
105
+ /** Whether `provider` is a way to sign in this editor knows: a password or a known provider. */
106
+ function isKnownAuthenticationProvider(provider) {
107
+ return provider === "credential" || isKnownSocialProvider(provider);
108
+ }
109
+ /**
110
+ * A newer server may list a provider this editor has no words or button for: those entries are
111
+ * left out rather than failing the whole response, and anything else malformed still fails.
112
+ */
88
113
  const cloudAuthenticationMethodsResponseSchema = v.object({
89
- methods: v.array(cloudAuthenticationMethodSchema),
90
- availableSocialProviders: v.array(v.picklist(["google", "apple"]))
114
+ methods: v.pipe(v.array(v.looseObject({ provider: v.string() })), v.filterItems((method) => isKnownAuthenticationProvider(method.provider)), v.array(cloudAuthenticationMethodSchema)),
115
+ availableSocialProviders: v.pipe(v.array(v.string()), v.filterItems(isKnownSocialProvider), v.array(cloudSocialProviderSchema))
91
116
  });
92
117
  v.object({
93
118
  currentPassword: v.string(),
94
119
  newPassword: v.string()
95
120
  });
96
121
  v.object({
97
- provider: v.picklist(["google", "apple"]),
122
+ provider: cloudSocialProviderSchema,
98
123
  callbackURL: v.pipe(v.string(), v.url())
99
124
  });
100
125
  const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) });
@@ -106,6 +131,7 @@ const accountSecurityErrorCodeSchema = v.picklist([
106
131
  "last_authentication_method",
107
132
  "session_not_fresh",
108
133
  "authentication_method_failed",
134
+ "code_invalid",
109
135
  "email_unchanged",
110
136
  "email_change_unavailable",
111
137
  "current_session",
@@ -194,21 +220,24 @@ v.object({
194
220
  callbackURL: v.pipe(v.string(), v.url())
195
221
  });
196
222
  /** How a sign-in was made: the method it used, or the desktop app's approved code. */
197
- const cloudSignInMethodSchema = v.picklist([
223
+ const SIGN_IN_METHODS = [
198
224
  "password",
199
- "google",
200
- "apple",
225
+ ...CLOUD_SOCIAL_PROVIDERS,
201
226
  "passkey",
202
227
  "two-step",
203
228
  "email-link",
204
229
  "desktop",
205
230
  "other"
206
- ]);
231
+ ];
232
+ const cloudSignInMethodSchema = v.picklist(SIGN_IN_METHODS);
233
+ /** A method a newer server names that this editor does not know reads as `other`; a value that is
234
+ * not a method name at all still fails. */
235
+ const signInMethodResponseSchema = v.pipe(v.string(), v.transform((method) => v.is(cloudSignInMethodSchema, method) ? method : "other"));
207
236
  const cloudAccountSessionSchema = v.object({
208
237
  id: v.string(),
209
238
  /** The session this request was made with. */
210
239
  current: v.boolean(),
211
- method: v.nullable(cloudSignInMethodSchema),
240
+ method: v.nullable(signInMethodResponseSchema),
212
241
  ipAddress: v.nullable(v.string()),
213
242
  /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
214
243
  browser: v.nullable(v.string()),
@@ -221,7 +250,7 @@ const cloudAccountSessionsResponseSchema = v.object({ sessions: v.array(cloudAcc
221
250
  v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) });
222
251
  const cloudSignInSchema = v.object({
223
252
  id: v.string(),
224
- method: cloudSignInMethodSchema,
253
+ method: signInMethodResponseSchema,
225
254
  ipAddress: v.nullable(v.string()),
226
255
  /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
227
256
  browser: v.nullable(v.string()),
@@ -311,11 +340,38 @@ const chatModelSchema = v.object({
311
340
  });
312
341
  /** What one web search costs; a service without search leaves it out of its catalog. */
313
342
  const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema$1 });
314
- const serviceCatalogSchema = v.object({
343
+ const modelIDSchema = v.pipe(v.string(), v.minLength(1));
344
+ /**
345
+ * The model the service recommends for each of the editor's roles: Design runs the chat, Review
346
+ * critiques designs, Fast does quick tasks such as naming conversations, and Vision reads images.
347
+ * An editor signed in to the service with no model of its own yet sets itself up with them, so
348
+ * nobody has to choose one. Vision `null` recommends none, and the editor leaves it unassigned.
349
+ */
350
+ const roleModelsSchema = v.object({
351
+ design: modelIDSchema,
352
+ review: modelIDSchema,
353
+ fast: modelIDSchema,
354
+ vision: v.nullable(modelIDSchema)
355
+ });
356
+ const serviceCatalogSchema = v.pipe(v.object({
315
357
  models: v.array(chatModelSchema),
316
- defaultModelID: v.pipe(v.string(), v.minLength(1)),
358
+ defaultModelID: modelIDSchema,
359
+ /**
360
+ * Absent from a service that predates it, or whose default model can't run the chat. Editors
361
+ * then use `defaultModelID` for every role, except Vision when that model reads no images,
362
+ * and set nothing up when it calls no tools.
363
+ */
364
+ roleModels: v.optional(roleModelsSchema),
317
365
  search: v.optional(searchPricingSchema)
318
- });
366
+ }), v.check(({ models, roleModels }) => {
367
+ if (!roleModels) return true;
368
+ const can = (id, capability) => {
369
+ if (id === null) return true;
370
+ const model = models.find((candidate) => candidate.id === id);
371
+ return model !== void 0 && (capability === null || model.capabilities[capability]);
372
+ };
373
+ return can(roleModels.design, "tools") && can(roleModels.review, null) && can(roleModels.fast, "tools") && can(roleModels.vision, "vision");
374
+ }, "A recommended model is not in the catalog or cannot do its role"));
319
375
  const creditBucketSchema = v.object({
320
376
  kind: v.picklist([
321
377
  "allowance",
@@ -401,9 +457,22 @@ const idSchema = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/));
401
457
  const centsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
402
458
  const bytesSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
403
459
  const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
460
+ /**
461
+ * What an account without a plan has: the deployment's free plan, which a pricing page compares
462
+ * the plans with.
463
+ */
464
+ const billingFreePlanSchema = v.object({
465
+ /** The storage an account may use, or `null` for no limit. */
466
+ storageBytes: v.nullable(bytesSchema),
467
+ /** Whether the free plan includes services, such as AI and search. */
468
+ services: v.boolean(),
469
+ /** Credits granted each month with services, or `null` for no monthly limit. */
470
+ monthlyCredits: v.nullable(creditsSchema)
471
+ });
404
472
  const cloudBillingDiscoverySchema = v.object({
405
473
  endpoint: urlSchema,
406
- contractVersion: v.literal("1")
474
+ contractVersion: v.literal("1"),
475
+ freePlan: v.optional(billingFreePlanSchema)
407
476
  });
408
477
  const billingTokenSchema = v.object({
409
478
  token: v.pipe(v.string(), v.minLength(1)),
@@ -419,13 +488,34 @@ v.object({
419
488
  iat: v.pipe(v.number(), v.integer()),
420
489
  exp: v.pipe(v.number(), v.integer())
421
490
  });
422
- /** A plan an account subscribes to, billed every month in US dollars before tax. */
491
+ const seatCountSchema = v.pipe(v.number(), v.integer(), v.minValue(1));
492
+ /**
493
+ * A plan priced by the seat: everyone who can edit in the account's workspaces takes one, and the
494
+ * account pays for at least `minimum`. Every seat costs the price of the tier its count reaches,
495
+ * and adds its storage and credits to what the account shares.
496
+ */
497
+ const billingSeatPricingSchema = v.object({
498
+ minimum: seatCountSchema,
499
+ /** From the fewest seats up: the first from 1, each later one from more seats. */
500
+ tiers: v.pipe(v.array(v.object({
501
+ fromSeats: seatCountSchema,
502
+ unitPriceCents: centsSchema
503
+ })), v.minLength(1), v.check((tiers) => tiers[0]?.fromSeats === 1, "The first seat tier starts at one seat"), v.check((tiers) => tiers.every((tier, index) => index === 0 || tier.fromSeats > (tiers[index - 1]?.fromSeats ?? 0)), "Seat tiers start at more seats each")),
504
+ storageBytesPerSeat: bytesSchema,
505
+ monthlyCreditsPerSeat: creditsSchema
506
+ });
507
+ /**
508
+ * A plan an account subscribes to, billed every month in US dollars before tax. A plan priced by
509
+ * the seat states its price, storage, and credits at its minimum, so an editor that reads no
510
+ * `seats` still shows what it starts at.
511
+ */
423
512
  const billingPlanSchema = v.object({
424
513
  id: idSchema,
425
514
  name: v.pipe(v.string(), v.minLength(1)),
426
515
  monthlyPriceCents: centsSchema,
427
516
  storageBytes: bytesSchema,
428
- monthlyCredits: creditsSchema
517
+ monthlyCredits: creditsSchema,
518
+ seats: v.optional(billingSeatPricingSchema)
429
519
  });
430
520
  /** Credits an account on a plan buys once, in US dollars before tax. */
431
521
  const creditPackSchema = v.object({
@@ -435,16 +525,11 @@ const creditPackSchema = v.object({
435
525
  /** How long the credits last from purchase. */
436
526
  validDays: v.pipe(v.number(), v.integer(), v.minValue(1))
437
527
  });
438
- /** What the service sells; an account without a plan has its deployment's free entitlements. */
439
- const billingCatalogSchema = v.object({
528
+ v.object({
440
529
  plans: v.array(billingPlanSchema),
441
530
  creditPacks: v.array(creditPackSchema)
442
531
  });
443
- /**
444
- * The account's subscription as the payment provider holds it, or `null` without one. A
445
- * `past_due` plan keeps its entitlements while payment is retried.
446
- */
447
- const billingAccountSchema = v.object({ subscription: v.nullable(v.object({
532
+ v.object({ subscription: v.nullable(v.object({
448
533
  planId: idSchema,
449
534
  status: v.picklist(["active", "past_due"]),
450
535
  /** When the current period ends: the next charge, or the end of a cancelled plan. */
@@ -453,15 +538,14 @@ const billingAccountSchema = v.object({ subscription: v.nullable(v.object({
453
538
  cancelsAtPeriodEnd: v.boolean()
454
539
  })) });
455
540
  v.union([v.object({ planId: idSchema }), v.object({ creditPackId: idSchema })]);
456
- /** Where to send the person: the payment provider's checkout or account portal. */
457
- const billingRedirectSchema = v.object({ url: v.pipe(urlSchema, v.regex(/^https:\/\//i, "Billing sends people to an HTTPS page")) });
541
+ v.object({ url: v.pipe(urlSchema, v.regex(/^https:\/\//i, "Billing sends people to an HTTPS page")) });
458
542
  const billingErrorCodeSchema = v.picklist([
459
543
  "invalid_request",
460
544
  "unauthorized",
461
545
  "not_allowed",
462
546
  "provider_unavailable"
463
547
  ]);
464
- const billingErrorSchema = v.object({ error: v.object({
548
+ v.object({ error: v.object({
465
549
  code: billingErrorCodeSchema,
466
550
  message: v.optional(v.string())
467
551
  }) });
@@ -471,7 +555,19 @@ const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
471
555
  const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
472
556
  /** The most images one revision, or one request for image uploads, may name. */
473
557
  const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
474
- const imageNameSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9._-]{1,128}$/));
558
+ /**
559
+ * The most a Cloud API request body may hold; a server refuses anything past it before reading
560
+ * it. Files go to the object store, never through the API, so only lists grow large: a save's
561
+ * images fit with room to spare, and a client commits image uploads, whose part lists can run
562
+ * long, in batches under half of it.
563
+ */
564
+ const CLOUD_API_MAX_BODY_BYTES = 8388608;
565
+ /**
566
+ * An image's name inside a `.fig` file that Cloud stores apart from it: the SHA-1 Figma names it
567
+ * by, or an older plain name. A client leaves images under other names inside the file.
568
+ */
569
+ const CLOUD_IMAGE_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
570
+ const imageNameSchema = v.pipe(v.string(), v.regex(CLOUD_IMAGE_NAME_PATTERN));
475
571
  const objectDownloadSchema = v.object({
476
572
  url: v.pipe(v.string(), v.url()),
477
573
  method: v.literal("GET"),
@@ -682,6 +778,11 @@ const workspaceSummarySchema = v.object({
682
778
  name: v.string(),
683
779
  slug: v.string(),
684
780
  role: workspaceRoleSchema,
781
+ /**
782
+ * Whether the signed-in account owns the workspace, and so pays for its plan and AI credits.
783
+ * Absent from servers released before it.
784
+ */
785
+ owner: v.optional(v.boolean()),
685
786
  createdAt: v.string(),
686
787
  updatedAt: v.string()
687
788
  });
@@ -876,8 +977,11 @@ const adminErrorCodeSchema = v.picklist([
876
977
  "invalid_enrollment_transition",
877
978
  "last_admin_required",
878
979
  "self_admin_action_forbidden",
980
+ "last_authentication_method",
981
+ "account_approved",
879
982
  "email_regeneration_unavailable",
880
983
  "mfa_required",
984
+ "two_step_unconfirmed",
881
985
  "document_not_restorable",
882
986
  "workspace_gone"
883
987
  ]);
@@ -908,6 +1012,8 @@ const enrollmentsResponseSchema = v.object({
908
1012
  ...listTotals(enrollmentStatusSchema.options)
909
1013
  });
910
1014
  const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema });
1015
+ /** How many waiting requests were approved with the official deployment's invitation letter. */
1016
+ const enrollmentInviteResponseSchema = v.object({ invited: v.pipe(v.number(), v.integer(), v.minValue(0)) });
911
1017
  const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema });
912
1018
  const cloudAdminUserSchema = v.object({
913
1019
  ...cloudPersonSchema.entries,
@@ -919,7 +1025,14 @@ const cloudAdminUserSchema = v.object({
919
1025
  twoStep: v.boolean(),
920
1026
  /** When one of the account's sessions was last used, or null when none is left. */
921
1027
  lastActiveAt: nullableTimestampSchema,
922
- workspaceCount: countSchema
1028
+ workspaceCount: countSchema,
1029
+ /** How the account signs in: `credential` for a password, or a provider such as `google`. */
1030
+ methods: v.array(v.string()),
1031
+ /**
1032
+ * On a server that approves people, where this account's request to join stands: an account
1033
+ * exists from its first sign-in, before anyone approved it. Absent where everyone may join.
1034
+ */
1035
+ request: v.optional(v.nullable(enrollmentStatusSchema))
923
1036
  });
924
1037
  /** Which accounts a list of people shows. */
925
1038
  const cloudAdminUserFilterSchema = v.picklist([
@@ -928,6 +1041,7 @@ const cloudAdminUserFilterSchema = v.picklist([
928
1041
  "suspended",
929
1042
  "without-two-step"
930
1043
  ]);
1044
+ v.picklist(["password", ...CLOUD_SOCIAL_PROVIDERS]);
931
1045
  const cloudAdminUsersResponseSchema = v.object({
932
1046
  users: v.array(cloudAdminUserSchema),
933
1047
  ...listTotals(cloudAdminUserFilterSchema.options)
@@ -937,9 +1051,12 @@ const cloudAdminUserDetailSchema = v.object({
937
1051
  ...cloudAdminUserSchema.entries,
938
1052
  emailVerified: v.boolean()
939
1053
  }),
1054
+ /** `canRemove`: the account keeps a way in that still works without it. */
940
1055
  methods: v.array(v.object({
1056
+ id: v.string(),
941
1057
  provider: v.string(),
942
- createdAt: timestampSchema
1058
+ createdAt: timestampSchema,
1059
+ canRemove: v.boolean()
943
1060
  })),
944
1061
  authenticator: v.boolean(),
945
1062
  passkeyCount: countSchema,
@@ -1012,6 +1129,8 @@ const adminAuditResponseSchema = v.object({
1012
1129
  const cloudAdminDocumentSchema = v.object({
1013
1130
  id: v.string(),
1014
1131
  name: v.string(),
1132
+ /** A design or a board. Servers from before send none, and had only designs. */
1133
+ kind: v.optional(documentKindSchema, "design"),
1015
1134
  workspace: v.object({
1016
1135
  id: v.string(),
1017
1136
  name: v.string()
@@ -1033,7 +1152,25 @@ const cloudAdminDocumentSchema = v.object({
1033
1152
  * can still restore it. Servers from before Trash send neither.
1034
1153
  */
1035
1154
  purgedAt: v.optional(nullableTimestampSchema, null),
1036
- destroyedAt: v.optional(nullableTimestampSchema, null)
1155
+ destroyedAt: v.optional(nullableTimestampSchema, null),
1156
+ /**
1157
+ * The saved revision whose thumbnail previews it; null before its first save. Servers from
1158
+ * before previews send none.
1159
+ */
1160
+ revisionId: v.optional(v.nullable(v.string()), null),
1161
+ /**
1162
+ * Who beyond its workspace can open it: anyone, in the community gallery, and whoever holds one
1163
+ * of its live share links, `editLinks` of which let them edit. Servers from before send none.
1164
+ */
1165
+ exposure: v.optional(v.object({
1166
+ community: v.boolean(),
1167
+ links: countSchema,
1168
+ editLinks: countSchema
1169
+ }), {
1170
+ community: false,
1171
+ links: 0,
1172
+ editLinks: 0
1173
+ })
1037
1174
  });
1038
1175
  /** Which documents a list shows: live ones, or those deleted forever an administrator can restore. */
1039
1176
  const cloudAdminDocumentFilterSchema = v.picklist([
@@ -1134,6 +1271,11 @@ const accountEntitlementsSchema = workspaceEntitlementsSchema;
1134
1271
  const accountEntitlementsResponseSchema = v.object({ entitlements: accountEntitlementsSchema });
1135
1272
  const CLOUD_DISCOVERY_PATH = "/.well-known/openpencil";
1136
1273
  const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
1274
+ /**
1275
+ * The server's sign-in providers that this editor knows. A newer server may offer one this editor
1276
+ * has no button for; it is left out rather than failing discovery, so the editor still connects.
1277
+ */
1278
+ const socialProvidersSchema = v.pipe(v.array(v.string()), v.transform((providers) => providers.filter(isKnownSocialProvider)));
1137
1279
  const cloudAuthenticationSchema = v.object({
1138
1280
  emailPassword: v.optional(v.object({
1139
1281
  signIn: v.boolean(),
@@ -1144,7 +1286,7 @@ const cloudAuthenticationSchema = v.object({
1144
1286
  siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
1145
1287
  }))
1146
1288
  })),
1147
- socialProviders: v.array(v.picklist(["apple", "google"])),
1289
+ socialProviders: socialProvidersSchema,
1148
1290
  enterpriseSSO: v.boolean(),
1149
1291
  enrollmentMode: v.optional(v.picklist([
1150
1292
  "open",
@@ -1163,25 +1305,34 @@ const cloudCapabilitiesSchema = v.object({
1163
1305
  workspaces: v.boolean(),
1164
1306
  collaboration: v.boolean()
1165
1307
  });
1166
- /** A released editor version, `major.minor.patch`. */
1167
- const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
1168
- function editorVersionParts(version) {
1169
- const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
1170
- return match ? match.slice(1).map(Number) : null;
1308
+ /**
1309
+ * An editor version, as SemVer: a release such as `0.18.0`, or a pre-release such as
1310
+ * `0.18.0-beta.2` or a nightly's `0.18.0-nightly.20261116`.
1311
+ *
1312
+ * Editors before 0.18.0 accept only `major.minor.patch` here and fail discovery on anything else,
1313
+ * so a server names a pre-release minimum only once its minimum is already 0.18.0 or later.
1314
+ */
1315
+ const cloudEditorVersionSchema = v.pipe(v.string(), v.check(isSemVer, "Expected a SemVer version"));
1316
+ /**
1317
+ * Whether the text is exactly a SemVer version, build metadata included: semver's own parse also
1318
+ * takes a `v` prefix or spaces, which a version here never has.
1319
+ */
1320
+ function isSemVer(value) {
1321
+ const parsed = parseVersion(value);
1322
+ if (!parsed) return false;
1323
+ const build = parsed.build.length > 0 ? `+${parsed.build.join(".")}` : "";
1324
+ return `${parsed.version}${build}` === value;
1171
1325
  }
1172
1326
  /**
1173
- * Whether `version` is `minimum` or later, comparing `major.minor.patch` numerically; a prerelease
1174
- * counts as its release. A version that isn't one, on either side, is not at least anything.
1327
+ * Whether `version` is `minimum` or later, in SemVer order: a pre-release comes before its
1328
+ * release, so `0.18.0-beta.2` is not at least `0.18.0`; a release's nightlies come after its
1329
+ * betas and order by date. To admit a release's pre-releases, name the earliest one, such as
1330
+ * `0.18.0-beta.1`, or `0.18.0-nightly.20261116` for nightlies from that day on. A
1331
+ * version that isn't SemVer, on either side, is not at least anything.
1175
1332
  */
1176
1333
  function isEditorVersionAtLeast(version, minimum) {
1177
- const have = editorVersionParts(version);
1178
- const need = editorVersionParts(minimum);
1179
- if (!have || !need) return false;
1180
- for (let index = 0; index < need.length; index++) {
1181
- const difference = (have[index] ?? 0) - (need[index] ?? 0);
1182
- if (difference !== 0) return difference > 0;
1183
- }
1184
- return true;
1334
+ if (!isSemVer(version) || !isSemVer(minimum)) return false;
1335
+ return compareVersions(version, minimum) >= 0;
1185
1336
  }
1186
1337
  /**
1187
1338
  * Whether editors offer this server to everyone, and from which editor version on. Only the
@@ -1217,8 +1368,12 @@ const cloudBrandingSchema = v.object({
1217
1368
  /**
1218
1369
  * The server's community gallery: the workspace whose documents anyone may open read-only.
1219
1370
  * Saving to it publishes, so editors never choose it for anyone and say so when it is chosen.
1371
+ * `tourDocumentId` is the gallery document editors open as their tour.
1220
1372
  */
1221
- const cloudCommunityDiscoverySchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
1373
+ const cloudCommunityDiscoverySchema = v.object({
1374
+ workspaceId: v.pipe(v.string(), v.uuid()),
1375
+ tourDocumentId: v.optional(v.pipe(v.string(), v.uuid()))
1376
+ });
1222
1377
  const cloudDiscoverySchema = v.object({
1223
1378
  protocolVersion: v.literal("1"),
1224
1379
  deployment: cloudDeploymentSchema,
@@ -1294,6 +1449,159 @@ const restoredDocumentSchema = v.object({
1294
1449
  version: documentVersionSchema
1295
1450
  });
1296
1451
  //#endregion
1452
+ //#region src/contract/comments.ts
1453
+ /** The most a comment may say, in characters. */
1454
+ const COMMENT_BODY_MAX_LENGTH = 1e4;
1455
+ const ID_MAX_LENGTH = 200;
1456
+ /**
1457
+ * Who wrote a comment: an account, whose name is null once it is deleted, or a name a file gave
1458
+ * when the comment came in with it, which no account vouches for.
1459
+ */
1460
+ const commentAuthorSchema = v.variant("kind", [v.object({
1461
+ kind: v.literal("user"),
1462
+ id: v.string(),
1463
+ name: v.nullable(v.string())
1464
+ }), v.object({
1465
+ kind: v.literal("imported"),
1466
+ name: v.string()
1467
+ })]);
1468
+ const cloudCommentSchema = v.object({
1469
+ id: v.pipe(v.string(), v.uuid()),
1470
+ author: commentAuthorSchema,
1471
+ /** The agent that wrote it on its author's behalf. */
1472
+ agent: v.nullable(v.string()),
1473
+ /** Markdown, as the editor writes it. */
1474
+ body: v.string(),
1475
+ /** The accounts it names, which hear about it. */
1476
+ mentions: v.array(v.string()),
1477
+ createdAt: v.string(),
1478
+ editedAt: v.nullable(v.string())
1479
+ });
1480
+ /** Where a pin sits, as the editor places it. */
1481
+ const commentAnchorEntries = {
1482
+ pageId: v.pipe(v.string(), v.minLength(1), v.maxLength(ID_MAX_LENGTH)),
1483
+ pageName: v.nullable(v.pipe(v.string(), v.maxLength(255))),
1484
+ /** The top-level layer the pin follows, if any. */
1485
+ nodeId: v.nullable(v.pipe(v.string(), v.minLength(1), v.maxLength(ID_MAX_LENGTH))),
1486
+ nodeName: v.nullable(v.pipe(v.string(), v.maxLength(255))),
1487
+ /** The pin's offset from the layer's top-left corner. */
1488
+ offsetX: v.nullable(v.pipe(v.number(), v.finite())),
1489
+ offsetY: v.nullable(v.pipe(v.number(), v.finite())),
1490
+ /** The pin's canvas position, used once the layer is gone. */
1491
+ x: v.pipe(v.number(), v.finite()),
1492
+ y: v.pipe(v.number(), v.finite())
1493
+ };
1494
+ const commentAnchorSchema = v.object(commentAnchorEntries);
1495
+ const cloudCommentThreadSchema = v.object({
1496
+ id: v.pipe(v.string(), v.uuid()),
1497
+ ...commentAnchorEntries,
1498
+ createdAt: v.string(),
1499
+ /** When anything in the thread last changed: a comment, the pin, or whether it is resolved. */
1500
+ updatedAt: v.string(),
1501
+ resolvedAt: v.nullable(v.string()),
1502
+ resolvedBy: v.nullable(v.string()),
1503
+ /** Who started it, or brought it in from a file: they may move its pin and delete it. */
1504
+ createdBy: v.string(),
1505
+ /** Whether someone else wrote in it since the asker last read it; false for a guest. */
1506
+ unread: v.boolean(),
1507
+ /** Oldest first; the first is what started the thread. */
1508
+ comments: v.array(cloudCommentSchema)
1509
+ });
1510
+ /** What the person asking may do with the document's comments. */
1511
+ const commentAccessSchema = v.object({
1512
+ /** Start threads, reply, and change their own comments; anyone signed in who can view. */
1513
+ canComment: v.boolean(),
1514
+ /** Delete anyone's comments; editors. */
1515
+ canModerate: v.boolean(),
1516
+ /** The asker's account, which their own comments name; null for a guest. */
1517
+ accountId: v.nullable(v.string())
1518
+ });
1519
+ const commentThreadsSchema = v.object({
1520
+ threads: v.array(cloudCommentThreadSchema),
1521
+ access: commentAccessSchema
1522
+ });
1523
+ const commentThreadResponseSchema = v.object({ thread: cloudCommentThreadSchema });
1524
+ const bodySchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(COMMENT_BODY_MAX_LENGTH));
1525
+ /** The accounts a comment names; the server keeps those who can read the document. */
1526
+ const mentionsSchema = v.optional(v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), v.maxLength(50)), []);
1527
+ const agentSchema = v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)));
1528
+ /**
1529
+ * The ID the editor gave a new thread or comment, so it keeps showing it as the server's, and a
1530
+ * request sent again finds what the first one made.
1531
+ */
1532
+ const clientIdSchema = v.optional(v.pipe(v.string(), v.uuid()));
1533
+ const createCommentThreadSchema = v.object({
1534
+ id: clientIdSchema,
1535
+ ...commentAnchorEntries,
1536
+ body: bodySchema,
1537
+ mentions: mentionsSchema,
1538
+ agent: agentSchema
1539
+ });
1540
+ /** Resolves or reopens a thread, or moves its pin; what is left out stays as it is. */
1541
+ const updateCommentThreadSchema = v.object({
1542
+ resolved: v.optional(v.boolean()),
1543
+ anchor: v.optional(commentAnchorSchema)
1544
+ });
1545
+ const createCommentSchema = v.object({
1546
+ id: clientIdSchema,
1547
+ body: bodySchema,
1548
+ mentions: mentionsSchema,
1549
+ agent: agentSchema
1550
+ });
1551
+ const updateCommentSchema = v.object({
1552
+ body: bodySchema,
1553
+ mentions: mentionsSchema
1554
+ });
1555
+ /** Someone a comment may name: an account that can open the document. */
1556
+ const commentPersonSchema = v.object({
1557
+ id: v.string(),
1558
+ name: v.string(),
1559
+ image: v.nullable(v.string())
1560
+ });
1561
+ const commentPeopleSchema = v.object({ people: v.array(commentPersonSchema) });
1562
+ /** Which comments an account hears about by email. */
1563
+ const commentEmailSettingSchema = v.picklist([
1564
+ "all",
1565
+ "mentions",
1566
+ "off"
1567
+ ]);
1568
+ const notificationSettingsSchema = v.object({ commentEmails: commentEmailSettingSchema });
1569
+ /** The most threads, and comments in all, one import brings in. */
1570
+ const MAX_IMPORTED_COMMENT_THREADS = 1e3;
1571
+ const MAX_IMPORTED_COMMENTS = 1e4;
1572
+ v.object({ threads: v.pipe(v.array(v.object({
1573
+ ...commentAnchorEntries,
1574
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
1575
+ resolved: v.boolean(),
1576
+ comments: v.pipe(v.array(v.object({
1577
+ authorName: v.pipe(v.string(), v.trim(), v.maxLength(255)),
1578
+ body: bodySchema,
1579
+ createdAt: v.pipe(v.string(), v.isoTimestamp())
1580
+ })), v.minLength(1), v.maxLength(MAX_IMPORTED_COMMENTS))
1581
+ })), v.maxLength(MAX_IMPORTED_COMMENT_THREADS), v.check((threads) => threads.reduce((total, thread) => total + thread.comments.length, 0) <= MAX_IMPORTED_COMMENTS, `An import brings in at most ${MAX_IMPORTED_COMMENTS} comments`)) });
1582
+ /**
1583
+ * The same requests made through a share link: the link's secret rides in the body, as it does
1584
+ * for opening the document, since it must stay out of the address.
1585
+ */
1586
+ const shareEntries = { share: v.pick(resolveDocumentShareSchema, ["secret"]) };
1587
+ v.object(shareEntries);
1588
+ v.object({
1589
+ ...shareEntries,
1590
+ ...createCommentThreadSchema.entries
1591
+ });
1592
+ v.object({
1593
+ ...shareEntries,
1594
+ ...updateCommentThreadSchema.entries
1595
+ });
1596
+ v.object({
1597
+ ...shareEntries,
1598
+ ...createCommentSchema.entries
1599
+ });
1600
+ v.object({
1601
+ ...shareEntries,
1602
+ ...updateCommentSchema.entries
1603
+ });
1604
+ //#endregion
1297
1605
  //#region src/contract/community.ts
1298
1606
  /** A version of a community document someone named, such as the release it was published for. */
1299
1607
  const communityVersionSchema = v.object({
@@ -1376,9 +1684,9 @@ function cloudServicesFetch(tokens, fetch) {
1376
1684
  return send(input, init, await tokens.token());
1377
1685
  };
1378
1686
  }
1379
- const errorBodySchema$1 = v.pipe(v.string(), v.parseJson(), serviceErrorSchema);
1380
- function refused$1(status, body) {
1381
- const error = v.safeParse(errorBodySchema$1, body);
1687
+ const errorBodySchema = v.pipe(v.string(), v.parseJson(), serviceErrorSchema);
1688
+ function refused(status, body) {
1689
+ const error = v.safeParse(errorBodySchema, body);
1382
1690
  return new CloudServiceError(status, error.success ? error.output.error.code : void 0);
1383
1691
  }
1384
1692
  /** The services a Cloud advertises: the model API base URL, catalog, wallet, and search. */
@@ -1391,56 +1699,14 @@ function createCloudServicesClient(options) {
1391
1699
  modelBaseURL: joinURL(endpoint, CLOUD_SERVICES_API_PATHS.base),
1392
1700
  fetch,
1393
1701
  async catalog() {
1394
- return serviceJSON(await v1.catalog.$get(), serviceCatalogSchema, refused$1);
1702
+ return serviceJSON(await v1.catalog.$get(), serviceCatalogSchema, refused);
1395
1703
  },
1396
1704
  async wallet() {
1397
- return serviceJSON(await v1.wallet.$get(), creditWalletSchema, refused$1);
1705
+ return serviceJSON(await v1.wallet.$get(), creditWalletSchema, refused);
1398
1706
  },
1399
1707
  /** A web search, charged to the workspace; only when the catalog lists `search`. */
1400
1708
  async search(input) {
1401
- return serviceJSON(await v1.search.$post({ json: input }), searchResponseSchema, refused$1);
1402
- }
1403
- };
1404
- }
1405
- //#endregion
1406
- //#region src/client/billing.ts
1407
- var CloudBillingError = class extends Error {
1408
- status;
1409
- code;
1410
- name = "CloudBillingError";
1411
- constructor(status, code) {
1412
- super(`OpenPencil billing request failed with HTTP ${status}`);
1413
- this.status = status;
1414
- this.code = code;
1415
- }
1416
- };
1417
- const errorBodySchema = v.pipe(v.string(), v.parseJson(), billingErrorSchema);
1418
- function refused(status, body) {
1419
- const error = v.safeParse(errorBodySchema, body);
1420
- return new CloudBillingError(status, error.success ? error.output.error.code : void 0);
1421
- }
1422
- /**
1423
- * The billing a Cloud advertises: what it sells, the account's subscription, and where to buy or
1424
- * manage it. Checkout and the portal answer with the payment provider's page to open, so a token
1425
- * never travels in a URL.
1426
- */
1427
- function createCloudBillingClient(options) {
1428
- const endpoint = withoutTrailingSlash(options.endpoint);
1429
- const { v1 } = hc(endpoint, { fetch: cloudServicesFetch(options.tokens, options.fetch) });
1430
- return {
1431
- async catalog() {
1432
- return serviceJSON(await v1.catalog.$get(), billingCatalogSchema, refused);
1433
- },
1434
- async account() {
1435
- return serviceJSON(await v1.account.$get(), billingAccountSchema, refused);
1436
- },
1437
- /** The checkout page that buys `request` for the account. */
1438
- async checkout(request) {
1439
- return (await serviceJSON(await v1.checkout.$post({ json: request }), billingRedirectSchema, refused)).url;
1440
- },
1441
- /** The page where the account cancels, changes its card, and reads its invoices. */
1442
- async portal() {
1443
- return (await serviceJSON(await v1.portal.$post(), billingRedirectSchema, refused)).url;
1709
+ return serviceJSON(await v1.search.$post({ json: input }), searchResponseSchema, refused);
1444
1710
  }
1445
1711
  };
1446
1712
  }
@@ -1473,6 +1739,508 @@ function cloudRedirectPath(value, fallback = "/app") {
1473
1739
  return `${url.pathname}${url.search}${url.hash}`;
1474
1740
  }
1475
1741
  //#endregion
1742
+ //#region src/client/files/archive.ts
1743
+ /** Where a `.fig` archive keeps its images, each under the name its paints refer to. */
1744
+ const IMAGE_ENTRY_PREFIX = "images/";
1745
+ function archiveEntry(bytes, entry) {
1746
+ return {
1747
+ name: entry.name,
1748
+ data: zipEntryContents(bytes, entry),
1749
+ deflate: entry.method !== 0
1750
+ };
1751
+ }
1752
+ /**
1753
+ * The archive without its images, and the images, as views of `bytes`. A file that is not a zip
1754
+ * archive, or holds no images, comes back whole; an image under a name Cloud does not store
1755
+ * apart stays inside.
1756
+ */
1757
+ async function splitCloudDocument(bytes) {
1758
+ const entries = readZipDirectory(bytes);
1759
+ if (!entries) return {
1760
+ lean: bytes,
1761
+ images: []
1762
+ };
1763
+ const images = [];
1764
+ const rest = [];
1765
+ for (const entry of entries) {
1766
+ const name = entry.name.startsWith(IMAGE_ENTRY_PREFIX) ? entry.name.slice(7) : null;
1767
+ if (name && CLOUD_IMAGE_NAME_PATTERN.test(name) && entry.size > 0) images.push({
1768
+ name,
1769
+ bytes: zipEntryContents(bytes, entry)
1770
+ });
1771
+ else rest.push(archiveEntry(bytes, entry));
1772
+ }
1773
+ if (images.length === 0) return {
1774
+ lean: bytes,
1775
+ images
1776
+ };
1777
+ return {
1778
+ lean: await readStreamBytes(zipStream(rest)),
1779
+ images
1780
+ };
1781
+ }
1782
+ /** The archive with its images put back under their names; the lean archive when there are none. */
1783
+ async function assembleCloudDocument(lean, images) {
1784
+ const entries = images.length === 0 ? null : readZipDirectory(lean);
1785
+ if (!entries) return lean;
1786
+ return readStreamBytes(zipStream([...entries.map((entry) => archiveEntry(lean, entry)), ...images.map((image) => ({
1787
+ name: `${IMAGE_ENTRY_PREFIX}${image.name}`,
1788
+ data: image.bytes
1789
+ }))]));
1790
+ }
1791
+ //#endregion
1792
+ //#region src/client/files/checksum.ts
1793
+ /** The SHA-256 of `bytes`, in Base64, as Cloud checks an upload against it. */
1794
+ async function cloudChecksum(bytes) {
1795
+ return fromUint8Array(sha256(bytes));
1796
+ }
1797
+ //#endregion
1798
+ //#region src/client/files/download.ts
1799
+ const IMAGE_DOWNLOAD_CONCURRENCY = 6;
1800
+ /** An object's bytes from the store, checked against the size and checksum the server recorded. */
1801
+ async function fetchVerified(target, expected, objectFetch, signal) {
1802
+ const response = await objectFetch(target.url, {
1803
+ method: target.method,
1804
+ headers: target.headers,
1805
+ signal
1806
+ });
1807
+ if (!response.ok) throw new Error(`Cloud document download failed with HTTP ${response.status}`);
1808
+ const bytes = new Uint8Array(await response.arrayBuffer());
1809
+ if (bytes.byteLength !== expected.byteSize || await cloudChecksum(bytes) !== expected.checksum) throw new Error("The downloaded Cloud document does not match what the server stored");
1810
+ return bytes;
1811
+ }
1812
+ /** An image a live room names, from where the server linked it, checked against its record. */
1813
+ function downloadCloudImage(link, objectFetch, signal) {
1814
+ return fetchVerified(link.download, link, objectFetch, signal);
1815
+ }
1816
+ /** A revision as the editor opens it: its stored file with every image put back under its name. */
1817
+ async function downloadCloudDocument(download, objectFetch, options = {}) {
1818
+ const totalBytes = download.byteSize + sumBy(download.images, (image) => image.byteSize);
1819
+ let transferredBytes = 0;
1820
+ const received = (bytes) => {
1821
+ transferredBytes += bytes.byteLength;
1822
+ options.onProgress?.({
1823
+ transferredBytes,
1824
+ totalBytes
1825
+ });
1826
+ return bytes;
1827
+ };
1828
+ const fetchImage = limitAsync(async (image) => ({
1829
+ name: image.name,
1830
+ bytes: received(await fetchVerified(image.download, image, objectFetch, options.signal))
1831
+ }), IMAGE_DOWNLOAD_CONCURRENCY);
1832
+ const [lean, ...images] = await Promise.all([fetchVerified(download.download, download, objectFetch, options.signal).then(received), ...download.images.map(fetchImage)]);
1833
+ return assembleCloudDocument(lean, images);
1834
+ }
1835
+ /**
1836
+ * Reads exactly `length` bytes of a response, stopping a body that runs past them rather than
1837
+ * receiving the rest.
1838
+ */
1839
+ async function readExactly(response, length) {
1840
+ const bytes = new Uint8Array(length);
1841
+ let received = 0;
1842
+ const reader = response.body?.getReader();
1843
+ if (reader) for (;;) {
1844
+ const { done, value } = await reader.read();
1845
+ if (done) break;
1846
+ if (received + value.byteLength > length) {
1847
+ await reader.cancel();
1848
+ throw new Error(`Cloud document range read sent more than the ${length} bytes asked for`);
1849
+ }
1850
+ bytes.set(value, received);
1851
+ received += value.byteLength;
1852
+ }
1853
+ if (received !== length) throw new Error(`Cloud document range read sent ${received} of the ${length} bytes asked for`);
1854
+ return bytes;
1855
+ }
1856
+ /**
1857
+ * Bytes `start` to `endExclusive` of a revision, for reading its preview without the rest. Only
1858
+ * a partial response of exactly that range counts: a store that ignores the range, or answers
1859
+ * another one, is stopped rather than left sending the file. `Content-Range` is checked when the
1860
+ * store's CORS rules let the browser read it.
1861
+ */
1862
+ async function readCloudRevisionRange(download, objectFetch, start, endExclusive) {
1863
+ const response = await objectFetch(download.download.url, {
1864
+ method: download.download.method,
1865
+ headers: {
1866
+ ...download.download.headers,
1867
+ Range: `bytes=${start}-${endExclusive - 1}`
1868
+ }
1869
+ });
1870
+ const range = response.headers.get("Content-Range");
1871
+ if (response.status !== 206 || range && !range.startsWith(`bytes ${start}-${endExclusive - 1}/`)) {
1872
+ await response.body?.cancel();
1873
+ throw new Error(`Cloud document range read failed with HTTP ${response.status}${range ? ` (${range})` : ""}`);
1874
+ }
1875
+ return readExactly(response, endExclusive - start);
1876
+ }
1877
+ //#endregion
1878
+ //#region src/client/files/objects.ts
1879
+ const MULTIPART_CONCURRENCY = 4;
1880
+ const PART_RETRIES = 2;
1881
+ /** A part's upload is retried soon, since a part fails on a dropped connection more than a busy store. */
1882
+ const PART_RETRY = {
1883
+ baseMs: 200,
1884
+ capMs: 5 * SECOND_MS,
1885
+ jitter: true
1886
+ };
1887
+ /** An object-store request the presigned URL refused or the store failed. */
1888
+ var ObjectUploadError = class extends Error {
1889
+ status;
1890
+ name = "ObjectUploadError";
1891
+ constructor(status) {
1892
+ super(`Cloud object upload failed with HTTP ${status}`);
1893
+ this.status = status;
1894
+ }
1895
+ };
1896
+ const retryable = (status) => status === 408 || status === 429 || status >= 500;
1897
+ const expired = (error) => error instanceof ObjectUploadError && (error.status === 401 || error.status === 403);
1898
+ function body(bytes) {
1899
+ return bytes.buffer instanceof ArrayBuffer ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) : Uint8Array.from(bytes);
1900
+ }
1901
+ function report(upload, transferredBytes) {
1902
+ upload.onProgress?.({
1903
+ transferredBytes,
1904
+ totalBytes: upload.bytes.byteLength
1905
+ });
1906
+ }
1907
+ async function putPart(upload, part, bytes, signal) {
1908
+ return retry(async () => {
1909
+ const response = await upload.objectFetch(part.url, {
1910
+ method: part.method,
1911
+ headers: part.headers,
1912
+ body: body(bytes),
1913
+ signal
1914
+ });
1915
+ if (!response.ok) throw new ObjectUploadError(response.status);
1916
+ const etag = response.headers.get("etag");
1917
+ if (!etag) throw new Error("Cloud multipart upload response did not include an ETag");
1918
+ return etag;
1919
+ }, {
1920
+ retries: PART_RETRIES,
1921
+ delay: (attempt) => backoffDelay(attempt, PART_RETRY),
1922
+ signal,
1923
+ shouldRetry: (error) => error instanceof ObjectUploadError && retryable(error.status)
1924
+ });
1925
+ }
1926
+ async function putParts(upload, multipart) {
1927
+ const controller = new AbortController();
1928
+ const stop = () => controller.abort(upload.signal?.reason);
1929
+ upload.signal?.addEventListener("abort", stop, { once: true });
1930
+ let transferred = 0;
1931
+ const putOne = limitAsync(async (part) => {
1932
+ try {
1933
+ controller.signal.throwIfAborted();
1934
+ const start = (part.partNumber - 1) * multipart.partSize;
1935
+ const bytes = upload.bytes.subarray(start, start + multipart.partSize);
1936
+ const etag = await putPart(upload, part, bytes, controller.signal);
1937
+ transferred += bytes.byteLength;
1938
+ report(upload, transferred);
1939
+ return {
1940
+ partNumber: part.partNumber,
1941
+ etag
1942
+ };
1943
+ } catch (error) {
1944
+ controller.abort(error);
1945
+ throw error;
1946
+ }
1947
+ }, MULTIPART_CONCURRENCY);
1948
+ try {
1949
+ return await Promise.all(multipart.parts.map(putOne));
1950
+ } finally {
1951
+ upload.signal?.removeEventListener("abort", stop);
1952
+ }
1953
+ }
1954
+ /**
1955
+ * Puts bytes where the server said, in parallel parts for a multipart upload. What a commit names
1956
+ * of a multipart upload, or nothing for a single one.
1957
+ */
1958
+ async function putCloudObject(target, upload) {
1959
+ report(upload, 0);
1960
+ if (target.kind === "single") {
1961
+ const response = await upload.objectFetch(target.url, {
1962
+ method: target.method,
1963
+ headers: target.headers,
1964
+ body: body(upload.bytes),
1965
+ signal: upload.signal
1966
+ });
1967
+ if (!response.ok) throw new ObjectUploadError(response.status);
1968
+ report(upload, upload.bytes.byteLength);
1969
+ return;
1970
+ }
1971
+ const parts = await putParts(upload, target);
1972
+ return {
1973
+ uploadId: target.uploadId,
1974
+ parts
1975
+ };
1976
+ }
1977
+ async function transfer(upload) {
1978
+ const pending = await upload.cloud.createUpload(upload.documentId, {
1979
+ baseRevisionId: upload.baseRevision,
1980
+ byteSize: upload.bytes.byteLength,
1981
+ checksum: upload.checksum,
1982
+ contentType: "application/octet-stream"
1983
+ });
1984
+ const multipart = await putCloudObject(pending.upload, upload);
1985
+ return multipart ? {
1986
+ uploadId: pending.id,
1987
+ multipart
1988
+ } : { uploadId: pending.id };
1989
+ }
1990
+ /**
1991
+ * Sends a document's bytes straight to the server's object store through presigned URLs, in
1992
+ * parallel parts for large files, starting once more if the URLs expired on the way.
1993
+ */
1994
+ async function uploadCloudObject(upload) {
1995
+ try {
1996
+ return await transfer(upload);
1997
+ } catch (error) {
1998
+ if (!expired(error)) throw error;
1999
+ upload.signal?.throwIfAborted();
2000
+ return transfer(upload);
2001
+ }
2002
+ }
2003
+ //#endregion
2004
+ //#region src/client/files/images.ts
2005
+ const IMAGE_UPLOAD_CONCURRENCY = 4;
2006
+ /** How much of a request one image commit may fill: each upload brings its parts' ETags. */
2007
+ const IMAGE_COMMIT_BYTES = CLOUD_API_MAX_BODY_BYTES / 2;
2008
+ /** What one upload adds to a commit besides its parts: its keys, its ID, and its checksum. */
2009
+ const UPLOAD_ENTRY_BYTES = 256;
2010
+ /** What one part adds besides its ETag: its keys, a part number up to 10,000, and escaped quotes. */
2011
+ const PART_ENTRY_BYTES = 48;
2012
+ /**
2013
+ * At most what an upload adds to a commit's body: fixed room for its fields, and the lengths of
2014
+ * the strings the object store chose, its multipart upload's ID and each part's ETag.
2015
+ */
2016
+ function commitEntryBytes(upload) {
2017
+ const multipart = upload.multipart;
2018
+ if (!multipart) return UPLOAD_ENTRY_BYTES;
2019
+ return UPLOAD_ENTRY_BYTES + multipart.uploadId.length + sumBy(multipart.parts, (part) => PART_ENTRY_BYTES + part.etag.length);
2020
+ }
2021
+ /** Uploads in commits that each stay under `IMAGE_COMMIT_BYTES` once sent. */
2022
+ function imageCommitBatches(uploads) {
2023
+ const batches = [];
2024
+ let batch = [];
2025
+ let bytes = 0;
2026
+ for (const upload of uploads) {
2027
+ const size = commitEntryBytes(upload);
2028
+ if (batch.length > 0 && bytes + size > IMAGE_COMMIT_BYTES) {
2029
+ batches.push(batch);
2030
+ batch = [];
2031
+ bytes = 0;
2032
+ }
2033
+ batch.push(upload);
2034
+ bytes += size;
2035
+ }
2036
+ if (batch.length > 0) batches.push(batch);
2037
+ return batches;
2038
+ }
2039
+ /**
2040
+ * Uploads the images the document's workspace lacks: the server answers with uploads for those
2041
+ * only, and they are committed together once their bytes are in place.
2042
+ */
2043
+ async function uploadCloudImages(input) {
2044
+ if (input.images.length === 0) return;
2045
+ const byChecksum = new Map(input.images.map((image) => [image.checksum, image.bytes]));
2046
+ const offers = await input.cloud.requestImageUploads(input.documentId, { images: [...byChecksum].map(([checksum, bytes]) => ({
2047
+ checksum,
2048
+ byteSize: bytes.byteLength
2049
+ })) });
2050
+ if (offers.length === 0) return;
2051
+ const put = limitAsync((target, bytes) => putCloudObject(target, {
2052
+ bytes,
2053
+ objectFetch: input.objectFetch,
2054
+ signal: input.signal
2055
+ }), IMAGE_UPLOAD_CONCURRENCY);
2056
+ const uploaded = await Promise.all(offers.map(async (offer) => {
2057
+ const bytes = byChecksum.get(offer.checksum);
2058
+ if (!bytes) throw new Error("The server offered an upload for an image this save lacks");
2059
+ const multipart = await put(offer.upload, bytes);
2060
+ return {
2061
+ uploadId: offer.uploadId,
2062
+ checksum: offer.checksum,
2063
+ multipart
2064
+ };
2065
+ }));
2066
+ for (const batch of imageCommitBatches(uploaded)) await input.cloud.commitImageUploads(input.documentId, batch);
2067
+ }
2068
+ //#endregion
2069
+ //#region src/client/comments.ts
2070
+ /** A thread after deleting one of its comments; null once the thread went with its first. */
2071
+ const threadOrGoneSchema = v.nullable(commentThreadResponseSchema);
2072
+ async function thread(request, onDiagnostic) {
2073
+ return (await parseResponse(request, commentThreadResponseSchema, onDiagnostic)).thread;
2074
+ }
2075
+ async function threadOrGone(request, onDiagnostic) {
2076
+ return (await parseResponse(request, threadOrGoneSchema, onDiagnostic))?.thread ?? null;
2077
+ }
2078
+ /** Comment requests for documents people reach through membership or a direct grant. */
2079
+ function createCommentRequests(client, onDiagnostic) {
2080
+ return {
2081
+ /** The comments of a document the signed-in account can open. */
2082
+ documentComments(documentId) {
2083
+ const threads = client.documents[":documentId"].threads;
2084
+ const one = threads[":threadId"];
2085
+ const comment = one.comments[":commentId"];
2086
+ return {
2087
+ list: () => parseResponse(threads.$get({ param: { documentId } }), commentThreadsSchema, onDiagnostic),
2088
+ get: (threadId) => thread(one.$get({ param: {
2089
+ documentId,
2090
+ threadId
2091
+ } }), onDiagnostic),
2092
+ createThread: (json) => thread(threads.$post({
2093
+ param: { documentId },
2094
+ json
2095
+ }), onDiagnostic),
2096
+ updateThread: (threadId, json) => thread(one.$patch({
2097
+ param: {
2098
+ documentId,
2099
+ threadId
2100
+ },
2101
+ json
2102
+ }), onDiagnostic),
2103
+ deleteThread: async (threadId) => {
2104
+ await parseResponse(one.$delete({ param: {
2105
+ documentId,
2106
+ threadId
2107
+ } }), v.null(), onDiagnostic);
2108
+ },
2109
+ reply: (threadId, json) => thread(one.comments.$post({
2110
+ param: {
2111
+ documentId,
2112
+ threadId
2113
+ },
2114
+ json
2115
+ }), onDiagnostic),
2116
+ updateComment: (threadId, commentId, json) => thread(comment.$patch({
2117
+ param: {
2118
+ documentId,
2119
+ threadId,
2120
+ commentId
2121
+ },
2122
+ json
2123
+ }), onDiagnostic),
2124
+ deleteComment: (threadId, commentId) => threadOrGone(comment.$delete({ param: {
2125
+ documentId,
2126
+ threadId,
2127
+ commentId
2128
+ } }), onDiagnostic),
2129
+ markRead: async (threadId) => {
2130
+ await parseResponse(one.read.$post({ param: {
2131
+ documentId,
2132
+ threadId
2133
+ } }), v.null(), onDiagnostic);
2134
+ }
2135
+ };
2136
+ },
2137
+ /** Whom the signed-in account may name in a document's comments. */
2138
+ async commentPeople(documentId) {
2139
+ return (await parseResponse(client.documents[":documentId"].threads.people.$get({ param: { documentId } }), commentPeopleSchema, onDiagnostic)).people;
2140
+ },
2141
+ /** Which comments the signed-in account hears about by email. */
2142
+ notificationSettings() {
2143
+ return parseResponse(client.account.notifications.$get(), notificationSettingsSchema, onDiagnostic);
2144
+ },
2145
+ setNotificationSettings(json) {
2146
+ return parseResponse(client.account.notifications.$put({ json }), notificationSettingsSchema, onDiagnostic);
2147
+ },
2148
+ /** Brings a file's threads into a document that just moved to Cloud. */
2149
+ async importCommentThreads(documentId, json) {
2150
+ return parseResponse(client.documents[":documentId"].threads.import.$post({
2151
+ param: { documentId },
2152
+ json
2153
+ }), commentThreadsSchema, onDiagnostic);
2154
+ }
2155
+ };
2156
+ }
2157
+ /** Comment requests through a share link, whose secret every request carries in its body. */
2158
+ function createSharedCommentRequests(publicClient, onDiagnostic) {
2159
+ return { sharedComments(shareId, secret) {
2160
+ const share = { secret };
2161
+ const threads = publicClient.shares[":shareId"].threads;
2162
+ const one = threads[":threadId"];
2163
+ const comment = one.comments[":commentId"];
2164
+ return {
2165
+ list: () => parseResponse(threads.list.$post({
2166
+ param: { shareId },
2167
+ json: { share }
2168
+ }), commentThreadsSchema, onDiagnostic),
2169
+ get: (threadId) => thread(one.get.$post({
2170
+ param: {
2171
+ shareId,
2172
+ threadId
2173
+ },
2174
+ json: { share }
2175
+ }), onDiagnostic),
2176
+ createThread: (input) => thread(threads.$post({
2177
+ param: { shareId },
2178
+ json: {
2179
+ share,
2180
+ ...input
2181
+ }
2182
+ }), onDiagnostic),
2183
+ updateThread: (threadId, input) => thread(one.$patch({
2184
+ param: {
2185
+ shareId,
2186
+ threadId
2187
+ },
2188
+ json: {
2189
+ share,
2190
+ ...input
2191
+ }
2192
+ }), onDiagnostic),
2193
+ deleteThread: async (threadId) => {
2194
+ await parseResponse(one.$delete({
2195
+ param: {
2196
+ shareId,
2197
+ threadId
2198
+ },
2199
+ json: { share }
2200
+ }), v.null(), onDiagnostic);
2201
+ },
2202
+ reply: (threadId, input) => thread(one.comments.$post({
2203
+ param: {
2204
+ shareId,
2205
+ threadId
2206
+ },
2207
+ json: {
2208
+ share,
2209
+ ...input
2210
+ }
2211
+ }), onDiagnostic),
2212
+ updateComment: (threadId, commentId, input) => thread(comment.$patch({
2213
+ param: {
2214
+ shareId,
2215
+ threadId,
2216
+ commentId
2217
+ },
2218
+ json: {
2219
+ share,
2220
+ ...input
2221
+ }
2222
+ }), onDiagnostic),
2223
+ deleteComment: (threadId, commentId) => threadOrGone(comment.$delete({
2224
+ param: {
2225
+ shareId,
2226
+ threadId,
2227
+ commentId
2228
+ },
2229
+ json: { share }
2230
+ }), onDiagnostic),
2231
+ markRead: async (threadId) => {
2232
+ await parseResponse(one.read.$post({
2233
+ param: {
2234
+ shareId,
2235
+ threadId
2236
+ },
2237
+ json: { share }
2238
+ }), v.null(), onDiagnostic);
2239
+ }
2240
+ };
2241
+ } };
2242
+ }
2243
+ //#endregion
1476
2244
  //#region src/client/community.ts
1477
2245
  /** The server’s community gallery, which anyone may open without signing in. */
1478
2246
  function createCommunityRequests(publicClient, onDiagnostic) {
@@ -1759,7 +2527,10 @@ function createVersionRequests(client, onDiagnostic) {
1759
2527
  async listDocumentVersions(documentId, page = {}) {
1760
2528
  return parseResponse(client.documents[":documentId"].versions.$get({
1761
2529
  param: { documentId },
1762
- query: pickBy(page, (value) => value !== void 0)
2530
+ query: pickBy({
2531
+ before: page.before,
2532
+ limit: page.limit === void 0 ? void 0 : String(page.limit)
2533
+ }, (value) => value !== void 0)
1763
2534
  }), documentVersionsSchema, onDiagnostic);
1764
2535
  },
1765
2536
  async saveDocumentVersion(documentId, input) {
@@ -1881,13 +2652,28 @@ function apiURL(baseURL) {
1881
2652
  url.hash = "";
1882
2653
  return url.href;
1883
2654
  }
2655
+ /**
2656
+ * How long one Cloud API request may take. Some do real work on the server, such as saving a
2657
+ * revision or deleting an account, and bytes go to storage directly, so a JSON call past this has
2658
+ * hung rather than run slowly.
2659
+ */
2660
+ const API_DEADLINE_MS = DEADLINE_MS.slowRequest;
2661
+ /** `fetch`, with each request bounded by its own deadline as well as the caller's signal. */
2662
+ function boundedFetch(fetch = globalThis.fetch) {
2663
+ return (input, init) => fetch(input, {
2664
+ ...init,
2665
+ signal: anySignal([init?.signal, AbortSignal.timeout(API_DEADLINE_MS)])
2666
+ });
2667
+ }
1884
2668
  function createCloudAPIClient(baseURL, options = {}) {
2669
+ if (options.accessToken && !sendsTokenSafely(apiURL(baseURL))) throw new CloudAPIError("OpenPencil Cloud takes an access token only over HTTPS", 0);
1885
2670
  const headers = {
1886
2671
  "Content-Type": "application/json",
1887
2672
  ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1888
2673
  };
2674
+ const fetch = boundedFetch(options.fetch);
1889
2675
  const client = hc(apiURL(baseURL), {
1890
- fetch: options.fetch,
2676
+ fetch,
1891
2677
  init: {
1892
2678
  credentials: "include",
1893
2679
  signal: options.signal,
@@ -1895,7 +2681,7 @@ function createCloudAPIClient(baseURL, options = {}) {
1895
2681
  }
1896
2682
  });
1897
2683
  const publicClient = hc(apiURL(baseURL), {
1898
- fetch: options.fetch,
2684
+ fetch,
1899
2685
  init: {
1900
2686
  credentials: "include",
1901
2687
  signal: options.signal,
@@ -1924,11 +2710,173 @@ function createCloudAPIClient(baseURL, options = {}) {
1924
2710
  ...createImageRequests(client, publicClient, options.onDiagnostic),
1925
2711
  ...createDocumentRequests(client, options.onDiagnostic),
1926
2712
  ...createVersionRequests(client, options.onDiagnostic),
2713
+ ...createCommentRequests(client, options.onDiagnostic),
2714
+ ...createSharedCommentRequests(publicClient, options.onDiagnostic),
1927
2715
  ...createSharingRequests(client, publicClient, options.onDiagnostic),
1928
2716
  ...createCommunityRequests(publicClient, options.onDiagnostic)
1929
2717
  };
1930
2718
  }
1931
2719
  //#endregion
2720
+ //#region src/client/files/save.ts
2721
+ async function prepareCloudDocument(bytes) {
2722
+ const { lean, images } = await splitCloudDocument(bytes);
2723
+ return {
2724
+ lean,
2725
+ checksum: await cloudChecksum(lean),
2726
+ images: await Promise.all(images.map(async (image) => ({
2727
+ ...image,
2728
+ checksum: await cloudChecksum(image.bytes)
2729
+ })))
2730
+ };
2731
+ }
2732
+ /** The server refused the save as declared, as when an image it named was released meanwhile. */
2733
+ function invalidUpload(error) {
2734
+ return error instanceof CloudAPIError && error.code === "invalid_upload";
2735
+ }
2736
+ /**
2737
+ * Saves a document as a new revision on top of `baseRevision`, or as its first: the images the
2738
+ * workspace lacks, then the file, committed together. An image released between asking and
2739
+ * committing is uploaded again by a second try. A save on top of a revision that is no longer the
2740
+ * latest fails with a `revision_conflict` `CloudAPIError`.
2741
+ */
2742
+ async function saveCloudDocument(input) {
2743
+ const { cloud, documentId, document, objectFetch } = input;
2744
+ const save = async () => {
2745
+ await uploadCloudImages({
2746
+ cloud,
2747
+ documentId,
2748
+ images: document.images,
2749
+ objectFetch
2750
+ });
2751
+ const upload = await uploadCloudObject({
2752
+ cloud,
2753
+ documentId,
2754
+ bytes: document.lean,
2755
+ checksum: document.checksum,
2756
+ baseRevision: input.baseRevision,
2757
+ objectFetch,
2758
+ onProgress: input.onProgress
2759
+ });
2760
+ return cloud.commitUpload(upload.uploadId, {
2761
+ checksum: document.checksum,
2762
+ name: input.name,
2763
+ kind: input.kind,
2764
+ multipart: upload.multipart,
2765
+ images: document.images.map((image) => ({
2766
+ name: image.name,
2767
+ checksum: image.checksum
2768
+ }))
2769
+ });
2770
+ };
2771
+ return save().catch((error) => {
2772
+ if (invalidUpload(error)) return save();
2773
+ throw error;
2774
+ });
2775
+ }
2776
+ //#endregion
2777
+ //#region src/client/discovery.ts
2778
+ const DISCOVERY_TIMEOUT_MS = DEADLINE_MS.request;
2779
+ var CloudClientError = class extends Error {
2780
+ cause;
2781
+ reason;
2782
+ constructor(message, cause, reason = "unreachable") {
2783
+ super(message);
2784
+ this.cause = cause;
2785
+ this.reason = reason;
2786
+ this.name = "CloudClientError";
2787
+ }
2788
+ };
2789
+ const discoveryBodySchema = v.pipe(v.string(), v.parseJson(), v.looseObject({}));
2790
+ const protocolSchema = v.looseObject({ protocolVersion: v.string() });
2791
+ function discoveryURL(serverURL) {
2792
+ let url;
2793
+ try {
2794
+ url = new URL(serverURL);
2795
+ } catch (error) {
2796
+ throw new CloudClientError("OpenPencil server URL is invalid", error, "invalid-address");
2797
+ }
2798
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudClientError("OpenPencil server URL must use HTTP or HTTPS", void 0, "invalid-address");
2799
+ url.pathname = CLOUD_DISCOVERY_PATH;
2800
+ url.search = "";
2801
+ url.hash = "";
2802
+ return url;
2803
+ }
2804
+ /** Which side is behind when the server speaks another protocol, or null when it doesn't. */
2805
+ function protocolMismatch(version) {
2806
+ if (version === "1") return null;
2807
+ return Number(version) > 1 ? "editor-outdated" : "server-outdated";
2808
+ }
2809
+ function parseDiscoveryBody(text, editorVersion) {
2810
+ const body = v.safeParse(discoveryBodySchema, text);
2811
+ if (!body.success) throw new CloudClientError("OpenPencil server discovery is not JSON", body.issues, "not-cloud");
2812
+ const discovery = v.safeParse(cloudDiscoverySchema, body.output);
2813
+ if (discovery.success) {
2814
+ const minimum = discovery.output.minimumEditorVersion;
2815
+ if (minimum && editorVersion && !isEditorVersionAtLeast(editorVersion, minimum)) throw new CloudClientError(`OpenPencil server needs editor ${minimum} or later`, void 0, "editor-outdated");
2816
+ return discovery.output;
2817
+ }
2818
+ const protocol = v.safeParse(protocolSchema, body.output);
2819
+ const version = protocol.success ? protocol.output.protocolVersion : null;
2820
+ const mismatch = version === null ? null : protocolMismatch(version);
2821
+ throw new CloudClientError(mismatch ? `OpenPencil server speaks protocol ${version}` : "OpenPencil server discovery is invalid", discovery.issues, mismatch ?? "not-cloud");
2822
+ }
2823
+ async function discoverCloud(serverURL, options = {}) {
2824
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
2825
+ const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
2826
+ const signal = anySignal([options.signal, timeoutSignal]);
2827
+ try {
2828
+ const response = await fetchImplementation(discoveryURL(serverURL), {
2829
+ headers: { Accept: "application/json" },
2830
+ redirect: "follow",
2831
+ signal
2832
+ });
2833
+ if (!response.ok) throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`, void 0, response.status >= 500 ? "unreachable" : "not-cloud");
2834
+ return parseDiscoveryBody(await response.text(), options.editorVersion);
2835
+ } catch (error) {
2836
+ if (error instanceof CloudClientError) throw error;
2837
+ if (signal.aborted) throw new CloudClientError("OpenPencil server discovery was cancelled or timed out", error);
2838
+ throw new CloudClientError("OpenPencil server discovery failed", error);
2839
+ }
2840
+ }
2841
+ //#endregion
2842
+ //#region src/client/tour.ts
2843
+ /**
2844
+ * The tour a Cloud server's community gallery names (`[community] tour`), with its images, as
2845
+ * the named version for `version` when the gallery has one, such as the release an older editor
2846
+ * is, else as it is now. Null when the server names no tour or its gallery no longer holds it.
2847
+ * Requests carry no account, so any page may make them, as the documentation site's landing does.
2848
+ */
2849
+ async function fetchCommunityTour(serverURL, options = {}) {
2850
+ const base = options.fetch ?? globalThis.fetch;
2851
+ const fetch = (input, init) => base(input, {
2852
+ ...init,
2853
+ credentials: "omit"
2854
+ });
2855
+ const discovery = await discoverCloud(serverURL, {
2856
+ fetch,
2857
+ signal: options.signal
2858
+ });
2859
+ const tourId = discovery.community?.tourDocumentId;
2860
+ if (!tourId) return null;
2861
+ const cloud = createCloudAPIClient(discovery.apiURL, {
2862
+ fetch,
2863
+ signal: options.signal
2864
+ });
2865
+ const tour = (await cloud.listCommunityDocuments()).documents.find((document) => document.id === tourId);
2866
+ if (!tour) return null;
2867
+ const release = tour.versions.find((version) => version.name === options.version) ?? null;
2868
+ const download = await cloud.getCommunityDocument(tour.id, release?.id ?? null);
2869
+ const bytes = await downloadCloudDocument(download.document, (input, init) => fetch(input, {
2870
+ ...init,
2871
+ signal: anySignal([init.signal, AbortSignal.timeout(DEADLINE_MS.transfer)])
2872
+ }), { signal: options.signal });
2873
+ return {
2874
+ name: tour.name,
2875
+ version: download.version?.name ?? null,
2876
+ bytes
2877
+ };
2878
+ }
2879
+ //#endregion
1932
2880
  //#region src/client/auth/failure.ts
1933
2881
  /** The failure a Better Auth error stands for; anything unknown can only be retried later. */
1934
2882
  function cloudAuthFailure(error) {
@@ -2108,15 +3056,6 @@ var CloudDeviceAuthorizationError = class extends Error {
2108
3056
  this.code = code;
2109
3057
  }
2110
3058
  };
2111
- function abortableSleep(milliseconds, signal) {
2112
- return new Promise((resolve, reject) => {
2113
- const timeout = setTimeout(resolve, milliseconds);
2114
- signal?.addEventListener("abort", () => {
2115
- clearTimeout(timeout);
2116
- reject(signal.reason instanceof Error ? signal.reason : new DOMException("Authorization cancelled", "AbortError"));
2117
- }, { once: true });
2118
- });
2119
- }
2120
3059
  function authEndpoint(discovery, path) {
2121
3060
  return joinURL(discovery.authURL, path);
2122
3061
  }
@@ -2135,12 +3074,12 @@ async function requestCloudDeviceAuthorization(discovery, connectionId, options
2135
3074
  async function pollCloudDeviceToken(discovery, connectionId, authorization, options = {}) {
2136
3075
  const request = options.fetch ?? globalThis.fetch;
2137
3076
  const now = options.now ?? Date.now;
2138
- const sleep = options.sleep ?? abortableSleep;
3077
+ const wait = options.sleep ?? sleep;
2139
3078
  const expiresAt = now() + authorization.expires_in * 1e3;
2140
3079
  let interval = authorization.interval * 1e3;
2141
3080
  while (now() < expiresAt) {
2142
3081
  options.signal?.throwIfAborted();
2143
- await sleep(interval, options.signal);
3082
+ await wait(interval, options.signal);
2144
3083
  if (now() >= expiresAt) break;
2145
3084
  const response = await request(authEndpoint(discovery, "device/token"), {
2146
3085
  method: "POST",
@@ -2174,74 +3113,16 @@ async function pollCloudDeviceToken(discovery, connectionId, authorization, opti
2174
3113
  throw new CloudDeviceAuthorizationError("expired");
2175
3114
  }
2176
3115
  //#endregion
2177
- //#region src/client/discovery.ts
2178
- const DISCOVERY_TIMEOUT_MS = 1e4;
2179
- var CloudClientError = class extends Error {
2180
- cause;
2181
- reason;
2182
- constructor(message, cause, reason = "unreachable") {
2183
- super(message);
2184
- this.cause = cause;
2185
- this.reason = reason;
2186
- this.name = "CloudClientError";
2187
- }
2188
- };
2189
- const discoveryBodySchema = v.pipe(v.string(), v.parseJson(), v.looseObject({}));
2190
- const protocolSchema = v.looseObject({ protocolVersion: v.string() });
2191
- function discoveryURL(serverURL) {
2192
- let url;
2193
- try {
2194
- url = new URL(serverURL);
2195
- } catch (error) {
2196
- throw new CloudClientError("OpenPencil server URL is invalid", error, "invalid-address");
2197
- }
2198
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudClientError("OpenPencil server URL must use HTTP or HTTPS", void 0, "invalid-address");
2199
- url.pathname = CLOUD_DISCOVERY_PATH;
2200
- url.search = "";
2201
- url.hash = "";
2202
- return url;
2203
- }
2204
- /** Which side is behind when the server speaks another protocol, or null when it doesn't. */
2205
- function protocolMismatch(version) {
2206
- if (version === "1") return null;
2207
- return Number(version) > 1 ? "editor-outdated" : "server-outdated";
2208
- }
2209
- function parseDiscoveryBody(text, editorVersion) {
2210
- const body = v.safeParse(discoveryBodySchema, text);
2211
- if (!body.success) throw new CloudClientError("OpenPencil server discovery is not JSON", body.issues, "not-cloud");
2212
- const discovery = v.safeParse(cloudDiscoverySchema, body.output);
2213
- if (discovery.success) {
2214
- const minimum = discovery.output.minimumEditorVersion;
2215
- if (minimum && editorVersion && !isEditorVersionAtLeast(editorVersion, minimum)) throw new CloudClientError(`OpenPencil server needs editor ${minimum} or later`, void 0, "editor-outdated");
2216
- return discovery.output;
2217
- }
2218
- const protocol = v.safeParse(protocolSchema, body.output);
2219
- const version = protocol.success ? protocol.output.protocolVersion : null;
2220
- const mismatch = version === null ? null : protocolMismatch(version);
2221
- throw new CloudClientError(mismatch ? `OpenPencil server speaks protocol ${version}` : "OpenPencil server discovery is invalid", discovery.issues, mismatch ?? "not-cloud");
2222
- }
2223
- async function discoverCloud(serverURL, options = {}) {
2224
- const fetchImplementation = options.fetch ?? globalThis.fetch;
2225
- const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
2226
- const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
2227
- try {
2228
- const response = await fetchImplementation(discoveryURL(serverURL), {
2229
- headers: { Accept: "application/json" },
2230
- redirect: "follow",
2231
- signal
2232
- });
2233
- if (!response.ok) throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`, void 0, response.status >= 500 ? "unreachable" : "not-cloud");
2234
- return parseDiscoveryBody(await response.text(), options.editorVersion);
2235
- } catch (error) {
2236
- if (error instanceof CloudClientError) throw error;
2237
- if (signal.aborted) throw new CloudClientError("OpenPencil server discovery was cancelled or timed out", error);
2238
- throw new CloudClientError("OpenPencil server discovery failed", error);
2239
- }
2240
- }
2241
- //#endregion
2242
3116
  //#region src/client/portal/account.ts
2243
3117
  function createAccountAPI(call, { account, tokens, api }) {
2244
3118
  return {
3119
+ /** Which comments the account hears about by email. */
3120
+ notificationSettings(signal) {
3121
+ return call((options) => api.account.notifications.$get(void 0, options), notificationSettingsSchema, signal);
3122
+ },
3123
+ setNotificationSettings(settings, signal) {
3124
+ return call((options) => api.account.notifications.$put({ json: settings }, options), notificationSettingsSchema, signal);
3125
+ },
2245
3126
  /** The account's plan, and the storage its workspaces hold together. */
2246
3127
  entitlements(signal) {
2247
3128
  return call((options) => api.account.entitlements.$get(void 0, options), accountEntitlementsResponseSchema, signal);
@@ -2358,13 +3239,17 @@ function createAccountAPI(call, { account, tokens, api }) {
2358
3239
  }
2359
3240
  //#endregion
2360
3241
  //#region src/client/portal/administration.ts
3242
+ /** A count as a query string carries it. */
3243
+ function countParameter(count) {
3244
+ return count === void 0 ? void 0 : String(count);
3245
+ }
2361
3246
  /** The query string for `request`; an empty search asks for everything. */
2362
3247
  function listQuery(request) {
2363
3248
  return { query: {
2364
3249
  search: request.search || void 0,
2365
3250
  filter: request.filter,
2366
- limit: request.limit,
2367
- offset: request.offset
3251
+ limit: countParameter(request.limit),
3252
+ offset: countParameter(request.offset)
2368
3253
  } };
2369
3254
  }
2370
3255
  function createAdministrationAPI(call, { admin, api }) {
@@ -2381,8 +3266,17 @@ function createAdministrationAPI(call, { admin, api }) {
2381
3266
  json: { note }
2382
3267
  }, options), enrollmentReviewResponseSchema, signal);
2383
3268
  },
3269
+ /** Approves every waiting request and sends each the invitation letter (official only). */
3270
+ inviteEnrollments(signal) {
3271
+ return call((options) => admin.enrollments.invite.$post(void 0, options), enrollmentInviteResponseSchema, signal);
3272
+ },
3273
+ /** A page of people; `method` narrows any filter to those who sign in that way. */
2384
3274
  users(request, signal) {
2385
- return call((options) => admin.users.$get(listQuery(request), options), cloudAdminUsersResponseSchema, signal);
3275
+ const { query } = listQuery(request);
3276
+ return call((options) => admin.users.$get({ query: {
3277
+ ...query,
3278
+ method: request.method
3279
+ } }, options), cloudAdminUsersResponseSchema, signal);
2386
3280
  },
2387
3281
  user(id, signal) {
2388
3282
  return call((options) => admin.users[":id"].$get({ param: { id } }, options), cloudAdminUserDetailSchema, signal);
@@ -2393,6 +3287,13 @@ function createAdministrationAPI(call, { admin, api }) {
2393
3287
  reason
2394
3288
  } }, options), adminMutationResponseSchema, signal);
2395
3289
  },
3290
+ /** Removes one of an account's sign-in methods; the server keeps its last. */
3291
+ removeSignInMethod(userId, methodId, signal) {
3292
+ return call((options) => admin.users["remove-sign-in-method"].$post({ json: {
3293
+ userId,
3294
+ methodId
3295
+ } }, options), adminMutationResponseSchema, signal);
3296
+ },
2396
3297
  setAdmin(userId, enabled, signal) {
2397
3298
  return call((options) => admin.users["set-admin"].$post({ json: {
2398
3299
  userId,
@@ -2418,6 +3319,20 @@ function createAdministrationAPI(call, { admin, api }) {
2418
3319
  documents(request, signal) {
2419
3320
  return call((options) => admin.documents.$get(listQuery(request), options), cloudAdminDocumentsResponseSchema, signal);
2420
3321
  },
3322
+ /**
3323
+ * Where a document's thumbnail at `revisionId` is: an image the console shows on the server's
3324
+ * own address, so the administrator's session goes with it.
3325
+ */
3326
+ documentThumbnailURL(documentId, revisionId) {
3327
+ return admin.documents[":documentId"].thumbnails[":revisionId"].$url({ param: {
3328
+ documentId,
3329
+ revisionId
3330
+ } }).toString();
3331
+ },
3332
+ /** Links to a document's file and images as it is now; the server records the download. */
3333
+ downloadDocument(id, signal) {
3334
+ return call((options) => admin.documents[":id"].download.$post({ param: { id } }, options), documentDownloadSchema, signal);
3335
+ },
2421
3336
  /** Takes a document down, or puts it back. */
2422
3337
  documentAction(id, action, reason, signal) {
2423
3338
  return call((options) => {
@@ -2454,10 +3369,10 @@ var CloudPortalAPIError = class extends Error {
2454
3369
  * body is checked against the contract.
2455
3370
  */
2456
3371
  function createCloudCall(options = {}) {
2457
- const timeoutMs = options.timeoutMs ?? 1e4;
3372
+ const timeoutMs = options.timeoutMs ?? DEADLINE_MS.request;
2458
3373
  return async (send, schema, callerSignal) => {
2459
3374
  const timeout = AbortSignal.timeout(timeoutMs);
2460
- const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
3375
+ const signal = anySignal([callerSignal, timeout]);
2461
3376
  let response;
2462
3377
  try {
2463
3378
  response = await send({ init: { signal } });
@@ -2515,6 +3430,6 @@ function createCloudPortalClient(options = {}) {
2515
3430
  };
2516
3431
  }
2517
3432
  //#endregion
2518
- export { CloudAPIError, CloudBillingError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, CloudServiceError, CloudServiceInsecureEndpointError, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudServicesFetch, cloudSignInURL, createCloudAPIClient, createCloudAuthClient, createCloudBillingClient, createCloudPortalClient, createCloudServicesClient, discoverCloud, pollCloudDeviceToken, requestCloudDeviceAuthorization, resendCloudVerification, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail };
3433
+ export { CloudAPIError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, CloudServiceError, CloudServiceInsecureEndpointError, assembleCloudDocument, cloudAuthFailure, cloudChecksum, cloudEditorReturnURL, cloudRedirectPath, cloudServicesFetch, cloudSignInURL, createCloudAPIClient, createCloudAuthClient, createCloudPortalClient, createCloudServicesClient, discoverCloud, downloadCloudDocument, downloadCloudImage, fetchCommunityTour, imageCommitBatches, pollCloudDeviceToken, prepareCloudDocument, putCloudObject, readCloudRevisionRange, requestCloudDeviceAuthorization, resendCloudVerification, saveCloudDocument, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail, splitCloudDocument, uploadCloudImages, uploadCloudObject };
2519
3434
 
2520
3435
  //# sourceMappingURL=client.js.map