primitive-admin 1.2.0-alpha.9 → 1.3.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (546) hide show
  1. package/README.md +258 -186
  2. package/assets/skill/skills/primitive-platform/SKILL.md +93 -27
  3. package/dist/bin/primitive.js +15 -89
  4. package/dist/bin/primitive.js.map +1 -1
  5. package/dist/src/commands/admins.js +80 -17
  6. package/dist/src/commands/admins.js.map +1 -1
  7. package/dist/src/commands/agent-sessions.d.ts +129 -0
  8. package/dist/src/commands/agent-sessions.js +532 -20
  9. package/dist/src/commands/agent-sessions.js.map +1 -1
  10. package/dist/src/commands/analytics.js +207 -155
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps-children.js +3 -0
  13. package/dist/src/commands/apps-children.js.map +1 -1
  14. package/dist/src/commands/apps-transitions.d.ts +39 -0
  15. package/dist/src/commands/apps-transitions.js +198 -0
  16. package/dist/src/commands/apps-transitions.js.map +1 -0
  17. package/dist/src/commands/apps.d.ts +17 -0
  18. package/dist/src/commands/apps.js +108 -3
  19. package/dist/src/commands/apps.js.map +1 -1
  20. package/dist/src/commands/auth-sessions.js +2 -0
  21. package/dist/src/commands/auth-sessions.js.map +1 -1
  22. package/dist/src/commands/auth.js +138 -44
  23. package/dist/src/commands/auth.js.map +1 -1
  24. package/dist/src/commands/blob-buckets.js +2 -0
  25. package/dist/src/commands/blob-buckets.js.map +1 -1
  26. package/dist/src/commands/collections.js +318 -256
  27. package/dist/src/commands/collections.js.map +1 -1
  28. package/dist/src/commands/comparisons.js +2 -0
  29. package/dist/src/commands/comparisons.js.map +1 -1
  30. package/dist/src/commands/config.d.ts +2 -2
  31. package/dist/src/commands/config.js +59 -33
  32. package/dist/src/commands/config.js.map +1 -1
  33. package/dist/src/commands/connections.js +2 -0
  34. package/dist/src/commands/connections.js.map +1 -1
  35. package/dist/src/commands/database-type-configs.js +5 -3
  36. package/dist/src/commands/database-type-configs.js.map +1 -1
  37. package/dist/src/commands/databases.js +6 -4
  38. package/dist/src/commands/databases.js.map +1 -1
  39. package/dist/src/commands/db3-types.d.ts +15 -0
  40. package/dist/src/commands/db3-types.js +159 -0
  41. package/dist/src/commands/db3-types.js.map +1 -0
  42. package/dist/src/commands/db3.d.ts +24 -0
  43. package/dist/src/commands/db3.js +1444 -0
  44. package/dist/src/commands/db3.js.map +1 -0
  45. package/dist/src/commands/documents.d.ts +110 -10
  46. package/dist/src/commands/documents.js +1012 -748
  47. package/dist/src/commands/documents.js.map +1 -1
  48. package/dist/src/commands/email-templates.js +74 -0
  49. package/dist/src/commands/email-templates.js.map +1 -1
  50. package/dist/src/commands/env.js +8 -4
  51. package/dist/src/commands/env.js.map +1 -1
  52. package/dist/src/commands/function-trigger-commands.d.ts +28 -0
  53. package/dist/src/commands/function-trigger-commands.js +341 -0
  54. package/dist/src/commands/function-trigger-commands.js.map +1 -0
  55. package/dist/src/commands/functions.js +376 -30
  56. package/dist/src/commands/functions.js.map +1 -1
  57. package/dist/src/commands/groups.js +168 -50
  58. package/dist/src/commands/groups.js.map +1 -1
  59. package/dist/src/commands/guides.js +7 -5
  60. package/dist/src/commands/guides.js.map +1 -1
  61. package/dist/src/commands/hosting.d.ts +8 -0
  62. package/dist/src/commands/hosting.js +346 -0
  63. package/dist/src/commands/hosting.js.map +1 -0
  64. package/dist/src/commands/init.js +129 -38
  65. package/dist/src/commands/init.js.map +1 -1
  66. package/dist/src/commands/integrations.js +82 -53
  67. package/dist/src/commands/integrations.js.map +1 -1
  68. package/dist/src/commands/locks.d.ts +5 -3
  69. package/dist/src/commands/locks.js +19 -61
  70. package/dist/src/commands/locks.js.map +1 -1
  71. package/dist/src/commands/metadata-category-configs.d.ts +2 -2
  72. package/dist/src/commands/metadata-category-configs.js +4 -2
  73. package/dist/src/commands/metadata-category-configs.js.map +1 -1
  74. package/dist/src/commands/metadata.js +41 -0
  75. package/dist/src/commands/metadata.js.map +1 -1
  76. package/dist/src/commands/prompts.js +75 -52
  77. package/dist/src/commands/prompts.js.map +1 -1
  78. package/dist/src/commands/rate-counters.d.ts +19 -0
  79. package/dist/src/commands/rate-counters.js +104 -0
  80. package/dist/src/commands/rate-counters.js.map +1 -0
  81. package/dist/src/commands/rule-sets.d.ts +1 -1
  82. package/dist/src/commands/rule-sets.js +2 -1
  83. package/dist/src/commands/rule-sets.js.map +1 -1
  84. package/dist/src/commands/schemas.d.ts +15 -0
  85. package/dist/src/commands/schemas.js +122 -0
  86. package/dist/src/commands/schemas.js.map +1 -0
  87. package/dist/src/commands/scripts.d.ts +9 -17
  88. package/dist/src/commands/scripts.js +24 -479
  89. package/dist/src/commands/scripts.js.map +1 -1
  90. package/dist/src/commands/secrets.js +47 -3
  91. package/dist/src/commands/secrets.js.map +1 -1
  92. package/dist/src/commands/sessions.js +2 -0
  93. package/dist/src/commands/sessions.js.map +1 -1
  94. package/dist/src/commands/skill.js +2 -0
  95. package/dist/src/commands/skill.js.map +1 -1
  96. package/dist/src/commands/sync-schemas.d.ts +202 -0
  97. package/dist/src/commands/sync-schemas.js +629 -0
  98. package/dist/src/commands/sync-schemas.js.map +1 -0
  99. package/dist/src/commands/sync-user-properties.d.ts +118 -0
  100. package/dist/src/commands/sync-user-properties.js +276 -0
  101. package/dist/src/commands/sync-user-properties.js.map +1 -0
  102. package/dist/src/commands/sync.d.ts +518 -546
  103. package/dist/src/commands/sync.js +3010 -4877
  104. package/dist/src/commands/sync.js.map +1 -1
  105. package/dist/src/commands/tokens.js +5 -3
  106. package/dist/src/commands/tokens.js.map +1 -1
  107. package/dist/src/commands/transitions.d.ts +54 -0
  108. package/dist/src/commands/transitions.js +418 -0
  109. package/dist/src/commands/transitions.js.map +1 -0
  110. package/dist/src/commands/usage.d.ts +18 -0
  111. package/dist/src/commands/usage.js +343 -0
  112. package/dist/src/commands/usage.js.map +1 -0
  113. package/dist/src/commands/user-properties.d.ts +14 -0
  114. package/dist/src/commands/user-properties.js +79 -0
  115. package/dist/src/commands/user-properties.js.map +1 -0
  116. package/dist/src/commands/users.js +911 -18
  117. package/dist/src/commands/users.js.map +1 -1
  118. package/dist/src/commands/vars.js +2 -0
  119. package/dist/src/commands/vars.js.map +1 -1
  120. package/dist/src/commands/waitlist.js +39 -4
  121. package/dist/src/commands/waitlist.js.map +1 -1
  122. package/dist/src/commands/workflows.d.ts +5 -83
  123. package/dist/src/commands/workflows.js +57 -2282
  124. package/dist/src/commands/workflows.js.map +1 -1
  125. package/dist/src/lib/analytics-query.d.ts +58 -0
  126. package/dist/src/lib/analytics-query.js +134 -0
  127. package/dist/src/lib/analytics-query.js.map +1 -0
  128. package/dist/src/lib/api-client.d.ts +1818 -438
  129. package/dist/src/lib/api-client.js +965 -544
  130. package/dist/src/lib/api-client.js.map +1 -1
  131. package/dist/src/lib/app-settings-descriptor.d.ts +1 -1
  132. package/dist/src/lib/app-settings-descriptor.js +6 -0
  133. package/dist/src/lib/app-settings-descriptor.js.map +1 -1
  134. package/dist/src/lib/auth-fixtures.d.ts +44 -0
  135. package/dist/src/lib/auth-fixtures.js +61 -0
  136. package/dist/src/lib/auth-fixtures.js.map +1 -0
  137. package/dist/src/lib/auth-flow.d.ts +34 -1
  138. package/dist/src/lib/auth-flow.js +429 -13
  139. package/dist/src/lib/auth-flow.js.map +1 -1
  140. package/dist/src/lib/block-layout.d.ts +12 -23
  141. package/dist/src/lib/block-layout.js +26 -92
  142. package/dist/src/lib/block-layout.js.map +1 -1
  143. package/dist/src/lib/block-selector.d.ts +8 -14
  144. package/dist/src/lib/block-selector.js +8 -19
  145. package/dist/src/lib/block-selector.js.map +1 -1
  146. package/dist/src/lib/child-apps-local.d.ts +3 -1
  147. package/dist/src/lib/child-apps-local.js +9 -1
  148. package/dist/src/lib/child-apps-local.js.map +1 -1
  149. package/dist/src/lib/cli-manifest.d.ts +9 -0
  150. package/dist/src/lib/cli-manifest.js +10 -1
  151. package/dist/src/lib/cli-manifest.js.map +1 -1
  152. package/dist/src/lib/cli-version.d.ts +14 -0
  153. package/dist/src/lib/cli-version.js +38 -0
  154. package/dist/src/lib/cli-version.js.map +1 -0
  155. package/dist/src/lib/codegen-shared/prettierStable.d.ts +41 -0
  156. package/dist/src/lib/codegen-shared/prettierStable.js +146 -24
  157. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -1
  158. package/dist/src/lib/collection-export.d.ts +76 -15
  159. package/dist/src/lib/collection-export.js +116 -23
  160. package/dist/src/lib/collection-export.js.map +1 -1
  161. package/dist/src/lib/collection-principal.d.ts +22 -0
  162. package/dist/src/lib/collection-principal.js +35 -0
  163. package/dist/src/lib/collection-principal.js.map +1 -0
  164. package/dist/src/lib/command-groups.d.ts +30 -0
  165. package/dist/src/lib/command-groups.js +109 -0
  166. package/dist/src/lib/command-groups.js.map +1 -0
  167. package/dist/src/lib/command-status.d.ts +147 -0
  168. package/dist/src/lib/command-status.js +266 -0
  169. package/dist/src/lib/command-status.js.map +1 -0
  170. package/dist/src/lib/config-object-descriptor.d.ts +9 -22
  171. package/dist/src/lib/config-object-descriptor.js +107 -276
  172. package/dist/src/lib/config-object-descriptor.js.map +1 -1
  173. package/dist/src/lib/config-surface.d.ts +3 -7
  174. package/dist/src/lib/config-surface.js +9 -13
  175. package/dist/src/lib/config-surface.js.map +1 -1
  176. package/dist/src/lib/config-toml.d.ts +11 -2
  177. package/dist/src/lib/config-toml.js +25 -2
  178. package/dist/src/lib/config-toml.js.map +1 -1
  179. package/dist/src/lib/credentials-home.d.ts +7 -0
  180. package/dist/src/lib/credentials-home.js +45 -10
  181. package/dist/src/lib/credentials-home.js.map +1 -1
  182. package/dist/src/lib/credentials-lock.d.ts +14 -6
  183. package/dist/src/lib/credentials-lock.js +90 -10
  184. package/dist/src/lib/credentials-lock.js.map +1 -1
  185. package/dist/src/lib/credentials-store.d.ts +123 -70
  186. package/dist/src/lib/credentials-store.js +358 -113
  187. package/dist/src/lib/credentials-store.js.map +1 -1
  188. package/dist/src/lib/custodian.d.ts +8 -0
  189. package/dist/src/lib/custodian.js +18 -0
  190. package/dist/src/lib/custodian.js.map +1 -0
  191. package/dist/src/lib/data-input.d.ts +1 -1
  192. package/dist/src/lib/data-input.js +1 -1
  193. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +1 -1
  194. package/dist/src/lib/db-codegen/dbTsTypes.js +3 -0
  195. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -1
  196. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +38 -1
  197. package/dist/src/lib/db-codegen/dbTypeIR.js +29 -7
  198. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -1
  199. package/dist/src/lib/db-type-records.d.ts +106 -0
  200. package/dist/src/lib/db-type-records.js +224 -0
  201. package/dist/src/lib/db-type-records.js.map +1 -0
  202. package/dist/src/lib/db3-export.d.ts +287 -0
  203. package/dist/src/lib/db3-export.js +647 -0
  204. package/dist/src/lib/db3-export.js.map +1 -0
  205. package/dist/src/lib/db3-index-output.d.ts +116 -0
  206. package/dist/src/lib/db3-index-output.js +223 -0
  207. package/dist/src/lib/db3-index-output.js.map +1 -0
  208. package/dist/src/lib/db3-type-models.d.ts +134 -0
  209. package/dist/src/lib/db3-type-models.js +452 -0
  210. package/dist/src/lib/db3-type-models.js.map +1 -0
  211. package/dist/src/lib/deprecation.d.ts +2 -2
  212. package/dist/src/lib/deprecation.js +2 -2
  213. package/dist/src/lib/document-ingest-artifact.d.ts +13 -0
  214. package/dist/src/lib/document-ingest-artifact.js +36 -6
  215. package/dist/src/lib/document-ingest-artifact.js.map +1 -1
  216. package/dist/src/lib/document-ingest-format2.d.ts +36 -0
  217. package/dist/src/lib/document-ingest-format2.js +78 -0
  218. package/dist/src/lib/document-ingest-format2.js.map +1 -0
  219. package/dist/src/lib/document-ingest-input.d.ts +9 -0
  220. package/dist/src/lib/document-ingest-input.js +28 -1
  221. package/dist/src/lib/document-ingest-input.js.map +1 -1
  222. package/dist/src/lib/document-ingest.d.ts +11 -1
  223. package/dist/src/lib/document-ingest.js +16 -0
  224. package/dist/src/lib/document-ingest.js.map +1 -1
  225. package/dist/src/lib/document-schema-rows.d.ts +42 -0
  226. package/dist/src/lib/document-schema-rows.js +53 -0
  227. package/dist/src/lib/document-schema-rows.js.map +1 -0
  228. package/dist/src/lib/experimental-apis.d.ts +36 -0
  229. package/dist/src/lib/experimental-apis.js +46 -0
  230. package/dist/src/lib/experimental-apis.js.map +1 -0
  231. package/dist/src/lib/file-attachment.d.ts +24 -0
  232. package/dist/src/lib/file-attachment.js +31 -0
  233. package/dist/src/lib/file-attachment.js.map +1 -0
  234. package/dist/src/lib/function-authorize-check.d.ts +142 -0
  235. package/dist/src/lib/function-authorize-check.js +311 -0
  236. package/dist/src/lib/function-authorize-check.js.map +1 -0
  237. package/dist/src/lib/function-authorize-view.d.ts +27 -0
  238. package/dist/src/lib/function-authorize-view.js +88 -0
  239. package/dist/src/lib/function-authorize-view.js.map +1 -0
  240. package/dist/src/lib/function-bundle.d.ts +27 -5
  241. package/dist/src/lib/function-bundle.js +142 -7
  242. package/dist/src/lib/function-bundle.js.map +1 -1
  243. package/dist/src/lib/function-collect.d.ts +90 -12
  244. package/dist/src/lib/function-collect.js +482 -12
  245. package/dist/src/lib/function-collect.js.map +1 -1
  246. package/dist/src/lib/function-db-types.d.ts +65 -11
  247. package/dist/src/lib/function-db-types.js +297 -157
  248. package/dist/src/lib/function-db-types.js.map +1 -1
  249. package/dist/src/lib/function-document-types.d.ts +19 -7
  250. package/dist/src/lib/function-document-types.js +24 -12
  251. package/dist/src/lib/function-document-types.js.map +1 -1
  252. package/dist/src/lib/function-lint.d.ts +57 -0
  253. package/dist/src/lib/function-lint.js +234 -0
  254. package/dist/src/lib/function-lint.js.map +1 -0
  255. package/dist/src/lib/function-log-row.js +21 -2
  256. package/dist/src/lib/function-log-row.js.map +1 -1
  257. package/dist/src/lib/function-run.d.ts +13 -21
  258. package/dist/src/lib/function-run.js +14 -27
  259. package/dist/src/lib/function-run.js.map +1 -1
  260. package/dist/src/lib/function-schema-codegen.d.ts +86 -22
  261. package/dist/src/lib/function-schema-codegen.js +194 -88
  262. package/dist/src/lib/function-schema-codegen.js.map +1 -1
  263. package/dist/src/lib/function-schema-refs.d.ts +98 -0
  264. package/dist/src/lib/function-schema-refs.js +177 -0
  265. package/dist/src/lib/function-schema-refs.js.map +1 -0
  266. package/dist/src/lib/function-sync.d.ts +109 -6
  267. package/dist/src/lib/function-sync.js +179 -26
  268. package/dist/src/lib/function-sync.js.map +1 -1
  269. package/dist/src/lib/function-trigger-listing.d.ts +11 -6
  270. package/dist/src/lib/function-trigger-listing.js +32 -11
  271. package/dist/src/lib/function-trigger-listing.js.map +1 -1
  272. package/dist/src/lib/function-typecheck.d.ts +52 -0
  273. package/dist/src/lib/function-typecheck.js +174 -54
  274. package/dist/src/lib/function-typecheck.js.map +1 -1
  275. package/dist/src/lib/function-versions.d.ts +2 -0
  276. package/dist/src/lib/function-versions.js +1 -0
  277. package/dist/src/lib/function-versions.js.map +1 -1
  278. package/dist/src/lib/generated-build-flags.d.ts +13 -0
  279. package/dist/src/lib/generated-build-flags.js +14 -0
  280. package/dist/src/lib/generated-build-flags.js.map +1 -0
  281. package/dist/src/lib/generated-command-status.d.ts +6 -0
  282. package/dist/src/lib/generated-command-status.js +469 -0
  283. package/dist/src/lib/generated-command-status.js.map +1 -0
  284. package/dist/src/lib/generated-config-surfaces.d.ts +538 -141
  285. package/dist/src/lib/generated-config-surfaces.js +1772 -1854
  286. package/dist/src/lib/generated-config-surfaces.js.map +1 -1
  287. package/dist/src/lib/generated-sdk-types.d.ts +1 -1
  288. package/dist/src/lib/generated-sdk-types.js +1 -1
  289. package/dist/src/lib/generated-sdk-types.js.map +1 -1
  290. package/dist/src/lib/hosting-build.d.ts +97 -0
  291. package/dist/src/lib/hosting-build.js +204 -0
  292. package/dist/src/lib/hosting-build.js.map +1 -0
  293. package/dist/src/lib/hosting-client.d.ts +167 -0
  294. package/dist/src/lib/hosting-client.js +340 -0
  295. package/dist/src/lib/hosting-client.js.map +1 -0
  296. package/dist/src/lib/hosting-environments.d.ts +32 -0
  297. package/dist/src/lib/hosting-environments.js +74 -0
  298. package/dist/src/lib/hosting-environments.js.map +1 -0
  299. package/dist/src/lib/hosting-errors.d.ts +30 -0
  300. package/dist/src/lib/hosting-errors.js +43 -0
  301. package/dist/src/lib/hosting-errors.js.map +1 -0
  302. package/dist/src/lib/hosting-token.d.ts +46 -0
  303. package/dist/src/lib/hosting-token.js +60 -0
  304. package/dist/src/lib/hosting-token.js.map +1 -0
  305. package/dist/src/lib/hosting-wait.d.ts +42 -0
  306. package/dist/src/lib/hosting-wait.js +84 -0
  307. package/dist/src/lib/hosting-wait.js.map +1 -0
  308. package/dist/src/lib/hosting-wfp-upload.d.ts +86 -0
  309. package/dist/src/lib/hosting-wfp-upload.js +149 -0
  310. package/dist/src/lib/hosting-wfp-upload.js.map +1 -0
  311. package/dist/src/lib/init-assets.d.ts +2 -6
  312. package/dist/src/lib/init-assets.js +11 -27
  313. package/dist/src/lib/init-assets.js.map +1 -1
  314. package/dist/src/lib/init-ios-links.d.ts +11 -7
  315. package/dist/src/lib/init-ios-links.js +28 -22
  316. package/dist/src/lib/init-ios-links.js.map +1 -1
  317. package/dist/src/lib/init-login-note.d.ts +13 -0
  318. package/dist/src/lib/init-login-note.js +22 -0
  319. package/dist/src/lib/init-login-note.js.map +1 -0
  320. package/dist/src/lib/init-schema.d.ts +15 -0
  321. package/dist/src/lib/init-schema.js +54 -0
  322. package/dist/src/lib/init-schema.js.map +1 -1
  323. package/dist/src/lib/integration-test-request.d.ts +54 -0
  324. package/dist/src/lib/integration-test-request.js +207 -0
  325. package/dist/src/lib/integration-test-request.js.map +1 -0
  326. package/dist/src/lib/invoker-shared-enums.d.ts +35 -0
  327. package/dist/src/lib/invoker-shared-enums.js +98 -0
  328. package/dist/src/lib/invoker-shared-enums.js.map +1 -0
  329. package/dist/src/lib/json-value.d.ts +6 -0
  330. package/dist/src/lib/json-value.js +13 -0
  331. package/dist/src/lib/json-value.js.map +1 -0
  332. package/dist/src/lib/load-routes.d.ts +33 -0
  333. package/dist/src/lib/load-routes.js +35 -0
  334. package/dist/src/lib/load-routes.js.map +1 -0
  335. package/dist/src/lib/log-inspection.d.ts +23 -4
  336. package/dist/src/lib/log-inspection.js +14 -5
  337. package/dist/src/lib/log-inspection.js.map +1 -1
  338. package/dist/src/lib/login-exchange-check.d.ts +18 -0
  339. package/dist/src/lib/login-exchange-check.js +27 -0
  340. package/dist/src/lib/login-exchange-check.js.map +1 -0
  341. package/dist/src/lib/login-scope-lines.d.ts +17 -7
  342. package/dist/src/lib/login-scope-lines.js +33 -10
  343. package/dist/src/lib/login-scope-lines.js.map +1 -1
  344. package/dist/src/lib/metadata-report.d.ts +85 -0
  345. package/dist/src/lib/metadata-report.js +81 -0
  346. package/dist/src/lib/metadata-report.js.map +1 -0
  347. package/dist/src/lib/object-status-filter.d.ts +9 -1
  348. package/dist/src/lib/object-status-filter.js +9 -1
  349. package/dist/src/lib/object-status-filter.js.map +1 -1
  350. package/dist/src/lib/output.d.ts +1 -1
  351. package/dist/src/lib/output.js +3 -1
  352. package/dist/src/lib/output.js.map +1 -1
  353. package/dist/src/lib/pin-refusal-hint.d.ts +12 -0
  354. package/dist/src/lib/pin-refusal-hint.js +35 -0
  355. package/dist/src/lib/pin-refusal-hint.js.map +1 -0
  356. package/dist/src/lib/platform-owned.js +5 -0
  357. package/dist/src/lib/platform-owned.js.map +1 -1
  358. package/dist/src/lib/primitive-declaration-names.d.ts +21 -0
  359. package/dist/src/lib/primitive-declaration-names.js +22 -0
  360. package/dist/src/lib/primitive-declaration-names.js.map +1 -0
  361. package/dist/src/lib/primitive-declaration.d.ts +174 -0
  362. package/dist/src/lib/primitive-declaration.js +792 -0
  363. package/dist/src/lib/primitive-declaration.js.map +1 -0
  364. package/dist/src/lib/primitive-env-plugin.d.ts +99 -0
  365. package/dist/src/lib/primitive-env-plugin.js +408 -0
  366. package/dist/src/lib/primitive-env-plugin.js.map +1 -0
  367. package/dist/src/lib/project-login-apps.d.ts +8 -0
  368. package/dist/src/lib/project-login-apps.js +27 -0
  369. package/dist/src/lib/project-login-apps.js.map +1 -0
  370. package/dist/src/lib/prompt-schema-codegen.d.ts +36 -12
  371. package/dist/src/lib/prompt-schema-codegen.js +96 -100
  372. package/dist/src/lib/prompt-schema-codegen.js.map +1 -1
  373. package/dist/src/lib/prompt-schema-document.d.ts +35 -0
  374. package/dist/src/lib/prompt-schema-document.js +92 -0
  375. package/dist/src/lib/prompt-schema-document.js.map +1 -0
  376. package/dist/src/lib/prompt-schema-refs.d.ts +173 -0
  377. package/dist/src/lib/prompt-schema-refs.js +478 -0
  378. package/dist/src/lib/prompt-schema-refs.js.map +1 -0
  379. package/dist/src/lib/records-verbs.d.ts +79 -0
  380. package/dist/src/lib/records-verbs.js +45 -0
  381. package/dist/src/lib/records-verbs.js.map +1 -0
  382. package/dist/src/lib/register-commands.d.ts +36 -0
  383. package/dist/src/lib/register-commands.js +37 -0
  384. package/dist/src/lib/register-commands.js.map +1 -0
  385. package/dist/src/lib/retired-imports.d.ts +53 -0
  386. package/dist/src/lib/retired-imports.js +120 -0
  387. package/dist/src/lib/retired-imports.js.map +1 -0
  388. package/dist/src/lib/run-status.d.ts +1 -1
  389. package/dist/src/lib/run-status.generated.d.ts +2 -2
  390. package/dist/src/lib/run-status.generated.js +3 -1
  391. package/dist/src/lib/run-status.generated.js.map +1 -1
  392. package/dist/src/lib/run-status.js +1 -1
  393. package/dist/src/lib/schema-codegen/compiledSpace.d.ts +62 -0
  394. package/dist/src/lib/schema-codegen/compiledSpace.js +103 -0
  395. package/dist/src/lib/schema-codegen/compiledSpace.js.map +1 -0
  396. package/dist/src/lib/schema-codegen/generated-db3-bridge.d.ts +86 -0
  397. package/dist/src/lib/schema-codegen/generated-db3-bridge.js +227 -0
  398. package/dist/src/lib/schema-codegen/generated-db3-bridge.js.map +1 -0
  399. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.d.ts +85 -0
  400. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js +86 -0
  401. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js.map +1 -0
  402. package/dist/src/lib/schema-codegen/generated-field-grammar.d.ts +218 -0
  403. package/dist/src/lib/schema-codegen/generated-field-grammar.js +397 -0
  404. package/dist/src/lib/schema-codegen/generated-field-grammar.js.map +1 -0
  405. package/dist/src/lib/schema-codegen/generated-field-table.d.ts +80 -0
  406. package/dist/src/lib/schema-codegen/generated-field-table.js +542 -0
  407. package/dist/src/lib/schema-codegen/generated-field-table.js.map +1 -0
  408. package/dist/src/lib/schema-codegen/generated-prompt-schemas.d.ts +195 -0
  409. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js +503 -0
  410. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js.map +1 -0
  411. package/dist/src/lib/schema-codegen/generated-schema-descriptor.d.ts +258 -0
  412. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js +422 -0
  413. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js.map +1 -0
  414. package/dist/src/lib/schema-codegen/generated-schema-file.d.ts +129 -0
  415. package/dist/src/lib/schema-codegen/generated-schema-file.js +475 -0
  416. package/dist/src/lib/schema-codegen/generated-schema-file.js.map +1 -0
  417. package/dist/src/lib/schema-codegen/generated-schema-provenance.d.ts +115 -0
  418. package/dist/src/lib/schema-codegen/generated-schema-provenance.js +274 -0
  419. package/dist/src/lib/schema-codegen/generated-schema-provenance.js.map +1 -0
  420. package/dist/src/lib/schema-codegen/generated-schema-refs.d.ts +366 -0
  421. package/dist/src/lib/schema-codegen/generated-schema-refs.js +1789 -0
  422. package/dist/src/lib/schema-codegen/generated-schema-refs.js.map +1 -0
  423. package/dist/src/lib/schema-codegen/generated-schema-shape.d.ts +27 -0
  424. package/dist/src/lib/schema-codegen/generated-schema-shape.js +126 -0
  425. package/dist/src/lib/schema-codegen/generated-schema-shape.js.map +1 -0
  426. package/dist/src/lib/schema-codegen/namedRefs.d.ts +56 -0
  427. package/dist/src/lib/schema-codegen/namedRefs.js +143 -0
  428. package/dist/src/lib/schema-codegen/namedRefs.js.map +1 -0
  429. package/dist/src/lib/schema-codegen/naming.d.ts +35 -0
  430. package/dist/src/lib/schema-codegen/naming.js +83 -0
  431. package/dist/src/lib/schema-codegen/naming.js.map +1 -0
  432. package/dist/src/lib/schema-codegen/schemaChanges.d.ts +74 -0
  433. package/dist/src/lib/schema-codegen/schemaChanges.js +277 -0
  434. package/dist/src/lib/schema-codegen/schemaChanges.js.map +1 -0
  435. package/dist/src/lib/schema-codegen/schemaDocs.d.ts +69 -0
  436. package/dist/src/lib/schema-codegen/schemaDocs.js +219 -0
  437. package/dist/src/lib/schema-codegen/schemaDocs.js.map +1 -0
  438. package/dist/src/lib/schema-codegen/schemaIR.d.ts +158 -0
  439. package/dist/src/lib/schema-codegen/schemaIR.js +279 -0
  440. package/dist/src/lib/schema-codegen/schemaIR.js.map +1 -0
  441. package/dist/src/lib/schema-codegen/schemaToTs.d.ts +109 -0
  442. package/dist/src/lib/schema-codegen/schemaToTs.js +269 -0
  443. package/dist/src/lib/schema-codegen/schemaToTs.js.map +1 -0
  444. package/dist/src/lib/schema-codegen/valuesLists.d.ts +48 -0
  445. package/dist/src/lib/schema-codegen/valuesLists.js +144 -0
  446. package/dist/src/lib/schema-codegen/valuesLists.js.map +1 -0
  447. package/dist/src/lib/schema-family-index.d.ts +228 -0
  448. package/dist/src/lib/schema-family-index.js +813 -0
  449. package/dist/src/lib/schema-family-index.js.map +1 -0
  450. package/dist/src/lib/schema-pins.d.ts +82 -0
  451. package/dist/src/lib/schema-pins.js +198 -0
  452. package/dist/src/lib/schema-pins.js.map +1 -0
  453. package/dist/src/lib/schema-preview.d.ts +244 -0
  454. package/dist/src/lib/schema-preview.js +498 -0
  455. package/dist/src/lib/schema-preview.js.map +1 -0
  456. package/dist/src/lib/scope-request.d.ts +23 -11
  457. package/dist/src/lib/scope-request.js +69 -31
  458. package/dist/src/lib/scope-request.js.map +1 -1
  459. package/dist/src/lib/session-scope.d.ts +26 -0
  460. package/dist/src/lib/session-scope.js +58 -0
  461. package/dist/src/lib/session-scope.js.map +1 -0
  462. package/dist/src/lib/skill-installer.d.ts +2 -2
  463. package/dist/src/lib/skill-installer.js +2 -21
  464. package/dist/src/lib/skill-installer.js.map +1 -1
  465. package/dist/src/lib/step-run-table.d.ts +1 -2
  466. package/dist/src/lib/step-run-table.js +1 -2
  467. package/dist/src/lib/step-run-table.js.map +1 -1
  468. package/dist/src/lib/swift-codegen/agentGenerator.d.ts +2 -1
  469. package/dist/src/lib/swift-codegen/agentGenerator.js +25 -23
  470. package/dist/src/lib/swift-codegen/agentGenerator.js.map +1 -1
  471. package/dist/src/lib/swift-codegen/banners.d.ts +12 -0
  472. package/dist/src/lib/swift-codegen/banners.js +12 -0
  473. package/dist/src/lib/swift-codegen/banners.js.map +1 -1
  474. package/dist/src/lib/swift-codegen/functionGenerator.d.ts +36 -1
  475. package/dist/src/lib/swift-codegen/functionGenerator.js +169 -51
  476. package/dist/src/lib/swift-codegen/functionGenerator.js.map +1 -1
  477. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +33 -9
  478. package/dist/src/lib/swift-codegen/schemaToSwift.js +215 -179
  479. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -1
  480. package/dist/src/lib/swift-codegen/sharedGenerator.d.ts +45 -0
  481. package/dist/src/lib/swift-codegen/sharedGenerator.js +165 -0
  482. package/dist/src/lib/swift-codegen/sharedGenerator.js.map +1 -0
  483. package/dist/src/lib/swift-codegen/swiftKeys.d.ts +19 -0
  484. package/dist/src/lib/swift-codegen/swiftKeys.js +31 -0
  485. package/dist/src/lib/swift-codegen/swiftKeys.js.map +1 -0
  486. package/dist/src/lib/swift-codegen/userPropertiesGenerator.d.ts +30 -0
  487. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js +69 -0
  488. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js.map +1 -0
  489. package/dist/src/lib/sync-resource-types.d.ts +117 -31
  490. package/dist/src/lib/sync-resource-types.js +197 -189
  491. package/dist/src/lib/sync-resource-types.js.map +1 -1
  492. package/dist/src/lib/sync-selectors.d.ts +7 -0
  493. package/dist/src/lib/sync-selectors.js +22 -2
  494. package/dist/src/lib/sync-selectors.js.map +1 -1
  495. package/dist/src/lib/template.d.ts +39 -3
  496. package/dist/src/lib/template.js +103 -14
  497. package/dist/src/lib/template.js.map +1 -1
  498. package/dist/src/lib/test-case-file-names.d.ts +3 -5
  499. package/dist/src/lib/test-case-file-names.js +3 -5
  500. package/dist/src/lib/test-case-file-names.js.map +1 -1
  501. package/dist/src/lib/test-runs.d.ts +45 -0
  502. package/dist/src/lib/test-runs.js +150 -0
  503. package/dist/src/lib/test-runs.js.map +1 -0
  504. package/dist/src/lib/test-users.d.ts +25 -0
  505. package/dist/src/lib/test-users.js +36 -0
  506. package/dist/src/lib/test-users.js.map +1 -0
  507. package/dist/src/lib/toml-database-config.d.ts +4 -2
  508. package/dist/src/lib/toml-database-config.js +11 -6
  509. package/dist/src/lib/toml-database-config.js.map +1 -1
  510. package/dist/src/lib/toml-scalar-edit.js +6 -4
  511. package/dist/src/lib/toml-scalar-edit.js.map +1 -1
  512. package/dist/src/lib/transition-warnings.d.ts +21 -0
  513. package/dist/src/lib/transition-warnings.js +49 -0
  514. package/dist/src/lib/transition-warnings.js.map +1 -0
  515. package/dist/src/lib/user-index.d.ts +80 -0
  516. package/dist/src/lib/user-index.js +166 -0
  517. package/dist/src/lib/user-index.js.map +1 -0
  518. package/dist/src/lib/user-properties/generated-properties-schema.d.ts +159 -0
  519. package/dist/src/lib/user-properties/generated-properties-schema.js +471 -0
  520. package/dist/src/lib/user-properties/generated-properties-schema.js.map +1 -0
  521. package/dist/src/lib/user-properties/user-properties-codegen.d.ts +55 -0
  522. package/dist/src/lib/user-properties/user-properties-codegen.js +129 -0
  523. package/dist/src/lib/user-properties/user-properties-codegen.js.map +1 -0
  524. package/dist/src/lib/user-walk.d.ts +31 -0
  525. package/dist/src/lib/user-walk.js +102 -0
  526. package/dist/src/lib/user-walk.js.map +1 -0
  527. package/dist/src/lib/webhook-capture.d.ts +43 -0
  528. package/dist/src/lib/webhook-capture.js +91 -0
  529. package/dist/src/lib/webhook-capture.js.map +1 -0
  530. package/dist/src/lib/webhook-deliver.d.ts +18 -20
  531. package/dist/src/lib/webhook-deliver.js +34 -89
  532. package/dist/src/lib/webhook-deliver.js.map +1 -1
  533. package/dist/src/lib/webhook-test-run.d.ts +32 -0
  534. package/dist/src/lib/webhook-test-run.js +108 -0
  535. package/dist/src/lib/webhook-test-run.js.map +1 -0
  536. package/dist/src/lib/worker-perf-format.d.ts +22 -0
  537. package/dist/src/lib/worker-perf-format.js +27 -0
  538. package/dist/src/lib/worker-perf-format.js.map +1 -0
  539. package/dist/src/types/index.d.ts +20 -65
  540. package/dist/src/validators.d.ts +7 -55
  541. package/dist/src/validators.js +7 -53
  542. package/dist/src/validators.js.map +1 -1
  543. package/dist/src/vite.d.ts +17 -0
  544. package/dist/src/vite.js +18 -0
  545. package/dist/src/vite.js.map +1 -0
  546. package/package.json +20 -9
