primitive-admin 1.1.0-alpha.8 → 1.1.0-alpha.80

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 (522) hide show
  1. package/README.md +444 -106
  2. package/assets/skill/skills/primitive-platform/SKILL.md +811 -0
  3. package/dist/bin/primitive.d.ts +2 -0
  4. package/dist/bin/primitive.js +373 -21
  5. package/dist/bin/primitive.js.map +1 -1
  6. package/dist/src/commands/admins.d.ts +2 -0
  7. package/dist/src/commands/admins.js +128 -19
  8. package/dist/src/commands/admins.js.map +1 -1
  9. package/dist/src/commands/analytics.d.ts +2 -0
  10. package/dist/src/commands/analytics.js +700 -55
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps.d.ts +2 -0
  13. package/dist/src/commands/apps.js +54 -96
  14. package/dist/src/commands/apps.js.map +1 -1
  15. package/dist/src/commands/auth.d.ts +2 -0
  16. package/dist/src/commands/auth.js +196 -105
  17. package/dist/src/commands/auth.js.map +1 -1
  18. package/dist/src/commands/blob-buckets.d.ts +2 -0
  19. package/dist/src/commands/blob-buckets.js +330 -0
  20. package/dist/src/commands/blob-buckets.js.map +1 -0
  21. package/dist/src/commands/catalog.d.ts +2 -0
  22. package/dist/src/commands/catalog.js +37 -38
  23. package/dist/src/commands/catalog.js.map +1 -1
  24. package/dist/src/commands/collection-type-configs.d.ts +2 -0
  25. package/dist/src/commands/collection-type-configs.js +84 -0
  26. package/dist/src/commands/collection-type-configs.js.map +1 -0
  27. package/dist/src/commands/collections.d.ts +2 -0
  28. package/dist/src/commands/collections.js +565 -0
  29. package/dist/src/commands/collections.js.map +1 -0
  30. package/dist/src/commands/comparisons.d.ts +2 -0
  31. package/dist/src/commands/comparisons.js +6 -6
  32. package/dist/src/commands/comparisons.js.map +1 -1
  33. package/dist/src/commands/config.d.ts +46 -0
  34. package/dist/src/commands/config.js +465 -0
  35. package/dist/src/commands/config.js.map +1 -0
  36. package/dist/src/commands/connections.d.ts +2 -0
  37. package/dist/src/commands/connections.js +100 -0
  38. package/dist/src/commands/connections.js.map +1 -0
  39. package/dist/src/commands/cron-triggers.d.ts +2 -0
  40. package/dist/src/commands/cron-triggers.js +265 -0
  41. package/dist/src/commands/cron-triggers.js.map +1 -0
  42. package/dist/src/commands/database-type-configs.d.ts +2 -0
  43. package/dist/src/commands/database-type-configs.js +163 -0
  44. package/dist/src/commands/database-type-configs.js.map +1 -0
  45. package/dist/src/commands/database-types.d.ts +2 -0
  46. package/dist/src/commands/database-types.js +171 -0
  47. package/dist/src/commands/database-types.js.map +1 -0
  48. package/dist/src/commands/databases.d.ts +65 -0
  49. package/dist/src/commands/databases.js +1859 -238
  50. package/dist/src/commands/databases.js.map +1 -1
  51. package/dist/src/commands/documents.d.ts +2 -0
  52. package/dist/src/commands/documents.js +2062 -19
  53. package/dist/src/commands/documents.js.map +1 -1
  54. package/dist/src/commands/email-templates.d.ts +2 -0
  55. package/dist/src/commands/email-templates.js +174 -0
  56. package/dist/src/commands/email-templates.js.map +1 -0
  57. package/dist/src/commands/env.d.ts +23 -0
  58. package/dist/src/commands/env.js +385 -0
  59. package/dist/src/commands/env.js.map +1 -0
  60. package/dist/src/commands/feature-flags.d.ts +14 -0
  61. package/dist/src/commands/feature-flags.js +116 -0
  62. package/dist/src/commands/feature-flags.js.map +1 -0
  63. package/dist/src/commands/functions.d.ts +20 -0
  64. package/dist/src/commands/functions.js +672 -0
  65. package/dist/src/commands/functions.js.map +1 -0
  66. package/dist/src/commands/group-type-configs.d.ts +2 -0
  67. package/dist/src/commands/group-type-configs.js +86 -0
  68. package/dist/src/commands/group-type-configs.js.map +1 -0
  69. package/dist/src/commands/groups.d.ts +2 -0
  70. package/dist/src/commands/groups.js +39 -108
  71. package/dist/src/commands/groups.js.map +1 -1
  72. package/dist/src/commands/guides.d.ts +223 -0
  73. package/dist/src/commands/guides.js +617 -65
  74. package/dist/src/commands/guides.js.map +1 -1
  75. package/dist/src/commands/init.d.ts +37 -0
  76. package/dist/src/commands/init.js +1693 -208
  77. package/dist/src/commands/init.js.map +1 -1
  78. package/dist/src/commands/integrations.d.ts +2 -0
  79. package/dist/src/commands/integrations.js +402 -182
  80. package/dist/src/commands/integrations.js.map +1 -1
  81. package/dist/src/commands/llm.d.ts +2 -0
  82. package/dist/src/commands/llm.js +13 -8
  83. package/dist/src/commands/llm.js.map +1 -1
  84. package/dist/src/commands/locks.d.ts +8 -0
  85. package/dist/src/commands/locks.js +160 -0
  86. package/dist/src/commands/locks.js.map +1 -0
  87. package/dist/src/commands/metadata-category-configs.d.ts +12 -0
  88. package/dist/src/commands/metadata-category-configs.js +112 -0
  89. package/dist/src/commands/metadata-category-configs.js.map +1 -0
  90. package/dist/src/commands/metadata.d.ts +2 -0
  91. package/dist/src/commands/metadata.js +281 -0
  92. package/dist/src/commands/metadata.js.map +1 -0
  93. package/dist/src/commands/prompts.d.ts +2 -0
  94. package/dist/src/commands/prompts.js +275 -621
  95. package/dist/src/commands/prompts.js.map +1 -1
  96. package/dist/src/commands/rule-sets.d.ts +3 -0
  97. package/dist/src/commands/rule-sets.js +137 -147
  98. package/dist/src/commands/rule-sets.js.map +1 -1
  99. package/dist/src/commands/scripts.d.ts +30 -0
  100. package/dist/src/commands/scripts.js +679 -0
  101. package/dist/src/commands/scripts.js.map +1 -0
  102. package/dist/src/commands/secrets.d.ts +2 -0
  103. package/dist/src/commands/secrets.js +108 -0
  104. package/dist/src/commands/secrets.js.map +1 -0
  105. package/dist/src/commands/sessions.d.ts +2 -0
  106. package/dist/src/commands/sessions.js +75 -0
  107. package/dist/src/commands/sessions.js.map +1 -0
  108. package/dist/src/commands/settings.d.ts +18 -0
  109. package/dist/src/commands/settings.js +54 -0
  110. package/dist/src/commands/settings.js.map +1 -0
  111. package/dist/src/commands/skill.d.ts +2 -0
  112. package/dist/src/commands/skill.js +29 -0
  113. package/dist/src/commands/skill.js.map +1 -0
  114. package/dist/src/commands/sync-app-settings.d.ts +158 -0
  115. package/dist/src/commands/sync-app-settings.js +328 -0
  116. package/dist/src/commands/sync-app-settings.js.map +1 -0
  117. package/dist/src/commands/sync.d.ts +2514 -0
  118. package/dist/src/commands/sync.js +16106 -848
  119. package/dist/src/commands/sync.js.map +1 -1
  120. package/dist/src/commands/tokens.d.ts +2 -0
  121. package/dist/src/commands/tokens.js +130 -21
  122. package/dist/src/commands/tokens.js.map +1 -1
  123. package/dist/src/commands/users.d.ts +2 -0
  124. package/dist/src/commands/users.js +532 -23
  125. package/dist/src/commands/users.js.map +1 -1
  126. package/dist/src/commands/vars.d.ts +8 -0
  127. package/dist/src/commands/vars.js +96 -0
  128. package/dist/src/commands/vars.js.map +1 -0
  129. package/dist/src/commands/waitlist.d.ts +2 -0
  130. package/dist/src/commands/waitlist.js +10 -10
  131. package/dist/src/commands/waitlist.js.map +1 -1
  132. package/dist/src/commands/webhooks.d.ts +2 -0
  133. package/dist/src/commands/webhooks.js +562 -0
  134. package/dist/src/commands/webhooks.js.map +1 -0
  135. package/dist/src/commands/workflows.d.ts +116 -0
  136. package/dist/src/commands/workflows.js +1638 -729
  137. package/dist/src/commands/workflows.js.map +1 -1
  138. package/dist/src/lib/access-rule-display.d.ts +21 -0
  139. package/dist/src/lib/access-rule-display.js +34 -0
  140. package/dist/src/lib/access-rule-display.js.map +1 -0
  141. package/dist/src/lib/api-client.d.ts +2147 -0
  142. package/dist/src/lib/api-client.js +2042 -160
  143. package/dist/src/lib/api-client.js.map +1 -1
  144. package/dist/src/lib/app-match-guard.d.ts +44 -0
  145. package/dist/src/lib/app-match-guard.js +72 -0
  146. package/dist/src/lib/app-match-guard.js.map +1 -0
  147. package/dist/src/lib/app-settings-descriptor.d.ts +263 -0
  148. package/dist/src/lib/app-settings-descriptor.js +584 -0
  149. package/dist/src/lib/app-settings-descriptor.js.map +1 -0
  150. package/dist/src/lib/auth-flow.d.ts +8 -0
  151. package/dist/src/lib/batch.d.ts +26 -0
  152. package/dist/src/lib/batch.js +32 -0
  153. package/dist/src/lib/batch.js.map +1 -0
  154. package/dist/src/lib/block-layout.d.ts +160 -0
  155. package/dist/src/lib/block-layout.js +451 -0
  156. package/dist/src/lib/block-layout.js.map +1 -0
  157. package/dist/src/lib/block-selector.d.ts +58 -0
  158. package/dist/src/lib/block-selector.js +92 -0
  159. package/dist/src/lib/block-selector.js.map +1 -0
  160. package/dist/src/lib/canonical-json.d.ts +12 -0
  161. package/dist/src/lib/canonical-json.js +35 -0
  162. package/dist/src/lib/canonical-json.js.map +1 -0
  163. package/dist/src/lib/channel.d.ts +30 -0
  164. package/dist/src/lib/channel.js +68 -0
  165. package/dist/src/lib/channel.js.map +1 -0
  166. package/dist/src/lib/cli-manifest.d.ts +68 -0
  167. package/dist/src/lib/cli-manifest.js +71 -0
  168. package/dist/src/lib/cli-manifest.js.map +1 -0
  169. package/dist/src/lib/codegen-shared/generatedFiles.d.ts +101 -0
  170. package/dist/src/lib/codegen-shared/generatedFiles.js +191 -0
  171. package/dist/src/lib/codegen-shared/generatedFiles.js.map +1 -0
  172. package/dist/src/lib/codegen-shared/prettierStable.d.ts +262 -0
  173. package/dist/src/lib/codegen-shared/prettierStable.js +610 -0
  174. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -0
  175. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.d.ts +38 -0
  176. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js +46 -0
  177. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js.map +1 -0
  178. package/dist/src/lib/config-json-field.d.ts +28 -0
  179. package/dist/src/lib/config-json-field.js +56 -0
  180. package/dist/src/lib/config-json-field.js.map +1 -0
  181. package/dist/src/lib/config-object-descriptor.d.ts +127 -0
  182. package/dist/src/lib/config-object-descriptor.js +696 -0
  183. package/dist/src/lib/config-object-descriptor.js.map +1 -0
  184. package/dist/src/lib/config-payload.d.ts +85 -0
  185. package/dist/src/lib/config-payload.js +116 -0
  186. package/dist/src/lib/config-payload.js.map +1 -0
  187. package/dist/src/lib/config-surface.d.ts +140 -0
  188. package/dist/src/lib/config-surface.js +317 -0
  189. package/dist/src/lib/config-surface.js.map +1 -0
  190. package/dist/src/lib/config-toml.d.ts +10 -0
  191. package/dist/src/lib/config-toml.js +42 -0
  192. package/dist/src/lib/config-toml.js.map +1 -0
  193. package/dist/src/lib/config.d.ts +71 -0
  194. package/dist/src/lib/config.js +71 -68
  195. package/dist/src/lib/config.js.map +1 -1
  196. package/dist/src/lib/confirm-prompt.d.ts +83 -0
  197. package/dist/src/lib/confirm-prompt.js +110 -0
  198. package/dist/src/lib/confirm-prompt.js.map +1 -0
  199. package/dist/src/lib/constants.d.ts +11 -0
  200. package/dist/src/lib/constants.js +12 -0
  201. package/dist/src/lib/constants.js.map +1 -0
  202. package/dist/src/lib/crash-handlers.d.ts +20 -0
  203. package/dist/src/lib/crash-handlers.js +49 -0
  204. package/dist/src/lib/crash-handlers.js.map +1 -0
  205. package/dist/src/lib/credentials-store.d.ts +104 -0
  206. package/dist/src/lib/credentials-store.js +336 -0
  207. package/dist/src/lib/credentials-store.js.map +1 -0
  208. package/dist/src/lib/csv.d.ts +47 -0
  209. package/dist/src/lib/csv.js +172 -0
  210. package/dist/src/lib/csv.js.map +1 -0
  211. package/dist/src/lib/data-input.d.ts +23 -0
  212. package/dist/src/lib/data-input.js +50 -0
  213. package/dist/src/lib/data-input.js.map +1 -0
  214. package/dist/src/lib/db-codegen/dbFingerprint.d.ts +10 -0
  215. package/dist/src/lib/db-codegen/dbFingerprint.js +17 -0
  216. package/dist/src/lib/db-codegen/dbFingerprint.js.map +1 -0
  217. package/dist/src/lib/db-codegen/dbGenerator.d.ts +67 -0
  218. package/dist/src/lib/db-codegen/dbGenerator.js +170 -0
  219. package/dist/src/lib/db-codegen/dbGenerator.js.map +1 -0
  220. package/dist/src/lib/db-codegen/dbNaming.d.ts +87 -0
  221. package/dist/src/lib/db-codegen/dbNaming.js +180 -0
  222. package/dist/src/lib/db-codegen/dbNaming.js.map +1 -0
  223. package/dist/src/lib/db-codegen/dbTemplates.d.ts +272 -0
  224. package/dist/src/lib/db-codegen/dbTemplates.js +480 -0
  225. package/dist/src/lib/db-codegen/dbTemplates.js.map +1 -0
  226. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +73 -0
  227. package/dist/src/lib/db-codegen/dbTsTypes.js +139 -0
  228. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -0
  229. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +146 -0
  230. package/dist/src/lib/db-codegen/dbTypeIR.js +517 -0
  231. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -0
  232. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.d.ts +112 -0
  233. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js +211 -0
  234. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js.map +1 -0
  235. package/dist/src/lib/document-export-permissions.d.ts +30 -0
  236. package/dist/src/lib/document-export-permissions.js +54 -0
  237. package/dist/src/lib/document-export-permissions.js.map +1 -0
  238. package/dist/src/lib/env-resolver-core.d.ts +253 -0
  239. package/dist/src/lib/env-resolver-core.js +459 -0
  240. package/dist/src/lib/env-resolver-core.js.map +1 -0
  241. package/dist/src/lib/env-resolver.d.ts +99 -0
  242. package/dist/src/lib/env-resolver.js +153 -0
  243. package/dist/src/lib/env-resolver.js.map +1 -0
  244. package/dist/src/lib/fetch.d.ts +5 -0
  245. package/dist/src/lib/function-bundle.d.ts +141 -0
  246. package/dist/src/lib/function-bundle.js +333 -0
  247. package/dist/src/lib/function-bundle.js.map +1 -0
  248. package/dist/src/lib/function-collect.d.ts +123 -0
  249. package/dist/src/lib/function-collect.js +594 -0
  250. package/dist/src/lib/function-collect.js.map +1 -0
  251. package/dist/src/lib/function-db-types.d.ts +187 -0
  252. package/dist/src/lib/function-db-types.js +782 -0
  253. package/dist/src/lib/function-db-types.js.map +1 -0
  254. package/dist/src/lib/function-document-types.d.ts +50 -0
  255. package/dist/src/lib/function-document-types.js +163 -0
  256. package/dist/src/lib/function-document-types.js.map +1 -0
  257. package/dist/src/lib/function-grants-preflight.d.ts +64 -0
  258. package/dist/src/lib/function-grants-preflight.js +100 -0
  259. package/dist/src/lib/function-grants-preflight.js.map +1 -0
  260. package/dist/src/lib/function-log-tail.d.ts +83 -0
  261. package/dist/src/lib/function-log-tail.js +115 -0
  262. package/dist/src/lib/function-log-tail.js.map +1 -0
  263. package/dist/src/lib/function-schema-codegen.d.ts +118 -0
  264. package/dist/src/lib/function-schema-codegen.js +402 -0
  265. package/dist/src/lib/function-schema-codegen.js.map +1 -0
  266. package/dist/src/lib/function-sync.d.ts +263 -0
  267. package/dist/src/lib/function-sync.js +604 -0
  268. package/dist/src/lib/function-sync.js.map +1 -0
  269. package/dist/src/lib/function-triggers.d.ts +66 -0
  270. package/dist/src/lib/function-triggers.js +285 -0
  271. package/dist/src/lib/function-triggers.js.map +1 -0
  272. package/dist/src/lib/function-typecheck.d.ts +86 -0
  273. package/dist/src/lib/function-typecheck.js +370 -0
  274. package/dist/src/lib/function-typecheck.js.map +1 -0
  275. package/dist/src/lib/generated-allowlist.d.ts +28 -0
  276. package/dist/src/lib/generated-allowlist.js +281 -0
  277. package/dist/src/lib/generated-allowlist.js.map +1 -0
  278. package/dist/src/lib/generated-config-surfaces.d.ts +1445 -0
  279. package/dist/src/lib/generated-config-surfaces.js +5836 -0
  280. package/dist/src/lib/generated-config-surfaces.js.map +1 -0
  281. package/dist/src/lib/generated-sdk-types.d.ts +12 -0
  282. package/dist/src/lib/generated-sdk-types.js +13 -0
  283. package/dist/src/lib/generated-sdk-types.js.map +1 -0
  284. package/dist/src/lib/generated-template-lint.d.ts +212 -0
  285. package/dist/src/lib/generated-template-lint.js +624 -0
  286. package/dist/src/lib/generated-template-lint.js.map +1 -0
  287. package/dist/src/lib/generated-workflow-model-fields.d.ts +20 -0
  288. package/dist/src/lib/generated-workflow-model-fields.js +53 -0
  289. package/dist/src/lib/generated-workflow-model-fields.js.map +1 -0
  290. package/dist/src/lib/google-client-secret-status.d.ts +35 -0
  291. package/dist/src/lib/google-client-secret-status.js +56 -0
  292. package/dist/src/lib/google-client-secret-status.js.map +1 -0
  293. package/dist/src/lib/init-adopt.d.ts +16 -0
  294. package/dist/src/lib/init-adopt.js +34 -0
  295. package/dist/src/lib/init-adopt.js.map +1 -0
  296. package/dist/src/lib/init-assets.d.ts +39 -0
  297. package/dist/src/lib/init-assets.js +97 -0
  298. package/dist/src/lib/init-assets.js.map +1 -0
  299. package/dist/src/lib/init-client-platforms.d.ts +14 -0
  300. package/dist/src/lib/init-client-platforms.js +71 -0
  301. package/dist/src/lib/init-client-platforms.js.map +1 -0
  302. package/dist/src/lib/init-config.d.ts +98 -0
  303. package/dist/src/lib/init-config.js +186 -0
  304. package/dist/src/lib/init-config.js.map +1 -0
  305. package/dist/src/lib/init-email-redirect-uris.d.ts +37 -0
  306. package/dist/src/lib/init-email-redirect-uris.js +46 -0
  307. package/dist/src/lib/init-email-redirect-uris.js.map +1 -0
  308. package/dist/src/lib/init-ios-links.d.ts +91 -0
  309. package/dist/src/lib/init-ios-links.js +219 -0
  310. package/dist/src/lib/init-ios-links.js.map +1 -0
  311. package/dist/src/lib/init-plan.d.ts +80 -0
  312. package/dist/src/lib/init-plan.js +95 -0
  313. package/dist/src/lib/init-plan.js.map +1 -0
  314. package/dist/src/lib/init-production-env.d.ts +48 -0
  315. package/dist/src/lib/init-production-env.js +59 -0
  316. package/dist/src/lib/init-production-env.js.map +1 -0
  317. package/dist/src/lib/init-schema.d.ts +74 -0
  318. package/dist/src/lib/init-schema.js +358 -0
  319. package/dist/src/lib/init-schema.js.map +1 -0
  320. package/dist/src/lib/init-xcode.d.ts +34 -0
  321. package/dist/src/lib/init-xcode.js +138 -0
  322. package/dist/src/lib/init-xcode.js.map +1 -0
  323. package/dist/src/lib/integration-request-config.d.ts +30 -0
  324. package/dist/src/lib/integration-request-config.js +145 -0
  325. package/dist/src/lib/integration-request-config.js.map +1 -0
  326. package/dist/src/lib/integration-selector.d.ts +42 -0
  327. package/dist/src/lib/integration-selector.js +46 -0
  328. package/dist/src/lib/integration-selector.js.map +1 -0
  329. package/dist/src/lib/ios-app-id.d.ts +34 -0
  330. package/dist/src/lib/ios-app-id.js +69 -0
  331. package/dist/src/lib/ios-app-id.js.map +1 -0
  332. package/dist/src/lib/local-state.d.ts +55 -0
  333. package/dist/src/lib/local-state.js +167 -0
  334. package/dist/src/lib/local-state.js.map +1 -0
  335. package/dist/src/lib/local-test-cases.d.ts +63 -0
  336. package/dist/src/lib/local-test-cases.js +136 -0
  337. package/dist/src/lib/local-test-cases.js.map +1 -0
  338. package/dist/src/lib/log-inspection.d.ts +680 -0
  339. package/dist/src/lib/log-inspection.js +784 -0
  340. package/dist/src/lib/log-inspection.js.map +1 -0
  341. package/dist/src/lib/migration-nag.d.ts +49 -0
  342. package/dist/src/lib/migration-nag.js +164 -0
  343. package/dist/src/lib/migration-nag.js.map +1 -0
  344. package/dist/src/lib/object-status-filter.d.ts +22 -0
  345. package/dist/src/lib/object-status-filter.js +45 -0
  346. package/dist/src/lib/object-status-filter.js.map +1 -0
  347. package/dist/src/lib/output.d.ts +109 -0
  348. package/dist/src/lib/output.js +191 -8
  349. package/dist/src/lib/output.js.map +1 -1
  350. package/dist/src/lib/package-manager.d.ts +140 -0
  351. package/dist/src/lib/package-manager.js +305 -0
  352. package/dist/src/lib/package-manager.js.map +1 -0
  353. package/dist/src/lib/paginate.d.ts +83 -0
  354. package/dist/src/lib/paginate.js +95 -0
  355. package/dist/src/lib/paginate.js.map +1 -0
  356. package/dist/src/lib/platform-owned.d.ts +63 -0
  357. package/dist/src/lib/platform-owned.js +85 -0
  358. package/dist/src/lib/platform-owned.js.map +1 -0
  359. package/dist/src/lib/project-config.d.ts +122 -0
  360. package/dist/src/lib/project-config.js +244 -0
  361. package/dist/src/lib/project-config.js.map +1 -0
  362. package/dist/src/lib/query-operators.d.ts +43 -0
  363. package/dist/src/lib/query-operators.js +80 -0
  364. package/dist/src/lib/query-operators.js.map +1 -0
  365. package/dist/src/lib/record-filter.d.ts +18 -0
  366. package/dist/src/lib/record-filter.js +55 -0
  367. package/dist/src/lib/record-filter.js.map +1 -0
  368. package/dist/src/lib/refresh-admin-credentials.d.ts +65 -0
  369. package/dist/src/lib/refresh-admin-credentials.js +103 -0
  370. package/dist/src/lib/refresh-admin-credentials.js.map +1 -0
  371. package/dist/src/lib/resolve-init-dev-port.d.ts +56 -0
  372. package/dist/src/lib/resolve-init-dev-port.js +55 -0
  373. package/dist/src/lib/resolve-init-dev-port.js.map +1 -0
  374. package/dist/src/lib/resolve-init-server.d.ts +64 -0
  375. package/dist/src/lib/resolve-init-server.js +77 -0
  376. package/dist/src/lib/resolve-init-server.js.map +1 -0
  377. package/dist/src/lib/resolve-platform.d.ts +74 -0
  378. package/dist/src/lib/resolve-platform.js +105 -0
  379. package/dist/src/lib/resolve-platform.js.map +1 -0
  380. package/dist/src/lib/run-status.d.ts +19 -0
  381. package/dist/src/lib/run-status.generated.d.ts +39 -0
  382. package/dist/src/lib/run-status.generated.js +66 -0
  383. package/dist/src/lib/run-status.generated.js.map +1 -0
  384. package/dist/src/lib/run-status.js +19 -0
  385. package/dist/src/lib/run-status.js.map +1 -0
  386. package/dist/src/lib/server-text-normalization.d.ts +51 -0
  387. package/dist/src/lib/server-text-normalization.js +90 -0
  388. package/dist/src/lib/server-text-normalization.js.map +1 -0
  389. package/dist/src/lib/server-url.d.ts +22 -0
  390. package/dist/src/lib/server-url.js +33 -0
  391. package/dist/src/lib/server-url.js.map +1 -0
  392. package/dist/src/lib/signing-secret-status.d.ts +81 -0
  393. package/dist/src/lib/signing-secret-status.js +116 -0
  394. package/dist/src/lib/signing-secret-status.js.map +1 -0
  395. package/dist/src/lib/skill-installer.d.ts +25 -0
  396. package/dist/src/lib/skill-installer.js +266 -0
  397. package/dist/src/lib/skill-installer.js.map +1 -0
  398. package/dist/src/lib/snapshots.d.ts +98 -0
  399. package/dist/src/lib/snapshots.js +294 -0
  400. package/dist/src/lib/snapshots.js.map +1 -0
  401. package/dist/src/lib/swift-codegen/dbGenerator.d.ts +113 -0
  402. package/dist/src/lib/swift-codegen/dbGenerator.js +914 -0
  403. package/dist/src/lib/swift-codegen/dbGenerator.js.map +1 -0
  404. package/dist/src/lib/swift-codegen/dbSwiftTypes.d.ts +42 -0
  405. package/dist/src/lib/swift-codegen/dbSwiftTypes.js +100 -0
  406. package/dist/src/lib/swift-codegen/dbSwiftTypes.js.map +1 -0
  407. package/dist/src/lib/swift-codegen/generator.d.ts +94 -0
  408. package/dist/src/lib/swift-codegen/generator.js +440 -0
  409. package/dist/src/lib/swift-codegen/generator.js.map +1 -0
  410. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +72 -0
  411. package/dist/src/lib/swift-codegen/schemaToSwift.js +644 -0
  412. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -0
  413. package/dist/src/lib/swift-codegen/siblingSymbols.d.ts +94 -0
  414. package/dist/src/lib/swift-codegen/siblingSymbols.js +155 -0
  415. package/dist/src/lib/swift-codegen/siblingSymbols.js.map +1 -0
  416. package/dist/src/lib/swift-codegen/swiftNaming.d.ts +85 -0
  417. package/dist/src/lib/swift-codegen/swiftNaming.js +198 -0
  418. package/dist/src/lib/swift-codegen/swiftNaming.js.map +1 -0
  419. package/dist/src/lib/sync-dir-selector.d.ts +21 -0
  420. package/dist/src/lib/sync-dir-selector.js +30 -0
  421. package/dist/src/lib/sync-dir-selector.js.map +1 -0
  422. package/dist/src/lib/sync-paths.d.ts +123 -0
  423. package/dist/src/lib/sync-paths.js +193 -0
  424. package/dist/src/lib/sync-paths.js.map +1 -0
  425. package/dist/src/lib/sync-resource-types.d.ts +563 -0
  426. package/dist/src/lib/sync-resource-types.js +1073 -0
  427. package/dist/src/lib/sync-resource-types.js.map +1 -0
  428. package/dist/src/lib/sync-selectors.d.ts +95 -0
  429. package/dist/src/lib/sync-selectors.js +228 -0
  430. package/dist/src/lib/sync-selectors.js.map +1 -0
  431. package/dist/src/lib/template.d.ts +170 -0
  432. package/dist/src/lib/template.js +484 -68
  433. package/dist/src/lib/template.js.map +1 -1
  434. package/dist/src/lib/test-case-file-names.d.ts +40 -0
  435. package/dist/src/lib/test-case-file-names.js +91 -0
  436. package/dist/src/lib/test-case-file-names.js.map +1 -0
  437. package/dist/src/lib/test-case-keys.d.ts +29 -0
  438. package/dist/src/lib/test-case-keys.js +55 -0
  439. package/dist/src/lib/test-case-keys.js.map +1 -0
  440. package/dist/src/lib/test-case-variables.d.ts +29 -0
  441. package/dist/src/lib/test-case-variables.js +71 -0
  442. package/dist/src/lib/test-case-variables.js.map +1 -0
  443. package/dist/src/lib/token-inject.d.ts +56 -0
  444. package/dist/src/lib/token-inject.js +204 -0
  445. package/dist/src/lib/token-inject.js.map +1 -0
  446. package/dist/src/lib/toml-database-config.d.ts +123 -0
  447. package/dist/src/lib/toml-database-config.js +544 -0
  448. package/dist/src/lib/toml-database-config.js.map +1 -0
  449. package/dist/src/lib/toml-metadata-config.d.ts +151 -0
  450. package/dist/src/lib/toml-metadata-config.js +476 -0
  451. package/dist/src/lib/toml-metadata-config.js.map +1 -0
  452. package/dist/src/lib/toml-native-form.d.ts +46 -0
  453. package/dist/src/lib/toml-native-form.js +78 -0
  454. package/dist/src/lib/toml-native-form.js.map +1 -0
  455. package/dist/src/lib/toml-params-validator.d.ts +129 -0
  456. package/dist/src/lib/toml-params-validator.js +298 -0
  457. package/dist/src/lib/toml-params-validator.js.map +1 -0
  458. package/dist/src/lib/toml-scalar-edit.d.ts +43 -0
  459. package/dist/src/lib/toml-scalar-edit.js +283 -0
  460. package/dist/src/lib/toml-scalar-edit.js.map +1 -0
  461. package/dist/src/lib/user-selector.d.ts +24 -0
  462. package/dist/src/lib/user-selector.js +33 -0
  463. package/dist/src/lib/user-selector.js.map +1 -0
  464. package/dist/src/lib/version-check.d.ts +35 -0
  465. package/dist/src/lib/version-check.js +241 -0
  466. package/dist/src/lib/version-check.js.map +1 -0
  467. package/dist/src/lib/watch.d.ts +121 -0
  468. package/dist/src/lib/watch.js +169 -0
  469. package/dist/src/lib/watch.js.map +1 -0
  470. package/dist/src/lib/web-url.d.ts +40 -0
  471. package/dist/src/lib/web-url.js +76 -0
  472. package/dist/src/lib/web-url.js.map +1 -0
  473. package/dist/src/lib/workflow-apply.d.ts +110 -0
  474. package/dist/src/lib/workflow-apply.js +164 -0
  475. package/dist/src/lib/workflow-apply.js.map +1 -0
  476. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.d.ts +129 -0
  477. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js +269 -0
  478. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js.map +1 -0
  479. package/dist/src/lib/workflow-codegen/generator.d.ts +96 -0
  480. package/dist/src/lib/workflow-codegen/generator.js +361 -0
  481. package/dist/src/lib/workflow-codegen/generator.js.map +1 -0
  482. package/dist/src/lib/workflow-codegen/invokerIR.d.ts +94 -0
  483. package/dist/src/lib/workflow-codegen/invokerIR.js +76 -0
  484. package/dist/src/lib/workflow-codegen/invokerIR.js.map +1 -0
  485. package/dist/src/lib/workflow-codegen/naming.d.ts +33 -0
  486. package/dist/src/lib/workflow-codegen/naming.js +81 -0
  487. package/dist/src/lib/workflow-codegen/naming.js.map +1 -0
  488. package/dist/src/lib/workflow-codegen/schemaToTs.d.ts +80 -0
  489. package/dist/src/lib/workflow-codegen/schemaToTs.js +303 -0
  490. package/dist/src/lib/workflow-codegen/schemaToTs.js.map +1 -0
  491. package/dist/src/lib/workflow-config-apply.d.ts +70 -0
  492. package/dist/src/lib/workflow-config-apply.js +137 -0
  493. package/dist/src/lib/workflow-config-apply.js.map +1 -0
  494. package/dist/src/lib/workflow-config-sidecar.d.ts +63 -0
  495. package/dist/src/lib/workflow-config-sidecar.js +96 -0
  496. package/dist/src/lib/workflow-config-sidecar.js.map +1 -0
  497. package/dist/src/lib/workflow-defaults.d.ts +29 -0
  498. package/dist/src/lib/workflow-defaults.js +41 -0
  499. package/dist/src/lib/workflow-defaults.js.map +1 -0
  500. package/dist/src/lib/workflow-field-descriptor.d.ts +91 -0
  501. package/dist/src/lib/workflow-field-descriptor.js +153 -0
  502. package/dist/src/lib/workflow-field-descriptor.js.map +1 -0
  503. package/dist/src/lib/workflow-fragments.d.ts +64 -0
  504. package/dist/src/lib/workflow-fragments.js +342 -0
  505. package/dist/src/lib/workflow-fragments.js.map +1 -0
  506. package/dist/src/lib/workflow-include-preserve.d.ts +76 -0
  507. package/dist/src/lib/workflow-include-preserve.js +286 -0
  508. package/dist/src/lib/workflow-include-preserve.js.map +1 -0
  509. package/dist/src/lib/workflow-payload.d.ts +98 -0
  510. package/dist/src/lib/workflow-payload.js +178 -0
  511. package/dist/src/lib/workflow-payload.js.map +1 -0
  512. package/dist/src/lib/workflow-toml-validator.d.ts +207 -0
  513. package/dist/src/lib/workflow-toml-validator.js +762 -0
  514. package/dist/src/lib/workflow-toml-validator.js.map +1 -0
  515. package/dist/src/lib/workflow-usage.d.ts +198 -0
  516. package/dist/src/lib/workflow-usage.js +312 -0
  517. package/dist/src/lib/workflow-usage.js.map +1 -0
  518. package/dist/src/types/index.d.ts +591 -0
  519. package/dist/src/validators.d.ts +65 -0
  520. package/dist/src/validators.js +64 -0
  521. package/dist/src/validators.js.map +1 -0
  522. package/package.json +34 -9
