@open-pencil/cloud 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +7 -0
  4. package/README.md +37 -2
  5. package/dist/bin/ai-relay.d.mts +1 -0
  6. package/dist/bin/ai-relay.mjs +31 -0
  7. package/dist/bin/ai-relay.mjs.map +1 -0
  8. package/dist/bin/server.d.mts +1 -0
  9. package/dist/bin/server.mjs +29 -0
  10. package/dist/bin/server.mjs.map +1 -0
  11. package/dist/client.d.ts +1520 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +1917 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/contract.d.ts +2 -0
  16. package/dist/contract.js +2 -0
  17. package/dist/contract2.js +1453 -0
  18. package/dist/contract2.js.map +1 -0
  19. package/dist/email.d.ts +169 -0
  20. package/dist/email.d.ts.map +1 -0
  21. package/dist/email.js +670 -0
  22. package/dist/email.js.map +1 -0
  23. package/dist/index.d.ts +1755 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/listen.mjs +1881 -0
  26. package/dist/listen.mjs.map +1 -0
  27. package/dist/runtime-node.d.mts +10040 -0
  28. package/dist/runtime-node.d.mts.map +1 -0
  29. package/dist/runtime-node.mjs +32 -0
  30. package/dist/runtime-node.mjs.map +1 -0
  31. package/dist/server.d.ts +12792 -0
  32. package/dist/server.d.ts.map +1 -0
  33. package/dist/server.js +8475 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/server.mjs +8324 -0
  36. package/dist/server.mjs.map +1 -0
  37. package/dist/server2.mjs +505 -0
  38. package/dist/server2.mjs.map +1 -0
  39. package/package.json +124 -4
  40. package/src/admin/api/routes.ts +223 -0
  41. package/src/admin/api/security.ts +12 -0
  42. package/src/admin/audit/service.ts +138 -0
  43. package/src/admin/email/service.ts +140 -0
  44. package/src/admin/enrollment/email.ts +77 -0
  45. package/src/admin/enrollment/service.ts +308 -0
  46. package/src/admin/errors.ts +20 -0
  47. package/src/admin/index.ts +19 -0
  48. package/src/admin/list.ts +61 -0
  49. package/src/admin/operations/service.ts +70 -0
  50. package/src/admin/schema.ts +28 -0
  51. package/src/admin/users/service.ts +369 -0
  52. package/src/ai-relay/app.ts +251 -0
  53. package/src/ai-relay/config.ts +120 -0
  54. package/src/ai-relay/db/index.ts +10 -0
  55. package/src/ai-relay/db/migrate.ts +32 -0
  56. package/src/ai-relay/db/migrations/001_usage.ts +26 -0
  57. package/src/ai-relay/db/schema.ts +20 -0
  58. package/src/ai-relay/index.ts +18 -0
  59. package/src/ai-relay/metering.ts +68 -0
  60. package/src/ai-relay/usage.ts +115 -0
  61. package/src/client/ai.ts +96 -0
  62. package/src/client/api.ts +528 -0
  63. package/src/client/auth/client.ts +188 -0
  64. package/src/client/auth/failure.ts +54 -0
  65. package/src/client/auth/navigation.ts +45 -0
  66. package/src/client/device-authorization.ts +134 -0
  67. package/src/client/discovery.ts +105 -0
  68. package/src/client/images.ts +81 -0
  69. package/src/client/index.ts +53 -0
  70. package/src/client/portal/account.ts +183 -0
  71. package/src/client/portal/administration.ts +130 -0
  72. package/src/client/portal/client.ts +18 -0
  73. package/src/client/portal/request.ts +115 -0
  74. package/src/client/response.ts +51 -0
  75. package/src/client/workspaces.ts +142 -0
  76. package/src/contract/account.ts +204 -0
  77. package/src/contract/admin/index.ts +187 -0
  78. package/src/contract/ai.ts +150 -0
  79. package/src/contract/collaboration.ts +45 -0
  80. package/src/contract/discovery.ts +81 -0
  81. package/src/contract/documents.ts +265 -0
  82. package/src/contract/entitlements.ts +28 -0
  83. package/src/contract/index.ts +204 -0
  84. package/src/contract/links.ts +87 -0
  85. package/src/contract/portal.ts +11 -0
  86. package/src/contract/relay.ts +368 -0
  87. package/src/contract/sharing.ts +191 -0
  88. package/src/contract/versions.ts +87 -0
  89. package/src/contract/workspaces.ts +100 -0
  90. package/src/email/index.ts +14 -0
  91. package/src/email/render.ts +276 -0
  92. package/src/email/schema.ts +144 -0
  93. package/src/email/templates/brand.ts +105 -0
  94. package/src/email/templates/document-invitation.ts +35 -0
  95. package/src/email/templates/enrollment.ts +27 -0
  96. package/src/email/templates/layout.ts +18 -0
  97. package/src/runtime/cloudflare/email.ts +70 -0
  98. package/src/runtime/cloudflare/environment.ts +57 -0
  99. package/src/runtime/cloudflare/index.ts +3 -0
  100. package/src/runtime/cloudflare/relay.ts +136 -0
  101. package/src/runtime/cloudflare/site.ts +13 -0
  102. package/src/runtime/cloudflare/tsconfig.json +21 -0
  103. package/src/runtime/cloudflare/worker.ts +160 -0
  104. package/src/runtime/node/admin.ts +59 -0
  105. package/src/runtime/node/ai-relay/main.ts +35 -0
  106. package/src/runtime/node/ai-relay/server.ts +63 -0
  107. package/src/runtime/node/application.ts +50 -0
  108. package/src/runtime/node/bootstrap.ts +22 -0
  109. package/src/runtime/node/cleanup.ts +24 -0
  110. package/src/runtime/node/command.ts +17 -0
  111. package/src/runtime/node/config.ts +16 -0
  112. package/src/runtime/node/email/runtime.ts +43 -0
  113. package/src/runtime/node/email/transport.ts +112 -0
  114. package/src/runtime/node/entitlements/main.ts +41 -0
  115. package/src/runtime/node/entitlements/refusal.ts +15 -0
  116. package/src/runtime/node/index.ts +25 -0
  117. package/src/runtime/node/listen.ts +35 -0
  118. package/src/runtime/node/main.ts +29 -0
  119. package/src/runtime/node/migrate.ts +13 -0
  120. package/src/runtime/node/quota-reconcile.ts +9 -0
  121. package/src/runtime/node/relay.ts +54 -0
  122. package/src/runtime/node/server.ts +121 -0
  123. package/src/runtime/node/site.ts +64 -0
  124. package/src/runtime/postgres/database.ts +19 -0
  125. package/src/runtime/s3/objects.ts +244 -0
  126. package/src/runtime/site/server.ts +82 -0
  127. package/src/server/account/actions.ts +66 -0
  128. package/src/server/account/routes.ts +300 -0
  129. package/src/server/ai/errors.ts +7 -0
  130. package/src/server/ai/index.ts +4 -0
  131. package/src/server/ai/keys.ts +43 -0
  132. package/src/server/ai/routes.ts +43 -0
  133. package/src/server/ai/service.ts +70 -0
  134. package/src/server/api/index.ts +8 -0
  135. package/src/server/api/router.ts +117 -0
  136. package/src/server/api/types.ts +7 -0
  137. package/src/server/app.ts +375 -0
  138. package/src/server/auth/account.ts +73 -0
  139. package/src/server/auth/activity.ts +213 -0
  140. package/src/server/auth/adapter.ts +79 -0
  141. package/src/server/auth/email.ts +125 -0
  142. package/src/server/auth/endpoints.ts +57 -0
  143. package/src/server/auth/factory.ts +583 -0
  144. package/src/server/auth/index.ts +17 -0
  145. package/src/server/auth/mfa-assurance.ts +55 -0
  146. package/src/server/auth/runtime.ts +26 -0
  147. package/src/server/auth/session.ts +19 -0
  148. package/src/server/auth/social-providers.ts +55 -0
  149. package/src/server/auth/user-agent.ts +16 -0
  150. package/src/server/auth/workspace-access.ts +23 -0
  151. package/src/server/cleanup/configured.ts +38 -0
  152. package/src/server/cleanup/documents.ts +231 -0
  153. package/src/server/cleanup/index.ts +29 -0
  154. package/src/server/cleanup/objects.ts +27 -0
  155. package/src/server/cleanup/revisions.ts +232 -0
  156. package/src/server/cleanup/uploads.ts +129 -0
  157. package/src/server/cleanup/worker.ts +79 -0
  158. package/src/server/collaboration/index.ts +28 -0
  159. package/src/server/collaboration/relay/authorize.ts +53 -0
  160. package/src/server/collaboration/relay/awareness.ts +104 -0
  161. package/src/server/collaboration/relay/documents.ts +39 -0
  162. package/src/server/collaboration/relay/hub.ts +524 -0
  163. package/src/server/collaboration/relay/index.ts +15 -0
  164. package/src/server/collaboration/relay/persistence.ts +48 -0
  165. package/src/server/collaboration/routes.ts +77 -0
  166. package/src/server/collaboration/service.ts +188 -0
  167. package/src/server/config/deployment.ts +178 -0
  168. package/src/server/config/index.ts +20 -0
  169. package/src/server/config/limits.ts +8 -0
  170. package/src/server/config/public.ts +66 -0
  171. package/src/server/config/schema.ts +512 -0
  172. package/src/server/db/database.ts +15 -0
  173. package/src/server/db/expressions.ts +13 -0
  174. package/src/server/db/index.ts +21 -0
  175. package/src/server/db/migrate.ts +177 -0
  176. package/src/server/db/migrations/001_foundation.ts +164 -0
  177. package/src/server/db/migrations/002_upload_cleanup_claims.ts +34 -0
  178. package/src/server/db/migrations/003_document_cleanup_claims.ts +23 -0
  179. package/src/server/db/migrations/004_document_sharing.ts +82 -0
  180. package/src/server/db/migrations/005_document_collaboration_epoch.ts +13 -0
  181. package/src/server/db/migrations/006_invitation_continuation.ts +27 -0
  182. package/src/server/db/migrations/007_collaboration_state.ts +25 -0
  183. package/src/server/db/migrations/008_storage_reservations.ts +37 -0
  184. package/src/server/db/migrations/009_workspace_entitlements.ts +22 -0
  185. package/src/server/db/migrations/010_upload_finalization.ts +22 -0
  186. package/src/server/db/migrations/011_upload_finalization_lease.ts +12 -0
  187. package/src/server/db/migrations/012_transactional_email.ts +48 -0
  188. package/src/server/db/migrations/013_admin_enrollment.ts +54 -0
  189. package/src/server/db/migrations/014_enrollment_email_kinds.ts +30 -0
  190. package/src/server/db/migrations/015_cloud_rate_limit.ts +22 -0
  191. package/src/server/db/migrations/016_auth_schema.ts +16 -0
  192. package/src/server/db/migrations/017_authentication_email_kinds.ts +32 -0
  193. package/src/server/db/migrations/018_authentication_mfa.ts +78 -0
  194. package/src/server/db/migrations/019_better_auth_account_issuer.ts +42 -0
  195. package/src/server/db/migrations/020_workspace_invitations.ts +57 -0
  196. package/src/server/db/migrations/021_document_versions.ts +66 -0
  197. package/src/server/db/migrations/022_entitlement_external_version.ts +17 -0
  198. package/src/server/db/migrations/023_document_images.ts +61 -0
  199. package/src/server/db/migrations/024_account_activity.ts +66 -0
  200. package/src/server/db/migrations/025_table_names.ts +58 -0
  201. package/src/server/db/migrations/026_user_picture.ts +30 -0
  202. package/src/server/db/migrations/027_document_kind.ts +19 -0
  203. package/src/server/db/migrations/helpers.ts +78 -0
  204. package/src/server/db/tables.ts +394 -0
  205. package/src/server/documents/access.ts +103 -0
  206. package/src/server/documents/errors.ts +16 -0
  207. package/src/server/documents/images.ts +407 -0
  208. package/src/server/documents/index.ts +14 -0
  209. package/src/server/documents/limits.ts +57 -0
  210. package/src/server/documents/repository.ts +141 -0
  211. package/src/server/documents/routes.ts +239 -0
  212. package/src/server/documents/service.ts +597 -0
  213. package/src/server/documents/summary.ts +37 -0
  214. package/src/server/documents/types.ts +14 -0
  215. package/src/server/documents/versions/checkpoint.ts +98 -0
  216. package/src/server/documents/versions/history.ts +25 -0
  217. package/src/server/documents/versions/index.ts +4 -0
  218. package/src/server/documents/versions/routes.ts +112 -0
  219. package/src/server/documents/versions/service.ts +397 -0
  220. package/src/server/email/crypto.ts +57 -0
  221. package/src/server/email/index.ts +18 -0
  222. package/src/server/email/invitations.ts +30 -0
  223. package/src/server/email/service.ts +245 -0
  224. package/src/server/email/types.ts +56 -0
  225. package/src/server/email/worker.ts +33 -0
  226. package/src/server/index.ts +279 -0
  227. package/src/server/internal/index.ts +8 -0
  228. package/src/server/internal/routes.ts +41 -0
  229. package/src/server/internal/schema.ts +10 -0
  230. package/src/server/internal/service.ts +44 -0
  231. package/src/server/invitations/index.ts +6 -0
  232. package/src/server/invitations/types.ts +30 -0
  233. package/src/server/objects/index.ts +16 -0
  234. package/src/server/objects/types.ts +81 -0
  235. package/src/server/pictures/index.ts +9 -0
  236. package/src/server/pictures/provider.ts +61 -0
  237. package/src/server/pictures/routes.ts +21 -0
  238. package/src/server/pictures/service.ts +235 -0
  239. package/src/server/policy/configured.ts +23 -0
  240. package/src/server/policy/database.ts +108 -0
  241. package/src/server/policy/entitlements.ts +29 -0
  242. package/src/server/policy/index.ts +17 -0
  243. package/src/server/policy/keys.ts +23 -0
  244. package/src/server/policy/policy.ts +117 -0
  245. package/src/server/policy/provider.ts +67 -0
  246. package/src/server/policy/schema.ts +69 -0
  247. package/src/server/policy/service.ts +85 -0
  248. package/src/server/policy/static.ts +62 -0
  249. package/src/server/quota/index.ts +7 -0
  250. package/src/server/quota/reconcile.ts +61 -0
  251. package/src/server/quota/storage.ts +165 -0
  252. package/src/server/rate-limit/cleanup.ts +16 -0
  253. package/src/server/rate-limit/index.ts +12 -0
  254. package/src/server/rate-limit/keys.ts +38 -0
  255. package/src/server/rate-limit/middleware.ts +137 -0
  256. package/src/server/rate-limit/postgres.ts +79 -0
  257. package/src/server/sharing/access.ts +29 -0
  258. package/src/server/sharing/actor.ts +12 -0
  259. package/src/server/sharing/capabilities/service.ts +262 -0
  260. package/src/server/sharing/continuation.ts +85 -0
  261. package/src/server/sharing/contracts.ts +80 -0
  262. package/src/server/sharing/crypto.ts +48 -0
  263. package/src/server/sharing/document-routes.ts +41 -0
  264. package/src/server/sharing/errors.ts +12 -0
  265. package/src/server/sharing/grants/service.ts +79 -0
  266. package/src/server/sharing/http.ts +41 -0
  267. package/src/server/sharing/index.ts +39 -0
  268. package/src/server/sharing/invitations/service.ts +315 -0
  269. package/src/server/sharing/policy.ts +44 -0
  270. package/src/server/sharing/routes.ts +251 -0
  271. package/src/server/sharing/service.ts +117 -0
  272. package/src/server/validation.ts +24 -0
  273. package/src/server/worker/interval.ts +23 -0
  274. package/src/server/worker/periodic.ts +42 -0
  275. package/src/server/workspaces/index.ts +16 -0
  276. package/src/server/workspaces/members.ts +502 -0
  277. package/src/server/workspaces/repository.ts +91 -0
  278. package/src/server/workspaces/routes.ts +198 -0
  279. package/src/server/workspaces/service.ts +84 -0