@@ -1,8 +1,11 @@
1
+ import { commandStatus } from "../lib/command-status.js";
2
+ import { deprecateCommandGroup } from "../lib/deprecation.js";
1
3
  import { segmentRows, snapshotBuildRows } from "../lib/snapshot-build-rows.js";
2
4
  import { exportRecordLogDocument } from "../lib/document-export-record-log.js";
3
5
  import { driveSnapshotBuild } from "../lib/snapshot-build.js";
4
6
  import { ingestClientRows, ingestSessionRows, } from "../lib/document-ingest-rows.js";
5
7
  import { ApiClient } from "../lib/api-client.js";
8
+ import { documentSchemaRows } from "../lib/document-schema-rows.js";
6
9
  import { resolveAppId } from "../lib/config.js";
7
10
  import { success, error, info, formatTable, formatId, formatDate, json, keyValue, result as printResult, warn, flushOutput, } from "../lib/output.js";
8
11
  import { renderAggregateResult } from "../lib/aggregate-output.js";
@@ -16,8 +19,11 @@ import { buildPermissionsExport, PENDING_INVITATIONS_ABSENT_STATUSES, } from "..
16
19
  import { readExportLookup } from "../lib/document-export-lookups.js";
17
20
  import { discoverIngestInput, } from "../lib/document-ingest-input.js";
