@neta-art/cohub-cli 10.23.0 → 10.25.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 (369) hide show
  1. package/README.md +18 -5
  2. package/bin/cohub.js +4 -1
  3. package/dist/board-gpu/page.js +1566 -71230
  4. package/dist/bootstrap.js +67 -27
  5. package/dist/build.json +1 -1
  6. package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
  7. package/dist/chunks/about.js +102 -0
  8. package/dist/chunks/app-realtime.js +2216 -0
  9. package/dist/chunks/app-realtime2.js +2 -0
  10. package/dist/chunks/app-ref.js +88 -0
  11. package/dist/chunks/apps.js +1423 -0
  12. package/dist/chunks/auth.js +175 -0
  13. package/dist/chunks/avatar.js +146 -0
  14. package/dist/chunks/board-export-resources.js +232 -0
  15. package/dist/chunks/board-export.js +874 -0
  16. package/dist/chunks/board-export2.js +2 -0
  17. package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
  18. package/dist/chunks/board-kernel2.js +4 -0
  19. package/dist/chunks/board-profile.js +69 -0
  20. package/dist/chunks/board-simulate.js +315 -0
  21. package/dist/chunks/board-time.js +34 -0
  22. package/dist/chunks/boards.js +1943 -0
  23. package/dist/{board-kernel → chunks}/browserAll.js +9 -8
  24. package/dist/chunks/channels.js +64 -0
  25. package/dist/chunks/client.js +12606 -0
  26. package/dist/chunks/command-input.js +17 -0
  27. package/dist/chunks/commander.js +2962 -0
  28. package/dist/chunks/cron-jobs.js +163 -0
  29. package/dist/chunks/daemon.js +545 -0
  30. package/dist/chunks/daemon2.js +2 -0
  31. package/dist/chunks/desktop.js +172 -0
  32. package/dist/chunks/endpoint-options.js +26 -0
  33. package/dist/chunks/env-proxy.js +35 -0
  34. package/dist/chunks/environment.js +154 -0
  35. package/dist/chunks/feedback.js +120 -0
  36. package/dist/chunks/generations.js +379 -0
  37. package/dist/chunks/host.js +9 -0
  38. package/dist/chunks/http-put.js +131 -0
  39. package/dist/chunks/id.js +2416 -0
  40. package/dist/{board-kernel → chunks}/init.js +1 -1
  41. package/dist/chunks/install.js +11959 -0
  42. package/dist/chunks/launch.js +374 -0
  43. package/dist/chunks/local-media.js +47 -0
  44. package/dist/chunks/me.js +134 -0
  45. package/dist/chunks/media.js +315 -0
  46. package/dist/chunks/models.js +242 -0
  47. package/dist/chunks/operands.js +46 -0
  48. package/dist/chunks/package-paths.js +13 -0
  49. package/dist/chunks/policy.js +221 -0
  50. package/dist/chunks/preferences.js +29 -0
  51. package/dist/chunks/profile.js +64 -0
  52. package/dist/chunks/prompts.js +41 -0
  53. package/dist/chunks/public.js +2 -0
  54. package/dist/chunks/public2.js +244 -0
  55. package/dist/chunks/references.js +197 -0
  56. package/dist/chunks/referrals.js +90 -0
  57. package/dist/chunks/rolldown-runtime.js +26 -0
  58. package/dist/chunks/rooms-connect.js +2 -0
  59. package/dist/chunks/rooms-connect2.js +151 -0
  60. package/dist/chunks/rooms-rtc.js +309 -0
  61. package/dist/chunks/rooms.js +211 -0
  62. package/dist/chunks/run.js +220 -0
  63. package/dist/chunks/runtime.js +638 -0
  64. package/dist/chunks/runtime2.js +286 -0
  65. package/dist/chunks/runtimes.js +48 -0
  66. package/dist/chunks/safe-remote-image.js +198 -0
  67. package/dist/chunks/schemas.js +6017 -0
  68. package/dist/chunks/search.js +113 -0
  69. package/dist/chunks/self-update.js +238 -0
  70. package/dist/chunks/serve.js +1246 -0
  71. package/dist/chunks/session-status.js +24 -0
  72. package/dist/chunks/skills.js +35 -0
  73. package/dist/chunks/spaces.js +5080 -0
  74. package/dist/chunks/src.js +405 -0
  75. package/dist/chunks/supervisor.js +2511 -0
  76. package/dist/chunks/supervisor2.js +2 -0
  77. package/dist/chunks/tasks.js +82 -0
  78. package/dist/chunks/themes.js +2898 -0
  79. package/dist/chunks/version.js +2 -0
  80. package/dist/chunks/version2.js +22 -0
  81. package/dist/chunks/version3.js +18 -0
  82. package/dist/chunks/web.js +7 -0
  83. package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
  84. package/dist/runtime/native/pi-extension.js +174 -166
  85. package/dist/runtime/worker.js +27 -16
  86. package/package.json +8 -9
  87. package/dist/about.d.ts +0 -2
  88. package/dist/about.js +0 -71
  89. package/dist/app-download.d.ts +0 -11
  90. package/dist/app-download.js +0 -252
  91. package/dist/app-ref.d.ts +0 -5
  92. package/dist/app-ref.js +0 -8
  93. package/dist/app-target.d.ts +0 -26
  94. package/dist/app-target.js +0 -55
  95. package/dist/auth.d.ts +0 -45
  96. package/dist/auth.js +0 -307
  97. package/dist/avatar.d.ts +0 -55
  98. package/dist/avatar.js +0 -104
  99. package/dist/board-command-support.d.ts +0 -6
  100. package/dist/board-command-support.js +0 -88
  101. package/dist/board-export-resources.d.ts +0 -12
  102. package/dist/board-export-resources.js +0 -51
  103. package/dist/board-export.d.ts +0 -110
  104. package/dist/board-export.js +0 -592
  105. package/dist/board-fonts.d.ts +0 -11
  106. package/dist/board-fonts.js +0 -10
  107. package/dist/board-gpu/daemon.d.ts +0 -11
  108. package/dist/board-gpu/daemon.js +0 -295
  109. package/dist/board-gpu/index.d.ts +0 -33
  110. package/dist/board-gpu/index.js +0 -189
  111. package/dist/board-gpu/protocol.d.ts +0 -77
  112. package/dist/board-gpu/protocol.js +0 -1
  113. package/dist/board-kernel.d.ts +0 -5
  114. package/dist/board-media-export.d.ts +0 -17
  115. package/dist/board-media-export.js +0 -164
  116. package/dist/board-media.d.ts +0 -5
  117. package/dist/board-media.js +0 -66
  118. package/dist/board-profile.d.ts +0 -21
  119. package/dist/board-profile.js +0 -67
  120. package/dist/board-simulate.d.ts +0 -67
  121. package/dist/board-simulate.js +0 -259
  122. package/dist/board-time.d.ts +0 -3
  123. package/dist/board-time.js +0 -34
  124. package/dist/bootstrap.d.ts +0 -2
  125. package/dist/client.d.ts +0 -5
  126. package/dist/client.js +0 -24
  127. package/dist/command-input.d.ts +0 -4
  128. package/dist/command-input.js +0 -16
  129. package/dist/commands/app-commerce.d.ts +0 -2
  130. package/dist/commands/app-commerce.js +0 -228
  131. package/dist/commands/app-domains.d.ts +0 -2
  132. package/dist/commands/app-domains.js +0 -133
  133. package/dist/commands/apps.d.ts +0 -4
  134. package/dist/commands/apps.js +0 -827
  135. package/dist/commands/auth.d.ts +0 -2
  136. package/dist/commands/auth.js +0 -186
  137. package/dist/commands/boards/authoring.d.ts +0 -2
  138. package/dist/commands/boards/authoring.js +0 -166
  139. package/dist/commands/boards/examples.d.ts +0 -10
  140. package/dist/commands/boards/examples.js +0 -118
  141. package/dist/commands/boards.d.ts +0 -13
  142. package/dist/commands/boards.js +0 -836
  143. package/dist/commands/channels.d.ts +0 -2
  144. package/dist/commands/channels.js +0 -74
  145. package/dist/commands/cron-jobs.d.ts +0 -2
  146. package/dist/commands/cron-jobs.js +0 -155
  147. package/dist/commands/decision.d.ts +0 -4
  148. package/dist/commands/decision.js +0 -113
  149. package/dist/commands/desktop.d.ts +0 -10
  150. package/dist/commands/desktop.js +0 -233
  151. package/dist/commands/feedback.d.ts +0 -2
  152. package/dist/commands/feedback.js +0 -131
  153. package/dist/commands/generations.d.ts +0 -2
  154. package/dist/commands/generations.js +0 -427
  155. package/dist/commands/host.d.ts +0 -2
  156. package/dist/commands/host.js +0 -11
  157. package/dist/commands/me.d.ts +0 -2
  158. package/dist/commands/me.js +0 -118
  159. package/dist/commands/models.d.ts +0 -28
  160. package/dist/commands/models.js +0 -271
  161. package/dist/commands/profile.d.ts +0 -2
  162. package/dist/commands/profile.js +0 -81
  163. package/dist/commands/prompts.d.ts +0 -2
  164. package/dist/commands/prompts.js +0 -37
  165. package/dist/commands/public.d.ts +0 -20
  166. package/dist/commands/public.js +0 -291
  167. package/dist/commands/references.d.ts +0 -2
  168. package/dist/commands/references.js +0 -193
  169. package/dist/commands/referrals.d.ts +0 -2
  170. package/dist/commands/referrals.js +0 -88
  171. package/dist/commands/rooms-connect.d.ts +0 -17
  172. package/dist/commands/rooms-connect.js +0 -140
  173. package/dist/commands/rooms-rtc-binary.d.ts +0 -2
  174. package/dist/commands/rooms-rtc-binary.js +0 -107
  175. package/dist/commands/rooms-rtc.d.ts +0 -21
  176. package/dist/commands/rooms-rtc.js +0 -171
  177. package/dist/commands/rooms.d.ts +0 -3
  178. package/dist/commands/rooms.js +0 -277
  179. package/dist/commands/run.d.ts +0 -13
  180. package/dist/commands/run.js +0 -246
  181. package/dist/commands/runtime.d.ts +0 -3
  182. package/dist/commands/runtime.js +0 -320
  183. package/dist/commands/sandboxd-binary.d.ts +0 -11
  184. package/dist/commands/sandboxd-binary.js +0 -238
  185. package/dist/commands/search.d.ts +0 -2
  186. package/dist/commands/search.js +0 -114
  187. package/dist/commands/session-access.d.ts +0 -2
  188. package/dist/commands/session-access.js +0 -70
  189. package/dist/commands/skills.d.ts +0 -2
  190. package/dist/commands/skills.js +0 -34
  191. package/dist/commands/space-activity.d.ts +0 -26
  192. package/dist/commands/space-activity.js +0 -147
  193. package/dist/commands/space-commerce.d.ts +0 -2
  194. package/dist/commands/space-commerce.js +0 -514
  195. package/dist/commands/space-displays.d.ts +0 -2
  196. package/dist/commands/space-displays.js +0 -620
  197. package/dist/commands/space-files.d.ts +0 -5
  198. package/dist/commands/space-files.js +0 -215
  199. package/dist/commands/space-invitations.d.ts +0 -29
  200. package/dist/commands/space-invitations.js +0 -189
  201. package/dist/commands/space-turns.d.ts +0 -49
  202. package/dist/commands/space-turns.js +0 -205
  203. package/dist/commands/space-wallet.d.ts +0 -2
  204. package/dist/commands/space-wallet.js +0 -64
  205. package/dist/commands/space-webhooks.d.ts +0 -7
  206. package/dist/commands/space-webhooks.js +0 -73
  207. package/dist/commands/spaces.d.ts +0 -25
  208. package/dist/commands/spaces.js +0 -2139
  209. package/dist/commands/tasks.d.ts +0 -8
  210. package/dist/commands/tasks.js +0 -80
  211. package/dist/commands/version.d.ts +0 -2
  212. package/dist/commands/version.js +0 -21
  213. package/dist/endpoint-options.d.ts +0 -4
  214. package/dist/endpoint-options.js +0 -26
  215. package/dist/env-proxy.d.ts +0 -5
  216. package/dist/env-proxy.js +0 -20
  217. package/dist/help-path.d.ts +0 -18
  218. package/dist/help-path.js +0 -223
  219. package/dist/host/auth.d.ts +0 -20
  220. package/dist/host/auth.js +0 -119
  221. package/dist/host/login-env.d.ts +0 -1
  222. package/dist/host/login-env.js +0 -31
  223. package/dist/host/runtime.d.ts +0 -35
  224. package/dist/host/runtime.js +0 -395
  225. package/dist/host/runtimes.d.ts +0 -9
  226. package/dist/host/runtimes.js +0 -42
  227. package/dist/host/serve.d.ts +0 -2
  228. package/dist/host/serve.js +0 -117
  229. package/dist/host/workspaces.d.ts +0 -2
  230. package/dist/host/workspaces.js +0 -18
  231. package/dist/http-put.d.ts +0 -25
  232. package/dist/http-put.js +0 -132
  233. package/dist/index.d.ts +0 -2
  234. package/dist/index.js +0 -129
  235. package/dist/launcher.d.ts +0 -4
  236. package/dist/launcher.js +0 -38
  237. package/dist/local-media.d.ts +0 -2
  238. package/dist/local-media.js +0 -30
  239. package/dist/network-error.d.ts +0 -3
  240. package/dist/network-error.js +0 -22
  241. package/dist/output.d.ts +0 -46
  242. package/dist/output.js +0 -244
  243. package/dist/runtime/archive-store.d.ts +0 -54
  244. package/dist/runtime/archive-store.js +0 -379
  245. package/dist/runtime/cli-path.d.ts +0 -5
  246. package/dist/runtime/cli-path.js +0 -27
  247. package/dist/runtime/codex-usage.d.ts +0 -7
  248. package/dist/runtime/codex-usage.js +0 -11
  249. package/dist/runtime/connection.d.ts +0 -42
  250. package/dist/runtime/connection.js +0 -789
  251. package/dist/runtime/diagnostics.d.ts +0 -107
  252. package/dist/runtime/diagnostics.js +0 -392
  253. package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
  254. package/dist/runtime/harnesses/chained-projection.js +0 -95
  255. package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
  256. package/dist/runtime/harnesses/chained-transcript.js +0 -62
  257. package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
  258. package/dist/runtime/harnesses/claude-approval.js +0 -124
  259. package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
  260. package/dist/runtime/harnesses/claude-transcript.js +0 -138
  261. package/dist/runtime/harnesses/claude.d.ts +0 -8
  262. package/dist/runtime/harnesses/claude.js +0 -225
  263. package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
  264. package/dist/runtime/harnesses/codex-approval.js +0 -69
  265. package/dist/runtime/harnesses/codex.d.ts +0 -4
  266. package/dist/runtime/harnesses/codex.js +0 -269
  267. package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
  268. package/dist/runtime/harnesses/cursor-transcript.js +0 -183
  269. package/dist/runtime/harnesses/cursor.d.ts +0 -24
  270. package/dist/runtime/harnesses/cursor.js +0 -620
  271. package/dist/runtime/harnesses/index.d.ts +0 -16
  272. package/dist/runtime/harnesses/index.js +0 -73
  273. package/dist/runtime/harnesses/pi.d.ts +0 -4
  274. package/dist/runtime/harnesses/pi.js +0 -247
  275. package/dist/runtime/harnesses/process.d.ts +0 -31
  276. package/dist/runtime/harnesses/process.js +0 -75
  277. package/dist/runtime/harnesses/stream-json.d.ts +0 -48
  278. package/dist/runtime/harnesses/stream-json.js +0 -336
  279. package/dist/runtime/harnesses/types.d.ts +0 -117
  280. package/dist/runtime/harnesses/types.js +0 -1
  281. package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
  282. package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
  283. package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
  284. package/dist/runtime/harnesses/workbuddy.js +0 -123
  285. package/dist/runtime/instance.d.ts +0 -20
  286. package/dist/runtime/instance.js +0 -247
  287. package/dist/runtime/json-rpc.d.ts +0 -53
  288. package/dist/runtime/json-rpc.js +0 -212
  289. package/dist/runtime/launch.d.ts +0 -25
  290. package/dist/runtime/launch.js +0 -247
  291. package/dist/runtime/local-workspace.d.ts +0 -15
  292. package/dist/runtime/local-workspace.js +0 -52
  293. package/dist/runtime/model-catalog.d.ts +0 -12
  294. package/dist/runtime/model-catalog.js +0 -84
  295. package/dist/runtime/native/adapters.d.ts +0 -15
  296. package/dist/runtime/native/adapters.js +0 -11
  297. package/dist/runtime/native/approvals.d.ts +0 -18
  298. package/dist/runtime/native/approvals.js +0 -54
  299. package/dist/runtime/native/archive.d.ts +0 -19
  300. package/dist/runtime/native/archive.js +0 -142
  301. package/dist/runtime/native/attach.d.ts +0 -36
  302. package/dist/runtime/native/attach.js +0 -128
  303. package/dist/runtime/native/codex-link.d.ts +0 -60
  304. package/dist/runtime/native/codex-link.js +0 -322
  305. package/dist/runtime/native/config.d.ts +0 -16
  306. package/dist/runtime/native/config.js +0 -24
  307. package/dist/runtime/native/daemon.d.ts +0 -92
  308. package/dist/runtime/native/daemon.js +0 -380
  309. package/dist/runtime/native/execution.d.ts +0 -26
  310. package/dist/runtime/native/execution.js +0 -34
  311. package/dist/runtime/native/identity.d.ts +0 -9
  312. package/dist/runtime/native/identity.js +0 -15
  313. package/dist/runtime/native/ingest.d.ts +0 -263
  314. package/dist/runtime/native/ingest.js +0 -884
  315. package/dist/runtime/native/install.d.ts +0 -9
  316. package/dist/runtime/native/install.js +0 -113
  317. package/dist/runtime/native/paths.d.ts +0 -2
  318. package/dist/runtime/native/paths.js +0 -7
  319. package/dist/runtime/native/pi-extension.d.ts +0 -36
  320. package/dist/runtime/native/pi-link.d.ts +0 -69
  321. package/dist/runtime/native/pi-link.js +0 -269
  322. package/dist/runtime/native/results.d.ts +0 -41
  323. package/dist/runtime/native/results.js +0 -128
  324. package/dist/runtime/native/sessions.d.ts +0 -45
  325. package/dist/runtime/native/sessions.js +0 -87
  326. package/dist/runtime/native/transcript.d.ts +0 -89
  327. package/dist/runtime/native/transcript.js +0 -656
  328. package/dist/runtime/native/translate.d.ts +0 -46
  329. package/dist/runtime/native/translate.js +0 -299
  330. package/dist/runtime/native/transport.d.ts +0 -7
  331. package/dist/runtime/native/transport.js +0 -16
  332. package/dist/runtime/native/version.d.ts +0 -5
  333. package/dist/runtime/native/version.js +0 -21
  334. package/dist/runtime/preferences.d.ts +0 -7
  335. package/dist/runtime/preferences.js +0 -22
  336. package/dist/runtime/presentation.d.ts +0 -32
  337. package/dist/runtime/presentation.js +0 -124
  338. package/dist/runtime/process-group.d.ts +0 -5
  339. package/dist/runtime/process-group.js +0 -161
  340. package/dist/runtime/projection-store.d.ts +0 -27
  341. package/dist/runtime/projection-store.js +0 -30
  342. package/dist/runtime/space-binding.d.ts +0 -48
  343. package/dist/runtime/space-binding.js +0 -342
  344. package/dist/runtime/supervisor.d.ts +0 -19
  345. package/dist/runtime/supervisor.js +0 -441
  346. package/dist/runtime/turn-projection.d.ts +0 -41
  347. package/dist/runtime/turn-projection.js +0 -120
  348. package/dist/runtime/worker.d.ts +0 -1
  349. package/dist/safe-remote-image.d.ts +0 -36
  350. package/dist/safe-remote-image.js +0 -191
  351. package/dist/self-update.d.ts +0 -7
  352. package/dist/self-update.js +0 -202
  353. package/dist/session-status.d.ts +0 -6
  354. package/dist/session-status.js +0 -16
  355. package/dist/space-files/limit.d.ts +0 -2
  356. package/dist/space-files/limit.js +0 -16
  357. package/dist/space-files/operands.d.ts +0 -17
  358. package/dist/space-files/operands.js +0 -33
  359. package/dist/space-files/transfer.d.ts +0 -53
  360. package/dist/space-files/transfer.js +0 -297
  361. package/dist/space-files/upload.d.ts +0 -17
  362. package/dist/space-files/upload.js +0 -76
  363. package/dist/space.d.ts +0 -44
  364. package/dist/space.js +0 -192
  365. package/dist/version.d.ts +0 -2
  366. package/dist/version.js +0 -17
  367. package/dist/web.d.ts +0 -1
  368. package/dist/web.js +0 -4
  369. /package/dist/{board-kernel → chunks}/lexer.js +0 -0
