@open-pencil/cloud 0.17.0-beta.4 → 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 (280) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/server.mjs +1 -1
  3. package/dist/bin/server.mjs.map +1 -1
  4. package/dist/bin/services.mjs +1 -1
  5. package/dist/bin/services.mjs.map +1 -1
  6. package/dist/client.d.ts +783 -47
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +1651 -382
  9. package/dist/client.js.map +1 -1
  10. package/dist/contract.d.ts +2 -2
  11. package/dist/contract.js +2 -2
  12. package/dist/contract2.js +701 -45
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +2138 -34
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +4343 -306
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +61 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +1338 -44
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +45 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +958 -340
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +93 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +18032 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +12615 -5249
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/server.d.ts +17367 -8567
  34. package/dist/server.d.ts.map +1 -1
  35. package/dist/server.js +13587 -7333
  36. package/dist/server.js.map +1 -1
  37. package/dist/server.mjs +11601 -5401
  38. package/dist/server.mjs.map +1 -1
  39. package/dist/server2.mjs +84 -62
  40. package/dist/server2.mjs.map +1 -1
  41. package/package.json +31 -5
  42. package/src/admin/api/routes.ts +263 -190
  43. package/src/admin/audit/service.ts +11 -3
  44. package/src/admin/bootstrap.ts +86 -0
  45. package/src/admin/documents/service.ts +195 -10
  46. package/src/admin/email/service.ts +2 -1
  47. package/src/admin/enrollment/email.ts +17 -3
  48. package/src/admin/enrollment/service.ts +71 -10
  49. package/src/admin/errors.ts +5 -0
  50. package/src/admin/index.ts +1 -0
  51. package/src/admin/reports/service.ts +15 -3
  52. package/src/admin/schema.ts +6 -5
  53. package/src/admin/users/service.ts +173 -16
  54. package/src/client/api.ts +52 -473
  55. package/src/client/auth/client.ts +22 -3
  56. package/src/client/comments.ts +205 -0
  57. package/src/client/community.ts +40 -0
  58. package/src/client/device-authorization.ts +4 -20
  59. package/src/client/discovery.ts +39 -11
  60. package/src/client/documents.ts +160 -0
  61. package/src/client/files/archive.ts +60 -0
  62. package/src/client/files/checksum.ts +7 -0
  63. package/src/client/files/download.ts +122 -0
  64. package/src/client/files/images.ts +89 -0
  65. package/src/client/files/index.ts +15 -0
  66. package/src/client/files/objects.ts +173 -0
  67. package/src/client/files/save.ts +79 -0
  68. package/src/client/index.ts +4 -0
  69. package/src/client/portal/account.ts +73 -3
  70. package/src/client/portal/administration.ts +52 -5
  71. package/src/client/portal/request.ts +6 -2
  72. package/src/client/response.ts +21 -0
  73. package/src/client/schema.ts +8 -0
  74. package/src/client/services.ts +23 -18
  75. package/src/client/sharing.ts +262 -0
  76. package/src/client/tour.ts +44 -0
  77. package/src/client/versions.ts +110 -0
  78. package/src/contract/account.ts +111 -11
  79. package/src/contract/admin/index.ts +48 -3
  80. package/src/contract/billing.ts +235 -0
  81. package/src/contract/collaboration.ts +5 -0
  82. package/src/contract/comments.ts +223 -0
  83. package/src/contract/community.ts +60 -0
  84. package/src/contract/discovery.ts +94 -5
  85. package/src/contract/entitlements.ts +10 -0
  86. package/src/contract/index.ts +64 -5
  87. package/src/contract/links.ts +62 -4
  88. package/src/contract/locale.ts +27 -0
  89. package/src/contract/portal.ts +12 -1
  90. package/src/contract/relay.ts +3 -1
  91. package/src/contract/routes.ts +10 -0
  92. package/src/contract/services.ts +62 -20
  93. package/src/contract/workspaces.ts +5 -0
  94. package/src/email/i18n.ts +174 -0
  95. package/src/email/index.ts +13 -2
  96. package/src/email/locales/ar.json +169 -0
  97. package/src/email/locales/de.json +169 -0
  98. package/src/email/locales/es.json +169 -0
  99. package/src/email/locales/fr.json +169 -0
  100. package/src/email/locales/it.json +169 -0
  101. package/src/email/locales/ja.json +169 -0
  102. package/src/email/locales/pl.json +169 -0
  103. package/src/email/locales/pt-br.json +169 -0
  104. package/src/email/locales/ru.json +169 -0
  105. package/src/email/locales/zh-cn.json +169 -0
  106. package/src/email/messages.ts +235 -0
  107. package/src/email/render.ts +160 -276
  108. package/src/email/samples.ts +142 -0
  109. package/src/email/schema.ts +98 -8
  110. package/src/email/templates/BrandEmail.vue +56 -0
  111. package/src/email/templates/CommentNotification.vue +39 -0
  112. package/src/email/templates/DocumentBlocked.vue +45 -0
  113. package/src/email/templates/DocumentInvitation.vue +24 -0
  114. package/src/email/templates/DocumentReport.vue +32 -0
  115. package/src/email/templates/DocumentReportDecided.vue +36 -0
  116. package/src/email/templates/DocumentReportReceived.vue +18 -0
  117. package/src/email/templates/DocumentRestored.vue +24 -0
  118. package/src/email/templates/EmailChangeRequested.vue +24 -0
  119. package/src/email/templates/EmailRoot.vue +19 -0
  120. package/src/email/templates/EmailText.vue +9 -0
  121. package/src/email/templates/EmailVerification.vue +38 -0
  122. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  123. package/src/email/templates/EnrollmentNotification.vue +24 -0
  124. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  125. package/src/email/templates/NewSignIn.vue +37 -0
  126. package/src/email/templates/PasswordChanged.vue +22 -0
  127. package/src/email/templates/PasswordReset.vue +23 -0
  128. package/src/email/templates/StorageLimitReached.vue +28 -0
  129. package/src/email/templates/TwoStepChanged.vue +47 -0
  130. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  131. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  132. package/src/email/templates/brand.ts +15 -61
  133. package/src/email/templates/localization.ts +17 -0
  134. package/src/errors/index.ts +6 -0
  135. package/src/{server/errors → errors}/posthog.ts +28 -4
  136. package/src/global.d.ts +7 -0
  137. package/src/runtime/cloudflare/email.ts +2 -0
  138. package/src/runtime/cloudflare/relay/index.ts +28 -7
  139. package/src/runtime/cloudflare/tsconfig.json +2 -1
  140. package/src/runtime/cloudflare/worker.ts +14 -1
  141. package/src/runtime/cloudflare/xml.ts +12 -0
  142. package/src/runtime/node/admin.ts +51 -47
  143. package/src/runtime/node/cleanup.ts +5 -1
  144. package/src/runtime/node/email/runtime.ts +1 -0
  145. package/src/runtime/node/email/transport.ts +14 -10
  146. package/src/runtime/node/main.ts +1 -1
  147. package/src/runtime/node/server.ts +20 -4
  148. package/src/runtime/node/services/main.ts +1 -1
  149. package/src/runtime/posthog/errors.ts +5 -2
  150. package/src/runtime/s3/objects.ts +17 -0
  151. package/src/runtime/site/community.ts +101 -0
  152. package/src/runtime/site/server.ts +17 -1
  153. package/src/server/account/actions.ts +3 -1
  154. package/src/server/account/deletion.ts +40 -4
  155. package/src/server/account/routes.ts +305 -253
  156. package/src/server/account/tokens.ts +57 -0
  157. package/src/server/api/router.ts +44 -6
  158. package/src/server/app/checks.ts +89 -0
  159. package/src/server/app/cors.ts +44 -0
  160. package/src/server/app/editors.ts +20 -0
  161. package/src/server/app/index.ts +128 -0
  162. package/src/server/app/indexing.ts +40 -0
  163. package/src/server/app/limiters.ts +53 -0
  164. package/src/server/app/routes.ts +123 -0
  165. package/src/server/app/services.ts +219 -0
  166. package/src/server/auth/access-control.ts +13 -8
  167. package/src/server/auth/access-tokens.ts +62 -0
  168. package/src/server/auth/account.ts +13 -12
  169. package/src/server/auth/activity.ts +7 -2
  170. package/src/server/auth/adapter.ts +36 -3
  171. package/src/server/auth/email.ts +33 -18
  172. package/src/server/auth/endpoints.ts +4 -0
  173. package/src/server/auth/enrollment.ts +116 -0
  174. package/src/server/auth/factory.ts +165 -189
  175. package/src/server/auth/index.ts +1 -1
  176. package/src/server/auth/logger.ts +23 -0
  177. package/src/server/auth/methods.ts +162 -0
  178. package/src/server/auth/mfa-assurance.ts +190 -2
  179. package/src/server/auth/passwords.ts +43 -0
  180. package/src/server/auth/rate-limit.ts +31 -0
  181. package/src/server/auth/runtime.ts +19 -5
  182. package/src/server/auth/session.ts +2 -0
  183. package/src/server/auth/social-providers.ts +70 -24
  184. package/src/server/billing/index.ts +8 -0
  185. package/src/server/billing/notify.ts +55 -0
  186. package/src/server/billing/routes.ts +27 -0
  187. package/src/server/billing/seats.ts +17 -0
  188. package/src/server/billing/tokens.ts +37 -0
  189. package/src/server/cleanup/configured.ts +16 -3
  190. package/src/server/cleanup/documents.ts +5 -2
  191. package/src/server/cleanup/revisions.ts +6 -3
  192. package/src/server/cleanup/uploads.ts +2 -1
  193. package/src/server/cleanup/worker.ts +10 -1
  194. package/src/server/collaboration/relay/connection.ts +7 -2
  195. package/src/server/collaboration/relay/hub.ts +80 -166
  196. package/src/server/collaboration/relay/room.ts +154 -0
  197. package/src/server/collaboration/routes.ts +8 -5
  198. package/src/server/collaboration/service.ts +21 -2
  199. package/src/server/comments/index.ts +9 -0
  200. package/src/server/comments/notify.ts +277 -0
  201. package/src/server/comments/routes.ts +352 -0
  202. package/src/server/comments/rows.ts +249 -0
  203. package/src/server/comments/service.ts +570 -0
  204. package/src/server/community/index.ts +2 -0
  205. package/src/server/community/routes.ts +93 -0
  206. package/src/server/community/service.ts +134 -0
  207. package/src/server/config/deployment.ts +35 -10
  208. package/src/server/config/index.ts +2 -2
  209. package/src/server/config/public.ts +25 -6
  210. package/src/server/config/schema.ts +53 -293
  211. package/src/server/config/toml/schema.ts +330 -0
  212. package/src/server/db/index.ts +3 -1
  213. package/src/server/db/migrate.ts +33 -1
  214. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  215. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  216. package/src/server/db/migrations/011_account_ids.ts +30 -0
  217. package/src/server/db/migrations/012_email_locales.ts +34 -0
  218. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  219. package/src/server/db/migrations/014_report_replies.ts +28 -0
  220. package/src/server/db/migrations/015_comments.ts +57 -0
  221. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  222. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  223. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  224. package/src/server/db/migrations/schema.ts +26 -1
  225. package/src/server/db/tables.ts +122 -3
  226. package/src/server/db/users.ts +22 -0
  227. package/src/server/documents/access.ts +17 -0
  228. package/src/server/documents/images.ts +6 -1
  229. package/src/server/documents/index.ts +1 -1
  230. package/src/server/documents/limits.ts +7 -1
  231. package/src/server/documents/routes.ts +12 -12
  232. package/src/server/documents/service.ts +31 -407
  233. package/src/server/documents/summary.ts +15 -0
  234. package/src/server/documents/uploads.ts +450 -0
  235. package/src/server/documents/versions/routes.ts +7 -8
  236. package/src/server/documents/versions/service.ts +86 -26
  237. package/src/server/email/invitations.ts +1 -0
  238. package/src/server/email/service.ts +39 -6
  239. package/src/server/email/types.ts +13 -0
  240. package/src/server/errors/index.ts +49 -12
  241. package/src/server/index.ts +27 -6
  242. package/src/server/internal/routes.ts +8 -2
  243. package/src/server/internal/service.ts +10 -0
  244. package/src/server/invitations/budget.ts +3 -1
  245. package/src/server/invitations/index.ts +1 -0
  246. package/src/server/invitations/links.ts +6 -0
  247. package/src/server/invitations/types.ts +5 -1
  248. package/src/server/objects/types.ts +5 -0
  249. package/src/server/pictures/service.ts +3 -1
  250. package/src/server/policy/configured.ts +9 -3
  251. package/src/server/policy/database.ts +13 -2
  252. package/src/server/policy/policy.ts +39 -12
  253. package/src/server/policy/service.ts +71 -52
  254. package/src/server/policy/storage.ts +33 -0
  255. package/src/server/policy/workspace.ts +5 -2
  256. package/src/server/quota/index.ts +6 -0
  257. package/src/server/quota/notices.ts +121 -0
  258. package/src/server/quota/storage.ts +5 -0
  259. package/src/server/rate-limit/middleware.ts +4 -0
  260. package/src/server/reports/index.ts +1 -0
  261. package/src/server/reports/replies.ts +55 -0
  262. package/src/server/reports/routes.ts +5 -3
  263. package/src/server/reports/service.ts +27 -3
  264. package/src/server/services/routes.ts +2 -2
  265. package/src/server/sharing/capabilities/service.ts +3 -4
  266. package/src/server/sharing/document-routes.ts +3 -3
  267. package/src/server/sharing/invitations/service.ts +17 -8
  268. package/src/server/sharing/routes.ts +15 -15
  269. package/src/server/validation.ts +35 -24
  270. package/src/server/workspaces/members.ts +57 -31
  271. package/src/server/workspaces/repository.ts +23 -12
  272. package/src/server/workspaces/routes.ts +8 -8
  273. package/src/services/app.ts +31 -22
  274. package/src/services/config.ts +48 -8
  275. package/src/services/metering.ts +15 -27
  276. package/src/services/usage.ts +6 -14
  277. package/src/email/templates/document-invitation.ts +0 -35
  278. package/src/email/templates/enrollment.ts +0 -27
  279. package/src/email/templates/layout.ts +0 -18
  280. package/src/server/app.ts +0 -453
