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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) 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 +296 -27
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +649 -295
  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 +331 -21
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +1773 -32
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +3478 -288
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +48 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +466 -13
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +35 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +447 -290
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +89 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +15667 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +2963 -294
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/server.d.ts +3473 -842
  34. package/dist/server.d.ts.map +1 -1
  35. package/dist/server.js +12187 -8244
  36. package/dist/server.js.map +1 -1
  37. package/dist/server.mjs +7739 -3548
  38. package/dist/server.mjs.map +1 -1
  39. package/dist/server2.mjs +5 -5
  40. package/dist/server2.mjs.map +1 -1
  41. package/package.json +22 -5
  42. package/src/admin/audit/service.ts +2 -2
  43. package/src/admin/documents/service.ts +76 -6
  44. package/src/admin/reports/service.ts +7 -1
  45. package/src/client/api.ts +23 -471
  46. package/src/client/auth/client.ts +22 -3
  47. package/src/client/billing.ts +80 -0
  48. package/src/client/community.ts +40 -0
  49. package/src/client/discovery.ts +35 -9
  50. package/src/client/documents.ts +160 -0
  51. package/src/client/index.ts +7 -0
  52. package/src/client/portal/account.ts +54 -2
  53. package/src/client/portal/request.ts +2 -0
  54. package/src/client/response.ts +21 -0
  55. package/src/client/schema.ts +8 -0
  56. package/src/client/services.ts +23 -18
  57. package/src/client/sharing.ts +262 -0
  58. package/src/client/versions.ts +104 -0
  59. package/src/contract/account.ts +50 -0
  60. package/src/contract/billing.ts +166 -0
  61. package/src/contract/collaboration.ts +5 -0
  62. package/src/contract/community.ts +60 -0
  63. package/src/contract/discovery.ts +63 -2
  64. package/src/contract/entitlements.ts +10 -0
  65. package/src/contract/index.ts +54 -5
  66. package/src/contract/links.ts +57 -4
  67. package/src/contract/locale.ts +27 -0
  68. package/src/contract/portal.ts +12 -1
  69. package/src/contract/routes.ts +10 -0
  70. package/src/contract/services.ts +18 -16
  71. package/src/email/i18n.ts +174 -0
  72. package/src/email/index.ts +13 -2
  73. package/src/email/locales/ar.json +141 -0
  74. package/src/email/locales/de.json +141 -0
  75. package/src/email/locales/es.json +141 -0
  76. package/src/email/locales/fr.json +141 -0
  77. package/src/email/locales/it.json +141 -0
  78. package/src/email/locales/ja.json +141 -0
  79. package/src/email/locales/pl.json +141 -0
  80. package/src/email/locales/pt-br.json +141 -0
  81. package/src/email/locales/ru.json +141 -0
  82. package/src/email/locales/zh-cn.json +141 -0
  83. package/src/email/messages.ts +200 -0
  84. package/src/email/render.ts +142 -276
  85. package/src/email/samples.ts +115 -0
  86. package/src/email/schema.ts +70 -6
  87. package/src/email/templates/BrandEmail.vue +54 -0
  88. package/src/email/templates/DocumentBlocked.vue +45 -0
  89. package/src/email/templates/DocumentInvitation.vue +24 -0
  90. package/src/email/templates/DocumentReport.vue +32 -0
  91. package/src/email/templates/DocumentReportDecided.vue +36 -0
  92. package/src/email/templates/DocumentReportReceived.vue +18 -0
  93. package/src/email/templates/DocumentRestored.vue +24 -0
  94. package/src/email/templates/EmailChangeRequested.vue +24 -0
  95. package/src/email/templates/EmailRoot.vue +19 -0
  96. package/src/email/templates/EmailText.vue +9 -0
  97. package/src/email/templates/EmailVerification.vue +38 -0
  98. package/src/email/templates/EnrollmentNotification.vue +24 -0
  99. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  100. package/src/email/templates/NewSignIn.vue +37 -0
  101. package/src/email/templates/PasswordChanged.vue +22 -0
  102. package/src/email/templates/PasswordReset.vue +23 -0
  103. package/src/email/templates/StorageLimitReached.vue +28 -0
  104. package/src/email/templates/TwoStepChanged.vue +32 -0
  105. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  106. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  107. package/src/email/templates/brand.ts +9 -61
  108. package/src/email/templates/localization.ts +17 -0
  109. package/src/errors/index.ts +6 -0
  110. package/src/global.d.ts +7 -0
  111. package/src/runtime/cloudflare/relay/index.ts +7 -1
  112. package/src/runtime/cloudflare/tsconfig.json +2 -1
  113. package/src/runtime/cloudflare/worker.ts +8 -1
  114. package/src/runtime/node/cleanup.ts +5 -1
  115. package/src/runtime/node/email/transport.ts +13 -10
  116. package/src/runtime/node/main.ts +1 -1
  117. package/src/runtime/node/server.ts +12 -2
  118. package/src/runtime/node/services/main.ts +1 -1
  119. package/src/runtime/posthog/errors.ts +2 -1
  120. package/src/runtime/s3/objects.ts +17 -0
  121. package/src/runtime/site/community.ts +101 -0
  122. package/src/runtime/site/server.ts +17 -1
  123. package/src/server/account/deletion.ts +2 -0
  124. package/src/server/account/routes.ts +271 -240
  125. package/src/server/account/tokens.ts +57 -0
  126. package/src/server/api/router.ts +23 -0
  127. package/src/server/app/checks.ts +84 -0
  128. package/src/server/app/editors.ts +20 -0
  129. package/src/server/app/index.ts +128 -0
  130. package/src/server/app/indexing.ts +40 -0
  131. package/src/server/app/limiters.ts +53 -0
  132. package/src/server/app/routes.ts +114 -0
  133. package/src/server/app/services.ts +185 -0
  134. package/src/server/auth/access-tokens.ts +62 -0
  135. package/src/server/auth/adapter.ts +21 -1
  136. package/src/server/auth/email.ts +4 -1
  137. package/src/server/auth/enrollment.ts +116 -0
  138. package/src/server/auth/factory.ts +88 -131
  139. package/src/server/auth/logger.ts +23 -0
  140. package/src/server/auth/mfa-assurance.ts +51 -0
  141. package/src/server/auth/passwords.ts +43 -0
  142. package/src/server/auth/session.ts +2 -0
  143. package/src/server/billing/index.ts +6 -0
  144. package/src/server/billing/routes.ts +27 -0
  145. package/src/server/billing/tokens.ts +37 -0
  146. package/src/server/cleanup/configured.ts +16 -3
  147. package/src/server/cleanup/worker.ts +10 -1
  148. package/src/server/collaboration/relay/hub.ts +25 -142
  149. package/src/server/collaboration/relay/room.ts +154 -0
  150. package/src/server/collaboration/service.ts +21 -2
  151. package/src/server/community/index.ts +2 -0
  152. package/src/server/community/routes.ts +93 -0
  153. package/src/server/community/service.ts +134 -0
  154. package/src/server/config/deployment.ts +17 -5
  155. package/src/server/config/index.ts +1 -1
  156. package/src/server/config/public.ts +7 -1
  157. package/src/server/config/schema.ts +40 -292
  158. package/src/server/config/toml/schema.ts +307 -0
  159. package/src/server/db/index.ts +1 -0
  160. package/src/server/db/migrate.ts +13 -1
  161. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  162. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  163. package/src/server/db/migrations/011_account_ids.ts +30 -0
  164. package/src/server/db/migrations/012_email_locales.ts +34 -0
  165. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  166. package/src/server/db/migrations/014_report_replies.ts +28 -0
  167. package/src/server/db/migrations/schema.ts +26 -1
  168. package/src/server/db/tables.ts +30 -1
  169. package/src/server/db/users.ts +22 -0
  170. package/src/server/documents/index.ts +1 -1
  171. package/src/server/documents/limits.ts +7 -1
  172. package/src/server/documents/service.ts +12 -402
  173. package/src/server/documents/uploads.ts +450 -0
  174. package/src/server/documents/versions/service.ts +81 -24
  175. package/src/server/email/invitations.ts +1 -0
  176. package/src/server/email/service.ts +31 -4
  177. package/src/server/email/types.ts +12 -0
  178. package/src/server/errors/index.ts +1 -9
  179. package/src/server/index.ts +12 -5
  180. package/src/server/invitations/types.ts +5 -1
  181. package/src/server/objects/types.ts +5 -0
  182. package/src/server/policy/configured.ts +9 -3
  183. package/src/server/policy/database.ts +13 -2
  184. package/src/server/policy/policy.ts +39 -12
  185. package/src/server/policy/service.ts +71 -52
  186. package/src/server/policy/storage.ts +33 -0
  187. package/src/server/quota/index.ts +6 -0
  188. package/src/server/quota/notices.ts +121 -0
  189. package/src/server/quota/storage.ts +5 -0
  190. package/src/server/rate-limit/middleware.ts +4 -0
  191. package/src/server/reports/index.ts +1 -0
  192. package/src/server/reports/replies.ts +55 -0
  193. package/src/server/reports/routes.ts +3 -1
  194. package/src/server/reports/service.ts +24 -2
  195. package/src/server/sharing/capabilities/service.ts +2 -3
  196. package/src/server/sharing/invitations/service.ts +14 -4
  197. package/src/server/validation.ts +3 -0
  198. package/src/server/workspaces/members.ts +7 -19
  199. package/src/services/app.ts +1 -3
  200. package/src/services/config.ts +1 -0
  201. package/src/services/usage.ts +6 -14
  202. package/src/email/templates/document-invitation.ts +0 -35
  203. package/src/email/templates/enrollment.ts +0 -27
  204. package/src/email/templates/layout.ts +0 -18
  205. package/src/server/app.ts +0 -453
  206. /package/src/{server/errors → errors}/posthog.ts +0 -0