@@ -1,15 +1,903 @@
1
1
  import { ApiClient } from "../lib/api-client.js";
2
2
  import { resolveAppId } from "../lib/config.js";
3
- import { success, error, info, formatTable, formatDate, json, } from "../lib/output.js";
3
+ import { success, error, info, formatTable, formatId, formatDate, json, keyValue, result as printResult, warn, } from "../lib/output.js";
4
+ import { confirmPrompt } from "../lib/confirm-prompt.js";
5
+ import { parseDataOption } from "../lib/data-input.js";
6
+ import { parseFilterOptions } from "../lib/record-filter.js";
7
+ import { buildPermissionsExport } from "../lib/document-export-permissions.js";
8
+ import { ulid } from "ulid";
9
+ import * as fs from "fs";
10
+ import * as path from "path";
11
+ /**
12
+ * Report a document's format (#2816) — but only when it is a large document.
13
+ *
14
+ * The format is chosen at creation and never migrated, so an operator has to
15
+ * be able to read it back: `--large` that the server ignored would otherwise
16
+ * hand back an ordinary-looking document. A legacy document says nothing at
17
+ * all, so its output is byte-for-byte what it has always been, however the
18
+ * stored row spells the format (absent, null or 1).
19
+ */
20
+ function printDocumentFormat(doc) {
21
+ if (Number(doc?.documentFormat) === 2) {
22
+ keyValue("Format", "2 (large document)");
23
+ }
24
+ }
25
+ /**
26
+ * Resolve a `--owner` value to a userId. A value containing "@" is looked up
27
+ * by exact email through the member-accessible `users/lookup` endpoint
28
+ * (issue #2763); anything else is already a user id and is passed through.
29
+ * Failures throw with the server's own message — a permission problem must
30
+ * not read as "no such user", which is how the old admin-only lookup
31
+ * reported it.
32
+ */
33
+ async function resolveOwnerUserId(client, appId, owner) {
34
+ if (!owner.includes("@"))
35
+ return owner;
36
+ const lookup = await client.lookupUserByEmail(appId, owner);
37
+ if (!lookup?.exists || !lookup.user) {
38
+ throw new Error(`No app user found with email "${owner}" in app ${appId}.`);
39
+ }
40
+ info(`Resolved owner email to userId: ${lookup.user.userId}`);
41
+ return lookup.user.userId;
42
+ }
4
43
  export function registerDocumentsCommands(program) {
5
44
  const documents = program
6
45
  .command("documents")
7
46
  .description("Manage documents within an app")
8
47
  .addHelpText("after", `
9
48
  Examples:
49
+ $ primitive documents list --user-id <user-id>
50
+ $ primitive documents get <document-id>
51
+ $ primitive documents create "My Doc"
52
+ $ primitive documents create "My Doc" --owner user@example.com
53
+ $ primitive documents delete <document-id> -y
54
+ $ primitive documents permissions list <document-id>
55
+ $ primitive documents permissions grant <document-id> --user-id <user-id> --permission reader
56
+ $ primitive documents permissions revoke <document-id> <user-id>
57
+ $ primitive documents records models <document-id>
58
+ $ primitive documents records describe <document-id> <model-name>
59
+ $ primitive documents records query <document-id> <model-name> --filter '{"status":"open"}'
60
+ $ primitive documents records count <document-id> <model-name>
61
+ $ primitive documents records save <document-id> <model-name> --data '{"qty":10}'
62
+ $ primitive documents records patch <document-id> <model-name> <record-id> --data '{"qty":11}'
63
+ $ primitive documents records delete <document-id> <model-name> <record-id> -y
64
+ $ primitive documents records aggregate <document-id> <model-name> --op avg --field price
65
+ $ primitive documents records bulk <document-id> --data-file ops.json -y
66
+ $ primitive documents dump <document-id>
67
+ $ primitive documents stats <document-id>
10
68
  $ primitive documents transfer-owner <document-id> <new-owner-id>
11
69
  $ primitive documents group-permissions list <document-id>
12
70
  `);
71
+ // ---- List a user's documents ----
72
+ // No app-wide enumeration: `--user-id` is required (the admin token has no
73
+ // "self"). Reads the per-user permission partition via the admin endpoint.
74
+ documents
75
+ .command("list")
76
+ .description("List a user's documents")
77
+ .requiredOption("--user-id <id>", "User ID whose documents to list")
78
+ .option("--app <app-id>", "App ID")
79
+ .option("--json", "Output as JSON")
80
+ .action(async (options) => {
81
+ const resolvedAppId = resolveAppId(undefined, options);
82
+ const client = new ApiClient();
83
+ try {
84
+ const list = await client.listAdminDocuments(resolvedAppId, options.userId);
85
+ if (options.json) {
86
+ json(list);
87
+ return;
88
+ }
89
+ if (list.length === 0) {
90
+ info("No documents found.");
91
+ return;
92
+ }
93
+ console.log(formatTable(list, [
94
+ { header: "DOCUMENT_ID", key: "documentId", format: formatId },
95
+ { header: "TITLE", key: "title", flex: true },
96
+ { header: "PERMISSION", key: "permission" },
97
+ { header: "GRANTED", key: "grantedAt", format: formatDate },
98
+ ]));
99
+ }
100
+ catch (err) {
101
+ error(err.message);
102
+ process.exit(1);
103
+ }
104
+ });
105
+ // ---- Get a single document's metadata ----
106
+ documents
107
+ .command("get")
108
+ .description("Show a document's metadata and the caller's access to it")
109
+ .argument("<document-id>", "Document ID")
110
+ .option("--app <app-id>", "App ID")
111
+ .option("--json", "Output as JSON")
112
+ .action(async (documentId, options) => {
113
+ const resolvedAppId = resolveAppId(undefined, options);
114
+ const client = new ApiClient();
115
+ try {
116
+ const doc = await client.getDocument(resolvedAppId, documentId);
117
+ if (options.json) {
118
+ json(doc);
119
+ return;
120
+ }
121
+ keyValue("Document ID", doc.documentId);
122
+ keyValue("Title", doc.title);
123
+ keyValue("Created By", doc.createdBy);
124
+ keyValue("Created", formatDate(doc.createdAt));
125
+ keyValue("Modified", formatDate(doc.modifiedAt ?? doc.lastModified));
126
+ printDocumentFormat(doc);
127
+ // `GET documents/:id` reports the caller's own access, not the
128
+ // document's grant/alias/collection inventory — printing counts for
129
+ // fields the endpoint never returns read as a definitive "0" for
130
+ // documents that demonstrably have them. Use
131
+ // `documents permissions list` for the grant list.
132
+ if (doc.permission)
133
+ keyValue("Your Permission", doc.permission);
134
+ if (doc.accessSource)
135
+ keyValue("Access Source", doc.accessSource);
136
+ if (doc.linkAccess)
137
+ keyValue("Link Access", doc.linkAccess);
138
+ }
139
+ catch (err) {
140
+ error(err.message);
141
+ process.exit(1);
142
+ }
143
+ });
144
+ // ---- Create a document ----
145
+ // The same `POST /documents` every client uses (#2763). Who ends up owning
146
+ // the document is the server's call, decided from the token's identity —
147
+ // the help below states that matrix rather than the CLI guessing at a role.
148
+ documents
149
+ .command("create")
150
+ .description("Create a document")
151
+ .argument("<title>", "Document title")
152
+ .option("--app <app-id>", "App ID")
153
+ .option("--owner <userId-or-email>", "User ID or email to own the document (super-admin or assigned-console-admin tokens only)")
154
+ .option("--large", "Create a large document (format 2): base snapshots + epoch overlays, for documents that outgrow a single in-memory Y.Doc")
155
+ .option("--json", "Output as JSON")
156
+ .addHelpText("after", `
157
+ Ownership:
158
+ An app-user token — member, admin, or owner — always creates the document
159
+ owned by the caller: the server ignores --owner for those tokens.
160
+ A super-admin token, or a console-admin token assigned to this app, acts
161
+ through an admin shadow app user — without --owner that shadow user owns the
162
+ document, with --owner the named user does.
163
+ A console admin not assigned to this app has no access to the app at all.
164
+
165
+ An email given to --owner is resolved to a user id before anything is
166
+ created; a user who is not in the app fails the command without creating a
167
+ document.
168
+ `)
169
+ .action(async (title, options) => {
170
+ const resolvedAppId = resolveAppId(undefined, options);
171
+ const client = new ApiClient();
172
+ let ownerUserId;
173
+ if (options.owner) {
174
+ try {
175
+ ownerUserId = await resolveOwnerUserId(client, resolvedAppId, options.owner);
176
+ }
177
+ catch (err) {
178
+ error(err.message);
179
+ process.exit(1);
180
+ }
181
+ }
182
+ try {
183
+ const result = await client.createDocument(resolvedAppId, {
184
+ title,
185
+ ...(ownerUserId ? { createdBy: ownerUserId } : {}),
186
+ // Opt-in only: without --large nothing is sent, so the document is
187
+ // created in the legacy format exactly as before (#2816).
188
+ ...(options.large ? { documentFormat: 2 } : {}),
189
+ });
190
+ if (options.json) {
191
+ json(result);
192
+ return;
193
+ }
194
+ success("Document created.");
195
+ keyValue("Document ID", result.documentId);
196
+ keyValue("Title", result.title);
197
+ keyValue("Owner", result.createdBy);
198
+ // Read back from the RESPONSE, not from `--large`: what the server
199
+ // created is what the document will be for the rest of its life.
200
+ printDocumentFormat(result);
201
+ }
202
+ catch (err) {
203
+ error(err.message);
204
+ process.exit(1);
205
+ }
206
+ });
207
+ // ---- Delete a document ----
208
+ // The runtime-resource delete verb (#2756): the server endpoint cascades
209
+ // through records, Yjs history, blobs, aliases and permissions, so an
210
+ // operator resetting an app's data no longer needs a one-off SDK script.
211
+ // Who may run it is the server's decision, so the help below states that
212
+ // model (#2763) rather than leaving it to be discovered from a 403.
213
+ documents
214
+ .command("delete")
215
+ .description("Delete a document and all its data (records, history, blobs, aliases, permissions)")
216
+ .argument("<document-id>", "Document ID")
217
+ .option("--app <app-id>", "App ID")
218
+ .option("-y, --yes", "Skip confirmation prompt")
219
+ .option("--json", "Output as JSON")
220
+ .addHelpText("after", `
221
+ Permissions (enforced by the server, not the CLI):
222
+ The document's owner, the app owner, and super-admin or assigned-console-admin
223
+ tokens — which act with app-owner authority — delete directly.
224
+ Everyone else, including app-role admins, can delete only when a containing
225
+ collection's document.delete rule allows it: an app admin cannot delete a
226
+ standalone document (one in no collection) they do not own.
227
+ The app's root document cannot be deleted.
228
+ `)
229
+ .action(async (documentId, options) => {
230
+ const resolvedAppId = resolveAppId(undefined, options);
231
+ if (!options.yes) {
232
+ let confirm;
233
+ try {
234
+ confirm = await confirmPrompt(`Delete document ${documentId}? This permanently deletes its records, ` +
235
+ `update history, blobs, aliases, and permissions. This cannot be undone.`);
236
+ }
237
+ catch (err) {
238
+ error(err.message);
239
+ process.exit(1);
240
+ }
241
+ if (!confirm) {
242
+ info("Cancelled.");
243
+ return;
244
+ }
245
+ }
246
+ const client = new ApiClient();
247
+ try {
248
+ const result = await client.deleteDocument(resolvedAppId, documentId);
249
+ if (options.json) {
250
+ json(result);
251
+ return;
252
+ }
253
+ success(`Document ${documentId} deleted.`);
254
+ }
255
+ catch (err) {
256
+ // Server refusals (404 not found, 403 root document / owner-only, the
257
+ // non-owner fail-closed 503) are printed verbatim, never swallowed.
258
+ error(err.message);
259
+ process.exit(1);
260
+ }
261
+ });
262
+ // ---- User-level permissions subcommand group ----
263
+ const permissions = documents
264
+ .command("permissions")
265
+ .description("Manage user-level permissions on a document");
266
+ // List user-level permissions
267
+ permissions
268
+ .command("list")
269
+ .description("List user-level permissions for a document")
270
+ .argument("<document-id>", "Document ID")
271
+ .option("--app <app-id>", "App ID")
272
+ .option("--json", "Output as JSON")
273
+ .action(async (documentId, options) => {
274
+ const resolvedAppId = resolveAppId(undefined, options);
275
+ const client = new ApiClient();
276
+ try {
277
+ const result = await client.listDocumentPermissions(resolvedAppId, documentId);
278
+ const list = Array.isArray(result) ? result : result?.permissions ?? [];
279
+ if (options.json) {
280
+ json(list);
281
+ return;
282
+ }
283
+ if (list.length === 0) {
284
+ info("No permissions found.");
285
+ return;
286
+ }
287
+ console.log(formatTable(list, [
288
+ { header: "USER_ID", key: "userId", format: formatId },
289
+ { header: "EMAIL", key: "email", flex: true },
290
+ { header: "PERMISSION", key: "permission" },
291
+ { header: "GRANTED", key: "grantedAt", format: formatDate },
292
+ ]));
293
+ }
294
+ catch (err) {
295
+ error(err.message);
296
+ process.exit(1);
297
+ }
298
+ });
299
+ // Grant (or update) a user-level permission
300
+ permissions
301
+ .command("grant")
302
+ .description("Grant or update a user's permission on a document")
303
+ .argument("<document-id>", "Document ID")
304
+ .option("--user-id <id>", "User ID to grant the permission to")
305
+ .option("--email <email>", "Email of the user to grant the permission to")
306
+ .requiredOption("--permission <permission>", "Permission level: reader or read-write")
307
+ .option("--app <app-id>", "App ID")
308
+ .option("--json", "Output as JSON")
309
+ .action(async (documentId, options) => {
310
+ if (!options.userId && !options.email) {
311
+ error("Either --user-id or --email is required.");
312
+ process.exit(1);
313
+ }
314
+ if (options.userId && options.email) {
315
+ error("Provide only one of --user-id or --email, not both.");
316
+ process.exit(1);
317
+ }
318
+ if (!["reader", "read-write"].includes(options.permission)) {
319
+ error("Invalid --permission. Must be 'reader' or 'read-write'.");
320
+ process.exit(1);
321
+ }
322
+ const resolvedAppId = resolveAppId(undefined, options);
323
+ const client = new ApiClient();
324
+ try {
325
+ const entry = options.userId
326
+ ? { userId: options.userId, permission: options.permission }
327
+ : { email: options.email, permission: options.permission };
328
+ const result = await client.grantDocumentPermission(resolvedAppId, documentId, [entry]);
329
+ if (options.json) {
330
+ json(result);
331
+ return;
332
+ }
333
+ const target = options.userId ? options.userId : options.email;
334
+ success(`Permission '${options.permission}' granted to ${target}.`);
335
+ }
336
+ catch (err) {
337
+ error(err.message);
338
+ process.exit(1);
339
+ }
340
+ });
341
+ // Revoke a user-level permission
342
+ permissions
343
+ .command("revoke")
344
+ .description("Revoke a user's permission on a document")
345
+ .argument("<document-id>", "Document ID")
346
+ .argument("[user-id]", "User ID to revoke (or use --email)")
347
+ .option("--email <email>", "Email of the user to revoke (alternative to <user-id>)")
348
+ .option("--app <app-id>", "App ID")
349
+ .option("-y, --yes", "Skip confirmation prompt")
350
+ .action(async (documentId, userId, options) => {
351
+ if (!userId && !options.email) {
352
+ error("Either a <user-id> argument or --email is required.");
353
+ process.exit(1);
354
+ }
355
+ if (userId && options.email) {
356
+ error("Provide only one of <user-id> or --email, not both.");
357
+ process.exit(1);
358
+ }
359
+ const target = userId ?? options.email;
360
+ const resolvedAppId = resolveAppId(undefined, options);
361
+ if (!options.yes) {
362
+ let confirm;
363
+ try {
364
+ confirm = await confirmPrompt(`Revoke permission for ${target} on document ${documentId}?`);
365
+ }
366
+ catch (err) {
367
+ error(err.message);
368
+ process.exit(1);
369
+ }
370
+ if (!confirm) {
371
+ info("Cancelled.");
372
+ return;
373
+ }
374
+ }
375
+ const client = new ApiClient();
376
+ try {
377
+ await client.revokeDocumentPermission(resolvedAppId, documentId, {
378
+ userId,
379
+ email: options.email,
380
+ });
381
+ success(`Permission revoked for ${target}.`);
382
+ }
383
+ catch (err) {
384
+ error(err.message);
385
+ process.exit(1);
386
+ }
387
+ });
388
+ // ---- Records introspection subcommand group ----
389
+ const records = documents
390
+ .command("records")
391
+ .description("Inspect a document's models and records");
392
+ // List model names
393
+ records
394
+ .command("models")
395
+ .description("List model names in a document")
396
+ .argument("<document-id>", "Document ID")
397
+ .option("--app <app-id>", "App ID")
398
+ .option("--json", "Output as JSON")
399
+ .action(async (documentId, options) => {
400
+ const resolvedAppId = resolveAppId(undefined, options);
401
+ const client = new ApiClient();
402
+ try {
403
+ const result = await client.getDocumentSchema(resolvedAppId, documentId);
404
+ const models = result?.modelNames ?? Object.keys(result?.schema?.models ?? {});
405
+ if (options.json) {
406
+ json(models);
407
+ return;
408
+ }
409
+ if (models.length === 0) {
410
+ info("No models found.");
411
+ return;
412
+ }
413
+ for (const m of models) {
414
+ console.log(` ${m}`);
415
+ }
416
+ }
417
+ catch (err) {
418
+ error(err.message);
419
+ process.exit(1);
420
+ }
421
+ });
422
+ // Describe a model's fields and indexes
423
+ records
424
+ .command("describe")
425
+ .description("Show a model's fields and indexes")
426
+ .argument("<document-id>", "Document ID")
427
+ .argument("<model-name>", "Model name")
428
+ .option("--app <app-id>", "App ID")
429
+ .option("--json", "Output as JSON")
430
+ .action(async (documentId, modelName, options) => {
431
+ const resolvedAppId = resolveAppId(undefined, options);
432
+ const client = new ApiClient();
433
+ try {
434
+ const result = await client.getDocumentSchema(resolvedAppId, documentId);
435
+ const model = result?.schema?.models?.[modelName];
436
+ if (!model) {
437
+ if (options.json) {
438
+ json(null);
439
+ return;
440
+ }
441
+ info(`Model '${modelName}' not found in this document.`);
442
+ return;
443
+ }
444
+ const fieldsObj = model.fields ?? {};
445
+ const rows = Object.entries(fieldsObj).map(([name, meta]) => ({
446
+ field: name,
447
+ type: meta?.type ?? "unknown",
448
+ indexed: meta?.indexed ? "yes" : "",
449
+ unique: meta?.unique ? "yes" : "",
450
+ required: meta?.required ? "yes" : "",
451
+ }));
452
+ if (options.json) {
453
+ json({ fields: fieldsObj, constraints: model.constraints ?? {} });
454
+ return;
455
+ }
456
+ if (rows.length === 0) {
457
+ info("No fields detected for this model.");
458
+ return;
459
+ }
460
+ console.log(formatTable(rows, [
461
+ { header: "FIELD", key: "field", flex: true },
462
+ { header: "TYPE", key: "type" },
463
+ { header: "INDEXED", key: "indexed" },
464
+ { header: "UNIQUE", key: "unique" },
465
+ { header: "REQUIRED", key: "required" },
466
+ ]));
467
+ }
468
+ catch (err) {
469
+ error(err.message);
470
+ process.exit(1);
471
+ }
472
+ });
473
+ // Query records in a document model
474
+ records
475
+ .command("query")
476
+ .description("Query records in a document model")
477
+ .argument("<document-id>", "Document ID")
478
+ .argument("<model-name>", "Model name to query")
479
+ .option("--app <app-id>", "App ID")
480
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
481
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
482
+ .option("--limit <n>", "Maximum number of records to return (max 100)", parseInt)
483
+ .option("--cursor <cursor>", "Pagination cursor from a previous query")
484
+ .option("--json", "Output as JSON")
485
+ .action(async (documentId, modelName, options) => {
486
+ const resolvedAppId = resolveAppId(undefined, options);
487
+ const filter = parseFilterOptions(options);
488
+ const client = new ApiClient();
489
+ try {
490
+ const result = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { filter, limit: options.limit, cursor: options.cursor });
491
+ if (options.json) {
492
+ json(result);
493
+ return;
494
+ }
495
+ const items = result.items;
496
+ if (items.length === 0) {
497
+ info("No records found.");
498
+ return;
499
+ }
500
+ const allKeys = new Set();
501
+ for (const rec of items) {
502
+ for (const key of Object.keys(rec))
503
+ allKeys.add(key);
504
+ }
505
+ const orderedKeys = [];
506
+ if (allKeys.has("id")) {
507
+ orderedKeys.push("id");
508
+ allKeys.delete("id");
509
+ }
510
+ orderedKeys.push(...[...allKeys].sort());
511
+ const columns = orderedKeys.map((key) => ({
512
+ header: key.toUpperCase(),
513
+ key,
514
+ format: (v) => {
515
+ if (v === null || v === undefined)
516
+ return "—";
517
+ if (typeof v === "object")
518
+ return JSON.stringify(v);
519
+ return String(v);
520
+ },
521
+ }));
522
+ console.log(formatTable(items, columns));
523
+ if (result.nextCursor) {
524
+ info(`More results available. Use --cursor ${result.nextCursor}`);
525
+ }
526
+ }
527
+ catch (err) {
528
+ error(err.message);
529
+ process.exit(1);
530
+ }
531
+ });
532
+ // Get a single record by id (mirrors `databases records get`, issue #2357).
533
+ records
534
+ .command("get")
535
+ .description("Get a single record by id from a document model")
536
+ .argument("<document-id>", "Document ID")
537
+ .argument("<model-name>", "Model name")
538
+ .argument("<record-id>", "Record ID")
539
+ .option("--app <app-id>", "App ID")
540
+ .option("--json", "Output as JSON")
541
+ .action(async (documentId, modelName, recordId, options) => {
542
+ const resolvedAppId = resolveAppId(undefined, options);
543
+ const client = new ApiClient();
544
+ try {
545
+ // A single-record fetch is a query filtered by primary-key id (there is
546
+ // no dedicated get endpoint — reuse queryDocumentRecords, exactly as
547
+ // the `databases records get` twin reuses queryDatabaseRecords).
548
+ const result = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { filter: { id: recordId }, limit: 1 });
549
+ const record = result.items[0];
550
+ if (options.json) {
551
+ json(record ?? null);
552
+ return;
553
+ }
554
+ if (!record) {
555
+ info(`No record found with id ${recordId} in ${modelName}.`);
556
+ return;
557
+ }
558
+ // `get` is a data command, so its fields go to stdout via `result()`
559
+ // — the #711 split (`result()` = the data the caller asked for,
560
+ // `keyValue()` = a post-action diagnostic summary). Issue #2437; the
561
+ // databases twin renders identically.
562
+ for (const [key, value] of Object.entries(record)) {
563
+ const rendered = value === null || value === undefined
564
+ ? "—"
565
+ : typeof value === "object"
566
+ ? JSON.stringify(value)
567
+ : String(value);
568
+ printResult(key, rendered);
569
+ }
570
+ }
571
+ catch (err) {
572
+ error(err.message);
573
+ process.exit(1);
574
+ }
575
+ });
576
+ // Count records in a document model
577
+ records
578
+ .command("count")
579
+ .description("Count records in a document model")
580
+ .argument("<document-id>", "Document ID")
581
+ .argument("<model-name>", "Model name to count")
582
+ .option("--app <app-id>", "App ID")
583
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
584
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
585
+ .option("--json", "Output as JSON")
586
+ .action(async (documentId, modelName, options) => {
587
+ const resolvedAppId = resolveAppId(undefined, options);
588
+ const filter = parseFilterOptions(options);
589
+ const client = new ApiClient();
590
+ try {
591
+ const result = await client.countDocumentRecords(resolvedAppId, documentId, modelName, { filter });
592
+ if (options.json) {
593
+ json(result);
594
+ return;
595
+ }
596
+ console.log(` ${result.count}`);
597
+ }
598
+ catch (err) {
599
+ error(err.message);
600
+ process.exit(1);
601
+ }
602
+ });
603
+ // Aggregate records in a document model (issue #2437). Mirrors
604
+ // `databases records aggregate` flag for flag and rendering for rendering —
605
+ // including the deliberate `keyValue()` for the ungrouped scalar, so the two
606
+ // twins keep printing the same thing.
607
+ const AGGREGATE_OPS = ["count", "sum", "avg", "min", "max"];
608
+ records
609
+ .command("aggregate")
610
+ .description("Aggregate records in a document model (count/sum/avg/min/max, optional group-by)")
611
+ .argument("<document-id>", "Document ID")
612
+ .argument("<model-name>", "Model name")
613
+ .option("--app <app-id>", "App ID")
614
+ .requiredOption("--op <operation>", `Aggregate operation: ${AGGREGATE_OPS.join("|")}`)
615
+ .option("--field <field>", "Field to aggregate (required for sum/avg/min/max)")
616
+ .option("--group-by <field>", "Group results by this plain field (repeatable; StringSet fields are not supported)", (value, previous = []) => previous.concat(value), [])
617
+ .option("--filter <json>", "Filter as JSON")
618
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
619
+ .option("--json", "Output as JSON")
620
+ .action(async (documentId, modelName, options) => {
621
+ const resolvedAppId = resolveAppId(undefined, options);
622
+ if (!AGGREGATE_OPS.includes(options.op)) {
623
+ error(`Invalid --op "${options.op}". Expected one of: ${AGGREGATE_OPS.join(", ")}.`);
624
+ process.exit(1);
625
+ }
626
+ const operation = { type: options.op };
627
+ if (options.op === "count") {
628
+ if (options.field) {
629
+ error("--field is not valid for --op count.");
630
+ process.exit(1);
631
+ }
632
+ }
633
+ else {
634
+ if (!options.field) {
635
+ error(`--op ${options.op} requires --field.`);
636
+ process.exit(1);
637
+ }
638
+ operation.field = options.field;
639
+ }
640
+ const filter = parseFilterOptions(options);
641
+ const groupBy = options.groupBy || [];
642
+ const client = new ApiClient();
643
+ try {
644
+ const response = await client.aggregateDocumentRecords(resolvedAppId, documentId, modelName, { operations: [operation], groupBy, filter });
645
+ if (options.json) {
646
+ json(response);
647
+ return;
648
+ }
649
+ const aggregated = response?.result;
650
+ // Same labelling rule as the databases twin: the field name is
651
+ // reproduced verbatim, never case-folded (issue #2357).
652
+ const valueLabel = options.op === "count"
653
+ ? "COUNT"
654
+ : `${options.op.toUpperCase()}(${options.field})`;
655
+ const scalarLabel = options.op === "count"
656
+ ? "count"
657
+ : `${options.op.toLowerCase()}(${options.field})`;
658
+ if (groupBy.length === 0) {
659
+ const value = (aggregated ?? {})[options.op === "count" ? "count" : `${options.op}_${options.field}`];
660
+ keyValue(scalarLabel, value === null || value === undefined ? "—" : String(value));
661
+ return;
662
+ }
663
+ if (aggregated &&
664
+ typeof aggregated === "object" &&
665
+ !Array.isArray(aggregated) &&
666
+ Object.values(aggregated).every((v) => typeof v !== "object" || v === null)) {
667
+ const rows = Object.entries(aggregated).map(([group, value]) => ({
668
+ group,
669
+ value: value === null || value === undefined ? "—" : String(value),
670
+ }));
671
+ console.log(formatTable(rows, [
672
+ { header: "GROUP", key: "group" },
673
+ { header: valueLabel, key: "value" },
674
+ ]));
675
+ }
676
+ else {
677
+ console.log(JSON.stringify(aggregated ?? {}, null, 2));
678
+ }
679
+ }
680
+ catch (err) {
681
+ error(err.message);
682
+ process.exit(1);
683
+ }
684
+ });
685
+ // ---- Record writes (#1964 Phase 4) ----
686
+ // Server-side writes through the document facade: Yjs-first, CRDT-safe,
687
+ // broadcast to connected clients. Requires read-write or higher on the
688
+ // document (or an admin token). `--data` / `--data-file` are validated
689
+ // CLI-side before any request is sent.
690
+ // `--data`/`--data-file` parsing (including the object-shape check and the
691
+ // both-flags rule) is the shared `parseDataOption` helper, so these verbs
692
+ // behave and diagnose identically to `metadata` and `databases records`.
693
+ // Create or replace a record
694
+ records
695
+ .command("save")
696
+ .description("Create or replace a record in a document model")
697
+ .argument("<document-id>", "Document ID")
698
+ .argument("<model-name>", "Model name to write to")
699
+ .option("--app <app-id>", "App ID")
700
+ .option("--id <record-id>", "Record ID (a ULID is generated when omitted)")
701
+ .option("--data <json>", "Record fields as JSON (e.g. '{\"qty\":10}')")
702
+ .option("--data-file <file>", "Read record fields from a JSON file")
703
+ .option("--upsert-on <field>", "Update the record whose <field> matches instead of creating")
704
+ .option("--json", "Output as JSON")
705
+ .action(async (documentId, modelName, options) => {
706
+ const data = parseDataOption(options, "record fields");
707
+ const resolvedAppId = resolveAppId(undefined, options);
708
+ const recordId = options.id || ulid();
709
+ const writeOptions = options.upsertOn ? { upsertOn: options.upsertOn } : undefined;
710
+ const client = new ApiClient();
711
+ try {
712
+ const result = await client.saveDocumentRecord(resolvedAppId, documentId, modelName, { id: recordId, data, ...(writeOptions ? { options: writeOptions } : {}) });
713
+ if (options.json) {
714
+ json(result);
715
+ return;
716
+ }
717
+ success(`Record saved: ${result.record?.id ?? recordId}`);
718
+ }
719
+ catch (err) {
720
+ error(err.message);
721
+ process.exit(1);
722
+ }
723
+ });
724
+ // Merge fields into an existing record
725
+ records
726
+ .command("patch")
727
+ .description("Merge fields into an existing record in a document model")
728
+ .argument("<document-id>", "Document ID")
729
+ .argument("<model-name>", "Model name")
730
+ .argument("<record-id>", "Record ID to patch")
731
+ .option("--app <app-id>", "App ID")
732
+ .option("--data <json>", "Fields to merge as JSON (e.g. '{\"status\":\"closed\"}')")
733
+ .option("--data-file <file>", "Read fields from a JSON file")
734
+ .option("--json", "Output as JSON")
735
+ .action(async (documentId, modelName, recordId, options) => {
736
+ const data = parseDataOption(options, "fields to merge");
737
+ const resolvedAppId = resolveAppId(undefined, options);
738
+ const client = new ApiClient();
739
+ try {
740
+ const result = await client.patchDocumentRecord(resolvedAppId, documentId, modelName, recordId, { data });
741
+ if (options.json) {
742
+ json(result);
743
+ return;
744
+ }
745
+ success(`Record patched: ${recordId}`);
746
+ }
747
+ catch (err) {
748
+ error(err.message);
749
+ process.exit(1);
750
+ }
751
+ });
752
+ // Delete a record
753
+ records
754
+ .command("delete")
755
+ .description("Delete a record from a document model")
756
+ .argument("<document-id>", "Document ID")
757
+ .argument("<model-name>", "Model name")
758
+ .argument("<record-id>", "Record ID to delete")
759
+ .option("--app <app-id>", "App ID")
760
+ .option("-y, --yes", "Skip confirmation prompt")
761
+ .option("--json", "Output as JSON")
762
+ .action(async (documentId, modelName, recordId, options) => {
763
+ const resolvedAppId = resolveAppId(undefined, options);
764
+ if (!options.yes) {
765
+ const confirmed = await confirmPrompt(`Delete record ${recordId} from ${modelName} in document ${documentId}?`);
766
+ if (!confirmed) {
767
+ info("Cancelled.");
768
+ return;
769
+ }
770
+ }
771
+ const client = new ApiClient();
772
+ try {
773
+ const result = await client.deleteDocumentRecord(resolvedAppId, documentId, modelName, recordId);
774
+ if (options.json) {
775
+ json(result);
776
+ return;
777
+ }
778
+ // A delete of a missing record is a silent no-op server-side, so
779
+ // this reports the request outcome, not record existence.
780
+ success(`Record deleted: ${recordId}`);
781
+ }
782
+ catch (err) {
783
+ error(err.message);
784
+ process.exit(1);
785
+ }
786
+ });
787
+ // Apply an atomic multi-model operations blob
788
+ records
789
+ .command("bulk")
790
+ .description("Apply an atomic create/patch/delete operations blob to a document")
791
+ .argument("<document-id>", "Document ID")
792
+ .requiredOption("--data-file <file>", "JSON file with { operations: [...] } or a bare operations array. " +
793
+ "Each op is { model, action: create|patch|delete, id, data, precondition? } " +
794
+ "— `data` holds the record fields and is required (non-empty) on " +
795
+ "create/patch, not allowed on delete; a create `id` must be a 26-char " +
796
+ "uppercase Crockford ULID")
797
+ .option("--app <app-id>", "App ID")
798
+ .option("-y, --yes", "Skip confirmation prompt")
799
+ .option("--json", "Output as JSON")
800
+ .action(async (documentId, options) => {
801
+ const parsed = parseDataOption(options, "operations blob", {
802
+ allowArray: true,
803
+ });
804
+ const operations = Array.isArray(parsed) ? parsed : parsed?.operations;
805
+ if (!Array.isArray(operations) || operations.length === 0) {
806
+ error("--data-file must contain { operations: [...] } or a non-empty operations array.");
807
+ process.exit(1);
808
+ }
809
+ const resolvedAppId = resolveAppId(undefined, options);
810
+ if (!options.yes) {
811
+ const confirmed = await confirmPrompt(`Apply ${operations.length} operation(s) atomically to document ${documentId}?`);
812
+ if (!confirmed) {
813
+ info("Cancelled.");
814
+ return;
815
+ }
816
+ }
817
+ const client = new ApiClient();
818
+ try {
819
+ const result = await client.bulkDocumentRecords(resolvedAppId, documentId, operations);
820
+ if (options.json) {
821
+ json(result);
822
+ return;
823
+ }
824
+ success(`Applied ${result.applied} operation(s): ` +
825
+ `${result.added.length} added, ${result.updated.length} updated, ${result.deleted} deleted.`);
826
+ }
827
+ catch (err) {
828
+ error(err.message);
829
+ process.exit(1);
830
+ }
831
+ });
832
+ // Dump a document's records grouped by model (CLI-side composition)
833
+ documents
834
+ .command("dump")
835
+ .description("Dump a document's records grouped by model as JSON")
836
+ .argument("<document-id>", "Document ID")
837
+ .option("--app <app-id>", "App ID")
838
+ .option("--output <file>", "Write the JSON dump to a file instead of stdout")
839
+ .option("--json", "Output as JSON (default)")
840
+ .action(async (documentId, options) => {
841
+ const resolvedAppId = resolveAppId(undefined, options);
842
+ const client = new ApiClient();
843
+ try {
844
+ // Model names come from the schema; records are assembled from paged
845
+ // reads per model (not a single atomic snapshot — the paged path is
846
+ // the contract, same pattern as `databases export`).
847
+ const schema = await client.getDocumentSchema(resolvedAppId, documentId);
848
+ const modelNames = schema?.modelNames ?? Object.keys(schema?.schema?.models ?? {});
849
+ const grouped = {};
850
+ for (const modelName of modelNames) {
851
+ const records = [];
852
+ let cursor;
853
+ do {
854
+ const page = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { limit: 100, cursor });
855
+ records.push(...page.items);
856
+ cursor = page.nextCursor;
857
+ } while (cursor);
858
+ grouped[modelName] = records;
859
+ }
860
+ const output = JSON.stringify(grouped, null, 2);
861
+ if (options.output) {
862
+ fs.writeFileSync(options.output, output);
863
+ success(`Document dump written to ${options.output}`);
864
+ return;
865
+ }
866
+ console.log(output);
867
+ }
868
+ catch (err) {
869
+ error(err.message);
870
+ process.exit(1);
871
+ }
872
+ });
873
+ // Document statistics (platform-vocabulary projection)
874
+ documents
875
+ .command("stats")
876
+ .description("Show a document's record/model/blob counts and approximate size")
877
+ .argument("<document-id>", "Document ID")
878
+ .option("--app <app-id>", "App ID")
879
+ .option("--json", "Output as JSON")
880
+ .action(async (documentId, options) => {
881
+ const resolvedAppId = resolveAppId(undefined, options);
882
+ const client = new ApiClient();
883
+ try {
884
+ const result = await client.getDocumentStats(resolvedAppId, documentId);
885
+ if (options.json) {
886
+ json(result);
887
+ return;
888
+ }
889
+ keyValue("Document ID", result.documentId);
890
+ keyValue("Records", result.recordCount);
891
+ keyValue("Models", result.modelCount);
892
+ keyValue("Blobs", result.blobCount);
893
+ keyValue("Size (bytes, approx)", result.sizeBytes);
894
+ keyValue("Last modified", result.lastModifiedAt ? formatDate(result.lastModifiedAt) : "—");
895
+ }
896
+ catch (err) {
897
+ error(err.message);
898
+ process.exit(1);
899
+ }
900
+ });
13
901
  // Transfer document ownership