package/dist/client.js CHANGED
@@ -1,22 +1,71 @@
1
- import { isValid } from "js-base64";
2
1
  import * as v from "valibot";
3
- import { zipObject } from "es-toolkit";
4
- import { joinURL, withQuery, withoutFragment } from "ufo";
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";
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";
9
14
  import { deviceAuthorizationClient, twoFactorClient } from "better-auth/client/plugins";
15
+ //#region src/client/response.ts
16
+ const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
17
+ var CloudAPIError = class extends Error {
18
+ status;
19
+ code;
20
+ name = "CloudAPIError";
21
+ constructor(message, status, code) {
22
+ super(message);
23
+ this.status = status;
24
+ this.code = code;
25
+ }
26
+ };
27
+ async function responseBody(response, onDiagnostic) {
28
+ if (response.ok) return response.status === 204 ? null : response.json();
29
+ let code;
30
+ try {
31
+ const body = v.safeParse(cloudErrorResponseSchema, await response.json());
32
+ if (body.success) code = body.output.error.code;
33
+ } catch (error) {
34
+ onDiagnostic?.("Cloud API error response was not JSON", error);
35
+ }
36
+ throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
37
+ }
38
+ async function parseResponse(request, schema, onDiagnostic) {
39
+ return v.parse(schema, await responseBody(await request, onDiagnostic));
40
+ }
41
+ /**
42
+ * The JSON a service deployed apart from Cloud answered, parsed with `schema` rather than trusted;
43
+ * a refusal throws what `refused` makes of its status and body.
44
+ */
45
+ async function serviceJSON(response, schema, refused) {
46
+ if (!response.ok) {
47
+ const body = await response.text().catch((failure) => {
48
+ const error = refused(response.status, "");
49
+ error.cause = failure;
50
+ throw error;
51
+ });
52
+ throw refused(response.status, body);
53
+ }
54
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), await response.text());
55
+ }
56
+ //#endregion
10
57
  //#region src/contract/account.ts
11
58
  /**
12
59
  * Where an account stands: it may use the server, waits for an administrator, was refused or had
13
- * 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.
14
62
  */
15
63
  const cloudAccountStateSchema = v.picklist([
16
64
  "active",
17
65
  "pending",
18
66
  "rejected",
19
67
  "revoked",
68
+ "two-step",
20
69
  "terms"
21
70
  ]);
22
71
  const cloudIdentitySchema = v.object({
@@ -32,27 +81,45 @@ const cloudAccountStatusResponseSchema = v.object({
32
81
  state: cloudAccountStateSchema
33
82
  });
34
83
  v.object({ version: v.pipe(v.string(), v.minLength(1)) });
35
- const cloudAuthenticationProviderSchema = v.picklist([
36
- "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 = [
37
89
  "google",
38
- "apple"
39
- ]);
90
+ "apple",
91
+ "github"
92
+ ];
93
+ const cloudSocialProviderSchema = v.picklist(CLOUD_SOCIAL_PROVIDERS);
94
+ const cloudAuthenticationProviderSchema = v.picklist(["credential", ...CLOUD_SOCIAL_PROVIDERS]);
40
95
  const cloudAuthenticationMethodSchema = v.object({
41
96
  id: v.string(),
42
97
  provider: cloudAuthenticationProviderSchema,
43
98
  createdAt: v.string(),
44
99
  canUnlink: v.boolean()
45
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
+ */
46
113
  const cloudAuthenticationMethodsResponseSchema = v.object({
47
- methods: v.array(cloudAuthenticationMethodSchema),
48
- 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))
49
116
  });
50
117
  v.object({
51
118
  currentPassword: v.string(),
52
119
  newPassword: v.string()
53
120
  });
54
121
  v.object({
55
- provider: v.picklist(["google", "apple"]),
122
+ provider: cloudSocialProviderSchema,
56
123
  callbackURL: v.pipe(v.string(), v.url())
57
124
  });
58
125
  const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) });
@@ -64,6 +131,7 @@ const accountSecurityErrorCodeSchema = v.picklist([
64
131
  "last_authentication_method",
65
132
  "session_not_fresh",
66
133
  "authentication_method_failed",
134
+ "code_invalid",
67
135
  "email_unchanged",
68
136
  "email_change_unavailable",
69
137
  "current_session",
@@ -98,6 +166,32 @@ const cloudPasskeySchema = v.object({
98
166
  });
99
167
  const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) });
100
168
  v.object({ id: v.string() });
169
+ /**
170
+ * Personal access tokens: an account's own credentials for scripts and CI, sent as
171
+ * `Authorization: Bearer <token>`. A token acts as its account on the document API only; it never
172
+ * changes how the account is reached, makes other tokens, or reaches administration.
173
+ */
174
+ const CLOUD_ACCESS_TOKEN_PREFIX = "opc_";
175
+ const cloudAccessTokenSchema = v.object({
176
+ id: v.string(),
177
+ name: v.string(),
178
+ /** The token's first characters, prefix included, to tell tokens apart; never the whole token. */
179
+ start: v.nullable(v.string()),
180
+ createdAt: v.string(),
181
+ expiresAt: v.nullable(v.string()),
182
+ lastUsedAt: v.nullable(v.string())
183
+ });
184
+ const cloudAccessTokensResponseSchema = v.object({ tokens: v.array(cloudAccessTokenSchema) });
185
+ v.object({
186
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),
187
+ expiresInDays: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(365))
188
+ });
189
+ /** A new token, the only time the whole of it is shown. */
190
+ const cloudAccessTokenCreatedResponseSchema = v.object({
191
+ token: v.pipe(v.string(), v.startsWith(CLOUD_ACCESS_TOKEN_PREFIX)),
192
+ accessToken: cloudAccessTokenSchema
193
+ });
194
+ v.object({ id: v.pipe(v.string(), v.minLength(1)) });
101
195
  const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
102
196
  /** Who an account belongs to, as the portal shows it. */