package/dist/client.js CHANGED
@@ -1,12 +1,54 @@
1
- import { isValid } from "js-base64";
2
1
  import * as v from "valibot";
2
+ import { isValid } from "js-base64";
3
3
  import { zipObject } from "es-toolkit";
4
- import { joinURL, withQuery, withoutFragment } from "ufo";
4
+ import { joinURL, withQuery, withoutFragment, withoutTrailingSlash } from "ufo";
5
5
  import { hc } from "hono/client";
6
6
  import { pickBy } from "es-toolkit/object";
7
7
  import { passkeyClient } from "@better-auth/passkey/client";
8
8
  import { createAuthClient } from "better-auth/client";
9
9
  import { deviceAuthorizationClient, twoFactorClient } from "better-auth/client/plugins";
10
+ //#region src/client/response.ts
11
+ const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
12
+ var CloudAPIError = class extends Error {
13
+ status;
14
+ code;
15
+ name = "CloudAPIError";
16
+ constructor(message, status, code) {
17
+ super(message);
18
+ this.status = status;
19
+ this.code = code;
20
+ }
21
+ };
22
+ async function responseBody(response, onDiagnostic) {
23
+ if (response.ok) return response.status === 204 ? null : response.json();
24
+ let code;
25
+ try {
26
+ const body = v.safeParse(cloudErrorResponseSchema, await response.json());
27
+ if (body.success) code = body.output.error.code;
28
+ } catch (error) {
29
+ onDiagnostic?.("Cloud API error response was not JSON", error);
30
+ }
31
+ throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
32
+ }
33
+ async function parseResponse(request, schema, onDiagnostic) {
34
+ return v.parse(schema, await responseBody(await request, onDiagnostic));
35
+ }
36
+ /**
37
+ * The JSON a service deployed apart from Cloud answered, parsed with `schema` rather than trusted;
38
+ * a refusal throws what `refused` makes of its status and body.
39
+ */
40
+ async function serviceJSON(response, schema, refused) {
41
+ if (!response.ok) {
42
+ const body = await response.text().catch((failure) => {
43
+ const error = refused(response.status, "");
44
+ error.cause = failure;
45
+ throw error;
46
+ });
47
+ throw refused(response.status, body);
48
+ }
49
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), await response.text());
50
+ }
51
+ //#endregion
10
52
  //#region src/contract/account.ts
11
53
  /**
12
54
  * Where an account stands: it may use the server, waits for an administrator, was refused or had
@@ -98,6 +140,32 @@ const cloudPasskeySchema = v.object({
98
140
  });
99
141
  const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) });
100
142
  v.object({ id: v.string() });
143
+ /**
144
+ * Personal access tokens: an account's own credentials for scripts and CI, sent as
145
+ * `Authorization: Bearer <token>`. A token acts as its account on the document API only; it never
146
+ * changes how the account is reached, makes other tokens, or reaches administration.
147
+ */
148
+ const CLOUD_ACCESS_TOKEN_PREFIX = "opc_";
149
+ const cloudAccessTokenSchema = v.object({
150
+ id: v.string(),
151
+ name: v.string(),
152
+ /** The token's first characters, prefix included, to tell tokens apart; never the whole token. */
153
+ start: v.nullable(v.string()),
154
+ createdAt: v.string(),
155
+ expiresAt: v.nullable(v.string()),
156
+ lastUsedAt: v.nullable(v.string())
157
+ });
158
+ const cloudAccessTokensResponseSchema = v.object({ tokens: v.array(cloudAccessTokenSchema) });
159
+ v.object({
160
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),
161
+ expiresInDays: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(365))
162
+ });
163
+ /** A new token, the only time the whole of it is shown. */
164
+ const cloudAccessTokenCreatedResponseSchema = v.object({
165
+ token: v.pipe(v.string(), v.startsWith(CLOUD_ACCESS_TOKEN_PREFIX)),
166
+ accessToken: cloudAccessTokenSchema
167
+ });
168
+ v.object({ id: v.pipe(v.string(), v.minLength(1)) });
101
169
  const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
102
170
  /** Who an account belongs to, as the portal shows it. */
103
171
  const cloudPersonSchema = v.object({
@@ -202,31 +270,29 @@ const CLOUD_SERVICES_API_PATHS = {
202
270
  usage: "/v1/usage",
203
271
  search: "/v1/search"
204
272
  };
205
- const urlSchema = v.pipe(v.string(), v.url());
206
- const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
273
+ const urlSchema$1 = v.pipe(v.string(), v.url());
274
+ const creditsSchema$1 = v.pipe(v.number(), v.integer(), v.minValue(0));
207
275
  const cloudServicesDiscoverySchema = v.object({
208
- endpoint: urlSchema,
276
+ endpoint: urlSchema$1,
209
277
  contractVersion: v.literal("1")
210
278
  });
211
- const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
212
279
  v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
213
280
  const servicesTokenSchema = v.object({
214
281
  token: v.pipe(v.string(), v.minLength(1)),
215
282
  expiresAt: v.pipe(v.string(), v.isoTimestamp())
216
283
  });
217
284
  v.object({
218
- iss: urlSchema,
285
+ iss: urlSchema$1,
219
286
  aud: v.literal(CLOUD_SERVICES_TOKEN_AUDIENCE),
220
287
  sub: v.pipe(v.string(), v.minLength(1)),
221
288
  workspaceId: v.pipe(v.string(), v.uuid()),
222
289
  /**
223
290
  * 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.
291
+ * workspace they own shares.
226
292
  */
227
- accountId: v.optional(v.pipe(v.string(), v.minLength(1))),
293
+ accountId: v.pipe(v.string(), v.minLength(1)),
228
294
  /** Credits the owner's plan grants each month; `null` when Cloud sets no allowance. */
229
- monthlyCreditAllowance: v.nullable(creditsSchema),
295
+ monthlyCreditAllowance: v.nullable(creditsSchema$1),
230
296
  iat: v.pipe(v.number(), v.integer()),
231
297
  exp: v.pipe(v.number(), v.integer())
232
298
  });
@@ -234,8 +300,8 @@ const chatModelSchema = v.object({
234
300
  id: v.pipe(v.string(), v.minLength(1)),
235
301
  label: v.pipe(v.string(), v.minLength(1)),
236
302
  /** Credits per million input and output tokens. */
237
- creditsPerMillionInputTokens: creditsSchema,
238
- creditsPerMillionOutputTokens: creditsSchema,
303
+ creditsPerMillionInputTokens: creditsSchema$1,
304
+ creditsPerMillionOutputTokens: creditsSchema$1,
239
305
  contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
240
306
  capabilities: v.object({
241
307
  reasoning: v.boolean(),
@@ -244,7 +310,7 @@ const chatModelSchema = v.object({
244
310
  })
245
311
  });
246
312
  /** What one web search costs; a service without search leaves it out of its catalog. */
247
- const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema });
313
+ const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema$1 });
248
314
  const serviceCatalogSchema = v.object({
249
315
  models: v.array(chatModelSchema),
250
316
  defaultModelID: v.pipe(v.string(), v.minLength(1)),
@@ -256,7 +322,7 @@ const creditBucketSchema = v.object({
256
322
  "purchased",
257
323
  "grant"
258
324
  ]),
259
- remaining: creditsSchema,
325
+ remaining: creditsSchema$1,
260
326
  expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
261
327
  });