14
902
  documents
15
903
  .command("transfer-owner")
@@ -43,15 +931,14 @@ Examples:
43
931
  process.exit(1);
44
932
  }
45
933
  if (!options.yes) {
46
- const inquirer = await import("inquirer");
47
- const { confirm } = await inquirer.default.prompt([
48
- {
49
- type: "confirm",
50
- name: "confirm",
51
- message: `Transfer ownership of document ${documentId} to user ${newOwnerId}? This cannot be undone.`,
52
- default: false,
53
- },
54
- ]);
934
+ let confirm;
935
+ try {
936
+ confirm = await confirmPrompt(`Transfer ownership of document ${documentId} to user ${newOwnerId}? This cannot be undone.`);
937
+ }
938
+ catch (err) {
939
+ error(err.message);
940
+ process.exit(1);
941
+ }
55
942
  if (!confirm) {
56
943
  info("Cancelled.");
57
944
  return;
@@ -138,6 +1025,328 @@ Examples:
138
1025
  process.exit(1);
139
1026
  }
140
1027
  });
1028
+ // ---- Link access ("anyone with the link") ----
1029
+ const linkAccess = documents
1030
+ .command("link-access")
1031
+ .description('Manage "anyone with the link" access on a document');
1032
+ linkAccess
1033
+ .command("get")
1034
+ .description("Show the current link-access level for a document")
1035
+ .argument("<document-id>", "Document ID")
1036
+ .option("--app <app-id>", "App ID")
1037
+ .option("--json", "Output as JSON")
1038
+ .action(async (documentId, options) => {
1039
+ const resolvedAppId = resolveAppId(undefined, options);
1040
+ const client = new ApiClient();
1041
+ try {
1042
+ const state = await client.getDocumentLinkAccess(resolvedAppId, documentId);
1043
+ const level = state?.linkAccess ?? null;
1044
+ if (options.json) {
1045
+ json({ documentId, linkAccess: level });
1046
+ return;
1047
+ }
1048
+ if (!level) {
1049
+ info("Link access is off for this document.");
1050
+ return;
1051
+ }
1052
+ keyValue("Document", documentId);
1053
+ keyValue("Link access", level);
1054
+ }
1055
+ catch (err) {
1056
+ error(err.message);
1057
+ process.exit(1);
1058
+ }
1059
+ });
1060
+ linkAccess
1061
+ .command("set")
1062
+ .description("Turn on link access at a given level")
1063
+ .argument("<document-id>", "Document ID")
1064
+ .requiredOption("--level <level>", "Link access level: reader or read-write")
1065
+ .option("--app <app-id>", "App ID")
1066
+ .option("--json", "Output as JSON")
1067
+ .action(async (documentId, options) => {
1068
+ const resolvedAppId = resolveAppId(undefined, options);
1069
+ const client = new ApiClient();
1070
+ try {
1071
+ const result = await client.setDocumentLinkAccess(resolvedAppId, documentId, options.level);
1072
+ if (options.json) {
1073
+ json(result);
1074
+ return;
1075
+ }
1076
+ success(`Link access set to '${options.level}' for document ${documentId}.`);
1077
+ }
1078
+ catch (err) {
1079
+ error(err.message);
1080
+ process.exit(1);
1081
+ }
1082
+ });
1083
+ linkAccess
1084
+ .command("clear")
1085
+ .description("Turn off link access")
1086
+ .argument("<document-id>", "Document ID")
1087
+ .option("--app <app-id>", "App ID")
1088
+ .option("--json", "Output as JSON")
1089
+ .action(async (documentId, options) => {
1090
+ const resolvedAppId = resolveAppId(undefined, options);
1091
+ const client = new ApiClient();
1092
+ try {
1093
+ const result = await client.clearDocumentLinkAccess(resolvedAppId, documentId);
1094
+ if (options.json) {
1095
+ json(result);
1096
+ return;
1097
+ }
1098
+ success(`Link access turned off for document ${documentId}.`);
1099
+ }
1100
+ catch (err) {
1101
+ error(err.message);
1102
+ process.exit(1);
1103
+ }
1104
+ });
1105
+ // ---- Export / Import commands ----
1106
+ documents
1107
+ .command("export")
1108
+ .description("Export a document (Yjs state, blobs, permissions, aliases)")
1109
+ .argument("[app-id]", "App ID (uses current app if not specified)")
1110
+ .argument("<document-id>", "Document ID to export")
1111
+ .option("--app <app-id>", "App ID")
1112
+ .option("--output <dir>", "Output directory", "./primitive-export")
1113
+ .option("--no-blobs", "Skip blob data")
1114
+ .option("--json", "Output as JSON")
1115
+ .action(async (first, second, options) => {
1116
+ let resolvedAppId;
1117
+ let documentId;
1118
+ if (second && !second.startsWith("-")) {
1119
+ resolvedAppId = resolveAppId(first, options);
1120
+ documentId = second;
1121
+ }
1122
+ else {
1123
+ resolvedAppId = resolveAppId(undefined, options);
1124
+ documentId = first;
1125
+ }
1126
+ if (!documentId) {
1127
+ error("Document ID is required.");
1128
+ process.exit(1);
1129
+ }
1130
+ const client = new ApiClient();
1131
+ try {
1132
+ await exportSingleDocument(client, resolvedAppId, documentId, options.output, options.blobs !== false ? true : false, options.json);
1133
+ }
1134
+ catch (err) {
1135
+ error(err.message);
1136
+ process.exit(1);
1137
+ }
1138
+ });
1139
+ documents
1140
+ .command("export-all")
1141
+ .description("Export all documents for a user")
1142
+ .argument("[app-id]", "App ID (uses current app if not specified)")
1143
+ .requiredOption("--user-id <id>", "User ID to export documents for")
1144
+ .option("--app <app-id>", "App ID")
1145
+ .option("--owned-only", "Only export documents owned by the user")
1146
+ .option("--output <dir>", "Output directory", "./primitive-export")
1147
+ .option("--no-blobs", "Skip blob data")
1148
+ .option("--json", "Output as JSON")
1149
+ .action(async (appIdArg, options) => {
1150
+ const resolvedAppId = resolveAppId(appIdArg, options);
1151
+ const client = new ApiClient();
1152
+ const includeBlobs = options.blobs !== false;
1153
+ try {
1154
+ const documents = await client.listAdminDocuments(resolvedAppId, options.userId);
1155
+ let docList = Array.isArray(documents) ? documents : [];
1156
+ if (options.ownedOnly) {
1157
+ docList = docList.filter((d) => d.permission === "owner");
1158
+ }
1159
+ if (docList.length === 0) {
1160
+ info("No documents found.");
1161
+ return;
1162
+ }
1163
+ info(`Exporting ${docList.length} document(s)...`);
1164
+ const exportedIds = [];
1165
+ for (const doc of docList) {
1166
+ const docId = doc.documentId || doc.id;
1167
+ try {
1168
+ await exportSingleDocument(client, resolvedAppId, docId, options.output, includeBlobs, false);
1169
+ exportedIds.push(docId);
1170
+ }
1171
+ catch (err) {
1172
+ warn(`Failed to export ${docId}: ${err.message}`);
1173
+ }
1174
+ }
1175
+ // Write manifest. `export-all` is per-user, and each run REPLACES the
1176
+ // manifest with its own ids — so exporting a second user into the same
1177
+ // directory leaves the first user's documents on disk but unreachable
1178
+ // through the manifest an import reads. The supported migration is one
1179
+ // directory per user; a run that would drop ids says so (#3135).
1180
+ const manifestPath = path.join(options.output, "manifest.json");
1181
+ if (fs.existsSync(manifestPath)) {
1182
+ try {
1183
+ const existing = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
1184
+ const dropped = (Array.isArray(existing?.documents) ? existing.documents : []).filter((id) => !exportedIds.includes(id));
1185
+ if (dropped.length > 0) {
1186
+ warn(`The manifest already in ${options.output} lists ` +
1187
+ `${dropped.length} document(s) this export does not: ` +
1188
+ `${dropped.join(", ")}. Replacing it leaves them on disk but ` +
1189
+ `no longer reachable through the manifest an import reads — ` +
1190
+ `export each user into their own directory.`);
1191
+ }
1192
+ }
1193
+ catch {
1194
+ // An unreadable manifest is not a reason to refuse the export.
1195
+ }
1196
+ }
1197
+ const manifest = {
1198
+ version: 1,
1199
+ exportedAt: new Date().toISOString(),
1200
+ sourceAppId: resolvedAppId,
1201
+ documentCount: exportedIds.length,
1202
+ documents: exportedIds,
1203
+ };
1204
+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
1205
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
1206
+ if (options.json) {
1207
+ json(manifest);
1208
+ }
1209
+ else {
1210
+ success(`Exported ${exportedIds.length} document(s) to ${options.output}`);
1211
+ }
1212
+ }
1213
+ catch (err) {
1214
+ error(err.message);
1215
+ process.exit(1);
1216
+ }
1217
+ });
1218
+ documents
1219
+ .command("import")
1220
+ .description("Import documents from an export directory")
1221
+ .argument("[app-id]", "App ID (uses current app if not specified)")
1222
+ .argument("<path>", "Path to export directory or single document directory")
1223
+ .option("--app <app-id>", "App ID")
1224
+ .option("--aliases <mode>", "Alias conflict handling: overwrite or skip", "skip")
1225
+ // `--overwrite` has never replaced a document: the import path issues no
1226
+ // delete and calls `import/state`, whose room handler merges the exported
1227
+ // state into the document with `Y.applyUpdate`. The description says so
1228
+ // (#3135), and names the one id remapping on top of it — plus the one
1229
+ // format that is installed rather than merged.
1230
+ .option("--overwrite", "Merge the exported state into a document that already exists (a root document export is merged into the target user's root document; a large-document export is installed, so it needs a document that holds nothing yet)")
1231
+ .option("--dry-run", "Show what would be imported without making changes")
1232
+ .option("--owner <userId-or-email>", "User ID or email to set as document owner (admin only)")
1233
+ .option("--json", "Output as JSON")
1234
+ .action(async (first, second, options) => {
1235
+ let resolvedAppId;
1236
+ let importPath;
1237
+ if (second && !second.startsWith("-")) {
1238
+ resolvedAppId = resolveAppId(first, options);
1239
+ importPath = second;
1240
+ }
1241
+ else {
1242
+ resolvedAppId = resolveAppId(undefined, options);
1243
+ importPath = first;
1244
+ }
1245
+ if (!importPath) {
1246
+ error("Import path is required.");
1247
+ process.exit(1);
1248
+ }
1249
+ const client = new ApiClient();
1250
+ // Resolve --owner to a userId through the one shared lookup (#2763).
1251
+ let ownerUserId;
1252
+ if (options.owner) {
1253
+ try {
1254
+ ownerUserId = await resolveOwnerUserId(client, resolvedAppId, options.owner);
1255
+ }
1256
+ catch (err) {
1257
+ error(err.message);
1258
+ process.exit(1);
1259
+ }
1260
+ }
1261
+ try {
1262
+ // Determine if this is a manifest-based export or a single document
1263
+ const manifestPath = path.join(importPath, "manifest.json");
1264
+ let docDirs = [];
1265
+ if (fs.existsSync(manifestPath)) {
1266
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
1267
+ for (const docId of manifest.documents) {
1268
+ const docDir = path.join(importPath, "documents", docId);
1269
+ if (fs.existsSync(docDir)) {
1270
+ docDirs.push(docDir);
1271
+ }
1272
+ }
1273
+ }
1274
+ else if (fs.existsSync(path.join(importPath, "metadata.json"))) {
1275
+ // Single document directory
1276
+ docDirs = [importPath];
1277
+ }
1278
+ else if (fs.existsSync(path.join(importPath, "documents"))) {
1279
+ // Export directory without manifest — discover documents
1280
+ const entries = fs.readdirSync(path.join(importPath, "documents"), { withFileTypes: true });
1281
+ for (const entry of entries) {
1282
+ if (entry.isDirectory()) {
1283
+ docDirs.push(path.join(importPath, "documents", entry.name));
1284
+ }
1285
+ }
1286
+ }
1287
+ else {
1288
+ error("No valid export data found at the specified path.");
1289
+ process.exit(1);
1290
+ }
1291
+ if (docDirs.length === 0) {
1292
+ info("No documents to import.");
1293
+ return;
1294
+ }
1295
+ const summary = {
1296
+ created: 0,
1297
+ updated: 0,
1298
+ skipped: 0,
1299
+ blobsUploaded: 0,
1300
+ aliasesSet: 0,
1301
+ aliasesSkipped: 0,
1302
+ rootDocuments: [],
1303
+ };
1304
+ // Where every root-marked export in this run lands, decided from reads
1305
+ // alone and before any write (#3135): a refusal, or two exports
1306
+ // competing for one user's root document, is reported up front.
1307
+ const rootPlans = await planRootImports(client, resolvedAppId, docDirs, options.owner, ownerUserId, options.overwrite || false);
1308
+ // Nothing is created until every artifact is one this CLI can install:
1309
+ // a refusal halfway through a multi-document import would leave the
1310
+ // app half-populated (#2816). A root export is never installed as a
1311
+ // chain — `planRootImports` has already refused a format-2 one — so it
1312
+ // is not vouched for here.
1313
+ for (const docDir of docDirs) {
1314
+ if (rootPlans.has(docDir))
1315
+ continue;
1316
+ if (!largeDocumentArtifactAt(docDir))
1317
+ continue;
1318
+ const metadataPath = path.join(docDir, "metadata.json");
1319
+ const documentId = fs.existsSync(metadataPath)
1320
+ ? JSON.parse(fs.readFileSync(metadataPath, "utf-8")).documentId
1321
+ : path.basename(docDir);
1322
+ readChainArtifact(docDir, documentId);
1323
+ }
1324
+ for (const docDir of docDirs) {
1325
+ await importSingleDocument(client, resolvedAppId, docDir, options.overwrite || false, options.aliases || "skip", options.dryRun || false, summary, ownerUserId, rootPlans.get(docDir));
1326
+ }
1327
+ if (options.json) {
1328
+ json(summary);
1329
+ }
1330
+ else {
1331
+ success(`Import complete:`);
1332
+ keyValue(" Documents created", String(summary.created));
1333
+ if (summary.updated > 0)
1334
+ keyValue(" Documents updated", String(summary.updated));
1335
+ if (summary.skipped > 0)
1336
+ keyValue(" Documents skipped", String(summary.skipped));
1337
+ if (summary.blobsUploaded > 0)
1338
+ keyValue(" Blobs uploaded", String(summary.blobsUploaded));
1339
+ if (summary.aliasesSet > 0)
1340
+ keyValue(" Aliases set", String(summary.aliasesSet));
1341
+ if (summary.aliasesSkipped > 0)
1342
+ keyValue(" Aliases skipped", String(summary.aliasesSkipped));
1343
+ }
1344
+ }
1345
+ catch (err) {
1346
+ error(err.message);
1347
+ process.exit(1);
1348
+ }
1349
+ });
141
1350
  // Revoke group permission