103
197
  const cloudPersonSchema = v.object({
@@ -126,21 +220,24 @@ v.object({
126
220
  callbackURL: v.pipe(v.string(), v.url())
127
221
  });
128
222
  /** How a sign-in was made: the method it used, or the desktop app's approved code. */
129
- const cloudSignInMethodSchema = v.picklist([
223
+ const SIGN_IN_METHODS = [
130
224
  "password",
131
- "google",
132
- "apple",
225
+ ...CLOUD_SOCIAL_PROVIDERS,
133
226
  "passkey",
134
227
  "two-step",
135
228
  "email-link",
136
229
  "desktop",
137
230
  "other"
138
- ]);
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"));
139
236
  const cloudAccountSessionSchema = v.object({
140
237
  id: v.string(),
141
238
  /** The session this request was made with. */
142
239
  current: v.boolean(),
143
- method: v.nullable(cloudSignInMethodSchema),
240
+ method: v.nullable(signInMethodResponseSchema),
144
241
  ipAddress: v.nullable(v.string()),
145
242
  /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
146
243
  browser: v.nullable(v.string()),
@@ -153,7 +250,7 @@ const cloudAccountSessionsResponseSchema = v.object({ sessions: v.array(cloudAcc
153
250
  v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) });
154
251
  const cloudSignInSchema = v.object({
155
252
  id: v.string(),
156
- method: cloudSignInMethodSchema,
253
+ method: signInMethodResponseSchema,
157
254
  ipAddress: v.nullable(v.string()),
158
255
  /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
159
256
  browser: v.nullable(v.string()),
@@ -202,31 +299,29 @@ const CLOUD_SERVICES_API_PATHS = {
202
299
  usage: "/v1/usage",
203
300
  search: "/v1/search"
204
301
  };
205
- const urlSchema = v.pipe(v.string(), v.url());
206
- const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
302
+ const urlSchema$1 = v.pipe(v.string(), v.url());
303
+ const creditsSchema$1 = v.pipe(v.number(), v.integer(), v.minValue(0));
207
304
  const cloudServicesDiscoverySchema = v.object({
208
- endpoint: urlSchema,
305
+ endpoint: urlSchema$1,
209
306
  contractVersion: v.literal("1")
210
307
  });
211
- const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
212
308
  v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
213
309
  const servicesTokenSchema = v.object({
214
310
  token: v.pipe(v.string(), v.minLength(1)),
215
311
  expiresAt: v.pipe(v.string(), v.isoTimestamp())
216
312
  });
217
313
  v.object({
218
- iss: urlSchema,
314
+ iss: urlSchema$1,
219
315
  aud: v.literal(CLOUD_SERVICES_TOKEN_AUDIENCE),
220
316
  sub: v.pipe(v.string(), v.minLength(1)),
221
317
  workspaceId: v.pipe(v.string(), v.uuid()),
222
318
  /**
223
319
  * The account whose credits the request spends: the workspace's owner, whose allowance every
224
- * workspace they own shares. Absent from tokens a Cloud from before account plans issued, which
225
- * a relay takes as the workspace's own allowance, as such a Cloud meant.
320
+ * workspace they own shares.
226
321
  */
227
- accountId: v.optional(v.pipe(v.string(), v.minLength(1))),
322
+ accountId: v.pipe(v.string(), v.minLength(1)),
228
323
  /** Credits the owner's plan grants each month; `null` when Cloud sets no allowance. */
229
- monthlyCreditAllowance: v.nullable(creditsSchema),
324
+ monthlyCreditAllowance: v.nullable(creditsSchema$1),
230
325
  iat: v.pipe(v.number(), v.integer()),
231
326
  exp: v.pipe(v.number(), v.integer())
232
327
  });
@@ -234,8 +329,8 @@ const chatModelSchema = v.object({
234
329
  id: v.pipe(v.string(), v.minLength(1)),
235
330
  label: v.pipe(v.string(), v.minLength(1)),
236
331
  /** Credits per million input and output tokens. */
237
- creditsPerMillionInputTokens: creditsSchema,
238
- creditsPerMillionOutputTokens: creditsSchema,
332
+ creditsPerMillionInputTokens: creditsSchema$1,
333
+ creditsPerMillionOutputTokens: creditsSchema$1,
239
334
  contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
240
335
  capabilities: v.object({
241
336
  reasoning: v.boolean(),
@@ -244,19 +339,46 @@ const chatModelSchema = v.object({
244
339
  })
245
340
  });
246
341
  /** What one web search costs; a service without search leaves it out of its catalog. */
247
- const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema });
248
- const serviceCatalogSchema = v.object({
342
+ const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema$1 });
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({
249
357
  models: v.array(chatModelSchema),
250
- 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),
251
365
  search: v.optional(searchPricingSchema)
252
- });
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"));
253
375
  const creditBucketSchema = v.object({
254
376
  kind: v.picklist([
255
377
  "allowance",
256
378
  "purchased",
257
379
  "grant"
258
380
  ]),
259
- remaining: creditsSchema,
381
+ remaining: creditsSchema$1,
260
382
  expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
261
383
  });
262
384
  /**
@@ -265,7 +387,7 @@ const creditBucketSchema = v.object({
265
387
  */
266
388
  const creditWalletSchema = v.object({
267
389
  /** Credits left to spend; `null` when the service sets no limit. */
268
- balance: v.nullable(creditsSchema),
390
+ balance: v.nullable(creditsSchema$1),
269
391
  /** Spent first to last. */
270
392
  buckets: v.array(creditBucketSchema)
271
393
  });
@@ -279,7 +401,7 @@ const usageEntrySchema = v.object({
279
401
  ]),
280
402
  modelID: v.nullable(v.string()),
281
403
  userId: v.pipe(v.string(), v.minLength(1)),
282
- credits: creditsSchema
404
+ credits: creditsSchema$1
283
405
  });
284
406
  v.object({
285
407
  query: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(1e3)),
@@ -287,7 +409,7 @@ v.object({
287
409
  });
288
410
  /** One page a search found, with the part of its text that answers the query. */
289
411
  const searchResultSchema = v.object({
290
- url: v.pipe(urlSchema, v.regex(/^https?:\/\//i, "A search result links to an HTTP(S) page")),
412
+ url: v.pipe(urlSchema$1, v.regex(/^https?:\/\//i, "A search result links to an HTTP(S) page")),
291
413
  title: v.string(),
292
414
  publishedAt: v.nullable(v.pipe(v.string(), v.isoTimestamp())),
293
415
  author: v.nullable(v.string()),
@@ -314,13 +436,138 @@ const serviceErrorSchema = v.object({ error: v.object({
314
436
  /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
315
437
  resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
316
438
  }) });
439
+ /**
440
+ * Whether a bearer token may travel to `url`: over HTTPS, or in the clear only to a loopback
441
+ * address, for development. Only literal addresses count, since a name such as `localhost` is
442
+ * whatever the resolver answers. Services and billing tokens act as the account until they expire.
443
+ */
444
+ function sendsTokenSafely(url) {
445
+ const { protocol, hostname } = new URL(url);
446
+ if (protocol === "https:") return true;
447
+ if (protocol !== "http:") return false;
448
+ return hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
449
+ }
450
+ /**
451
+ * The `aud` of the tokens Cloud signs for its billing service, with the services' signing key,
452
+ * whose public keys it publishes at `CLOUD_SERVICES_JWKS_PATH`.
453
+ */
454
+ const CLOUD_BILLING_TOKEN_AUDIENCE = "openpencil-billing";
455
+ const urlSchema = v.pipe(v.string(), v.url());
456
+ const idSchema = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/));
457
+ const centsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
458
+ const bytesSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
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
+ });
472
+ const cloudBillingDiscoverySchema = v.object({
473
+ endpoint: urlSchema,
474
+ contractVersion: v.literal("1"),
475
+ freePlan: v.optional(billingFreePlanSchema)
476
+ });
477
+ const billingTokenSchema = v.object({
478
+ token: v.pipe(v.string(), v.minLength(1)),
479
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
480
+ });
481
+ v.object({
482
+ iss: urlSchema,
483
+ aud: v.literal(CLOUD_BILLING_TOKEN_AUDIENCE),
484
+ /** The account: the Cloud user whose plan and credits these are. */
485
+ sub: v.pipe(v.string(), v.minLength(1)),
486
+ /** Where the payment provider sends receipts and invoices. */
487
+ email: v.pipe(v.string(), v.email()),
488
+ iat: v.pipe(v.number(), v.integer()),
489
+ exp: v.pipe(v.number(), v.integer())
490
+ });
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
+ */
512
+ const billingPlanSchema = v.object({
513
+ id: idSchema,
514
+ name: v.pipe(v.string(), v.minLength(1)),
515
+ monthlyPriceCents: centsSchema,
516
+ storageBytes: bytesSchema,
517
+ monthlyCredits: creditsSchema,
518
+ seats: v.optional(billingSeatPricingSchema)
519
+ });
520
+ /** Credits an account on a plan buys once, in US dollars before tax. */
521
+ const creditPackSchema = v.object({
522
+ id: idSchema,
523
+ credits: creditsSchema,
524
+ priceCents: centsSchema,
525
+ /** How long the credits last from purchase. */
526
+ validDays: v.pipe(v.number(), v.integer(), v.minValue(1))
527
+ });
528
+ v.object({
529
+ plans: v.array(billingPlanSchema),
530
+ creditPacks: v.array(creditPackSchema)
531
+ });
532
+ v.object({ subscription: v.nullable(v.object({
533
+ planId: idSchema,
534
+ status: v.picklist(["active", "past_due"]),
535
+ /** When the current period ends: the next charge, or the end of a cancelled plan. */
536
+ currentPeriodEnd: v.pipe(v.string(), v.isoTimestamp()),
537
+ /** Whether the plan ends at `currentPeriodEnd` instead of renewing. */
538
+ cancelsAtPeriodEnd: v.boolean()
539
+ })) });
540
+ v.union([v.object({ planId: idSchema }), v.object({ creditPackId: idSchema })]);
541
+ v.object({ url: v.pipe(urlSchema, v.regex(/^https:\/\//i, "Billing sends people to an HTTPS page")) });
542
+ const billingErrorCodeSchema = v.picklist([
543
+ "invalid_request",
544
+ "unauthorized",
545
+ "not_allowed",
546
+ "provider_unavailable"
547
+ ]);
548
+ v.object({ error: v.object({
549
+ code: billingErrorCodeSchema,
550
+ message: v.optional(v.string())
551
+ }) });
317
552
  //#endregion
318
553
  //#region src/contract/documents.ts
319
554
  const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
320
555
  const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
321
556
  /** The most images one revision, or one request for image uploads, may name. */
322
557
  const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
323
- 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));
324
571
  const objectDownloadSchema = v.object({
325
572
  url: v.pipe(v.string(), v.url()),
326
573
  method: v.literal("GET"),
@@ -505,6 +752,11 @@ const collaborationTicketSchema = v.object({
505
752
  roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
506
753
  principal: collaborationPrincipalSchema,
507
754
  permission: documentPermissionSchema,
755
+ /**
756
+ * Why a peer whose access would let them edit may only view: `storage-limit` when the document's
757
+ * owner holds their whole storage allowance, until they free space or their plan grows.
758
+ */
759
+ readOnly: v.optional(v.picklist(["storage-limit"])),
508
760
  roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
509
761
  expiresAt: v.string(),
510
762
  serverEnforcedWrites: v.boolean(),
@@ -526,6 +778,11 @@ const workspaceSummarySchema = v.object({
526
778
  name: v.string(),
527
779
  slug: v.string(),
528
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()),
529
786
  createdAt: v.string(),
530
787
  updatedAt: v.string()
531
788
  });
@@ -720,8 +977,11 @@ const adminErrorCodeSchema = v.picklist([
720
977
  "invalid_enrollment_transition",
721
978
  "last_admin_required",
722
979
  "self_admin_action_forbidden",
980
+ "last_authentication_method",
981
+ "account_approved",
723
982
  "email_regeneration_unavailable",
724
983
  "mfa_required",
984
+ "two_step_unconfirmed",
725
985
  "document_not_restorable",
726
986
  "workspace_gone"
727
987
  ]);
@@ -752,6 +1012,8 @@ const enrollmentsResponseSchema = v.object({
752
1012
  ...listTotals(enrollmentStatusSchema.options)
753
1013
  });
754
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)) });
755
1017
  const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema });
756
1018
  const cloudAdminUserSchema = v.object({
757
1019
  ...cloudPersonSchema.entries,
@@ -763,7 +1025,14 @@ const cloudAdminUserSchema = v.object({
763
1025
  twoStep: v.boolean(),
764
1026
  /** When one of the account's sessions was last used, or null when none is left. */
765
1027
  lastActiveAt: nullableTimestampSchema,
766
- 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))
767
1036
  });
768
1037
  /** Which accounts a list of people shows. */
769
1038
  const cloudAdminUserFilterSchema = v.picklist([
@@ -772,6 +1041,7 @@ const cloudAdminUserFilterSchema = v.picklist([
772
1041
  "suspended",
773
1042
  "without-two-step"
774
1043
  ]);
1044
+ v.picklist(["password", ...CLOUD_SOCIAL_PROVIDERS]);
775
1045
  const cloudAdminUsersResponseSchema = v.object({
776
1046
  users: v.array(cloudAdminUserSchema),
777
1047
  ...listTotals(cloudAdminUserFilterSchema.options)
@@ -781,9 +1051,12 @@ const cloudAdminUserDetailSchema = v.object({
781
1051
  ...cloudAdminUserSchema.entries,
782
1052
  emailVerified: v.boolean()
783
1053
  }),
1054
+ /** `canRemove`: the account keeps a way in that still works without it. */
784
1055
  methods: v.array(v.object({
1056
+ id: v.string(),
785
1057
  provider: v.string(),
786
- createdAt: timestampSchema
1058
+ createdAt: timestampSchema,
1059
+ canRemove: v.boolean()
787
1060
  })),
788
1061
  authenticator: v.boolean(),
789
1062
  passkeyCount: countSchema,
@@ -856,6 +1129,8 @@ const adminAuditResponseSchema = v.object({
856
1129
  const cloudAdminDocumentSchema = v.object({
857
1130
  id: v.string(),
858
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"),
859
1134
  workspace: v.object({
860
1135
  id: v.string(),
861
1136
  name: v.string()
@@ -877,7 +1152,25 @@ const cloudAdminDocumentSchema = v.object({
877
1152
  * can still restore it. Servers from before Trash send neither.
878
1153
  */
879
1154
  purgedAt: v.optional(nullableTimestampSchema, null),
880
- 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
+ })
881
1174
  });
882
1175
  /** Which documents a list shows: live ones, or those deleted forever an administrator can restore. */
883
1176
  const cloudAdminDocumentFilterSchema = v.picklist([
@@ -970,8 +1263,19 @@ const workspaceEntitlementsSchema = v.object({
970
1263
  reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
971
1264
  })
972
1265
  });
1266
+ /**
1267
+ * An account's own plan and the storage its workspaces hold together. A workspace reports the
1268
+ * same for its owner, so the two read alike.
1269
+ */
1270
+ const accountEntitlementsSchema = workspaceEntitlementsSchema;
1271
+ const accountEntitlementsResponseSchema = v.object({ entitlements: accountEntitlementsSchema });
973
1272
  const CLOUD_DISCOVERY_PATH = "/.well-known/openpencil";
974
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)));
975
1279
  const cloudAuthenticationSchema = v.object({
976
1280
  emailPassword: v.optional(v.object({
977
1281
  signIn: v.boolean(),
@@ -982,7 +1286,7 @@ const cloudAuthenticationSchema = v.object({
982
1286
  siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
983
1287
  }))
984
1288
  })),
985
- socialProviders: v.array(v.picklist(["apple", "google"])),
1289
+ socialProviders: socialProvidersSchema,
986
1290
  enterpriseSSO: v.boolean(),
987
1291
  enrollmentMode: v.optional(v.picklist([
988
1292
  "open",
@@ -1001,8 +1305,35 @@ const cloudCapabilitiesSchema = v.object({
1001
1305
  workspaces: v.boolean(),
1002
1306
  collaboration: v.boolean()
1003
1307
  });
1004
- /** A released editor version, `major.minor.patch`. */
1005
- const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
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;
1325
+ }
1326
+ /**
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.
1332
+ */
1333
+ function isEditorVersionAtLeast(version, minimum) {
1334
+ if (!isSemVer(version) || !isSemVer(minimum)) return false;
1335
+ return compareVersions(version, minimum) >= 0;
1336
+ }
1006
1337
  /**
1007
1338
  * Whether editors offer this server to everyone, and from which editor version on. Only the
1008
1339
  * official server's listing is read: it turns the Cloud entry points on without an editor release,
@@ -1023,6 +1354,26 @@ const cloudLegalDiscoverySchema = v.object({
1023
1354
  abuseEmail: v.optional(v.pipe(v.string(), v.email())),
1024
1355
  minimumAge: v.optional(v.pipe(v.number(), v.integer()))
1025
1356
  });
1357
+ /** A web address a page may link or load: `http` or `https` only, never a script or data URL. */
1358
+ const webURLSchema = v.pipe(v.string(), v.url(), v.check((value) => ["http:", "https:"].includes(new URL(value).protocol)));
1359
+ /**
1360
+ * How a self-hosted server names itself on its public pages: the operator's name and logo in the
1361
+ * bar, and where its people get help. The official server is OpenPencil's own and names none.
1362
+ */
1363
+ const cloudBrandingSchema = v.object({
1364
+ name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
1365
+ logoURL: v.optional(webURLSchema),
1366
+ helpURL: v.optional(webURLSchema)
1367
+ });
1368
+ /**
1369
+ * The server's community gallery: the workspace whose documents anyone may open read-only.
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.
1372
+ */
1373
+ const cloudCommunityDiscoverySchema = v.object({
1374
+ workspaceId: v.pipe(v.string(), v.uuid()),
1375
+ tourDocumentId: v.optional(v.pipe(v.string(), v.uuid()))
1376
+ });
1026
1377
  const cloudDiscoverySchema = v.object({
1027
1378
  protocolVersion: v.literal("1"),
1028
1379
  deployment: cloudDeploymentSchema,
@@ -1033,11 +1384,19 @@ const cloudDiscoverySchema = v.object({
1033
1384
  authentication: cloudAuthenticationSchema,
1034
1385
  capabilities: cloudCapabilitiesSchema,
1035
1386
  listing: v.optional(cloudListingSchema),
1387
+ /**
1388
+ * The oldest editor version the server works with. Older editors ask to be updated instead of
1389
+ * connecting, and the server refuses their requests.
1390
+ */
1391
+ minimumEditorVersion: v.optional(cloudEditorVersionSchema),
1036
1392
  /** The services editors reach with Cloud-signed tokens; absent when the deployment has none. */
1037
1393
  services: v.optional(cloudServicesDiscoverySchema),
1038
1394
  /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
1039
1395
  billing: v.optional(cloudBillingDiscoverySchema),
1040
- legal: v.optional(cloudLegalDiscoverySchema)
1396
+ /** The community gallery; absent when the deployment has none. */
1397
+ community: v.optional(cloudCommunityDiscoverySchema),
1398
+ legal: v.optional(cloudLegalDiscoverySchema),
1399
+ branding: v.optional(cloudBrandingSchema)
1041
1400
  });
1042
1401
  /** The server's own address, where its editor and pages are, from its auth API's. */
1043
1402
  function cloudServerOrigin(discovery) {
@@ -1090,6 +1449,191 @@ const restoredDocumentSchema = v.object({
1090
1449
  version: documentVersionSchema
1091
1450
  });
1092
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
1605
+ //#region src/contract/community.ts
1606
+ /** A version of a community document someone named, such as the release it was published for. */
1607
+ const communityVersionSchema = v.object({
1608
+ id: v.pipe(v.string(), v.uuid()),
1609
+ name: v.string(),
1610
+ description: v.nullable(v.string()),
1611
+ createdAt: v.string(),
1612
+ /** Whether the document holds this version now, with nothing changed since it was named. */
1613
+ current: v.boolean()
1614
+ });
1615
+ /**
1616
+ * A document in the deployment's community workspace, which anyone may open read-only: its name,
1617
+ * when it last changed, its thumbnail's path on the server, and its named versions, newest first.
1618
+ */
1619
+ const communityDocumentSchema = v.object({
1620
+ id: v.pipe(v.string(), v.uuid()),
1621
+ name: v.string(),
1622
+ kind: documentKindSchema,
1623
+ updatedAt: v.string(),
1624
+ revisionId: v.pipe(v.string(), v.uuid()),
1625
+ thumbnailPath: v.string(),
1626
+ versions: v.array(communityVersionSchema)
1627
+ });
1628
+ /** The community workspace's documents, most recently changed first. */
1629
+ const communityDocumentsSchema = v.object({ documents: v.array(communityDocumentSchema) });
1630
+ v.object({ version: v.optional(v.pipe(v.string(), v.uuid())) });
1631
+ /** A community document, or one of its named versions, with where to download it. */
1632
+ const communityDownloadSchema = v.object({
1633
+ document: documentDownloadSchema,
1634
+ version: v.nullable(communityVersionSchema)
1635
+ });
1636
+ //#endregion
1093
1637
  //#region src/client/services.ts
1094
1638
  var CloudServiceError = class extends Error {
1095
1639
  status;
@@ -1101,6 +1645,15 @@ var CloudServiceError = class extends Error {
1101
1645
  this.code = code;
1102
1646
  }
1103
1647
  };
1648
+ /** A service endpoint a token would reach in the clear, which no request is sent to. */
1649
+ var CloudServiceInsecureEndpointError = class extends Error {
1650
+ url;
1651
+ name = "CloudServiceInsecureEndpointError";
1652
+ constructor(url) {
1653
+ super("OpenPencil services and billing are reached only over HTTPS");
1654
+ this.url = url;
1655
+ }
1656
+ };
1104
1657
  /** Whether a request can be sent twice: a stream, in `init` or a `Request`, is read by the first. */
1105
1658
  function replayable(input, body) {
1106
1659
  if (input instanceof Request && input.body) return false;
@@ -1121,6 +1674,8 @@ function cloudServicesFetch(tokens, fetch) {
1121
1674
  });
1122
1675
  };
1123
1676
  return async (input, init) => {
1677
+ const url = input instanceof Request ? input.url : input;
1678
+ if (!sendsTokenSafely(url)) throw new CloudServiceInsecureEndpointError(String(url));
1124
1679
  const token = await tokens.token();
1125
1680
  const response = await send(input, init, token);
1126
1681
  if (response.status !== 401) return response;
@@ -1130,32 +1685,28 @@ function cloudServicesFetch(tokens, fetch) {
1130
1685
  };
1131
1686
  }
1132
1687
  const errorBodySchema = v.pipe(v.string(), v.parseJson(), serviceErrorSchema);
1133
- async function parsed(response, schema) {
1134
- const text = await response.text();
1135
- if (!response.ok) {
1136
- const error = v.safeParse(errorBodySchema, text);
1137
- throw new CloudServiceError(response.status, error.success ? error.output.error.code : void 0);
1138
- }
1139
- return v.parse(v.pipe(v.string(), v.parseJson(), schema), text);
1688
+ function refused(status, body) {
1689
+ const error = v.safeParse(errorBodySchema, body);
1690
+ return new CloudServiceError(status, error.success ? error.output.error.code : void 0);
1140
1691
  }
1141
1692
  /** The services a Cloud advertises: the model API base URL, catalog, wallet, and search. */
1142
1693
  function createCloudServicesClient(options) {
1143
- const endpoint = options.endpoint.replace(/\/+$/, "");
1694
+ const endpoint = withoutTrailingSlash(options.endpoint);
1144
1695
  const fetch = cloudServicesFetch(options.tokens, options.fetch);
1145
1696
  const { v1 } = hc(endpoint, { fetch });
1146
1697
  return {
1147
1698
  /** The base URL an OpenAI-compatible client sends chat completions below. */
1148
- modelBaseURL: `${endpoint}${CLOUD_SERVICES_API_PATHS.base}`,
1699
+ modelBaseURL: joinURL(endpoint, CLOUD_SERVICES_API_PATHS.base),
1149
1700
  fetch,
1150
1701
  async catalog() {
1151
- return parsed(await v1.catalog.$get(), serviceCatalogSchema);
1702
+ return serviceJSON(await v1.catalog.$get(), serviceCatalogSchema, refused);
1152
1703
  },
1153
1704
  async wallet() {
1154
- return parsed(await v1.wallet.$get(), creditWalletSchema);
1705
+ return serviceJSON(await v1.wallet.$get(), creditWalletSchema, refused);
1155
1706
  },
1156
1707
  /** A web search, charged to the workspace; only when the catalog lists `search`. */
1157
1708
  async search(input) {
1158
- return parsed(await v1.search.$post({ json: input }), searchResponseSchema);
1709
+ return serviceJSON(await v1.search.$post({ json: input }), searchResponseSchema, refused);
1159
1710
  }
1160
1711
  };
1161
1712
  }
@@ -1188,33 +1739,611 @@ function cloudRedirectPath(value, fallback = "/app") {
1188
1739
  return `${url.pathname}${url.search}${url.hash}`;
1189
1740
  }
1190
1741
  //#endregion
1191
- //#region src/client/response.ts
1192
- const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
1193
- var CloudAPIError = class extends Error {
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 {
1194
1889
  status;
1195
- code;
1196
- name = "CloudAPIError";
1197
- constructor(message, status, code) {
1198
- super(message);
1890
+ name = "ObjectUploadError";
1891
+ constructor(status) {
1892
+ super(`Cloud object upload failed with HTTP ${status}`);
1199
1893
  this.status = status;
1200
- this.code = code;
1201
1894
  }
1202
1895
  };
1203
- async function responseBody(response, onDiagnostic) {
1204
- if (response.ok) return response.status === 204 ? null : response.json();
1205
- let code;
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);
1206
1948
  try {
1207
- const body = v.safeParse(cloudErrorResponseSchema, await response.json());
1208
- if (body.success) code = body.output.error.code;
1209
- } catch (error) {
1210
- onDiagnostic?.("Cloud API error response was not JSON", error);
1949
+ return await Promise.all(multipart.parts.map(putOne));
1950
+ } finally {
1951
+ upload.signal?.removeEventListener("abort", stop);
1211
1952
  }
1212
- throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
1213
1953
  }
1214
- async function parseResponse(request, schema, onDiagnostic) {
1215
- return v.parse(schema, await responseBody(await request, onDiagnostic));
1216
- }
1217
- //#endregion
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
2244
+ //#region src/client/community.ts
2245
+ /** The server’s community gallery, which anyone may open without signing in. */
2246
+ function createCommunityRequests(publicClient, onDiagnostic) {
2247
+ return {
2248
+ /** The gallery's documents, most recently changed first. */
2249
+ async listCommunityDocuments() {
2250
+ return parseResponse(publicClient.community.$get(), communityDocumentsSchema, onDiagnostic);
2251
+ },
2252
+ /**
2253
+ * A document of the server's community gallery as it is now, or one of its named versions,
2254
+ * which anyone may open without signing in.
2255
+ */
2256
+ async getCommunityDocument(documentId, versionId = null) {
2257
+ return parseResponse(publicClient.community[":documentId"].document.$get({
2258
+ param: { documentId },
2259
+ query: versionId ? { version: versionId } : {}
2260
+ }), communityDownloadSchema, onDiagnostic);
2261
+ }
2262
+ };
2263
+ }
2264
+ //#endregion
2265
+ //#region src/client/schema.ts
2266
+ /** What the API answers with one document, as creating, restoring, or duplicating one does. */
2267
+ const documentResponseSchema = v.object({ document: documentSummarySchema });
2268
+ /** What the API answers with a ticket into a document's live room. */
2269
+ const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
2270
+ //#endregion
2271
+ //#region src/client/documents.ts
2272
+ const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
2273
+ const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
2274
+ const downloadResponseSchema = v.object({ document: documentDownloadSchema });
2275
+ const accessResponseSchema = v.object({ access: documentAccessSchema });
2276
+ const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
2277
+ const uploadResponseSchema = v.object({
2278
+ id: v.pipe(v.string(), v.uuid()),
2279
+ upload: objectUploadSchema
2280
+ });
2281
+ /** Documents: listing and creating them, Trash, downloads, uploads, and collaboration tickets. */
2282
+ function createDocumentRequests(client, onDiagnostic) {
2283
+ return {
2284
+ async getUserProfile(documentId, userId) {
2285
+ return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
2286
+ documentId,
2287
+ userId
2288
+ } }), userLookupResponseSchema, onDiagnostic)).user;
2289
+ },
2290
+ /** Documents shared with the person directly, outside their workspaces. */
2291
+ async listSharedDocuments() {
2292
+ return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, onDiagnostic)).documents;
2293
+ },
2294
+ async listDocuments(workspaceId) {
2295
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, onDiagnostic)).documents;
2296
+ },
2297
+ async createDocument(workspaceId, input) {
2298
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
2299
+ param: { workspaceId },
2300
+ json: {
2301
+ ...input,
2302
+ kind: input.kind ?? "design"
2303
+ }
2304
+ }), documentResponseSchema, onDiagnostic)).document;
2305
+ },
2306
+ /** Documents in Trash the person may restore, across their workspaces, newest first. */
2307
+ async listTrash() {
2308
+ return (await parseResponse(client.trash.$get(), trashSchema, onDiagnostic)).documents;
2309
+ },
2310
+ async restoreDocument(documentId) {
2311
+ await responseBody(await client.trash[":documentId"].restore.$post({ param: { documentId } }), onDiagnostic);
2312
+ },
2313
+ /** Deletes a document in Trash for good. */
2314
+ async purgeDocument(documentId) {
2315
+ await responseBody(await client.trash[":documentId"].$delete({ param: { documentId } }), onDiagnostic);
2316
+ },
2317
+ async deleteDocument(documentId) {
2318
+ await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), onDiagnostic);
2319
+ },
2320
+ async getDocument(documentId) {
2321
+ return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, onDiagnostic)).document;
2322
+ },
2323
+ async getDocumentAccess(documentId) {
2324
+ return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, onDiagnostic)).access;
2325
+ },
2326
+ async getCollaborationTicket(documentId) {
2327
+ return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, onDiagnostic)).ticket;
2328
+ },
2329
+ async createUpload(documentId, input) {
2330
+ return parseResponse(client.documents[":documentId"].uploads.$post({
2331
+ param: { documentId },
2332
+ json: input
2333
+ }), uploadResponseSchema, onDiagnostic);
2334
+ },
2335
+ async commitUpload(uploadId, input) {
2336
+ return (await parseResponse(client.uploads[":uploadId"].commit.$post({
2337
+ param: { uploadId },
2338
+ json: {
2339
+ ...input,
2340
+ images: input.images ?? []
2341
+ }
2342
+ }), documentResponseSchema, onDiagnostic)).document;
2343
+ }
2344
+ };
2345
+ }
2346
+ //#endregion
1218
2347
  //#region src/client/images.ts