262
328
  /**
@@ -265,7 +331,7 @@ const creditBucketSchema = v.object({
265
331
  */
266
332
  const creditWalletSchema = v.object({
267
333
  /** Credits left to spend; `null` when the service sets no limit. */
268
- balance: v.nullable(creditsSchema),
334
+ balance: v.nullable(creditsSchema$1),
269
335
  /** Spent first to last. */
270
336
  buckets: v.array(creditBucketSchema)
271
337
  });
@@ -279,7 +345,7 @@ const usageEntrySchema = v.object({
279
345
  ]),
280
346
  modelID: v.nullable(v.string()),
281
347
  userId: v.pipe(v.string(), v.minLength(1)),
282
- credits: creditsSchema
348
+ credits: creditsSchema$1
283
349
  });
284
350
  v.object({
285
351
  query: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(1e3)),
@@ -287,7 +353,7 @@ v.object({
287
353
  });
288
354
  /** One page a search found, with the part of its text that answers the query. */
289
355
  const searchResultSchema = v.object({
290
- url: v.pipe(urlSchema, v.regex(/^https?:\/\//i, "A search result links to an HTTP(S) page")),
356
+ url: v.pipe(urlSchema$1, v.regex(/^https?:\/\//i, "A search result links to an HTTP(S) page")),
291
357
  title: v.string(),
292
358
  publishedAt: v.nullable(v.pipe(v.string(), v.isoTimestamp())),
293
359
  author: v.nullable(v.string()),
@@ -314,6 +380,91 @@ const serviceErrorSchema = v.object({ error: v.object({
314
380
  /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
315
381
  resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
316
382
  }) });
383
+ /**
384
+ * Whether a bearer token may travel to `url`: over HTTPS, or in the clear only to a loopback
385
+ * address, for development. Only literal addresses count, since a name such as `localhost` is
386
+ * whatever the resolver answers. Services and billing tokens act as the account until they expire.
387
+ */
388
+ function sendsTokenSafely(url) {
389
+ const { protocol, hostname } = new URL(url);
390
+ if (protocol === "https:") return true;
391
+ if (protocol !== "http:") return false;
392
+ return hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
393
+ }
394
+ /**
395
+ * The `aud` of the tokens Cloud signs for its billing service, with the services' signing key,
396
+ * whose public keys it publishes at `CLOUD_SERVICES_JWKS_PATH`.
397
+ */
398
+ const CLOUD_BILLING_TOKEN_AUDIENCE = "openpencil-billing";
399
+ const urlSchema = v.pipe(v.string(), v.url());
400
+ const idSchema = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/));
401
+ const centsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
402
+ const bytesSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
403
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
404
+ const cloudBillingDiscoverySchema = v.object({
405
+ endpoint: urlSchema,
406
+ contractVersion: v.literal("1")
407
+ });
408
+ const billingTokenSchema = v.object({
409
+ token: v.pipe(v.string(), v.minLength(1)),
410
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
411
+ });
412
+ v.object({
413
+ iss: urlSchema,
414
+ aud: v.literal(CLOUD_BILLING_TOKEN_AUDIENCE),
415
+ /** The account: the Cloud user whose plan and credits these are. */
416
+ sub: v.pipe(v.string(), v.minLength(1)),
417
+ /** Where the payment provider sends receipts and invoices. */
418
+ email: v.pipe(v.string(), v.email()),
419
+ iat: v.pipe(v.number(), v.integer()),
420
+ exp: v.pipe(v.number(), v.integer())
421
+ });
422
+ /** A plan an account subscribes to, billed every month in US dollars before tax. */
423
+ const billingPlanSchema = v.object({
424
+ id: idSchema,
425
+ name: v.pipe(v.string(), v.minLength(1)),
426
+ monthlyPriceCents: centsSchema,
427
+ storageBytes: bytesSchema,
428
+ monthlyCredits: creditsSchema
429
+ });
430
+ /** Credits an account on a plan buys once, in US dollars before tax. */
431
+ const creditPackSchema = v.object({
432
+ id: idSchema,
433
+ credits: creditsSchema,
434
+ priceCents: centsSchema,
435
+ /** How long the credits last from purchase. */
436
+ validDays: v.pipe(v.number(), v.integer(), v.minValue(1))
437
+ });
438
+ /** What the service sells; an account without a plan has its deployment's free entitlements. */
439
+ const billingCatalogSchema = v.object({
440
+ plans: v.array(billingPlanSchema),
441
+ creditPacks: v.array(creditPackSchema)
442
+ });
443
+ /**
444
+ * The account's subscription as the payment provider holds it, or `null` without one. A
445
+ * `past_due` plan keeps its entitlements while payment is retried.
446
+ */
447
+ const billingAccountSchema = v.object({ subscription: v.nullable(v.object({
448
+ planId: idSchema,
449
+ status: v.picklist(["active", "past_due"]),
450
+ /** When the current period ends: the next charge, or the end of a cancelled plan. */
451
+ currentPeriodEnd: v.pipe(v.string(), v.isoTimestamp()),
452
+ /** Whether the plan ends at `currentPeriodEnd` instead of renewing. */
453
+ cancelsAtPeriodEnd: v.boolean()
454
+ })) });
455
+ v.union([v.object({ planId: idSchema }), v.object({ creditPackId: idSchema })]);
456
+ /** Where to send the person: the payment provider's checkout or account portal. */
457
+ const billingRedirectSchema = v.object({ url: v.pipe(urlSchema, v.regex(/^https:\/\//i, "Billing sends people to an HTTPS page")) });
458
+ const billingErrorCodeSchema = v.picklist([
459
+ "invalid_request",
460
+ "unauthorized",
461
+ "not_allowed",
462
+ "provider_unavailable"
463
+ ]);
464
+ const billingErrorSchema = v.object({ error: v.object({
465
+ code: billingErrorCodeSchema,
466
+ message: v.optional(v.string())
467
+ }) });
317
468
  //#endregion
318
469
  //#region src/contract/documents.ts
319
470
  const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
@@ -505,6 +656,11 @@ const collaborationTicketSchema = v.object({
505
656
  roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
506
657
  principal: collaborationPrincipalSchema,
507
658
  permission: documentPermissionSchema,
659
+ /**
660
+ * Why a peer whose access would let them edit may only view: `storage-limit` when the document's
661
+ * owner holds their whole storage allowance, until they free space or their plan grows.
662
+ */
663
+ readOnly: v.optional(v.picklist(["storage-limit"])),
508
664
  roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
509
665
  expiresAt: v.string(),
510
666
  serverEnforcedWrites: v.boolean(),
@@ -970,6 +1126,12 @@ const workspaceEntitlementsSchema = v.object({
970
1126
  reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
971
1127
  })
972
1128
  });
1129
+ /**
1130
+ * An account's own plan and the storage its workspaces hold together. A workspace reports the
1131
+ * same for its owner, so the two read alike.
1132
+ */
1133
+ const accountEntitlementsSchema = workspaceEntitlementsSchema;
1134
+ const accountEntitlementsResponseSchema = v.object({ entitlements: accountEntitlementsSchema });
973
1135
  const CLOUD_DISCOVERY_PATH = "/.well-known/openpencil";
974
1136
  const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
975
1137
  const cloudAuthenticationSchema = v.object({
@@ -1003,6 +1165,24 @@ const cloudCapabilitiesSchema = v.object({
1003
1165
  });
1004
1166
  /** A released editor version, `major.minor.patch`. */
1005
1167
  const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
1168
+ function editorVersionParts(version) {
1169
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
1170
+ return match ? match.slice(1).map(Number) : null;
1171
+ }
1172
+ /**
1173
+ * Whether `version` is `minimum` or later, comparing `major.minor.patch` numerically; a prerelease
1174
+ * counts as its release. A version that isn't one, on either side, is not at least anything.
1175
+ */
1176
+ function isEditorVersionAtLeast(version, minimum) {
1177
+ const have = editorVersionParts(version);
1178
+ const need = editorVersionParts(minimum);
1179
+ if (!have || !need) return false;
1180
+ for (let index = 0; index < need.length; index++) {
1181
+ const difference = (have[index] ?? 0) - (need[index] ?? 0);
1182
+ if (difference !== 0) return difference > 0;
1183
+ }
1184
+ return true;
1185
+ }
1006
1186
  /**
1007
1187
  * Whether editors offer this server to everyone, and from which editor version on. Only the
1008
1188
  * official server's listing is read: it turns the Cloud entry points on without an editor release,
@@ -1023,6 +1203,22 @@ const cloudLegalDiscoverySchema = v.object({
1023
1203
  abuseEmail: v.optional(v.pipe(v.string(), v.email())),
1024
1204
  minimumAge: v.optional(v.pipe(v.number(), v.integer()))
1025
1205
  });
1206
+ /** A web address a page may link or load: `http` or `https` only, never a script or data URL. */
1207
+ const webURLSchema = v.pipe(v.string(), v.url(), v.check((value) => ["http:", "https:"].includes(new URL(value).protocol)));
1208
+ /**
1209
+ * How a self-hosted server names itself on its public pages: the operator's name and logo in the
1210
+ * bar, and where its people get help. The official server is OpenPencil's own and names none.
1211
+ */
1212
+ const cloudBrandingSchema = v.object({
1213
+ name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
1214
+ logoURL: v.optional(webURLSchema),
1215
+ helpURL: v.optional(webURLSchema)
1216
+ });
1217
+ /**
1218
+ * The server's community gallery: the workspace whose documents anyone may open read-only.
1219
+ * Saving to it publishes, so editors never choose it for anyone and say so when it is chosen.
1220
+ */
1221
+ const cloudCommunityDiscoverySchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
1026
1222
  const cloudDiscoverySchema = v.object({
1027
1223
  protocolVersion: v.literal("1"),
1028
1224
  deployment: cloudDeploymentSchema,
@@ -1033,11 +1229,19 @@ const cloudDiscoverySchema = v.object({
1033
1229
  authentication: cloudAuthenticationSchema,
1034
1230
  capabilities: cloudCapabilitiesSchema,
1035
1231
  listing: v.optional(cloudListingSchema),
1232
+ /**
1233
+ * The oldest editor version the server works with. Older editors ask to be updated instead of
1234
+ * connecting, and the server refuses their requests.
1235
+ */
1236
+ minimumEditorVersion: v.optional(cloudEditorVersionSchema),
1036
1237
  /** The services editors reach with Cloud-signed tokens; absent when the deployment has none. */
1037
1238
  services: v.optional(cloudServicesDiscoverySchema),
1038
1239
  /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
1039
1240
  billing: v.optional(cloudBillingDiscoverySchema),
1040
- legal: v.optional(cloudLegalDiscoverySchema)
1241
+ /** The community gallery; absent when the deployment has none. */
1242
+ community: v.optional(cloudCommunityDiscoverySchema),
1243
+ legal: v.optional(cloudLegalDiscoverySchema),
1244
+ branding: v.optional(cloudBrandingSchema)
1041
1245
  });
1042
1246
  /** The server's own address, where its editor and pages are, from its auth API's. */
1043
1247
  function cloudServerOrigin(discovery) {
@@ -1090,6 +1294,38 @@ const restoredDocumentSchema = v.object({
1090
1294
  version: documentVersionSchema
1091
1295
  });
1092
1296
  //#endregion
1297
+ //#region src/contract/community.ts
1298
+ /** A version of a community document someone named, such as the release it was published for. */
1299
+ const communityVersionSchema = v.object({
1300
+ id: v.pipe(v.string(), v.uuid()),
1301
+ name: v.string(),
1302
+ description: v.nullable(v.string()),
1303
+ createdAt: v.string(),
1304
+ /** Whether the document holds this version now, with nothing changed since it was named. */
1305
+ current: v.boolean()
1306
+ });
1307
+ /**
1308
+ * A document in the deployment's community workspace, which anyone may open read-only: its name,
1309
+ * when it last changed, its thumbnail's path on the server, and its named versions, newest first.
1310
+ */
1311
+ const communityDocumentSchema = v.object({
1312
+ id: v.pipe(v.string(), v.uuid()),
1313
+ name: v.string(),
1314
+ kind: documentKindSchema,
1315
+ updatedAt: v.string(),
1316
+ revisionId: v.pipe(v.string(), v.uuid()),
1317
+ thumbnailPath: v.string(),
1318
+ versions: v.array(communityVersionSchema)
1319
+ });
1320
+ /** The community workspace's documents, most recently changed first. */
1321
+ const communityDocumentsSchema = v.object({ documents: v.array(communityDocumentSchema) });
1322
+ v.object({ version: v.optional(v.pipe(v.string(), v.uuid())) });
1323
+ /** A community document, or one of its named versions, with where to download it. */
1324
+ const communityDownloadSchema = v.object({
1325
+ document: documentDownloadSchema,
1326
+ version: v.nullable(communityVersionSchema)
1327
+ });
1328
+ //#endregion
1093
1329
  //#region src/client/services.ts
1094
1330
  var CloudServiceError = class extends Error {
1095
1331
  status;
@@ -1101,6 +1337,15 @@ var CloudServiceError = class extends Error {
1101
1337
  this.code = code;
1102
1338
  }
1103
1339
  };
1340
+ /** A service endpoint a token would reach in the clear, which no request is sent to. */
1341
+ var CloudServiceInsecureEndpointError = class extends Error {
1342
+ url;
1343
+ name = "CloudServiceInsecureEndpointError";
1344
+ constructor(url) {
1345
+ super("OpenPencil services and billing are reached only over HTTPS");
1346
+ this.url = url;
1347
+ }
1348
+ };
1104
1349
  /** Whether a request can be sent twice: a stream, in `init` or a `Request`, is read by the first. */
1105
1350
  function replayable(input, body) {
1106
1351
  if (input instanceof Request && input.body) return false;
@@ -1121,6 +1366,8 @@ function cloudServicesFetch(tokens, fetch) {
1121
1366
  });
1122
1367
  };
1123
1368
  return async (input, init) => {
1369
+ const url = input instanceof Request ? input.url : input;
1370
+ if (!sendsTokenSafely(url)) throw new CloudServiceInsecureEndpointError(String(url));
1124
1371
  const token = await tokens.token();
1125
1372
  const response = await send(input, init, token);
1126
1373
  if (response.status !== 401) return response;
@@ -1129,33 +1376,71 @@ function cloudServicesFetch(tokens, fetch) {
1129
1376
  return send(input, init, await tokens.token());
1130
1377
  };
1131
1378
  }
1132
- 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);
1379
+ const errorBodySchema$1 = v.pipe(v.string(), v.parseJson(), serviceErrorSchema);
1380
+ function refused$1(status, body) {
1381
+ const error = v.safeParse(errorBodySchema$1, body);
1382
+ return new CloudServiceError(status, error.success ? error.output.error.code : void 0);
1140
1383
  }
1141
1384
  /** The services a Cloud advertises: the model API base URL, catalog, wallet, and search. */
1142
1385
  function createCloudServicesClient(options) {
1143
- const endpoint = options.endpoint.replace(/\/+$/, "");
1386
+ const endpoint = withoutTrailingSlash(options.endpoint);
1144
1387
  const fetch = cloudServicesFetch(options.tokens, options.fetch);
1145
1388
  const { v1 } = hc(endpoint, { fetch });
1146
1389
  return {
1147
1390
  /** The base URL an OpenAI-compatible client sends chat completions below. */
1148
- modelBaseURL: `${endpoint}${CLOUD_SERVICES_API_PATHS.base}`,
1391
+ modelBaseURL: joinURL(endpoint, CLOUD_SERVICES_API_PATHS.base),
1149
1392
  fetch,
1150
1393
  async catalog() {
1151
- return parsed(await v1.catalog.$get(), serviceCatalogSchema);
1394
+ return serviceJSON(await v1.catalog.$get(), serviceCatalogSchema, refused$1);
1152
1395
  },
1153
1396
  async wallet() {
1154
- return parsed(await v1.wallet.$get(), creditWalletSchema);
1397
+ return serviceJSON(await v1.wallet.$get(), creditWalletSchema, refused$1);
1155
1398
  },
1156
1399
  /** A web search, charged to the workspace; only when the catalog lists `search`. */
1157
1400
  async search(input) {
1158
- return parsed(await v1.search.$post({ json: input }), searchResponseSchema);
1401
+ return serviceJSON(await v1.search.$post({ json: input }), searchResponseSchema, refused$1);
1402
+ }
1403
+ };
1404
+ }
1405
+ //#endregion
1406
+ //#region src/client/billing.ts
1407
+ var CloudBillingError = class extends Error {
1408
+ status;
1409
+ code;
1410
+ name = "CloudBillingError";
1411
+ constructor(status, code) {
1412
+ super(`OpenPencil billing request failed with HTTP ${status}`);
1413
+ this.status = status;
1414
+ this.code = code;
1415
+ }
1416
+ };
1417
+ const errorBodySchema = v.pipe(v.string(), v.parseJson(), billingErrorSchema);
1418
+ function refused(status, body) {
1419
+ const error = v.safeParse(errorBodySchema, body);
1420
+ return new CloudBillingError(status, error.success ? error.output.error.code : void 0);
1421
+ }
1422
+ /**
1423
+ * The billing a Cloud advertises: what it sells, the account's subscription, and where to buy or
1424
+ * manage it. Checkout and the portal answer with the payment provider's page to open, so a token
1425
+ * never travels in a URL.
1426
+ */
1427
+ function createCloudBillingClient(options) {
1428
+ const endpoint = withoutTrailingSlash(options.endpoint);
1429
+ const { v1 } = hc(endpoint, { fetch: cloudServicesFetch(options.tokens, options.fetch) });
1430
+ return {
1431
+ async catalog() {
1432
+ return serviceJSON(await v1.catalog.$get(), billingCatalogSchema, refused);
1433
+ },
1434
+ async account() {
1435
+ return serviceJSON(await v1.account.$get(), billingAccountSchema, refused);
1436
+ },
1437
+ /** The checkout page that buys `request` for the account. */
1438
+ async checkout(request) {
1439
+ return (await serviceJSON(await v1.checkout.$post({ json: request }), billingRedirectSchema, refused)).url;
1440
+ },
1441
+ /** The page where the account cancels, changes its card, and reads its invoices. */
1442
+ async portal() {
1443
+ return (await serviceJSON(await v1.portal.$post(), billingRedirectSchema, refused)).url;
1159
1444
  }
1160
1445
  };
1161
1446
  }
@@ -1188,31 +1473,107 @@ function cloudRedirectPath(value, fallback = "/app") {
1188
1473
  return `${url.pathname}${url.search}${url.hash}`;
1189
1474
  }
1190
1475
  //#endregion
1191
- //#region src/client/response.ts
1192
- const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
1193
- var CloudAPIError = class extends Error {
1194
- status;
1195
- code;
1196
- name = "CloudAPIError";
1197
- constructor(message, status, code) {
1198
- super(message);
1199
- this.status = status;
1200
- this.code = code;
1201
- }
1202
- };
1203
- async function responseBody(response, onDiagnostic) {
1204
- if (response.ok) return response.status === 204 ? null : response.json();
1205
- let code;
1206
- 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);
1211
- }
1212
- throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
1476
+ //#region src/client/community.ts
1477
+ /** The server’s community gallery, which anyone may open without signing in. */
1478
+ function createCommunityRequests(publicClient, onDiagnostic) {
1479
+ return {
1480
+ /** The gallery's documents, most recently changed first. */
1481
+ async listCommunityDocuments() {
1482
+ return parseResponse(publicClient.community.$get(), communityDocumentsSchema, onDiagnostic);
1483
+ },
1484
+ /**
1485
+ * A document of the server's community gallery as it is now, or one of its named versions,
1486
+ * which anyone may open without signing in.
1487
+ */
1488
+ async getCommunityDocument(documentId, versionId = null) {
1489
+ return parseResponse(publicClient.community[":documentId"].document.$get({
1490
+ param: { documentId },
1491
+ query: versionId ? { version: versionId } : {}
1492
+ }), communityDownloadSchema, onDiagnostic);
1493
+ }
1494
+ };
1213
1495
  }
1214
- async function parseResponse(request, schema, onDiagnostic) {
1215
- return v.parse(schema, await responseBody(await request, onDiagnostic));
1496
+ //#endregion
1497
+ //#region src/client/schema.ts
1498
+ /** What the API answers with one document, as creating, restoring, or duplicating one does. */
1499
+ const documentResponseSchema = v.object({ document: documentSummarySchema });
1500
+ /** What the API answers with a ticket into a document's live room. */
1501
+ const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1502
+ //#endregion
1503
+ //#region src/client/documents.ts
1504
+ const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
1505
+ const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
1506
+ const downloadResponseSchema = v.object({ document: documentDownloadSchema });
1507
+ const accessResponseSchema = v.object({ access: documentAccessSchema });
1508
+ const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
1509
+ const uploadResponseSchema = v.object({
1510
+ id: v.pipe(v.string(), v.uuid()),
1511
+ upload: objectUploadSchema
1512
+ });
1513
+ /** Documents: listing and creating them, Trash, downloads, uploads, and collaboration tickets. */
1514
+ function createDocumentRequests(client, onDiagnostic) {
1515
+ return {
1516
+ async getUserProfile(documentId, userId) {
1517
+ return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
1518
+ documentId,
1519
+ userId
1520
+ } }), userLookupResponseSchema, onDiagnostic)).user;
1521
+ },
1522
+ /** Documents shared with the person directly, outside their workspaces. */
1523
+ async listSharedDocuments() {
1524
+ return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, onDiagnostic)).documents;
1525
+ },
1526
+ async listDocuments(workspaceId) {
1527
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, onDiagnostic)).documents;
1528
+ },
1529
+ async createDocument(workspaceId, input) {
1530
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
1531
+ param: { workspaceId },
1532
+ json: {
1533
+ ...input,
1534
+ kind: input.kind ?? "design"
1535
+ }
1536
+ }), documentResponseSchema, onDiagnostic)).document;
1537
+ },
1538
+ /** Documents in Trash the person may restore, across their workspaces, newest first. */
1539
+ async listTrash() {
1540
+ return (await parseResponse(client.trash.$get(), trashSchema, onDiagnostic)).documents;
1541
+ },
1542
+ async restoreDocument(documentId) {
1543
+ await responseBody(await client.trash[":documentId"].restore.$post({ param: { documentId } }), onDiagnostic);
1544
+ },
1545
+ /** Deletes a document in Trash for good. */
1546
+ async purgeDocument(documentId) {
1547
+ await responseBody(await client.trash[":documentId"].$delete({ param: { documentId } }), onDiagnostic);
1548
+ },
1549
+ async deleteDocument(documentId) {
1550
+ await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), onDiagnostic);
1551
+ },
1552
+ async getDocument(documentId) {
1553
+ return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, onDiagnostic)).document;
1554
+ },
1555
+ async getDocumentAccess(documentId) {
1556
+ return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, onDiagnostic)).access;
1557
+ },
1558
+ async getCollaborationTicket(documentId) {
1559
+ return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, onDiagnostic)).ticket;
1560
+ },
1561
+ async createUpload(documentId, input) {
1562
+ return parseResponse(client.documents[":documentId"].uploads.$post({
1563
+ param: { documentId },
1564
+ json: input
1565
+ }), uploadResponseSchema, onDiagnostic);
1566
+ },
1567
+ async commitUpload(uploadId, input) {
1568
+ return (await parseResponse(client.uploads[":uploadId"].commit.$post({
1569
+ param: { uploadId },
1570
+ json: {
1571
+ ...input,
1572
+ images: input.images ?? []
1573
+ }
1574
+ }), documentResponseSchema, onDiagnostic)).document;
1575
+ }
1576
+ };
1216
1577
  }