142
1351
  groupPermissions
143
1352
  .command("revoke")
@@ -150,15 +1359,14 @@ Examples:
150
1359
  .action(async (documentId, groupType, groupId, options) => {
151
1360
  const resolvedAppId = resolveAppId(undefined, options);
152
1361
  if (!options.yes) {
153
- const inquirer = await import("inquirer");
154
- const { confirm } = await inquirer.default.prompt([
155
- {
156
- type: "confirm",
157
- name: "confirm",
158
- message: `Revoke permission for group ${groupType}/${groupId} on document ${documentId}?`,
159
- default: false,
160
- },
161
- ]);
1362
+ let confirm;
1363
+ try {
1364
+ confirm = await confirmPrompt(`Revoke permission for group ${groupType}/${groupId} on document ${documentId}?`);
1365
+ }
1366
+ catch (err) {
1367
+ error(err.message);
1368
+ process.exit(1);
1369
+ }
162
1370
  if (!confirm) {
163
1371
  info("Cancelled.");
164
1372
  return;
@@ -175,4 +1383,839 @@ Examples:
175
1383
  }
176
1384
  });
177
1385
  }
1386
+ // ============================================
1387
+ // Helper functions for export/import
1388
+ // ============================================
1389
+ /**
1390
+ * Write a large document's export chain into `docDir` (#2816, behavior 20).
1391
+ *
1392
+ * The layout mirrors the chain and is applied in that order on import:
1393
+ *
1394
+ * ```
1395
+ * chain.json what this artifact is, and the order to apply it in
1396
+ * snapshot/ manifest.json + {model}/{n}.ndjson.gz, when there is a base
1397
+ * epochs/{E}.yjs each sealed overlay after the base's epoch, oldest first
1398
+ * current.yjs the open epoch's overlay
1399
+ * ```
1400
+ *
1401
+ * The server refuses a chain it cannot vouch for, so nothing here has to guess
1402
+ * whether an artifact is complete; what this function must not do is write a
1403
+ * PARTIAL one, which is why `chain.json` — the file that says "this is a
1404
+ * complete v2 export" — is written last.
1405
+ *
1406
+ * Returns the bytes written, which is what `--json` reports as the document's
1407
+ * size: for a large document that is the artifact, not one Yjs update.
1408
+ */
1409
+ async function exportLargeDocumentChain(client, appId, documentId, docDir) {
1410
+ const chain = await client.exportDocumentChain(appId, documentId);
1411
+ let bytes = 0;
1412
+ // The open epoch's overlay travels inline: the rotation threshold bounds it.
1413
+ const current = Buffer.from(chain.current.update, "base64");
1414
+ fs.writeFileSync(path.join(docDir, "current.yjs"), current);
1415
+ bytes += current.byteLength;
1416
+ const overlays = [];
1417
+ if (Array.isArray(chain.overlays) && chain.overlays.length > 0) {
1418
+ const epochsDir = path.join(docDir, "epochs");
1419
+ fs.mkdirSync(epochsDir, { recursive: true });
1420
+ for (const overlay of chain.overlays) {
1421
+ const archive = await client.downloadDocumentArtifact(appId, overlay.download.path);
1422
+ fs.writeFileSync(path.join(epochsDir, `${overlay.epoch}.yjs`), archive);
1423
+ bytes += archive.byteLength;
1424
+ overlays.push({ epoch: overlay.epoch, sealedAt: overlay.sealedAt ?? null });
1425
+ }
1426
+ }
1427
+ let base = null;
1428
+ if (chain.base) {
1429
+ const snapshotDir = path.join(docDir, "snapshot");
1430
+ fs.mkdirSync(snapshotDir, { recursive: true });
1431
+ const manifestBytes = await client.downloadDocumentArtifact(appId, chain.base.download.path);
1432
+ fs.writeFileSync(path.join(snapshotDir, "manifest.json"), manifestBytes);
1433
+ const manifest = JSON.parse(manifestBytes.toString("utf-8"));
1434
+ for (const chunk of manifest.chunks ?? []) {
1435
+ // Addressed within the granted build — `{model}/{n}` — never by key.
1436
+ const index = chunkIndexFromKey(chunk.key);
1437
+ const body = await client.downloadDocumentArtifact(appId, `${chain.base.download.path}/${chunk.model}/${index}`);
1438
+ const modelDir = path.join(snapshotDir, chunk.model);
1439
+ fs.mkdirSync(modelDir, { recursive: true });
1440
+ fs.writeFileSync(path.join(modelDir, `${index}.ndjson.gz`), body);
1441
+ bytes += body.byteLength;
1442
+ }
1443
+ base = {
1444
+ epoch: chain.base.epoch,
1445
+ buildId: chain.base.buildId,
1446
+ rows: chain.base.rows,
1447
+ };
1448
+ }
1449
+ // Last, and without the signatures: a grant is this run's read of the
1450
+ // document, and an artifact that outlives it must not carry one.
1451
+ fs.writeFileSync(path.join(docDir, "chain.json"), JSON.stringify({
1452
+ version: 2,
1453
+ documentFormat: 2,
1454
+ documentId,
1455
+ epoch: chain.epoch,
1456
+ base,
1457
+ overlays,
1458
+ current: { epoch: chain.current.epoch, file: "current.yjs" },
1459
+ }, null, 2));
1460
+ return bytes;
1461
+ }
1462
+ /** The chunk number out of a manifest entry's key (`…/{model}/{n}.ndjson.gz`). */
1463
+ function chunkIndexFromKey(key) {
1464
+ const match = /\/(\d+)\.ndjson\.gz$/.exec(String(key ?? ""));
1465
+ if (!match) {
1466
+ throw new Error(`Snapshot manifest names a chunk this CLI cannot address: ${key}`);
1467
+ }
1468
+ return Number(match[1]);
1469
+ }
1470
+ async function exportSingleDocument(client, appId, documentId, outputDir, includeBlobs, jsonOutput) {
1471
+ const docDir = path.join(outputDir, "documents", documentId);
1472
+ fs.mkdirSync(docDir, { recursive: true });
1473
+ // 1. Fetch document metadata
1474
+ const docMeta = await client.getDocument(appId, documentId);
1475
+ // 2. Export the document's state. A legacy document is one blob; a large
1476
+ // one (#2816) is the chain — snapshot, sealed overlays, open epoch —
1477
+ // because the blob is exactly the whole-document-in-memory cost format 2
1478
+ // exists to avoid.
1479
+ let stateBytes;
1480
+ if (Number(docMeta?.documentFormat) === 2) {
1481
+ stateBytes = await exportLargeDocumentChain(client, appId, documentId, docDir);
1482
+ }
1483
+ else {
1484
+ const stateResult = await client.exportDocumentState(appId, documentId);
1485
+ fs.writeFileSync(path.join(docDir, "document.yjs"), Buffer.from(stateResult.state, "base64"));
1486
+ stateBytes = stateResult.byteLength;
1487
+ }
1488
+ // 3. Fetch permissions
1489
+ let permResult = null;
1490
+ try {
1491
+ permResult = await client.listDocumentPermissions(appId, documentId);
1492
+ }
1493
+ catch {
1494
+ // Permissions endpoint might not return data for all docs
1495
+ }
1496
+ // 4. Fetch pending invitations (deferred grants). An older server answers
1497
+ // 403/404 here; the export still writes the permission rows.
1498
+ let pendingResult = null;
1499
+ try {
1500
+ pendingResult = await client.listDocumentPendingInvitations(appId, documentId);
1501
+ }
1502
+ catch {
1503
+ // May not have pending invitations, or the server predates the endpoint
1504
+ }
1505
+ const permissionsExport = buildPermissionsExport(permResult, pendingResult);
1506
+ fs.writeFileSync(path.join(docDir, "permissions.json"), JSON.stringify(permissionsExport, null, 2));
1507
+ // 5. Fetch aliases (user-scoped only)
1508
+ let aliases = [];
1509
+ try {
1510
+ const aliasResult = await client.listDocumentAliases(appId, documentId);
1511
+ aliases = (Array.isArray(aliasResult) ? aliasResult : aliasResult?.aliases || [])
1512
+ .filter((a) => (a.scope || a.aliasScope) === "user");
1513
+ }
1514
+ catch {
1515
+ // May not have aliases
1516
+ }
1517
+ // 6. Write metadata. A large document says so here as well as in
1518
+ // `chain.json`: the format decides how the artifact has to be installed,
1519
+ // and an import that reads only `metadata.json` must not mistake one for
1520
+ // a legacy document (#2816).
1521
+ const metadata = {
1522
+ documentId: docMeta.documentId || documentId,
1523
+ title: docMeta.title,
1524
+ tags: docMeta.tags || [],
1525
+ ...(Number(docMeta?.documentFormat) === 2 ? { documentFormat: 2 } : {}),
1526
+ createdAt: docMeta.createdAt,
1527
+ createdBy: docMeta.createdByEmail || docMeta.createdBy,
1528
+ aliases: aliases.map((a) => ({
1529
+ aliasScope: a.scope || a.aliasScope,
1530
+ aliasKey: a.aliasKey,
1531
+ })),
1532
+ };
1533
+ fs.writeFileSync(path.join(docDir, "metadata.json"), JSON.stringify(metadata, null, 2));
1534
+ // 7. Blobs
1535
+ if (includeBlobs) {
1536
+ let blobs = [];
1537
+ try {
1538
+ const blobResult = await client.listDocumentBlobs(appId, documentId);
1539
+ blobs = Array.isArray(blobResult) ? blobResult : blobResult?.items || blobResult?.blobs || [];
1540
+ }
1541
+ catch {
1542
+ // May not have blobs
1543
+ }
1544
+ if (blobs.length > 0) {
1545
+ const blobsDir = path.join(docDir, "blobs");
1546
+ fs.mkdirSync(blobsDir, { recursive: true });
1547
+ const blobIndex = blobs.map((b) => ({
1548
+ blobId: b.blobId,
1549
+ filename: b.filename,
1550
+ contentType: b.contentType,
1551
+ sha256: b.sha256,
1552
+ numBytes: b.numBytes,
1553
+ }));
1554
+ fs.writeFileSync(path.join(blobsDir, "index.json"), JSON.stringify(blobIndex, null, 2));
1555
+ // Download blobs (sequentially to avoid overwhelming the server)
1556
+ for (const blob of blobs) {
1557
+ const data = await client.downloadBlob(appId, documentId, blob.blobId);
1558
+ fs.writeFileSync(path.join(blobsDir, `${blob.blobId}.bin`), data);
1559
+ }
1560
+ }
1561
+ }
1562
+ if (jsonOutput) {
1563
+ json({
1564
+ documentId,
1565
+ title: metadata.title,
1566
+ stateBytes,
1567
+ permissions: permissionsExport.length,
1568
+ aliases: aliases.length,
1569
+ exportPath: docDir,
1570
+ });
1571
+ }
1572
+ else {
1573
+ success(`Exported document ${documentId} (${metadata.title || "untitled"}) to ${docDir}`);
1574
+ }
1575
+ }
1576
+ /**
1577
+ * Whether `docDir` holds a large document's export (#2816, behavior 20).
1578
+ *
1579
+ * Either marker is enough: `chain.json` is what the chain export writes last,
1580
+ * and `metadata.json` carries the format for artifacts inspected on their own.
1581
+ */
1582
+ function largeDocumentArtifactAt(docDir) {
1583
+ if (fs.existsSync(path.join(docDir, "chain.json")))
1584
+ return true;
1585
+ const metadataPath = path.join(docDir, "metadata.json");
1586
+ if (!fs.existsSync(metadataPath))
1587
+ return false;
1588
+ try {
1589
+ const metadata = JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
1590
+ return Number(metadata?.documentFormat) === 2;
1591
+ }
1592
+ catch {
1593
+ return false;
1594
+ }
1595
+ }
1596
+ /**
1597
+ * Read (and vouch for) a large document's chain artifact.
1598
+ *
1599
+ * `chain.json` is what the export writes LAST, so its absence means the
1600
+ * artifact is partial — a directory recognizable as a large document with no
1601
+ * description of what to install. Importing that as a legacy document would
1602
+ * read a `document.yjs` that is not there, create an empty document, and
1603
+ * report success: total data loss from the operator's point of view, since the
1604
+ * export is the only copy they were told they had. Refusing is the honest
1605
+ * answer, and it happens before anything is created.
1606
+ */
1607
+ function readChainArtifact(docDir, documentId) {
1608
+ const chainPath = path.join(docDir, "chain.json");
1609
+ if (!fs.existsSync(chainPath)) {
1610
+ throw new Error(`Document ${documentId} was exported as a large document (documentFormat 2), ` +
1611
+ `but ${chainPath} is missing, so this artifact is incomplete. A large document's ` +
1612
+ `data IS its chain — a base snapshot, the sealed overlays after it, and the open ` +
1613
+ `epoch — and importing this directory as a legacy document would create an EMPTY ` +
1614
+ `document. Nothing was imported.`);
1615
+ }
1616
+ let chain;
1617
+ try {
1618
+ chain = JSON.parse(fs.readFileSync(chainPath, "utf-8"));
1619
+ }
1620
+ catch (parseError) {
1621
+ throw new Error(`Document ${documentId}: ${chainPath} is not readable as a chain description ` +
1622
+ `(${parseError.message}), so nothing was imported.`);
1623
+ }
1624
+ if (!Number.isSafeInteger(Number(chain?.epoch))) {
1625
+ throw new Error(`Document ${documentId}: ${chainPath} names no open epoch, so nothing was imported.`);
1626
+ }
1627
+ const artifact = {
1628
+ epoch: Number(chain.epoch),
1629
+ base: chain.base
1630
+ ? {
1631
+ epoch: Number(chain.base.epoch),
1632
+ buildId: String(chain.base.buildId),
1633
+ rows: Number(chain.base.rows ?? 0),
1634
+ }
1635
+ : null,
1636
+ overlays: (Array.isArray(chain.overlays) ? chain.overlays : []).map((overlay) => ({ epoch: Number(overlay.epoch) })),
1637
+ };
1638
+ verifyChainArtifact(docDir, documentId, artifact);
1639
+ return artifact;
1640
+ }
1641
+ /**
1642
+ * Check that the directory holds every file the chain names, and that the
1643
+ * chain is one.
1644
+ *
1645
+ * `chain.json` being present says the export finished writing; it does not say
1646
+ * the files are there, and until this check the first missing chunk was found
1647
+ * AFTER the destination document had been created — leaving an empty document
1648
+ * behind, and in a multi-document import an app half-populated. The chain's
1649
+ * shape is checked here too, for the same reason the server checks it: a
1650
+ * chain with an epoch missing from the middle installs cleanly and is missing
1651
+ * everything that epoch held.
1652
+ */
1653
+ function verifyChainArtifact(docDir, documentId, chain) {
1654
+ const refuse = (reason) => {
1655
+ throw new Error(`Document ${documentId}: its large-document export ${reason}, so nothing was imported.`);
1656
+ };
1657
+ const from = chain.base ? chain.base.epoch : 1;
1658
+ const expected = [];
1659
+ for (let epoch = from; epoch < chain.epoch; epoch++)
1660
+ expected.push(epoch);
1661
+ const named = chain.overlays
1662
+ .map((overlay) => overlay.epoch)
1663
+ .sort((left, right) => left - right);
1664
+ if (named.length !== expected.length ||
1665
+ named.some((epoch, index) => epoch !== expected[index])) {
1666
+ refuse(`describes sealed overlays [${named.join(", ")}] where the chain from ` +
1667
+ (chain.base ? `its base at epoch ${chain.base.epoch}` : "epoch 1") +
1668
+ ` to its open epoch ${chain.epoch} is [${expected.join(", ")}]`);
1669
+ }
1670
+ const require = (file, what) => {
1671
+ if (!fs.existsSync(file))
1672
+ refuse(`is missing ${what} (${file})`);
1673
+ };
1674
+ if (chain.base) {
1675
+ const manifestPath = path.join(docDir, "snapshot", "manifest.json");
1676
+ require(manifestPath, "its base snapshot's manifest");
1677
+ let manifest;
1678
+ try {
1679
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
1680
+ }
1681
+ catch (parseError) {
1682
+ refuse(`has a base snapshot manifest that is not readable ` +
1683
+ `(${parseError.message})`);
1684
+ }
1685
+ for (const chunk of manifest.chunks ?? []) {
1686
+ const index = chunkIndexFromKey(String(chunk.key));
1687
+ require(path.join(docDir, "snapshot", String(chunk.model), `${index}.ndjson.gz`), `chunk ${index} of ${chunk.model}`);
1688
+ }
1689
+ }
1690
+ for (const overlay of chain.overlays) {
1691
+ require(path.join(docDir, "epochs", `${overlay.epoch}.yjs`), `the archived overlay of epoch ${overlay.epoch}`);
1692
+ }
1693
+ require(path.join(docDir, "current.yjs"), "its open epoch's overlay");
1694
+ }
1695
+ /** How long an install is waited on before the CLI gives up on it. */
1696
+ const CHAIN_INSTALL_TIMEOUT_MS = 60 * 60 * 1000;
1697
+ /** How often the install's progress is asked for. */
1698
+ const CHAIN_INSTALL_POLL_MS = 1000;
1699
+ /**
1700
+ * Install a large document's chain export into a freshly created document
1701
+ * (#2816, behavior 20).
1702
+ *
1703
+ * Every artifact is uploaded byte-for-byte into the new document's own prefix
1704
+ * — the manifest's digests are over the STORED bytes, so re-encoding a chunk
1705
+ * here would fail its own verification on install — and then the server
1706
+ * streams them into the document's `records` table a tick at a time. The full
1707
+ * document is never built as a Y.Doc on either side, which is what makes
1708
+ * importing a multi-hundred-MB artifact possible at all; it is also the
1709
+ * efficient way to bulk-seed a new large document.
1710
+ */
1711
+ async function importLargeDocumentChain(client, appId, docDir, documentId) {
1712
+ const chain = readChainArtifact(docDir, documentId);
1713
+ // The base's manifest and chunks. The manifest names the chunks, so nothing
1714
+ // here has to walk the directory and guess what belongs to the build.
1715
+ if (chain.base) {
1716
+ const manifestPath = path.join(docDir, "snapshot", "manifest.json");
1717
+ const manifestBytes = fs.readFileSync(manifestPath);
1718
+ await client.uploadDocumentChainArtifact(appId, documentId, {
1719
+ kind: "manifest",
1720
+ epoch: chain.base.epoch,
1721
+ buildId: chain.base.buildId,
1722
+ }, manifestBytes);
1723
+ const manifest = JSON.parse(manifestBytes.toString("utf-8"));
1724
+ for (const chunk of manifest.chunks ?? []) {
1725
+ const index = chunkIndexFromKey(chunk.key);
1726
+ await client.uploadDocumentChainArtifact(appId, documentId, {
1727
+ kind: "chunk",
1728
+ epoch: chain.base.epoch,
1729
+ buildId: chain.base.buildId,
1730
+ model: chunk.model,
1731
+ index,
1732
+ }, fs.readFileSync(path.join(docDir, "snapshot", chunk.model, `${index}.ndjson.gz`)));
1733
+ }
1734
+ }
1735
+ // The sealed overlays, oldest first, then the open epoch's — which travels
1736
+ // archived exactly like a sealed one, so the imported document's chain is
1737
+ // the chain that was exported.
1738
+ for (const overlay of chain.overlays) {
1739
+ await client.uploadDocumentChainArtifact(appId, documentId, { kind: "overlay", epoch: overlay.epoch }, fs.readFileSync(path.join(docDir, "epochs", `${overlay.epoch}.yjs`)));
1740
+ }
1741
+ await client.uploadDocumentChainArtifact(appId, documentId, { kind: "overlay", epoch: chain.epoch }, fs.readFileSync(path.join(docDir, "current.yjs")));
1742
+ await client.installDocumentChain(appId, documentId, {
1743
+ base: chain.base
1744
+ ? { epoch: chain.base.epoch, buildId: chain.base.buildId }
1745
+ : null,
1746
+ overlays: chain.overlays.map((overlay) => overlay.epoch),
1747
+ currentEpoch: chain.epoch,
1748
+ });
1749
+ // The install runs on the document's alarm, a bounded tick at a time, so it
1750
+ // is waited on rather than awaited: reporting "imported" while the records
1751
+ // are still arriving is the failure this whole path exists to avoid.
1752
+ const deadline = Date.now() + CHAIN_INSTALL_TIMEOUT_MS;
1753
+ for (;;) {
1754
+ const status = await client.getDocumentChainInstall(appId, documentId);
1755
+ const install = status?.install;
1756
+ if (install?.state === "complete")
1757
+ return;
1758
+ if (install?.state === "failed") {
1759
+ throw new Error(`Document ${documentId}: installing its chain failed — ` +
1760
+ `${install.error || "no reason given"}. The document is incomplete ` +
1761
+ `and should be deleted before the import is retried.`);
1762
+ }
1763
+ if (Date.now() >= deadline) {
1764
+ throw new Error(`Document ${documentId}: its chain install has not finished after ` +
1765
+ `${Math.round(CHAIN_INSTALL_TIMEOUT_MS / 60000)} minutes. It continues ` +
1766
+ `on the server; check with 'primitive documents get ${documentId}'.`);
1767
+ }
1768
+ await new Promise((resolve) => setTimeout(resolve, CHAIN_INSTALL_POLL_MS));
1769
+ }
1770
+ }
1771
+ /** Mirrors `ROOT_DOCUMENT_TAG` in `src/config/constants.ts`. */
1772
+ const ROOT_DOCUMENT_TAG = "__ROOT_TAG__";
1773
+ /** Does this `metadata.json` describe somebody's root document? */
1774
+ function isRootDocumentExport(tags) {
1775
+ return Array.isArray(tags) && tags.includes(ROOT_DOCUMENT_TAG);
1776
+ }
1777
+ /**
1778
+ * Why a large-document root export is refused (#3135, contract 7).
1779
+ *
1780
+ * A format-2 export is a chain installed wholesale into a freshly created
1781
+ * format-2 document — a replace, not a merge, and not something that can be
1782
+ * done to a root document, which the server only ever mints as a legacy
1783
+ * document. Refusing says so rather than installing a chain somewhere it does
1784
+ * not belong.
1785
+ */
1786
+ const ROOT_LARGE_DOCUMENT_REFUSAL = "it is a root document exported as a large document (documentFormat 2). A " +
1787
+ "root document is minted as a legacy document and a chain is installed " +
1788
+ "wholesale into a new format-2 document, so the export cannot be applied " +
1789
+ "to the target user's root. Nothing was imported for it.";
1790
+ /** Read an export directory's `metadata.json`, or null when it has none. */
1791
+ function readExportMetadata(docDir) {
1792
+ const metadataPath = path.join(docDir, "metadata.json");
1793
+ if (!fs.existsSync(metadataPath))
1794
+ return null;
1795
+ try {
1796
+ return JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
1797
+ }
1798
+ catch {
1799
+ return null;
1800
+ }
1801
+ }
1802
+ /**
1803
+ * Decide what each root-marked export in this run resolves to (#3135).
1804
+ *
1805
+ * A root document is a per-user singleton the server owns: the exported id is
1806
+ * the SOURCE user's root and means nothing here, so the export is mapped to
1807
+ * the TARGET user's root document instead. The target is `--owner` when given,
1808
+ * otherwise the owner `metadata.json` recorded — an email since #3135, which
1809
+ * is the only owner identity that survives a move between environments.
1810
+ *
1811
+ * Only a definitive answer reads as absence: `exists: false` from the email
1812
+ * lookup, or a 404 from the root-document read. Anything else (an expired
1813
+ * login, a lost permission, a server fault) fails the run, exactly as the
1814
+ * document-existence check does (#3096) — a failed read must never turn into a
1815
+ * confident create.
1816
+ */
1817
+ async function planRootImports(client, appId, docDirs, explicitOwner, explicitOwnerUserId, overwrite) {
1818
+ const plans = new Map();
1819
+ for (const docDir of docDirs) {
1820
+ const metadata = readExportMetadata(docDir);
1821
+ if (!metadata || !isRootDocumentExport(metadata.tags))
1822
+ continue;
1823
+ const exportedDocumentId = metadata.documentId || path.basename(docDir);
1824
+ const owner = String(explicitOwner || metadata.createdBy || "");
1825
+ const plan = {
1826
+ docDir,
1827
+ exportedDocumentId,
1828
+ owner,
1829
+ action: "refused",
1830
+ };
1831
+ const refuse = (reason) => {
1832
+ plan.action = "refused";
1833
+ plan.reason = reason;
1834
+ plans.set(docDir, plan);
1835
+ };
1836
+ if (Number(metadata.documentFormat) === 2) {
1837
+ refuse(ROOT_LARGE_DOCUMENT_REFUSAL);
1838
+ continue;
1839
+ }
1840
+ if (!owner) {
1841
+ refuse(`it is a root document export that records no owner, so there is no ` +
1842
+ `user in ${appId} to restore it into. Pass --owner <userId-or-email>.`);
1843
+ continue;
1844
+ }
1845
+ // Resolve the target user. An explicit `--owner` was already resolved,
1846
+ // command-level, before anything was read.
1847
+ let targetUserId = explicitOwnerUserId;
1848
+ if (!targetUserId) {
1849
+ if (owner.includes("@")) {
1850
+ // Absence is what the lookup ANSWERS with — `exists: false` on a 200.
1851
+ // A thrown lookup is a failed read (an expired login, a lost
1852
+ // permission, a proxy), and a failed read must never pass for "no such
1853
+ // user": it fails the run instead (#3096).
1854
+ let lookup;
1855
+ try {
1856
+ lookup = await client.lookupUserByEmail(appId, owner);
1857
+ }
1858
+ catch (error) {
1859
+ throw new Error(`Document ${exportedDocumentId}: looking up its recorded owner ` +
1860
+ `"${owner}" failed — ${error?.message || "no reason given"}. ` +
1861
+ `Nothing was imported.`);
1862
+ }
1863
+ if (!lookup?.exists || !lookup.user) {
1864
+ refuse(unresolvableRootOwner(appId, owner));
1865
+ continue;
1866
+ }
1867
+ targetUserId = lookup.user.userId;
1868
+ }
1869
+ else {
1870
+ targetUserId = owner;
1871
+ }
1872
+ }
1873
+ plan.targetUserId = targetUserId;
1874
+ let assignment;
1875
+ try {
1876
+ assignment = await client.getUserRootDocument(appId, targetUserId);
1877
+ }
1878
+ catch (error) {
1879
+ if (error?.statusCode !== 404) {
1880
+ throw new Error(`Document ${exportedDocumentId}: reading the root document of ` +
1881
+ `"${owner}" failed — ${error?.message || "no reason given"}. ` +
1882
+ `Nothing was imported.`);
1883
+ }
1884
+ refuse(unresolvableRootOwner(appId, owner));
1885
+ continue;
1886
+ }
1887
+ const rootDocId = assignment?.rootDocId || null;
1888
+ if (!rootDocId) {
1889
+ plan.action = "create";
1890
+ }
1891
+ else {
1892
+ plan.targetRootDocId = rootDocId;
1893
+ plan.action = overwrite ? "apply" : "skip";
1894
+ }
1895
+ plans.set(docDir, plan);
1896
+ }
1897
+ assertDistinctRootTargets(plans);
1898
+ return plans;
1899
+ }
1900
+ /** Why a recorded owner cannot be restored into, and what to do about it. */
1901
+ function unresolvableRootOwner(appId, owner) {
1902
+ return (`it is a root document export whose owner "${owner}" is not a user of ` +
1903
+ `app ${appId}. A root document is restored into one specific user's own ` +
1904
+ `root document, so name the target user with --owner <userId-or-email>, ` +
1905
+ `or re-export so the owner's email is recorded.`);
1906
+ }
1907
+ /**
1908
+ * Refuse a run in which two root exports would land in one user's root
1909
+ * document (#3135, contract 5).
1910
+ *
1911
+ * The supported migration is one `export-all --user-id` directory per user,
1912
+ * imported one directory per run. A hand-assembled directory holding two
1913
+ * users' roots — or `--owner` given for a run containing more than one root
1914
+ * export — would merge both sources into a single root and lose one of them,
1915
+ * so it fails before anything is created rather than half-way through.
1916
+ */
1917
+ function assertDistinctRootTargets(plans) {
1918
+ const byUser = new Map();
1919
+ for (const plan of plans.values()) {
1920
+ if (plan.action === "refused" || !plan.targetUserId)
1921
+ continue;
1922
+ const seen = byUser.get(plan.targetUserId) ?? [];
1923
+ seen.push(plan.exportedDocumentId);
1924
+ byUser.set(plan.targetUserId, seen);
1925
+ }
1926
+ for (const [userId, documents] of byUser) {
1927
+ if (documents.length > 1) {
1928
+ throw new Error(`Root document exports ${documents.join(", ")} all resolve to user ` +
1929
+ `${userId}, and a user has exactly one root document — importing ` +
1930
+ `them would merge them into each other. Export one user per ` +
1931
+ `directory and import one directory per run. Nothing was imported.`);
1932
+ }
1933
+ }
1934
+ }
1935
+ /**
1936
+ * Does the target app already hold this document?
1937
+ *
1938
+ * Only an explicit 404 answers "no" (#3096). An expired login (401), a lost
1939
+ * permission (403), a server fault or a transport failure says nothing about
1940
+ * the document, and reading those as absence turns a failed lookup into a
1941
+ * confident create — or, for a root-marked export, into a reported skip that
1942
+ * silently omits the overwrite the operator asked for. Those propagate, and
1943
+ * `documents import` fails the run.
1944
+ */
1945
+ async function documentExists(client, appId, documentId) {
1946
+ try {
1947
+ await client.getDocument(appId, documentId);
1948
+ return true;
1949
+ }
1950
+ catch (error) {
1951
+ if (error?.statusCode === 404)
1952
+ return false;
1953
+ throw new Error(`Document ${documentId}: checking whether it already exists failed — ` +
1954
+ `${error?.message || "no reason given"}. Nothing was imported for it.`);
1955
+ }
1956
+ }
1957
+ async function importSingleDocument(client, appId, docDir, overwrite, aliasMode, dryRun, summary, ownerUserId, rootPlan) {
1958
+ const metadataPath = path.join(docDir, "metadata.json");
1959
+ if (!fs.existsSync(metadataPath)) {
1960
+ warn(`Skipping ${docDir}: no metadata.json found`);
1961
+ summary.skipped++;
1962
+ return;
1963
+ }
1964
+ const metadata = JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
1965
+ const documentId = metadata.documentId;
1966
+ // A root-marked export is never restored under its exported id: that id is
1967
+ // the SOURCE user's root document. It goes to the target user's own root
1968
+ // instead, per the plan made before this run wrote anything (#3135).
1969
+ //
1970
+ // Decided BEFORE the chain artifact below is read, because a root export is
1971
+ // never installed as a chain: a large-document root is refused by the plan,
1972
+ // and reading its chain here would fail the whole run over an artifact this
1973
+ // run has already decided not to touch.
1974
+ if (isRootDocumentExport(metadata.tags)) {
1975
+ await importRootDocument(client, appId, docDir, metadata, rootPlan, overwrite, aliasMode, dryRun, summary);
1976
+ return;
1977
+ }
1978
+ // A large document's data is the chain, not `document.yjs` (#2816), and it
1979
+ // is installed rather than replayed. Vouched for before anything is created.
1980
+ const isLargeDocument = largeDocumentArtifactAt(docDir);
1981
+ if (isLargeDocument)
1982
+ readChainArtifact(docDir, documentId);
1983
+ // `--dry-run` decides from the same facts the real run does (#3096), so a
1984
+ // preview never promises a skip that the run turns into a merge: it looks
1985
+ // the document up as well, and only the writes below are withheld.
1986
+ const exists = await documentExists(client, appId, documentId);
1987
+ const wouldSkip = dryRun ? "[dry-run] Would skip" : "Skipping";
1988
+ if (exists && !overwrite) {
1989
+ // `--overwrite` merges a legacy document's state — but a large document is
1990
+ // INSTALLED, and the server refuses to install a chain into a document
1991
+ // that already holds records (`assertDocumentIsImportable`), so the remedy
1992
+ // is only honest for the format the state path handles.
1993
+ warn(isLargeDocument
1994
+ ? `${wouldSkip} ${documentId}: already exists, and ` +
1995
+ `a large-document export is installed rather than merged — ` +
1996
+ `--overwrite can only install it into a document that holds ` +
1997
+ `nothing yet`
1998
+ : `${wouldSkip} ${documentId}: already exists (use --overwrite to merge ` +
1999
+ `the exported state into it)`);
2000
+ summary.skipped++;
2001
+ return;
2002
+ }
2003
+ if (dryRun) {
2004
+ info(`[dry-run] Would ${exists ? "update" : "import"} document ${documentId} ` +
2005
+ `(${metadata.title || "untitled"})`);
2006
+ if (exists)
2007
+ summary.updated++;
2008
+ else
2009
+ summary.created++;
2010
+ return;
2011
+ }
2012
+ // Create document if it doesn't exist. The format is decided at creation and
2013
+ // never migrated, so a large document has to be created as one (#2816).
2014
+ //
2015
+ // Tags go back exactly as `metadata.json` recorded them (#3096): an export
2016
+ // is a faithful record of what the document is, and editing the list on the
2017
+ // way back in loses that.
2018
+ if (!exists) {
2019
+ await client.createDocument(appId, {
2020
+ title: metadata.title || "Imported Document",
2021
+ documentId,
2022
+ tags: metadata.tags,
2023
+ ...(isLargeDocument ? { documentFormat: 2 } : {}),
2024
+ ...(ownerUserId ? { createdBy: ownerUserId } : {}),
2025
+ });
2026
+ summary.created++;
2027
+ }
2028
+ else {
2029
+ summary.updated++;
2030
+ }
2031
+ if (isLargeDocument) {
2032
+ // The chain, installed: streamed into the document's records table on the
2033
+ // server, never replayed here as one Yjs update.
2034
+ await importLargeDocumentChain(client, appId, docDir, documentId);
2035
+ }
2036
+ else {
2037
+ // Import Yjs state
2038
+ const yjsPath = path.join(docDir, "document.yjs");
2039
+ if (fs.existsSync(yjsPath)) {
2040
+ const stateBuffer = fs.readFileSync(yjsPath);
2041
+ const stateBase64 = stateBuffer.toString("base64");
2042
+ await client.importDocumentState(appId, documentId, stateBase64);
2043
+ }
2044
+ }
2045
+ // Upload blobs
2046
+ const blobIndexPath = path.join(docDir, "blobs", "index.json");
2047
+ if (fs.existsSync(blobIndexPath)) {
2048
+ const blobIndex = JSON.parse(fs.readFileSync(blobIndexPath, "utf-8"));
2049
+ for (const blob of blobIndex) {
2050
+ const blobPath = path.join(docDir, "blobs", `${blob.blobId}.bin`);
2051
+ if (fs.existsSync(blobPath)) {
2052
+ const data = fs.readFileSync(blobPath);
2053
+ await client.uploadBlob(appId, documentId, blob.blobId, data, {
2054
+ filename: blob.filename,
2055
+ contentType: blob.contentType,
2056
+ sha256: blob.sha256,
2057
+ });
2058
+ summary.blobsUploaded++;
2059
+ }
2060
+ }
2061
+ }
2062
+ // Permissions are exported for reference but not restored during import.
2063
+ // The importing admin is the new owner; sharing is managed in the target app.
2064
+ // Restore aliases
2065
+ if (metadata.aliases && Array.isArray(metadata.aliases)) {
2066
+ for (const alias of metadata.aliases) {
2067
+ if (alias.aliasScope !== "user")
2068
+ continue;
2069
+ if (!ownerUserId) {
2070
+ summary.aliasesSkipped++;
2071
+ continue;
2072
+ }
2073
+ try {
2074
+ await client.setDocumentAlias(appId, alias.aliasScope, alias.aliasKey, documentId, ownerUserId, aliasMode === "skip" // mustNotExist: true for skip mode, false for overwrite
2075
+ );
2076
+ summary.aliasesSet++;
2077
+ }
2078
+ catch {
2079
+ summary.aliasesSkipped++;
2080
+ }
2081
+ }
2082
+ }
2083
+ info(`Imported document ${documentId} (${metadata.title || "untitled"})`);
2084
+ }
2085
+ /**
2086
+ * Restore a root-marked export into the target user's own root document
2087
+ * (#3135).
2088
+ *
2089
+ * The exported id is never created and never looked up: it is the source
2090
+ * user's root id, which means nothing in this app. Everything — the Yjs state,
2091
+ * the blobs, the user-scoped aliases — is written against the target user's
2092
+ * root document id instead, so blob references inside the document still
2093
+ * resolve and the app still holds exactly one root document per user.
2094
+ *
2095
+ * "Apply" is the merge `import/state` has always performed: keys only one side
2096
+ * holds survive, and a key both sides set resolves by Yjs's own conflict rule,
2097
+ * which guarantees neither source-wins nor target-wins. That is why merging
2098
+ * into an existing root needs `--overwrite` — the default must not quietly
2099
+ * rewrite a user's live preferences.
2100
+ */
2101
+ async function importRootDocument(client, appId, docDir, metadata, plan, overwrite, aliasMode, dryRun, summary) {
2102
+ const exportedDocumentId = metadata.documentId || path.basename(docDir);
2103
+ const wouldSkip = dryRun ? "[dry-run] Would skip" : "Skipping";
2104
+ const report = (action, targetRootDocId, reason) => {
2105
+ summary.rootDocuments.push({
2106
+ exportedDocumentId,
2107
+ owner: plan?.owner ?? "",
2108
+ ...(targetRootDocId ? { targetRootDocId } : {}),
2109
+ action,
2110
+ ...(reason ? { reason } : {}),
2111
+ });
2112
+ };
2113
+ if (!plan || plan.action === "refused") {
2114
+ const reason = plan?.reason ||
2115
+ `it is a root document export this run could not resolve to a user in ` +
2116
+ `app ${appId}. Pass --owner <userId-or-email>.`;
2117
+ warn(`${wouldSkip} ${exportedDocumentId}: ${reason}`);
2118
+ summary.skipped++;
2119
+ report("refused", undefined, reason);
2120
+ return;
2121
+ }
2122
+ if (plan.action === "skip") {
2123
+ const reason = `the root document of ${plan.owner} already exists ` +
2124
+ `(${plan.targetRootDocId}); use --overwrite to merge the exported ` +
2125
+ `content into it`;
2126
+ warn(`${wouldSkip} ${exportedDocumentId}: ${reason}`);
2127
+ summary.skipped++;
2128
+ report("skipped", plan.targetRootDocId, reason);
2129
+ return;
2130
+ }
2131
+ if (dryRun) {
2132
+ if (plan.action === "create") {
2133
+ info(`[dry-run] Would create the root document for ${plan.owner} and ` +
2134
+ `apply root document export ${exportedDocumentId} to it`);
2135
+ summary.created++;
2136
+ report("created");
2137
+ }
2138
+ else {
2139
+ info(`[dry-run] Would apply root document export ${exportedDocumentId} to ` +
2140
+ `${plan.owner}'s root document ${plan.targetRootDocId}`);
2141
+ summary.updated++;
2142
+ report("applied", plan.targetRootDocId);
2143
+ }
2144
+ return;
2145
+ }
2146
+ let targetRootDocId = plan.targetRootDocId;
2147
+ let created = false;
2148
+ if (plan.action === "create") {
2149
+ // The server's own get-or-create, and the only place a root document is
2150
+ // ever minted. Its answer — not the preflight read — decides both the id
2151
+ // the content lands in and whether this run created it: a first sign-in
2152
+ // may have minted the root between the read and this call.
2153
+ const ensured = await client.ensureUserRootDocument(appId, plan.targetUserId);
2154
+ targetRootDocId = ensured?.rootDocId;
2155
+ if (!targetRootDocId) {
2156
+ throw new Error(`Document ${exportedDocumentId}: the server returned no root document ` +
2157
+ `for ${plan.owner}, so nothing was imported for it.`);
2158
+ }
2159
+ created = ensured.created === true;
2160
+ if (!created && !overwrite) {
2161
+ const reason = `the root document of ${plan.owner} (${targetRootDocId}) was created ` +
2162
+ `by a concurrent sign-in while this import was running; use ` +
2163
+ `--overwrite to merge the exported content into it`;
2164
+ warn(`Skipping ${exportedDocumentId}: ${reason}`);
2165
+ summary.skipped++;
2166
+ report("skipped", targetRootDocId, reason);
2167
+ return;
2168
+ }
2169
+ }
2170
+ // Only content moves. The target root keeps its own id, title, tags and
2171
+ // permissions — the ensure path already granted the owner read-write.
2172
+ const yjsPath = path.join(docDir, "document.yjs");
2173
+ if (fs.existsSync(yjsPath)) {
2174
+ await client.importDocumentState(appId, targetRootDocId, fs.readFileSync(yjsPath).toString("base64"));
2175
+ }
2176
+ const blobIndexPath = path.join(docDir, "blobs", "index.json");
2177
+ if (fs.existsSync(blobIndexPath)) {
2178
+ const blobIndex = JSON.parse(fs.readFileSync(blobIndexPath, "utf-8"));
2179
+ for (const blob of blobIndex) {
2180
+ const blobPath = path.join(docDir, "blobs", `${blob.blobId}.bin`);
2181
+ if (!fs.existsSync(blobPath))
2182
+ continue;
2183
+ // The blobId is preserved: a document's own references travel by blobId,
2184
+ // so they resolve inside the target root as they did in the source.
2185
+ await client.uploadBlob(appId, targetRootDocId, blob.blobId, fs.readFileSync(blobPath), {
2186
+ filename: blob.filename,
2187
+ contentType: blob.contentType,
2188
+ sha256: blob.sha256,
2189
+ });
2190
+ summary.blobsUploaded++;
2191
+ }
2192
+ }
2193
+ // A root document's user-scoped aliases belong to its owner by definition,
2194
+ // so they are restored without `--owner` — the target user is already known.
2195
+ if (Array.isArray(metadata.aliases)) {
2196
+ for (const alias of metadata.aliases) {
2197
+ if (alias.aliasScope !== "user")
2198
+ continue;
2199
+ try {
2200
+ await client.setDocumentAlias(appId, alias.aliasScope, alias.aliasKey, targetRootDocId, plan.targetUserId, aliasMode === "skip");
2201
+ summary.aliasesSet++;
2202
+ }
2203
+ catch {
2204
+ summary.aliasesSkipped++;
2205
+ }
2206
+ }
2207
+ }
2208
+ if (created) {
2209
+ summary.created++;
2210
+ report("created", targetRootDocId);
2211
+ info(`Created root document ${targetRootDocId} for ${plan.owner} and applied ` +
2212
+ `root document export ${exportedDocumentId} to it`);
2213
+ }
2214
+ else {
2215
+ summary.updated++;
2216
+ report("applied", targetRootDocId);
2217
+ info(`Applied root document export ${exportedDocumentId} to ${plan.owner}'s ` +
2218
+ `root document ${targetRootDocId}`);
2219
+ }
2220
+ }
178
2221
  //# sourceMappingURL=documents.js.map