1219
2348
  const imageLinksResponseSchema = v.object({ images: v.array(documentImageLinkSchema) });
1220
2349
  const imageUploadsResponseSchema = v.object({ uploads: v.array(imageUploadOfferSchema) });
@@ -1255,83 +2384,7 @@ function createImageRequests(client, publicClient, onDiagnostic) {
1255
2384
  };
1256
2385
  }
1257
2386
  //#endregion
1258
- //#region src/client/workspaces.ts
1259
- const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
1260
- const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
1261
- const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
1262
- /** Workspaces, their members, invitations, entitlements, and storage use. */
1263
- function createWorkspaceRequests(client, onDiagnostic) {
1264
- return {
1265
- async listWorkspaces() {
1266
- return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
1267
- },
1268
- async createWorkspace(name) {
1269
- return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
1270
- },
1271
- async renameWorkspace(workspaceId, name) {
1272
- return (await parseResponse(client.workspaces[":workspaceId"].$patch({
1273
- param: { workspaceId },
1274
- json: { name }
1275
- }), workspaceResponseSchema, onDiagnostic)).workspace;
1276
- },
1277
- /** Deletes an empty workspace; the server refuses one that still holds documents. */
1278
- async deleteWorkspace(workspaceId) {
1279
- await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1280
- },
1281
- /** The workspace's members, and for administrators its pending invitations. */
1282
- async listWorkspaceMembers(workspaceId) {
1283
- return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1284
- },
1285
- async inviteToWorkspace(workspaceId, input) {
1286
- return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
1287
- param: { workspaceId },
1288
- json: input
1289
- }), createdWorkspaceInvitationSchema, onDiagnostic);
1290
- },
1291
- /** Sends a waiting invitation again; its earlier link stops working. */
1292
- async resendWorkspaceInvitation(workspaceId, invitationId) {
1293
- return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
1294
- workspaceId,
1295
- invitationId
1296
- } }), createdWorkspaceInvitationSchema, onDiagnostic);
1297
- },
1298
- async revokeWorkspaceInvitation(workspaceId, invitationId) {
1299
- await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
1300
- workspaceId,
1301
- invitationId
1302
- } }), onDiagnostic);
1303
- },
1304
- async updateWorkspaceMember(workspaceId, userId, role) {
1305
- await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1306
- param: {
1307
- workspaceId,
1308
- userId
1309
- },
1310
- json: { role }
1311
- }), onDiagnostic);
1312
- },
1313
- /** Removes someone from the workspace; with the person's own id, leaves it. */
1314
- async removeWorkspaceMember(workspaceId, userId) {
1315
- await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
1316
- workspaceId,
1317
- userId
1318
- } }), onDiagnostic);
1319
- },
1320
- async getWorkspaceEntitlements(workspaceId) {
1321
- return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1322
- },
1323
- async getUsage(workspaceId) {
1324
- return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
1325
- }
1326
- };
1327
- }
1328
- //#endregion
1329
- //#region src/client/api.ts
1330
- const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
1331
- const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
1332
- const documentResponseSchema = v.object({ document: documentSummarySchema });
1333
- const downloadResponseSchema = v.object({ document: documentDownloadSchema });
1334
- const accessResponseSchema = v.object({ access: documentAccessSchema });
2387
+ //#region src/client/sharing.ts
1335
2388
  const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) });