1217
1578
  //#endregion
1218
1579
  //#region src/client/images.ts
@@ -1255,201 +1616,39 @@ function createImageRequests(client, publicClient, onDiagnostic) {
1255
1616
  };
1256
1617
  }
1257
1618
  //#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) {
1619
+ //#region src/client/sharing.ts
1620
+ const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) });
1621
+ const shareResponseSchema = v.object({ share: documentShareSchema });
1622
+ const shareCapabilityResponseSchema = v.object({
1623
+ share: documentShareSchema,
1624
+ secret: v.string(),
1625
+ path: v.string()
1626
+ });
1627
+ const grantsResponseSchema = v.object({ grants: v.array(documentGrantSchema) });
1628
+ const grantResponseSchema = v.object({ grant: documentGrantSchema });
1629
+ const acceptedResponseSchema = v.object({ accepted: acceptedInvitationSchema });
1630
+ const invitationPreviewResponseSchema = v.object({ invitation: invitationPreviewSchema });
1631
+ const invitationsResponseSchema = v.object({ invitations: v.array(documentInvitationSchema) });
1632
+ const invitationCapabilityResponseSchema = v.object({
1633
+ invitation: documentInvitationSchema,
1634
+ token: v.string()
1635
+ });
1636
+ const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema });
1637
+ const sharedDocumentResponseSchema = v.object({
1638
+ resolution: resolvedDocumentShareSchema,
1639
+ document: documentDownloadSchema
1640
+ });
1641
+ /** Sharing a document: its links, grants, and invitations, and opening what someone shared. */
1642
+ function createSharingRequests(client, publicClient, onDiagnostic) {
1264
1643
  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 });