package/dist/client.js ADDED
@@ -0,0 +1,1917 @@
1
+ import { isValid } from "js-base64";
2
+ import * as v from "valibot";
3
+ import { zipObject } from "es-toolkit";
4
+ import { joinURL, withQuery, withoutFragment } from "ufo";
5
+ import { pickBy } from "es-toolkit/object";
6
+ import { hc } from "hono/client";
7
+ import { passkeyClient } from "@better-auth/passkey/client";
8
+ import { createAuthClient } from "better-auth/client";
9
+ import { deviceAuthorizationClient, twoFactorClient } from "better-auth/client/plugins";
10
+ //#region src/contract/account.ts
11
+ const cloudAccountStateSchema = v.picklist([
12
+ "active",
13
+ "pending",
14
+ "rejected",
15
+ "revoked"
16
+ ]);
17
+ const cloudIdentitySchema = v.object({
18
+ userId: v.string(),
19
+ email: v.pipe(v.string(), v.email()),
20
+ name: v.string(),
21
+ /** The account's picture, such as one a social provider gave it. */
22
+ image: v.optional(v.nullable(v.string())),
23
+ deploymentRole: v.optional(v.picklist(["user", "admin"]))
24
+ });
25
+ const cloudAccountStatusResponseSchema = v.object({
26
+ user: cloudIdentitySchema,
27
+ state: cloudAccountStateSchema
28
+ });
29
+ const cloudAuthenticationProviderSchema = v.picklist([
30
+ "credential",
31
+ "google",
32
+ "apple"
33
+ ]);
34
+ const cloudAuthenticationMethodSchema = v.object({
35
+ id: v.string(),
36
+ provider: cloudAuthenticationProviderSchema,
37
+ createdAt: v.string(),
38
+ canUnlink: v.boolean()
39
+ });
40
+ const cloudAuthenticationMethodsResponseSchema = v.object({
41
+ methods: v.array(cloudAuthenticationMethodSchema),
42
+ availableSocialProviders: v.array(v.picklist(["google", "apple"]))
43
+ });
44
+ v.object({
45
+ currentPassword: v.string(),
46
+ newPassword: v.string()
47
+ });
48
+ v.object({
49
+ provider: v.picklist(["google", "apple"]),
50
+ callbackURL: v.pipe(v.string(), v.url())
51
+ });
52
+ const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) });
53
+ v.object({ methodId: v.string() });
54
+ const accountSecurityErrorCodeSchema = v.picklist([
55
+ "current_password_invalid",
56
+ "password_too_short",
57
+ "password_too_long",
58
+ "last_authentication_method",
59
+ "session_not_fresh",
60
+ "authentication_method_failed",
61
+ "email_unchanged",
62
+ "email_change_unavailable",
63
+ "current_session",
64
+ "picture_invalid"
65
+ ]);
66
+ const accountSecurityErrorResponseSchema = v.object({ error: v.object({ code: accountSecurityErrorCodeSchema }) });
67
+ const cloudMFAStatusSchema = v.object({
68
+ required: v.boolean(),
69
+ enabled: v.boolean(),
70
+ totpEnabled: v.boolean(),
71
+ assured: v.boolean(),
72
+ totpAvailable: v.boolean(),
73
+ passkeysAvailable: v.boolean(),
74
+ recoveryCodesAvailable: v.boolean()
75
+ });
76
+ const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema });
77
+ v.object({ password: v.optional(v.string()) });
78
+ const cloudMFAEnableResponseSchema = v.object({
79
+ totpURI: v.string(),
80
+ backupCodes: v.array(v.string())
81
+ });
82
+ v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) });
83
+ const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) });
84
+ const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) });
85
+ const cloudPasskeySchema = v.object({
86
+ id: v.string(),
87
+ name: v.nullish(v.string()),
88
+ createdAt: v.string()
89
+ });
90
+ const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) });
91
+ v.object({ id: v.string() });
92
+ const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
93
+ /** Who an account belongs to, as the portal shows it. */
94
+ const cloudPersonSchema = v.object({
95
+ id: v.string(),
96
+ name: v.string(),
97
+ email: v.pipe(v.string(), v.email()),
98
+ /** The address of the account's picture, which the server serves; null shows initials. */
99
+ image: v.nullable(v.string())
100
+ });
101
+ /** What a person can see and change about themselves. */
102
+ const cloudProfileSchema = v.object({
103
+ ...cloudPersonSchema.entries,
104
+ createdAt: v.string(),
105
+ /** Whether the server can send the verification a new email address needs. */
106
+ emailChangeAvailable: v.boolean()
107
+ });
108
+ const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema });
109
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
110
+ v.object({
111
+ /** The picture's PNG or JPEG bytes, in Base64. */
112
+ data: v.pipe(v.string(), v.maxLength(Math.ceil(262144 / 3) * 4), v.check((value) => isValid(value))) });
113
+ /** The address the account's picture is now served from. */
114
+ const cloudPictureResponseSchema = v.object({ image: v.string() });
115
+ v.object({
116
+ newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
117
+ callbackURL: v.pipe(v.string(), v.url())
118
+ });
119
+ /** How a sign-in was made: the method it used, or the desktop app's approved code. */
120
+ const cloudSignInMethodSchema = v.picklist([
121
+ "password",
122
+ "google",
123
+ "apple",
124
+ "passkey",
125
+ "two-step",
126
+ "email-link",
127
+ "desktop",
128
+ "other"
129
+ ]);
130
+ const cloudAccountSessionSchema = v.object({
131
+ id: v.string(),
132
+ /** The session this request was made with. */
133
+ current: v.boolean(),
134
+ method: v.nullable(cloudSignInMethodSchema),
135
+ ipAddress: v.nullable(v.string()),
136
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
137
+ browser: v.nullable(v.string()),
138
+ system: v.nullable(v.string()),
139
+ createdAt: v.string(),
140
+ lastActiveAt: v.string(),
141
+ expiresAt: v.string()
142
+ });
143
+ const cloudAccountSessionsResponseSchema = v.object({ sessions: v.array(cloudAccountSessionSchema) });
144
+ v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) });
145
+ const cloudSignInSchema = v.object({
146
+ id: v.string(),
147
+ method: cloudSignInMethodSchema,
148
+ ipAddress: v.nullable(v.string()),
149
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
150
+ browser: v.nullable(v.string()),
151
+ system: v.nullable(v.string()),
152
+ createdAt: v.string()
153
+ });
154
+ const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) });
155
+ /** The `aud` of every token Cloud signs for an AI service. */
156
+ const CLOUD_AI_TOKEN_AUDIENCE = "openpencil-ai";
157
+ /**
158
+ * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat
159
+ * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.
160
+ */
161
+ const CLOUD_AI_API_PATHS = {
162
+ base: "/v1",
163
+ chatCompletions: "/v1/chat/completions",
164
+ catalog: "/v1/catalog",
165
+ wallet: "/v1/wallet",
166
+ usage: "/v1/usage"
167
+ };
168
+ const urlSchema = v.pipe(v.string(), v.url());
169
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
170
+ const cloudAIDiscoverySchema = v.object({
171
+ endpoint: urlSchema,
172
+ contractVersion: v.literal("1")
173
+ });
174
+ const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
175
+ v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
176
+ const aiTokenSchema = v.object({
177
+ token: v.pipe(v.string(), v.minLength(1)),
178
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
179
+ });
180
+ v.object({
181
+ iss: urlSchema,
182
+ aud: v.literal(CLOUD_AI_TOKEN_AUDIENCE),
183
+ sub: v.pipe(v.string(), v.minLength(1)),
184
+ workspaceId: v.pipe(v.string(), v.uuid()),
185
+ /** Credits the workspace's plan grants each month; `null` when Cloud sets no allowance. */
186
+ monthlyCreditAllowance: v.nullable(creditsSchema),
187
+ iat: v.pipe(v.number(), v.integer()),
188
+ exp: v.pipe(v.number(), v.integer())
189
+ });
190
+ const aiModelSchema = v.object({
191
+ id: v.pipe(v.string(), v.minLength(1)),
192
+ label: v.pipe(v.string(), v.minLength(1)),
193
+ /** Credits per million input and output tokens. */
194
+ creditsPerMillionInputTokens: creditsSchema,
195
+ creditsPerMillionOutputTokens: creditsSchema,
196
+ contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
197
+ capabilities: v.object({
198
+ reasoning: v.boolean(),
199
+ vision: v.boolean(),
200
+ tools: v.boolean()
201
+ })
202
+ });
203
+ const aiCatalogSchema = v.object({
204
+ models: v.array(aiModelSchema),
205
+ defaultModelID: v.pipe(v.string(), v.minLength(1))
206
+ });
207
+ const aiCreditBucketSchema = v.object({
208
+ kind: v.picklist([
209
+ "allowance",
210
+ "purchased",
211
+ "grant"
212
+ ]),
213
+ remaining: creditsSchema,
214
+ expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
215
+ });
216
+ /**
217
+ * A service records a request's charge before the request's answer ends, so a wallet read after
218
+ * an answer includes what it cost.
219
+ */
220
+ const aiWalletSchema = v.object({
221
+ /** Credits left to spend; `null` when the service sets no limit. */
222
+ balance: v.nullable(creditsSchema),
223
+ /** Spent first to last. */
224
+ buckets: v.array(aiCreditBucketSchema)
225
+ });
226
+ const aiUsageEntrySchema = v.object({
227
+ id: v.pipe(v.string(), v.minLength(1)),
228
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
229
+ kind: v.picklist([
230
+ "model",
231
+ "image",
232
+ "search"
233
+ ]),
234
+ modelID: v.nullable(v.string()),
235
+ userId: v.pipe(v.string(), v.minLength(1)),
236
+ credits: creditsSchema
237
+ });
238
+ v.object({ cursor: v.optional(v.pipe(v.string(), v.minLength(1))) });
239
+ v.object({
240
+ entries: v.array(aiUsageEntrySchema),
241
+ next: v.nullable(v.string())
242
+ });
243
+ /** Errors an AI service answers with, beside the upstream model's own. */
244
+ const aiErrorCodeSchema = v.picklist([
245
+ "unauthorized",
246
+ "insufficient_credits",
247
+ "model_not_allowed",
248
+ "rate_limited"
249
+ ]);
250
+ const aiErrorSchema = v.object({ error: v.object({
251
+ code: aiErrorCodeSchema,
252
+ message: v.optional(v.string()),
253
+ /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
254
+ resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
255
+ }) });
256
+ //#endregion
257
+ //#region src/contract/workspaces.ts
258
+ const workspaceRoleSchema = v.picklist([
259
+ "viewer",
260
+ "editor",
261
+ "admin"
262
+ ]);
263
+ const workspaceSummarySchema = v.object({
264
+ id: v.pipe(v.string(), v.uuid()),
265
+ name: v.string(),
266
+ slug: v.string(),
267
+ role: workspaceRoleSchema,
268
+ createdAt: v.string(),
269
+ updatedAt: v.string()
270
+ });
271
+ v.object({
272
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
273
+ slug: v.optional(v.pipe(v.string(), v.trim(), v.minLength(3), v.maxLength(63), v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)))
274
+ });
275
+ const workspaceListSchema = v.object({ workspaces: v.array(workspaceSummarySchema) });
276
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
277
+ /** Someone who belongs to a workspace, and what they may do in it. */
278
+ const workspaceMemberSchema = v.object({
279
+ userId: v.string(),
280
+ name: v.string(),
281
+ email: v.string(),
282
+ image: v.nullable(v.string()),
283
+ role: workspaceRoleSchema,
284
+ joinedAt: v.string()
285
+ });
286
+ /** An invitation to join a workspace that has not been accepted yet. */
287
+ const workspaceInvitationSchema = v.object({
288
+ id: v.pipe(v.string(), v.uuid()),
289
+ email: v.string(),
290
+ role: workspaceRoleSchema,
291
+ /** Who sent it; the name is null once their account is gone. */
292
+ invitedBy: v.object({
293
+ id: v.string(),
294
+ name: v.nullable(v.string())
295
+ }),
296
+ invitedAt: v.string(),
297
+ expiresAt: v.string()
298
+ });
299
+ const workspaceMembersSchema = v.object({
300
+ members: v.array(workspaceMemberSchema),
301
+ /** Only administrators see pending invitations. */
302
+ invitations: v.array(workspaceInvitationSchema)
303
+ });
304
+ v.object({
305
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
306
+ role: workspaceRoleSchema
307
+ });
308
+ /** A new invitation and its link, for an administrator to pass on when email is off. */
309
+ const createdWorkspaceInvitationSchema = v.object({
310
+ invitation: workspaceInvitationSchema,
311
+ acceptanceURL: v.string()
312
+ });
313
+ v.object({ role: workspaceRoleSchema });
314
+ //#endregion
315
+ //#region src/contract/admin/index.ts
316
+ const timestampSchema = v.pipe(v.string(), v.isoTimestamp());
317
+ const nullableTimestampSchema = v.nullable(timestampSchema);
318
+ const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
319
+ /**
320
+ * What every admin list answers besides its rows: how many rows match the search and filter
321
+ * across every page, and how many match the search under each filter.
322
+ */
323
+ function listTotals(filters) {
324
+ return {
325
+ total: countSchema,
326
+ counts: v.object(zipObject(filters, filters.map(() => countSchema)))
327
+ };
328
+ }
329
+ const adminErrorCodeSchema = v.picklist([
330
+ "bad_request",
331
+ "unauthorized",
332
+ "forbidden",
333
+ "not_found",
334
+ "rate_limited",
335
+ "invalid_enrollment_transition",
336
+ "last_admin_required",
337
+ "self_admin_action_forbidden",
338
+ "email_regeneration_unavailable",
339
+ "mfa_required"
340
+ ]);
341
+ const adminErrorResponseSchema = v.object({ error: v.object({ code: adminErrorCodeSchema }) });
342
+ const enrollmentStatusSchema = v.picklist([
343
+ "pending",
344
+ "approved",
345
+ "rejected",
346
+ "revoked"
347
+ ]);
348
+ const enrollmentSchema = v.object({
349
+ id: v.string(),
350
+ email: v.pipe(v.string(), v.email()),
351
+ name: v.nullable(v.string()),
352
+ reason: v.nullable(v.string()),
353
+ status: enrollmentStatusSchema,
354
+ requestedAt: timestampSchema,
355
+ reviewedAt: nullableTimestampSchema,
356
+ reviewedBy: v.nullable(v.string()),
357
+ /** The reviewer's name, in lists, while the server still knows them. */
358
+ reviewerName: v.optional(v.nullable(v.string())),
359
+ reviewNote: v.nullable(v.string()),
360
+ approvedUserId: v.nullable(v.string()),
361
+ requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))
362
+ });
363
+ const enrollmentsResponseSchema = v.object({
364
+ enrollments: v.array(enrollmentSchema),
365
+ ...listTotals(enrollmentStatusSchema.options)
366
+ });
367
+ const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema });
368
+ const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema });
369
+ const cloudAdminUserSchema = v.object({
370
+ ...cloudPersonSchema.entries,
371
+ role: v.optional(v.string()),
372
+ banned: v.nullable(v.boolean()),
373
+ banReason: v.optional(v.nullable(v.string())),
374
+ createdAt: timestampSchema,
375
+ /** An authenticator app or a passkey confirms this account's sign-ins. */
376
+ twoStep: v.boolean(),
377
+ /** When one of the account's sessions was last used, or null when none is left. */
378
+ lastActiveAt: nullableTimestampSchema,
379
+ workspaceCount: countSchema
380
+ });
381
+ /** Which accounts a list of people shows. */
382
+ const cloudAdminUserFilterSchema = v.picklist([
383
+ "all",
384
+ "administrators",
385
+ "suspended",
386
+ "without-two-step"
387
+ ]);
388
+ const cloudAdminUsersResponseSchema = v.object({
389
+ users: v.array(cloudAdminUserSchema),
390
+ ...listTotals(cloudAdminUserFilterSchema.options)
391
+ });
392
+ const cloudAdminUserDetailSchema = v.object({
393
+ user: v.object({
394
+ ...cloudAdminUserSchema.entries,
395
+ emailVerified: v.boolean()
396
+ }),
397
+ methods: v.array(v.object({
398
+ provider: v.string(),
399
+ createdAt: timestampSchema
400
+ })),
401
+ authenticator: v.boolean(),
402
+ passkeyCount: countSchema,
403
+ sessions: v.array(cloudAccountSessionSchema),
404
+ signIns: v.array(cloudSignInSchema),
405
+ workspaces: v.array(v.object({
406
+ id: v.string(),
407
+ name: v.string(),
408
+ role: workspaceRoleSchema,
409
+ memberCount: countSchema,
410
+ joinedAt: timestampSchema
411
+ }))
412
+ });
413
+ const adminMutationResponseSchema = v.object({ ok: v.literal(true) });
414
+ const transactionalEmailAdminSchema = v.object({
415
+ id: v.string(),
416
+ kind: v.string(),
417
+ recipientEmailNormalized: v.pipe(v.string(), v.email()),
418
+ status: v.string(),
419
+ attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
420
+ nextAttemptAt: timestampSchema,
421
+ transport: v.nullable(v.string()),
422
+ transportMessageId: v.nullable(v.string()),
423
+ lastErrorCode: v.nullable(v.string()),
424
+ createdAt: timestampSchema,
425
+ acceptedAt: nullableTimestampSchema,
426
+ regeneratable: v.boolean()
427
+ });
428
+ /** Which messages a list of email shows, by how their delivery went. */
429
+ const cloudAdminEmailFilterSchema = v.picklist([
430
+ "all",
431
+ "sent",
432
+ "waiting",
433
+ "failed"
434
+ ]);
435
+ const adminEmailResponseSchema = v.object({
436
+ messages: v.array(transactionalEmailAdminSchema),
437
+ ...listTotals(cloudAdminEmailFilterSchema.options)
438
+ });
439
+ /** Who or what an event names; `name` is null once the server no longer knows it. */
440
+ const auditPartySchema = v.object({
441
+ id: v.string(),
442
+ name: v.nullable(v.string())
443
+ });
444
+ const adminAuditEventSchema = v.object({
445
+ id: v.string(),
446
+ actor: auditPartySchema,
447
+ action: v.string(),
448
+ /** What the event is about: an account, an access request, or an email. */
449
+ subject: v.object({
450
+ ...auditPartySchema.entries,
451
+ type: v.string()
452
+ }),
453
+ metadata: v.unknown(),
454
+ createdAt: timestampSchema
455
+ });
456
+ /** Which events a list of activity shows, by what they are about. */
457
+ const cloudAdminAuditFilterSchema = v.picklist([
458
+ "all",
459
+ "accounts",
460
+ "requests",
461
+ "email"
462
+ ]);
463
+ const adminAuditResponseSchema = v.object({
464
+ events: v.array(adminAuditEventSchema),
465
+ ...listTotals(cloudAdminAuditFilterSchema.options)
466
+ });
467
+ const adminOperationsResponseSchema = v.object({
468
+ deployment: v.picklist(["official", "self-hosted"]),
469
+ enrollmentMode: v.picklist([
470
+ "open",
471
+ "approval",
472
+ "closed"
473
+ ]),
474
+ emailTransport: v.picklist([
475
+ "none",
476
+ "smtp",
477
+ "cloudflare"
478
+ ]),
479
+ pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),
480
+ pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
481
+ failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
482
+ accounts: countSchema,
483
+ workspaces: countSchema,
484
+ documents: countSchema,
485
+ storedBytes: countSchema
486
+ });
487
+ //#endregion
488
+ //#region src/contract/documents.ts
489
+ const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
490
+ const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
491
+ /** The most images one revision, or one request for image uploads, may name. */
492
+ const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
493
+ const imageNameSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9._-]{1,128}$/));
494
+ const objectDownloadSchema = v.object({
495
+ url: v.pipe(v.string(), v.url()),
496
+ method: v.literal("GET"),
497
+ headers: v.record(v.string(), v.string()),
498
+ expiresAt: v.string()
499
+ });
500
+ /** An image a stored revision uses, where to download it, and what to check it against. */
501
+ const documentImageDownloadSchema = v.object({
502
+ name: imageNameSchema,
503
+ checksum: checksumSchema,
504
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
505
+ download: objectDownloadSchema
506
+ });
507
+ /** Where to download an image a document uses, found by its checksum. */
508
+ const documentImageLinkSchema = v.object({
509
+ checksum: checksumSchema,
510
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
511
+ download: objectDownloadSchema
512
+ });
513
+ /** The images a live room names, by checksum, that a peer needs links for. */
514
+ const requestImageLinksSchema = v.object({ checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
515
+ const documentPermissionSchema = v.picklist(["view", "edit"]);
516
+ const documentAccessSourceSchema = v.picklist([
517
+ "owner",
518
+ "workspace",
519
+ "direct-grant"
520
+ ]);
521
+ const documentAccessSchema = v.object({
522
+ permission: documentPermissionSchema,
523
+ canManageSharing: v.boolean(),
524
+ sources: v.array(documentAccessSourceSchema)
525
+ });
526
+ /** What a document is: a Figma design or a FigJam board, which the file it stores says too. */
527
+ const documentKindSchema = v.picklist(["design", "board"]);
528
+ const documentSummarySchema = v.object({
529
+ id: v.pipe(v.string(), v.uuid()),
530
+ workspaceId: v.pipe(v.string(), v.uuid()),
531
+ name: v.string(),
532
+ /** A design unless said otherwise; servers from before boards list no kind. */
533
+ kind: v.optional(documentKindSchema, "design"),
534
+ currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
535
+ version: v.number(),
536
+ createdAt: v.string(),
537
+ updatedAt: v.string()
538
+ });
539
+ /** A document someone granted the person directly, in a workspace they are not a member of. */
540
+ const sharedDocumentSchema = v.object({
541
+ ...documentSummarySchema.entries,
542
+ workspaceName: v.string(),
543
+ permission: documentPermissionSchema,
544
+ sharedBy: v.nullable(v.object({ name: v.string() })),
545
+ sharedAt: v.string()
546
+ });
547
+ const documentDownloadSchema = v.object({
548
+ document: documentSummarySchema,
549
+ revisionId: v.pipe(v.string(), v.uuid()),
550
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
551
+ checksum: checksumSchema,
552
+ contentType: v.string(),
553
+ download: objectDownloadSchema,
554
+ /** The images the stored file leaves out, which a client puts back under their names. */
555
+ images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
556
+ });
557
+ const cloudActorSchema = v.object({
558
+ userId: v.string(),
559
+ email: v.pipe(v.string(), v.email()),
560
+ name: v.string()
561
+ });
562
+ const cloudSessionSchema = v.object({ user: cloudActorSchema });
563
+ const workspaceUsageSchema = v.object({
564
+ bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
565
+ objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
566
+ documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
567
+ });
568
+ const createDocumentSchema = v.object({
569
+ id: v.optional(v.pipe(v.string(), v.uuid())),
570
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)),
571
+ /** A design unless said otherwise; older clients create only designs. */
572
+ kind: v.optional(documentKindSchema, "design")
573
+ });
574
+ v.object({
575
+ baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
576
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
577
+ checksum: checksumSchema,
578
+ contentType: v.literal("application/octet-stream")
579
+ });
580
+ const imageSizeSchema = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES));
581
+ /** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */
582
+ const objectUploadSchema = v.variant("kind", [v.object({
583
+ kind: v.literal("single"),
584
+ url: v.pipe(v.string(), v.url()),
585
+ method: v.literal("PUT"),
586
+ headers: v.record(v.string(), v.string()),
587
+ expiresAt: v.string()
588
+ }), v.object({
589
+ kind: v.literal("multipart"),
590
+ uploadId: v.string(),
591
+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
592
+ parts: v.array(v.object({
593
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
594
+ url: v.pipe(v.string(), v.url()),
595
+ method: v.literal("PUT"),
596
+ headers: v.record(v.string(), v.string())
597
+ })),
598
+ expiresAt: v.string()
599
+ })]);
600
+ /** An upload the server offers for an image the workspace lacks. */
601
+ const imageUploadOfferSchema = v.object({
602
+ checksum: checksumSchema,
603
+ uploadId: v.pipe(v.string(), v.uuid()),
604
+ upload: objectUploadSchema
605
+ });
606
+ v.object({ images: v.pipe(v.array(v.object({
607
+ checksum: checksumSchema,
608
+ byteSize: imageSizeSchema
609
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
610
+ const completedUploadPartSchema = v.object({
611
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
612
+ etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
613
+ });
614
+ const commitUploadSchema = v.object({
615
+ checksum: checksumSchema,
616
+ /** The document title captured with this revision; omitted by older clients. */
617
+ name: v.optional(createDocumentSchema.entries.name),
618
+ /** What the uploaded file is, which the document takes; omitted by older clients. */
619
+ kind: v.optional(documentKindSchema),
620
+ multipart: v.optional(v.object({
621
+ uploadId: v.pipe(v.string(), v.minLength(1)),
622
+ parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(1e4))
623
+ })),
624
+ /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */
625
+ images: v.optional(v.pipe(v.array(v.object({
626
+ name: imageNameSchema,
627
+ checksum: checksumSchema
628
+ })), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)), [])
629
+ });
630
+ v.object({ uploads: v.pipe(v.array(v.object({
631
+ uploadId: v.pipe(v.string(), v.uuid()),
632
+ checksum: checksumSchema,
633
+ multipart: commitUploadSchema.entries.multipart
634
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
635
+ //#endregion
636
+ //#region src/contract/collaboration.ts
637
+ const collaborationPrincipalSchema = v.variant("kind", [v.object({
638
+ kind: v.literal("user"),
639
+ userId: v.string(),
640
+ name: v.string(),
641
+ email: v.pipe(v.string(), v.email())
642
+ }), v.object({
643
+ kind: v.literal("guest"),
644
+ guestId: v.string(),
645
+ name: v.string()
646
+ })]);
647
+ v.object({
648
+ kind: v.picklist(["user", "guest"]),
649
+ id: v.string(),
650
+ name: v.string(),
651
+ permission: documentPermissionSchema
652
+ });
653
+ const collaborationTicketSchema = v.object({
654
+ token: v.string(),
655
+ provider: v.optional(v.picklist(["trystero", "relay"])),
656
+ serverURL: v.optional(v.pipe(v.string(), v.url())),
657
+ documentId: v.pipe(v.string(), v.uuid()),
658
+ roomId: v.string(),
659
+ roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
660
+ principal: collaborationPrincipalSchema,
661
+ permission: documentPermissionSchema,
662
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
663
+ expiresAt: v.string(),
664
+ serverEnforcedWrites: v.boolean()
665
+ });
666
+ //#endregion
667
+ //#region src/contract/entitlements.ts
668
+ const workspaceEntitlementsSchema = v.object({
669
+ features: v.object({
670
+ links: v.boolean(),
671
+ guestView: v.boolean(),
672
+ guestEdit: v.boolean(),
673
+ guestPresence: v.boolean(),
674
+ collaboration: v.boolean(),
675
+ revisionHistory: v.boolean(),
676
+ cloudAI: v.optional(v.boolean(), false)
677
+ }),
678
+ limits: v.object({
679
+ maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
680
+ maximumStorageBytes: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
681
+ maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
682
+ monthlyCreditAllowance: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), null)
683
+ }),
684
+ usage: v.object({
685
+ committedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0)),
686
+ reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
687
+ })
688
+ });
689
+ const CLOUD_DISCOVERY_PATH = "/.well-known/openpencil";
690
+ const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
691
+ const cloudAuthenticationSchema = v.object({
692
+ emailPassword: v.optional(v.object({
693
+ signIn: v.boolean(),
694
+ signUp: v.boolean(),
695
+ minimumPasswordLength: v.pipe(v.number(), v.integer(), v.minValue(8)),
696
+ captcha: v.optional(v.object({
697
+ provider: v.literal("cloudflare-turnstile"),
698
+ siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
699
+ }))
700
+ })),
701
+ socialProviders: v.array(v.picklist(["apple", "google"])),
702
+ enterpriseSSO: v.boolean(),
703
+ enrollmentMode: v.optional(v.picklist([
704
+ "open",
705
+ "approval",
706
+ "closed"
707
+ ]), "open"),
708
+ mfa: v.optional(v.object({
709
+ deploymentAdminRequired: v.boolean(),
710
+ totp: v.boolean(),
711
+ passkeys: v.boolean(),
712
+ recoveryCodes: v.boolean()
713
+ }))
714
+ });
715
+ const cloudCapabilitiesSchema = v.object({
716
+ documents: v.boolean(),
717
+ workspaces: v.boolean(),
718
+ collaboration: v.boolean()
719
+ });
720
+ /** A released editor version, `major.minor.patch`. */
721
+ const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
722
+ /**
723
+ * Whether editors offer this server to everyone, and from which editor version on. Only the
724
+ * official server's listing is read: it turns the Cloud entry points on without an editor release,
725
+ * and an editor older than the minimum keeps them hidden.
726
+ */
727
+ const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema });
728
+ const cloudDiscoverySchema = v.object({
729
+ protocolVersion: v.literal("1"),
730
+ deployment: cloudDeploymentSchema,
731
+ apiURL: v.pipe(v.string(), v.url()),
732
+ authURL: v.pipe(v.string(), v.url()),
733
+ /** Whether the server's own editor works with files on this device without signing in. */
734
+ localEditor: v.optional(v.boolean(), true),
735
+ authentication: cloudAuthenticationSchema,
736
+ capabilities: cloudCapabilitiesSchema,
737
+ listing: v.optional(cloudListingSchema),
738
+ /** The AI service editors reach with Cloud-signed tokens; absent when the deployment has none. */
739
+ ai: v.optional(cloudAIDiscoverySchema),
740
+ /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
741
+ billing: v.optional(cloudBillingDiscoverySchema)
742
+ });
743
+ /** The server's own address, where its editor and pages are, from its auth API's. */
744
+ function cloudServerOrigin(discovery) {
745
+ return new URL(discovery.authURL).origin;
746
+ }
747
+ //#endregion
748
+ //#region src/contract/sharing.ts
749
+ const documentShareSchema = v.object({
750
+ id: v.pipe(v.string(), v.uuid()),
751
+ documentId: v.pipe(v.string(), v.uuid()),
752
+ permission: documentPermissionSchema,
753
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
754
+ createdBy: v.string(),
755
+ createdAt: v.string(),
756
+ updatedAt: v.string(),
757
+ expiresAt: v.nullable(v.string()),
758
+ revokedAt: v.nullable(v.string()),
759
+ lastUsedAt: v.nullable(v.string())
760
+ });
761
+ /** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
762
+ const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())));
763
+ v.object({
764
+ permission: documentPermissionSchema,
765
+ expiresAt: shareExpirySchema
766
+ });
767
+ v.object({
768
+ permission: v.optional(documentPermissionSchema),
769
+ expiresAt: shareExpirySchema
770
+ });
771
+ const resolveDocumentShareSchema = v.object({
772
+ secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
773
+ guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
774
+ guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
775
+ });
776
+ v.object({
777
+ ...resolveDocumentShareSchema.entries,
778
+ ...requestImageLinksSchema.entries
779
+ });
780
+ const resolvedDocumentShareSchema = v.object({
781
+ documentId: v.pipe(v.string(), v.uuid()),
782
+ permission: documentPermissionSchema,
783
+ principal: collaborationPrincipalSchema,
784
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))
785
+ });
786
+ const cloudUserProfileSchema = v.object({
787
+ id: v.string(),
788
+ name: v.string(),
789
+ email: v.pipe(v.string(), v.email()),
790
+ image: v.nullable(v.pipe(v.string(), v.url()))
791
+ });
792
+ const documentGrantSchema = v.object({
793
+ id: v.pipe(v.string(), v.uuid()),
794
+ documentId: v.pipe(v.string(), v.uuid()),
795
+ userId: v.string(),
796
+ permission: documentPermissionSchema,
797
+ createdBy: v.string(),
798
+ createdAt: v.string(),
799
+ updatedAt: v.string()
800
+ });
801
+ /** What accepting an invitation gave: access to a document, or a place in a workspace. */
802
+ const acceptedInvitationSchema = v.variant("kind", [v.object({
803
+ kind: v.literal("document"),
804
+ grant: documentGrantSchema
805
+ }), v.object({
806
+ kind: v.literal("workspace"),
807
+ workspaceId: v.pipe(v.string(), v.uuid()),
808
+ role: workspaceRoleSchema
809
+ })]);
810
+ v.object({ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()) });
811
+ v.object({ permission: documentPermissionSchema });
812
+ v.object({
813
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
814
+ permission: documentPermissionSchema
815
+ });
816
+ v.object({ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128)) });
817
+ const createInvitationContinuationSchema = v.object({
818
+ invitationId: v.pipe(v.string(), v.uuid()),
819
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
820
+ });
821
+ const invitationContinuationSchema = v.object({ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128)) });
822
+ const invitationPreviewFields = {
823
+ inviterName: v.string(),
824
+ expiresAt: v.string(),
825
+ recipientHint: v.string()
826
+ };
827
+ /** What an invitation link opens: one document, or a whole workspace. */
828
+ const invitationPreviewSchema = v.variant("kind", [v.object({
829
+ kind: v.literal("document"),
830
+ documentName: v.string(),
831
+ permission: documentPermissionSchema,
832
+ ...invitationPreviewFields
833
+ }), v.object({
834
+ kind: v.literal("workspace"),
835
+ workspaceName: v.string(),
836
+ role: workspaceRoleSchema,
837
+ ...invitationPreviewFields
838
+ })]);
839
+ const documentInvitationSchema = v.object({
840
+ id: v.pipe(v.string(), v.uuid()),
841
+ documentId: v.pipe(v.string(), v.uuid()),
842
+ email: v.pipe(v.string(), v.email()),
843
+ permission: documentPermissionSchema,
844
+ invitedBy: v.string(),
845
+ invitedAt: v.string(),
846
+ expiresAt: v.string(),
847
+ acceptedAt: v.nullable(v.string())
848
+ });
849
+ const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1e3;
850
+ /** A checkpoint the server kept on its own, or a version someone named. */
851
+ const documentVersionKindSchema = v.picklist(["checkpoint", "named"]);
852
+ const documentVersionSchema = v.object({
853
+ id: v.pipe(v.string(), v.uuid()),
854
+ revisionId: v.pipe(v.string(), v.uuid()),
855
+ kind: documentVersionKindSchema,
856
+ name: v.nullable(v.string()),
857
+ description: v.nullable(v.string()),
858
+ createdAt: v.string(),
859
+ /** Who made the version: the author of a checkpoint's save, or who named or restored it. */
860
+ createdBy: v.object({
861
+ id: v.string(),
862
+ name: v.nullable(v.string())
863
+ }),
864
+ /** The version this one restored, while that version is still in the history. */
865
+ restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),
866
+ /** Whether the document holds this version now. */
867
+ current: v.boolean()
868
+ });
869
+ const documentVersionsSchema = v.object({
870
+ versions: v.array(documentVersionSchema),
871
+ /** Pass as `before` for the next, older page; null on the last one. */
872
+ nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))
873
+ });
874
+ const versionNameSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));
875
+ const versionDescriptionSchema = v.pipe(v.string(), v.trim(), v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH));
876
+ v.object({
877
+ name: versionNameSchema,
878
+ description: v.optional(versionDescriptionSchema, "")
879
+ });
880
+ v.object({
881
+ name: v.nullable(versionNameSchema),
882
+ description: v.optional(versionDescriptionSchema, "")
883
+ });
884
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)) });
885
+ const documentVersionResponseSchema = v.object({ version: documentVersionSchema });
886
+ /** A version with where to download it, so a link to it can show it without the history. */
887
+ const documentVersionDownloadSchema = v.object({
888
+ document: documentDownloadSchema,
889
+ version: documentVersionSchema
890
+ });
891
+ const restoredDocumentSchema = v.object({
892
+ document: documentSummarySchema,
893
+ version: documentVersionSchema
894
+ });
895
+ //#endregion
896
+ //#region src/client/ai.ts
897
+ var CloudAIError = class extends Error {
898
+ status;
899
+ code;
900
+ name = "CloudAIError";
901
+ constructor(status, code) {
902
+ super(`OpenPencil AI request failed with HTTP ${status}`);
903
+ this.status = status;
904
+ this.code = code;
905
+ }
906
+ };
907
+ /** Whether a request can be sent twice: a stream, in `init` or a `Request`, is read by the first. */
908
+ function replayable(input, body) {
909
+ if (input instanceof Request && input.body) return false;
910
+ return !(body instanceof ReadableStream);
911
+ }
912
+ /**
913
+ * Sends each request with a current token. A token the service refuses, for instance one signed
914
+ * by a key Cloud has since replaced, is dropped and a request that can be replayed is sent once
915
+ * more with a new one.
916
+ */
917
+ function cloudAIFetch(tokens, fetch) {
918
+ const send = async (input, init, token) => {
919
+ const headers = new Headers(init?.headers);
920
+ headers.set("Authorization", `Bearer ${token}`);
921
+ return fetch(input, {
922
+ ...init,
923
+ headers
924
+ });
925
+ };
926
+ return async (input, init) => {
927
+ const token = await tokens.token();
928
+ const response = await send(input, init, token);
929
+ if (response.status !== 401) return response;
930
+ tokens.invalidate(token);
931
+ if (!replayable(input, init?.body)) return response;
932
+ return send(input, init, await tokens.token());
933
+ };
934
+ }
935
+ const errorBodySchema = v.pipe(v.string(), v.parseJson(), aiErrorSchema);
936
+ async function parsed(response, schema) {
937
+ const text = await response.text();
938
+ if (!response.ok) {
939
+ const error = v.safeParse(errorBodySchema, text);
940
+ throw new CloudAIError(response.status, error.success ? error.output.error.code : void 0);
941
+ }
942
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), text);
943
+ }
944
+ /** The AI service a Cloud advertises: its model API base URL, catalog, and the wallet. */
945
+ function createCloudAIClient(options) {
946
+ const endpoint = options.endpoint.replace(/\/+$/, "");
947
+ const fetch = cloudAIFetch(options.tokens, options.fetch);
948
+ return {
949
+ /** The base URL an OpenAI-compatible client sends chat completions below. */
950
+ modelBaseURL: `${endpoint}${CLOUD_AI_API_PATHS.base}`,
951
+ fetch,
952
+ async catalog() {
953
+ return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.catalog}`), aiCatalogSchema);
954
+ },
955
+ async wallet() {
956
+ return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.wallet}`), aiWalletSchema);
957
+ }
958
+ };
959
+ }
960
+ //#endregion
961
+ //#region src/client/auth/navigation.ts
962
+ /** The instance owns authentication; only its own editor may receive the return. */
963
+ function cloudEditorReturnURL(discovery, value) {
964
+ const destination = new URL(value);
965
+ if (!["https:", "http:"].includes(destination.protocol) || destination.origin !== cloudServerOrigin(discovery) || destination.username || destination.password) throw new Error("Authentication return URL must belong to this instance editor");
966
+ return withoutFragment(destination.href);
967
+ }
968
+ /**
969
+ * The server's sign-in page, coming back to `returnURL` on its editor afterwards. A `provider`
970
+ * starts that provider's sign-in at once, while the server's pages still handle two-step sign-in
971
+ * and approval before the return.
972
+ */
973
+ function cloudSignInURL(discovery, returnURL, provider) {
974
+ const offered = provider && discovery.authentication.socialProviders.includes(provider);
975
+ return withQuery(new URL("/auth/sign-in", discovery.authURL).href, {
976
+ redirect: withQuery("/auth/return", { editor: cloudEditorReturnURL(discovery, returnURL) }),
977
+ provider: offered ? provider : void 0
978
+ });
979
+ }
980
+ /** Accept only same-origin application paths for post-authentication navigation. */
981
+ function cloudRedirectPath(value, fallback = "/app") {
982
+ if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//")) return fallback;
983
+ const origin = "https://redirect.invalid";
984
+ const url = new URL(value, origin);
985
+ if (url.origin !== origin) return fallback;
986
+ return `${url.pathname}${url.search}${url.hash}`;
987
+ }
988
+ //#endregion
989
+ //#region src/client/response.ts
990
+ const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
991
+ var CloudAPIError = class extends Error {
992
+ status;
993
+ code;
994
+ name = "CloudAPIError";
995
+ constructor(message, status, code) {
996
+ super(message);
997
+ this.status = status;
998
+ this.code = code;
999
+ }
1000
+ };
1001
+ async function responseBody(response, onDiagnostic) {
1002
+ if (response.ok) return response.status === 204 ? null : response.json();
1003
+ let code;
1004
+ try {
1005
+ const body = v.safeParse(cloudErrorResponseSchema, await response.json());
1006
+ if (body.success) code = body.output.error.code;
1007
+ } catch (error) {
1008
+ onDiagnostic?.("Cloud API error response was not JSON", error);
1009
+ }
1010
+ throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
1011
+ }
1012
+ async function parseResponse(request, schema, onDiagnostic) {
1013
+ return v.parse(schema, await responseBody(await request, onDiagnostic));
1014
+ }
1015
+ //#endregion
1016
+ //#region src/client/images.ts
1017
+ const imageLinksResponseSchema = v.object({ images: v.array(documentImageLinkSchema) });
1018
+ const imageUploadsResponseSchema = v.object({ uploads: v.array(imageUploadOfferSchema) });
1019
+ /** The images a save uploads apart from the document, and the links a live room loads them by. */
1020
+ function createImageRequests(client, publicClient, onDiagnostic) {
1021
+ return {
1022
+ /** Uploads for the images a save will name that the document's workspace lacks. */
1023
+ async requestImageUploads(documentId, input) {
1024
+ return (await parseResponse(client.documents[":documentId"].images.$post({
1025
+ param: { documentId },
1026
+ json: input
1027
+ }), imageUploadsResponseSchema, onDiagnostic)).uploads;
1028
+ },
1029
+ /** Commits the image uploads a save asked for, once their bytes are in place. */
1030
+ async commitImageUploads(documentId, uploads) {
1031
+ await responseBody(await client.documents[":documentId"].images.commit.$post({
1032
+ param: { documentId },
1033
+ json: { uploads }
1034
+ }), onDiagnostic);
1035
+ },
1036
+ /** Links for images a document's live room names. */
1037
+ async getImageLinks(documentId, checksums) {
1038
+ return (await parseResponse(client.documents[":documentId"].images.links.$post({
1039
+ param: { documentId },
1040
+ json: { checksums }
1041
+ }), imageLinksResponseSchema, onDiagnostic)).images;
1042
+ },
1043
+ /** Links for images a shared document's live room names, as the share's guest. */
1044
+ async getSharedImageLinks(shareId, input, checksums) {
1045
+ return (await parseResponse(publicClient.shares[":shareId"].images.$post({
1046
+ param: { shareId },
1047
+ json: {
1048
+ ...input,
1049
+ checksums
1050
+ }
1051
+ }), imageLinksResponseSchema, onDiagnostic)).images;
1052
+ }
1053
+ };
1054
+ }
1055
+ //#endregion
1056
+ //#region src/client/workspaces.ts
1057
+ const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
1058
+ const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
1059
+ const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
1060
+ /** Workspaces, their members, invitations, entitlements, and storage use. */
1061
+ function createWorkspaceRequests(client, onDiagnostic) {
1062
+ return {
1063
+ async listWorkspaces() {
1064
+ return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
1065
+ },
1066
+ async createWorkspace(name) {
1067
+ return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
1068
+ },
1069
+ async renameWorkspace(workspaceId, name) {
1070
+ return (await parseResponse(client.workspaces[":workspaceId"].$patch({
1071
+ param: { workspaceId },
1072
+ json: { name }
1073
+ }), workspaceResponseSchema, onDiagnostic)).workspace;
1074
+ },
1075
+ /** Deletes an empty workspace; the server refuses one that still holds documents. */
1076
+ async deleteWorkspace(workspaceId) {
1077
+ await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1078
+ },
1079
+ /** The workspace's members, and for administrators its pending invitations. */
1080
+ async listWorkspaceMembers(workspaceId) {
1081
+ return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1082
+ },
1083
+ async inviteToWorkspace(workspaceId, input) {
1084
+ return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
1085
+ param: { workspaceId },
1086
+ json: input
1087
+ }), createdWorkspaceInvitationSchema, onDiagnostic);
1088
+ },
1089
+ /** Sends a waiting invitation again; its earlier link stops working. */
1090
+ async resendWorkspaceInvitation(workspaceId, invitationId) {
1091
+ return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
1092
+ workspaceId,
1093
+ invitationId
1094
+ } }), createdWorkspaceInvitationSchema, onDiagnostic);
1095
+ },
1096
+ async revokeWorkspaceInvitation(workspaceId, invitationId) {
1097
+ await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
1098
+ workspaceId,
1099
+ invitationId
1100
+ } }), onDiagnostic);
1101
+ },
1102
+ async updateWorkspaceMember(workspaceId, userId, role) {
1103
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1104
+ param: {
1105
+ workspaceId,
1106
+ userId
1107
+ },
1108
+ json: { role }
1109
+ }), onDiagnostic);
1110
+ },
1111
+ /** Removes someone from the workspace; with the person's own id, leaves it. */
1112
+ async removeWorkspaceMember(workspaceId, userId) {
1113
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
1114
+ workspaceId,
1115
+ userId
1116
+ } }), onDiagnostic);
1117
+ },
1118
+ async getWorkspaceEntitlements(workspaceId) {
1119
+ return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1120
+ },
1121
+ async getUsage(workspaceId) {
1122
+ return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
1123
+ }
1124
+ };
1125
+ }
1126
+ //#endregion
1127
+ //#region src/client/api.ts
1128
+ const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
1129
+ const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
1130
+ const documentResponseSchema = v.object({ document: documentSummarySchema });
1131
+ const downloadResponseSchema = v.object({ document: documentDownloadSchema });
1132
+ const accessResponseSchema = v.object({ access: documentAccessSchema });
1133
+ const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) });
1134
+ const shareResponseSchema = v.object({ share: documentShareSchema });
1135
+ const shareCapabilityResponseSchema = v.object({
1136
+ share: documentShareSchema,
1137
+ secret: v.string(),
1138
+ path: v.string()
1139
+ });
1140
+ const grantsResponseSchema = v.object({ grants: v.array(documentGrantSchema) });
1141
+ const grantResponseSchema = v.object({ grant: documentGrantSchema });
1142
+ const acceptedResponseSchema = v.object({ accepted: acceptedInvitationSchema });
1143
+ const invitationPreviewResponseSchema = v.object({ invitation: invitationPreviewSchema });
1144
+ const invitationsResponseSchema = v.object({ invitations: v.array(documentInvitationSchema) });
1145
+ const invitationCapabilityResponseSchema = v.object({
1146
+ invitation: documentInvitationSchema,
1147
+ token: v.string()
1148
+ });
1149
+ const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1150
+ const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema });
1151
+ const sharedDocumentResponseSchema = v.object({
1152
+ resolution: resolvedDocumentShareSchema,
1153
+ document: documentDownloadSchema
1154
+ });
1155
+ const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
1156
+ const uploadResponseSchema = v.object({
1157
+ id: v.pipe(v.string(), v.uuid()),
1158
+ upload: objectUploadSchema
1159
+ });
1160
+ function apiURL(baseURL) {
1161
+ const url = new URL(baseURL);
1162
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("OpenPencil Cloud API URL must use HTTP or HTTPS", 0);
1163
+ url.pathname = url.pathname.replace(/\/$/, "");
1164
+ url.search = "";
1165
+ url.hash = "";
1166
+ return url.href;
1167
+ }
1168
+ function createCloudAPIClient(baseURL, options = {}) {
1169
+ const headers = {
1170
+ "Content-Type": "application/json",
1171
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1172
+ };
1173
+ const client = hc(apiURL(baseURL), {
1174
+ fetch: options.fetch,
1175
+ init: {
1176
+ credentials: "include",
1177
+ signal: options.signal,
1178
+ headers
1179
+ }
1180
+ });
1181
+ const publicClient = hc(apiURL(baseURL), {
1182
+ fetch: options.fetch,
1183
+ init: {
1184
+ credentials: "include",
1185
+ signal: options.signal,
1186
+ headers
1187
+ }
1188
+ });
1189
+ return {
1190
+ async getSession() {
1191
+ const response = await client.session.$get();
1192
+ if (response.status === 401) return null;
1193
+ return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
1194
+ },
1195
+ /** A short-lived token for the deployment's AI service, on the workspace's behalf. */
1196
+ async requestAIToken(workspaceId) {
1197
+ return parseResponse(client.ai.token.$post({ json: { workspaceId } }), aiTokenSchema, options.onDiagnostic);
1198
+ },
1199
+ async lookupUser(documentId, input) {
1200
+ return (await parseResponse(client.documents[":documentId"].users.lookup.$post({
1201
+ param: { documentId },
1202
+ json: input
1203
+ }), userLookupResponseSchema, options.onDiagnostic)).user;
1204
+ },
1205
+ async getUserProfile(documentId, userId) {
1206
+ return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
1207
+ documentId,
1208
+ userId
1209
+ } }), userLookupResponseSchema, options.onDiagnostic)).user;
1210
+ },
1211
+ ...createWorkspaceRequests(client, options.onDiagnostic),
1212
+ ...createImageRequests(client, publicClient, options.onDiagnostic),
1213
+ /** Documents shared with the person directly, outside their workspaces. */
1214
+ async listSharedDocuments() {
1215
+ return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, options.onDiagnostic)).documents;
1216
+ },
1217
+ async listDocuments(workspaceId) {
1218
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, options.onDiagnostic)).documents;
1219
+ },
1220
+ async createDocument(workspaceId, input) {
1221
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
1222
+ param: { workspaceId },
1223
+ json: {
1224
+ ...input,
1225
+ kind: input.kind ?? "design"
1226
+ }
1227
+ }), documentResponseSchema, options.onDiagnostic)).document;
1228
+ },
1229
+ async deleteDocument(documentId) {
1230
+ await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), options.onDiagnostic);
1231
+ },
1232
+ async getDocument(documentId) {
1233
+ return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, options.onDiagnostic)).document;
1234
+ },
1235
+ async getDocumentAccess(documentId) {
1236
+ return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, options.onDiagnostic)).access;
1237
+ },
1238
+ async listDocumentShares(documentId) {
1239
+ return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, options.onDiagnostic)).shares;
1240
+ },
1241
+ async createDocumentShare(documentId, input) {
1242
+ return parseResponse(client.documents[":documentId"].shares.$post({
1243
+ param: { documentId },
1244
+ json: input
1245
+ }), shareCapabilityResponseSchema, options.onDiagnostic);
1246
+ },
1247
+ async updateDocumentShare(documentId, shareId, input) {
1248
+ return (await parseResponse(client.documents[":documentId"].shares[":shareId"].$patch({
1249
+ param: {
1250
+ documentId,
1251
+ shareId
1252
+ },
1253
+ json: input
1254
+ }), shareResponseSchema, options.onDiagnostic)).share;
1255
+ },
1256
+ async rotateDocumentShare(documentId, shareId) {
1257
+ return parseResponse(client.documents[":documentId"].shares[":shareId"].rotate.$post({ param: {
1258
+ documentId,
1259
+ shareId
1260
+ } }), shareCapabilityResponseSchema, options.onDiagnostic);
1261
+ },
1262
+ async revokeDocumentShare(documentId, shareId) {
1263
+ await responseBody(await client.documents[":documentId"].shares[":shareId"].$delete({ param: {
1264
+ documentId,
1265
+ shareId
1266
+ } }), options.onDiagnostic);
1267
+ },
1268
+ async listDocumentGrants(documentId) {
1269
+ return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, options.onDiagnostic)).grants;
1270
+ },
1271
+ async putDocumentGrant(documentId, userId, input) {
1272
+ return (await parseResponse(client.documents[":documentId"].grants[":userId"].$put({
1273
+ param: {
1274
+ documentId,
1275
+ userId
1276
+ },
1277
+ json: input
1278
+ }), grantResponseSchema, options.onDiagnostic)).grant;
1279
+ },
1280
+ async revokeDocumentGrant(documentId, userId) {
1281
+ await responseBody(await client.documents[":documentId"].grants[":userId"].$delete({ param: {
1282
+ documentId,
1283
+ userId
1284
+ } }), options.onDiagnostic);
1285
+ },
1286
+ async listDocumentInvitations(documentId) {
1287
+ return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, options.onDiagnostic)).invitations;
1288
+ },
1289
+ async createDocumentInvitation(documentId, input) {
1290
+ return parseResponse(client.documents[":documentId"].invitations.$post({
1291
+ param: { documentId },
1292
+ json: input
1293
+ }), invitationCapabilityResponseSchema, options.onDiagnostic);
1294
+ },
1295
+ async createInvitationContinuation(input) {
1296
+ return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, options.onDiagnostic);
1297
+ },
1298
+ async consumeInvitationContinuation(id) {
1299
+ return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, options.onDiagnostic);
1300
+ },
1301
+ async previewInvitation(invitationId, input) {
1302
+ return (await parseResponse(publicClient.invitations[":invitationId"].preview.$post({
1303
+ param: { invitationId },
1304
+ json: input
1305
+ }), invitationPreviewResponseSchema, options.onDiagnostic)).invitation;
1306
+ },
1307
+ /** Accepts a document or workspace invitation, and says which it was. */
1308
+ async acceptInvitation(invitationId, input) {
1309
+ return (await parseResponse(client.invitations[":invitationId"].accept.$post({
1310
+ param: { invitationId },
1311
+ json: input
1312
+ }), acceptedResponseSchema, options.onDiagnostic)).accepted;
1313
+ },
1314
+ async revokeDocumentInvitation(documentId, invitationId) {
1315
+ await responseBody(await client.documents[":documentId"].invitations[":invitationId"].$delete({ param: {
1316
+ documentId,
1317
+ invitationId
1318
+ } }), options.onDiagnostic);
1319
+ },
1320
+ async resolveDocumentShare(shareId, input) {
1321
+ return (await parseResponse(publicClient.shares[":shareId"].resolve.$post({
1322
+ param: { shareId },
1323
+ json: input
1324
+ }), resolvedShareResponseSchema, options.onDiagnostic)).resolution;
1325
+ },
1326
+ async getSharedDocument(shareId, input) {
1327
+ return parseResponse(publicClient.shares[":shareId"].document.$post({
1328
+ param: { shareId },
1329
+ json: input
1330
+ }), sharedDocumentResponseSchema, options.onDiagnostic);
1331
+ },
1332
+ async getSharedCollaborationTicket(shareId, input) {
1333
+ return (await parseResponse(publicClient.shares[":shareId"]["collaboration-ticket"].$post({
1334
+ param: { shareId },
1335
+ json: input
1336
+ }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1337
+ },
1338
+ async getCollaborationTicket(documentId) {
1339
+ return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1340
+ },
1341
+ async createUpload(documentId, input) {
1342
+ return parseResponse(client.documents[":documentId"].uploads.$post({
1343
+ param: { documentId },
1344
+ json: input
1345
+ }), uploadResponseSchema, options.onDiagnostic);
1346
+ },
1347
+ async commitUpload(uploadId, input) {
1348
+ return (await parseResponse(client.uploads[":uploadId"].commit.$post({
1349
+ param: { uploadId },
1350
+ json: {
1351
+ ...input,
1352
+ images: input.images ?? []
1353
+ }
1354
+ }), documentResponseSchema, options.onDiagnostic)).document;
1355
+ },
1356
+ /** A page of the document's version history, newest first. */
1357
+ async listDocumentVersions(documentId, page = {}) {
1358
+ return parseResponse(client.documents[":documentId"].versions.$get({
1359
+ param: { documentId },
1360
+ query: pickBy(page, (value) => value !== void 0)
1361
+ }), documentVersionsSchema, options.onDiagnostic);
1362
+ },
1363
+ async saveDocumentVersion(documentId, input) {
1364
+ return (await parseResponse(client.documents[":documentId"].versions.$post({
1365
+ param: { documentId },
1366
+ json: input
1367
+ }), documentVersionResponseSchema, options.onDiagnostic)).version;
1368
+ },
1369
+ async updateDocumentVersion(documentId, versionId, input) {
1370
+ return (await parseResponse(client.documents[":documentId"].versions[":versionId"].$patch({
1371
+ param: {
1372
+ documentId,
1373
+ versionId
1374
+ },
1375
+ json: input
1376
+ }), documentVersionResponseSchema, options.onDiagnostic)).version;
1377
+ },
1378
+ async getDocumentVersion(documentId, versionId) {
1379
+ return parseResponse(client.documents[":documentId"].versions[":versionId"].$get({ param: {
1380
+ documentId,
1381
+ versionId
1382
+ } }), documentVersionDownloadSchema, options.onDiagnostic);
1383
+ },
1384
+ async restoreDocumentVersion(documentId, versionId) {
1385
+ return parseResponse(client.documents[":documentId"].versions[":versionId"].restore.$post({ param: {
1386
+ documentId,
1387
+ versionId
1388
+ } }), restoredDocumentSchema, options.onDiagnostic);
1389
+ },
1390
+ async duplicateDocumentVersion(documentId, versionId, input) {
1391
+ return (await parseResponse(client.documents[":documentId"].versions[":versionId"].duplicate.$post({
1392
+ param: {
1393
+ documentId,
1394
+ versionId
1395
+ },
1396
+ json: input
1397
+ }), documentResponseSchema, options.onDiagnostic)).document;
1398
+ }
1399
+ };
1400
+ }
1401
+ //#endregion
1402
+ //#region src/client/auth/failure.ts
1403
+ /** The failure a Better Auth error stands for; anything unknown can only be retried later. */
1404
+ function cloudAuthFailure(error) {
1405
+ if (error?.status === 429) return {
1406
+ ok: false,
1407
+ failure: "rate-limited"
1408
+ };
1409
+ switch (error?.code ?? "") {
1410
+ case "INVALID_EMAIL_OR_PASSWORD": return {
1411
+ ok: false,
1412
+ failure: "invalid-credentials"
1413
+ };
1414
+ case "EMAIL_NOT_VERIFIED": return {
1415
+ ok: false,
1416
+ failure: "email-not-verified"
1417
+ };
1418
+ case "PASSWORD_TOO_SHORT": return {
1419
+ ok: false,
1420
+ failure: "password-too-short"
1421
+ };
1422
+ case "PASSWORD_TOO_LONG": return {
1423
+ ok: false,
1424
+ failure: "password-too-long"
1425
+ };
1426
+ case "INVALID_TOKEN": return {
1427
+ ok: false,
1428
+ failure: "invalid-link"
1429
+ };
1430
+ case "SESSION_NOT_FRESH": return {
1431
+ ok: false,
1432
+ failure: "session-not-fresh"
1433
+ };
1434
+ case "AUTH_CANCELLED":
1435
+ case "ERROR_CEREMONY_ABORTED": return {
1436
+ ok: false,
1437
+ failure: "passkey-cancelled"
1438
+ };
1439
+ case "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED": return {
1440
+ ok: false,
1441
+ failure: "passkey-exists"
1442
+ };
1443
+ case "INVALID_CODE":
1444
+ case "INVALID_TWO_FACTOR_CODE":
1445
+ case "INVALID_BACKUP_CODE": return {
1446
+ ok: false,
1447
+ failure: "invalid-code"
1448
+ };
1449
+ default: return {
1450
+ ok: false,
1451
+ failure: error?.code?.startsWith("ERROR_") ? "passkey-unavailable" : "unavailable"
1452
+ };
1453
+ }
1454
+ }
1455
+ //#endregion
1456
+ //#region src/client/auth/client.ts
1457
+ function returnURL() {
1458
+ return withoutFragment(globalThis.location.href);
1459
+ }
1460
+ function authHeaders(options) {
1461
+ const headers = {};
1462
+ if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`;
1463
+ if (options.captchaResponse) headers["x-captcha-response"] = options.captchaResponse;
1464
+ return Object.keys(headers).length > 0 ? headers : void 0;
1465
+ }
1466
+ function createCloudAuthClient(discovery, options = {}) {
1467
+ return createAuthClient({
1468
+ baseURL: discovery.authURL,
1469
+ plugins: [
1470
+ deviceAuthorizationClient(),
1471
+ twoFactorClient({ twoFactorPage: "/auth/two-factor" }),
1472
+ passkeyClient()
1473
+ ],
1474
+ fetchOptions: {
1475
+ credentials: "include",
1476
+ customFetchImpl: options.fetch,
1477
+ headers: authHeaders(options)
1478
+ }
1479
+ });
1480
+ }
1481
+ async function signInToCloud(discovery, provider, options = {}) {
1482
+ const callbackURL = options.callbackURL ?? returnURL();
1483
+ if (!discovery.authentication.socialProviders.includes(provider)) throw new Error(`Cloud sign-in provider is unavailable: ${provider}`);
1484
+ const result = await createCloudAuthClient(discovery, { fetch: options.fetch }).signIn.social({
1485
+ provider,
1486
+ callbackURL,
1487
+ errorCallbackURL: callbackURL,
1488
+ disableRedirect: true
1489
+ });
1490
+ if (result.error) throw new Error(result.error.message ?? "Cloud sign-in failed");
1491
+ if (typeof result.data.url !== "string") throw new TypeError("Cloud sign-in response did not include a URL");
1492
+ (options.navigate ?? ((url) => globalThis.location.assign(url)))(result.data.url);
1493
+ }
1494
+ async function signOutFromCloud(discovery, options = {}) {
1495
+ const result = await createCloudAuthClient(discovery, options).signOut();
1496
+ if (result.error) throw new Error(result.error.message ?? "Cloud sign-out failed");
1497
+ }
1498
+ /**
1499
+ * Signs in with an email and password without leaving the app. The token goes on every later
1500
+ * request, so no cookie has to cross from the server to the editor.
1501
+ */
1502
+ async function signInToCloudWithEmail(discovery, input, options = {}) {
1503
+ const result = await createCloudAuthClient(discovery, options).signIn.email({
1504
+ ...input,
1505
+ rememberMe: true
1506
+ }).catch(() => null);
1507
+ if (!result) return cloudAuthFailure(null);
1508
+ if (result.error) return cloudAuthFailure(result.error);
1509
+ if ("twoFactorRedirect" in result.data && result.data.twoFactorRedirect === true) return {
1510
+ ok: true,
1511
+ value: { status: "two-step" }
1512
+ };
1513
+ if (!("token" in result.data) || typeof result.data.token !== "string") return cloudAuthFailure(null);
1514
+ return {
1515
+ ok: true,
1516
+ value: {
1517
+ status: "signed-in",
1518
+ token: result.data.token
1519
+ }
1520
+ };
1521
+ }
1522
+ /** Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed. */
1523
+ async function signUpToCloudWithEmail(discovery, input, options = {}) {
1524
+ const result = await createCloudAuthClient(discovery, options).signUp.email({
1525
+ name: input.name,
1526
+ email: input.email,
1527
+ password: input.password,
1528
+ callbackURL: input.verifiedURL
1529
+ }).catch(() => null);
1530
+ if (!result) return cloudAuthFailure(null);
1531
+ return result.error ? cloudAuthFailure(result.error) : {
1532
+ ok: true,
1533
+ value: void 0
1534
+ };
1535
+ }
1536
+ async function resendCloudVerification(discovery, input, options = {}) {
1537
+ const result = await createCloudAuthClient(discovery, options).sendVerificationEmail({
1538
+ email: input.email,
1539
+ callbackURL: input.verifiedURL
1540
+ }).catch(() => null);
1541
+ if (!result) return cloudAuthFailure(null);
1542
+ return result.error ? cloudAuthFailure(result.error) : {
1543
+ ok: true,
1544
+ value: void 0
1545
+ };
1546
+ }
1547
+ //#endregion
1548
+ //#region src/client/device-authorization.ts
1549
+ const deviceCodeSchema = v.object({
1550
+ device_code: v.string(),
1551
+ user_code: v.string(),
1552
+ verification_uri: v.pipe(v.string(), v.url()),
1553
+ verification_uri_complete: v.pipe(v.string(), v.url()),
1554
+ expires_in: v.pipe(v.number(), v.integer(), v.minValue(1)),
1555
+ interval: v.pipe(v.number(), v.integer(), v.minValue(1))
1556
+ });
1557
+ const deviceTokenSchema = v.object({
1558
+ access_token: v.string(),
1559
+ token_type: v.literal("Bearer"),
1560
+ expires_in: v.pipe(v.number(), v.integer(), v.minValue(1)),
1561
+ scope: v.string()
1562
+ });
1563
+ const deviceErrorSchema = v.object({
1564
+ error: v.string(),
1565
+ error_description: v.optional(v.string())
1566
+ });
1567
+ /** RFC 8628: each `slow_down` adds five seconds to the polling interval. */
1568
+ const SLOW_DOWN_MS = 5e3;
1569
+ var CloudDeviceAuthorizationError = class extends Error {
1570
+ code;
1571
+ name = "CloudDeviceAuthorizationError";
1572
+ constructor(code) {
1573
+ super(`Cloud device authorization ${code}`);
1574
+ this.code = code;
1575
+ }
1576
+ };
1577
+ function abortableSleep(milliseconds, signal) {
1578
+ return new Promise((resolve, reject) => {
1579
+ const timeout = setTimeout(resolve, milliseconds);
1580
+ signal?.addEventListener("abort", () => {
1581
+ clearTimeout(timeout);
1582
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException("Authorization cancelled", "AbortError"));
1583
+ }, { once: true });
1584
+ });
1585
+ }
1586
+ function authEndpoint(discovery, path) {
1587
+ return joinURL(discovery.authURL, path);
1588
+ }
1589
+ async function requestCloudDeviceAuthorization(discovery, connectionId, options = {}) {
1590
+ const response = await (options.fetch ?? globalThis.fetch)(authEndpoint(discovery, "device/code"), {
1591
+ method: "POST",
1592
+ headers: { "Content-Type": "application/json" },
1593
+ body: JSON.stringify({
1594
+ client_id: `openpencil-desktop:${connectionId}`,
1595
+ scope: "openid profile"
1596
+ })
1597
+ });
1598
+ if (!response.ok) throw new CloudDeviceAuthorizationError("unavailable");
1599
+ return v.parse(deviceCodeSchema, await response.json());
1600
+ }
1601
+ async function pollCloudDeviceToken(discovery, connectionId, authorization, options = {}) {
1602
+ const request = options.fetch ?? globalThis.fetch;
1603
+ const now = options.now ?? Date.now;
1604
+ const sleep = options.sleep ?? abortableSleep;
1605
+ const expiresAt = now() + authorization.expires_in * 1e3;
1606
+ let interval = authorization.interval * 1e3;
1607
+ while (now() < expiresAt) {
1608
+ options.signal?.throwIfAborted();
1609
+ await sleep(interval, options.signal);
1610
+ if (now() >= expiresAt) break;
1611
+ const response = await request(authEndpoint(discovery, "device/token"), {
1612
+ method: "POST",
1613
+ headers: { "Content-Type": "application/json" },
1614
+ body: JSON.stringify({
1615
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1616
+ device_code: authorization.device_code,
1617
+ client_id: `openpencil-desktop:${connectionId}`
1618
+ }),
1619
+ signal: options.signal
1620
+ });
1621
+ const body = await response.text();
1622
+ if (response.ok) return v.parse(v.pipe(v.string(), v.parseJson(), deviceTokenSchema), body);
1623
+ if (response.status === 429) {
1624
+ interval += SLOW_DOWN_MS;
1625
+ continue;
1626
+ }
1627
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), deviceErrorSchema), body);
1628
+ if (!parsed.success) throw new CloudDeviceAuthorizationError("unavailable");
1629
+ const error = parsed.output;
1630
+ if (error.error === "authorization_pending") continue;
1631
+ if (error.error === "slow_down") {
1632
+ interval += SLOW_DOWN_MS;
1633
+ continue;
1634
+ }
1635
+ let code = "unavailable";
1636
+ if (error.error === "access_denied") code = "denied";
1637
+ else if (error.error === "expired_token") code = "expired";
1638
+ throw new CloudDeviceAuthorizationError(code);
1639
+ }
1640
+ throw new CloudDeviceAuthorizationError("expired");
1641
+ }
1642
+ //#endregion
1643
+ //#region src/client/discovery.ts
1644
+ const DISCOVERY_TIMEOUT_MS = 1e4;
1645
+ var CloudClientError = class extends Error {
1646
+ cause;
1647
+ reason;
1648
+ constructor(message, cause, reason = "unreachable") {
1649
+ super(message);
1650
+ this.cause = cause;
1651
+ this.reason = reason;
1652
+ this.name = "CloudClientError";
1653
+ }
1654
+ };
1655
+ const discoveryBodySchema = v.pipe(v.string(), v.parseJson(), v.looseObject({}));
1656
+ const protocolSchema = v.looseObject({ protocolVersion: v.string() });
1657
+ function discoveryURL(serverURL) {
1658
+ let url;
1659
+ try {
1660
+ url = new URL(serverURL);
1661
+ } catch (error) {
1662
+ throw new CloudClientError("OpenPencil server URL is invalid", error, "invalid-address");
1663
+ }
1664
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudClientError("OpenPencil server URL must use HTTP or HTTPS", void 0, "invalid-address");
1665
+ url.pathname = CLOUD_DISCOVERY_PATH;
1666
+ url.search = "";
1667
+ url.hash = "";
1668
+ return url;
1669
+ }
1670
+ function parseDiscoveryBody(text) {
1671
+ const body = v.safeParse(discoveryBodySchema, text);
1672
+ if (!body.success) throw new CloudClientError("OpenPencil server discovery is not JSON", body.issues, "not-cloud");
1673
+ const discovery = v.safeParse(cloudDiscoverySchema, body.output);
1674
+ if (discovery.success) return discovery.output;
1675
+ const protocol = v.safeParse(protocolSchema, body.output);
1676
+ const outdated = protocol.success && protocol.output.protocolVersion !== "1";
1677
+ throw new CloudClientError(outdated ? `OpenPencil server speaks protocol ${protocol.output.protocolVersion}` : "OpenPencil server discovery is invalid", discovery.issues, outdated ? "outdated" : "not-cloud");
1678
+ }
1679
+ async function discoverCloud(serverURL, options = {}) {
1680
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
1681
+ const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
1682
+ const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
1683
+ try {
1684
+ const response = await fetchImplementation(discoveryURL(serverURL), {
1685
+ headers: { Accept: "application/json" },
1686
+ redirect: "follow",
1687
+ signal
1688
+ });
1689
+ if (!response.ok) throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`, void 0, response.status >= 500 ? "unreachable" : "not-cloud");
1690
+ return parseDiscoveryBody(await response.text());
1691
+ } catch (error) {
1692
+ if (error instanceof CloudClientError) throw error;
1693
+ if (signal.aborted) throw new CloudClientError("OpenPencil server discovery was cancelled or timed out", error);
1694
+ throw new CloudClientError("OpenPencil server discovery failed", error);
1695
+ }
1696
+ }
1697
+ //#endregion
1698
+ //#region src/client/portal/account.ts
1699
+ function createAccountAPI(call, { account }) {
1700
+ return {
1701
+ accountStatus(signal) {
1702
+ return call((options) => account.status.$get(void 0, options), cloudAccountStatusResponseSchema, signal);
1703
+ },
1704
+ authenticationMethods(signal) {
1705
+ return call((options) => account.authentication.$get(void 0, options), cloudAuthenticationMethodsResponseSchema, signal);
1706
+ },
1707
+ mfaStatus(signal) {
1708
+ return call((options) => account.mfa.$get(void 0, options), cloudMFAStatusResponseSchema, signal);
1709
+ },
1710
+ enableTOTP(password, signal) {
1711
+ return call((options) => account.mfa.totp.enable.$post({ json: { password } }, options), cloudMFAEnableResponseSchema, signal);
1712
+ },
1713
+ verifyTOTP(code, signal) {
1714
+ return call((options) => account.mfa.totp.verify.$post({ json: { code } }, options), cloudMFAVerifyResponseSchema, signal);
1715
+ },
1716
+ verifyRecoveryCode(code, signal) {
1717
+ return call((options) => account.mfa.recovery.verify.$post({ json: { code } }, options), cloudMFAVerifyResponseSchema, signal);
1718
+ },
1719
+ regenerateRecoveryCodes(password, signal) {
1720
+ return call((options) => account.mfa.recovery.regenerate.$post({ json: { password } }, options), cloudMFARecoveryCodesResponseSchema, signal);
1721
+ },
1722
+ disableTOTP(password, signal) {
1723
+ return call((options) => account.mfa.totp.disable.$post({ json: { password } }, options), cloudAccountMutationResponseSchema, signal);
1724
+ },
1725
+ passkeys(signal) {
1726
+ return call((options) => account.mfa.passkeys.$get(void 0, options), cloudPasskeysResponseSchema, signal);
1727
+ },
1728
+ deletePasskey(id, signal) {
1729
+ return call((options) => account.mfa.passkeys.delete.$post({ json: { id } }, options), cloudAccountMutationResponseSchema, signal);
1730
+ },
1731
+ changePassword(currentPassword, newPassword, signal) {
1732
+ return call((options) => account.authentication["change-password"].$post({ json: {
1733
+ currentPassword,
1734
+ newPassword
1735
+ } }, options), cloudAccountMutationResponseSchema, signal);
1736
+ },
1737
+ linkSocial(provider, callbackURL, signal) {
1738
+ return call((options) => account.authentication["link-social"].$post({ json: {
1739
+ provider,
1740
+ callbackURL
1741
+ } }, options), cloudSocialLinkResponseSchema, signal);
1742
+ },
1743
+ profile(signal) {
1744
+ return call((options) => account.profile.$get(void 0, options), cloudProfileResponseSchema, signal);
1745
+ },
1746
+ updateProfile(name, signal) {
1747
+ return call((options) => account.profile.$post({ json: { name } }, options), cloudAccountMutationResponseSchema, signal);
1748
+ },
1749
+ /** Shows `data`, a Base64 PNG or JPEG the page cropped and shrank, as the account's picture. */
1750
+ uploadPicture(data, signal) {
1751
+ return call((options) => account.profile.picture.$put({ json: { data } }, options), cloudPictureResponseSchema, signal);
1752
+ },
1753
+ removePicture(signal) {
1754
+ return call((options) => account.profile.picture.$delete(void 0, options), cloudAccountMutationResponseSchema, signal);
1755
+ },
1756
+ /** Sends a confirmation to the new address; the email changes once it is followed. */
1757
+ changeEmail(newEmail, callbackURL, signal) {
1758
+ return call((options) => account.profile.email.$post({ json: {
1759
+ newEmail,
1760
+ callbackURL
1761
+ } }, options), cloudAccountMutationResponseSchema, signal);
1762
+ },
1763
+ sessions(signal) {
1764
+ return call((options) => account.sessions.$get(void 0, options), cloudAccountSessionsResponseSchema, signal);
1765
+ },
1766
+ revokeSession(sessionId, signal) {
1767
+ return call((options) => account.sessions.revoke.$post({ json: { sessionId } }, options), cloudAccountMutationResponseSchema, signal);
1768
+ },
1769
+ revokeOtherSessions(signal) {
1770
+ return call((options) => account.sessions["revoke-others"].$post(void 0, options), cloudAccountMutationResponseSchema, signal);
1771
+ },
1772
+ signIns(signal) {
1773
+ return call((options) => account["sign-ins"].$get(void 0, options), cloudSignInsResponseSchema, signal);
1774
+ },
1775
+ unlinkAuthenticationMethod(methodId, signal) {
1776
+ return call((options) => account.authentication.unlink.$post({ json: { methodId } }, options), cloudAccountMutationResponseSchema, signal);
1777
+ }
1778
+ };
1779
+ }
1780
+ //#endregion
1781
+ //#region src/client/portal/administration.ts
1782
+ /** The query string for `request`; an empty search asks for everything. */
1783
+ function listQuery(request) {
1784
+ return { query: {
1785
+ search: request.search || void 0,
1786
+ filter: request.filter,
1787
+ limit: request.limit,
1788
+ offset: request.offset
1789
+ } };
1790
+ }
1791
+ function createAdministrationAPI(call, { admin, api }) {
1792
+ return {
1793
+ session(signal) {
1794
+ return call((options) => api.session.$get(void 0, options), cloudAdminSessionResponseSchema, signal);
1795
+ },
1796
+ enrollments(request, signal) {
1797
+ return call((options) => admin.enrollments.$get(listQuery(request), options), enrollmentsResponseSchema, signal);
1798
+ },
1799
+ reviewEnrollment(id, action, note, signal) {
1800
+ return call((options) => admin.enrollments[":id"][action].$post({
1801
+ param: { id },
1802
+ json: { note }
1803
+ }, options), enrollmentReviewResponseSchema, signal);
1804
+ },
1805
+ users(request, signal) {
1806
+ return call((options) => admin.users.$get(listQuery(request), options), cloudAdminUsersResponseSchema, signal);
1807
+ },
1808
+ user(id, signal) {
1809
+ return call((options) => admin.users[":id"].$get({ param: { id } }, options), cloudAdminUserDetailSchema, signal);
1810
+ },
1811
+ userAction(action, userId, reason, signal) {
1812
+ return call((options) => admin.users[action].$post({ json: {
1813
+ userId,
1814
+ reason
1815
+ } }, options), adminMutationResponseSchema, signal);
1816
+ },
1817
+ setAdmin(userId, enabled, signal) {
1818
+ return call((options) => admin.users["set-admin"].$post({ json: {
1819
+ userId,
1820
+ enabled
1821
+ } }, options), adminMutationResponseSchema, signal);
1822
+ },
1823
+ email(request, signal) {
1824
+ return call((options) => admin.email.$get(listQuery(request), options), adminEmailResponseSchema, signal);
1825
+ },
1826
+ regenerateEmail(id, signal) {
1827
+ return call((options) => admin.email[":id"].regenerate.$post({ param: { id } }, options), adminMutationResponseSchema, signal);
1828
+ },
1829
+ audit(request, signal) {
1830
+ return call((options) => admin.audit.$get(listQuery(request), options), adminAuditResponseSchema, signal);
1831
+ },
1832
+ operations(signal) {
1833
+ return call((options) => admin.operations.$get(void 0, options), adminOperationsResponseSchema, signal);
1834
+ }
1835
+ };
1836
+ }
1837
+ //#endregion
1838
+ //#region src/client/portal/request.ts
1839
+ var CloudPortalAPIError = class extends Error {
1840
+ kind;
1841
+ code;
1842
+ name = "CloudPortalAPIError";
1843
+ constructor(kind, code, options) {
1844
+ super(kind, options);
1845
+ this.kind = kind;
1846
+ this.code = code;
1847
+ }
1848
+ };
1849
+ /**
1850
+ * Sends a request and reads its answer the same way for every portal route: transport failures,
1851
+ * missing sessions and permissions, and domain errors become `CloudPortalAPIError`, and a success
1852
+ * body is checked against the contract.
1853
+ */
1854
+ function createCloudCall(options = {}) {
1855
+ const timeoutMs = options.timeoutMs ?? 1e4;
1856
+ return async (send, schema, callerSignal) => {
1857
+ const timeout = AbortSignal.timeout(timeoutMs);
1858
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
1859
+ let response;
1860
+ try {
1861
+ response = await send({ init: { signal } });
1862
+ } catch (cause) {
1863
+ if (callerSignal?.aborted) throw new CloudPortalAPIError("cancelled", void 0, { cause });
1864
+ if (timeout.aborted) throw new CloudPortalAPIError("timeout", void 0, { cause });
1865
+ throw new CloudPortalAPIError("network", void 0, { cause });
1866
+ }
1867
+ if (response.status === 401) throw new CloudPortalAPIError("authentication-required");
1868
+ let body;
1869
+ try {
1870
+ body = await response.json();
1871
+ } catch (cause) {
1872
+ if (response.status === 403) throw new CloudPortalAPIError("authorization-required");
1873
+ throw new CloudPortalAPIError("protocol", void 0, { cause });
1874
+ }
1875
+ if (!response.ok) {
1876
+ const accountError = v.safeParse(accountSecurityErrorResponseSchema, body);
1877
+ const adminError = v.safeParse(adminErrorResponseSchema, body);
1878
+ let code;
1879
+ if (accountError.success) code = accountError.output.error.code;
1880
+ else if (adminError.success) code = adminError.output.error.code;
1881
+ if (response.status === 403 && (!code || code === "forbidden")) throw new CloudPortalAPIError("authorization-required");
1882
+ throw new CloudPortalAPIError("domain", code);
1883
+ }
1884
+ const parsed = v.safeParse(schema, body);
1885
+ if (!parsed.success) throw new CloudPortalAPIError("protocol", void 0, { cause: parsed.issues });
1886
+ return parsed.output;
1887
+ };
1888
+ }
1889
+ /** Typed clients for the routes the portal calls, all on the server's own address. */
1890
+ function createPortalRouteClients(options = {}) {
1891
+ const origin = options.baseURL ?? globalThis.location.origin;
1892
+ const clientOptions = {
1893
+ fetch: options.fetch,
1894
+ headers: { Accept: "application/json" },
1895
+ init: { credentials: "include" }
1896
+ };
1897
+ return {
1898
+ account: hc(origin, clientOptions).api.account,
1899
+ admin: hc(new URL("/api/admin", origin).href, clientOptions),
1900
+ api: hc(new URL("/api", origin).href, clientOptions)
1901
+ };
1902
+ }
1903
+ //#endregion
1904
+ //#region src/client/portal/client.ts
1905
+ /** The account and administration routes Cloud's own web pages use, validated against the contract. */
1906
+ function createCloudPortalClient(options = {}) {
1907
+ const call = createCloudCall(options);
1908
+ const routes = createPortalRouteClients(options);
1909
+ return {
1910
+ ...createAccountAPI(call, routes),
1911
+ ...createAdministrationAPI(call, routes)
1912
+ };
1913
+ }
1914
+ //#endregion
1915
+ export { CloudAIError, CloudAPIError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, cloudAIFetch, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudSignInURL, createCloudAIClient, createCloudAPIClient, createCloudAuthClient, createCloudPortalClient, discoverCloud, pollCloudDeviceToken, requestCloudDeviceAuthorization, resendCloudVerification, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail };
1916
+
1917
+ //# sourceMappingURL=client.js.map