1336
2389
  const shareResponseSchema = v.object({ share: documentShareSchema });
1337
2390
  const shareCapabilityResponseSchema = v.object({
@@ -1348,108 +2401,22 @@ const invitationCapabilityResponseSchema = v.object({
1348
2401
  invitation: documentInvitationSchema,
1349
2402
  token: v.string()
1350
2403
  });
1351
- const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1352
2404
  const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema });
1353
2405
  const sharedDocumentResponseSchema = v.object({
1354
2406
  resolution: resolvedDocumentShareSchema,
1355
2407
  document: documentDownloadSchema
1356
2408
  });
1357
- const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
1358
- const uploadResponseSchema = v.object({
1359
- id: v.pipe(v.string(), v.uuid()),
1360
- upload: objectUploadSchema
1361
- });
1362
- function apiURL(baseURL) {
1363
- const url = new URL(baseURL);
1364
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("OpenPencil Cloud API URL must use HTTP or HTTPS", 0);
1365
- url.pathname = url.pathname.replace(/\/$/, "");
1366
- url.search = "";
1367
- url.hash = "";
1368
- return url.href;
1369
- }
1370
- function createCloudAPIClient(baseURL, options = {}) {
1371
- const headers = {
1372
- "Content-Type": "application/json",
1373
- ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1374
- };
1375
- const client = hc(apiURL(baseURL), {
1376
- fetch: options.fetch,
1377
- init: {
1378
- credentials: "include",
1379
- signal: options.signal,
1380
- headers
1381
- }
1382
- });
1383
- const publicClient = hc(apiURL(baseURL), {
1384
- fetch: options.fetch,
1385
- init: {
1386
- credentials: "include",
1387
- signal: options.signal,
1388
- headers
1389
- }
1390
- });
2409
+ /** Sharing a document: its links, grants, and invitations, and opening what someone shared. */
2410
+ function createSharingRequests(client, publicClient, onDiagnostic) {
1391
2411
  return {
1392
- async getSession() {
1393
- const response = await client.session.$get();
1394
- if (response.status === 401) return null;
1395
- return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
1396
- },
1397
- /** A short-lived token for the deployment's services, on the workspace's behalf. */
1398
- async requestServicesToken(workspaceId) {
1399
- return parseResponse(client.services.token.$post({ json: { workspaceId } }), servicesTokenSchema, options.onDiagnostic);
1400
- },
1401
- async getUserProfile(documentId, userId) {
1402
- return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
1403
- documentId,
1404
- userId
1405
- } }), userLookupResponseSchema, options.onDiagnostic)).user;
1406
- },
1407
- ...createWorkspaceRequests(client, options.onDiagnostic),
1408
- ...createImageRequests(client, publicClient, options.onDiagnostic),
1409
- /** Documents shared with the person directly, outside their workspaces. */
1410
- async listSharedDocuments() {
1411
- return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, options.onDiagnostic)).documents;
1412
- },
1413
- async listDocuments(workspaceId) {
1414
- return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, options.onDiagnostic)).documents;
1415
- },
1416
- async createDocument(workspaceId, input) {
1417
- return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
1418
- param: { workspaceId },
1419
- json: {
1420
- ...input,
1421
- kind: input.kind ?? "design"
1422
- }
1423
- }), documentResponseSchema, options.onDiagnostic)).document;
1424
- },
1425
- /** Documents in Trash the person may restore, across their workspaces, newest first. */
1426
- async listTrash() {
1427
- return (await parseResponse(client.trash.$get(), trashSchema, options.onDiagnostic)).documents;
1428
- },
1429
- async restoreDocument(documentId) {
1430
- await responseBody(await client.trash[":documentId"].restore.$post({ param: { documentId } }), options.onDiagnostic);
1431
- },
1432
- /** Deletes a document in Trash for good. */
1433
- async purgeDocument(documentId) {
1434
- await responseBody(await client.trash[":documentId"].$delete({ param: { documentId } }), options.onDiagnostic);
1435
- },
1436
- async deleteDocument(documentId) {
1437
- await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), options.onDiagnostic);
1438
- },
1439
- async getDocument(documentId) {
1440
- return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, options.onDiagnostic)).document;
1441
- },
1442
- async getDocumentAccess(documentId) {
1443
- return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, options.onDiagnostic)).access;
1444
- },
1445
2412
  async listDocumentShares(documentId) {
1446
- return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, options.onDiagnostic)).shares;
2413
+ return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, onDiagnostic)).shares;
1447
2414
  },