1335
- const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) });
1336
- const shareResponseSchema = v.object({ share: documentShareSchema });
1337
- const shareCapabilityResponseSchema = v.object({
1338
- share: documentShareSchema,
1339
- secret: v.string(),
1340
- path: v.string()
1341
- });
1342
- const grantsResponseSchema = v.object({ grants: v.array(documentGrantSchema) });
1343
- const grantResponseSchema = v.object({ grant: documentGrantSchema });
1344
- const acceptedResponseSchema = v.object({ accepted: acceptedInvitationSchema });
1345
- const invitationPreviewResponseSchema = v.object({ invitation: invitationPreviewSchema });
1346
- const invitationsResponseSchema = v.object({ invitations: v.array(documentInvitationSchema) });
1347
- const invitationCapabilityResponseSchema = v.object({
1348
- invitation: documentInvitationSchema,
1349
- token: v.string()
1350
- });
1351
- const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1352
- const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema });
1353
- const sharedDocumentResponseSchema = v.object({
1354
- resolution: resolvedDocumentShareSchema,
1355
- document: documentDownloadSchema
1356
- });
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
- });
1391
- 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
- async listDocumentShares(documentId) {
1446
- return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, options.onDiagnostic)).shares;
1644
+ async listDocumentShares(documentId) {
1645
+ return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, onDiagnostic)).shares;
1447
1646
  },
