@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
@@ -0,0 +1,1453 @@
1
+ import { isValid } from "js-base64";
2
+ import * as v from "valibot";
3
+ import { zipObject } from "es-toolkit";
4
+ import { Inflate, deflateSync } from "fflate";
5
+ import * as decoding from "lib0/decoding";
6
+ import * as encoding from "lib0/encoding";
7
+ import * as Y from "yjs";
8
+ import { encodeParam, parseURL, withFragment, withQuery } from "ufo";
9
+ //#region src/contract/account.ts
10
+ const cloudAccountStateSchema = v.picklist([
11
+ "active",
12
+ "pending",
13
+ "rejected",
14
+ "revoked"
15
+ ]);
16
+ const cloudIdentitySchema = v.object({
17
+ userId: v.string(),
18
+ email: v.pipe(v.string(), v.email()),
19
+ name: v.string(),
20
+ /** The account's picture, such as one a social provider gave it. */
21
+ image: v.optional(v.nullable(v.string())),
22
+ deploymentRole: v.optional(v.picklist(["user", "admin"]))
23
+ });
24
+ const cloudAccountStatusResponseSchema = v.object({
25
+ user: cloudIdentitySchema,
26
+ state: cloudAccountStateSchema
27
+ });
28
+ const cloudAuthenticationProviderSchema = v.picklist([
29
+ "credential",
30
+ "google",
31
+ "apple"
32
+ ]);
33
+ const cloudAuthenticationMethodSchema = v.object({
34
+ id: v.string(),
35
+ provider: cloudAuthenticationProviderSchema,
36
+ createdAt: v.string(),
37
+ canUnlink: v.boolean()
38
+ });
39
+ const cloudAuthenticationMethodsResponseSchema = v.object({
40
+ methods: v.array(cloudAuthenticationMethodSchema),
41
+ availableSocialProviders: v.array(v.picklist(["google", "apple"]))
42
+ });
43
+ const cloudPasswordChangeSchema = v.object({
44
+ currentPassword: v.string(),
45
+ newPassword: v.string()
46
+ });
47
+ const cloudSocialLinkSchema = v.object({
48
+ provider: v.picklist(["google", "apple"]),
49
+ callbackURL: v.pipe(v.string(), v.url())
50
+ });
51
+ const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) });
52
+ const cloudUnlinkAuthenticationMethodSchema = v.object({ methodId: v.string() });
53
+ const accountSecurityErrorCodeSchema = v.picklist([
54
+ "current_password_invalid",
55
+ "password_too_short",
56
+ "password_too_long",
57
+ "last_authentication_method",
58
+ "session_not_fresh",
59
+ "authentication_method_failed",
60
+ "email_unchanged",
61
+ "email_change_unavailable",
62
+ "current_session",
63
+ "picture_invalid"
64
+ ]);
65
+ const accountSecurityErrorResponseSchema = v.object({ error: v.object({ code: accountSecurityErrorCodeSchema }) });
66
+ const cloudMFAStatusSchema = v.object({
67
+ required: v.boolean(),
68
+ enabled: v.boolean(),
69
+ totpEnabled: v.boolean(),
70
+ assured: v.boolean(),
71
+ totpAvailable: v.boolean(),
72
+ passkeysAvailable: v.boolean(),
73
+ recoveryCodesAvailable: v.boolean()
74
+ });
75
+ const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema });
76
+ const cloudMFAEnableSchema = v.object({ password: v.optional(v.string()) });
77
+ const cloudMFAEnableResponseSchema = v.object({
78
+ totpURI: v.string(),
79
+ backupCodes: v.array(v.string())
80
+ });
81
+ const cloudMFAVerifySchema = v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) });
82
+ const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) });
83
+ const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) });
84
+ const cloudPasskeySchema = v.object({
85
+ id: v.string(),
86
+ name: v.nullish(v.string()),
87
+ createdAt: v.string()
88
+ });
89
+ const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) });
90
+ const cloudPasskeyDeleteSchema = v.object({ id: v.string() });
91
+ function parseCloudMFAEnable(input) {
92
+ return v.parse(cloudMFAEnableSchema, input);
93
+ }
94
+ function parseCloudMFAVerify(input) {
95
+ return v.parse(cloudMFAVerifySchema, input);
96
+ }
97
+ function parseCloudPasskeyDelete(input) {
98
+ return v.parse(cloudPasskeyDeleteSchema, input);
99
+ }
100
+ function parseCloudPasswordChange(input) {
101
+ return v.parse(cloudPasswordChangeSchema, input);
102
+ }
103
+ function parseCloudSocialLink(input) {
104
+ return v.parse(cloudSocialLinkSchema, input);
105
+ }
106
+ function parseCloudUnlinkAuthenticationMethod(input) {
107
+ return v.parse(cloudUnlinkAuthenticationMethodSchema, input);
108
+ }
109
+ const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
110
+ /** Who an account belongs to, as the portal shows it. */
111
+ const cloudPersonSchema = v.object({
112
+ id: v.string(),
113
+ name: v.string(),
114
+ email: v.pipe(v.string(), v.email()),
115
+ /** The address of the account's picture, which the server serves; null shows initials. */
116
+ image: v.nullable(v.string())
117
+ });
118
+ /** What a person can see and change about themselves. */
119
+ const cloudProfileSchema = v.object({
120
+ ...cloudPersonSchema.entries,
121
+ createdAt: v.string(),
122
+ /** Whether the server can send the verification a new email address needs. */
123
+ emailChangeAvailable: v.boolean()
124
+ });
125
+ const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema });
126
+ const cloudProfileUpdateSchema = v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
127
+ /** The largest picture an account may upload, once the page has cropped and shrunk it. */
128
+ const CLOUD_PICTURE_MAX_BYTES = 262144;
129
+ /** The width and height a page shrinks a picture to before it uploads it. */
130
+ const CLOUD_PICTURE_SIZE = 256;
131
+ const cloudPictureUploadSchema = v.object({
132
+ /** The picture's PNG or JPEG bytes, in Base64. */
133
+ data: v.pipe(v.string(), v.maxLength(Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4), v.check((value) => isValid(value))) });
134
+ /** The address the account's picture is now served from. */
135
+ const cloudPictureResponseSchema = v.object({ image: v.string() });
136
+ const cloudEmailChangeSchema = v.object({
137
+ newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
138
+ callbackURL: v.pipe(v.string(), v.url())
139
+ });
140
+ /** How a sign-in was made: the method it used, or the desktop app's approved code. */
141
+ const cloudSignInMethodSchema = v.picklist([
142
+ "password",
143
+ "google",
144
+ "apple",
145
+ "passkey",
146
+ "two-step",
147
+ "email-link",
148
+ "desktop",
149
+ "other"
150
+ ]);
151
+ const cloudAccountSessionSchema = v.object({
152
+ id: v.string(),
153
+ /** The session this request was made with. */
154
+ current: v.boolean(),
155
+ method: v.nullable(cloudSignInMethodSchema),
156
+ ipAddress: v.nullable(v.string()),
157
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
158
+ browser: v.nullable(v.string()),
159
+ system: v.nullable(v.string()),
160
+ createdAt: v.string(),
161
+ lastActiveAt: v.string(),
162
+ expiresAt: v.string()
163
+ });
164
+ const cloudAccountSessionsResponseSchema = v.object({ sessions: v.array(cloudAccountSessionSchema) });
165
+ const cloudSessionRevokeSchema = v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) });
166
+ const cloudSignInSchema = v.object({
167
+ id: v.string(),
168
+ method: cloudSignInMethodSchema,
169
+ ipAddress: v.nullable(v.string()),
170
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
171
+ browser: v.nullable(v.string()),
172
+ system: v.nullable(v.string()),
173
+ createdAt: v.string()
174
+ });
175
+ const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) });
176
+ function parseCloudProfileUpdate(input) {
177
+ return v.parse(cloudProfileUpdateSchema, input);
178
+ }
179
+ function parseCloudPictureUpload(input) {
180
+ return v.parse(cloudPictureUploadSchema, input);
181
+ }
182
+ function parseCloudEmailChange(input) {
183
+ return v.parse(cloudEmailChangeSchema, input);
184
+ }
185
+ function parseCloudSessionRevoke(input) {
186
+ return v.parse(cloudSessionRevokeSchema, input);
187
+ }
188
+ //#endregion
189
+ //#region src/contract/ai.ts
190
+ /**
191
+ * The contract between editors, Cloud, and an AI service. Cloud only advertises the service and
192
+ * signs short-lived tokens for it; the service, official or self-hosted, proxies models and keeps
193
+ * the credit wallet. It is versioned apart from the Cloud protocol so a service can change without
194
+ * a Cloud release.
195
+ */
196
+ const CLOUD_AI_CONTRACT_VERSION = "1";
197
+ /** The `aud` of every token Cloud signs for an AI service. */
198
+ const CLOUD_AI_TOKEN_AUDIENCE = "openpencil-ai";
199
+ /** Where Cloud publishes the public keys an AI service verifies its tokens with. */
200
+ const CLOUD_AI_JWKS_PATH = "/.well-known/jwks.json";
201
+ /**
202
+ * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat
203
+ * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.
204
+ */
205
+ const CLOUD_AI_API_PATHS = {
206
+ base: "/v1",
207
+ chatCompletions: "/v1/chat/completions",
208
+ catalog: "/v1/catalog",
209
+ wallet: "/v1/wallet",
210
+ usage: "/v1/usage"
211
+ };
212
+ const urlSchema = v.pipe(v.string(), v.url());
213
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
214
+ const cloudAIDiscoverySchema = v.object({
215
+ endpoint: urlSchema,
216
+ contractVersion: v.literal("1")
217
+ });
218
+ const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
219
+ const createAITokenSchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
220
+ function parseCreateAIToken(input) {
221
+ return v.parse(createAITokenSchema, input);
222
+ }
223
+ const aiTokenSchema = v.object({
224
+ token: v.pipe(v.string(), v.minLength(1)),
225
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
226
+ });
227
+ /** What an AI service may rely on once a token's signature, issuer, audience, and expiry check. */
228
+ const aiTokenClaimsSchema = v.object({
229
+ iss: urlSchema,
230
+ aud: v.literal(CLOUD_AI_TOKEN_AUDIENCE),
231
+ sub: v.pipe(v.string(), v.minLength(1)),
232
+ workspaceId: v.pipe(v.string(), v.uuid()),
233
+ /** Credits the workspace's plan grants each month; `null` when Cloud sets no allowance. */
234
+ monthlyCreditAllowance: v.nullable(creditsSchema),
235
+ iat: v.pipe(v.number(), v.integer()),
236
+ exp: v.pipe(v.number(), v.integer())
237
+ });
238
+ const aiModelSchema = v.object({
239
+ id: v.pipe(v.string(), v.minLength(1)),
240
+ label: v.pipe(v.string(), v.minLength(1)),
241
+ /** Credits per million input and output tokens. */
242
+ creditsPerMillionInputTokens: creditsSchema,
243
+ creditsPerMillionOutputTokens: creditsSchema,
244
+ contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
245
+ capabilities: v.object({
246
+ reasoning: v.boolean(),
247
+ vision: v.boolean(),
248
+ tools: v.boolean()
249
+ })
250
+ });
251
+ const aiCatalogSchema = v.object({
252
+ models: v.array(aiModelSchema),
253
+ defaultModelID: v.pipe(v.string(), v.minLength(1))
254
+ });
255
+ const aiCreditBucketSchema = v.object({
256
+ kind: v.picklist([
257
+ "allowance",
258
+ "purchased",
259
+ "grant"
260
+ ]),
261
+ remaining: creditsSchema,
262
+ expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
263
+ });
264
+ /**
265
+ * A service records a request's charge before the request's answer ends, so a wallet read after
266
+ * an answer includes what it cost.
267
+ */
268
+ const aiWalletSchema = v.object({
269
+ /** Credits left to spend; `null` when the service sets no limit. */
270
+ balance: v.nullable(creditsSchema),
271
+ /** Spent first to last. */
272
+ buckets: v.array(aiCreditBucketSchema)
273
+ });
274
+ const aiUsageEntrySchema = v.object({
275
+ id: v.pipe(v.string(), v.minLength(1)),
276
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
277
+ kind: v.picklist([
278
+ "model",
279
+ "image",
280
+ "search"
281
+ ]),
282
+ modelID: v.nullable(v.string()),
283
+ userId: v.pipe(v.string(), v.minLength(1)),
284
+ credits: creditsSchema
285
+ });
286
+ const aiUsageQuerySchema = v.object({ cursor: v.optional(v.pipe(v.string(), v.minLength(1))) });
287
+ function parseAIUsageQuery(input) {
288
+ return v.parse(aiUsageQuerySchema, input);
289
+ }
290
+ const aiUsagePageSchema = v.object({
291
+ entries: v.array(aiUsageEntrySchema),
292
+ next: v.nullable(v.string())
293
+ });
294
+ /** Errors an AI service answers with, beside the upstream model's own. */
295
+ const aiErrorCodeSchema = v.picklist([
296
+ "unauthorized",
297
+ "insufficient_credits",
298
+ "model_not_allowed",
299
+ "rate_limited"
300
+ ]);
301
+ const aiErrorSchema = v.object({ error: v.object({
302
+ code: aiErrorCodeSchema,
303
+ message: v.optional(v.string()),
304
+ /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
305
+ resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
306
+ }) });
307
+ const AI_ERROR_STATUS = {
308
+ unauthorized: 401,
309
+ insufficient_credits: 402,
310
+ model_not_allowed: 403,
311
+ rate_limited: 429
312
+ };
313
+ //#endregion
314
+ //#region src/contract/workspaces.ts
315
+ const workspaceRoleSchema = v.picklist([
316
+ "viewer",
317
+ "editor",
318
+ "admin"
319
+ ]);
320
+ const workspaceSummarySchema = v.object({
321
+ id: v.pipe(v.string(), v.uuid()),
322
+ name: v.string(),
323
+ slug: v.string(),
324
+ role: workspaceRoleSchema,
325
+ createdAt: v.string(),
326
+ updatedAt: v.string()
327
+ });
328
+ const createWorkspaceSchema = v.object({
329
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
330
+ slug: v.optional(v.pipe(v.string(), v.trim(), v.minLength(3), v.maxLength(63), v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)))
331
+ });
332
+ const workspaceListSchema = v.object({ workspaces: v.array(workspaceSummarySchema) });
333
+ const updateWorkspaceSchema = v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
334
+ /** Someone who belongs to a workspace, and what they may do in it. */
335
+ const workspaceMemberSchema = v.object({
336
+ userId: v.string(),
337
+ name: v.string(),
338
+ email: v.string(),
339
+ image: v.nullable(v.string()),
340
+ role: workspaceRoleSchema,
341
+ joinedAt: v.string()
342
+ });
343
+ /** An invitation to join a workspace that has not been accepted yet. */
344
+ const workspaceInvitationSchema = v.object({
345
+ id: v.pipe(v.string(), v.uuid()),
346
+ email: v.string(),
347
+ role: workspaceRoleSchema,
348
+ /** Who sent it; the name is null once their account is gone. */
349
+ invitedBy: v.object({
350
+ id: v.string(),
351
+ name: v.nullable(v.string())
352
+ }),
353
+ invitedAt: v.string(),
354
+ expiresAt: v.string()
355
+ });
356
+ const workspaceMembersSchema = v.object({
357
+ members: v.array(workspaceMemberSchema),
358
+ /** Only administrators see pending invitations. */
359
+ invitations: v.array(workspaceInvitationSchema)
360
+ });
361
+ const createWorkspaceInvitationSchema = v.object({
362
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
363
+ role: workspaceRoleSchema
364
+ });
365
+ /** A new invitation and its link, for an administrator to pass on when email is off. */
366
+ const createdWorkspaceInvitationSchema = v.object({
367
+ invitation: workspaceInvitationSchema,
368
+ acceptanceURL: v.string()
369
+ });
370
+ const updateWorkspaceMemberSchema = v.object({ role: workspaceRoleSchema });
371
+ function parseCreateWorkspace(input) {
372
+ return v.parse(createWorkspaceSchema, input);
373
+ }
374
+ function parseUpdateWorkspace(input) {
375
+ return v.parse(updateWorkspaceSchema, input);
376
+ }
377
+ function parseCreateWorkspaceInvitation(input) {
378
+ return v.parse(createWorkspaceInvitationSchema, input);
379
+ }
380
+ function parseUpdateWorkspaceMember(input) {
381
+ return v.parse(updateWorkspaceMemberSchema, input);
382
+ }
383
+ //#endregion
384
+ //#region src/contract/admin/index.ts
385
+ const timestampSchema = v.pipe(v.string(), v.isoTimestamp());
386
+ const nullableTimestampSchema = v.nullable(timestampSchema);
387
+ const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
388
+ /**
389
+ * What every admin list answers besides its rows: how many rows match the search and filter
390
+ * across every page, and how many match the search under each filter.
391
+ */
392
+ function listTotals(filters) {
393
+ return {
394
+ total: countSchema,
395
+ counts: v.object(zipObject(filters, filters.map(() => countSchema)))
396
+ };
397
+ }
398
+ const adminErrorCodeSchema = v.picklist([
399
+ "bad_request",
400
+ "unauthorized",
401
+ "forbidden",
402
+ "not_found",
403
+ "rate_limited",
404
+ "invalid_enrollment_transition",
405
+ "last_admin_required",
406
+ "self_admin_action_forbidden",
407
+ "email_regeneration_unavailable",
408
+ "mfa_required"
409
+ ]);
410
+ const adminErrorResponseSchema = v.object({ error: v.object({ code: adminErrorCodeSchema }) });
411
+ const enrollmentStatusSchema = v.picklist([
412
+ "pending",
413
+ "approved",
414
+ "rejected",
415
+ "revoked"
416
+ ]);
417
+ const enrollmentSchema = v.object({
418
+ id: v.string(),
419
+ email: v.pipe(v.string(), v.email()),
420
+ name: v.nullable(v.string()),
421
+ reason: v.nullable(v.string()),
422
+ status: enrollmentStatusSchema,
423
+ requestedAt: timestampSchema,
424
+ reviewedAt: nullableTimestampSchema,
425
+ reviewedBy: v.nullable(v.string()),
426
+ /** The reviewer's name, in lists, while the server still knows them. */
427
+ reviewerName: v.optional(v.nullable(v.string())),
428
+ reviewNote: v.nullable(v.string()),
429
+ approvedUserId: v.nullable(v.string()),
430
+ requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))
431
+ });
432
+ const enrollmentsResponseSchema = v.object({
433
+ enrollments: v.array(enrollmentSchema),
434
+ ...listTotals(enrollmentStatusSchema.options)
435
+ });
436
+ const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema });
437
+ const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema });
438
+ const cloudAdminUserSchema = v.object({
439
+ ...cloudPersonSchema.entries,
440
+ role: v.optional(v.string()),
441
+ banned: v.nullable(v.boolean()),
442
+ banReason: v.optional(v.nullable(v.string())),
443
+ createdAt: timestampSchema,
444
+ /** An authenticator app or a passkey confirms this account's sign-ins. */
445
+ twoStep: v.boolean(),
446
+ /** When one of the account's sessions was last used, or null when none is left. */
447
+ lastActiveAt: nullableTimestampSchema,
448
+ workspaceCount: countSchema
449
+ });
450
+ /** Which accounts a list of people shows. */
451
+ const cloudAdminUserFilterSchema = v.picklist([
452
+ "all",
453
+ "administrators",
454
+ "suspended",
455
+ "without-two-step"
456
+ ]);
457
+ const cloudAdminUsersResponseSchema = v.object({
458
+ users: v.array(cloudAdminUserSchema),
459
+ ...listTotals(cloudAdminUserFilterSchema.options)
460
+ });
461
+ const cloudAdminUserDetailSchema = v.object({
462
+ user: v.object({
463
+ ...cloudAdminUserSchema.entries,
464
+ emailVerified: v.boolean()
465
+ }),
466
+ methods: v.array(v.object({
467
+ provider: v.string(),
468
+ createdAt: timestampSchema
469
+ })),
470
+ authenticator: v.boolean(),
471
+ passkeyCount: countSchema,
472
+ sessions: v.array(cloudAccountSessionSchema),
473
+ signIns: v.array(cloudSignInSchema),
474
+ workspaces: v.array(v.object({
475
+ id: v.string(),
476
+ name: v.string(),
477
+ role: workspaceRoleSchema,
478
+ memberCount: countSchema,
479
+ joinedAt: timestampSchema
480
+ }))
481
+ });
482
+ const adminMutationResponseSchema = v.object({ ok: v.literal(true) });
483
+ const transactionalEmailAdminSchema = v.object({
484
+ id: v.string(),
485
+ kind: v.string(),
486
+ recipientEmailNormalized: v.pipe(v.string(), v.email()),
487
+ status: v.string(),
488
+ attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
489
+ nextAttemptAt: timestampSchema,
490
+ transport: v.nullable(v.string()),
491
+ transportMessageId: v.nullable(v.string()),
492
+ lastErrorCode: v.nullable(v.string()),
493
+ createdAt: timestampSchema,
494
+ acceptedAt: nullableTimestampSchema,
495
+ regeneratable: v.boolean()
496
+ });
497
+ /** Which messages a list of email shows, by how their delivery went. */
498
+ const cloudAdminEmailFilterSchema = v.picklist([
499
+ "all",
500
+ "sent",
501
+ "waiting",
502
+ "failed"
503
+ ]);
504
+ const adminEmailResponseSchema = v.object({
505
+ messages: v.array(transactionalEmailAdminSchema),
506
+ ...listTotals(cloudAdminEmailFilterSchema.options)
507
+ });
508
+ /** Who or what an event names; `name` is null once the server no longer knows it. */
509
+ const auditPartySchema = v.object({
510
+ id: v.string(),
511
+ name: v.nullable(v.string())
512
+ });
513
+ const adminAuditEventSchema = v.object({
514
+ id: v.string(),
515
+ actor: auditPartySchema,
516
+ action: v.string(),
517
+ /** What the event is about: an account, an access request, or an email. */
518
+ subject: v.object({
519
+ ...auditPartySchema.entries,
520
+ type: v.string()
521
+ }),
522
+ metadata: v.unknown(),
523
+ createdAt: timestampSchema
524
+ });
525
+ /** Which events a list of activity shows, by what they are about. */
526
+ const cloudAdminAuditFilterSchema = v.picklist([
527
+ "all",
528
+ "accounts",
529
+ "requests",
530
+ "email"
531
+ ]);
532
+ const adminAuditResponseSchema = v.object({
533
+ events: v.array(adminAuditEventSchema),
534
+ ...listTotals(cloudAdminAuditFilterSchema.options)
535
+ });
536
+ const adminOperationsResponseSchema = v.object({
537
+ deployment: v.picklist(["official", "self-hosted"]),
538
+ enrollmentMode: v.picklist([
539
+ "open",
540
+ "approval",
541
+ "closed"
542
+ ]),
543
+ emailTransport: v.picklist([
544
+ "none",
545
+ "smtp",
546
+ "cloudflare"
547
+ ]),
548
+ pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),
549
+ pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
550
+ failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
551
+ accounts: countSchema,
552
+ workspaces: countSchema,
553
+ documents: countSchema,
554
+ storedBytes: countSchema
555
+ });
556
+ //#endregion
557
+ //#region src/contract/documents.ts
558
+ const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
559
+ const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
560
+ /** Whether a value is a SHA-256 checksum as the server names stored objects, base64 encoded. */
561
+ function isCloudChecksum(value) {
562
+ return v.is(checksumSchema, value);
563
+ }
564
+ /** The most images one revision, or one request for image uploads, may name. */
565
+ const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
566
+ /**
567
+ * An image's name inside a `.fig` file that Cloud stores apart from it: the SHA-1 Figma names it
568
+ * by, or an older plain name. A client leaves images under other names inside the file.
569
+ */
570
+ const CLOUD_IMAGE_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
571
+ const imageNameSchema = v.pipe(v.string(), v.regex(CLOUD_IMAGE_NAME_PATTERN));
572
+ const objectDownloadSchema = v.object({
573
+ url: v.pipe(v.string(), v.url()),
574
+ method: v.literal("GET"),
575
+ headers: v.record(v.string(), v.string()),
576
+ expiresAt: v.string()
577
+ });
578
+ /** An image a stored revision uses, where to download it, and what to check it against. */
579
+ const documentImageDownloadSchema = v.object({
580
+ name: imageNameSchema,
581
+ checksum: checksumSchema,
582
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
583
+ download: objectDownloadSchema
584
+ });
585
+ /** Where to download an image a document uses, found by its checksum. */
586
+ const documentImageLinkSchema = v.object({
587
+ checksum: checksumSchema,
588
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
589
+ download: objectDownloadSchema
590
+ });
591
+ /** The images a live room names, by checksum, that a peer needs links for. */
592
+ const requestImageLinksSchema = v.object({ checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
593
+ const documentPermissionSchema = v.picklist(["view", "edit"]);
594
+ const documentAccessSourceSchema = v.picklist([
595
+ "owner",
596
+ "workspace",
597
+ "direct-grant"
598
+ ]);
599
+ const documentAccessSchema = v.object({
600
+ permission: documentPermissionSchema,
601
+ canManageSharing: v.boolean(),
602
+ sources: v.array(documentAccessSourceSchema)
603
+ });
604
+ /** What a document is: a Figma design or a FigJam board, which the file it stores says too. */
605
+ const documentKindSchema = v.picklist(["design", "board"]);
606
+ const documentSummarySchema = v.object({
607
+ id: v.pipe(v.string(), v.uuid()),
608
+ workspaceId: v.pipe(v.string(), v.uuid()),
609
+ name: v.string(),
610
+ /** A design unless said otherwise; servers from before boards list no kind. */
611
+ kind: v.optional(documentKindSchema, "design"),
612
+ currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
613
+ version: v.number(),
614
+ createdAt: v.string(),
615
+ updatedAt: v.string()
616
+ });
617
+ /** A document someone granted the person directly, in a workspace they are not a member of. */
618
+ const sharedDocumentSchema = v.object({
619
+ ...documentSummarySchema.entries,
620
+ workspaceName: v.string(),
621
+ permission: documentPermissionSchema,
622
+ sharedBy: v.nullable(v.object({ name: v.string() })),
623
+ sharedAt: v.string()
624
+ });
625
+ const documentDownloadSchema = v.object({
626
+ document: documentSummarySchema,
627
+ revisionId: v.pipe(v.string(), v.uuid()),
628
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
629
+ checksum: checksumSchema,
630
+ contentType: v.string(),
631
+ download: objectDownloadSchema,
632
+ /** The images the stored file leaves out, which a client puts back under their names. */
633
+ images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
634
+ });
635
+ const cloudActorSchema = v.object({
636
+ userId: v.string(),
637
+ email: v.pipe(v.string(), v.email()),
638
+ name: v.string()
639
+ });
640
+ const cloudSessionSchema = v.object({ user: cloudActorSchema });
641
+ const workspaceUsageSchema = v.object({
642
+ bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
643
+ objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
644
+ documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
645
+ });
646
+ const CLOUD_DOCUMENT_NAME_MAX_LENGTH = 255;
647
+ const createDocumentSchema = v.object({
648
+ id: v.optional(v.pipe(v.string(), v.uuid())),
649
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)),
650
+ /** A design unless said otherwise; older clients create only designs. */
651
+ kind: v.optional(documentKindSchema, "design")
652
+ });
653
+ const createUploadSchema = v.object({
654
+ baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
655
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
656
+ checksum: checksumSchema,
657
+ contentType: v.literal("application/octet-stream")
658
+ });
659
+ const imageSizeSchema = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES));
660
+ /** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */
661
+ const objectUploadSchema = v.variant("kind", [v.object({
662
+ kind: v.literal("single"),
663
+ url: v.pipe(v.string(), v.url()),
664
+ method: v.literal("PUT"),
665
+ headers: v.record(v.string(), v.string()),
666
+ expiresAt: v.string()
667
+ }), v.object({
668
+ kind: v.literal("multipart"),
669
+ uploadId: v.string(),
670
+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
671
+ parts: v.array(v.object({
672
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
673
+ url: v.pipe(v.string(), v.url()),
674
+ method: v.literal("PUT"),
675
+ headers: v.record(v.string(), v.string())
676
+ })),
677
+ expiresAt: v.string()
678
+ })]);
679
+ /** An upload the server offers for an image the workspace lacks. */
680
+ const imageUploadOfferSchema = v.object({
681
+ checksum: checksumSchema,
682
+ uploadId: v.pipe(v.string(), v.uuid()),
683
+ upload: objectUploadSchema
684
+ });
685
+ /** The images a save will refer to; the server answers with uploads for those it lacks. */
686
+ const requestImageUploadsSchema = v.object({ images: v.pipe(v.array(v.object({
687
+ checksum: checksumSchema,
688
+ byteSize: imageSizeSchema
689
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
690
+ const completedUploadPartSchema = v.object({
691
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
692
+ etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
693
+ });
694
+ const commitUploadSchema = v.object({
695
+ checksum: checksumSchema,
696
+ /** The document title captured with this revision; omitted by older clients. */
697
+ name: v.optional(createDocumentSchema.entries.name),
698
+ /** What the uploaded file is, which the document takes; omitted by older clients. */
699
+ kind: v.optional(documentKindSchema),
700
+ multipart: v.optional(v.object({
701
+ uploadId: v.pipe(v.string(), v.minLength(1)),
702
+ parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(1e4))
703
+ })),
704
+ /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */
705
+ images: v.optional(v.pipe(v.array(v.object({
706
+ name: imageNameSchema,
707
+ checksum: checksumSchema
708
+ })), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)), [])
709
+ });
710
+ /** The image uploads a save asked for, committed together once their bytes are in place. */
711
+ const commitImageUploadsSchema = v.object({ uploads: v.pipe(v.array(v.object({
712
+ uploadId: v.pipe(v.string(), v.uuid()),
713
+ checksum: checksumSchema,
714
+ multipart: commitUploadSchema.entries.multipart
715
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
716
+ function parseCreateDocument(input) {
717
+ return v.parse(createDocumentSchema, input);
718
+ }
719
+ function parseCreateUpload(input) {
720
+ return v.parse(createUploadSchema, input);
721
+ }
722
+ function parseRequestImageUploads(input) {
723
+ return v.parse(requestImageUploadsSchema, input);
724
+ }
725
+ function parseCommitImageUploads(input) {
726
+ return v.parse(commitImageUploadsSchema, input);
727
+ }
728
+ function parseRequestImageLinks(input) {
729
+ return v.parse(requestImageLinksSchema, input);
730
+ }
731
+ function parseCommitUpload(input) {
732
+ return v.parse(commitUploadSchema, input);
733
+ }
734
+ //#endregion
735
+ //#region src/contract/collaboration.ts
736
+ const collaborationPrincipalSchema = v.variant("kind", [v.object({
737
+ kind: v.literal("user"),
738
+ userId: v.string(),
739
+ name: v.string(),
740
+ email: v.pipe(v.string(), v.email())
741
+ }), v.object({
742
+ kind: v.literal("guest"),
743
+ guestId: v.string(),
744
+ name: v.string()
745
+ })]);
746
+ /**
747
+ * Who the relay verified a peer to be, as it writes into that peer's presence under `cloud`, so
748
+ * other peers can trust it over what the peer says of itself.
749
+ */
750
+ const cloudPresenceSchema = v.object({
751
+ kind: v.picklist(["user", "guest"]),
752
+ id: v.string(),
753
+ name: v.string(),
754
+ permission: documentPermissionSchema
755
+ });
756
+ const collaborationTicketSchema = v.object({
757
+ token: v.string(),
758
+ provider: v.optional(v.picklist(["trystero", "relay"])),
759
+ serverURL: v.optional(v.pipe(v.string(), v.url())),
760
+ documentId: v.pipe(v.string(), v.uuid()),
761
+ roomId: v.string(),
762
+ roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
763
+ principal: collaborationPrincipalSchema,
764
+ permission: documentPermissionSchema,
765
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
766
+ expiresAt: v.string(),
767
+ serverEnforcedWrites: v.boolean()
768
+ });
769
+ //#endregion
770
+ //#region src/contract/relay.ts
771
+ /** Where the relay accepts WebSocket upgrades, under the Cloud API origin. */
772
+ const RELAY_PATH = "/api/collaboration/relay";
773
+ /**
774
+ * The relay URL's query parameter naming the ticket's document, so a runtime that keeps each
775
+ * document's room in its own place can route the socket there before the ticket arrives.
776
+ */
777
+ const RELAY_DOCUMENT_PARAM = "document";
778
+ /** The relay's public URL on the same origin as the API, unless the deployment names another. */
779
+ function defaultRelayURL(publicURL) {
780
+ const url = new URL(RELAY_PATH, publicURL);
781
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
782
+ return url.href;
783
+ }
784
+ /**
785
+ * The room messages collaboration sends. The relay reads the document ones to keep its copy,
786
+ * persist it, and drop writes from viewers; it forwards the rest unread.
787
+ */
788
+ const COLLAB_ACTIONS = {
789
+ yjsUpdate: "yjs-update",
790
+ syncStep1: "sync-step1",
791
+ syncReply: "sync-reply",
792
+ awareness: "awareness",
793
+ agentPreview: "agent-preview",
794
+ upload: "upload",
795
+ /** From the server only: the document's version history changed, so open lists load it again. */
796
+ versions: "versions"
797
+ };
798
+ /**
799
+ * The most a room message may decode to, compressed or not. A peer's update past it is dropped
800
+ * before it is decoded, so a small compressed reply cannot expand without bound.
801
+ */
802
+ const MAX_COLLAB_MESSAGE_BYTES = 268435456;
803
+ /**
804
+ * What a peer joining needs is the whole document, which repeats the same field names across
805
+ * every layer, so the reply to its state vector travels compressed; Yjs's V2 encoding already
806
+ * groups that repetition, and together they make a room's first sync about a twelfth the size.
807
+ * Edits travel as V2 updates uncompressed: they are small, and arrive in a stream.
808
+ */
809
+ function encodeSyncReply(document, stateVector) {
810
+ return deflateSync(Y.encodeStateAsUpdateV2(document, stateVector));
811
+ }
812
+ /**
813
+ * Compressed input is inflated this much at a time, so a reply stops within a step of passing
814
+ * the limit: deflate expands at most about 1,032 times, so a step can overshoot by about 16 MB.
815
+ */
816
+ const INFLATE_STEP = 16384;
817
+ /**
818
+ * The V2 update a peer sent, inflated first when `compressed`, as a sync reply is; null once it
819
+ * would decode past `limit` bytes. Throws on data that does not inflate.
820
+ */
821
+ function decodeRoomUpdate(data, { limit, compressed = false }) {
822
+ if (!compressed) return data.length <= limit ? data : null;
823
+ const chunks = [];
824
+ let size = 0;
825
+ const inflate = new Inflate((chunk) => {
826
+ size += chunk.length;
827
+ if (size <= limit) chunks.push(chunk);
828
+ });
829
+ for (let offset = 0; offset < data.length; offset += INFLATE_STEP) {
830
+ inflate.push(data.subarray(offset, offset + INFLATE_STEP), offset + INFLATE_STEP >= data.length);
831
+ if (size > limit) return null;
832
+ }
833
+ const inflated = new Uint8Array(size);
834
+ let at = 0;
835
+ for (const chunk of chunks) {
836
+ inflated.set(chunk, at);
837
+ at += chunk.length;
838
+ }
839
+ return inflated;
840
+ }
841
+ /** The peer ID the relay itself uses: it holds the room's document and answers sync requests. */
842
+ const RELAY_SERVER_PEER = "server";
843
+ /** The longest name a peer's presence may carry; peers drop presence with a longer one. */
844
+ const MAX_PRESENCE_NAME_LENGTH = 40;
845
+ /** A name as presence carries it: trimmed and cut to what every peer accepts. */
846
+ function presenceName(name) {
847
+ return name.trim().slice(0, 40);
848
+ }
849
+ /**
850
+ * Close codes in the WebSocket application range. A client reconnects with a fresh ticket after
851
+ * `expired`, and gives up on the others.
852
+ */
853
+ const RELAY_CLOSE = {
854
+ unauthorized: 4401,
855
+ expired: 4403,
856
+ roomFull: 4409,
857
+ messageTooLarge: 4413,
858
+ protocol: 4400,
859
+ /** The document was restored to a version, so its room started over under a new ID. */
860
+ restored: 4410
861
+ };
862
+ const CLIENT_AUTH = 0;
863
+ const CLIENT_MESSAGE = 1;
864
+ const CLIENT_FRAGMENT = 2;
865
+ const SERVER_WELCOME = 0;
866
+ const SERVER_JOIN = 1;
867
+ const SERVER_LEAVE = 2;
868
+ const SERVER_MESSAGE = 3;
869
+ const SERVER_FRAGMENT = 4;
870
+ /**
871
+ * The most one WebSocket message carries. A frame past it travels as fragments of this size that
872
+ * the receiver joins again, so a large paste or a room's first sync fits under any host's message
873
+ * cap, such as the 32 MiB of Cloudflare Workers, and the relay can turn away a viewer's or an
874
+ * unadmitted peer's large frame before holding it whole.
875
+ */
876
+ const RELAY_FRAGMENT_BYTES = 262144;
877
+ /** The smallest per-message limit a relay may set: one fragment and its few bytes of framing. */
878
+ const RELAY_MINIMUM_MESSAGE_BYTES = 262160;
879
+ /**
880
+ * What the relay adds to a frame it forwards: the frame type, the sender's peer ID, and lengths.
881
+ * A client reads frames this much past the relay's own limit, so a forwarded edit at that limit
882
+ * still arrives.
883
+ */
884
+ const RELAY_FORWARDING_BYTES = 65536;
885
+ /** Encodes into a buffer of its own, which `WebSocket.send` accepts. */
886
+ function toSendable(write) {
887
+ return new Uint8Array(encoding.encode(write));
888
+ }
889
+ function encodeRelayClientFrame(frame) {
890
+ return toSendable((encoder) => {
891
+ if (frame.type === "auth") {
892
+ encoding.writeVarUint(encoder, CLIENT_AUTH);
893
+ encoding.writeVarString(encoder, frame.token);
894
+ return;
895
+ }
896
+ encoding.writeVarUint(encoder, CLIENT_MESSAGE);
897
+ encoding.writeVarString(encoder, frame.namespace);
898
+ encoding.writeVarString(encoder, frame.target ?? "");
899
+ encoding.writeVarUint8Array(encoder, frame.payload);
900
+ });
901
+ }
902
+ function encodeRelayServerFrame(frame) {
903
+ return toSendable((encoder) => {
904
+ switch (frame.type) {
905
+ case "welcome":
906
+ encoding.writeVarUint(encoder, SERVER_WELCOME);
907
+ encoding.writeVarString(encoder, frame.peerId);
908
+ encoding.writeVarUint(encoder, frame.peers.length);
909
+ for (const peer of frame.peers) encoding.writeVarString(encoder, peer);
910
+ return;
911
+ case "join":
912
+ case "leave":
913
+ encoding.writeVarUint(encoder, frame.type === "join" ? SERVER_JOIN : SERVER_LEAVE);
914
+ encoding.writeVarString(encoder, frame.peerId);
915
+ return;
916
+ case "message":
917
+ encoding.writeVarUint(encoder, SERVER_MESSAGE);
918
+ encoding.writeVarString(encoder, frame.namespace);
919
+ encoding.writeVarString(encoder, frame.from);
920
+ encoding.writeVarUint8Array(encoder, frame.payload);
921
+ }
922
+ });
923
+ }
924
+ /** The frame as it goes over the socket: itself, or fragments of it when it is large. */
925
+ function fragments(tag, frame) {
926
+ if (frame.byteLength <= 262144) return [frame];
927
+ const parts = [];
928
+ for (let offset = 0; offset < frame.byteLength; offset += RELAY_FRAGMENT_BYTES) {
929
+ const end = Math.min(offset + RELAY_FRAGMENT_BYTES, frame.byteLength);
930
+ parts.push(toSendable((encoder) => {
931
+ encoding.writeVarUint(encoder, tag);
932
+ encoding.writeVarUint(encoder, end < frame.byteLength ? 1 : 0);
933
+ encoding.writeVarUint8Array(encoder, frame.subarray(offset, end));
934
+ }));
935
+ }
936
+ return parts;
937
+ }
938
+ /** A client frame as the socket messages that carry it, in order. */
939
+ function relayClientMessages(frame) {
940
+ return fragments(CLIENT_FRAGMENT, encodeRelayClientFrame(frame));
941
+ }
942
+ /** A server frame as the socket messages that carry it, in order. */
943
+ function relayServerMessages(frame) {
944
+ return fragments(SERVER_FRAGMENT, encodeRelayServerFrame(frame));
945
+ }
946
+ /**
947
+ * Joins one socket's fragments into the frames they carry. A socket sends a frame's fragments in
948
+ * a row, so a whole frame arriving between them is malformed. `limit` caps the joined frame and is
949
+ * read for every message, so it can follow what the sender may do.
950
+ */
951
+ function createAssembler(tag, limit) {
952
+ let parts = [];
953
+ let size = 0;
954
+ /** Set while the rest of a refused frame arrives, so its tail never reads as a frame of its own. */
955
+ let discarding = false;
956
+ const reset = () => {
957
+ parts = [];
958
+ size = 0;
959
+ };
960
+ return { push(data) {
961
+ let decoder;
962
+ let type;
963
+ try {
964
+ decoder = decoding.createDecoder(data);
965
+ type = decoding.readVarUint(decoder);
966
+ } catch {
967
+ reset();
968
+ return { type: "malformed" };
969
+ }
970
+ if (type !== tag) {
971
+ if (parts.length > 0) {
972
+ reset();
973
+ return { type: "malformed" };
974
+ }
975
+ return {
976
+ type: "frame",
977
+ data
978
+ };
979
+ }
980
+ let more;
981
+ let chunk;
982
+ try {
983
+ more = decoding.readVarUint(decoder);
984
+ chunk = decoding.readVarUint8Array(decoder);
985
+ } catch {
986
+ reset();
987
+ discarding = true;
988
+ return { type: "malformed" };
989
+ }
990
+ if (decoder.pos !== data.byteLength || more > 1) {
991
+ reset();
992
+ discarding = more !== 0;
993
+ return { type: "malformed" };
994
+ }
995
+ if (discarding) {
996
+ discarding = more === 1;
997
+ return { type: "partial" };
998
+ }
999
+ size += chunk.byteLength;
1000
+ if (size > limit()) {
1001
+ reset();
1002
+ discarding = more === 1;
1003
+ return { type: "too-large" };
1004
+ }
1005
+ parts.push(chunk.slice());
1006
+ if (more === 1) return { type: "partial" };
1007
+ const joined = new Uint8Array(size);
1008
+ let at = 0;
1009
+ for (const part of parts) {
1010
+ joined.set(part, at);
1011
+ at += part.byteLength;
1012
+ }
1013
+ reset();
1014
+ return {
1015
+ type: "frame",
1016
+ data: joined
1017
+ };
1018
+ } };
1019
+ }
1020
+ /** Joins the fragments a client sends; the relay holds one per socket. */
1021
+ function createRelayClientAssembler(limit) {
1022
+ return createAssembler(CLIENT_FRAGMENT, limit);
1023
+ }
1024
+ /** Joins the fragments the relay sends; a client holds one per socket. */
1025
+ function createRelayServerAssembler(limit) {
1026
+ return createAssembler(SERVER_FRAGMENT, limit);
1027
+ }
1028
+ /**
1029
+ * lib0 reads byte arrays as views of the underlying buffer, which can run past the end of the
1030
+ * frame's own view, as with pooled socket buffers. A frame is valid only when decoding consumed
1031
+ * exactly its bytes, and payloads are copied out of the shared buffer.
1032
+ */
1033
+ function complete(decoder, data, frame) {
1034
+ return decoder.pos === data.byteLength ? frame : null;
1035
+ }
1036
+ function readPayload(decoder) {
1037
+ return decoding.readVarUint8Array(decoder).slice();
1038
+ }
1039
+ /** Returns null for a frame that is malformed or of an unknown type. */
1040
+ function decodeRelayClientFrame(data) {
1041
+ try {
1042
+ const decoder = decoding.createDecoder(data);
1043
+ const type = decoding.readVarUint(decoder);
1044
+ if (type === CLIENT_AUTH) return complete(decoder, data, {
1045
+ type: "auth",
1046
+ token: decoding.readVarString(decoder)
1047
+ });
1048
+ if (type !== CLIENT_MESSAGE) return null;
1049
+ const namespace = decoding.readVarString(decoder);
1050
+ const target = decoding.readVarString(decoder);
1051
+ const payload = readPayload(decoder);
1052
+ return complete(decoder, data, {
1053
+ type: "message",
1054
+ namespace,
1055
+ target: target || null,
1056
+ payload
1057
+ });
1058
+ } catch {
1059
+ return null;
1060
+ }
1061
+ }
1062
+ /** Returns null for a frame that is malformed or of an unknown type. */
1063
+ function decodeRelayServerFrame(data) {
1064
+ try {
1065
+ const decoder = decoding.createDecoder(data);
1066
+ switch (decoding.readVarUint(decoder)) {
1067
+ case SERVER_WELCOME: {
1068
+ const peerId = decoding.readVarString(decoder);
1069
+ const count = decoding.readVarUint(decoder);
1070
+ const peers = [];
1071
+ for (let index = 0; index < count; index++) peers.push(decoding.readVarString(decoder));
1072
+ return complete(decoder, data, {
1073
+ type: "welcome",
1074
+ peerId,
1075
+ peers
1076
+ });
1077
+ }
1078
+ case SERVER_JOIN: return complete(decoder, data, {
1079
+ type: "join",
1080
+ peerId: decoding.readVarString(decoder)
1081
+ });
1082
+ case SERVER_LEAVE: return complete(decoder, data, {
1083
+ type: "leave",
1084
+ peerId: decoding.readVarString(decoder)
1085
+ });
1086
+ case SERVER_MESSAGE: return complete(decoder, data, {
1087
+ type: "message",
1088
+ namespace: decoding.readVarString(decoder),
1089
+ from: decoding.readVarString(decoder),
1090
+ payload: readPayload(decoder)
1091
+ });
1092
+ default: return null;
1093
+ }
1094
+ } catch {
1095
+ return null;
1096
+ }
1097
+ }
1098
+ //#endregion
1099
+ //#region src/contract/entitlements.ts
1100
+ const workspaceEntitlementsSchema = v.object({
1101
+ features: v.object({
1102
+ links: v.boolean(),
1103
+ guestView: v.boolean(),
1104
+ guestEdit: v.boolean(),
1105
+ guestPresence: v.boolean(),
1106
+ collaboration: v.boolean(),
1107
+ revisionHistory: v.boolean(),
1108
+ cloudAI: v.optional(v.boolean(), false)
1109
+ }),
1110
+ limits: v.object({
1111
+ maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
1112
+ maximumStorageBytes: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
1113
+ maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
1114
+ monthlyCreditAllowance: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), null)
1115
+ }),
1116
+ usage: v.object({
1117
+ committedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0)),
1118
+ reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
1119
+ })
1120
+ });
1121
+ //#endregion
1122
+ //#region src/contract/discovery.ts
1123
+ const CLOUD_PROTOCOL_VERSION = "1";
1124
+ const CLOUD_DISCOVERY_PATH = "/.well-known/openpencil";
1125
+ const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
1126
+ const cloudAuthenticationSchema = v.object({
1127
+ emailPassword: v.optional(v.object({
1128
+ signIn: v.boolean(),
1129
+ signUp: v.boolean(),
1130
+ minimumPasswordLength: v.pipe(v.number(), v.integer(), v.minValue(8)),
1131
+ captcha: v.optional(v.object({
1132
+ provider: v.literal("cloudflare-turnstile"),
1133
+ siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
1134
+ }))
1135
+ })),
1136
+ socialProviders: v.array(v.picklist(["apple", "google"])),
1137
+ enterpriseSSO: v.boolean(),
1138
+ enrollmentMode: v.optional(v.picklist([
1139
+ "open",
1140
+ "approval",
1141
+ "closed"
1142
+ ]), "open"),
1143
+ mfa: v.optional(v.object({
1144
+ deploymentAdminRequired: v.boolean(),
1145
+ totp: v.boolean(),
1146
+ passkeys: v.boolean(),
1147
+ recoveryCodes: v.boolean()
1148
+ }))
1149
+ });
1150
+ const cloudCapabilitiesSchema = v.object({
1151
+ documents: v.boolean(),
1152
+ workspaces: v.boolean(),
1153
+ collaboration: v.boolean()
1154
+ });
1155
+ /** A released editor version, `major.minor.patch`. */
1156
+ const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
1157
+ /**
1158
+ * Whether editors offer this server to everyone, and from which editor version on. Only the
1159
+ * official server's listing is read: it turns the Cloud entry points on without an editor release,
1160
+ * and an editor older than the minimum keeps them hidden.
1161
+ */
1162
+ const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema });
1163
+ const cloudDiscoverySchema = v.object({
1164
+ protocolVersion: v.literal("1"),
1165
+ deployment: cloudDeploymentSchema,
1166
+ apiURL: v.pipe(v.string(), v.url()),
1167
+ authURL: v.pipe(v.string(), v.url()),
1168
+ /** Whether the server's own editor works with files on this device without signing in. */
1169
+ localEditor: v.optional(v.boolean(), true),
1170
+ authentication: cloudAuthenticationSchema,
1171
+ capabilities: cloudCapabilitiesSchema,
1172
+ listing: v.optional(cloudListingSchema),
1173
+ /** The AI service editors reach with Cloud-signed tokens; absent when the deployment has none. */
1174
+ ai: v.optional(cloudAIDiscoverySchema),
1175
+ /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
1176
+ billing: v.optional(cloudBillingDiscoverySchema)
1177
+ });
1178
+ /** The server's own address, where its editor and pages are, from its auth API's. */
1179
+ function cloudServerOrigin(discovery) {
1180
+ return new URL(discovery.authURL).origin;
1181
+ }
1182
+ function parseCloudDiscovery(input) {
1183
+ return v.parse(cloudDiscoverySchema, input);
1184
+ }
1185
+ //#endregion
1186
+ //#region src/contract/sharing.ts
1187
+ const documentShareSchema = v.object({
1188
+ id: v.pipe(v.string(), v.uuid()),
1189
+ documentId: v.pipe(v.string(), v.uuid()),
1190
+ permission: documentPermissionSchema,
1191
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
1192
+ createdBy: v.string(),
1193
+ createdAt: v.string(),
1194
+ updatedAt: v.string(),
1195
+ expiresAt: v.nullable(v.string()),
1196
+ revokedAt: v.nullable(v.string()),
1197
+ lastUsedAt: v.nullable(v.string())
1198
+ });
1199
+ /** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
1200
+ const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())));
1201
+ const createDocumentShareSchema = v.object({
1202
+ permission: documentPermissionSchema,
1203
+ expiresAt: shareExpirySchema
1204
+ });
1205
+ const updateDocumentShareSchema = v.object({
1206
+ permission: v.optional(documentPermissionSchema),
1207
+ expiresAt: shareExpirySchema
1208
+ });
1209
+ const resolveDocumentShareSchema = v.object({
1210
+ secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
1211
+ guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
1212
+ guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
1213
+ });
1214
+ /** A guest's request for the links of images a shared document's live room names. */
1215
+ const requestSharedImageLinksSchema = v.object({
1216
+ ...resolveDocumentShareSchema.entries,
1217
+ ...requestImageLinksSchema.entries
1218
+ });
1219
+ function parseRequestSharedImageLinks(input) {
1220
+ return v.parse(requestSharedImageLinksSchema, input);
1221
+ }
1222
+ const resolvedDocumentShareSchema = v.object({
1223
+ documentId: v.pipe(v.string(), v.uuid()),
1224
+ permission: documentPermissionSchema,
1225
+ principal: collaborationPrincipalSchema,
1226
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))
1227
+ });
1228
+ const cloudUserProfileSchema = v.object({
1229
+ id: v.string(),
1230
+ name: v.string(),
1231
+ email: v.pipe(v.string(), v.email()),
1232
+ image: v.nullable(v.pipe(v.string(), v.url()))
1233
+ });
1234
+ const documentGrantSchema = v.object({
1235
+ id: v.pipe(v.string(), v.uuid()),
1236
+ documentId: v.pipe(v.string(), v.uuid()),
1237
+ userId: v.string(),
1238
+ permission: documentPermissionSchema,
1239
+ createdBy: v.string(),
1240
+ createdAt: v.string(),
1241
+ updatedAt: v.string()
1242
+ });
1243
+ /** What accepting an invitation gave: access to a document, or a place in a workspace. */
1244
+ const acceptedInvitationSchema = v.variant("kind", [v.object({
1245
+ kind: v.literal("document"),
1246
+ grant: documentGrantSchema
1247
+ }), v.object({
1248
+ kind: v.literal("workspace"),
1249
+ workspaceId: v.pipe(v.string(), v.uuid()),
1250
+ role: workspaceRoleSchema
1251
+ })]);
1252
+ const lookupCloudUserSchema = v.object({ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()) });
1253
+ const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema });
1254
+ const createDocumentInvitationSchema = v.object({
1255
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
1256
+ permission: documentPermissionSchema
1257
+ });
1258
+ const acceptDocumentInvitationSchema = v.object({ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128)) });
1259
+ const createInvitationContinuationSchema = v.object({
1260
+ invitationId: v.pipe(v.string(), v.uuid()),
1261
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
1262
+ });
1263
+ const invitationContinuationSchema = v.object({ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128)) });
1264
+ const invitationPreviewFields = {
1265
+ inviterName: v.string(),
1266
+ expiresAt: v.string(),
1267
+ recipientHint: v.string()
1268
+ };
1269
+ /** What an invitation link opens: one document, or a whole workspace. */
1270
+ const invitationPreviewSchema = v.variant("kind", [v.object({
1271
+ kind: v.literal("document"),
1272
+ documentName: v.string(),
1273
+ permission: documentPermissionSchema,
1274
+ ...invitationPreviewFields
1275
+ }), v.object({
1276
+ kind: v.literal("workspace"),
1277
+ workspaceName: v.string(),
1278
+ role: workspaceRoleSchema,
1279
+ ...invitationPreviewFields
1280
+ })]);
1281
+ const documentInvitationSchema = v.object({
1282
+ id: v.pipe(v.string(), v.uuid()),
1283
+ documentId: v.pipe(v.string(), v.uuid()),
1284
+ email: v.pipe(v.string(), v.email()),
1285
+ permission: documentPermissionSchema,
1286
+ invitedBy: v.string(),
1287
+ invitedAt: v.string(),
1288
+ expiresAt: v.string(),
1289
+ acceptedAt: v.nullable(v.string())
1290
+ });
1291
+ function parseCreateInvitationContinuation(input) {
1292
+ return v.parse(createInvitationContinuationSchema, input);
1293
+ }
1294
+ function parseLookupCloudUser(input) {
1295
+ return v.parse(lookupCloudUserSchema, input);
1296
+ }
1297
+ function parseCreateDocumentShare(input) {
1298
+ return v.parse(createDocumentShareSchema, input);
1299
+ }
1300
+ function parseUpdateDocumentShare(input) {
1301
+ return v.parse(updateDocumentShareSchema, input);
1302
+ }
1303
+ function parseResolveDocumentShare(input) {
1304
+ return v.parse(resolveDocumentShareSchema, input);
1305
+ }
1306
+ function parsePutDocumentGrant(input) {
1307
+ return v.parse(putDocumentGrantSchema, input);
1308
+ }
1309
+ function parseCreateDocumentInvitation(input) {
1310
+ return v.parse(createDocumentInvitationSchema, input);
1311
+ }
1312
+ function parseAcceptDocumentInvitation(input) {
1313
+ return v.parse(acceptDocumentInvitationSchema, input);
1314
+ }
1315
+ //#endregion
1316
+ //#region src/contract/links.ts
1317
+ const CLOUD_LINK_PATH = /^\/(invitations|share|documents)\/([^/]+)$/;
1318
+ /**
1319
+ * A link on the server's own editor. The server is the link's own address, so the link needs
1320
+ * nothing else to name it; a secret travels in the fragment, so it never reaches access logs or
1321
+ * `Referer` headers.
1322
+ */
1323
+ function serverLink(serverURL, path, query = {}, secret) {
1324
+ const { protocol, host } = parseURL(serverURL);
1325
+ if (protocol !== "https:" && protocol !== "http:") throw new Error("A Cloud server address must use HTTP or HTTPS");
1326
+ const link = withQuery(`${protocol}//${host}${path}`, query);
1327
+ return secret ? withFragment(link, secret) : link;
1328
+ }
1329
+ /** An invitation to a document or a workspace, `/invitations/:id#token`. */
1330
+ function cloudInvitationURL(serverURL, invitationId, token) {
1331
+ return serverLink(serverURL, `/invitations/${encodeParam(invitationId)}`, {}, token);
1332
+ }
1333
+ /** A document shared by link, `/share/:id#secret`. */
1334
+ function cloudShareURL(serverURL, shareId, secret) {
1335
+ return serverLink(serverURL, `/share/${encodeParam(shareId)}`, {}, secret);
1336
+ }
1337
+ /**
1338
+ * A document's address for its members, `/documents/:id`, or one of its versions with
1339
+ * `?version=…`. It carries no secret: whoever opens it signs in, and the server decides.
1340
+ */
1341
+ function cloudDocumentURL(serverURL, documentId, versionId = null) {
1342
+ return serverLink(serverURL, cloudDocumentPath(documentId), { version: versionId ?? void 0 });
1343
+ }
1344
+ function cloudDocumentPath(documentId) {
1345
+ return `/documents/${encodeParam(documentId)}`;
1346
+ }
1347
+ /**
1348
+ * The kind and ID of a Cloud link's path, or null for any other path. The ID is decoded; a broken
1349
+ * escape such as `%E0` is no link.
1350
+ */
1351
+ function parseCloudLinkPath(pathname) {
1352
+ const [, kind, id] = pathname.match(CLOUD_LINK_PATH) ?? [];
1353
+ if (kind !== "invitations" && kind !== "share" && kind !== "documents" || !id) return null;
1354
+ try {
1355
+ return {
1356
+ kind,
1357
+ id: decodeURIComponent(id)
1358
+ };
1359
+ } catch {
1360
+ return null;
1361
+ }
1362
+ }
1363
+ /**
1364
+ * The desktop app's form of a Cloud link, `openpencil://cloud?url=<link>#secret`: the web link,
1365
+ * whose address names the server, with its secret kept in the fragment.
1366
+ * `desktop/src/launch/links.rs` validates it before the editor sees it.
1367
+ */
1368
+ function cloudDesktopLinkURL(kind, id, serverURL, secret) {
1369
+ const link = serverLink(serverURL, `/${kind}/${encodeParam(id)}`);
1370
+ return withFragment(withQuery("openpencil://cloud", { url: link }), secret);
1371
+ }
1372
+ //#endregion
1373
+ //#region src/contract/portal.ts
1374
+ /**
1375
+ * The pages a Cloud server shows on its own address, apart from the editor: the welcome page for
1376
+ * visitors who are not signed in, sign-in and desktop sign-in approval, account settings, and the
1377
+ * administration console. Every runtime serves the portal's `cloud.html` at and below these
1378
+ * paths, and the editor's `index.html` at the root and at any other page the API does not answer.
1379
+ */
1380
+ const CLOUD_PORTAL_PAGE_ROOTS = [
1381
+ "/welcome",
1382
+ "/auth",
1383
+ "/account",
1384
+ "/admin"
1385
+ ];
1386
+ function isCloudPortalPage(path) {
1387
+ return CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`));
1388
+ }
1389
+ //#endregion
1390
+ //#region src/contract/versions.ts
1391
+ /** How long a version's name may be; the history list shows the start of longer ones. */
1392
+ const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100;
1393
+ const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1e3;
1394
+ /** A checkpoint the server kept on its own, or a version someone named. */
1395
+ const documentVersionKindSchema = v.picklist(["checkpoint", "named"]);
1396
+ const documentVersionSchema = v.object({
1397
+ id: v.pipe(v.string(), v.uuid()),
1398
+ revisionId: v.pipe(v.string(), v.uuid()),
1399
+ kind: documentVersionKindSchema,
1400
+ name: v.nullable(v.string()),
1401
+ description: v.nullable(v.string()),
1402
+ createdAt: v.string(),
1403
+ /** Who made the version: the author of a checkpoint's save, or who named or restored it. */
1404
+ createdBy: v.object({
1405
+ id: v.string(),
1406
+ name: v.nullable(v.string())
1407
+ }),
1408
+ /** The version this one restored, while that version is still in the history. */
1409
+ restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),
1410
+ /** Whether the document holds this version now. */
1411
+ current: v.boolean()
1412
+ });
1413
+ const documentVersionsSchema = v.object({
1414
+ versions: v.array(documentVersionSchema),
1415
+ /** Pass as `before` for the next, older page; null on the last one. */
1416
+ nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))
1417
+ });
1418
+ const versionNameSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));
1419
+ const versionDescriptionSchema = v.pipe(v.string(), v.trim(), v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH));
1420
+ /** Names the document as it is now, like Save to version history. */
1421
+ const saveDocumentVersionSchema = v.object({
1422
+ name: versionNameSchema,
1423
+ description: v.optional(versionDescriptionSchema, "")
1424
+ });
1425
+ /** Names a version or changes its name; a null name deletes its info and leaves a checkpoint. */
1426
+ const updateDocumentVersionSchema = v.object({
1427
+ name: v.nullable(versionNameSchema),
1428
+ description: v.optional(versionDescriptionSchema, "")
1429
+ });
1430
+ const duplicateDocumentVersionSchema = v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)) });
1431
+ const documentVersionResponseSchema = v.object({ version: documentVersionSchema });
1432
+ /** A version with where to download it, so a link to it can show it without the history. */
1433
+ const documentVersionDownloadSchema = v.object({
1434
+ document: documentDownloadSchema,
1435
+ version: documentVersionSchema
1436
+ });
1437
+ const restoredDocumentSchema = v.object({
1438
+ document: documentSummarySchema,
1439
+ version: documentVersionSchema
1440
+ });
1441
+ function parseSaveDocumentVersion(input) {
1442
+ return v.parse(saveDocumentVersionSchema, input);
1443
+ }
1444
+ function parseUpdateDocumentVersion(input) {
1445
+ return v.parse(updateDocumentVersionSchema, input);
1446
+ }
1447
+ function parseDuplicateDocumentVersion(input) {
1448
+ return v.parse(duplicateDocumentVersionSchema, input);
1449
+ }
1450
+ //#endregion
1451
+ export { AI_ERROR_STATUS, CLOUD_AI_API_PATHS, CLOUD_AI_CONTRACT_VERSION, CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_DISCOVERY_PATH, CLOUD_DOCUMENT_NAME_MAX_LENGTH, CLOUD_IMAGE_NAME_PATTERN, CLOUD_MAX_DOCUMENT_IMAGES, CLOUD_PICTURE_MAX_BYTES, CLOUD_PICTURE_SIZE, CLOUD_PORTAL_PAGE_ROOTS, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, CLOUD_PROTOCOL_VERSION, COLLAB_ACTIONS, DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH, DOCUMENT_VERSION_NAME_MAX_LENGTH, MAX_COLLAB_MESSAGE_BYTES, MAX_PRESENCE_NAME_LENGTH, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_FORWARDING_BYTES, RELAY_FRAGMENT_BYTES, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_PATH, RELAY_SERVER_PEER, acceptDocumentInvitationSchema, acceptedInvitationSchema, accountSecurityErrorCodeSchema, accountSecurityErrorResponseSchema, adminAuditEventSchema, adminAuditResponseSchema, adminEmailResponseSchema, adminErrorCodeSchema, adminErrorResponseSchema, adminMutationResponseSchema, adminOperationsResponseSchema, aiCatalogSchema, aiCreditBucketSchema, aiErrorCodeSchema, aiErrorSchema, aiModelSchema, aiTokenClaimsSchema, aiTokenSchema, aiUsageEntrySchema, aiUsagePageSchema, aiUsageQuerySchema, aiWalletSchema, cloudAIDiscoverySchema, cloudAccountMutationResponseSchema, cloudAccountSessionSchema, cloudAccountSessionsResponseSchema, cloudAccountStateSchema, cloudAccountStatusResponseSchema, cloudActorSchema, cloudAdminAuditFilterSchema, cloudAdminEmailFilterSchema, cloudAdminSessionResponseSchema, cloudAdminUserDetailSchema, cloudAdminUserFilterSchema, cloudAdminUserSchema, cloudAdminUsersResponseSchema, cloudAuthenticationMethodSchema, cloudAuthenticationMethodsResponseSchema, cloudAuthenticationProviderSchema, cloudAuthenticationSchema, cloudBillingDiscoverySchema, cloudCapabilitiesSchema, cloudDeploymentSchema, cloudDesktopLinkURL, cloudDiscoverySchema, cloudDocumentPath, cloudDocumentURL, cloudEditorVersionSchema, cloudEmailChangeSchema, cloudIdentitySchema, cloudInvitationURL, cloudListingSchema, cloudMFAEnableResponseSchema, cloudMFAEnableSchema, cloudMFARecoveryCodesResponseSchema, cloudMFAStatusResponseSchema, cloudMFAStatusSchema, cloudMFAVerifyResponseSchema, cloudMFAVerifySchema, cloudPasskeyDeleteSchema, cloudPasskeySchema, cloudPasskeysResponseSchema, cloudPasswordChangeSchema, cloudPersonSchema, cloudPictureResponseSchema, cloudPictureUploadSchema, cloudPresenceSchema, cloudProfileResponseSchema, cloudProfileSchema, cloudProfileUpdateSchema, cloudServerOrigin, cloudSessionRevokeSchema, cloudSessionSchema, cloudShareURL, cloudSignInMethodSchema, cloudSignInSchema, cloudSignInsResponseSchema, cloudSocialLinkResponseSchema, cloudSocialLinkSchema, cloudUnlinkAuthenticationMethodSchema, cloudUserProfileSchema, collaborationPrincipalSchema, collaborationTicketSchema, commitImageUploadsSchema, commitUploadSchema, createAITokenSchema, createDocumentInvitationSchema, createDocumentSchema, createDocumentShareSchema, createInvitationContinuationSchema, createRelayClientAssembler, createRelayServerAssembler, createUploadSchema, createWorkspaceInvitationSchema, createWorkspaceSchema, createdWorkspaceInvitationSchema, decodeRelayClientFrame, decodeRelayServerFrame, decodeRoomUpdate, defaultRelayURL, documentAccessSchema, documentAccessSourceSchema, documentDownloadSchema, documentGrantSchema, documentImageDownloadSchema, documentImageLinkSchema, documentInvitationSchema, documentPermissionSchema, documentShareSchema, documentSummarySchema, documentVersionDownloadSchema, documentVersionKindSchema, documentVersionResponseSchema, documentVersionSchema, documentVersionsSchema, duplicateDocumentVersionSchema, encodeRelayClientFrame, encodeRelayServerFrame, encodeSyncReply, enrollmentReviewResponseSchema, enrollmentSchema, enrollmentStatusSchema, enrollmentsResponseSchema, imageUploadOfferSchema, invitationContinuationSchema, invitationPreviewSchema, isCloudChecksum, isCloudPortalPage, lookupCloudUserSchema, objectUploadSchema, parseAIUsageQuery, parseAcceptDocumentInvitation, parseCloudDiscovery, parseCloudEmailChange, parseCloudLinkPath, parseCloudMFAEnable, parseCloudMFAVerify, parseCloudPasskeyDelete, parseCloudPasswordChange, parseCloudPictureUpload, parseCloudProfileUpdate, parseCloudSessionRevoke, parseCloudSocialLink, parseCloudUnlinkAuthenticationMethod, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateDocumentInvitation, parseCreateDocumentShare, parseCreateInvitationContinuation, parseCreateUpload, parseCreateWorkspace, parseCreateWorkspaceInvitation, parseDuplicateDocumentVersion, parseLookupCloudUser, parsePutDocumentGrant, parseRequestImageLinks, parseRequestImageUploads, parseRequestSharedImageLinks, parseResolveDocumentShare, parseSaveDocumentVersion, parseUpdateDocumentShare, parseUpdateDocumentVersion, parseUpdateWorkspace, parseUpdateWorkspaceMember, presenceName, putDocumentGrantSchema, relayClientMessages, relayServerMessages, requestImageLinksSchema, requestImageUploadsSchema, requestSharedImageLinksSchema, resolveDocumentShareSchema, resolvedDocumentShareSchema, restoredDocumentSchema, saveDocumentVersionSchema, sharedDocumentSchema, transactionalEmailAdminSchema, updateDocumentShareSchema, updateDocumentVersionSchema, updateWorkspaceMemberSchema, updateWorkspaceSchema, workspaceEntitlementsSchema, workspaceInvitationSchema, workspaceListSchema, workspaceMemberSchema, workspaceMembersSchema, workspaceRoleSchema, workspaceSummarySchema, workspaceUsageSchema };
1452
+
1453
+ //# sourceMappingURL=contract2.js.map