1448
2415
  async createDocumentShare(documentId, input) {
1449
2416
  return parseResponse(client.documents[":documentId"].shares.$post({
1450
2417
  param: { documentId },
1451
2418
  json: input
1452
- }), shareCapabilityResponseSchema, options.onDiagnostic);
2419
+ }), shareCapabilityResponseSchema, onDiagnostic);
1453
2420
  },
1454
2421
  async updateDocumentShare(documentId, shareId, input) {
1455
2422
  return (await parseResponse(client.documents[":documentId"].shares[":shareId"].$patch({
@@ -1458,22 +2425,22 @@ function createCloudAPIClient(baseURL, options = {}) {
1458
2425
  shareId
1459
2426
  },
1460
2427
  json: input
1461
- }), shareResponseSchema, options.onDiagnostic)).share;
2428
+ }), shareResponseSchema, onDiagnostic)).share;
1462
2429
  },
1463
2430
  async rotateDocumentShare(documentId, shareId) {
1464
2431
  return parseResponse(client.documents[":documentId"].shares[":shareId"].rotate.$post({ param: {
1465
2432
  documentId,
1466
2433
  shareId
1467
- } }), shareCapabilityResponseSchema, options.onDiagnostic);
2434
+ } }), shareCapabilityResponseSchema, onDiagnostic);
1468
2435
  },
1469
2436
  async revokeDocumentShare(documentId, shareId) {
1470
2437
  await responseBody(await client.documents[":documentId"].shares[":shareId"].$delete({ param: {
1471
2438
  documentId,
1472
2439
  shareId
1473
- } }), options.onDiagnostic);
2440
+ } }), onDiagnostic);
1474
2441
  },
1475
2442
  async listDocumentGrants(documentId) {
1476
- return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, options.onDiagnostic)).grants;
2443
+ return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, onDiagnostic)).grants;
1477
2444
  },
1478
2445
  async putDocumentGrant(documentId, userId, input) {
1479
2446
  return (await parseResponse(client.documents[":documentId"].grants[":userId"].$put({
@@ -1482,134 +2449,431 @@ function createCloudAPIClient(baseURL, options = {}) {
1482
2449
  userId
1483
2450
  },
1484
2451
  json: input
1485
- }), grantResponseSchema, options.onDiagnostic)).grant;
2452
+ }), grantResponseSchema, onDiagnostic)).grant;
1486
2453
  },
1487
2454
  async revokeDocumentGrant(documentId, userId) {
1488
2455
  await responseBody(await client.documents[":documentId"].grants[":userId"].$delete({ param: {
1489
2456
  documentId,
1490
2457
  userId
1491
- } }), options.onDiagnostic);
2458
+ } }), onDiagnostic);
1492
2459
  },
1493
2460
  async listDocumentInvitations(documentId) {
1494
- return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, options.onDiagnostic)).invitations;
2461
+ return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, onDiagnostic)).invitations;
1495
2462
  },
1496
2463
  async createDocumentInvitation(documentId, input) {
1497
2464
  return parseResponse(client.documents[":documentId"].invitations.$post({
1498
2465
  param: { documentId },
1499
2466
  json: input
1500
- }), invitationCapabilityResponseSchema, options.onDiagnostic);
2467
+ }), invitationCapabilityResponseSchema, onDiagnostic);
1501
2468
  },
1502
2469
  async createInvitationContinuation(input) {
1503
- return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, options.onDiagnostic);
2470
+ return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, onDiagnostic);
1504
2471
  },
1505
2472
  async consumeInvitationContinuation(id) {
1506
- return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, options.onDiagnostic);
2473
+ return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, onDiagnostic);
1507
2474
  },
1508
2475
  async previewInvitation(invitationId, input) {
1509
2476
  return (await parseResponse(publicClient.invitations[":invitationId"].preview.$post({
1510
2477
  param: { invitationId },
1511
2478
  json: input
1512
- }), invitationPreviewResponseSchema, options.onDiagnostic)).invitation;
2479
+ }), invitationPreviewResponseSchema, onDiagnostic)).invitation;
1513
2480
  },
1514
2481
  /** Accepts a document or workspace invitation, and says which it was. */
1515
2482
  async acceptInvitation(invitationId, input) {
1516
2483
  return (await parseResponse(client.invitations[":invitationId"].accept.$post({
1517
2484
  param: { invitationId },
1518
2485
  json: input
1519
- }), acceptedResponseSchema, options.onDiagnostic)).accepted;
2486
+ }), acceptedResponseSchema, onDiagnostic)).accepted;
1520
2487
  },
1521
2488
  async revokeDocumentInvitation(documentId, invitationId) {
1522
2489
  await responseBody(await client.documents[":documentId"].invitations[":invitationId"].$delete({ param: {
1523
2490
  documentId,
1524
2491
  invitationId
1525
- } }), options.onDiagnostic);
2492
+ } }), onDiagnostic);
1526
2493
  },
1527
2494
  /** Reports the document a share link opens to the server's administrators. */
1528
2495
  async fileDocumentReport(shareId, input) {
1529
2496
  await parseResponse(publicClient.shares[":shareId"].reports.$post({
1530
2497
  param: { shareId },
1531
2498
  json: input
1532
- }), fileDocumentReportResponseSchema, options.onDiagnostic);
2499
+ }), fileDocumentReportResponseSchema, onDiagnostic);
1533
2500
  },
1534
2501
  async resolveDocumentShare(shareId, input) {
1535
2502
  return (await parseResponse(publicClient.shares[":shareId"].resolve.$post({
1536
2503
  param: { shareId },
1537
2504
  json: input
1538
- }), resolvedShareResponseSchema, options.onDiagnostic)).resolution;
2505
+ }), resolvedShareResponseSchema, onDiagnostic)).resolution;
1539
2506
  },
1540
2507
  async getSharedDocument(shareId, input) {
1541
2508
  return parseResponse(publicClient.shares[":shareId"].document.$post({
1542
2509
  param: { shareId },
1543
2510
  json: input
1544
- }), sharedDocumentResponseSchema, options.onDiagnostic);
2511
+ }), sharedDocumentResponseSchema, onDiagnostic);
1545
2512
  },