1448
1647
  async createDocumentShare(documentId, input) {
1449
1648
  return parseResponse(client.documents[":documentId"].shares.$post({
1450
1649
  param: { documentId },
1451
1650
  json: input
1452
- }), shareCapabilityResponseSchema, options.onDiagnostic);
1651
+ }), shareCapabilityResponseSchema, onDiagnostic);
1453
1652
  },
1454
1653
  async updateDocumentShare(documentId, shareId, input) {
1455
1654
  return (await parseResponse(client.documents[":documentId"].shares[":shareId"].$patch({
@@ -1458,22 +1657,22 @@ function createCloudAPIClient(baseURL, options = {}) {
1458
1657
  shareId
1459
1658
  },
1460
1659
  json: input
1461
- }), shareResponseSchema, options.onDiagnostic)).share;
1660
+ }), shareResponseSchema, onDiagnostic)).share;
1462
1661
  },
1463
1662
  async rotateDocumentShare(documentId, shareId) {
1464
1663
  return parseResponse(client.documents[":documentId"].shares[":shareId"].rotate.$post({ param: {
1465
1664
  documentId,
1466
1665
  shareId
1467
- } }), shareCapabilityResponseSchema, options.onDiagnostic);
1666
+ } }), shareCapabilityResponseSchema, onDiagnostic);
1468
1667
  },
1469
1668
  async revokeDocumentShare(documentId, shareId) {
1470
1669
  await responseBody(await client.documents[":documentId"].shares[":shareId"].$delete({ param: {
1471
1670
  documentId,
1472
1671
  shareId
1473
- } }), options.onDiagnostic);
1672
+ } }), onDiagnostic);
1474
1673
  },
1475
1674
  async listDocumentGrants(documentId) {
1476
- return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, options.onDiagnostic)).grants;
1675
+ return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, onDiagnostic)).grants;
1477
1676
  },
1478
1677
  async putDocumentGrant(documentId, userId, input) {
1479
1678
  return (await parseResponse(client.documents[":documentId"].grants[":userId"].$put({
@@ -1482,103 +1681,92 @@ function createCloudAPIClient(baseURL, options = {}) {
1482
1681
  userId
1483
1682
  },
1484
1683
  json: input
1485
- }), grantResponseSchema, options.onDiagnostic)).grant;
1684
+ }), grantResponseSchema, onDiagnostic)).grant;
1486
1685
  },
1487
1686
  async revokeDocumentGrant(documentId, userId) {
1488
1687
  await responseBody(await client.documents[":documentId"].grants[":userId"].$delete({ param: {
1489
1688
  documentId,
1490
1689
  userId
1491
- } }), options.onDiagnostic);
1690
+ } }), onDiagnostic);
1492
1691
  },
1493
1692
  async listDocumentInvitations(documentId) {
1494
- return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, options.onDiagnostic)).invitations;
1693
+ return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, onDiagnostic)).invitations;
1495
1694
  },
1496
1695
  async createDocumentInvitation(documentId, input) {
1497
1696
  return parseResponse(client.documents[":documentId"].invitations.$post({
1498
1697
  param: { documentId },
1499
1698
  json: input
1500
- }), invitationCapabilityResponseSchema, options.onDiagnostic);
1699
+ }), invitationCapabilityResponseSchema, onDiagnostic);
1501
1700
  },
1502
1701
  async createInvitationContinuation(input) {
1503
- return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, options.onDiagnostic);
1702
+ return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, onDiagnostic);
1504
1703
  },
1505
1704
  async consumeInvitationContinuation(id) {
1506
- return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, options.onDiagnostic);
1705
+ return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, onDiagnostic);
1507
1706
  },
1508
1707
  async previewInvitation(invitationId, input) {
1509
1708
  return (await parseResponse(publicClient.invitations[":invitationId"].preview.$post({
1510
1709
  param: { invitationId },
1511
1710
  json: input
1512
- }), invitationPreviewResponseSchema, options.onDiagnostic)).invitation;
1711
+ }), invitationPreviewResponseSchema, onDiagnostic)).invitation;
1513
1712
  },
1514
1713
  /** Accepts a document or workspace invitation, and says which it was. */
1515
1714
  async acceptInvitation(invitationId, input) {
1516
1715
  return (await parseResponse(client.invitations[":invitationId"].accept.$post({
1517
1716
  param: { invitationId },
1518
1717
  json: input
1519
- }), acceptedResponseSchema, options.onDiagnostic)).accepted;
1718
+ }), acceptedResponseSchema, onDiagnostic)).accepted;
1520
1719
  },
1521
1720
  async revokeDocumentInvitation(documentId, invitationId) {
1522
1721
  await responseBody(await client.documents[":documentId"].invitations[":invitationId"].$delete({ param: {
1523
1722
  documentId,
1524
1723
  invitationId
1525
- } }), options.onDiagnostic);
1724
+ } }), onDiagnostic);
1526
1725
  },
1527
1726
  /** Reports the document a share link opens to the server's administrators. */
1528
1727
  async fileDocumentReport(shareId, input) {
1529
1728
  await parseResponse(publicClient.shares[":shareId"].reports.$post({
1530
1729
  param: { shareId },
1531
1730
  json: input
1532
- }), fileDocumentReportResponseSchema, options.onDiagnostic);
1731
+ }), fileDocumentReportResponseSchema, onDiagnostic);
1533
1732
  },
1534
1733
  async resolveDocumentShare(shareId, input) {
1535
1734
  return (await parseResponse(publicClient.shares[":shareId"].resolve.$post({
1536
1735
  param: { shareId },
1537
1736
  json: input
1538
- }), resolvedShareResponseSchema, options.onDiagnostic)).resolution;
1737
+ }), resolvedShareResponseSchema, onDiagnostic)).resolution;
1539
1738
  },