18
21
  import { buildIngestArtifact, ingestSchemaFromIntrospection, } from "../lib/document-ingest-artifact.js";
19
- import { driveDocumentIngest, summariseIngestPlan, assertIngestConfirmable, ingestCreateBody, parseIngestFlags, } from "../lib/document-ingest.js";
22
+ import { driveDocumentIngest, summariseIngestPlan, assertIngestConfirmable, assertIngestRefreshKeepsRefused, ingestCreateBody, parseIngestFlags, } from "../lib/document-ingest.js";
20
23
  import { withTransientRetry } from "../lib/transient-retry.js";
24
+ import { recordLogSchemaToToml } from "js-bao";
25
+ import { DB3_BATCH_OPERATION_CAP, DOCUMENT_ROUTES } from "../lib/records-verbs.js";
26
+ import { DOCUMENT_LOAD_ROUTES } from "../lib/load-routes.js";
21
27
  import { ulid } from "ulid";
22
28
  import * as Y from "yjs";
23
29
  import * as fs from "fs";
@@ -50,7 +56,7 @@ export function describeDocumentFailure(err) {
50
56
  /**
51
57
  * One refused records call, as one line for an operator (#3764).
52
58
  *
53
- * The same composition `describeBulkFailure` makes for the atomic blob, on the
59
+ * The same composition `describeBatchFailure` makes for the atomic blob, on the
54
60
  * verbs that have no `--json` envelope to fill: the server's sentence, the
55
61
  * stable code a script branches on, and the status. `statusCode` FIRST —
56
62
  * `cli/src/lib/api-client.ts`'s `ApiError` is where the status lives, and a
@@ -139,7 +145,17 @@ const DOCUMENT_FORMAT_HELP = "The document format you expect: 1 (ordinary) or 3
139
145
  "with the platform's own answer is refused with DOCUMENT_FORMAT_MISMATCH " +
140
146
  "rather than answered out of the wrong tables";
141
147
  /**
142
- * What `documents records bulk` reports when the write is refused (#3619).
148
+ * One row of `documents inspect --refused`, as the label and value it prints:
149
+ * the code, a constraint refusal's constraint and holder, and the reason a
150
+ * record-log rule refusal carries (#4621).
151
+ */
152
+ export function refusedRowLine(row) {
153
+ const conflicting = row.conflicting ? ` (held by ${row.conflicting.model} ${row.conflicting.id})` : "";
154
+ const reason = row.reason ? `: ${row.reason}` : "";
155
+ return [` ${row.model} ${row.id}`, `${row.code}${row.constraint ? ` ${row.constraint}` : ""}${conflicting}${reason}`];
156
+ }
157
+ /**
158
+ * What `documents records batch` reports when the write is refused (#3619).
143
159
  *
144
160
  * The command used to catch every failure with `error(err.message)` while
145
161
  * `ApiError` carried the code and the status on separate fields, so the stable
@@ -157,7 +173,7 @@ const DOCUMENT_FORMAT_HELP = "The document format you expect: 1 (ordinary) or 3
157
173
  * without spawning a process: the human line and the `--json` envelope must
158
174
  * agree about which failure happened.
159
175
  */
160
- export function describeBulkFailure(err) {
176
+ export function describeBatchFailure(err) {
161
177
  const message = (typeof err?.message === "string" && err.message) || String(err);
162
178
  const code = typeof err?.code === "string" && err.code ? err.code : undefined;
163
179
  const raw = err?.statusCode ?? err?.status;
@@ -173,11 +189,11 @@ export function describeBulkFailure(err) {
173
189
  };
174
190
  }
175
191
  /**
176
- * The `--data-file` help of `documents records bulk`: the op shapes the route
192
+ * The `--data-file` help of `documents records batch`: the op shapes the route
177
193
  * accepts, including the `upsert` action addressed by a declared unique
178
- * constraint (#3750).
194
+ * constraint (#3750), and the cap (#5243).
179
195
  */
180
- export const BULK_DATA_FILE_HELP = "JSON file with { operations: [...] } or a bare operations array. " +
196
+ export const BATCH_DATA_FILE_HELP = `JSON file with { operations: [...] } or a bare operations array, at most ${DB3_BATCH_OPERATION_CAP} operations per call. ` +
181
197
  "Each op is { model, action: create|patch|delete, id, data, precondition? } " +
182
198
  "— `data` holds the record fields and is required (non-empty) on " +
183
199
  "create/patch, not allowed on delete; a create `id` must be a 26-char " +
@@ -186,17 +202,40 @@ export const BULK_DATA_FILE_HELP = "JSON file with { operations: [...] } or a ba
186
202
  "constraint the model declares and `data` carries its fields; the record " +
187
203
  "holding that key is merged into, or created (at `id` when given)";
188
204
  /**
189
- * The success line of `documents records bulk` (#3750): the blob's counts,
190
- * with the upsert ops and how many of them created their record. An answer
191
- * without `upserted` (an older server) reads as no upserts.
205
+ * The success line of `records batch` (#3750): the blob's counts, with the
206
+ * upsert ops and how many of them created their record, then the reads a
207
+ * db3 batch answered and how many were refused (#5243). An answer without
208
+ * `upserted` (an older server) reads as no upserts.
192
209
  */
193
- export function describeBulkResult(result) {
210
+ export function describeBatchResult(result) {
194
211
  const upserted = Array.isArray(result.upserted) ? result.upserted : [];
195
212
  const created = upserted.filter((entry) => entry.created).length;
213
+ const reads = Array.isArray(result.reads) ? result.reads : [];
214
+ const refused = reads.filter((read) => read?.ok === false).length;
196
215
  return (`Applied ${result.applied} operation(s): ` +
197
216
  `${result.added.length} added, ${result.updated.length} updated, ` +
198
217
  `${result.deleted} deleted, ${upserted.length} upserted` +
199
- `${upserted.length > 0 ? ` (${created} created)` : ""}.`);
218
+ `${upserted.length > 0 ? ` (${created} created)` : ""}` +
219
+ `${reads.length > 0 ? `; answered ${reads.length} read(s)${refused > 0 ? `, ${refused} refused` : ""}` : ""}.`);
220
+ }
221
+ /**
222
+ * One line per result of a db3 batch's reads (#5243): its index, model and
223
+ * action, then the answer (a page's record count and whether more follow, a
224
+ * count, an aggregate's group count) or the refusal's code and message.
225
+ */
226
+ export function describeBatchReadResults(results) {
227
+ return results.map((read) => {
228
+ const head = `[${read.index}] ${read.model} ${read.action}`;
229
+ if (read.ok === false)
230
+ return `${head}: refused ${read.code ?? ""} (${read.status ?? ""}): ${read.error ?? ""}`;
231
+ if (read.action === "query") {
232
+ const items = Array.isArray(read.items) ? read.items.length : 0;
233
+ return `${head}: ${items} record(s)${read.hasMore ? `, more after cursor ${read.nextCursor ?? ""}` : ""}`;
234
+ }
235
+ if (read.action === "count")
236
+ return `${head}: ${read.count}`;
237
+ return `${head}: ${Array.isArray(read.result) ? read.result.length : 0} row(s) ${JSON.stringify(read.result ?? [])}`;
238
+ });
200
239
  }
201
240
  /**
202
241
  * A document's tags as a list, from whatever the wire handed back (#3644).
@@ -248,7 +287,7 @@ export function formatTags(tags) {
248
287
  export function registerDocumentsCommands(program) {
249
288
  const documents = program
250
289
  .command("documents")
251
- .description("Manage documents within an app")
290
+ .description("(deprecated: use db3) Manage documents within an app")
252
291
  .addHelpText("after", `
253
292
  Examples:
254
293
  $ primitive documents list --user-id <user-id>
@@ -275,6 +314,8 @@ Examples:
275
314
  $ primitive documents transfer-owner <document-id> <new-owner-id>
276
315
  $ primitive documents group-permissions list <document-id>
277
316
  `);
317
+ commandStatus(documents, { stability: "production", deprecated: true });
318
+ deprecateCommandGroup(documents, "`primitive db3`");
278
319
  // ---- List a user's documents ----
279
320
  // No app-wide enumeration: `--user-id` is required (the admin token has no
280
321
  // "self"). Reads the per-user permission partition via the admin endpoint.
@@ -387,8 +428,9 @@ Ownership:
387
428
  An app-user token — member, admin, or owner — always creates the document
388
429
  owned by the caller: the server ignores --owner for those tokens.
389
430
  A super-admin token, or a console-admin token assigned to this app, acts
390
- through an admin shadow app user — without --owner that shadow user owns the
391
- document, with --owner the named user does.
431
+ through an admin shadow app user — without --owner that shadow user owns an
432
+ ordinary document and the app holds a record-log document (--format 3),
433
+ which no member owns; with --owner the named user does.
392
434
  A console admin not assigned to this app has no access to the app at all.
393
435
 
394
436
  An email given to --owner is resolved to a user id before anything is
@@ -640,29 +682,7 @@ Permissions (enforced by the server, not the CLI):
640
682
  .option("--app <app-id>", "App ID")
641
683
  .option("--json", "Output as JSON")
642
684
  .action(async (documentId, options) => {
643
- const resolvedAppId = resolveAppId(undefined, options);
644
- const client = new ApiClient();
645
- try {
646
- const result = await client.getDocumentSchema(resolvedAppId, documentId);
647
- const models = result?.modelNames ?? Object.keys(result?.schema?.models ?? {});
648
- if (options.json) {
649
- json(models);
650
- return;
651
- }
652
- if (models.length === 0) {
653
- info("No models found.");
654
- return;
655
- }
656
- for (const m of models) {
657
- console.log(` ${m}`);
658
- }
659
- }
660
- catch (err) {
661
- // #3764 — the server's sentence, the stable code and the status, so a
662
- // refused records call is scriptable rather than only readable.
663
- error(describeRecordsFailure(err));
664
- process.exit(1);
665
- }
685
+ await modelsAction(DOCUMENT_ROUTES, documentId, options);
666
686
  });
667
687
  // Describe a model's fields and indexes
668
688
  records
@@ -673,49 +693,7 @@ Permissions (enforced by the server, not the CLI):
673
693
  .option("--app <app-id>", "App ID")
674
694
  .option("--json", "Output as JSON")
675
695
  .action(async (documentId, modelName, options) => {
676
- const resolvedAppId = resolveAppId(undefined, options);
677
- const client = new ApiClient();
678
- try {
679
- const result = await client.getDocumentSchema(resolvedAppId, documentId);
680
- const model = result?.schema?.models?.[modelName];
681
- if (!model) {
682
- if (options.json) {
683
- json(null);
684
- return;
685
- }
686
- info(`Model '${modelName}' not found in this document.`);
687
- return;
688
- }
689
- const fieldsObj = model.fields ?? {};
690
- const rows = Object.entries(fieldsObj).map(([name, meta]) => ({
691
- field: name,
692
- type: meta?.type ?? "unknown",
693
- indexed: meta?.indexed ? "yes" : "",
694
- unique: meta?.unique ? "yes" : "",
695
- required: meta?.required ? "yes" : "",
696
- }));
697
- if (options.json) {
698
- json({ fields: fieldsObj, constraints: model.constraints ?? {} });
699
- return;
700
- }
701
- if (rows.length === 0) {
702
- info("No fields detected for this model.");
703
- return;
704
- }
705
- console.log(formatTable(rows, [
706
- { header: "FIELD", key: "field", flex: true },
707
- { header: "TYPE", key: "type" },
708
- { header: "INDEXED", key: "indexed" },
709
- { header: "UNIQUE", key: "unique" },
710
- { header: "REQUIRED", key: "required" },
711
- ]));
712
- }
713
- catch (err) {
714
- // #3764 — the server's sentence, the stable code and the status, so a
715
- // refused records call is scriptable rather than only readable.
716
- error(describeRecordsFailure(err));
717
- process.exit(1);
718
- }
696
+ await describeAction(DOCUMENT_ROUTES, documentId, modelName, options);
719
697
  });
720
698
  // Query records in a document model
721
699
  records
@@ -731,6 +709,7 @@ Permissions (enforced by the server, not the CLI):
731
709
  // sentence naming the maximum, which a CLI-side parse would hide.
732
710
  .option("--limit <n>", "Records per page (default 100, max 10000)")
733
711
  .option("--cursor <cursor>", "Pagination cursor from a previous query (valid only with the same --sort)")
712
+ .option("--include <json>", "Related records as a JSON array of include specs, e.g. '[{\"model\":\"customer\",\"type\":\"refersTo\",\"sourceField\":\"customerId\"}]'; answered on a db3 as _related")
734
713
  .option(DOCUMENT_FORMAT_FLAG, DOCUMENT_FORMAT_HELP)
735
714
  .option("--json", "Output as JSON")
736
715
  .action(async (documentId, modelName, options) => {
@@ -745,66 +724,7 @@ Permissions (enforced by the server, not the CLI):
745
724
  error(describeRecordsFailure(err));
746
725
  process.exit(1);
747
726
  }
748
- const filter = parseFilterOptions(options);
749
- // The JSON is checked here; its shape (`{ field: 1 | -1 }`) is the
750
- // route's to refuse, with its own `Invalid sort` message.
751
- let sort;
752
- if (options.sort !== undefined) {
753
- try {
754
- sort = JSON.parse(options.sort);
755
- }
756
- catch {
757
- error("Invalid --sort JSON.");
758
- process.exit(1);
759
- }
760
- }
761
- const client = new ApiClient();
762
- try {
763
- const result = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { filter, sort, limit: options.limit, cursor: options.cursor, documentFormat });
764
- if (options.json) {
765
- json(result);
766
- return;
767
- }
768
- const items = result.items;
769
- if (items.length === 0) {
770
- info("No records found.");
771
- return;
772
- }
773
- const allKeys = new Set();
774
- for (const rec of items) {
775
- for (const key of Object.keys(rec))
776
- allKeys.add(key);
777
- }
778
- const orderedKeys = [];
779
- if (allKeys.has("id")) {
780
- orderedKeys.push("id");
781
- allKeys.delete("id");
782
- }
783
- orderedKeys.push(...[...allKeys].sort());
784
- const columns = orderedKeys.map((key) => ({
785
- header: key.toUpperCase(),
786
- key,
787
- format: (v) => {
788
- if (v === null || v === undefined)
789
- return "—";
790
- if (typeof v === "object")
791
- return JSON.stringify(v);
792
- return String(v);
793
- },
794
- }));
795
- console.log(formatTable(items, columns));
796
- if (result.nextCursor) {
797
- // A cursor continues only the sort that minted it.
798
- const sortArg = sort !== undefined ? ` --sort ${quoteCursorArg(JSON.stringify(sort))}` : "";
799
- info(`More results available. Use --cursor ${result.nextCursor}${sortArg}`);
800
- }
801
- }
802
- catch (err) {
803
- // #3764 — the server's sentence, the stable code and the status, so a
804
- // refused records call is scriptable rather than only readable.
805
- error(describeRecordsFailure(err));
806
- process.exit(1);
807
- }
727
+ await queryRecordsAction(DOCUMENT_ROUTES, resolvedAppId, documentId, modelName, options, documentFormat);
808
728
  });
809
729
  // Get a single record by id (mirrors `databases records get`, issue #2357).
810
730
  records
@@ -886,28 +806,12 @@ Permissions (enforced by the server, not the CLI):
886
806
  error(describeRecordsFailure(err));
887
807
  process.exit(1);
888
808
  }
889
- const filter = parseFilterOptions(options);
890
- const client = new ApiClient();
891
- try {
892
- const result = await client.countDocumentRecords(resolvedAppId, documentId, modelName, { filter, documentFormat });
893
- if (options.json) {
894
- json(result);
895
- return;
896
- }
897
- console.log(` ${result.count}`);
898
- }
899
- catch (err) {
900
- // #3764 — the server's sentence, the stable code and the status, so a
901
- // refused records call is scriptable rather than only readable.
902
- error(describeRecordsFailure(err));
903
- process.exit(1);
904
- }
809
+ await countRecordsAction(DOCUMENT_ROUTES, resolvedAppId, documentId, modelName, options, documentFormat);
905
810
  });
906
811
  // Aggregate records in a document model (issue #2437). Mirrors
907
812
  // `databases records aggregate` flag for flag and rendering for rendering —
908
813
  // including the deliberate `keyValue()` for the ungrouped scalar, so the two
909
814
  // twins keep printing the same thing.
910
- const AGGREGATE_OPS = ["count", "sum", "avg", "min", "max"];
911
815
  records
912
816
  .command("aggregate")
913
817
  .description("Aggregate records in a document model (count/sum/avg/min/max, optional group-by)")
@@ -933,53 +837,7 @@ Permissions (enforced by the server, not the CLI):
933
837
  error(describeRecordsFailure(err));
934
838
  process.exit(1);
935
839
  }
936
- if (!AGGREGATE_OPS.includes(options.op)) {
937
- error(`Invalid --op "${options.op}". Expected one of: ${AGGREGATE_OPS.join(", ")}.`);
938
- process.exit(1);
939
- }
940
- const operation = { type: options.op };
941
- if (options.op === "count") {
942
- if (options.field) {
943
- error("--field is not valid for --op count.");
944
- process.exit(1);
945
- }
946
- }
947
- else {
948
- if (!options.field) {
949
- error(`--op ${options.op} requires --field.`);
950
- process.exit(1);
951
- }
952
- operation.field = options.field;
953
- }
954
- const filter = parseFilterOptions(options);
955
- const groupBy = options.groupBy || [];
956
- const client = new ApiClient();
957
- try {
958
- const response = await client.aggregateDocumentRecords(resolvedAppId, documentId, modelName, { operations: [operation], groupBy, filter }, { documentFormat });
959
- if (options.json) {
960
- json(response);
961
- return;
962
- }
963
- // The route answers rows (#4265): one key/value line when
964
- // ungrouped, a table with one column per group key when grouped.
965
- const rendered = renderAggregateResult(response?.result, {
966
- groupBy,
967
- op: options.op,
968
- field: options.field,
969
- });
970
- if (rendered.kind === "scalar") {
971
- keyValue(rendered.label, rendered.value);
972
- }
973
- else {
974
- console.log(rendered.text);
975
- }
976
- }
977
- catch (err) {
978
- // #3764 — the server's sentence, the stable code and the status, so a
979
- // refused records call is scriptable rather than only readable.
980
- error(describeRecordsFailure(err));
981
- process.exit(1);
982
- }
840
+ await aggregateRecordsAction(DOCUMENT_ROUTES, resolvedAppId, documentId, modelName, options, documentFormat);
983
841
  });
984
842
  // ---- Record writes (#1964 Phase 4) ----
985
843
  // Server-side writes through the document facade: Yjs-first, CRDT-safe,
@@ -1015,23 +873,7 @@ Permissions (enforced by the server, not the CLI):
1015
873
  error(describeRecordsFailure(err));
1016
874
  process.exit(1);
1017
875
  }
1018
- const recordId = options.id || ulid();
1019
- const writeOptions = options.upsertOn ? { upsertOn: options.upsertOn } : undefined;
1020
- const client = new ApiClient();
1021
- try {
1022
- const result = await client.saveDocumentRecord(resolvedAppId, documentId, modelName, { id: recordId, data, ...(writeOptions ? { options: writeOptions } : {}) }, { documentFormat });
1023
- if (options.json) {
1024
- json(result);
1025
- return;
1026
- }
1027
- success(`Record saved: ${result.record?.id ?? recordId}`);
1028
- }
1029
- catch (err) {
1030
- // #3764 — the server's sentence, the stable code and the status, so a
1031
- // refused records call is scriptable rather than only readable.
1032
- error(describeRecordsFailure(err));
1033
- process.exit(1);
1034
- }
876
+ await saveRecordAction(DOCUMENT_ROUTES, resolvedAppId, documentId, modelName, data, options, documentFormat);
1035
877
  });
1036
878
  // Merge fields into an existing record
1037
879
  records
@@ -1058,21 +900,7 @@ Permissions (enforced by the server, not the CLI):
1058
900
  error(describeRecordsFailure(err));
1059
901
  process.exit(1);
1060
902
  }
1061
- const client = new ApiClient();
1062
- try {
1063
- const result = await client.patchDocumentRecord(resolvedAppId, documentId, modelName, recordId, { data }, { documentFormat });
1064
- if (options.json) {
1065
- json(result);
1066
- return;
1067
- }
1068
- success(`Record patched: ${recordId}`);
1069
- }
1070
- catch (err) {
1071
- // #3764 — the server's sentence, the stable code and the status, so a
1072
- // refused records call is scriptable rather than only readable.
1073
- error(describeRecordsFailure(err));
1074
- process.exit(1);
1075
- }
903
+ await patchRecordAction(DOCUMENT_ROUTES, resolvedAppId, documentId, modelName, recordId, data, options, documentFormat);
1076
904
  });
1077
905
  // Delete a record
1078
906
  records
@@ -1097,37 +925,14 @@ Permissions (enforced by the server, not the CLI):
1097
925
  error(describeRecordsFailure(err));
1098
926
  process.exit(1);
1099
927
  }
1100
- if (!options.yes) {
1101
- const confirmed = await confirmPrompt(`Delete record ${recordId} from ${modelName} in document ${documentId}?`);
1102
- if (!confirmed) {
1103
- info("Cancelled.");
1104
- return;
1105
- }
1106
- }
1107
- const client = new ApiClient();
1108
- try {
1109
- const result = await client.deleteDocumentRecord(resolvedAppId, documentId, modelName, recordId, { documentFormat });
1110
- if (options.json) {
1111
- json(result);
1112
- return;
1113
- }
1114
- // A delete of a missing record is a silent no-op server-side, so
1115
- // this reports the request outcome, not record existence.
1116
- success(`Record deleted: ${recordId}`);
1117
- }
1118
- catch (err) {
1119
- // #3764 — the server's sentence, the stable code and the status, so a
1120
- // refused records call is scriptable rather than only readable.
1121
- error(describeRecordsFailure(err));
1122
- process.exit(1);
1123
- }
928
+ await deleteRecordAction(DOCUMENT_ROUTES, resolvedAppId, documentId, modelName, recordId, options, documentFormat);
1124
929
  });
1125
930
  // Apply an atomic multi-model operations blob
1126
931
  records
1127
- .command("bulk")
1128
- .description("Apply an atomic create/patch/delete/upsert operations blob to a document")
932
+ .command("batch")
933
+ .description(`Apply an atomic create/patch/delete/upsert operations blob to a document, at most ${DB3_BATCH_OPERATION_CAP} operations per call`)
1129
934
  .argument("<document-id>", "Document ID")
1130
- .requiredOption("--data-file <file>", BULK_DATA_FILE_HELP)
935
+ .requiredOption("--data-file <file>", BATCH_DATA_FILE_HELP)
1131
936
  .option("--app <app-id>", "App ID")
1132
937
  .option(DOCUMENT_FORMAT_FLAG, DOCUMENT_FORMAT_HELP)
1133
938
  .option("-y, --yes", "Skip confirmation prompt")
@@ -1143,39 +948,7 @@ Permissions (enforced by the server, not the CLI):
1143
948
  error(describeRecordsFailure(err));
1144
949
  process.exit(1);
1145
950
  }
1146
- const parsed = parseDataOption(options, "operations blob", {
1147
- allowArray: true,
1148
- });
1149
- const operations = Array.isArray(parsed) ? parsed : parsed?.operations;
1150
- if (!Array.isArray(operations) || operations.length === 0) {
1151
- error("--data-file must contain { operations: [...] } or a non-empty operations array.");
1152
- process.exit(1);
1153
- }
1154
- const resolvedAppId = resolveAppId(undefined, options);
1155
- if (!options.yes) {
1156
- const confirmed = await confirmPrompt(`Apply ${operations.length} operation(s) atomically to document ${documentId}?`);
1157
- if (!confirmed) {
1158
- info("Cancelled.");
1159
- return;
1160
- }
1161
- }
1162
- const client = new ApiClient();
1163
- try {
1164
- const result = await client.bulkDocumentRecords(resolvedAppId, documentId, operations, { documentFormat });
1165
- if (options.json) {
1166
- json(result);
1167
- return;
1168
- }
1169
- success(describeBulkResult(result));
1170
- }
1171
- catch (err) {
1172
- const report = describeBulkFailure(err);
1173
- if (options.json)
1174
- json(report.envelope);
1175
- else
1176
- error(report.line);
1177
- process.exit(1);
1178
- }
951
+ await batchRecordsAction(DOCUMENT_ROUTES, documentId, options, documentFormat);
1179
952
  });
1180
953
  // Dump a document's records grouped by model (CLI-side composition)
1181
954
  documents
@@ -1226,29 +999,21 @@ Permissions (enforced by the server, not the CLI):
1226
999
  .option("--app <app-id>", "App ID")
1227
1000
  .option("--json", "Output as JSON")
1228
1001
  .action(async (documentId, options) => {
1229
- const resolvedAppId = resolveAppId(undefined, options);
1230
- const client = new ApiClient();
1231
- try {
1232
- const result = await client.getDocumentStats(resolvedAppId, documentId);
1233
- if (options.json) {
1234
- json(result);
1235
- return;
1236
- }
1237
- keyValue("Document ID", result.documentId);
1238
- keyValue("Records", result.recordCount);
1239
- keyValue("Models", result.modelCount);
1240
- keyValue("Blobs", result.blobCount);
1241
- // A large document's size is its records' stored JSON, exact; an
1242
- // ordinary document's is an estimate (#4193).
1243
- keyValue(result.sizeBasis === "records"
1244
- ? "Size (bytes, records)"
1245
- : "Size (bytes, approx)", result.sizeBytes);
1246
- keyValue("Last modified", result.lastModifiedAt ? formatDate(result.lastModifiedAt) : "—");
1247
- }
1248
- catch (err) {
1249
- error(describeDocumentFailure(err));
1250
- process.exit(1);
1251
- }
1002
+ await statsAction(DOCUMENT_ROUTES, documentId, options);
1003
+ });
1004
+ // #4623 — a document's models and fields as the room declared and observed
1005
+ // them (`GET .../schema`): a table, the route's JSON, or a schema.toml the
1006
+ // client's `schemaToml` option and js-bao-codegen-v2 accept.
1007
+ documents
1008
+ .command("schema")
1009
+ .description("Show a document's models and fields as declared and observed, or export them as a schema.toml")
1010
+ .argument("<document-id>", "Document ID")
1011
+ .option("--app <app-id>", "App ID")
1012
+ .option("--toml", "Print a schema.toml the client's schemaToml option and js-bao-codegen-v2 accept")
1013
+ .option("--output <file>", "With --toml: write the TOML to this file (overwriting it) instead of stdout")
1014
+ .option("--json", "Output the /schema answer as JSON")
1015
+ .action(async (documentId, options) => {
1016
+ await schemaAction(DOCUMENT_ROUTES, documentId, options);
1252
1017
  });
1253
1018
  // #4306 — a record-log document's room: the inspection route's payload.
1254
1019
  documents
@@ -1260,86 +1025,7 @@ Permissions (enforced by the server, not the CLI):
1260
1025
  .option("--limit <n>", "With --refused: rows per page read (1–100)", "100")
1261
1026
  .option("--json", "Output as JSON")
1262
1027
  .action(async (documentId, options) => {
1263
- const resolvedAppId = resolveAppId(undefined, options);
1264
- const client = new ApiClient();
1265
- try {
1266
- if (options.refused !== undefined) {
1267
- // Every page, in order: the room keeps each refused row with its code.
1268
- const items = [];
1269
- let cursor;
1270
- do {
1271
- const page = await client.getDocumentRoom(resolvedAppId, documentId, {
1272
- refused: options.refused,
1273
- limit: Number(options.limit),
1274
- cursor,
1275
- });
1276
- items.push(...page.refused.items);
1277
- cursor = page.refused.hasMore ? page.refused.nextCursor : undefined;
1278
- } while (cursor);
1279
- if (options.json) {
1280
- json({ documentId, sessionId: options.refused, items });
1281
- return;
1282
- }
1283
- keyValue("Document ID", documentId);
1284
- keyValue("Session", options.refused);
1285
- keyValue("Refused rows", items.length);
1286
- for (const row of items) {
1287
- const conflicting = row.conflicting ? ` (held by ${row.conflicting.model} ${row.conflicting.id})` : "";
1288
- keyValue(` ${row.model} ${row.id}`, `${row.code}${row.constraint ? ` ${row.constraint}` : ""}${conflicting}`);
1289
- }
1290
- return;
1291
- }
1292
- const result = await client.getDocumentRoom(resolvedAppId, documentId);
1293
- if (options.json) {
1294
- json(result);
1295
- return;
1296
- }
1297
- keyValue("Document ID", result.documentId);
1298
- printDocumentFormat(result);
1299
- const room = result.room;
1300
- if (!room) {
1301
- keyValue("Room", `no record room (format ${result.documentFormat ?? 1})`);
1302
- return;
1303
- }
1304
- keyValue("Log number", room.lsn);
1305
- keyValue("Epochs", `current ${room.epochs.current}, next ${room.epochs.next}, high ${room.epochs.high}`);
1306
- keyValue("Epoch floor", room.epochs.floor);
1307
- keyValue("Cursor floor", room.cursorFloor);
1308
- keyValue("Entries since rotation", room.epochs.entriesSinceRotation);
1309
- keyValue("Rotated", room.epochs.rotatedAt ? formatDate(room.epochs.rotatedAt) : "—");
1310
- keyValue("Writers", `${room.writers.count} (${room.writers.connected} connected)`);
1311
- keyValue("Subscribers", room.subscribers);
1312
- keyValue("Held entries", room.held.entries);
1313
- const load = room.load;
1314
- keyValue("Load", load
1315
- ? `${load.sessionId} ${load.state} (${load.mode}, epoch reserved at ${load.reserveEpoch}` +
1316
- (load.epoch !== null ? `: epoch ${load.epoch} from log number ${load.k}` : "") +
1317
- `), ${load.chunksApplied}/${load.chunks} chunks, ${load.rowsApplied} rows applied, ` +
1318
- `${load.refusedRows} refused, ${load.touched} keys touched`
1319
- : "none");
1320
- const loads = Array.isArray(room.loads) ? room.loads : [];
1321
- keyValue("Loads", loads.length
1322
- ? loads
1323
- .map((l) => `${l.sessionId} (${l.mode}, log numbers ${l.firstLsn ?? "—"}–${l.lastLsn ?? "—"}, ${l.rows} rows, ${l.touched} keys touched)`)
1324
- .join("; ")
1325
- : "none kept");
1326
- const segmentLine = (s) => `${s.segmentId} ${s.state} (log number ${s.lsn}` +
1327
- (s.completedLsn !== null && s.completedLsn !== undefined ? `, completed at ${s.completedLsn}` : "") +
1328
- `, ${s.rows} rows, ${s.chunks} chunks)`;
1329
- keyValue("Segment", room.segment ? segmentLine(room.segment) : "none");
1330
- keyValue("Segment export", room.segmentExport ? segmentLine(room.segmentExport) : "none");
1331
- keyValue("Last checkpoint", room.checkpoint
1332
- ? `${formatDate(room.checkpoint.at)} (${room.checkpoint.durationMs} ms, ` +
1333
- `${room.checkpoint.pruned} pruned, ${room.checkpoint.dropped} dropped, ` +
1334
- `${room.checkpoint.writersDropped} writers dropped)`
1335
- : "none yet");
1336
- keyValue("Next alarm", room.nextAlarmAt ? formatDate(room.nextAlarmAt) : "—");
1337
- keyValue("Storage (bytes)", room.storage?.databaseSize ?? "—");
1338
- }
1339
- catch (err) {
1340
- error(describeDocumentFailure(err));
1341
- process.exit(1);
1342
- }
1028
+ await inspectAction(DOCUMENT_ROUTES, documentId, options);
1343
1029
  });
1344
1030
  // The action verb (#3435, criterion 9): a directory of records becomes a
1345
1031
  // chunked, digested, uploaded artifact and one atomic swap of the
@@ -1362,125 +1048,7 @@ Permissions (enforced by the server, not the CLI):
1362
1048
  .option("--timeout <seconds>", "Give up waiting after this many seconds")
1363
1049
  .option("--json", "Output as JSON")
1364
1050
  .action(async (documentId, options) => {
1365
- const resolvedAppId = resolveAppId(undefined, options);
1366
- const client = new ApiClient();
1367
- let plan = null;
1368
- // The exit code is carried out of here rather than taken inside: a
1369
- // `process.exit` does not unwind, so ending the process in the try block
1370
- // would skip the cleanup in the finally and leave the compressed
1371
- // artifact — up to the whole input, gzipped — in the OS temp directory
1372
- // on every run, successful or not (finding 3435-FROZEN-05).
1373
- const run = async () => {
1374
- // A flag's value is checked before any request.
1375
- const flags = parseIngestFlags({ reserveEpoch: options.reserveEpoch, mode: options.mode });
1376
- // The preflight, in this order and before a byte is read from disk:
1377
- // the schema read says whether this caller may see the document's
1378
- // declarations at all and hands over the ones the lines are checked
1379
- // against, and the session reader says whether this is a large
1380
- // document. Both are READS on the arm the ingest routes admit, so a
1381
- // caller who would be refused halfway is refused at once, and neither
1382
- // opens a session.
1383
- const introspection = await client.getDocumentSchema(resolvedAppId, documentId);
1384
- await client.listDocumentIngests(resolvedAppId, documentId, { limit: 1 });
1385
- const schema = ingestSchemaFromIntrospection(introspection);
1386
- // A record-log (format 3) document takes models and fields it does
1387
- // not declare, as its writes do (#4310); its schema read says so.
1388
- const recordLog = Number(introspection?.documentFormat) === 3;
1389
- const input = discoverIngestInput(options.input, documentId);
1390
- for (const ignored of input.ignored) {
1391
- info(`Ignoring ${ignored}: a bulk load reads the snapshot only.`);
1392
- }
1393
- const body = ingestCreateBody(flags, input.sources.map((source) => source.model));
1394
- // #3598 — reading, checking, sorting, cutting and gzipping is this
1395
- // side's biggest phase on a large input, and it used to be invisible
1396
- // inside one wall-clock number that also covered the platform's work.
1397
- const buildStartedAt = Date.now();
1398
- plan = await buildIngestArtifact({ input, schema, open: recordLog });
1399
- const buildMs = Date.now() - buildStartedAt;
1400
- info(`Built artifact in ${(buildMs / 1000).toFixed(1)}s.`);
1401
- for (const line of summariseIngestPlan(plan))
1402
- info(line);
1403
- assertIngestConfirmable({
1404
- yes: Boolean(options.yes),
1405
- isTTY: Boolean(process.stdin.isTTY),
1406
- });
1407
- if (!options.yes) {
1408
- const confirmed = await confirmPrompt(`Bulk-load ${plan.rows} records into ${documentId}? ` +
1409
- "This replaces records in a live document and cannot be undone.");
1410
- if (!confirmed) {
1411
- info("Nothing was uploaded.");
1412
- return 1;
1413
- }
1414
- }
1415
- // Ctrl-C is a decision the driver makes differently depending on
1416
- // where it lands, so it is handed the signal rather than killing the
1417
- // process: mid-upload the session is aborted, mid-poll it is left
1418
- // running, because by then the document is already being changed.
1419
- const interrupt = new AbortController();
1420
- const onSignal = () => interrupt.abort();
1421
- process.on("SIGINT", onSignal);
1422
- let outcome;
1423
- try {
1424
- outcome = await driveDocumentIngest({
1425
- client: {
1426
- createIngest: (id) => client.createDocumentIngest(resolvedAppId, id, body),
1427
- uploadIngestChunk: (id, sessionId, chunk) => client.uploadDocumentIngestChunk(resolvedAppId, id, sessionId, chunk),
1428
- commitIngest: (id, sessionId) => client.commitDocumentIngest(resolvedAppId, id, sessionId),
1429
- abortIngest: (id, sessionId) => client.abortDocumentIngest(resolvedAppId, id, sessionId),
1430
- getIngest: (id, sessionId) => client.getDocumentIngest(resolvedAppId, id, sessionId),
1431
- },
1432
- documentId,
1433
- plan,
1434
- wait: options.wait !== false,
1435
- timeoutMs: options.timeout ? Number(options.timeout) * 1000 : null,
1436
- signal: interrupt.signal,
1437
- onProgress: (line) => info(line),
1438
- });
1439
- }
1440
- finally {
1441
- process.off("SIGINT", onSignal);
1442
- }
1443
- if (outcome.message)
1444
- error(outcome.message);
1445
- // #3598 — the two sides, side by side. The session's own `timings`
1446
- // say where the platform's share went; `client` says what this
1447
- // process spent before and around it, so a slow load can be blamed on
1448
- // the side that was actually slow.
1449
- const clientTimings = { buildMs, ...outcome.timings };
1450
- if (options.json) {
1451
- json({
1452
- ...(outcome.session ?? { sessionId: outcome.sessionId }),
1453
- client: clientTimings,
1454
- });
1455
- }
1456
- else {
1457
- if (outcome.session) {
1458
- printIngestSession(outcome.session);
1459
- }
1460
- else if (outcome.sessionId) {
1461
- printResult("Session", outcome.sessionId);
1462
- }
1463
- for (const [label, value] of ingestClientRows(clientTimings)) {
1464
- printResult(label, value);
1465
- }
1466
- }
1467
- return outcome.exitCode;
1468
- };
1469
- let code = 1;
1470
- try {
1471
- code = await run();
1472
- }
1473
- catch (err) {
1474
- error(describeDocumentFailure(err));
1475
- code = 1;
1476
- }
1477
- finally {
1478
- await plan?.cleanup().catch(() => undefined);
1479
- }
1480
- // The result has to reach the pipe before the process ends: stdout to a
1481
- // pipe is asynchronous and `process.exit` does not wait for it.
1482
- await flushOutput();
1483
- process.exit(code);
1051
+ await ingestAction(DOCUMENT_LOAD_ROUTES, documentId, options);
1484
1052
  });
1485
1053
  // Bulk-load sessions of a large document (#3434, criterion 9): a data noun
1486
1054
  // with `list` and `get` readers, per docs/cli-design.md, beside `snapshots`
@@ -1499,42 +1067,7 @@ Permissions (enforced by the server, not the CLI):
1499
1067
  .option("--cursor <cursor>", "Continue from a previous page's nextCursor")
1500
1068
  .option("--json", "Output as JSON")
1501
1069
  .action(async (documentId, options) => {
1502
- const limit = parsePageLimit(options.limit);
1503
- const resolvedAppId = resolveAppId(undefined, options);
1504
- const client = new ApiClient();
1505
- try {
1506
- const page = normalizeCliListEnvelope(await client.listDocumentIngests(resolvedAppId, documentId, {
1507
- limit,
1508
- ...(options.cursor ? { cursor: options.cursor } : {}),
1509
- }));
1510
- if (options.json) {
1511
- json(page);
1512
- return;
1513
- }
1514
- if (page.items.length === 0) {
1515
- info("No ingest sessions yet.");
1516
- return;
1517
- }
1518
- console.log(formatTable(page.items, [
1519
- { header: "SESSION", key: "sessionId" },
1520
- { header: "STATE", key: "state" },
1521
- { header: "CREATED", key: "createdAt", format: formatDate },
1522
- { header: "CHUNKS", key: "chunks" },
1523
- { header: "ROWS", key: "rows" },
1524
- {
1525
- header: "COMPLETED",
1526
- key: "completedAt",
1527
- format: (at) => (at ? formatDate(at) : "—"),
1528
- },
1529
- ]));
1530
- if (page.hasMore && page.nextCursor) {
1531
- info(`More sessions: --cursor ${page.nextCursor}`);
1532
- }
1533
- }
1534
- catch (err) {
1535
- error(describeDocumentFailure(err));
1536
- process.exit(1);
1537
- }
1070
+ await listIngestsAction(DOCUMENT_LOAD_ROUTES, documentId, options);
1538
1071
  });
1539
1072
  ingests
1540
1073
  .command("get")
@@ -1544,20 +1077,7 @@ Permissions (enforced by the server, not the CLI):
1544
1077
  .option("--app <app-id>", "App ID")
1545
1078
  .option("--json", "Output as JSON")
1546
1079
  .action(async (documentId, sessionId, options) => {
1547
- const resolvedAppId = resolveAppId(undefined, options);
1548
- const client = new ApiClient();
1549
- try {
1550
- const session = await client.getDocumentIngest(resolvedAppId, documentId, sessionId);
1551
- if (options.json) {
1552
- json(session);
1553
- return;
1554
- }
1555
- printIngestSession(session);
1556
- }
1557
- catch (err) {
1558
- error(describeDocumentFailure(err));
1559
- process.exit(1);
1560
- }
1080
+ await getIngestAction(DOCUMENT_LOAD_ROUTES, documentId, sessionId, options);
1561
1081
  });
1562
1082
  // Destructive — what the session uploaded is discarded — so it confirms
1563
1083
  // unless `-y`, and a non-TTY stdin without `-y` is refused before any
@@ -1571,33 +1091,7 @@ Permissions (enforced by the server, not the CLI):
1571
1091
  .option("-y, --yes", "Skip the confirmation prompt")
1572
1092
  .option("--json", "Output as JSON")
1573
1093
  .action(async (documentId, sessionId, options) => {
1574
- const resolvedAppId = resolveAppId(undefined, options);
1575
- if (!options.yes) {
1576
- if (!process.stdin.isTTY) {
1577
- error("Aborting a bulk load discards what it uploaded. " +
1578
- "Re-run with -y to confirm it without a prompt.");
1579
- process.exit(1);
1580
- }
1581
- const confirmed = await confirmPrompt(`Abort bulk load ${sessionId} on ${documentId}? What it uploaded is ` +
1582
- "discarded; rows a committed load already applied stay.");
1583
- if (!confirmed) {
1584
- info("Cancelled.");
1585
- return;
1586
- }
1587
- }
1588
- const client = new ApiClient();
1589
- try {
1590
- const session = await client.abortDocumentIngest(resolvedAppId, documentId, sessionId);
1591
- if (options.json) {
1592
- json(session);
1593
- return;
1594
- }
1595
- printIngestSession(session);
1596
- }
1597
- catch (err) {
1598
- error(describeDocumentFailure(err));
1599
- process.exit(1);
1600
- }
1094
+ await abortIngestAction(DOCUMENT_LOAD_ROUTES, documentId, sessionId, options);
1601
1095
  });
1602
1096
  // Snapshot builds of a large document (#3432, criterion 9): a data noun
1603
1097
  // with `list` and `get` readers, per docs/cli-design.md, over the app API's
@@ -1614,63 +1108,7 @@ Permissions (enforced by the server, not the CLI):
1614
1108
  .option("--cursor <cursor>", "Continue from a previous page's nextCursor")
1615
1109
  .option("--json", "Output as JSON")
1616
1110
  .action(async (documentId, options) => {
1617
- const limit = parsePageLimit(options.limit);
1618
- const resolvedAppId = resolveAppId(undefined, options);
1619
- const client = new ApiClient();
1620
- try {
1621
- const page = normalizeCliListEnvelope(await client.listDocumentSnapshots(resolvedAppId, documentId, {
1622
- limit,
1623
- ...(options.cursor ? { cursor: options.cursor } : {}),
1624
- }));
1625
- if (options.json) {
1626
- json(page);
1627
- return;
1628
- }
1629
- if (page.items.length === 0) {
1630
- info("No snapshot builds yet.");
1631
- return;
1632
- }
1633
- // A record-log (format 3) document's are its segments (#4310).
1634
- if (page.items.some((item) => typeof item?.segmentId === "string")) {
1635
- console.log(formatTable(page.items, [
1636
- { header: "SEGMENT", key: "segmentId" },
1637
- { header: "LOG NUMBER", key: "lsn" },
1638
- { header: "COMPLETED AT LOG NUMBER", key: "completedLsn", format: (v) => (v === null || v === undefined ? "-" : String(v)) },
1639
- { header: "STATE", key: "state" },
1640
- { header: "ROWS", key: "rows" },
1641
- { header: "CHUNKS", key: "chunks" },
1642
- { header: "STARTED", key: "startedAt", format: formatDate },
1643
- { header: "COMPLETED", key: "completedAt", format: formatDate },
1644
- ]));
1645
- return;
1646
- }
1647
- console.log(formatTable(page.items, [
1648
- { header: "BUILD", key: "buildId" },
1649
- { header: "EPOCH", key: "epoch" },
1650
- { header: "STATE", key: "state" },
1651
- { header: "SOURCE", key: "source" },
1652
- {
1653
- header: "VERIFICATION",
1654
- key: "verification",
1655
- format: (verification) => verification
1656
- ? verification.code
1657
- ? `${verification.state} (${verification.code})`
1658
- : verification.state
1659
- : "-",
1660
- },
1661
- { header: "ROWS", key: "rows" },
1662
- { header: "CHUNKS", key: "chunks" },
1663
- { header: "STARTED", key: "startedAt", format: formatDate },
1664
- { header: "COMPLETED", key: "completedAt", format: formatDate },
1665
- ]));
1666
- if (page.hasMore && page.nextCursor) {
1667
- info(`More builds: --cursor ${page.nextCursor}`);
1668
- }
1669
- }
1670
- catch (err) {
1671
- error(describeDocumentFailure(err));
1672
- process.exit(1);
1673
- }
1111
+ await listSnapshotsAction(DOCUMENT_LOAD_ROUTES, documentId, options);
1674
1112
  });
1675
1113
  snapshots
1676
1114
  .command("get")
@@ -1680,26 +1118,7 @@ Permissions (enforced by the server, not the CLI):
1680
1118
  .option("--app <app-id>", "App ID")
1681
1119
  .option("--json", "Output as JSON")
1682
1120
  .action(async (documentId, buildId, options) => {
1683
- const resolvedAppId = resolveAppId(undefined, options);
1684
- const client = new ApiClient();
1685
- try {
1686
- const build = await client.getDocumentSnapshot(resolvedAppId, documentId, buildId);
1687
- if (options.json) {
1688
- json(build);
1689
- return;
1690
- }
1691
- // The rows are composed by a pure function (#3435), so what a
1692
- // terminal shows is checkable without spawning one; the command still
1693
- // owns the printing. A record-log document's build is a segment (#4310).
1694
- const rows = typeof build?.segmentId === "string" ? segmentRows(build) : snapshotBuildRows(build);
1695
- for (const [label, value] of rows) {
1696
- printResult(label, value);
1697
- }
1698
- }
1699
- catch (err) {
1700
- error(describeDocumentFailure(err));
1701
- process.exit(1);
1702
- }
1121
+ await getSnapshotAction(DOCUMENT_LOAD_ROUTES, documentId, buildId, options);
1703
1122
  });
1704
1123
  // #3666, criterion 7 — the one ACTION verb in this group: snapshot the
1705
1124
  // document now instead of waiting for the size or age trigger. Its exit
@@ -1715,81 +1134,11 @@ Permissions (enforced by the server, not the CLI):
1715
1134
  .description("Snapshot a large document now: start a segment export of its records")
1716
1135
  .argument("<document-id>", "Document ID")
1717
1136
  .option("--app <app-id>", "App ID")
1718
- .option("--wait", "Poll until the segment is complete or failed")
1719
- .option("--timeout <seconds>", "Give up waiting after this many seconds")
1720
- .option("--json", "Output as JSON")
1721
- .action(async (documentId, options) => {
1722
- const resolvedAppId = resolveAppId(undefined, options);
1723
- const client = new ApiClient();
1724
- const run = async () => {
1725
- // Ctrl-C while polling leaves the build running — by then the room is
1726
- // already building it and giving up on watching is not giving up on
1727
- // the build — so the signal is handed to the driver rather than
1728
- // killing the process.
1729
- const interrupt = new AbortController();
1730
- const onSignal = () => interrupt.abort();
1731
- process.on("SIGINT", onSignal);
1732
- let outcome;
1733
- try {
1734
- outcome = await driveSnapshotBuild({
1735
- client: {
1736
- requestSnapshot: (id) => client.requestDocumentSnapshot(resolvedAppId, id),
1737
- getSnapshot: (id, buildId) => client.getDocumentSnapshot(resolvedAppId, id, buildId),
1738
- },
1739
- documentId,
1740
- wait: Boolean(options.wait),
1741
- timeoutMs: options.timeout ? Number(options.timeout) * 1000 : null,
1742
- signal: interrupt.signal,
1743
- onProgress: (line) => info(line),
1744
- });
1745
- }
1746
- finally {
1747
- process.off("SIGINT", onSignal);
1748
- }
1749
- if (outcome.message)
1750
- error(outcome.message);
1751
- if (options.json) {
1752
- // The route's answer as received, with the build the wait settled
1753
- // on beside it when there was one — so a script branches on the
1754
- // verdict rather than on an exit code alone.
1755
- json(outcome.build ? { ...outcome.response, build: outcome.build } : outcome.response);
1756
- return outcome.exitCode;
1757
- }
1758
- if (typeof outcome.response?.segmentId === "string") {
1759
- // A record-log document's segment export (#4310).
1760
- if (outcome.build) {
1761
- for (const [label, value] of segmentRows(outcome.build))
1762
- printResult(label, value);
1763
- }
1764
- else {
1765
- printResult("Segment", outcome.response.segmentId);
1766
- printResult("State", outcome.response.state);
1767
- printResult("Log number", outcome.response.lsn);
1768
- }
1769
- return outcome.exitCode;
1770
- }
1771
- printResult("Build", outcome.response?.buildId);
1772
- return outcome.exitCode;
1773
- };
1774
- let code = 1;
1775
- try {
1776
- code = await run();
1777
- }
1778
- catch (err) {
1779
- // The server's own sentence, plus the code a script branches on
1780
- // (#3403) — a refused loop that only says "too young to seal" leaves
1781
- // a caller parsing prose to tell it from a permission refusal.
1782
- error(err.code ? `${err.message} (${err.code})` : err.message);
1783
- const retryAfterMs = err.details?.retryAfterMs;
1784
- if (typeof retryAfterMs === "number") {
1785
- error(`Ask again in ${Math.ceil(retryAfterMs / 1000)}s.`);
1786
- }
1787
- code = 1;
1788
- }
1789
- // The result has to reach the pipe before the process ends: stdout to a
1790
- // pipe is asynchronous and `process.exit` does not wait for it.
1791
- await flushOutput();
1792
- process.exit(code);
1137
+ .option("--wait", "Poll until the segment is complete or failed")
1138
+ .option("--timeout <seconds>", "Give up waiting after this many seconds")
1139
+ .option("--json", "Output as JSON")
1140
+ .action(async (documentId, options) => {
1141
+ await buildSnapshotAction(DOCUMENT_LOAD_ROUTES, documentId, options);
1793
1142
  });
1794
1143
  // Transfer document ownership
1795
1144
  documents
@@ -3218,4 +2567,919 @@ async function importRootDocument(client, appId, docDir, metadata, plan, overwri
3218
2567
  `${plan.owner}'s root document ${targetRootDocId}`);
3219
2568
  }
3220
2569
  }
2570
+ /** The aggregate operations `records aggregate` takes. */
2571
+ const AGGREGATE_OPS = ["count", "sum", "avg", "min", "max"];
2572
+ // ---- The records, schema and inspect verbs' bodies (#4696) ----
2573
+ // Shared by the `documents` verbs and their `db3` twins (`./db3.ts`): each
2574
+ // sends its request through `routes` and prints the answer, so both nouns
2575
+ // print the same thing for the same answer. The caller has resolved the app
2576
+ // (where the body does not) and read its own flags, `--document-format`
2577
+ // included.
2578
+ /**
2579
+ * The read `records query`'s flags describe: the filter, and `--sort` and
2580
+ * `--include` parsed as JSON (their shapes are the route's to refuse, with
2581
+ * its own messages). Exits 1 on JSON that does not parse.
2582
+ */
2583
+ export function queryReadOf(options) {
2584
+ const filter = parseFilterOptions(options);
2585
+ // The JSON is checked here; its shape (`{ field: 1 | -1 }`) is the
2586
+ // route's to refuse, with its own `Invalid sort` message.
2587
+ let sort;
2588
+ if (options.sort !== undefined) {
2589
+ try {
2590
+ sort = JSON.parse(options.sort);
2591
+ }
2592
+ catch {
2593
+ error("Invalid --sort JSON.");
2594
+ process.exit(1);
2595
+ }
2596
+ }
2597
+ // The same for `--include`: its specs are the route's to refuse.
2598
+ let include;
2599
+ if (options.include !== undefined) {
2600
+ try {
2601
+ include = JSON.parse(options.include);
2602
+ }
2603
+ catch {
2604
+ error("Invalid --include JSON.");
2605
+ process.exit(1);
2606
+ }
2607
+ }
2608
+ return { filter, sort, include };
2609
+ }
2610
+ /** `records query`: one page of a model's records, as a table or `--json`. */
2611
+ export async function queryRecordsAction(routes, resolvedAppId, documentId, modelName, options, documentFormat) {
2612
+ const { filter, sort, include } = queryReadOf(options);
2613
+ const client = new ApiClient();
2614
+ try {
2615
+ const result = await routes.query(client, resolvedAppId, documentId, modelName, { filter, sort, limit: options.limit, cursor: options.cursor, documentFormat, include });
2616
+ if (options.json) {
2617
+ json(result);
2618
+ return;
2619
+ }
2620
+ const items = result.items;
2621
+ if (items.length === 0) {
2622
+ info("No records found.");
2623
+ return;
2624
+ }
2625
+ const allKeys = new Set();
2626
+ for (const rec of items) {
2627
+ for (const key of Object.keys(rec))
2628
+ allKeys.add(key);
2629
+ }
2630
+ const orderedKeys = [];
2631
+ if (allKeys.has("id")) {
2632
+ orderedKeys.push("id");
2633
+ allKeys.delete("id");
2634
+ }
2635
+ orderedKeys.push(...[...allKeys].sort());
2636
+ const columns = orderedKeys.map((key) => ({
2637
+ header: key.toUpperCase(),
2638
+ key,
2639
+ format: (v) => {
2640
+ if (v === null || v === undefined)
2641
+ return "—";
2642
+ if (typeof v === "object")
2643
+ return JSON.stringify(v);
2644
+ return String(v);
2645
+ },
2646
+ }));
2647
+ console.log(formatTable(items, columns));
2648
+ if (result.nextCursor) {
2649
+ // A cursor continues only the sort that minted it.
2650
+ const sortArg = sort !== undefined ? ` --sort ${quoteCursorArg(JSON.stringify(sort))}` : "";
2651
+ info(`More results available. Use --cursor ${result.nextCursor}${sortArg}`);
2652
+ }
2653
+ }
2654
+ catch (err) {
2655
+ // #3764 — the server's sentence, the stable code and the status, so a
2656
+ // refused records call is scriptable rather than only readable.
2657
+ error(describeRecordsFailure(err));
2658
+ process.exit(1);
2659
+ }
2660
+ }
2661
+ /** `records count`: how many of a model's records match the filter. */
2662
+ export async function countRecordsAction(routes, resolvedAppId, documentId, modelName, options, documentFormat) {
2663
+ const filter = parseFilterOptions(options);
2664
+ const client = new ApiClient();
2665
+ try {
2666
+ const result = await routes.count(client, resolvedAppId, documentId, modelName, { filter, documentFormat });
2667
+ if (options.json) {
2668
+ json(result);
2669
+ return;
2670
+ }
2671
+ console.log(` ${result.count}`);
2672
+ }
2673
+ catch (err) {
2674
+ // #3764 — the server's sentence, the stable code and the status, so a
2675
+ // refused records call is scriptable rather than only readable.
2676
+ error(describeRecordsFailure(err));
2677
+ process.exit(1);
2678
+ }
2679
+ }
2680
+ /**
2681
+ * The aggregate `records aggregate`'s flags describe: its one operation, its
2682
+ * `--group-by` levels and its filter. Exits 1 before any request on an
2683
+ * unknown `--op`, or a `--field` the operation does not take or lacks.
2684
+ */
2685
+ export function aggregateReadOf(options) {
2686
+ if (!AGGREGATE_OPS.includes(options.op)) {
2687
+ error(`Invalid --op "${options.op}". Expected one of: ${AGGREGATE_OPS.join(", ")}.`);
2688
+ process.exit(1);
2689
+ }
2690
+ const operation = { type: options.op };
2691
+ if (options.op === "count") {
2692
+ if (options.field) {
2693
+ error("--field is not valid for --op count.");
2694
+ process.exit(1);
2695
+ }
2696
+ }
2697
+ else {
2698
+ if (!options.field) {
2699
+ error(`--op ${options.op} requires --field.`);
2700
+ process.exit(1);
2701
+ }
2702
+ operation.field = options.field;
2703
+ }
2704
+ return { operations: [operation], groupBy: options.groupBy || [], filter: parseFilterOptions(options) };
2705
+ }
2706
+ /** `records aggregate`: one operation over a model's records, optionally grouped. */
2707
+ export async function aggregateRecordsAction(routes, resolvedAppId, documentId, modelName, options, documentFormat) {
2708
+ const { operations, groupBy, filter } = aggregateReadOf(options);
2709
+ const client = new ApiClient();
2710
+ try {
2711
+ const response = await routes.aggregate(client, resolvedAppId, documentId, modelName, { operations, groupBy, filter }, { documentFormat });
2712
+ if (options.json) {
2713
+ json(response);
2714
+ return;
2715
+ }
2716
+ // The route answers rows (#4265): one key/value line when
2717
+ // ungrouped, a table with one column per group key when grouped.
2718
+ const rendered = renderAggregateResult(response?.result, {
2719
+ groupBy,
2720
+ op: options.op,
2721
+ field: options.field,
2722
+ });
2723
+ if (rendered.kind === "scalar") {
2724
+ keyValue(rendered.label, rendered.value);
2725
+ }
2726
+ else {
2727
+ console.log(rendered.text);
2728
+ }
2729
+ }
2730
+ catch (err) {
2731
+ // #3764 — the server's sentence, the stable code and the status, so a
2732
+ // refused records call is scriptable rather than only readable.
2733
+ error(describeRecordsFailure(err));
2734
+ process.exit(1);
2735
+ }
2736
+ }
2737
+ /** `records save`: create or replace a record with the parsed `data`. */
2738
+ export async function saveRecordAction(routes, resolvedAppId, documentId, modelName, data, options, documentFormat) {
2739
+ const recordId = options.id || ulid();
2740
+ const writeOptions = options.upsertOn ? { upsertOn: options.upsertOn } : undefined;
2741
+ const client = new ApiClient();
2742
+ try {
2743
+ const result = await routes.save(client, resolvedAppId, documentId, modelName, { id: recordId, data, ...(writeOptions ? { options: writeOptions } : {}) }, { documentFormat });
2744
+ if (options.json) {
2745
+ json(result);
2746
+ return;
2747
+ }
2748
+ success(`Record saved: ${result.record?.id ?? recordId}`);
2749
+ }
2750
+ catch (err) {
2751
+ // #3764 — the server's sentence, the stable code and the status, so a
2752
+ // refused records call is scriptable rather than only readable.
2753
+ error(describeRecordsFailure(err));
2754
+ process.exit(1);
2755
+ }
2756
+ }
2757
+ /** `records patch`: merge the parsed `data` into a record. */
2758
+ export async function patchRecordAction(routes, resolvedAppId, documentId, modelName, recordId, data, options, documentFormat) {
2759
+ const client = new ApiClient();
2760
+ try {
2761
+ const result = await routes.patch(client, resolvedAppId, documentId, modelName, recordId, { data }, { documentFormat });
2762
+ if (options.json) {
2763
+ json(result);
2764
+ return;
2765
+ }
2766
+ success(`Record patched: ${recordId}`);
2767
+ }
2768
+ catch (err) {
2769
+ // #3764 — the server's sentence, the stable code and the status, so a
2770
+ // refused records call is scriptable rather than only readable.
2771
+ error(describeRecordsFailure(err));
2772
+ process.exit(1);
2773
+ }
2774
+ }
2775
+ /** `records delete`: delete a record, confirming first unless `--yes`. */
2776
+ export async function deleteRecordAction(routes, resolvedAppId, documentId, modelName, recordId, options, documentFormat) {
2777
+ if (!options.yes) {
2778
+ const confirmed = await confirmPrompt(`Delete record ${recordId} from ${modelName} in ${routes.noun} ${documentId}?`);
2779
+ if (!confirmed) {
2780
+ info("Cancelled.");
2781
+ return;
2782
+ }
2783
+ }
2784
+ const client = new ApiClient();
2785
+ try {
2786
+ const result = await routes.delete(client, resolvedAppId, documentId, modelName, recordId, { documentFormat });
2787
+ if (options.json) {
2788
+ json(result);
2789
+ return;
2790
+ }
2791
+ // A delete of a missing record is a silent no-op server-side, so
2792
+ // this reports the request outcome, not record existence.
2793
+ success(`Record deleted: ${recordId}`);
2794
+ }
2795
+ catch (err) {
2796
+ // #3764 — the server's sentence, the stable code and the status, so a
2797
+ // refused records call is scriptable rather than only readable.
2798
+ error(describeRecordsFailure(err));
2799
+ process.exit(1);
2800
+ }
2801
+ }
2802
+ /** `records batch`: apply an operations blob atomically, confirming first unless `--yes`. */
2803
+ export async function batchRecordsAction(routes, documentId, options, documentFormat) {
2804
+ const parsed = parseDataOption(options, "operations blob", {
2805
+ allowArray: true,
2806
+ });
2807
+ const operations = Array.isArray(parsed) ? parsed : parsed?.operations;
2808
+ if (!Array.isArray(operations) || operations.length === 0) {
2809
+ error("--data-file must contain { operations: [...] } or a non-empty operations array.");
2810
+ process.exit(1);
2811
+ }
2812
+ // A blob over the cap is refused whole by the server, and splitting it
2813
+ // would give up the one-call atomicity the verb promises, so say so first.
2814
+ const limit = routes.batchLimit;
2815
+ if (operations.length > limit.operations) {
2816
+ error(`--data-file holds ${operations.length} operations; ${routes.noun} records batch takes ` +
2817
+ `at most ${limit.operations} operations per call (atomic). ` +
2818
+ `Use \`${limit.largerLoads}\` for larger loads.`);
2819
+ process.exit(1);
2820
+ }
2821
+ const resolvedAppId = resolveAppId(undefined, options);
2822
+ if (!options.yes) {
2823
+ const confirmed = await confirmPrompt(`Apply ${operations.length} operation(s) atomically to ${routes.noun} ${documentId}?`);
2824
+ if (!confirmed) {
2825
+ info("Cancelled.");
2826
+ return;
2827
+ }
2828
+ }
2829
+ const client = new ApiClient();
2830
+ try {
2831
+ const result = await routes.batch(client, resolvedAppId, documentId, operations, { documentFormat });
2832
+ if (options.json) {
2833
+ json(result);
2834
+ return;
2835
+ }
2836
+ success(describeBatchResult(result));
2837
+ for (const line of describeBatchReadResults(result.reads ?? []))
2838
+ info(line);
2839
+ }
2840
+ catch (err) {
2841
+ const report = describeBatchFailure(err);
2842
+ if (options.json)
2843
+ json(report.envelope);
2844
+ else
2845
+ error(report.line);
2846
+ process.exit(1);
2847
+ }
2848
+ }
2849
+ /**
2850
+ * `db3 records batch-read` (#5243): several reads of a db3 in one request,
2851
+ * answered from one state of it, one line per result; `--json` prints the
2852
+ * envelope. `--partial` answers a refused read in its place.
2853
+ */
2854
+ export async function batchReadRecordsAction(client, db3Id, options) {
2855
+ const parsed = parseDataOption(options, "reads blob", { allowArray: true });
2856
+ const operations = Array.isArray(parsed) ? parsed : parsed?.operations;
2857
+ if (!Array.isArray(operations) || operations.length === 0) {
2858
+ error("--data-file must contain { operations: [...] } or a non-empty array of reads.");
2859
+ process.exit(1);
2860
+ }
2861
+ if (operations.length > DB3_BATCH_OPERATION_CAP) {
2862
+ error(`--data-file holds ${operations.length} reads; db3 records batch-read takes ` +
2863
+ `at most ${DB3_BATCH_OPERATION_CAP} operations per call.`);
2864
+ process.exit(1);
2865
+ }
2866
+ const resolvedAppId = resolveAppId(undefined, options);
2867
+ try {
2868
+ const result = await client.batchReadDb3Records(resolvedAppId, db3Id, operations, { atomic: options.partial ? false : undefined });
2869
+ if (options.json) {
2870
+ json(result);
2871
+ return;
2872
+ }
2873
+ // One line per result, on stdout: the answer is the command's output.
2874
+ for (const line of describeBatchReadResults(result.results ?? []))
2875
+ console.log(line);
2876
+ }
2877
+ catch (err) {
2878
+ const report = describeBatchFailure(err);
2879
+ if (options.json)
2880
+ json(report.envelope);
2881
+ else
2882
+ error(report.line);
2883
+ process.exit(1);
2884
+ }
2885
+ }
2886
+ /** `schema`: the models and fields as declared and observed, a table, the JSON or a schema.toml. */
2887
+ /** `records models` (shared with `db3 records models`, #4804): the model names the schema route answers. */
2888
+ export async function modelsAction(routes, documentId, options) {
2889
+ const resolvedAppId = resolveAppId(undefined, options);
2890
+ const client = new ApiClient();
2891
+ try {
2892
+ const result = await routes.schema(client, resolvedAppId, documentId);
2893
+ const models = result?.modelNames ?? Object.keys(result?.schema?.models ?? {});
2894
+ if (options.json) {
2895
+ json(models);
2896
+ return;
2897
+ }
2898
+ if (models.length === 0) {
2899
+ info("No models found.");
2900
+ return;
2901
+ }
2902
+ for (const m of models) {
2903
+ console.log(` ${m}`);
2904
+ }
2905
+ }
2906
+ catch (err) {
2907
+ // #3764 — the server's sentence, the stable code and the status, so a
2908
+ // refused records call is scriptable rather than only readable.
2909
+ error(describeRecordsFailure(err));
2910
+ process.exit(1);
2911
+ }
2912
+ }
2913
+ /** `records describe` (shared with `db3 records describe`, #4804): one model's fields and indexes. */
2914
+ export async function describeAction(routes, documentId, modelName, options) {
2915
+ const resolvedAppId = resolveAppId(undefined, options);
2916
+ const client = new ApiClient();
2917
+ try {
2918
+ const result = await routes.schema(client, resolvedAppId, documentId);
2919
+ const model = result?.schema?.models?.[modelName];
2920
+ if (!model) {
2921
+ if (options.json) {
2922
+ json(null);
2923
+ return;
2924
+ }
2925
+ info(`Model '${modelName}' not found in this ${routes.noun}.`);
2926
+ return;
2927
+ }
2928
+ const fieldsObj = model.fields ?? {};
2929
+ const rows = Object.entries(fieldsObj).map(([name, meta]) => ({
2930
+ field: name,
2931
+ type: meta?.type ?? "unknown",
2932
+ indexed: meta?.indexed ? "yes" : "",
2933
+ unique: meta?.unique ? "yes" : "",
2934
+ required: meta?.required ? "yes" : "",
2935
+ }));
2936
+ if (options.json) {
2937
+ json({ fields: fieldsObj, constraints: model.constraints ?? {} });
2938
+ return;
2939
+ }
2940
+ if (rows.length === 0) {
2941
+ info("No fields detected for this model.");
2942
+ return;
2943
+ }
2944
+ console.log(formatTable(rows, [
2945
+ { header: "FIELD", key: "field", flex: true },
2946
+ { header: "TYPE", key: "type" },
2947
+ { header: "INDEXED", key: "indexed" },
2948
+ { header: "UNIQUE", key: "unique" },
2949
+ { header: "REQUIRED", key: "required" },
2950
+ ]));
2951
+ }
2952
+ catch (err) {
2953
+ // #3764 — the server's sentence, the stable code and the status, so a
2954
+ // refused records call is scriptable rather than only readable.
2955
+ error(describeRecordsFailure(err));
2956
+ process.exit(1);
2957
+ }
2958
+ }
2959
+ /** `stats` (shared with `db3 stats`, #4804): record, model and blob counts and the size. */
2960
+ export async function statsAction(routes, documentId, options) {
2961
+ const resolvedAppId = resolveAppId(undefined, options);
2962
+ const client = new ApiClient();
2963
+ try {
2964
+ const result = await routes.stats(client, resolvedAppId, documentId);
2965
+ if (options.json) {
2966
+ json(result);
2967
+ return;
2968
+ }
2969
+ keyValue(routes.noun === "db3" ? "db3 ID" : "Document ID", result.documentId);
2970
+ keyValue("Records", result.recordCount);
2971
+ keyValue("Models", result.modelCount);
2972
+ keyValue("Blobs", result.blobCount);
2973
+ // A large document's size is its records' stored JSON, exact; an
2974
+ // ordinary document's is an estimate (#4193).
2975
+ keyValue(result.sizeBasis === "records"
2976
+ ? "Size (bytes, records)"
2977
+ : "Size (bytes, approx)", result.sizeBytes);
2978
+ keyValue("Last modified", result.lastModifiedAt ? formatDate(result.lastModifiedAt) : "—");
2979
+ }
2980
+ catch (err) {
2981
+ error(describeDocumentFailure(err));
2982
+ process.exit(1);
2983
+ }
2984
+ }
2985
+ export async function schemaAction(routes, documentId, options) {
2986
+ if (options.output && !options.toml) {
2987
+ error("--output writes the TOML: pass --toml with it.");
2988
+ process.exit(1);
2989
+ }
2990
+ const resolvedAppId = resolveAppId(undefined, options);
2991
+ const client = new ApiClient();
2992
+ try {
2993
+ const answer = await routes.schema(client, resolvedAppId, documentId);
2994
+ if (options.json) {
2995
+ json(answer);
2996
+ return;
2997
+ }
2998
+ if (options.toml) {
2999
+ // Each field, constraint or model the export leaves out is one warn line.
3000
+ const toml = recordLogSchemaToToml(answer, { warn: (line) => warn(line) });
3001
+ if (options.output) {
3002
+ fs.writeFileSync(options.output, toml);
3003
+ success(`Wrote ${options.output}.`);
3004
+ return;
3005
+ }
3006
+ process.stdout.write(toml);
3007
+ return;
3008
+ }
3009
+ const rows = documentSchemaRows(answer);
3010
+ if (rows.length === 0) {
3011
+ info("No models found.");
3012
+ return;
3013
+ }
3014
+ console.log(formatTable(rows, [
3015
+ { key: "model", header: "Model" },
3016
+ { key: "field", header: "Field" },
3017
+ { key: "type", header: "Type" },
3018
+ { key: "kinds", header: "Kinds" },
3019
+ { key: "counts", header: "Counts" },
3020
+ { key: "hint", header: "Hint" },
3021
+ ]));
3022
+ }
3023
+ catch (err) {
3024
+ error(describeRecordsFailure(err));
3025
+ process.exit(1);
3026
+ }
3027
+ }
3028
+ /** `inspect`: the room's state, or every row a bulk load refused. */
3029
+ export async function inspectAction(routes, documentId, options) {
3030
+ const resolvedAppId = resolveAppId(undefined, options);
3031
+ const client = new ApiClient();
3032
+ try {
3033
+ if (options.refused !== undefined) {
3034
+ // Every page, in order: the room keeps each refused row with its code.
3035
+ const items = [];
3036
+ let cursor;
3037
+ do {
3038
+ const page = await routes.room(client, resolvedAppId, documentId, {
3039
+ refused: options.refused,
3040
+ limit: Number(options.limit),
3041
+ cursor,
3042
+ });
3043
+ items.push(...page.refused.items);
3044
+ cursor = page.refused.hasMore ? page.refused.nextCursor : undefined;
3045
+ } while (cursor);
3046
+ if (options.json) {
3047
+ json({ documentId, sessionId: options.refused, items });
3048
+ return;
3049
+ }
3050
+ keyValue("Document ID", documentId);
3051
+ keyValue("Session", options.refused);
3052
+ keyValue("Refused rows", items.length);
3053
+ for (const row of items)
3054
+ keyValue(...refusedRowLine(row));
3055
+ return;
3056
+ }
3057
+ const result = await routes.room(client, resolvedAppId, documentId);
3058
+ if (options.json) {
3059
+ json(result);
3060
+ return;
3061
+ }
3062
+ keyValue("Document ID", result.documentId);
3063
+ printDocumentFormat(result);
3064
+ const room = result.room;
3065
+ if (!room) {
3066
+ keyValue("Room", `no record room (format ${result.documentFormat ?? 1})`);
3067
+ return;
3068
+ }
3069
+ keyValue("Log number", room.lsn);
3070
+ keyValue("Epochs", `current ${room.epochs.current}, next ${room.epochs.next}, high ${room.epochs.high}`);
3071
+ keyValue("Epoch floor", room.epochs.floor);
3072
+ keyValue("Cursor floor", room.cursorFloor);
3073
+ keyValue("Entries since rotation", room.epochs.entriesSinceRotation);
3074
+ keyValue("Rotated", room.epochs.rotatedAt ? formatDate(room.epochs.rotatedAt) : "—");
3075
+ keyValue("Writers", `${room.writers.count} (${room.writers.connected} connected)`);
3076
+ keyValue("Subscribers", room.subscribers);
3077
+ keyValue("Held entries", room.held.entries);
3078
+ const load = room.load;
3079
+ keyValue("Load", load
3080
+ ? `${load.sessionId} ${load.state} (${load.mode}, epoch reserved at ${load.reserveEpoch}` +
3081
+ (load.epoch !== null ? `: epoch ${load.epoch} from log number ${load.k}` : "") +
3082
+ `), ${load.chunksApplied}/${load.chunks} chunks, ${load.rowsApplied} rows applied, ` +
3083
+ `${load.refusedRows} refused, ${load.touched} keys touched`
3084
+ : "none");
3085
+ const loads = Array.isArray(room.loads) ? room.loads : [];
3086
+ keyValue("Loads", loads.length
3087
+ ? loads
3088
+ .map((l) => `${l.sessionId} (${l.mode}, log numbers ${l.firstLsn ?? "—"}–${l.lastLsn ?? "—"}, ${l.rows} rows, ${l.touched} keys touched)`)
3089
+ .join("; ")
3090
+ : "none kept");
3091
+ const segmentLine = (s) => `${s.segmentId} ${s.state} (log number ${s.lsn}` +
3092
+ (s.completedLsn !== null && s.completedLsn !== undefined ? `, completed at ${s.completedLsn}` : "") +
3093
+ `, ${s.rows} rows, ${s.chunks} chunks)`;
3094
+ keyValue("Segment", room.segment ? segmentLine(room.segment) : "none");
3095
+ keyValue("Segment export", room.segmentExport ? segmentLine(room.segmentExport) : "none");
3096
+ keyValue("Last checkpoint", room.checkpoint
3097
+ ? `${formatDate(room.checkpoint.at)} (${room.checkpoint.durationMs} ms, ` +
3098
+ `${room.checkpoint.pruned} pruned, ${room.checkpoint.dropped} dropped, ` +
3099
+ `${room.checkpoint.writersDropped} writers dropped)`
3100
+ : "none yet");
3101
+ keyValue("Next alarm", room.nextAlarmAt ? formatDate(room.nextAlarmAt) : "—");
3102
+ keyValue("Storage (bytes)", room.storage?.databaseSize ?? "—");
3103
+ }
3104
+ catch (err) {
3105
+ error(describeDocumentFailure(err));
3106
+ process.exit(1);
3107
+ }
3108
+ }
3109
+ /**
3110
+ * `documents ingest` and `db3 ingest` (#4889): load a directory into a
3111
+ * document or a db3 through `routes`, confirming unless `-y`, then exit with
3112
+ * the load's code.
3113
+ */
3114
+ export async function ingestAction(routes, documentId, options) {
3115
+ const resolvedAppId = resolveAppId(undefined, options);
3116
+ const client = new ApiClient();
3117
+ let plan = null;
3118
+ // The exit code is carried out of here rather than taken inside: a
3119
+ // `process.exit` does not unwind, so ending the process in the try block
3120
+ // would skip the cleanup in the finally and leave the compressed
3121
+ // artifact — up to the whole input, gzipped — in the OS temp directory
3122
+ // on every run, successful or not (finding 3435-FROZEN-05).
3123
+ const run = async () => {
3124
+ // A flag's value is checked before any request.
3125
+ const flags = parseIngestFlags({ reserveEpoch: options.reserveEpoch, mode: options.mode });
3126
+ // The preflight, in this order and before a byte is read from disk:
3127
+ // the schema read says whether this caller may see the document's
3128
+ // declarations at all and hands over the ones the lines are checked
3129
+ // against, and the session reader says whether this is a large
3130
+ // document. Both are READS on the arm the ingest routes admit, so a
3131
+ // caller who would be refused halfway is refused at once, and neither
3132
+ // opens a session.
3133
+ const introspection = await routes.schema(client, resolvedAppId, documentId);
3134
+ await routes.listIngests(client, resolvedAppId, documentId, { limit: 1 });
3135
+ const schema = ingestSchemaFromIntrospection(introspection);
3136
+ // A record-log (format 3) document takes models and fields it does
3137
+ // not declare, as its writes do (#4310); its schema read says so.
3138
+ const recordLog = Number(introspection?.documentFormat) === 3;
3139
+ const input = discoverIngestInput(options.input, documentId);
3140
+ for (const ignored of input.ignored) {
3141
+ info(`Ignoring ${ignored}: a bulk load reads the snapshot only.`);
3142
+ }
3143
+ const body = ingestCreateBody(flags, input.sources.map((source) => source.model));
3144
+ // #3598 — reading, checking, sorting, cutting and gzipping is this
3145
+ // side's biggest phase on a large input, and it used to be invisible
3146
+ // inside one wall-clock number that also covered the platform's work.
3147
+ const buildStartedAt = Date.now();
3148
+ plan = await buildIngestArtifact({ input, schema, open: recordLog });
3149
+ const buildMs = Date.now() - buildStartedAt;
3150
+ info(`Built artifact in ${(buildMs / 1000).toFixed(1)}s.`);
3151
+ for (const line of summariseIngestPlan(plan))
3152
+ info(line);
3153
+ // A format-2 export's row that cannot be one record (#4638): left
3154
+ // out, and named, before anything is uploaded.
3155
+ for (const row of plan.refused) {
3156
+ warn(`Refused before upload: ${row.where}: ${row.reason}`);
3157
+ }
3158
+ assertIngestRefreshKeepsRefused(flags, plan.refused);
3159
+ assertIngestConfirmable({
3160
+ yes: Boolean(options.yes),
3161
+ isTTY: Boolean(process.stdin.isTTY),
3162
+ });
3163
+ if (!options.yes) {
3164
+ const confirmed = await confirmPrompt(`Bulk-load ${plan.rows} records into ${documentId}? ` +
3165
+ `This replaces records in a live ${routes.noun} and cannot be undone.`);
3166
+ if (!confirmed) {
3167
+ info("Nothing was uploaded.");
3168
+ return 1;
3169
+ }
3170
+ }
3171
+ // Ctrl-C is a decision the driver makes differently depending on
3172
+ // where it lands, so it is handed the signal rather than killing the
3173
+ // process: mid-upload the session is aborted, mid-poll it is left
3174
+ // running, because by then the document is already being changed.
3175
+ const interrupt = new AbortController();
3176
+ const onSignal = () => interrupt.abort();
3177
+ process.on("SIGINT", onSignal);
3178
+ let outcome;
3179
+ try {
3180
+ outcome = await driveDocumentIngest({
3181
+ client: {
3182
+ createIngest: (id) => routes.createIngest(client, resolvedAppId, id, body),
3183
+ uploadIngestChunk: (id, sessionId, chunk) => routes.uploadIngestChunk(client, resolvedAppId, id, sessionId, chunk),
3184
+ commitIngest: (id, sessionId) => routes.commitIngest(client, resolvedAppId, id, sessionId),
3185
+ abortIngest: (id, sessionId) => routes.abortIngest(client, resolvedAppId, id, sessionId),
3186
+ getIngest: (id, sessionId) => routes.getIngest(client, resolvedAppId, id, sessionId),
3187
+ },
3188
+ documentId,
3189
+ plan,
3190
+ wait: options.wait !== false,
3191
+ timeoutMs: options.timeout ? Number(options.timeout) * 1000 : null,
3192
+ signal: interrupt.signal,
3193
+ onProgress: (line) => info(line),
3194
+ });
3195
+ }
3196
+ finally {
3197
+ process.off("SIGINT", onSignal);
3198
+ }
3199
+ if (outcome.message)
3200
+ error(outcome.message);
3201
+ // #3598 — the two sides, side by side. The session's own `timings`
3202
+ // say where the platform's share went; `client` says what this
3203
+ // process spent before and around it, so a slow load can be blamed on
3204
+ // the side that was actually slow.
3205
+ const clientTimings = { buildMs, ...outcome.timings };
3206
+ if (options.json) {
3207
+ json({
3208
+ ...(outcome.session ?? { sessionId: outcome.sessionId }),
3209
+ client: clientTimings,
3210
+ refusedBeforeUpload: plan.refused,
3211
+ });
3212
+ }
3213
+ else {
3214
+ if (outcome.session) {
3215
+ printIngestSession(outcome.session);
3216
+ }
3217
+ else if (outcome.sessionId) {
3218
+ printResult("Session", outcome.sessionId);
3219
+ }
3220
+ for (const [label, value] of ingestClientRows(clientTimings)) {
3221
+ printResult(label, value);
3222
+ }
3223
+ }
3224
+ return outcome.exitCode;
3225
+ };
3226
+ let code = 1;
3227
+ try {
3228
+ code = await run();
3229
+ }
3230
+ catch (err) {
3231
+ error(describeDocumentFailure(err));
3232
+ code = 1;
3233
+ }
3234
+ finally {
3235
+ await plan?.cleanup().catch(() => undefined);
3236
+ }
3237
+ // The result has to reach the pipe before the process ends: stdout to a
3238
+ // pipe is asynchronous and `process.exit` does not wait for it.
3239
+ await flushOutput();
3240
+ process.exit(code);
3241
+ }
3242
+ /** `documents ingests list` and `db3 ingests list` (#4889). */
3243
+ export async function listIngestsAction(routes, documentId, options) {
3244
+ const limit = parsePageLimit(options.limit);
3245
+ const resolvedAppId = resolveAppId(undefined, options);
3246
+ const client = new ApiClient();
3247
+ try {
3248
+ const page = normalizeCliListEnvelope(await routes.listIngests(client, resolvedAppId, documentId, {
3249
+ limit,
3250
+ ...(options.cursor ? { cursor: options.cursor } : {}),
3251
+ }));
3252
+ if (options.json) {
3253
+ json(page);
3254
+ return;
3255
+ }
3256
+ if (page.items.length === 0) {
3257
+ info("No ingest sessions yet.");
3258
+ return;
3259
+ }
3260
+ console.log(formatTable(page.items, [
3261
+ { header: "SESSION", key: "sessionId" },
3262
+ { header: "STATE", key: "state" },
3263
+ { header: "CREATED", key: "createdAt", format: formatDate },
3264
+ { header: "CHUNKS", key: "chunks" },
3265
+ { header: "ROWS", key: "rows" },
3266
+ {
3267
+ header: "COMPLETED",
3268
+ key: "completedAt",
3269
+ format: (at) => (at ? formatDate(at) : "—"),
3270
+ },
3271
+ ]));
3272
+ if (page.hasMore && page.nextCursor) {
3273
+ info(`More sessions: --cursor ${page.nextCursor}`);
3274
+ }
3275
+ }
3276
+ catch (err) {
3277
+ error(describeDocumentFailure(err));
3278
+ process.exit(1);
3279
+ }
3280
+ }
3281
+ /** `documents ingests get` and `db3 ingests get` (#4889). */
3282
+ export async function getIngestAction(routes, documentId, sessionId, options) {
3283
+ const resolvedAppId = resolveAppId(undefined, options);
3284
+ const client = new ApiClient();
3285
+ try {
3286
+ const session = await routes.getIngest(client, resolvedAppId, documentId, sessionId);
3287
+ if (options.json) {
3288
+ json(session);
3289
+ return;
3290
+ }
3291
+ printIngestSession(session);
3292
+ }
3293
+ catch (err) {
3294
+ error(describeDocumentFailure(err));
3295
+ process.exit(1);
3296
+ }
3297
+ }
3298
+ /** `documents ingests abort` and `db3 ingests abort` (#4889). */
3299
+ export async function abortIngestAction(routes, documentId, sessionId, options) {
3300
+ const resolvedAppId = resolveAppId(undefined, options);
3301
+ if (!options.yes) {
3302
+ if (!process.stdin.isTTY) {
3303
+ error("Aborting a bulk load discards what it uploaded. " +
3304
+ "Re-run with -y to confirm it without a prompt.");
3305
+ process.exit(1);
3306
+ }
3307
+ const confirmed = await confirmPrompt(`Abort bulk load ${sessionId} on ${documentId}? What it uploaded is ` +
3308
+ "discarded; rows a committed load already applied stay.");
3309
+ if (!confirmed) {
3310
+ info("Cancelled.");
3311
+ return;
3312
+ }
3313
+ }
3314
+ const client = new ApiClient();
3315
+ try {
3316
+ const session = await routes.abortIngest(client, resolvedAppId, documentId, sessionId);
3317
+ if (options.json) {
3318
+ json(session);
3319
+ return;
3320
+ }
3321
+ printIngestSession(session);
3322
+ }
3323
+ catch (err) {
3324
+ error(describeDocumentFailure(err));
3325
+ process.exit(1);
3326
+ }
3327
+ }
3328
+ /** `documents snapshots list` and `db3 snapshots list` (#4889). */
3329
+ export async function listSnapshotsAction(routes, documentId, options) {
3330
+ const limit = parsePageLimit(options.limit);
3331
+ const resolvedAppId = resolveAppId(undefined, options);
3332
+ const client = new ApiClient();
3333
+ try {
3334
+ const page = normalizeCliListEnvelope(await routes.listSnapshots(client, resolvedAppId, documentId, {
3335
+ limit,
3336
+ ...(options.cursor ? { cursor: options.cursor } : {}),
3337
+ }));
3338
+ if (options.json) {
3339
+ json(page);
3340
+ return;
3341
+ }
3342
+ if (page.items.length === 0) {
3343
+ info("No snapshot builds yet.");
3344
+ return;
3345
+ }
3346
+ // A record-log (format 3) document's are its segments (#4310).
3347
+ if (page.items.some((item) => typeof item?.segmentId === "string")) {
3348
+ console.log(formatTable(page.items, [
3349
+ { header: "SEGMENT", key: "segmentId" },
3350
+ { header: "LOG NUMBER", key: "lsn" },
3351
+ { header: "COMPLETED AT LOG NUMBER", key: "completedLsn", format: (v) => (v === null || v === undefined ? "-" : String(v)) },
3352
+ { header: "STATE", key: "state" },
3353
+ { header: "ROWS", key: "rows" },
3354
+ { header: "CHUNKS", key: "chunks" },
3355
+ { header: "STARTED", key: "startedAt", format: formatDate },
3356
+ { header: "COMPLETED", key: "completedAt", format: formatDate },
3357
+ ]));
3358
+ return;
3359
+ }
3360
+ console.log(formatTable(page.items, [
3361
+ { header: "BUILD", key: "buildId" },
3362
+ { header: "EPOCH", key: "epoch" },
3363
+ { header: "STATE", key: "state" },
3364
+ { header: "SOURCE", key: "source" },
3365
+ {
3366
+ header: "VERIFICATION",
3367
+ key: "verification",
3368
+ format: (verification) => verification
3369
+ ? verification.code
3370
+ ? `${verification.state} (${verification.code})`
3371
+ : verification.state
3372
+ : "-",
3373
+ },
3374
+ { header: "ROWS", key: "rows" },
3375
+ { header: "CHUNKS", key: "chunks" },
3376
+ { header: "STARTED", key: "startedAt", format: formatDate },
3377
+ { header: "COMPLETED", key: "completedAt", format: formatDate },
3378
+ ]));
3379
+ if (page.hasMore && page.nextCursor) {
3380
+ info(`More builds: --cursor ${page.nextCursor}`);
3381
+ }
3382
+ }
3383
+ catch (err) {
3384
+ error(describeDocumentFailure(err));
3385
+ process.exit(1);
3386
+ }
3387
+ }
3388
+ /** `documents snapshots get` and `db3 snapshots get` (#4889). */
3389
+ export async function getSnapshotAction(routes, documentId, buildId, options) {
3390
+ const resolvedAppId = resolveAppId(undefined, options);
3391
+ const client = new ApiClient();
3392
+ try {
3393
+ const build = await routes.getSnapshot(client, resolvedAppId, documentId, buildId);
3394
+ if (options.json) {
3395
+ json(build);
3396
+ return;
3397
+ }
3398
+ // The rows are composed by a pure function (#3435), so what a
3399
+ // terminal shows is checkable without spawning one; the command still
3400
+ // owns the printing. A record-log document's build is a segment (#4310).
3401
+ const rows = typeof build?.segmentId === "string" ? segmentRows(build) : snapshotBuildRows(build);
3402
+ for (const [label, value] of rows) {
3403
+ printResult(label, value);
3404
+ }
3405
+ }
3406
+ catch (err) {
3407
+ error(describeDocumentFailure(err));
3408
+ process.exit(1);
3409
+ }
3410
+ }
3411
+ /** `documents snapshots build` and `db3 snapshots build` (#4889). */
3412
+ export async function buildSnapshotAction(routes, documentId, options) {
3413
+ const resolvedAppId = resolveAppId(undefined, options);
3414
+ const client = new ApiClient();
3415
+ const run = async () => {
3416
+ // Ctrl-C while polling leaves the build running — by then the room is
3417
+ // already building it and giving up on watching is not giving up on
3418
+ // the build — so the signal is handed to the driver rather than
3419
+ // killing the process.
3420
+ const interrupt = new AbortController();
3421
+ const onSignal = () => interrupt.abort();
3422
+ process.on("SIGINT", onSignal);
3423
+ let outcome;
3424
+ try {
3425
+ outcome = await driveSnapshotBuild({
3426
+ client: {
3427
+ requestSnapshot: (id) => routes.requestSnapshot(client, resolvedAppId, id),
3428
+ getSnapshot: (id, buildId) => routes.getSnapshot(client, resolvedAppId, id, buildId),
3429
+ },
3430
+ documentId,
3431
+ wait: Boolean(options.wait),
3432
+ timeoutMs: options.timeout ? Number(options.timeout) * 1000 : null,
3433
+ signal: interrupt.signal,
3434
+ onProgress: (line) => info(line),
3435
+ });
3436
+ }
3437
+ finally {
3438
+ process.off("SIGINT", onSignal);
3439
+ }
3440
+ if (outcome.message)
3441
+ error(outcome.message);
3442
+ if (options.json) {
3443
+ // The route's answer as received, with the build the wait settled
3444
+ // on beside it when there was one — so a script branches on the
3445
+ // verdict rather than on an exit code alone.
3446
+ json(outcome.build ? { ...outcome.response, build: outcome.build } : outcome.response);
3447
+ return outcome.exitCode;
3448
+ }
3449
+ if (typeof outcome.response?.segmentId === "string") {
3450
+ // A record-log document's segment export (#4310).
3451
+ if (outcome.build) {
3452
+ for (const [label, value] of segmentRows(outcome.build))
3453
+ printResult(label, value);
3454
+ }
3455
+ else {
3456
+ printResult("Segment", outcome.response.segmentId);
3457
+ printResult("State", outcome.response.state);
3458
+ printResult("Log number", outcome.response.lsn);
3459
+ }
3460
+ return outcome.exitCode;
3461
+ }
3462
+ printResult("Build", outcome.response?.buildId);
3463
+ return outcome.exitCode;
3464
+ };
3465
+ let code = 1;
3466
+ try {
3467
+ code = await run();
3468
+ }
3469
+ catch (err) {
3470
+ // The server's own sentence, plus the code a script branches on
3471
+ // (#3403) — a refused loop that only says "too young to seal" leaves
3472
+ // a caller parsing prose to tell it from a permission refusal.
3473
+ error(err.code ? `${err.message} (${err.code})` : err.message);
3474
+ const retryAfterMs = err.details?.retryAfterMs;
3475
+ if (typeof retryAfterMs === "number") {
3476
+ error(`Ask again in ${Math.ceil(retryAfterMs / 1000)}s.`);
3477
+ }
3478
+ code = 1;
3479
+ }
3480
+ // The result has to reach the pipe before the process ends: stdout to a
3481
+ // pipe is asynchronous and `process.exit` does not wait for it.
3482
+ await flushOutput();
3483
+ process.exit(code);
3484
+ }
3221
3485
  //# sourceMappingURL=documents.js.map