1546
2513
  async getSharedCollaborationTicket(shareId, input) {
1547
2514
  return (await parseResponse(publicClient.shares[":shareId"]["collaboration-ticket"].$post({
1548
2515
  param: { shareId },
1549
2516
  json: input
1550
- }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1551
- },
1552
- async getCollaborationTicket(documentId) {
1553
- return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
2517
+ }), collaborationTicketResponseSchema, onDiagnostic)).ticket;
2518
+ }
2519
+ };
2520
+ }
2521
+ //#endregion
2522
+ //#region src/client/versions.ts
2523
+ /** A document’s version history: listing, naming, opening, restoring, and duplicating. */
2524
+ function createVersionRequests(client, onDiagnostic) {
2525
+ return {
2526
+ /** A page of the document's version history, newest first. */
2527
+ async listDocumentVersions(documentId, page = {}) {
2528
+ return parseResponse(client.documents[":documentId"].versions.$get({
2529
+ param: { documentId },
2530
+ query: pickBy({
2531
+ before: page.before,
2532
+ limit: page.limit === void 0 ? void 0 : String(page.limit)
2533
+ }, (value) => value !== void 0)
2534
+ }), documentVersionsSchema, onDiagnostic);
1554
2535
  },
1555
- async createUpload(documentId, input) {
1556
- return parseResponse(client.documents[":documentId"].uploads.$post({
2536
+ async saveDocumentVersion(documentId, input) {
2537
+ return (await parseResponse(client.documents[":documentId"].versions.$post({
1557
2538
  param: { documentId },
1558
2539
  json: input
1559
- }), uploadResponseSchema, options.onDiagnostic);
2540
+ }), documentVersionResponseSchema, onDiagnostic)).version;
1560
2541
  },
1561
- async commitUpload(uploadId, input) {
1562
- return (await parseResponse(client.uploads[":uploadId"].commit.$post({
1563
- param: { uploadId },
1564
- json: {
1565
- ...input,
1566
- images: input.images ?? []
1567
- }
1568
- }), documentResponseSchema, options.onDiagnostic)).document;
2542
+ async updateDocumentVersion(documentId, versionId, input) {
2543
+ return (await parseResponse(client.documents[":documentId"].versions[":versionId"].$patch({
2544
+ param: {
2545
+ documentId,
2546
+ versionId
2547
+ },
2548
+ json: input
2549
+ }), documentVersionResponseSchema, onDiagnostic)).version;
2550
+ },
2551
+ async getDocumentVersion(documentId, versionId) {
2552
+ return parseResponse(client.documents[":documentId"].versions[":versionId"].$get({ param: {
2553
+ documentId,
2554
+ versionId
2555
+ } }), documentVersionDownloadSchema, onDiagnostic);
2556
+ },
2557
+ async restoreDocumentVersion(documentId, versionId) {
2558
+ return parseResponse(client.documents[":documentId"].versions[":versionId"].restore.$post({ param: {
2559
+ documentId,
2560
+ versionId
2561
+ } }), restoredDocumentSchema, onDiagnostic);
2562
+ },
2563
+ async duplicateDocumentVersion(documentId, versionId, input) {
2564
+ return (await parseResponse(client.documents[":documentId"].versions[":versionId"].duplicate.$post({
2565
+ param: {
2566
+ documentId,
2567
+ versionId
2568
+ },
2569
+ json: input
2570
+ }), documentResponseSchema, onDiagnostic)).document;
2571
+ }
2572
+ };
2573
+ }
2574
+ //#endregion
2575
+ //#region src/client/workspaces.ts
2576
+ const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
2577
+ const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
2578
+ const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
2579
+ /** Workspaces, their members, invitations, entitlements, and storage use. */
2580
+ function createWorkspaceRequests(client, onDiagnostic) {
2581
+ return {
2582
+ async listWorkspaces() {
2583
+ return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
2584
+ },
2585
+ async createWorkspace(name) {
2586
+ return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
2587
+ },
2588
+ async renameWorkspace(workspaceId, name) {
2589
+ return (await parseResponse(client.workspaces[":workspaceId"].$patch({
2590
+ param: { workspaceId },
2591
+ json: { name }
2592
+ }), workspaceResponseSchema, onDiagnostic)).workspace;
2593
+ },
2594
+ /** Deletes an empty workspace; the server refuses one that still holds documents. */
2595
+ async deleteWorkspace(workspaceId) {
2596
+ await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1569
2597
  },
1570
- /** A page of the document's version history, newest first. */
1571
- async listDocumentVersions(documentId, page = {}) {
1572
- return parseResponse(client.documents[":documentId"].versions.$get({
1573
- param: { documentId },
1574
- query: pickBy(page, (value) => value !== void 0)
1575
- }), documentVersionsSchema, options.onDiagnostic);
2598
+ /** The workspace's members, and for administrators its pending invitations. */
2599
+ async listWorkspaceMembers(workspaceId) {
2600
+ return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1576
2601
  },
1577
- async saveDocumentVersion(documentId, input) {
1578
- return (await parseResponse(client.documents[":documentId"].versions.$post({
1579
- param: { documentId },
2602
+ async inviteToWorkspace(workspaceId, input) {
2603
+ return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
2604
+ param: { workspaceId },
1580
2605
  json: input
1581
- }), documentVersionResponseSchema, options.onDiagnostic)).version;
2606
+ }), createdWorkspaceInvitationSchema, onDiagnostic);
1582
2607
  },
1583
- async updateDocumentVersion(documentId, versionId, input) {
1584
- return (await parseResponse(client.documents[":documentId"].versions[":versionId"].$patch({
2608
+ /** Sends a waiting invitation again; its earlier link stops working. */
2609
+ async resendWorkspaceInvitation(workspaceId, invitationId) {
2610
+ return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
2611
+ workspaceId,
2612
+ invitationId
2613
+ } }), createdWorkspaceInvitationSchema, onDiagnostic);
2614
+ },
2615
+ async revokeWorkspaceInvitation(workspaceId, invitationId) {
2616
+ await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
2617
+ workspaceId,
2618
+ invitationId
2619
+ } }), onDiagnostic);
2620
+ },
2621
+ async updateWorkspaceMember(workspaceId, userId, role) {
2622
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1585
2623
  param: {
1586
- documentId,
1587
- versionId
2624
+ workspaceId,
2625
+ userId
1588
2626
  },
1589
- json: input
1590
- }), documentVersionResponseSchema, options.onDiagnostic)).version;
2627
+ json: { role }
2628
+ }), onDiagnostic);
1591
2629
  },
1592
- async getDocumentVersion(documentId, versionId) {
1593
- return parseResponse(client.documents[":documentId"].versions[":versionId"].$get({ param: {
1594
- documentId,
1595
- versionId
1596
- } }), documentVersionDownloadSchema, options.onDiagnostic);
2630
+ /** Removes someone from the workspace; with the person's own id, leaves it. */
2631
+ async removeWorkspaceMember(workspaceId, userId) {
2632
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
2633
+ workspaceId,
2634
+ userId
2635
+ } }), onDiagnostic);
1597
2636
  },
1598
- async restoreDocumentVersion(documentId, versionId) {
1599
- return parseResponse(client.documents[":documentId"].versions[":versionId"].restore.$post({ param: {
1600
- documentId,
1601
- versionId
1602
- } }), restoredDocumentSchema, options.onDiagnostic);
2637
+ async getWorkspaceEntitlements(workspaceId) {
2638
+ return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1603
2639
  },
1604
- async duplicateDocumentVersion(documentId, versionId, input) {
1605
- return (await parseResponse(client.documents[":documentId"].versions[":versionId"].duplicate.$post({
1606
- param: {
1607
- documentId,
1608
- versionId
1609
- },
1610
- json: input
1611
- }), documentResponseSchema, options.onDiagnostic)).document;
2640
+ async getUsage(workspaceId) {
2641
+ return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
2642
+ }
2643
+ };
2644
+ }
2645
+ //#endregion
2646
+ //#region src/client/api.ts
2647
+ function apiURL(baseURL) {
2648
+ const url = new URL(baseURL);
2649
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("OpenPencil Cloud API URL must use HTTP or HTTPS", 0);
2650
+ url.pathname = url.pathname.replace(/\/$/, "");
2651
+ url.search = "";
2652
+ url.hash = "";
2653
+ return url.href;
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
+ }
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);
2670
+ const headers = {
2671
+ "Content-Type": "application/json",
2672
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
2673
+ };
2674
+ const fetch = boundedFetch(options.fetch);
2675
+ const client = hc(apiURL(baseURL), {
2676
+ fetch,
2677
+ init: {
2678
+ credentials: "include",
2679
+ signal: options.signal,
2680
+ headers
2681
+ }
2682
+ });
2683
+ const publicClient = hc(apiURL(baseURL), {
2684
+ fetch,
2685
+ init: {
2686
+ credentials: "include",
2687
+ signal: options.signal,
2688
+ headers
1612
2689
  }
2690
+ });
2691
+ return {
2692
+ async getSession() {
2693
+ const response = await client.session.$get();
2694
+ if (response.status === 401) return null;
2695
+ return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
2696
+ },
2697
+ /** A short-lived token for the deployment's services, on the workspace's behalf. */
2698
+ async requestServicesToken(workspaceId) {
2699
+ return parseResponse(client.services.token.$post({ json: { workspaceId } }), servicesTokenSchema, options.onDiagnostic);
2700
+ },
2701
+ /** A short-lived token for the deployment's billing, for the signed-in person's own account. */
2702
+ async requestBillingToken() {
2703
+ return parseResponse(client.billing.token.$post(), billingTokenSchema, options.onDiagnostic);
2704
+ },
2705
+ /** The signed-in account's plan, and the storage its workspaces hold together. */
2706
+ async getAccountEntitlements() {
2707
+ return (await parseResponse(client.account.entitlements.$get(), accountEntitlementsResponseSchema, options.onDiagnostic)).entitlements;
2708
+ },
2709
+ ...createWorkspaceRequests(client, options.onDiagnostic),
2710
+ ...createImageRequests(client, publicClient, options.onDiagnostic),
2711
+ ...createDocumentRequests(client, options.onDiagnostic),
2712
+ ...createVersionRequests(client, options.onDiagnostic),
2713
+ ...createCommentRequests(client, options.onDiagnostic),
2714
+ ...createSharedCommentRequests(publicClient, options.onDiagnostic),
2715
+ ...createSharingRequests(client, publicClient, options.onDiagnostic),
2716
+ ...createCommunityRequests(publicClient, options.onDiagnostic)
2717
+ };
2718
+ }
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
1613
2877
  };
1614
2878
  }
1615
2879
  //#endregion
@@ -1733,12 +2997,16 @@ async function signInToCloudWithEmail(discovery, input, options = {}) {
1733
2997
  }
1734
2998
  };
1735
2999
  }
1736
- /** Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed. */
3000
+ /**
3001
+ * Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed,
3002
+ * written in `locale`, the app's language.
3003
+ */
1737
3004
  async function signUpToCloudWithEmail(discovery, input, options = {}) {
1738
3005
  const result = await createCloudAuthClient(discovery, options).signUp.email({
1739
3006
  name: input.name,
1740
3007
  email: input.email,
1741
3008
  password: input.password,
3009
+ locale: input.locale,
1742
3010
  callbackURL: input.verifiedURL
1743
3011
  }).catch(() => null);
1744
3012
  if (!result) return cloudAuthFailure(null);
@@ -1788,15 +3056,6 @@ var CloudDeviceAuthorizationError = class extends Error {
1788
3056
  this.code = code;
1789
3057
  }
1790
3058
  };