1540
1739
  async getSharedDocument(shareId, input) {
1541
1740
  return parseResponse(publicClient.shares[":shareId"].document.$post({
1542
1741
  param: { shareId },
1543
1742
  json: input
1544
- }), sharedDocumentResponseSchema, options.onDiagnostic);
1743
+ }), sharedDocumentResponseSchema, onDiagnostic);
1545
1744
  },
1546
1745
  async getSharedCollaborationTicket(shareId, input) {
1547
1746
  return (await parseResponse(publicClient.shares[":shareId"]["collaboration-ticket"].$post({
1548
1747
  param: { shareId },
1549
1748
  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;
1554
- },
1555
- async createUpload(documentId, input) {
1556
- return parseResponse(client.documents[":documentId"].uploads.$post({
1557
- param: { documentId },
1558
- json: input
1559
- }), uploadResponseSchema, options.onDiagnostic);
1560
- },
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;
1569
- },
1749
+ }), collaborationTicketResponseSchema, onDiagnostic)).ticket;
1750
+ }
1751
+ };
1752
+ }
1753
+ //#endregion
1754
+ //#region src/client/versions.ts
1755
+ /** A document’s version history: listing, naming, opening, restoring, and duplicating. */
1756
+ function createVersionRequests(client, onDiagnostic) {
1757
+ return {
1570
1758
  /** A page of the document's version history, newest first. */
1571
1759
  async listDocumentVersions(documentId, page = {}) {
1572
1760
  return parseResponse(client.documents[":documentId"].versions.$get({
1573
1761
  param: { documentId },
1574
1762
  query: pickBy(page, (value) => value !== void 0)
1575
- }), documentVersionsSchema, options.onDiagnostic);
1763
+ }), documentVersionsSchema, onDiagnostic);
1576
1764
  },
1577
1765
  async saveDocumentVersion(documentId, input) {
1578
1766
  return (await parseResponse(client.documents[":documentId"].versions.$post({
1579
1767
  param: { documentId },
1580
1768
  json: input
1581
- }), documentVersionResponseSchema, options.onDiagnostic)).version;
1769
+ }), documentVersionResponseSchema, onDiagnostic)).version;
1582
1770
  },
1583
1771
  async updateDocumentVersion(documentId, versionId, input) {
1584
1772
  return (await parseResponse(client.documents[":documentId"].versions[":versionId"].$patch({
@@ -1587,19 +1775,19 @@ function createCloudAPIClient(baseURL, options = {}) {
1587
1775
  versionId
1588
1776
  },
1589
1777
  json: input
1590
- }), documentVersionResponseSchema, options.onDiagnostic)).version;
1778
+ }), documentVersionResponseSchema, onDiagnostic)).version;
1591
1779
  },
1592
1780
  async getDocumentVersion(documentId, versionId) {
1593
1781
  return parseResponse(client.documents[":documentId"].versions[":versionId"].$get({ param: {
1594
1782
  documentId,
1595
1783
  versionId
1596
- } }), documentVersionDownloadSchema, options.onDiagnostic);
1784
+ } }), documentVersionDownloadSchema, onDiagnostic);
1597
1785
  },
1598
1786
  async restoreDocumentVersion(documentId, versionId) {
1599
1787
  return parseResponse(client.documents[":documentId"].versions[":versionId"].restore.$post({ param: {
1600
1788
  documentId,
1601
1789
  versionId
1602
- } }), restoredDocumentSchema, options.onDiagnostic);
1790
+ } }), restoredDocumentSchema, onDiagnostic);
1603
1791
  },
1604
1792
  async duplicateDocumentVersion(documentId, versionId, input) {
1605
1793
  return (await parseResponse(client.documents[":documentId"].versions[":versionId"].duplicate.$post({
@@ -1608,11 +1796,139 @@ function createCloudAPIClient(baseURL, options = {}) {
1608
1796
  versionId
1609
1797
  },
1610
1798
  json: input
1611
- }), documentResponseSchema, options.onDiagnostic)).document;
1799
+ }), documentResponseSchema, onDiagnostic)).document;
1800
+ }
1801
+ };
1802
+ }
1803
+ //#endregion
1804
+ //#region src/client/workspaces.ts
1805
+ const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
1806
+ const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
1807
+ const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
1808
+ /** Workspaces, their members, invitations, entitlements, and storage use. */
1809
+ function createWorkspaceRequests(client, onDiagnostic) {
1810
+ return {
1811
+ async listWorkspaces() {
1812
+ return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
1813
+ },
1814
+ async createWorkspace(name) {
1815
+ return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
1816
+ },
1817
+ async renameWorkspace(workspaceId, name) {
1818
+ return (await parseResponse(client.workspaces[":workspaceId"].$patch({
1819
+ param: { workspaceId },
1820
+ json: { name }
1821
+ }), workspaceResponseSchema, onDiagnostic)).workspace;
1822
+ },
1823
+ /** Deletes an empty workspace; the server refuses one that still holds documents. */
1824
+ async deleteWorkspace(workspaceId) {
1825
+ await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1826
+ },
1827
+ /** The workspace's members, and for administrators its pending invitations. */
1828
+ async listWorkspaceMembers(workspaceId) {
1829
+ return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1830
+ },
1831
+ async inviteToWorkspace(workspaceId, input) {
1832
+ return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
1833
+ param: { workspaceId },
1834
+ json: input
1835
+ }), createdWorkspaceInvitationSchema, onDiagnostic);
1836
+ },
1837
+ /** Sends a waiting invitation again; its earlier link stops working. */
1838
+ async resendWorkspaceInvitation(workspaceId, invitationId) {
1839
+ return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
1840
+ workspaceId,
1841
+ invitationId
1842
+ } }), createdWorkspaceInvitationSchema, onDiagnostic);
1843
+ },
1844
+ async revokeWorkspaceInvitation(workspaceId, invitationId) {
1845
+ await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
1846
+ workspaceId,
1847
+ invitationId
1848
+ } }), onDiagnostic);
1849
+ },
1850
+ async updateWorkspaceMember(workspaceId, userId, role) {
1851
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1852
+ param: {
1853
+ workspaceId,
1854
+ userId
1855
+ },
1856
+ json: { role }
1857
+ }), onDiagnostic);
1858
+ },
1859
+ /** Removes someone from the workspace; with the person's own id, leaves it. */
1860
+ async removeWorkspaceMember(workspaceId, userId) {
1861
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
1862
+ workspaceId,
1863
+ userId
1864
+ } }), onDiagnostic);
1865
+ },
1866
+ async getWorkspaceEntitlements(workspaceId) {
1867
+ return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1868
+ },
1869
+ async getUsage(workspaceId) {
1870
+ return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
1612
1871
  }
1613
1872
  };
1614
1873
  }
1615
1874
  //#endregion
1875
+ //#region src/client/api.ts
1876
+ function apiURL(baseURL) {
1877
+ const url = new URL(baseURL);
1878
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("OpenPencil Cloud API URL must use HTTP or HTTPS", 0);
1879
+ url.pathname = url.pathname.replace(/\/$/, "");
1880
+ url.search = "";
1881
+ url.hash = "";
1882
+ return url.href;
1883
+ }
1884
+ function createCloudAPIClient(baseURL, options = {}) {
1885
+ const headers = {
1886
+ "Content-Type": "application/json",
1887
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1888
+ };
1889
+ const client = hc(apiURL(baseURL), {
1890
+ fetch: options.fetch,
1891
+ init: {
1892
+ credentials: "include",
1893
+ signal: options.signal,
1894
+ headers
1895
+ }
1896
+ });
1897
+ const publicClient = hc(apiURL(baseURL), {
1898
+ fetch: options.fetch,
1899
+ init: {
1900
+ credentials: "include",
1901
+ signal: options.signal,
1902
+ headers
1903
+ }
1904
+ });
1905
+ return {
1906
+ async getSession() {
1907
+ const response = await client.session.$get();
1908
+ if (response.status === 401) return null;
1909
+ return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
1910
+ },
1911
+ /** A short-lived token for the deployment's services, on the workspace's behalf. */
1912
+ async requestServicesToken(workspaceId) {
1913
+ return parseResponse(client.services.token.$post({ json: { workspaceId } }), servicesTokenSchema, options.onDiagnostic);
1914
+ },
1915
+ /** A short-lived token for the deployment's billing, for the signed-in person's own account. */
1916
+ async requestBillingToken() {
1917
+ return parseResponse(client.billing.token.$post(), billingTokenSchema, options.onDiagnostic);
1918
+ },
1919
+ /** The signed-in account's plan, and the storage its workspaces hold together. */
1920
+ async getAccountEntitlements() {
1921
+ return (await parseResponse(client.account.entitlements.$get(), accountEntitlementsResponseSchema, options.onDiagnostic)).entitlements;
1922
+ },
1923
+ ...createWorkspaceRequests(client, options.onDiagnostic),
1924
+ ...createImageRequests(client, publicClient, options.onDiagnostic),
1925
+ ...createDocumentRequests(client, options.onDiagnostic),
1926
+ ...createVersionRequests(client, options.onDiagnostic),
1927
+ ...createSharingRequests(client, publicClient, options.onDiagnostic),
1928
+ ...createCommunityRequests(publicClient, options.onDiagnostic)
1929
+ };
1930
+ }
1931
+ //#endregion
1616
1932
  //#region src/client/auth/failure.ts