package/dist/auth.js DELETED
@@ -1,307 +0,0 @@
1
- import { COHUB_ENVIRONMENTS, normalizeBaseUrl, resolveApiBaseUrl, resolveCohubEnvironment } from "@neta-art/cohub";
2
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
- import { createHash, randomUUID } from "node:crypto";
4
- import { withRuntimeSpaceBindingsLock } from "./runtime/space-binding.js";
5
- import { homedir } from "node:os";
6
- import { join } from "node:path";
7
- import { setTimeout as delay } from "node:timers/promises";
8
- const CONFIG_DIR = join(homedir(), ".config", "cohub");
9
- const EXPIRY_SKEW_MS = 5 * 60 * 1000;
10
- const DEFAULT_SCOPE = "openid profile email offline_access";
11
- const DEFAULT_RESOURCE = "https://api.talesofai";
12
- export class AuthRequiredError extends Error {
13
- constructor(message = "Not authenticated") {
14
- super(message);
15
- this.name = "AuthRequiredError";
16
- }
17
- }
18
- const currentEnv = () => resolveCohubEnvironment();
19
- const normalizeUrl = (url) => url.trim().replace(/\/+$/, "");
20
- const authConfig = (env = currentEnv()) => {
21
- const prefix = env === "dev" ? "COHUB_DEV" : "COHUB";
22
- const defaultIssuer = env === "dev" ? "https://dev-auth.neta.art" : "https://auth.neta.art";
23
- const defaultClientId = env === "dev" ? "u2fnfgvf8f16dnt8si2bv" : "f8d26cdlwx85b0e5l3om2";
24
- return {
25
- issuer: normalizeUrl(process.env[`${prefix}_AUTH_ISSUER`] ?? process.env.COHUB_AUTH_ISSUER ?? defaultIssuer),
26
- clientId: process.env[`${prefix}_AUTH_CLIENT_ID`] ?? process.env.COHUB_AUTH_CLIENT_ID ?? defaultClientId,
27
- resource: process.env[`${prefix}_AUTH_RESOURCE`] ?? process.env.COHUB_AUTH_RESOURCE ?? DEFAULT_RESOURCE,
28
- scope: process.env[`${prefix}_AUTH_SCOPE`] ?? process.env.COHUB_AUTH_SCOPE ?? DEFAULT_SCOPE,
29
- };
30
- };
31
- const endpointSuffix = (env, baseUrl = resolveApiBaseUrl({ env })) => {
32
- const url = normalizeBaseUrl(baseUrl);
33
- const endpoint = url === COHUB_ENVIRONMENTS[env].apiBaseUrl
34
- ? ""
35
- : `.${createHash("sha256").update(url).digest("hex")}`;
36
- return `${env === "dev" ? ".dev" : ""}${endpoint}`;
37
- };
38
- const sessionPath = (env = currentEnv(), baseUrl) => join(CONFIG_DIR, `auth${endpointSuffix(env, baseUrl)}.json`);
39
- const deviceCodePath = (env = currentEnv(), baseUrl) => join(CONFIG_DIR, `device-code${endpointSuffix(env, baseUrl)}.json`);
40
- const legacyTokenPath = (env = currentEnv(), baseUrl) => join(CONFIG_DIR, `token${endpointSuffix(env, baseUrl)}`);
41
- const sessionBaseUrl = (session) => session.baseUrl ?? COHUB_ENVIRONMENTS[session.env].apiBaseUrl;
42
- const writePrivateJson = (path, value) => {
43
- mkdirSync(CONFIG_DIR, { recursive: true });
44
- const temporary = `${path}.${randomUUID()}.tmp`;
45
- try {
46
- writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf-8", mode: 0o600, flag: "wx" });
47
- renameSync(temporary, path);
48
- }
49
- finally {
50
- rmSync(temporary, { force: true });
51
- }
52
- };
53
- const readJson = (path) => {
54
- if (!existsSync(path))
55
- return null;
56
- try {
57
- return JSON.parse(readFileSync(path, "utf-8"));
58
- }
59
- catch {
60
- return null;
61
- }
62
- };
63
- const removeIfExists = (path) => {
64
- if (existsSync(path))
65
- rmSync(path);
66
- };
67
- const tokenEndpoint = (issuer) => `${issuer}/oidc/token`;
68
- const deviceEndpoint = (issuer) => `${issuer}/oidc/device/auth`;
69
- const revocationEndpoint = (issuer) => `${issuer}/oidc/token/revocation`;
70
- const formPost = async (url, body) => {
71
- const response = await fetch(url, {
72
- method: "POST",
73
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
74
- body,
75
- signal: AbortSignal.timeout(15_000),
76
- });
77
- const contentType = response.headers.get("content-type") ?? "";
78
- const data = contentType.includes("application/json")
79
- ? await response.json().catch(() => null)
80
- : await response.text().catch(() => null);
81
- return { response, data };
82
- };
83
- const toNonEmptyString = (value, field) => {
84
- if (typeof value !== "string" || !value.trim())
85
- throw new Error(`Invalid auth response: missing ${field}`);
86
- return value;
87
- };
88
- const toPositiveNumber = (value, field) => {
89
- const number = typeof value === "number" ? value : Number(value);
90
- if (!Number.isFinite(number) || number <= 0)
91
- throw new Error(`Invalid auth response: invalid ${field}`);
92
- return number;
93
- };
94
- const authErrorCode = (data) => {
95
- if (typeof data !== "object" || data === null)
96
- return null;
97
- const error = data.error;
98
- return typeof error === "string" ? error : null;
99
- };
100
- const isUnrecoverableRefreshError = (data) => {
101
- const code = authErrorCode(data);
102
- return code === "invalid_grant" || code === "invalid_token";
103
- };
104
- const toSession = (token, config, env, previous) => {
105
- const accessToken = toNonEmptyString(token.access_token, "access_token");
106
- const expiresIn = toPositiveNumber(token.expires_in, "expires_in");
107
- if (token.token_type !== "Bearer")
108
- throw new Error(`Unsupported token type: ${token.token_type}`);
109
- if (token.refresh_token !== undefined && !token.refresh_token.trim())
110
- throw new Error("Invalid auth response: invalid refresh_token");
111
- if (!token.refresh_token && !previous?.refreshToken)
112
- throw new Error("Logto did not return a refresh token");
113
- const now = Date.now();
114
- return {
115
- schemaVersion: 1,
116
- env,
117
- baseUrl: previous ? sessionBaseUrl(previous) : resolveApiBaseUrl({ env }),
118
- issuer: config.issuer,
119
- clientId: config.clientId,
120
- resource: config.resource,
121
- scope: token.scope ?? config.scope,
122
- tokenType: "Bearer",
123
- accessToken,
124
- refreshToken: token.refresh_token ?? previous?.refreshToken ?? "",
125
- idToken: token.id_token ?? previous?.idToken,
126
- accessTokenExpiresAt: now + expiresIn * 1000,
127
- createdAt: previous?.createdAt ?? now,
128
- updatedAt: now,
129
- };
130
- };
131
- export const readAuthSession = () => readJson(sessionPath());
132
- export const authSessionPath = () => sessionPath();
133
- export const clearAuthSession = (env = currentEnv(), baseUrl = resolveApiBaseUrl({ env })) => {
134
- removeIfExists(sessionPath(env, baseUrl));
135
- removeIfExists(deviceCodePath(env, baseUrl));
136
- removeIfExists(legacyTokenPath(env, baseUrl));
137
- };
138
- export const authSource = () => {
139
- if (process.env.COHUB_EXECUTION_TOKEN?.trim())
140
- return "execution-token";
141
- if (readAuthSession())
142
- return "logto";
143
- return null;
144
- };
145
- export async function resolveAccessToken(options) {
146
- const executionToken = process.env.COHUB_EXECUTION_TOKEN?.trim();
147
- if (executionToken)
148
- return executionToken;
149
- const session = readAuthSession();
150
- if (!session)
151
- throw new AuthRequiredError();
152
- if (!options?.forceRefresh && session.accessTokenExpiresAt - Date.now() > EXPIRY_SKEW_MS)
153
- return session.accessToken;
154
- return refreshAccessToken(session);
155
- }
156
- export async function requireAccessToken() {
157
- const token = await resolveAccessToken();
158
- if (!token)
159
- throw new AuthRequiredError();
160
- return token;
161
- }
162
- const refreshesInFlight = new Map();
163
- export function refreshAccessToken(session = readAuthSession()) {
164
- if (!session?.refreshToken)
165
- return Promise.reject(new AuthRequiredError());
166
- const path = sessionPath(session.env, sessionBaseUrl(session));
167
- const inFlight = refreshesInFlight.get(path);
168
- if (inFlight)
169
- return inFlight;
170
- const refresh = withRuntimeSpaceBindingsLock(async () => {
171
- const current = readJson(path);
172
- if (!current)
173
- throw new AuthRequiredError();
174
- // Another process may already have rotated this refresh token.
175
- if (current.refreshToken !== session.refreshToken || current.updatedAt !== session.updatedAt)
176
- return current.accessToken;
177
- return performRefresh(current);
178
- }, { path, lockPath: `${path}.refresh.lock` }).finally(() => { refreshesInFlight.delete(path); });
179
- refreshesInFlight.set(path, refresh);
180
- return refresh;
181
- }
182
- async function performRefresh(session) {
183
- const config = authConfig(session.env);
184
- const path = sessionPath(session.env, sessionBaseUrl(session));
185
- const { response, data } = await formPost(tokenEndpoint(session.issuer), new URLSearchParams({
186
- client_id: session.clientId,
187
- grant_type: "refresh_token",
188
- refresh_token: session.refreshToken,
189
- scope: session.scope,
190
- resource: session.resource,
191
- }));
192
- if (!response.ok) {
193
- if (isUnrecoverableRefreshError(data)) {
194
- if (readJson(path)?.refreshToken === session.refreshToken)
195
- clearAuthSession(session.env, sessionBaseUrl(session));
196
- return null;
197
- }
198
- throw new Error(formatAuthError(data, response.status));
199
- }
200
- const next = toSession(data, config, session.env, session);
201
- // Never overwrite a login/logout that completed while the request was in flight.
202
- const current = readJson(path);
203
- if (!current)
204
- throw new AuthRequiredError();
205
- if (current.refreshToken !== session.refreshToken)
206
- return current.accessToken;
207
- writePrivateJson(path, next);
208
- return next.accessToken;
209
- }
210
- export async function requestDeviceCode() {
211
- const env = currentEnv();
212
- const baseUrl = resolveApiBaseUrl({ env });
213
- const config = authConfig(env);
214
- const { response, data } = await formPost(deviceEndpoint(config.issuer), new URLSearchParams({
215
- client_id: config.clientId,
216
- scope: config.scope,
217
- resource: config.resource,
218
- }));
219
- if (!response.ok || typeof data !== "object" || data === null) {
220
- throw new Error(typeof data === "string" ? data : `Failed to request device code: HTTP ${response.status}`);
221
- }
222
- const body = data;
223
- const now = Date.now();
224
- const expiresIn = toPositiveNumber(body.expires_in, "expires_in");
225
- const interval = body.interval === undefined ? 5 : toPositiveNumber(body.interval, "interval");
226
- const verificationUri = toNonEmptyString(body.verification_uri, "verification_uri");
227
- const deviceCode = {
228
- deviceCode: toNonEmptyString(body.device_code, "device_code"),
229
- userCode: toNonEmptyString(body.user_code, "user_code"),
230
- verificationUri,
231
- verificationUriComplete: body.verification_uri_complete === undefined
232
- ? verificationUri
233
- : toNonEmptyString(body.verification_uri_complete, "verification_uri_complete"),
234
- expiresAt: now + expiresIn * 1000,
235
- interval,
236
- createdAt: now,
237
- };
238
- writePrivateJson(deviceCodePath(env, baseUrl), deviceCode);
239
- return deviceCode;
240
- }
241
- export async function verifyDeviceCode() {
242
- const env = currentEnv();
243
- const baseUrl = resolveApiBaseUrl({ env });
244
- const config = authConfig(env);
245
- const deviceCode = readJson(deviceCodePath(env, baseUrl));
246
- if (!deviceCode)
247
- throw new Error("Device code not found. Run `cohub auth login --request-code` first.");
248
- if (deviceCode.expiresAt <= Date.now())
249
- throw new Error("Device code expired. Run `cohub auth login` again.");
250
- const { response, data } = await formPost(tokenEndpoint(config.issuer), new URLSearchParams({
251
- client_id: config.clientId,
252
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
253
- device_code: deviceCode.deviceCode,
254
- resource: config.resource,
255
- }));
256
- if (!response.ok)
257
- throw new Error(formatAuthError(data, response.status));
258
- const session = { ...toSession(data, config, env), baseUrl };
259
- writePrivateJson(sessionPath(env, sessionBaseUrl(session)), session);
260
- removeIfExists(deviceCodePath(env, baseUrl));
261
- return session;
262
- }
263
- export async function loginWithDeviceFlow(onCode, onPoll) {
264
- const code = await requestDeviceCode();
265
- onCode(code);
266
- return pollDeviceCode(code, onPoll);
267
- }
268
- export async function pollDeviceCode(code, onPoll) {
269
- while (Date.now() < code.expiresAt) {
270
- await delay(code.interval * 1000);
271
- onPoll?.();
272
- try {
273
- return await verifyDeviceCode();
274
- }
275
- catch (e) {
276
- const message = e instanceof Error ? e.message : String(e);
277
- if (message.includes("authorization_pending"))
278
- continue;
279
- if (message.includes("slow_down")) {
280
- await delay(code.interval * 1000);
281
- continue;
282
- }
283
- throw e;
284
- }
285
- }
286
- throw new Error("Login timed out. Run `cohub auth login` again.");
287
- }
288
- export async function revokeAndClearAuthSession() {
289
- const session = readAuthSession();
290
- if (session?.refreshToken) {
291
- await formPost(revocationEndpoint(session.issuer), new URLSearchParams({
292
- client_id: session.clientId,
293
- token: session.refreshToken,
294
- token_type_hint: "refresh_token",
295
- })).catch(() => null);
296
- }
297
- clearAuthSession();
298
- }
299
- function formatAuthError(data, status) {
300
- if (typeof data === "object" && data !== null) {
301
- const record = data;
302
- const code = String(record.error ?? "");
303
- const description = String(record.error_description ?? "");
304
- return [code, description].filter(Boolean).join(": ") || `Authentication failed: HTTP ${status}`;
305
- }
306
- return typeof data === "string" && data ? data : `Authentication failed: HTTP ${status}`;
307
- }
package/dist/avatar.d.ts DELETED
@@ -1,55 +0,0 @@
1
- import { type CohubHttpClient, type PublicAssetPurpose } from "@neta-art/cohub";
2
- type PreparedAvatar = {
3
- body: Buffer;
4
- mimeType: "image/webp" | "image/jpeg" | "image/png" | "image/gif";
5
- extension: "webp" | "jpg" | "png" | "gif";
6
- };
7
- export declare function normalizeAvatarFile(path: string): Promise<PreparedAvatar>;
8
- export declare function uploadAvatarAsset(input: {
9
- client: CohubHttpClient;
10
- purpose: PublicAssetPurpose;
11
- path: string;
12
- spaceId?: string;
13
- }): Promise<{
14
- purpose: PublicAssetPurpose;
15
- objectKey: string;
16
- publicUrl: string;
17
- uploadUrl: string;
18
- uploadMethod: "PUT";
19
- uploadHeaders?: Record<string, string>;
20
- }>;
21
- export declare function normalizeLikeStickerFile(path: string): Promise<PreparedAvatar>;
22
- export declare function uploadLikeStickerAsset(input: {
23
- client: CohubHttpClient;
24
- spaceId: string;
25
- path: string;
26
- }): Promise<{
27
- purpose: PublicAssetPurpose;
28
- objectKey: string;
29
- publicUrl: string;
30
- uploadUrl: string;
31
- uploadMethod: "PUT";
32
- uploadHeaders?: Record<string, string>;
33
- }>;
34
- export declare function normalizeChatImageFile(path: string): Promise<{
35
- body: Buffer<ArrayBuffer>;
36
- width: number;
37
- height: number;
38
- }>;
39
- export declare function uploadChatImageAsset(input: {
40
- client: CohubHttpClient;
41
- spaceId?: string;
42
- sessionId?: string;
43
- path: string;
44
- }): Promise<{
45
- purpose: PublicAssetPurpose;
46
- objectKey: string;
47
- publicUrl: string;
48
- uploadUrl: string;
49
- uploadMethod: "PUT";
50
- uploadHeaders?: Record<string, string>;
51
- size: number;
52
- width: number;
53
- height: number;
54
- }>;
55
- export {};
package/dist/avatar.js DELETED
@@ -1,104 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { LIKE_STICKER_MAX_EDGE, LIKE_STICKER_MAX_FILE_BYTES } from "@neta-art/cohub";
3
- const loadSharp = async () => (await import("sharp")).default;
4
- const AVATAR_SIZE = 1024;
5
- const AVATAR_QUALITY = 86;
6
- const detectAvatarFormat = (body) => {
7
- if (body.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) {
8
- return { mimeType: "image/jpeg", extension: "jpg" };
9
- }
10
- if (body.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) {
11
- return { mimeType: "image/png", extension: "png" };
12
- }
13
- if (body.subarray(0, 6).toString("ascii") === "GIF87a" || body.subarray(0, 6).toString("ascii") === "GIF89a") {
14
- return { mimeType: "image/gif", extension: "gif" };
15
- }
16
- if (body.subarray(0, 4).toString("ascii") === "RIFF" && body.subarray(8, 12).toString("ascii") === "WEBP") {
17
- return { mimeType: "image/webp", extension: "webp" };
18
- }
19
- return null;
20
- };
21
- export async function normalizeAvatarFile(path) {
22
- const original = await readFile(path);
23
- const originalFormat = detectAvatarFormat(original);
24
- if (!originalFormat)
25
- throw new Error("Avatar must be a JPEG, PNG, GIF, or WebP image");
26
- if (originalFormat.mimeType === "image/gif")
27
- return { body: original, ...originalFormat };
28
- try {
29
- const sharp = await loadSharp();
30
- const body = await sharp(original)
31
- .rotate()
32
- .resize(AVATAR_SIZE, AVATAR_SIZE, { fit: "cover", position: "centre" })
33
- .webp({ quality: AVATAR_QUALITY })
34
- .toBuffer();
35
- return { body, mimeType: "image/webp", extension: "webp" };
36
- }
37
- catch {
38
- return { body: original, ...originalFormat };
39
- }
40
- }
41
- export async function uploadAvatarAsset(input) {
42
- const avatar = await normalizeAvatarFile(input.path);
43
- return input.client.publicAssets.upload({
44
- purpose: input.purpose,
45
- spaceId: input.spaceId,
46
- file: new Blob([new Uint8Array(avatar.body)], { type: avatar.mimeType }),
47
- mimeType: avatar.mimeType,
48
- filename: `avatar.${avatar.extension}`,
49
- });
50
- }
51
- export async function normalizeLikeStickerFile(path) {
52
- const original = await readFile(path);
53
- const format = detectAvatarFormat(original);
54
- if (!format)
55
- throw new Error("Like sticker must be a PNG, GIF, WebP, or JPEG image");
56
- const sharp = await loadSharp().catch(() => null);
57
- let prepared = { body: original, ...format };
58
- if (sharp) {
59
- const body = await sharp(original, { animated: true })
60
- .resize(LIKE_STICKER_MAX_EDGE, LIKE_STICKER_MAX_EDGE, { fit: "inside", withoutEnlargement: true })
61
- .webp({ quality: AVATAR_QUALITY, effort: 5 })
62
- .toBuffer();
63
- prepared = { body, mimeType: "image/webp", extension: "webp" };
64
- }
65
- else if (format.mimeType === "image/jpeg") {
66
- throw new Error("Converting a JPEG like sticker needs sharp; use a PNG, GIF, or WebP image");
67
- }
68
- if (prepared.body.byteLength > LIKE_STICKER_MAX_FILE_BYTES) {
69
- throw new Error(`Like sticker must be at most ${LIKE_STICKER_MAX_FILE_BYTES / 1024 / 1024} MiB after resizing`);
70
- }
71
- return prepared;
72
- }
73
- export async function uploadLikeStickerAsset(input) {
74
- const sticker = await normalizeLikeStickerFile(input.path);
75
- return input.client.publicAssets.upload({
76
- purpose: "space_like_sticker",
77
- spaceId: input.spaceId,
78
- file: new Blob([new Uint8Array(sticker.body)], { type: sticker.mimeType }),
79
- mimeType: sticker.mimeType,
80
- filename: `like-sticker.${sticker.extension}`,
81
- });
82
- }
83
- const CHAT_IMAGE_MAX_EDGE = 1984;
84
- const CHAT_IMAGE_QUALITY = 86;
85
- export async function normalizeChatImageFile(path) {
86
- const sharp = await loadSharp();
87
- const { data, info } = await sharp(path)
88
- .rotate()
89
- .resize(CHAT_IMAGE_MAX_EDGE, CHAT_IMAGE_MAX_EDGE, { fit: "inside", withoutEnlargement: true })
90
- .webp({ quality: CHAT_IMAGE_QUALITY })
91
- .toBuffer({ resolveWithObject: true });
92
- return { body: data, width: info.width, height: info.height };
93
- }
94
- export async function uploadChatImageAsset(input) {
95
- const { body, width, height } = await normalizeChatImageFile(input.path);
96
- const asset = await input.client.publicAssets.uploadChatImageAttachment({
97
- spaceId: input.spaceId,
98
- sessionId: input.sessionId,
99
- file: new Blob([new Uint8Array(body)], { type: "image/webp" }),
100
- mimeType: "image/webp",
101
- filename: "image.webp",
102
- });
103
- return { ...asset, size: body.byteLength, width, height };
104
- }
@@ -1,6 +0,0 @@
1
- export declare const BOARD_TRANSACTION_INPUT_MAX_BYTES: number;
2
- export declare const BOARD_CREATE_INPUT_MAX_BYTES: number;
3
- export declare const BOARD_DOMAIN_INPUT_MAX_BYTES: number;
4
- export declare function parseBoardJsonObject(text: string, source?: string): Record<string, unknown>;
5
- export declare function readBoardJsonObject(source: string, maxBytes?: number): Promise<Record<string, unknown>>;
6
- export declare function writeBoardOutput(path: string, bytes: Uint8Array, force?: boolean): Promise<void>;
@@ -1,88 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { constants } from "node:fs";
3
- import { access, link, open, rename, unlink } from "node:fs/promises";
4
- import { basename, dirname, join } from "node:path";
5
- export const BOARD_TRANSACTION_INPUT_MAX_BYTES = 16 * 1024 * 1024;
6
- export const BOARD_CREATE_INPUT_MAX_BYTES = 32 * 1024 * 1024;
7
- export const BOARD_DOMAIN_INPUT_MAX_BYTES = 1024 * 1024;
8
- export function parseBoardJsonObject(text, source = "input") {
9
- if (!text.trim())
10
- throw new Error(`${source} is empty`);
11
- let value;
12
- try {
13
- value = JSON.parse(text);
14
- }
15
- catch (cause) {
16
- throw new Error(`${source} must contain valid JSON`, { cause });
17
- }
18
- if (!value || typeof value !== "object" || Array.isArray(value)) {
19
- throw new Error(`${source} must contain a JSON object`);
20
- }
21
- return value;
22
- }
23
- async function readStdinBounded(maxBytes) {
24
- const chunks = [];
25
- let size = 0;
26
- for await (const chunk of process.stdin) {
27
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
28
- size += bytes.byteLength;
29
- if (size > maxBytes)
30
- throw new Error(`stdin exceeds the ${maxBytes} byte input limit`);
31
- chunks.push(bytes);
32
- }
33
- return Buffer.concat(chunks).toString("utf8");
34
- }
35
- export async function readBoardJsonObject(source, maxBytes = BOARD_DOMAIN_INPUT_MAX_BYTES) {
36
- if (source === "-")
37
- return parseBoardJsonObject(await readStdinBounded(maxBytes), "stdin");
38
- const handle = await open(source, constants.O_RDONLY | constants.O_NONBLOCK);
39
- try {
40
- const info = await handle.stat();
41
- if (!info.isFile())
42
- throw new Error(`${source} must be a regular file`);
43
- if (info.size > maxBytes)
44
- throw new Error(`${source} exceeds the ${maxBytes} byte input limit`);
45
- const chunks = [];
46
- const buffer = Buffer.allocUnsafe(Math.max(1, Math.min(64 * 1024, maxBytes + 1)));
47
- let size = 0;
48
- for (;;) {
49
- const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, null);
50
- if (bytesRead === 0)
51
- break;
52
- size += bytesRead;
53
- if (size > maxBytes)
54
- throw new Error(`${source} exceeds the ${maxBytes} byte input limit`);
55
- chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
56
- }
57
- return parseBoardJsonObject(Buffer.concat(chunks).toString("utf8"), source);
58
- }
59
- finally {
60
- await handle.close();
61
- }
62
- }
63
- export async function writeBoardOutput(path, bytes, force = false) {
64
- if (!force) {
65
- await access(path).then(() => { throw new Error(`Output already exists: ${path}; use --force to replace it`); }, () => undefined);
66
- }
67
- const temp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
68
- try {
69
- const handle = await open(temp, "wx");
70
- try {
71
- await handle.writeFile(bytes);
72
- await handle.sync();
73
- }
74
- finally {
75
- await handle.close();
76
- }
77
- if (force)
78
- await rename(temp, path);
79
- else {
80
- await link(temp, path);
81
- await unlink(temp);
82
- }
83
- }
84
- catch (cause) {
85
- await unlink(temp).catch(() => undefined);
86
- throw cause;
87
- }
88
- }
@@ -1,12 +0,0 @@
1
- import type { BoardNodeRenderer } from "@neta-art/cohub/board/export/node";
2
- export declare const BOARD_EXPORT_IMAGE_MEMORY_MIB = 256;
3
- export declare const BOARD_EXPORT_RENDERERS: readonly ["auto", "canvas", "gpu"];
4
- export type BoardExportRenderer = (typeof BOARD_EXPORT_RENDERERS)[number];
5
- export declare class BoardExportResourceError extends Error {
6
- }
7
- export type BoardExportDecodeImage = (bytes: Uint8Array, mimeType?: string, maxEdge?: number) => ReturnType<BoardNodeRenderer["decodeImage"]>;
8
- /** Decodes within `maxBytes`, first scaling images down to `maxEdge` on their long edge. */
9
- export declare function createBoardExportImageBudget(renderer: BoardNodeRenderer, maxBytes: number): {
10
- decodeImage: BoardExportDecodeImage;
11
- readonly usedBytes: number;
12
- };
@@ -1,51 +0,0 @@
1
- export const BOARD_EXPORT_IMAGE_MEMORY_MIB = 256;
2
- export const BOARD_EXPORT_RENDERERS = ["auto", "canvas", "gpu"];
3
- export class BoardExportResourceError extends Error {
4
- }
5
- /** Decodes within `maxBytes`, first scaling images down to `maxEdge` on their long edge. */
6
- export function createBoardExportImageBudget(renderer, maxBytes) {
7
- if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
8
- throw new Error("Image memory budget must be a positive integer.");
9
- let usedBytes = 0;
10
- const decodeImage = async (input, mimeType, maxEdge = Number.POSITIVE_INFINITY) => {
11
- const { default: sharp } = await import("sharp");
12
- let bytes = input;
13
- let { width, height } = await sharp(bytes, { limitInputPixels: false }).metadata();
14
- if (Math.max(width ?? 0, height ?? 0) > maxEdge) {
15
- const resized = await sharp(bytes, { limitInputPixels: false })
16
- .resize({ width: maxEdge, height: maxEdge, fit: "inside" })
17
- .png({ compressionLevel: 0 })
18
- .toBuffer({ resolveWithObject: true });
19
- ({ width, height } = resized.info);
20
- bytes = new Uint8Array(resized.data);
21
- mimeType = "image/png";
22
- }
23
- const required = (width ?? 0) * (height ?? 0) * 4;
24
- if (!Number.isSafeInteger(required) || required <= 0)
25
- throw new Error("Image dimensions could not be read.");
26
- if (required > maxBytes - usedBytes) {
27
- throw new BoardExportResourceError(`Image ${width}x${height} needs ${Math.ceil(required / 1024 ** 2)} MiB; ` +
28
- `${Math.ceil(usedBytes / 1024 ** 2)} MiB is already reserved against the ${Math.floor(maxBytes / 1024 ** 2)} MiB image budget. ` +
29
- "Use smaller source images, export a smaller region, or increase --image-memory if enough memory is available.");
30
- }
31
- usedBytes += required;
32
- try {
33
- const texture = await renderer.decodeImage(bytes, mimeType);
34
- const destroy = texture.destroy.bind(texture);
35
- let released = false;
36
- texture.destroy = (destroySource) => {
37
- if (destroySource && !released) {
38
- released = true;
39
- usedBytes -= required;
40
- }
41
- destroy(destroySource);
42
- };
43
- return texture;
44
- }
45
- catch (error) {
46
- usedBytes -= required;
47
- throw error;
48
- }
49
- };
50
- return { decodeImage, get usedBytes() { return usedBytes; } };
51
- }