1791
- function abortableSleep(milliseconds, signal) {
1792
- return new Promise((resolve, reject) => {
1793
- const timeout = setTimeout(resolve, milliseconds);
1794
- signal?.addEventListener("abort", () => {
1795
- clearTimeout(timeout);
1796
- reject(signal.reason instanceof Error ? signal.reason : new DOMException("Authorization cancelled", "AbortError"));
1797
- }, { once: true });
1798
- });
1799
- }
1800
3059
  function authEndpoint(discovery, path) {
1801
3060
  return joinURL(discovery.authURL, path);
1802
3061
  }
@@ -1815,12 +3074,12 @@ async function requestCloudDeviceAuthorization(discovery, connectionId, options
1815
3074
  async function pollCloudDeviceToken(discovery, connectionId, authorization, options = {}) {
1816
3075
  const request = options.fetch ?? globalThis.fetch;
1817
3076
  const now = options.now ?? Date.now;
1818
- const sleep = options.sleep ?? abortableSleep;
3077
+ const wait = options.sleep ?? sleep;
1819
3078
  const expiresAt = now() + authorization.expires_in * 1e3;
1820
3079
  let interval = authorization.interval * 1e3;
1821
3080
  while (now() < expiresAt) {
1822
3081
  options.signal?.throwIfAborted();
1823
- await sleep(interval, options.signal);
3082
+ await wait(interval, options.signal);
1824
3083
  if (now() >= expiresAt) break;
1825
3084
  const response = await request(authEndpoint(discovery, "device/token"), {
1826
3085
  method: "POST",
@@ -1854,64 +3113,24 @@ async function pollCloudDeviceToken(discovery, connectionId, authorization, opti
1854
3113
  throw new CloudDeviceAuthorizationError("expired");
1855
3114
  }
1856
3115
  //#endregion
1857
- //#region src/client/discovery.ts
1858
- const DISCOVERY_TIMEOUT_MS = 1e4;
1859
- var CloudClientError = class extends Error {
1860
- cause;
1861
- reason;
1862
- constructor(message, cause, reason = "unreachable") {
1863
- super(message);
1864
- this.cause = cause;
1865
- this.reason = reason;
1866
- this.name = "CloudClientError";
1867
- }
1868
- };
1869
- const discoveryBodySchema = v.pipe(v.string(), v.parseJson(), v.looseObject({}));
1870
- const protocolSchema = v.looseObject({ protocolVersion: v.string() });
1871
- function discoveryURL(serverURL) {
1872
- let url;
1873
- try {
1874
- url = new URL(serverURL);
1875
- } catch (error) {
1876
- throw new CloudClientError("OpenPencil server URL is invalid", error, "invalid-address");
1877
- }
1878
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudClientError("OpenPencil server URL must use HTTP or HTTPS", void 0, "invalid-address");
1879
- url.pathname = CLOUD_DISCOVERY_PATH;
1880
- url.search = "";
1881
- url.hash = "";
1882
- return url;
1883
- }
1884
- function parseDiscoveryBody(text) {
1885
- const body = v.safeParse(discoveryBodySchema, text);
1886
- if (!body.success) throw new CloudClientError("OpenPencil server discovery is not JSON", body.issues, "not-cloud");
1887
- const discovery = v.safeParse(cloudDiscoverySchema, body.output);
1888
- if (discovery.success) return discovery.output;
1889
- const protocol = v.safeParse(protocolSchema, body.output);
1890
- const outdated = protocol.success && protocol.output.protocolVersion !== "1";
1891
- throw new CloudClientError(outdated ? `OpenPencil server speaks protocol ${protocol.output.protocolVersion}` : "OpenPencil server discovery is invalid", discovery.issues, outdated ? "outdated" : "not-cloud");
1892
- }
1893
- async function discoverCloud(serverURL, options = {}) {
1894
- const fetchImplementation = options.fetch ?? globalThis.fetch;
1895
- const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
1896
- const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
1897
- try {
1898
- const response = await fetchImplementation(discoveryURL(serverURL), {
1899
- headers: { Accept: "application/json" },
1900
- redirect: "follow",
1901
- signal
1902
- });
1903
- if (!response.ok) throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`, void 0, response.status >= 500 ? "unreachable" : "not-cloud");
1904
- return parseDiscoveryBody(await response.text());
1905
- } catch (error) {
1906
- if (error instanceof CloudClientError) throw error;
1907
- if (signal.aborted) throw new CloudClientError("OpenPencil server discovery was cancelled or timed out", error);
1908
- throw new CloudClientError("OpenPencil server discovery failed", error);
1909
- }
1910
- }
1911
- //#endregion
1912
3116
  //#region src/client/portal/account.ts
1913
- function createAccountAPI(call, { account }) {
3117
+ function createAccountAPI(call, { account, tokens, api }) {
1914
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
+ },
3126
+ /** The account's plan, and the storage its workspaces hold together. */
3127
+ entitlements(signal) {
3128
+ return call((options) => api.account.entitlements.$get(void 0, options), accountEntitlementsResponseSchema, signal);
3129
+ },
3130
+ /** A short-lived token for the deployment's billing, for this account. */
3131
+ billingToken(signal) {
3132
+ return call((options) => api.billing.token.$post(void 0, options), billingTokenSchema, signal);
3133
+ },
1915
3134
  accountStatus(signal) {
1916
3135
  return call((options) => account.status.$get(void 0, options), cloudAccountStatusResponseSchema, signal);
1917
3136
  },
@@ -1961,6 +3180,10 @@ function createAccountAPI(call, { account }) {
1961
3180
  profile(signal) {
1962
3181
  return call((options) => account.profile.$get(void 0, options), cloudProfileResponseSchema, signal);
1963
3182
  },
3183
+ /** The app's language tag; the server writes to the account in it, or the nearest it has. */
3184
+ setLocale(locale, signal) {
3185
+ return call((options) => account.locale.$put({ json: { locale } }, options), cloudAccountMutationResponseSchema, signal);
3186
+ },
1964
3187
  updateProfile(name, signal) {
1965
3188
  return call((options) => account.profile.$post({ json: { name } }, options), cloudAccountMutationResponseSchema, signal);
1966
3189
  },
@@ -1978,6 +3201,17 @@ function createAccountAPI(call, { account }) {
1978
3201
  callbackURL
1979
3202
  } }, options), cloudAccountMutationResponseSchema, signal);
1980
3203
  },
3204
+ /** The account's personal access tokens, by their first characters; never a whole one. */
3205
+ accessTokens(signal) {
3206
+ return call((options) => tokens.$get(void 0, options), cloudAccessTokensResponseSchema, signal);
3207
+ },
3208
+ /** Makes a token; the answer holds the whole token, which is shown this once. */
3209
+ createAccessToken(input, signal) {
3210
+ return call((options) => tokens.create.$post({ json: input }, options), cloudAccessTokenCreatedResponseSchema, signal);
3211
+ },
3212
+ revokeAccessToken(id, signal) {
3213
+ return call((options) => tokens.revoke.$post({ json: { id } }, options), cloudAccountMutationResponseSchema, signal);
3214
+ },
1981
3215
  sessions(signal) {
1982
3216
  return call((options) => account.sessions.$get(void 0, options), cloudAccountSessionsResponseSchema, signal);
1983
3217
  },
@@ -2005,13 +3239,17 @@ function createAccountAPI(call, { account }) {
2005
3239
  }
2006
3240
  //#endregion
2007
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
+ }
2008
3246
  /** The query string for `request`; an empty search asks for everything. */
2009
3247
  function listQuery(request) {
2010
3248
  return { query: {
2011
3249
  search: request.search || void 0,
2012
3250
  filter: request.filter,
2013
- limit: request.limit,
2014
- offset: request.offset
3251
+ limit: countParameter(request.limit),
3252
+ offset: countParameter(request.offset)
2015
3253
  } };
2016
3254
  }
2017
3255
  function createAdministrationAPI(call, { admin, api }) {
@@ -2028,8 +3266,17 @@ function createAdministrationAPI(call, { admin, api }) {
2028
3266
  json: { note }
2029
3267
  }, options), enrollmentReviewResponseSchema, signal);
2030
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. */
2031
3274
  users(request, signal) {
2032
- 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);
2033
3280
  },
2034
3281
  user(id, signal) {
2035
3282
  return call((options) => admin.users[":id"].$get({ param: { id } }, options), cloudAdminUserDetailSchema, signal);
@@ -2040,6 +3287,13 @@ function createAdministrationAPI(call, { admin, api }) {
2040
3287
  reason
2041
3288
  } }, options), adminMutationResponseSchema, signal);
2042
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
+ },
2043
3297
  setAdmin(userId, enabled, signal) {
2044
3298
  return call((options) => admin.users["set-admin"].$post({ json: {
2045
3299
  userId,
@@ -2065,6 +3319,20 @@ function createAdministrationAPI(call, { admin, api }) {
2065
3319
  documents(request, signal) {
2066
3320
  return call((options) => admin.documents.$get(listQuery(request), options), cloudAdminDocumentsResponseSchema, signal);
2067
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
+ },
2068
3336
  /** Takes a document down, or puts it back. */
2069
3337
  documentAction(id, action, reason, signal) {
2070
3338
  return call((options) => {
@@ -2101,10 +3369,10 @@ var CloudPortalAPIError = class extends Error {
2101
3369
  * body is checked against the contract.
2102
3370
  */
2103
3371
  function createCloudCall(options = {}) {
2104
- const timeoutMs = options.timeoutMs ?? 1e4;
3372
+ const timeoutMs = options.timeoutMs ?? DEADLINE_MS.request;
2105
3373
  return async (send, schema, callerSignal) => {
2106
3374
  const timeout = AbortSignal.timeout(timeoutMs);
2107
- const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
3375
+ const signal = anySignal([callerSignal, timeout]);
2108
3376
  let response;
2109
3377
  try {
2110
3378
  response = await send({ init: { signal } });
@@ -2145,6 +3413,7 @@ function createPortalRouteClients(options = {}) {
2145
3413
  };
2146
3414
  return {
2147
3415
  account: hc(origin, clientOptions).api.account,
3416
+ tokens: hc(origin, clientOptions).api.account.tokens,
2148
3417
  admin: hc(new URL("/api/admin", origin).href, clientOptions),
2149
3418
  api: hc(new URL("/api", origin).href, clientOptions)
2150
3419
  };
@@ -2161,6 +3430,6 @@ function createCloudPortalClient(options = {}) {
2161
3430
  };
2162
3431
  }
2163
3432
  //#endregion
2164
- export { CloudAPIError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, CloudServiceError, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudServicesFetch, cloudSignInURL, createCloudAPIClient, createCloudAuthClient, 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 };
2165
3434
 
2166
3435
  //# sourceMappingURL=client.js.map