1617
1933
  /** The failure a Better Auth error stands for; anything unknown can only be retried later. */
1618
1934
  function cloudAuthFailure(error) {
@@ -1733,12 +2049,16 @@ async function signInToCloudWithEmail(discovery, input, options = {}) {
1733
2049
  }
1734
2050
  };
1735
2051
  }
1736
- /** Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed. */
2052
+ /**
2053
+ * Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed,
2054
+ * written in `locale`, the app's language.
2055
+ */
1737
2056
  async function signUpToCloudWithEmail(discovery, input, options = {}) {
1738
2057
  const result = await createCloudAuthClient(discovery, options).signUp.email({
1739
2058
  name: input.name,
1740
2059
  email: input.email,
1741
2060
  password: input.password,
2061
+ locale: input.locale,
1742
2062
  callbackURL: input.verifiedURL
1743
2063
  }).catch(() => null);
1744
2064
  if (!result) return cloudAuthFailure(null);
@@ -1881,14 +2201,24 @@ function discoveryURL(serverURL) {
1881
2201
  url.hash = "";
1882
2202
  return url;
1883
2203
  }
1884
- function parseDiscoveryBody(text) {
2204
+ /** Which side is behind when the server speaks another protocol, or null when it doesn't. */
2205
+ function protocolMismatch(version) {
2206
+ if (version === "1") return null;
2207
+ return Number(version) > 1 ? "editor-outdated" : "server-outdated";
2208
+ }
2209
+ function parseDiscoveryBody(text, editorVersion) {
1885
2210
  const body = v.safeParse(discoveryBodySchema, text);
1886
2211
  if (!body.success) throw new CloudClientError("OpenPencil server discovery is not JSON", body.issues, "not-cloud");
1887
2212
  const discovery = v.safeParse(cloudDiscoverySchema, body.output);
1888
- if (discovery.success) return discovery.output;
2213
+ if (discovery.success) {
2214
+ const minimum = discovery.output.minimumEditorVersion;
2215
+ if (minimum && editorVersion && !isEditorVersionAtLeast(editorVersion, minimum)) throw new CloudClientError(`OpenPencil server needs editor ${minimum} or later`, void 0, "editor-outdated");
2216
+ return discovery.output;
2217
+ }
1889
2218
  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");
2219
+ const version = protocol.success ? protocol.output.protocolVersion : null;
2220
+ const mismatch = version === null ? null : protocolMismatch(version);
2221
+ throw new CloudClientError(mismatch ? `OpenPencil server speaks protocol ${version}` : "OpenPencil server discovery is invalid", discovery.issues, mismatch ?? "not-cloud");
1892
2222
  }
1893
2223
  async function discoverCloud(serverURL, options = {}) {
1894
2224
  const fetchImplementation = options.fetch ?? globalThis.fetch;
@@ -1901,7 +2231,7 @@ async function discoverCloud(serverURL, options = {}) {
1901
2231
  signal
1902
2232
  });
1903
2233
  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());
2234
+ return parseDiscoveryBody(await response.text(), options.editorVersion);
1905
2235
  } catch (error) {
1906
2236
  if (error instanceof CloudClientError) throw error;
1907
2237
  if (signal.aborted) throw new CloudClientError("OpenPencil server discovery was cancelled or timed out", error);
@@ -1910,8 +2240,16 @@ async function discoverCloud(serverURL, options = {}) {
1910
2240
  }
1911
2241
  //#endregion
1912
2242
  //#region src/client/portal/account.ts
1913
- function createAccountAPI(call, { account }) {
2243
+ function createAccountAPI(call, { account, tokens, api }) {
1914
2244
  return {
2245
+ /** The account's plan, and the storage its workspaces hold together. */
2246
+ entitlements(signal) {
2247
+ return call((options) => api.account.entitlements.$get(void 0, options), accountEntitlementsResponseSchema, signal);
2248
+ },
2249
+ /** A short-lived token for the deployment's billing, for this account. */
2250
+ billingToken(signal) {
2251
+ return call((options) => api.billing.token.$post(void 0, options), billingTokenSchema, signal);
2252
+ },
1915
2253
  accountStatus(signal) {
1916
2254
  return call((options) => account.status.$get(void 0, options), cloudAccountStatusResponseSchema, signal);
1917
2255
  },
@@ -1961,6 +2299,10 @@ function createAccountAPI(call, { account }) {
1961
2299
  profile(signal) {
1962
2300
  return call((options) => account.profile.$get(void 0, options), cloudProfileResponseSchema, signal);
1963
2301
  },
2302
+ /** The app's language tag; the server writes to the account in it, or the nearest it has. */
2303
+ setLocale(locale, signal) {
2304
+ return call((options) => account.locale.$put({ json: { locale } }, options), cloudAccountMutationResponseSchema, signal);
2305
+ },
1964
2306
  updateProfile(name, signal) {
1965
2307
  return call((options) => account.profile.$post({ json: { name } }, options), cloudAccountMutationResponseSchema, signal);
1966
2308
  },
@@ -1978,6 +2320,17 @@ function createAccountAPI(call, { account }) {
1978
2320
  callbackURL
1979
2321
  } }, options), cloudAccountMutationResponseSchema, signal);
1980
2322
  },
2323
+ /** The account's personal access tokens, by their first characters; never a whole one. */
2324
+ accessTokens(signal) {
2325
+ return call((options) => tokens.$get(void 0, options), cloudAccessTokensResponseSchema, signal);
2326
+ },
2327
+ /** Makes a token; the answer holds the whole token, which is shown this once. */
2328
+ createAccessToken(input, signal) {
2329
+ return call((options) => tokens.create.$post({ json: input }, options), cloudAccessTokenCreatedResponseSchema, signal);
2330
+ },
2331
+ revokeAccessToken(id, signal) {
2332
+ return call((options) => tokens.revoke.$post({ json: { id } }, options), cloudAccountMutationResponseSchema, signal);
2333
+ },
1981
2334
  sessions(signal) {
1982
2335
  return call((options) => account.sessions.$get(void 0, options), cloudAccountSessionsResponseSchema, signal);
1983
2336
  },
@@ -2145,6 +2498,7 @@ function createPortalRouteClients(options = {}) {
2145
2498
  };
2146
2499
  return {
2147
2500
  account: hc(origin, clientOptions).api.account,
2501
+ tokens: hc(origin, clientOptions).api.account.tokens,
2148
2502
  admin: hc(new URL("/api/admin", origin).href, clientOptions),
2149
2503
  api: hc(new URL("/api", origin).href, clientOptions)
2150
2504
  };
@@ -2161,6 +2515,6 @@ function createCloudPortalClient(options = {}) {
2161
2515
  };
2162
2516
  }
2163
2517
  //#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 };
2518
+ export { CloudAPIError, CloudBillingError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, CloudServiceError, CloudServiceInsecureEndpointError, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudServicesFetch, cloudSignInURL, createCloudAPIClient, createCloudAuthClient, createCloudBillingClient, createCloudPortalClient, createCloudServicesClient, discoverCloud, pollCloudDeviceToken, requestCloudDeviceAuthorization, resendCloudVerification, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail };
2165
2519
 
2166
2520
  //# sourceMappingURL=client.js.map