primitive-admin 1.1.0-alpha.6 → 1.1.0-alpha.61

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 (387) hide show
  1. package/README.md +389 -71
  2. package/assets/skill/skills/primitive-platform/SKILL.md +670 -0
  3. package/dist/bin/primitive.d.ts +2 -0
  4. package/dist/bin/primitive.js +287 -17
  5. package/dist/bin/primitive.js.map +1 -1
  6. package/dist/src/commands/admins.d.ts +2 -0
  7. package/dist/src/commands/admins.js +138 -19
  8. package/dist/src/commands/admins.js.map +1 -1
  9. package/dist/src/commands/analytics.d.ts +2 -0
  10. package/dist/src/commands/analytics.js +554 -55
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps.d.ts +2 -0
  13. package/dist/src/commands/apps.js +27 -80
  14. package/dist/src/commands/apps.js.map +1 -1
  15. package/dist/src/commands/auth.d.ts +2 -0
  16. package/dist/src/commands/auth.js +177 -7
  17. package/dist/src/commands/auth.js.map +1 -1
  18. package/dist/src/commands/blob-buckets.d.ts +2 -0
  19. package/dist/src/commands/blob-buckets.js +330 -0
  20. package/dist/src/commands/blob-buckets.js.map +1 -0
  21. package/dist/src/commands/catalog.d.ts +2 -0
  22. package/dist/src/commands/catalog.js +37 -38
  23. package/dist/src/commands/catalog.js.map +1 -1
  24. package/dist/src/commands/collection-type-configs.d.ts +2 -0
  25. package/dist/src/commands/collection-type-configs.js +92 -0
  26. package/dist/src/commands/collection-type-configs.js.map +1 -0
  27. package/dist/src/commands/collections.d.ts +2 -0
  28. package/dist/src/commands/collections.js +526 -0
  29. package/dist/src/commands/collections.js.map +1 -0
  30. package/dist/src/commands/comparisons.d.ts +2 -0
  31. package/dist/src/commands/comparisons.js +6 -6
  32. package/dist/src/commands/comparisons.js.map +1 -1
  33. package/dist/src/commands/config.d.ts +35 -0
  34. package/dist/src/commands/config.js +437 -0
  35. package/dist/src/commands/config.js.map +1 -0
  36. package/dist/src/commands/connections.d.ts +2 -0
  37. package/dist/src/commands/connections.js +100 -0
  38. package/dist/src/commands/connections.js.map +1 -0
  39. package/dist/src/commands/cron-triggers.d.ts +2 -0
  40. package/dist/src/commands/cron-triggers.js +204 -0
  41. package/dist/src/commands/cron-triggers.js.map +1 -0
  42. package/dist/src/commands/database-types.d.ts +2 -0
  43. package/dist/src/commands/database-types.js +171 -0
  44. package/dist/src/commands/database-types.js.map +1 -0
  45. package/dist/src/commands/databases.d.ts +65 -0
  46. package/dist/src/commands/databases.js +2153 -96
  47. package/dist/src/commands/databases.js.map +1 -1
  48. package/dist/src/commands/documents.d.ts +2 -0
  49. package/dist/src/commands/documents.js +1230 -19
  50. package/dist/src/commands/documents.js.map +1 -1
  51. package/dist/src/commands/email-templates.d.ts +2 -0
  52. package/dist/src/commands/email-templates.js +174 -0
  53. package/dist/src/commands/email-templates.js.map +1 -0
  54. package/dist/src/commands/env.d.ts +12 -0
  55. package/dist/src/commands/env.js +260 -0
  56. package/dist/src/commands/env.js.map +1 -0
  57. package/dist/src/commands/group-type-configs.d.ts +2 -0
  58. package/dist/src/commands/group-type-configs.js +86 -0
  59. package/dist/src/commands/group-type-configs.js.map +1 -0
  60. package/dist/src/commands/groups.d.ts +2 -0
  61. package/dist/src/commands/groups.js +38 -99
  62. package/dist/src/commands/groups.js.map +1 -1
  63. package/dist/src/commands/guides.d.ts +223 -0
  64. package/dist/src/commands/guides.js +617 -65
  65. package/dist/src/commands/guides.js.map +1 -1
  66. package/dist/src/commands/init.d.ts +17 -0
  67. package/dist/src/commands/init.js +964 -202
  68. package/dist/src/commands/init.js.map +1 -1
  69. package/dist/src/commands/integrations.d.ts +2 -0
  70. package/dist/src/commands/integrations.js +484 -205
  71. package/dist/src/commands/integrations.js.map +1 -1
  72. package/dist/src/commands/llm.d.ts +2 -0
  73. package/dist/src/commands/llm.js +13 -8
  74. package/dist/src/commands/llm.js.map +1 -1
  75. package/dist/src/commands/locks.d.ts +8 -0
  76. package/dist/src/commands/locks.js +160 -0
  77. package/dist/src/commands/locks.js.map +1 -0
  78. package/dist/src/commands/metadata.d.ts +2 -0
  79. package/dist/src/commands/metadata.js +406 -0
  80. package/dist/src/commands/metadata.js.map +1 -0
  81. package/dist/src/commands/prompts.d.ts +2 -0
  82. package/dist/src/commands/prompts.js +135 -355
  83. package/dist/src/commands/prompts.js.map +1 -1
  84. package/dist/src/commands/rule-sets.d.ts +3 -0
  85. package/dist/src/commands/rule-sets.js +271 -0
  86. package/dist/src/commands/rule-sets.js.map +1 -0
  87. package/dist/src/commands/scripts.d.ts +20 -0
  88. package/dist/src/commands/scripts.js +739 -0
  89. package/dist/src/commands/scripts.js.map +1 -0
  90. package/dist/src/commands/secrets.d.ts +2 -0
  91. package/dist/src/commands/secrets.js +108 -0
  92. package/dist/src/commands/secrets.js.map +1 -0
  93. package/dist/src/commands/sessions.d.ts +2 -0
  94. package/dist/src/commands/sessions.js +75 -0
  95. package/dist/src/commands/sessions.js.map +1 -0
  96. package/dist/src/commands/settings.d.ts +18 -0
  97. package/dist/src/commands/settings.js +54 -0
  98. package/dist/src/commands/settings.js.map +1 -0
  99. package/dist/src/commands/skill.d.ts +2 -0
  100. package/dist/src/commands/skill.js +29 -0
  101. package/dist/src/commands/skill.js.map +1 -0
  102. package/dist/src/commands/sync-app-settings.d.ts +125 -0
  103. package/dist/src/commands/sync-app-settings.js +380 -0
  104. package/dist/src/commands/sync-app-settings.js.map +1 -0
  105. package/dist/src/commands/sync.d.ts +958 -0
  106. package/dist/src/commands/sync.js +8954 -812
  107. package/dist/src/commands/sync.js.map +1 -1
  108. package/dist/src/commands/tokens.d.ts +2 -0
  109. package/dist/src/commands/tokens.js +130 -21
  110. package/dist/src/commands/tokens.js.map +1 -1
  111. package/dist/src/commands/users.d.ts +2 -0
  112. package/dist/src/commands/users.js +440 -22
  113. package/dist/src/commands/users.js.map +1 -1
  114. package/dist/src/commands/vars.d.ts +8 -0
  115. package/dist/src/commands/vars.js +96 -0
  116. package/dist/src/commands/vars.js.map +1 -0
  117. package/dist/src/commands/waitlist.d.ts +2 -0
  118. package/dist/src/commands/waitlist.js +10 -10
  119. package/dist/src/commands/waitlist.js.map +1 -1
  120. package/dist/src/commands/webhooks.d.ts +2 -0
  121. package/dist/src/commands/webhooks.js +442 -0
  122. package/dist/src/commands/webhooks.js.map +1 -0
  123. package/dist/src/commands/workflows.d.ts +94 -0
  124. package/dist/src/commands/workflows.js +1581 -448
  125. package/dist/src/commands/workflows.js.map +1 -1
  126. package/dist/src/lib/api-client.d.ts +1814 -0
  127. package/dist/src/lib/api-client.js +1655 -103
  128. package/dist/src/lib/api-client.js.map +1 -1
  129. package/dist/src/lib/app-settings-descriptor.d.ts +130 -0
  130. package/dist/src/lib/app-settings-descriptor.js +262 -0
  131. package/dist/src/lib/app-settings-descriptor.js.map +1 -0
  132. package/dist/src/lib/auth-flow.d.ts +8 -0
  133. package/dist/src/lib/batch.d.ts +26 -0
  134. package/dist/src/lib/batch.js +32 -0
  135. package/dist/src/lib/batch.js.map +1 -0
  136. package/dist/src/lib/block-layout.d.ts +160 -0
  137. package/dist/src/lib/block-layout.js +451 -0
  138. package/dist/src/lib/block-layout.js.map +1 -0
  139. package/dist/src/lib/canonical-json.d.ts +12 -0
  140. package/dist/src/lib/canonical-json.js +35 -0
  141. package/dist/src/lib/canonical-json.js.map +1 -0
  142. package/dist/src/lib/channel.d.ts +30 -0
  143. package/dist/src/lib/channel.js +68 -0
  144. package/dist/src/lib/channel.js.map +1 -0
  145. package/dist/src/lib/cli-manifest.d.ts +68 -0
  146. package/dist/src/lib/cli-manifest.js +71 -0
  147. package/dist/src/lib/cli-manifest.js.map +1 -0
  148. package/dist/src/lib/codegen-shared/generatedFiles.d.ts +97 -0
  149. package/dist/src/lib/codegen-shared/generatedFiles.js +184 -0
  150. package/dist/src/lib/codegen-shared/generatedFiles.js.map +1 -0
  151. package/dist/src/lib/codegen-shared/prettierStable.d.ts +262 -0
  152. package/dist/src/lib/codegen-shared/prettierStable.js +610 -0
  153. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -0
  154. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.d.ts +68 -0
  155. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js +168 -0
  156. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js.map +1 -0
  157. package/dist/src/lib/config-object-descriptor.d.ts +108 -0
  158. package/dist/src/lib/config-object-descriptor.js +607 -0
  159. package/dist/src/lib/config-object-descriptor.js.map +1 -0
  160. package/dist/src/lib/config-payload.d.ts +85 -0
  161. package/dist/src/lib/config-payload.js +105 -0
  162. package/dist/src/lib/config-payload.js.map +1 -0
  163. package/dist/src/lib/config-surface.d.ts +93 -0
  164. package/dist/src/lib/config-surface.js +178 -0
  165. package/dist/src/lib/config-surface.js.map +1 -0
  166. package/dist/src/lib/config-toml.d.ts +10 -0
  167. package/dist/src/lib/config-toml.js +42 -0
  168. package/dist/src/lib/config-toml.js.map +1 -0
  169. package/dist/src/lib/config.d.ts +53 -0
  170. package/dist/src/lib/config.js +92 -53
  171. package/dist/src/lib/config.js.map +1 -1
  172. package/dist/src/lib/confirm-prompt.d.ts +83 -0
  173. package/dist/src/lib/confirm-prompt.js +110 -0
  174. package/dist/src/lib/confirm-prompt.js.map +1 -0
  175. package/dist/src/lib/constants.d.ts +11 -0
  176. package/dist/src/lib/constants.js +12 -0
  177. package/dist/src/lib/constants.js.map +1 -0
  178. package/dist/src/lib/crash-handlers.d.ts +20 -0
  179. package/dist/src/lib/crash-handlers.js +49 -0
  180. package/dist/src/lib/crash-handlers.js.map +1 -0
  181. package/dist/src/lib/credentials-store.d.ts +89 -0
  182. package/dist/src/lib/credentials-store.js +330 -0
  183. package/dist/src/lib/credentials-store.js.map +1 -0
  184. package/dist/src/lib/csv.d.ts +47 -0
  185. package/dist/src/lib/csv.js +172 -0
  186. package/dist/src/lib/csv.js.map +1 -0
  187. package/dist/src/lib/data-input.d.ts +23 -0
  188. package/dist/src/lib/data-input.js +50 -0
  189. package/dist/src/lib/data-input.js.map +1 -0
  190. package/dist/src/lib/db-codegen/dbFingerprint.d.ts +10 -0
  191. package/dist/src/lib/db-codegen/dbFingerprint.js +17 -0
  192. package/dist/src/lib/db-codegen/dbFingerprint.js.map +1 -0
  193. package/dist/src/lib/db-codegen/dbGenerator.d.ts +67 -0
  194. package/dist/src/lib/db-codegen/dbGenerator.js +170 -0
  195. package/dist/src/lib/db-codegen/dbGenerator.js.map +1 -0
  196. package/dist/src/lib/db-codegen/dbNaming.d.ts +87 -0
  197. package/dist/src/lib/db-codegen/dbNaming.js +180 -0
  198. package/dist/src/lib/db-codegen/dbNaming.js.map +1 -0
  199. package/dist/src/lib/db-codegen/dbTemplates.d.ts +272 -0
  200. package/dist/src/lib/db-codegen/dbTemplates.js +480 -0
  201. package/dist/src/lib/db-codegen/dbTemplates.js.map +1 -0
  202. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +73 -0
  203. package/dist/src/lib/db-codegen/dbTsTypes.js +139 -0
  204. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -0
  205. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +146 -0
  206. package/dist/src/lib/db-codegen/dbTypeIR.js +517 -0
  207. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -0
  208. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.d.ts +112 -0
  209. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js +211 -0
  210. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js.map +1 -0
  211. package/dist/src/lib/env-resolver.d.ts +62 -0
  212. package/dist/src/lib/env-resolver.js +121 -0
  213. package/dist/src/lib/env-resolver.js.map +1 -0
  214. package/dist/src/lib/fetch.d.ts +5 -0
  215. package/dist/src/lib/generated-allowlist.d.ts +28 -0
  216. package/dist/src/lib/generated-allowlist.js +266 -0
  217. package/dist/src/lib/generated-allowlist.js.map +1 -0
  218. package/dist/src/lib/generated-config-surfaces.d.ts +578 -0
  219. package/dist/src/lib/generated-config-surfaces.js +3630 -0
  220. package/dist/src/lib/generated-config-surfaces.js.map +1 -0
  221. package/dist/src/lib/generated-template-lint.d.ts +206 -0
  222. package/dist/src/lib/generated-template-lint.js +589 -0
  223. package/dist/src/lib/generated-template-lint.js.map +1 -0
  224. package/dist/src/lib/generated-workflow-model-fields.d.ts +20 -0
  225. package/dist/src/lib/generated-workflow-model-fields.js +53 -0
  226. package/dist/src/lib/generated-workflow-model-fields.js.map +1 -0
  227. package/dist/src/lib/google-client-secret-status.d.ts +35 -0
  228. package/dist/src/lib/google-client-secret-status.js +56 -0
  229. package/dist/src/lib/google-client-secret-status.js.map +1 -0
  230. package/dist/src/lib/init-config.d.ts +81 -0
  231. package/dist/src/lib/init-config.js +149 -0
  232. package/dist/src/lib/init-config.js.map +1 -0
  233. package/dist/src/lib/log-inspection.d.ts +568 -0
  234. package/dist/src/lib/log-inspection.js +639 -0
  235. package/dist/src/lib/log-inspection.js.map +1 -0
  236. package/dist/src/lib/migration-nag.d.ts +49 -0
  237. package/dist/src/lib/migration-nag.js +163 -0
  238. package/dist/src/lib/migration-nag.js.map +1 -0
  239. package/dist/src/lib/output.d.ts +109 -0
  240. package/dist/src/lib/output.js +191 -8
  241. package/dist/src/lib/output.js.map +1 -1
  242. package/dist/src/lib/package-manager.d.ts +140 -0
  243. package/dist/src/lib/package-manager.js +305 -0
  244. package/dist/src/lib/package-manager.js.map +1 -0
  245. package/dist/src/lib/paginate.d.ts +83 -0
  246. package/dist/src/lib/paginate.js +95 -0
  247. package/dist/src/lib/paginate.js.map +1 -0
  248. package/dist/src/lib/platform-owned.d.ts +51 -0
  249. package/dist/src/lib/platform-owned.js +64 -0
  250. package/dist/src/lib/platform-owned.js.map +1 -0
  251. package/dist/src/lib/project-config.d.ts +97 -0
  252. package/dist/src/lib/project-config.js +219 -0
  253. package/dist/src/lib/project-config.js.map +1 -0
  254. package/dist/src/lib/query-operators.d.ts +43 -0
  255. package/dist/src/lib/query-operators.js +80 -0
  256. package/dist/src/lib/query-operators.js.map +1 -0
  257. package/dist/src/lib/record-filter.d.ts +18 -0
  258. package/dist/src/lib/record-filter.js +55 -0
  259. package/dist/src/lib/record-filter.js.map +1 -0
  260. package/dist/src/lib/refresh-admin-credentials.d.ts +65 -0
  261. package/dist/src/lib/refresh-admin-credentials.js +103 -0
  262. package/dist/src/lib/refresh-admin-credentials.js.map +1 -0
  263. package/dist/src/lib/resolve-init-dev-port.d.ts +56 -0
  264. package/dist/src/lib/resolve-init-dev-port.js +55 -0
  265. package/dist/src/lib/resolve-init-dev-port.js.map +1 -0
  266. package/dist/src/lib/resolve-init-server.d.ts +71 -0
  267. package/dist/src/lib/resolve-init-server.js +94 -0
  268. package/dist/src/lib/resolve-init-server.js.map +1 -0
  269. package/dist/src/lib/resolve-platform.d.ts +45 -0
  270. package/dist/src/lib/resolve-platform.js +43 -0
  271. package/dist/src/lib/resolve-platform.js.map +1 -0
  272. package/dist/src/lib/run-status.d.ts +19 -0
  273. package/dist/src/lib/run-status.generated.d.ts +39 -0
  274. package/dist/src/lib/run-status.generated.js +66 -0
  275. package/dist/src/lib/run-status.generated.js.map +1 -0
  276. package/dist/src/lib/run-status.js +19 -0
  277. package/dist/src/lib/run-status.js.map +1 -0
  278. package/dist/src/lib/signing-secret-status.d.ts +81 -0
  279. package/dist/src/lib/signing-secret-status.js +116 -0
  280. package/dist/src/lib/signing-secret-status.js.map +1 -0
  281. package/dist/src/lib/skill-installer.d.ts +25 -0
  282. package/dist/src/lib/skill-installer.js +266 -0
  283. package/dist/src/lib/skill-installer.js.map +1 -0
  284. package/dist/src/lib/snapshots.d.ts +99 -0
  285. package/dist/src/lib/snapshots.js +357 -0
  286. package/dist/src/lib/snapshots.js.map +1 -0
  287. package/dist/src/lib/swift-codegen/dbGenerator.d.ts +100 -0
  288. package/dist/src/lib/swift-codegen/dbGenerator.js +682 -0
  289. package/dist/src/lib/swift-codegen/dbGenerator.js.map +1 -0
  290. package/dist/src/lib/swift-codegen/dbSwiftTypes.d.ts +42 -0
  291. package/dist/src/lib/swift-codegen/dbSwiftTypes.js +100 -0
  292. package/dist/src/lib/swift-codegen/dbSwiftTypes.js.map +1 -0
  293. package/dist/src/lib/swift-codegen/generator.d.ts +85 -0
  294. package/dist/src/lib/swift-codegen/generator.js +266 -0
  295. package/dist/src/lib/swift-codegen/generator.js.map +1 -0
  296. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +72 -0
  297. package/dist/src/lib/swift-codegen/schemaToSwift.js +644 -0
  298. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -0
  299. package/dist/src/lib/swift-codegen/siblingSymbols.d.ts +90 -0
  300. package/dist/src/lib/swift-codegen/siblingSymbols.js +152 -0
  301. package/dist/src/lib/swift-codegen/siblingSymbols.js.map +1 -0
  302. package/dist/src/lib/swift-codegen/swiftNaming.d.ts +85 -0
  303. package/dist/src/lib/swift-codegen/swiftNaming.js +198 -0
  304. package/dist/src/lib/swift-codegen/swiftNaming.js.map +1 -0
  305. package/dist/src/lib/sync-paths.d.ts +72 -0
  306. package/dist/src/lib/sync-paths.js +130 -0
  307. package/dist/src/lib/sync-paths.js.map +1 -0
  308. package/dist/src/lib/sync-resource-types.d.ts +445 -0
  309. package/dist/src/lib/sync-resource-types.js +812 -0
  310. package/dist/src/lib/sync-resource-types.js.map +1 -0
  311. package/dist/src/lib/sync-selectors.d.ts +95 -0
  312. package/dist/src/lib/sync-selectors.js +228 -0
  313. package/dist/src/lib/sync-selectors.js.map +1 -0
  314. package/dist/src/lib/template.d.ts +121 -0
  315. package/dist/src/lib/template.js +447 -67
  316. package/dist/src/lib/template.js.map +1 -1
  317. package/dist/src/lib/token-inject.d.ts +56 -0
  318. package/dist/src/lib/token-inject.js +204 -0
  319. package/dist/src/lib/token-inject.js.map +1 -0
  320. package/dist/src/lib/toml-database-config.d.ts +123 -0
  321. package/dist/src/lib/toml-database-config.js +527 -0
  322. package/dist/src/lib/toml-database-config.js.map +1 -0
  323. package/dist/src/lib/toml-metadata-config.d.ts +151 -0
  324. package/dist/src/lib/toml-metadata-config.js +476 -0
  325. package/dist/src/lib/toml-metadata-config.js.map +1 -0
  326. package/dist/src/lib/toml-native-form.d.ts +46 -0
  327. package/dist/src/lib/toml-native-form.js +78 -0
  328. package/dist/src/lib/toml-native-form.js.map +1 -0
  329. package/dist/src/lib/toml-params-validator.d.ts +129 -0
  330. package/dist/src/lib/toml-params-validator.js +298 -0
  331. package/dist/src/lib/toml-params-validator.js.map +1 -0
  332. package/dist/src/lib/toml-scalar-edit.d.ts +43 -0
  333. package/dist/src/lib/toml-scalar-edit.js +283 -0
  334. package/dist/src/lib/toml-scalar-edit.js.map +1 -0
  335. package/dist/src/lib/user-selector.d.ts +24 -0
  336. package/dist/src/lib/user-selector.js +33 -0
  337. package/dist/src/lib/user-selector.js.map +1 -0
  338. package/dist/src/lib/version-check.d.ts +35 -0
  339. package/dist/src/lib/version-check.js +241 -0
  340. package/dist/src/lib/version-check.js.map +1 -0
  341. package/dist/src/lib/watch.d.ts +121 -0
  342. package/dist/src/lib/watch.js +169 -0
  343. package/dist/src/lib/watch.js.map +1 -0
  344. package/dist/src/lib/workflow-apply.d.ts +51 -0
  345. package/dist/src/lib/workflow-apply.js +89 -0
  346. package/dist/src/lib/workflow-apply.js.map +1 -0
  347. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.d.ts +129 -0
  348. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js +269 -0
  349. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js.map +1 -0
  350. package/dist/src/lib/workflow-codegen/generator.d.ts +96 -0
  351. package/dist/src/lib/workflow-codegen/generator.js +361 -0
  352. package/dist/src/lib/workflow-codegen/generator.js.map +1 -0
  353. package/dist/src/lib/workflow-codegen/invokerIR.d.ts +83 -0
  354. package/dist/src/lib/workflow-codegen/invokerIR.js +71 -0
  355. package/dist/src/lib/workflow-codegen/invokerIR.js.map +1 -0
  356. package/dist/src/lib/workflow-codegen/naming.d.ts +33 -0
  357. package/dist/src/lib/workflow-codegen/naming.js +81 -0
  358. package/dist/src/lib/workflow-codegen/naming.js.map +1 -0
  359. package/dist/src/lib/workflow-codegen/schemaToTs.d.ts +80 -0
  360. package/dist/src/lib/workflow-codegen/schemaToTs.js +303 -0
  361. package/dist/src/lib/workflow-codegen/schemaToTs.js.map +1 -0
  362. package/dist/src/lib/workflow-config-apply.d.ts +70 -0
  363. package/dist/src/lib/workflow-config-apply.js +137 -0
  364. package/dist/src/lib/workflow-config-apply.js.map +1 -0
  365. package/dist/src/lib/workflow-config-sidecar.d.ts +63 -0
  366. package/dist/src/lib/workflow-config-sidecar.js +96 -0
  367. package/dist/src/lib/workflow-config-sidecar.js.map +1 -0
  368. package/dist/src/lib/workflow-field-descriptor.d.ts +91 -0
  369. package/dist/src/lib/workflow-field-descriptor.js +153 -0
  370. package/dist/src/lib/workflow-field-descriptor.js.map +1 -0
  371. package/dist/src/lib/workflow-fragments.d.ts +64 -0
  372. package/dist/src/lib/workflow-fragments.js +342 -0
  373. package/dist/src/lib/workflow-fragments.js.map +1 -0
  374. package/dist/src/lib/workflow-include-preserve.d.ts +71 -0
  375. package/dist/src/lib/workflow-include-preserve.js +153 -0
  376. package/dist/src/lib/workflow-include-preserve.js.map +1 -0
  377. package/dist/src/lib/workflow-payload.d.ts +86 -0
  378. package/dist/src/lib/workflow-payload.js +168 -0
  379. package/dist/src/lib/workflow-payload.js.map +1 -0
  380. package/dist/src/lib/workflow-toml-validator.d.ts +199 -0
  381. package/dist/src/lib/workflow-toml-validator.js +754 -0
  382. package/dist/src/lib/workflow-toml-validator.js.map +1 -0
  383. package/dist/src/types/index.d.ts +533 -0
  384. package/dist/src/validators.d.ts +65 -0
  385. package/dist/src/validators.js +64 -0
  386. package/dist/src/validators.js.map +1 -0
  387. package/package.json +32 -6
@@ -1,25 +1,206 @@
1
1
  import { loadCredentials, saveCredentials, isTokenExpiringSoon, } from "./config.js";
2
2
  import { fetchWithTLS } from "./fetch.js";
3
+ import { paginateAll, normalizeCliListEnvelope } from "./paginate.js";
4
+ import { RefreshError, refreshAdminCredentials, } from "./refresh-admin-credentials.js";
3
5
  export class ApiError extends Error {
4
6
  statusCode;
5
7
  code;
6
- constructor(message, statusCode, code) {
8
+ /**
9
+ * Structured `details` payload from `corsErrorResponse`.
10
+ *
11
+ * The server's error envelope can emit `details` as either:
12
+ * - an array of validation issues (e.g. `[{ path, message }, ...]`) —
13
+ * this is what most legacy endpoints produce, and what sync.ts walks
14
+ * via `Array.isArray(err.details)` / `for (const detail of ...)`.
15
+ * - a record of structured offender fields (e.g. `{ refs, operations,
16
+ * opCount, line, column, ... }`) — emitted by the issue #666 schema
17
+ * gate and consumed by the typed exception subclasses below.
18
+ *
19
+ * Callers must narrow before use: `Array.isArray(err.details)` for the
20
+ * legacy shape, otherwise treat as `Record<string, any>`.
21
+ */
22
+ details;
23
+ constructor(message, statusCode, code, details) {
7
24
  super(message);
8
25
  this.statusCode = statusCode;
9
26
  this.code = code;
10
27
  this.name = "ApiError";
28
+ if (details !== undefined) {
29
+ this.details = details;
30
+ }
11
31
  }
12
32
  }
13
33
  export class ConflictError extends ApiError {
14
34
  serverModifiedAt;
15
35
  expectedModifiedAt;
16
- constructor(message, serverModifiedAt, expectedModifiedAt) {
17
- super(message, 409, "CONFLICT");
36
+ constructor(message, serverModifiedAt, expectedModifiedAt, details) {
37
+ super(message, 409, "CONFLICT", details);
18
38
  this.serverModifiedAt = serverModifiedAt;
19
39
  this.expectedModifiedAt = expectedModifiedAt;
20
40
  this.name = "ConflictError";
21
41
  }
22
42
  }
43
+ /**
44
+ * Extract a human-readable error message + structured fields from a non-OK
45
+ * HTTP response body. Single source of truth used by every error-handler call
46
+ * site in this file (see issue #684).
47
+ */
48
+ export function parseErrorResponse(response, text, path) {
49
+ // Empty body → fall back to status code.
50
+ if (!text) {
51
+ return { message: `HTTP ${response.status}` };
52
+ }
53
+ let errorData;
54
+ try {
55
+ errorData = JSON.parse(text);
56
+ }
57
+ catch {
58
+ // Non-JSON body. Surface the existing `<!DOCTYPE` special-case (an HTML
59
+ // 404 page from hitting the wrong path) so we don't regress the helpful
60
+ // "API endpoint not found" message at api-client.ts:343.
61
+ if (text.includes("<!DOCTYPE")) {
62
+ const where = path ? `: ${path}` : "";
63
+ return {
64
+ message: `API endpoint not found${where}. Make sure the server is running.`,
65
+ htmlNotFound: true,
66
+ };
67
+ }
68
+ // Other non-JSON bodies (e.g. plain-text 502 from a proxy) — surface the
69
+ // raw text so the operator at least sees what the server returned.
70
+ return { message: text };
71
+ }
72
+ // Server's standard envelope uses `error`; ConflictError + integrations
73
+ // proxy use `message`. Prefer `error` (more common), fall back to `message`.
74
+ const message = (typeof errorData?.error === "string" && errorData.error) ||
75
+ (typeof errorData?.message === "string" && errorData.message) ||
76
+ `HTTP ${response.status}`;
77
+ // Per issue #666 addendum A1, `code` may be at the top level or nested
78
+ // under `details.code` when the server's bespoke envelope didn't flatten.
79
+ const code = (typeof errorData?.code === "string" ? errorData.code : undefined) ??
80
+ (typeof errorData?.details?.code === "string"
81
+ ? errorData.details.code
82
+ : undefined);
83
+ // Accept either an array (legacy) or a plain object (#666 schema gate).
84
+ const details = Array.isArray(errorData?.details)
85
+ ? errorData.details
86
+ : errorData?.details && typeof errorData.details === "object"
87
+ ? errorData.details
88
+ : undefined;
89
+ return { message, code, details, raw: errorData };
90
+ }
91
+ /**
92
+ * Typed exception classes for the database-schema feature (issue #666).
93
+ * Each maps 1:1 to a server `code` value emitted from the op-edit or
94
+ * schema-edit gate. They all extend ApiError so existing catch-all paths
95
+ * continue to work; specialized catch blocks can branch on `instanceof`.
96
+ *
97
+ * Per round-2 addendum A1, `details` is always preserved so callers can
98
+ * extract structured offender lists (refs[], operations[], etc.).
99
+ */
100
+ export class SchemaRequiredError extends ApiError {
101
+ constructor(message, details) {
102
+ super(message, 422, "SCHEMA_REQUIRED", details);
103
+ this.name = "SchemaRequiredError";
104
+ }
105
+ }
106
+ function detailsRecord(details) {
107
+ return details && !Array.isArray(details) && typeof details === "object"
108
+ ? details
109
+ : undefined;
110
+ }
111
+ export class OperationRefError extends ApiError {
112
+ constructor(message, details) {
113
+ super(message, 422, "OPERATION_REFERENCES_UNDEFINED", details);
114
+ this.name = "OperationRefError";
115
+ }
116
+ get refs() {
117
+ const d = detailsRecord(this.details);
118
+ return Array.isArray(d?.refs) ? d.refs : [];
119
+ }
120
+ }
121
+ export class SchemaBreaksOpsError extends ApiError {
122
+ constructor(message, details) {
123
+ super(message, 422, "SCHEMA_BREAKS_OPERATIONS", details);
124
+ this.name = "SchemaBreaksOpsError";
125
+ }
126
+ get operations() {
127
+ const d = detailsRecord(this.details);
128
+ return Array.isArray(d?.operations) ? d.operations : [];
129
+ }
130
+ }
131
+ export class SchemaHasUncheckableOpsError extends ApiError {
132
+ constructor(message, details) {
133
+ super(message, 422, "SCHEMA_HAS_UNCHECKABLE_OPS", details);
134
+ this.name = "SchemaHasUncheckableOpsError";
135
+ }
136
+ get operations() {
137
+ const d = detailsRecord(this.details);
138
+ return Array.isArray(d?.operations) ? d.operations : [];
139
+ }
140
+ }
141
+ export class TomlParseError extends ApiError {
142
+ constructor(message, details) {
143
+ super(message, 400, "TOML_PARSE_ERROR", details);
144
+ this.name = "TomlParseError";
145
+ }
146
+ get line() {
147
+ const d = detailsRecord(this.details);
148
+ return typeof d?.line === "number" ? d.line : undefined;
149
+ }
150
+ get column() {
151
+ const d = detailsRecord(this.details);
152
+ return typeof d?.column === "number" ? d.column : undefined;
153
+ }
154
+ }
155
+ export class OpsExistError extends ApiError {
156
+ constructor(message, details) {
157
+ super(message, 409, "OPS_EXIST", details);
158
+ this.name = "OpsExistError";
159
+ }
160
+ get opCount() {
161
+ const d = detailsRecord(this.details);
162
+ return typeof d?.opCount === "number" ? d.opCount : 0;
163
+ }
164
+ }
165
+ /**
166
+ * Normalize a `databases operations execute` result to the CLI's one list
167
+ * envelope — but only when the result is a Durable Object query page
168
+ * (issue #2440).
169
+ *
170
+ * A registered operation is a list only sometimes. Of the shapes the server's
171
+ * operation dispatch can return, exactly two carry a top-level `data` array: a
172
+ * bare `query` and a `pipeline` whose `returnField` names a query step. A
173
+ * `count` (`{ count }`), an `aggregate` (`{ result }`), a mutation
174
+ * (`{ results }`), an `applyToQuery` (`{ matched, affected, failed, … }`) and a
175
+ * `returnField: "all"` pipeline (`{ steps: { … } }`) do not, so blanket
176
+ * normalization would corrupt them. This helper therefore tests the shape
177
+ * first and passes everything else through byte-for-byte — including the
178
+ * nested steps of a `returnField: "all"` pipeline, which are operation-defined
179
+ * objects the CLI must not reach into.
180
+ *
181
+ * Deliberately narrow, not a general-purpose predicate: the contract is
182
+ * specifically "an operations-execute result may be a DO query page".
183
+ * `executeDatabaseOperation()` is the only caller.
184
+ *
185
+ * The conversion itself is delegated to `normalizeCliListEnvelope()` so cursor
186
+ * handling, `prevCursor` dropping and `hasMore` derivation have exactly one
187
+ * implementation. That helper throws on an unrecognized shape — correct when
188
+ * the payload is supposed to be a list, wrong here, where the payload is the
189
+ * caller's own result — which is why the shape test has to run first. `_timing`
190
+ * (`--timing`) is re-attached afterwards, since it rides alongside the envelope
191
+ * rather than inside it.
192
+ */
193
+ export function normalizeDatabaseOperationResult(raw) {
194
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
195
+ return raw;
196
+ const page = raw;
197
+ if (!Array.isArray(page.data))
198
+ return raw;
199
+ const envelope = normalizeCliListEnvelope(page);
200
+ if (page._timing !== undefined)
201
+ envelope._timing = page._timing;
202
+ return envelope;
203
+ }
23
204
  export class ApiClient {
24
205
  credentials = null;
25
206
  constructor() {
@@ -39,39 +220,24 @@ export class ApiClient {
39
220
  return this.credentials;
40
221
  }
41
222
  async refreshToken() {
42
- if (!this.credentials?.refreshToken) {
43
- throw new ApiError("No refresh token available. Please login again.", 401);
223
+ if (!this.credentials) {
224
+ throw new ApiError("Not logged in. Run 'primitive login' first.", 401);
44
225
  }
45
- const url = `${this.credentials.serverUrl}/admin/api/auth/refresh`;
46
226
  try {
47
- const headers = {
48
- "Content-Type": "application/json",
49
- };
50
- if (this.credentials.globalAdminAppId) {
51
- headers["X-Global-Admin-App-Id"] = this.credentials.globalAdminAppId;
52
- }
53
- const response = await fetchWithTLS(url, {
54
- method: "POST",
55
- headers,
56
- body: JSON.stringify({ refreshToken: this.credentials.refreshToken }),
57
- });
58
- if (!response.ok) {
59
- throw new ApiError("Token refresh failed. Please login again.", 401);
60
- }
61
- const data = await response.json();
62
- // Update credentials with new tokens
63
- this.credentials = {
64
- ...this.credentials,
65
- accessToken: data.accessToken || data.token,
66
- refreshToken: data.refreshToken || this.credentials.refreshToken,
67
- expiresAt: data.expiresAt,
68
- };
227
+ const updated = await refreshAdminCredentials(this.credentials);
228
+ this.credentials = updated;
69
229
  saveCredentials(this.credentials);
70
230
  }
71
- catch (error) {
72
- if (error instanceof ApiError)
73
- throw error;
74
- throw new ApiError("Token refresh failed. Please login again.", 401);
231
+ catch (err) {
232
+ if (err instanceof RefreshError) {
233
+ // Preserve historical behavior: ApiClient surfaces refresh failures
234
+ // as 401s regardless of whether the underlying cause was a network
235
+ // error or a server-side rejection. Callers that need a finer
236
+ // distinction (e.g. `primitive token`) consume RefreshError directly
237
+ // from refresh-admin-credentials.ts instead of going through here.
238
+ throw new ApiError("Token refresh failed. Please login again.", 401);
239
+ }
240
+ throw err;
75
241
  }
76
242
  }
77
243
  async request(path, options = {}) {
@@ -92,20 +258,42 @@ export class ApiClient {
92
258
  });
93
259
  const text = await response.text();
94
260
  if (!response.ok) {
95
- let errorData;
96
- try {
97
- errorData = JSON.parse(text);
261
+ const parsed = parseErrorResponse(response, text, path);
262
+ // Preserve the `<!DOCTYPE` → 404 ApiError shape (status forced to 404).
263
+ if (parsed.htmlNotFound) {
264
+ throw new ApiError(parsed.message, 404);
98
265
  }
99
- catch {
100
- if (text.includes("<!DOCTYPE")) {
101
- throw new ApiError(`API endpoint not found: ${path}. Make sure the server is running.`, 404);
102
- }
103
- errorData = { message: text || `HTTP ${response.status}` };
266
+ // Narrow details to the record shape for the issue #666 typed-exception
267
+ // dispatch below. Conflict metadata may live under `details.*` (canonical
268
+ // location per A1) or on the top-level envelope (legacy).
269
+ const detailsRecord = parsed.details && !Array.isArray(parsed.details)
270
+ ? parsed.details
271
+ : undefined;
272
+ const serverModifiedAt = detailsRecord?.serverModifiedAt ?? parsed.raw?.serverModifiedAt;
273
+ const expectedModifiedAt = detailsRecord?.expectedModifiedAt ?? parsed.raw?.expectedModifiedAt;
274
+ // Typed exceptions for the schema-feature (issue #666).
275
+ if (response.status === 409 && parsed.code === "CONFLICT") {
276
+ throw new ConflictError(parsed.message, serverModifiedAt, expectedModifiedAt, detailsRecord);
277
+ }
278
+ if (response.status === 409 && parsed.code === "OPS_EXIST") {
279
+ throw new OpsExistError(parsed.message, detailsRecord);
280
+ }
281
+ if (response.status === 400 && parsed.code === "TOML_PARSE_ERROR") {
282
+ throw new TomlParseError(parsed.message, detailsRecord);
283
+ }
284
+ if (response.status === 422 && parsed.code === "SCHEMA_REQUIRED") {
285
+ throw new SchemaRequiredError(parsed.message, detailsRecord);
104
286
  }
105
- if (response.status === 409 && errorData?.code === "CONFLICT") {
106
- throw new ConflictError(errorData.message || "Resource conflict", errorData.serverModifiedAt, errorData.expectedModifiedAt);
287
+ if (response.status === 422 && parsed.code === "OPERATION_REFERENCES_UNDEFINED") {
288
+ throw new OperationRefError(parsed.message, detailsRecord);
107
289
  }
108
- throw new ApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.code);
290
+ if (response.status === 422 && parsed.code === "SCHEMA_BREAKS_OPERATIONS") {
291
+ throw new SchemaBreaksOpsError(parsed.message, detailsRecord);
292
+ }
293
+ if (response.status === 422 && parsed.code === "SCHEMA_HAS_UNCHECKABLE_OPS") {
294
+ throw new SchemaHasUncheckableOpsError(parsed.message, detailsRecord);
295
+ }
296
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
109
297
  }
110
298
  return text ? JSON.parse(text) : null;
111
299
  }
@@ -155,7 +343,25 @@ export class ApiClient {
155
343
  // APPS
156
344
  // ============================================
157
345
  async listApps() {
158
- return this.get("/admin/api/admins/me/apps");
346
+ // The server paginates cursor-style (default pageSize=25, cap=100). Historically
347
+ // this method issued a single un-paginated GET and silently truncated to the
348
+ // first page, which broke `primitive use <app-id>` and `primitive apps list`
349
+ // for admins with more than 25 apps (see #436). Iterate every page.
350
+ const apps = await paginateAll(async (cursor) => {
351
+ const qs = new URLSearchParams({ limit: "100" });
352
+ if (cursor)
353
+ qs.set("cursor", cursor);
354
+ const resp = await this.get(`/admin/api/admins/me/apps?${qs.toString()}`);
355
+ // The server now emits `items` with `apps` as a deprecation-window
356
+ // alias (#1316). Read `items` first so listings keep working once the
357
+ // alias is removed; fall back to the legacy `apps` key meanwhile.
358
+ return {
359
+ items: resp.items ??
360
+ (Array.isArray(resp.apps) ? resp.apps : []),
361
+ nextCursor: resp.nextCursor ?? resp.cursor,
362
+ };
363
+ });
364
+ return { apps };
159
365
  }
160
366
  async createApp(data) {
161
367
  return this.post("/admin/api/apps", data);
@@ -181,8 +387,32 @@ export class ApiClient {
181
387
  async addUserByEmail(appId, data) {
182
388
  return this.post(`/admin/api/apps/${appId}/users/add-by-email`, data);
183
389
  }
184
- async listUsers(appId) {
185
- return this.get(`/app/${appId}/api/users`);
390
+ async mintTestJwt(appId, userId, role) {
391
+ return this.post(`/admin/api/apps/${appId}/users/${userId}/mint-test-jwt`, role ? { role } : {});
392
+ }
393
+ async rebuildUserSearchText(appId) {
394
+ return this.post(`/admin/api/apps/${appId}/users/rebuild-search-text`, {});
395
+ }
396
+ async listUsers(appId, params) {
397
+ const query = new URLSearchParams();
398
+ if (params?.name)
399
+ query.set("name", params.name);
400
+ if (params?.email)
401
+ query.set("email", params.email);
402
+ if (params?.userId)
403
+ query.set("userId", params.userId);
404
+ if (params?.limit)
405
+ query.set("limit", String(params.limit));
406
+ if (params?.cursor)
407
+ query.set("cursor", params.cursor);
408
+ const path = query.toString()
409
+ ? `/app/${appId}/api/users?${query.toString()}`
410
+ : `/app/${appId}/api/users`;
411
+ const result = await this.get(path);
412
+ return {
413
+ items: result?.items ?? (Array.isArray(result) ? result : []),
414
+ nextCursor: result?.nextCursor ?? null,
415
+ };
186
416
  }
187
417
  async removeUser(appId, userId) {
188
418
  return this.delete(`/app/${appId}/api/users/${userId}`);
@@ -196,14 +426,39 @@ export class ApiClient {
196
426
  async transferAdminOwnership(appId, adminId) {
197
427
  return this.post(`/admin/api/apps/${appId}/admins/transfer-ownership`, { adminId });
198
428
  }
429
+ // App-level console admin management
430
+ async listAppAdmins(appId) {
431
+ return this.get(`/admin/api/apps/${appId}/admins`);
432
+ }
433
+ async addAppAdmin(appId, data) {
434
+ return this.post(`/admin/api/apps/${appId}/admins`, data);
435
+ }
436
+ async removeAppAdmin(appId, adminId) {
437
+ return this.delete(`/admin/api/apps/${appId}/admins/${adminId}`);
438
+ }
439
+ async listAppAdminInvitations(appId) {
440
+ return this.get(`/admin/api/apps/${appId}/admin-invitations`);
441
+ }
442
+ async deleteAppAdminInvitation(appId, invitationId) {
443
+ return this.delete(`/admin/api/apps/${appId}/admin-invitations/${invitationId}`);
444
+ }
199
445
  async transferDocumentOwnership(appId, documentId, newOwnerId) {
200
446
  return this.post(`/app/${appId}/api/documents/${documentId}/permissions/transfer`, { newOwnerId });
201
447
  }
202
448
  // ============================================
203
449
  // INVITATIONS
204
450
  // ============================================
205
- async listInvitations(appId) {
206
- return this.get(`/app/${appId}/api/invitations`);
451
+ async listInvitations(appId, params) {
452
+ const result = await this.get(`/app/${appId}/api/invitations`, params);
453
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias
454
+ // so the CLI keeps paginating against pre-#1316 servers.
455
+ const nextCursor = result?.nextCursor ?? result?.cursor;
456
+ return {
457
+ items: result?.items ?? [],
458
+ nextCursor,
459
+ hasMore: result?.hasMore ?? nextCursor != null,
460
+ cursor: nextCursor,
461
+ };
207
462
  }
208
463
  async createInvitation(appId, data) {
209
464
  return this.post(`/app/${appId}/api/invitations`, data);
@@ -228,6 +483,20 @@ export class ApiClient {
228
483
  return this.delete(`/app/${appId}/api/waitlist/${waitlistId}`);
229
484
  }
230
485
  // ============================================
486
+ // DEFERRED GRANTS
487
+ // ============================================
488
+ async listDeferredGrants(appId, params) {
489
+ const result = await this.get(`/app/${appId}/api/deferred-grants`, params);
490
+ return {
491
+ grants: result?.grants ?? result?.items ?? [],
492
+ nextCursor: result?.nextCursor ?? null,
493
+ hasMore: result?.hasMore,
494
+ };
495
+ }
496
+ async revokeDeferredGrant(appId, deferredId, type) {
497
+ return this.delete(`/app/${appId}/api/deferred-grants/${deferredId}?type=${type}`);
498
+ }
499
+ // ============================================
231
500
  // INTEGRATIONS
232
501
  // ============================================
233
502
  async listIntegrations(appId, params) {
@@ -237,6 +506,7 @@ export class ApiClient {
237
506
  nextCursor: result?.nextCursor ?? null,
238
507
  };
239
508
  }
509
+ /** Integration detail (#2631: `accessRule` is on the detail, not the list summary). */
240
510
  async getIntegration(appId, integrationId) {
241
511
  return this.get(`/admin/api/apps/${appId}/integrations/${integrationId}`);
242
512
  }
@@ -260,17 +530,256 @@ export class ApiClient {
260
530
  const result = await this.get(`/admin/api/apps/${appId}/integrations/${integrationId}/logs`, params);
261
531
  return result?.items ?? [];
262
532
  }
263
- async listIntegrationSecrets(appId, integrationId, params) {
264
- const result = await this.get(`/admin/api/apps/${appId}/integrations/${integrationId}/secrets`, params);
533
+ async listWorkflowRunIntegrationLogs(appId, runId, params) {
534
+ const result = await this.get(`/admin/api/apps/${appId}/workflows/runs/${runId}/integration-logs`, params);
265
535
  return result?.items ?? [];
266
536
  }
267
- async addIntegrationSecret(appId, integrationId, payload) {
268
- const result = await this.post(`/admin/api/apps/${appId}/integrations/${integrationId}/secrets`, payload);
269
- return result?.secret ?? null;
537
+ // ============================================
538
+ // APP SECRETS
539
+ // ============================================
540
+ async listAppSecrets(appId) {
541
+ const result = await this.get(`/admin/api/apps/${appId}/secrets`);
542
+ return result?.items ?? [];
543
+ }
544
+ async createAppSecret(appId, payload) {
545
+ return this.post(`/admin/api/apps/${appId}/secrets`, payload);
546
+ }
547
+ async updateAppSecret(appId, secretId, payload) {
548
+ return this.put(`/admin/api/apps/${appId}/secrets/${secretId}`, payload);
549
+ }
550
+ async upsertAppSecret(appId, key, payload) {
551
+ return this.put(`/admin/api/apps/${appId}/secrets/by-key/${key}`, payload);
552
+ }
553
+ async deleteAppSecret(appId, secretId) {
554
+ return this.delete(`/admin/api/apps/${appId}/secrets/${secretId}`);
555
+ }
556
+ // ============================================
557
+ // APP CONFIG VARS (issue #1364 — non-secret twin of secrets)
558
+ // ============================================
559
+ async listAppConfigVars(appId) {
560
+ const result = await this.get(`/admin/api/apps/${appId}/vars`);
561
+ return result?.items ?? [];
562
+ }
563
+ async upsertAppConfigVar(appId, key, payload, expectedModifiedAt, options = {}) {
564
+ // Encode the key so a malformed one (e.g. containing "/") reaches the
565
+ // server's key validation (400) instead of producing a routing 404.
566
+ // `expectedModifiedAt` (issue #1423 review r-2 P1) is the optimistic-
567
+ // concurrency precondition for an UPDATE — the server rejects the write
568
+ // with a 409 CONFLICT (surfaced as `ConflictError`) if the var changed
569
+ // since it.
570
+ //
571
+ // `expectNotExists` (issue #1423 review r-3 P1a) is the create-only
572
+ // precondition. A create has no baseline timestamp to send, but without
573
+ // any precondition the by-key upsert silently overwrites a var created
574
+ // remotely since our snapshot. Setting `expectNotExists` makes the server
575
+ // 409 CONFLICT if the key already exists instead of overwriting it.
576
+ const body = { ...payload };
577
+ if (expectedModifiedAt !== undefined)
578
+ body.expectedModifiedAt = expectedModifiedAt;
579
+ if (options.expectNotExists)
580
+ body.expectNotExists = true;
581
+ return this.put(`/admin/api/apps/${appId}/vars/by-key/${encodeURIComponent(key)}`, body);
582
+ }
583
+ async deleteAppConfigVar(appId, key, expectedModifiedAt) {
584
+ // The DELETE carries the optimistic-concurrency precondition (issue #1423
585
+ // review r-2 P1) as a query param since it has no body; the server 409s
586
+ // (ConflictError) if the var was edited remotely since `expectedModifiedAt`.
587
+ let path = `/admin/api/apps/${appId}/vars/by-key/${encodeURIComponent(key)}`;
588
+ if (expectedModifiedAt !== undefined) {
589
+ path += `?expectedModifiedAt=${encodeURIComponent(expectedModifiedAt)}`;
590
+ }
591
+ return this.delete(path);
592
+ }
593
+ // ============================================
594
+ // WEBHOOKS
595
+ // ============================================
596
+ async listWebhooks(appId, params) {
597
+ const result = await this.get(`/admin/api/apps/${appId}/webhooks`, params);
598
+ return {
599
+ items: result?.items ?? [],
600
+ nextCursor: result?.nextCursor ?? null,
601
+ };
602
+ }
603
+ async getWebhook(appId, webhookId) {
604
+ return this.get(`/admin/api/apps/${appId}/webhooks/${webhookId}`);
605
+ }
606
+ async createWebhook(appId, payload) {
607
+ return this.post(`/admin/api/apps/${appId}/webhooks`, payload);
608
+ }
609
+ async updateWebhook(appId, webhookId, payload, expectedModifiedAt) {
610
+ const body = expectedModifiedAt ? { ...payload, expectedModifiedAt } : payload;
611
+ return this.patch(`/admin/api/apps/${appId}/webhooks/${webhookId}`, body);
612
+ }
613
+ /**
614
+ * Delete a webhook. Archives it by default; `hard` hard-deletes the row
615
+ * instead (#2232), which is what frees a slot under the per-app webhook cap
616
+ * and releases the webhook key for reuse. Same `?hard=true` verb the admin
617
+ * integrations delete uses.
618
+ */
619
+ async deleteWebhook(appId, webhookId, options) {
620
+ const query = options?.hard ? "?hard=true" : "";
621
+ return this.delete(`/admin/api/apps/${appId}/webhooks/${webhookId}${query}`);
622
+ }
623
+ async rotateWebhookSecret(appId, webhookId, payload) {
624
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/rotate-secret`, payload);
625
+ }
626
+ async listWebhookEvents(appId, webhookId, params) {
627
+ const result = await this.get(`/admin/api/apps/${appId}/webhooks/${webhookId}/events`, params);
628
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias.
629
+ const nextCursor = result?.nextCursor ?? result?.cursor ?? null;
630
+ return {
631
+ items: result?.items ?? [],
632
+ hasMore: result?.hasMore ?? !!nextCursor,
633
+ nextCursor,
634
+ cursor: nextCursor,
635
+ };
636
+ }
637
+ // ============================================
638
+ // CONNECTIONS INSPECTION (#1968)
639
+ // ============================================
640
+ /**
641
+ * List the live connections the server believes exist for exactly one of a
642
+ * document, user, or database. Read-only inspection over admin-api. Rows are
643
+ * per-connection-×-subscription bindings, so `connectionId` is not unique
644
+ * across rows. `params` on a database-subscription row is caller-defined
645
+ * bound CEL input — typed `unknown`.
646
+ */
647
+ async listConnections(appId, selector, params) {
648
+ const result = await this.get(`/admin/api/apps/${appId}/connections`, {
649
+ ...selector,
650
+ ...params,
651
+ });
652
+ return {
653
+ items: result?.items ?? [],
654
+ nextCursor: result?.nextCursor ?? null,
655
+ };
656
+ }
657
+ async listSessions(appId, userId, params) {
658
+ const result = await this.get(`/admin/api/apps/${appId}/sessions`, {
659
+ userId,
660
+ ...params,
661
+ });
662
+ return {
663
+ items: result?.items ?? [],
664
+ nextCursor: result?.nextCursor ?? null,
665
+ };
666
+ }
667
+ async testWebhook(appId, webhookId, payload) {
668
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/test`, payload || {});
270
669
  }
271
- async archiveIntegrationSecret(appId, integrationId, secretId) {
272
- return this.patch(`/admin/api/apps/${appId}/integrations/${integrationId}/secrets/${secretId}`, {
273
- status: "inactive",
670
+ /**
671
+ * Run a webhook's configured verifier over headers and a body captured from
672
+ * a real delivery, and report whether that signature checks out (#2445).
673
+ *
674
+ * `headers` is sent as ordered `[name, value]` pairs so a capture carrying a
675
+ * field name on more than one line survives the round trip. Nothing is
676
+ * delivered: no delivery record, no workflow run.
677
+ */
678
+ async verifyWebhook(appId, webhookId, payload) {
679
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/verify`, payload);
680
+ }
681
+ // ============================================
682
+ // NAMED LOCKS (#1518)
683
+ // ============================================
684
+ async listLocks(appId) {
685
+ const result = await this.get(`/app/${appId}/api/locks`);
686
+ return { locks: result?.locks ?? [] };
687
+ }
688
+ async getLockStatus(appId, key) {
689
+ return this.post(`/app/${appId}/api/locks/status`, { key });
690
+ }
691
+ async acquireLock(appId, key, ttlMs) {
692
+ return this.post(`/app/${appId}/api/locks/acquire`, { key, ttlMs });
693
+ }
694
+ async releaseLock(appId, key, handleId) {
695
+ return this.post(`/app/${appId}/api/locks/release`, {
696
+ key,
697
+ handle: { handleId },
698
+ });
699
+ }
700
+ // ============================================
701
+ // CRON TRIGGERS
702
+ // ============================================
703
+ async listCronTriggers(appId) {
704
+ const result = await this.get(`/app/${appId}/api/cron-triggers`);
705
+ return { items: result?.items ?? [] };
706
+ }
707
+ async getCronTrigger(appId, triggerId) {
708
+ return this.get(`/app/${appId}/api/cron-triggers/${triggerId}`);
709
+ }
710
+ async createCronTrigger(appId, payload) {
711
+ return this.post(`/app/${appId}/api/cron-triggers`, payload);
712
+ }
713
+ async updateCronTrigger(appId, triggerId, payload) {
714
+ return this.put(`/app/${appId}/api/cron-triggers/${triggerId}`, payload);
715
+ }
716
+ async deleteCronTrigger(appId, triggerId) {
717
+ return this.delete(`/app/${appId}/api/cron-triggers/${triggerId}`);
718
+ }
719
+ async pauseCronTrigger(appId, triggerId) {
720
+ return this.post(`/app/${appId}/api/cron-triggers/${triggerId}/pause`, {});
721
+ }
722
+ async resumeCronTrigger(appId, triggerId) {
723
+ return this.post(`/app/${appId}/api/cron-triggers/${triggerId}/resume`, {});
724
+ }
725
+ async testCronTrigger(appId, triggerId) {
726
+ return this.post(`/app/${appId}/api/cron-triggers/${triggerId}/test`, {});
727
+ }
728
+ // ============================================
729
+ // ITERATIONS (iterate-users introspection / reset — #1209)
730
+ // ============================================
731
+ async listIterations(appId) {
732
+ const result = await this.get(`/app/${appId}/api/iterations`);
733
+ return { items: result?.items ?? [] };
734
+ }
735
+ async getIteration(appId, iterationName) {
736
+ return this.get(`/app/${appId}/api/iterations/${encodeURIComponent(iterationName)}`);
737
+ }
738
+ async resetIteration(appId, iterationName) {
739
+ return this.post(`/app/${appId}/api/iterations/${encodeURIComponent(iterationName)}/reset`, {});
740
+ }
741
+ // ============================================
742
+ // RESOURCE METADATA (values — issue #1352)
743
+ // ============================================
744
+ async readResourceMetadata(appId, resourceType, resourceId, category) {
745
+ return this.get(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata/${encodeURIComponent(category)}`);
746
+ }
747
+ async writeResourceMetadata(appId, resourceType, resourceId, category, data) {
748
+ return this.put(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata/${encodeURIComponent(category)}`, { data });
749
+ }
750
+ async batchReadResourceMetadata(appId, requests) {
751
+ return this.post(`/app/${appId}/api/resources/metadata/batch`, {
752
+ requests,
753
+ });
754
+ }
755
+ /**
756
+ * List every stored metadata category on one resource (issue #1402 — debug
757
+ * tooling). The CLI authenticates as a console admin, so the app-level
758
+ * owner/admin bypass returns every category regardless of its readRule.
759
+ */
760
+ async listResourceMetadata(appId, resourceType, resourceId) {
761
+ return this.get(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata`);
762
+ }
763
+ /**
764
+ * Delete one resource's metadata for one category (issue #1402 — debug
765
+ * tooling). Idempotent: deleting an absent item succeeds with
766
+ * `deleted: false` rather than a 404.
767
+ */
768
+ async deleteResourceMetadata(appId, resourceType, resourceId, category) {
769
+ return this.delete(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata/${encodeURIComponent(category)}`);
770
+ }
771
+ /**
772
+ * Reverse-resolve a resource by a category's unique metadata value (issue
773
+ * #2137). A miss is a success with `resourceId: null`, never an error. The
774
+ * CLI authenticates as a console admin, so the app-level owner/admin bypass
775
+ * skips readRule evaluation.
776
+ */
777
+ async resolveResourceMetadata(appId, resourceType, category, key, value) {
778
+ return this.post(`/app/${appId}/api/metadata/resolve`, {
779
+ resourceType,
780
+ category,
781
+ key,
782
+ value,
274
783
  });
275
784
  }
276
785
  // ============================================
@@ -325,6 +834,63 @@ export class ApiClient {
325
834
  async duplicatePromptConfig(appId, promptId, configId, payload) {
326
835
  return this.post(`/admin/api/apps/${appId}/prompts/${promptId}/configs/${configId}/duplicate`, payload || {});
327
836
  }
837
+ // ============================================
838
+ // SCRIPTS (Rhai transforms) — #1000 (prompt-model convergence)
839
+ // ============================================
840
+ //
841
+ // The `Script` model is the authoring surface for `script` workflow
842
+ // steps. A `Script` is a HEADER (name/description/activeConfigId); the
843
+ // Rhai body lives on versioned `ScriptConfig` rows resolved LIVE at run
844
+ // time. CLI `sync push` reads `transforms/*.rhai` files and reconciles
845
+ // them: a new file → create script (mints a default config); a changed
846
+ // file → create a new config + activate it (zero fan-out — referencing
847
+ // workflows pick up the new body on their next run).
848
+ async listScripts(appId) {
849
+ const result = await this.get(`/admin/api/apps/${appId}/scripts`);
850
+ return { items: result?.items ?? [] };
851
+ }
852
+ async getScript(appId, scriptId) {
853
+ return this.get(`/admin/api/apps/${appId}/scripts/${scriptId}`);
854
+ }
855
+ /**
856
+ * List a script's versioned configs (the `ScriptConfig` rows). Each config
857
+ * is a distinct block version: `configId` is the stable version selector,
858
+ * `contentHash` is its content identity, and `status` reports whether it is
859
+ * `active`/`draft`/`archived`. The script header's `activeConfigId` names
860
+ * the live version. Used by `scripts configs list` and by the script test
861
+ * commands to run against a specific pinned version.
862
+ */
863
+ async listScriptConfigs(appId, scriptId) {
864
+ const result = await this.get(`/admin/api/apps/${appId}/scripts/${scriptId}/configs`);
865
+ return { items: result?.items ?? [] };
866
+ }
867
+ async createScript(appId, payload) {
868
+ // Mints the script header + a default `active` config carrying the body.
869
+ return this.post(`/admin/api/apps/${appId}/scripts`, payload);
870
+ }
871
+ /**
872
+ * Push a new body for an existing script by creating a new `ScriptConfig`
873
+ * and activating it (the prompt-model "edit → activate" flow). Referencing
874
+ * workflows pick up the new body on their next run with no fan-out. The
875
+ * config name is unique per script, so we mint a timestamped name.
876
+ */
877
+ async pushScriptBody(appId, scriptId, body) {
878
+ const configName = `sync-${Date.now()}`;
879
+ const config = await this.post(`/admin/api/apps/${appId}/scripts/${scriptId}/configs`, { configName, body });
880
+ await this.post(`/admin/api/apps/${appId}/scripts/${scriptId}/configs/${config.configId}/activate`, {});
881
+ return config;
882
+ }
883
+ /**
884
+ * Delete a script header (cascades its configs). `force` overrides the
885
+ * server's guard against deleting a script that an active workflow still
886
+ * references by name — without it the server answers 409.
887
+ */
888
+ async deleteScript(appId, scriptId, force) {
889
+ const path = force
890
+ ? `/admin/api/apps/${appId}/scripts/${scriptId}?force=true`
891
+ : `/admin/api/apps/${appId}/scripts/${scriptId}`;
892
+ return this.delete(path);
893
+ }
328
894
  async getPromptSchema(appId, promptId) {
329
895
  return this.get(`/admin/api/apps/${appId}/prompts/${promptId}/schema`);
330
896
  }
@@ -415,14 +981,8 @@ export class ApiClient {
415
981
  });
416
982
  const text = await response.text();
417
983
  if (!response.ok) {
418
- let errorData;
419
- try {
420
- errorData = JSON.parse(text);
421
- }
422
- catch {
423
- errorData = { message: text || `HTTP ${response.status}` };
424
- }
425
- throw new ApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.code);
984
+ const parsed = parseErrorResponse(response, text, url);
985
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
426
986
  }
427
987
  return text ? JSON.parse(text) : null;
428
988
  }
@@ -442,14 +1002,8 @@ export class ApiClient {
442
1002
  });
443
1003
  if (!response.ok) {
444
1004
  const text = await response.text();
445
- let errorData;
446
- try {
447
- errorData = JSON.parse(text);
448
- }
449
- catch {
450
- errorData = { message: text || `HTTP ${response.status}` };
451
- }
452
- throw new ApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.code);
1005
+ const parsed = parseErrorResponse(response, text, url);
1006
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
453
1007
  }
454
1008
  const arrayBuffer = await response.arrayBuffer();
455
1009
  return {
@@ -497,6 +1051,18 @@ export class ApiClient {
497
1051
  async deleteWorkflow(appId, workflowId) {
498
1052
  return this.delete(`/admin/api/apps/${appId}/workflows/${workflowId}`);
499
1053
  }
1054
+ /**
1055
+ * #2645 criterion 9 — the operational toggle. Deliberately NOT the config
1056
+ * PATCH: `sync push` owns every configuration field, and taking a workflow
1057
+ * out of service must not touch one, or an operator's action would show up as
1058
+ * drift against the repo. Same route shape as `cron-triggers pause|resume`.
1059
+ */
1060
+ async disableWorkflow(appId, workflowId) {
1061
+ return this.post(`/app/${appId}/api/workflows/${workflowId}/disable`, {});
1062
+ }
1063
+ async enableWorkflow(appId, workflowId) {
1064
+ return this.post(`/app/${appId}/api/workflows/${workflowId}/enable`, {});
1065
+ }
500
1066
  async updateWorkflowDraft(appId, workflowId, payload) {
501
1067
  return this.put(`/admin/api/apps/${appId}/workflows/${workflowId}/draft`, payload);
502
1068
  }
@@ -511,14 +1077,46 @@ export class ApiClient {
511
1077
  }
512
1078
  async listWorkflowRuns(appId, workflowId, params) {
513
1079
  const result = await this.get(`/admin/api/apps/${appId}/workflows/${workflowId}/runs`, params);
1080
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias.
1081
+ const nextCursor = result?.nextCursor ?? result?.cursor ?? null;
514
1082
  return {
515
1083
  items: result?.items ?? [],
516
- cursor: result?.cursor ?? null,
1084
+ hasMore: result?.hasMore,
1085
+ nextCursor,
1086
+ cursor: nextCursor,
1087
+ resumeAfter: result?.resumeAfter,
1088
+ scanned: typeof result?.scanned === "number" ? result.scanned : undefined,
1089
+ };
1090
+ }
1091
+ /**
1092
+ * Workflow runs started by one app user, across every workflow (#1967).
1093
+ * Backed by `GET /admin/api/apps/{appId}/users/{userId}/workflow-runs`,
1094
+ * which resolves the app user before querying the `runsByUser` index.
1095
+ */
1096
+ async listUserWorkflowRuns(appId, userId, params) {
1097
+ const result = await this.get(`/admin/api/apps/${appId}/users/${encodeURIComponent(userId)}/workflow-runs`, params);
1098
+ const nextCursor = result?.nextCursor ?? result?.cursor ?? null;
1099
+ return {
1100
+ items: result?.items ?? [],
1101
+ hasMore: result?.hasMore,
1102
+ nextCursor,
1103
+ cursor: nextCursor,
1104
+ scanned: typeof result?.scanned === "number" ? result.scanned : undefined,
517
1105
  };
518
1106
  }
519
1107
  async getWorkflowRunStatus(appId, workflowId, runId) {
520
1108
  return this.get(`/admin/api/apps/${appId}/workflows/${workflowId}/runs/${runId}/status`);
521
1109
  }
1110
+ async getWorkflowStepRuns(appId, workflowId, runId) {
1111
+ const result = await this.get(`/admin/api/apps/${appId}/workflows/${workflowId}/runs/${runId}/steps`);
1112
+ return { items: result?.items ?? [] };
1113
+ }
1114
+ async getWorkflowAnalytics(appId, params) {
1115
+ return this.get(`/app/${appId}/api/analytics/workflows/overview`, params);
1116
+ }
1117
+ async getTopWorkflows(appId, params) {
1118
+ return this.get(`/app/${appId}/api/analytics/workflows/top`, params);
1119
+ }
522
1120
  // ============================================
523
1121
  // WORKFLOW CONFIGURATIONS
524
1122
  // ============================================
@@ -547,29 +1145,68 @@ export class ApiClient {
547
1145
  // ============================================
548
1146
  // ANALYTICS
549
1147
  // ============================================
550
- async getAnalyticsOverview(appId, params) {
551
- return this.get(`/app/${appId}/api/analytics/overview`, params);
552
- }
553
1148
  async getAnalyticsTopUsers(appId, params) {
554
1149
  return this.get(`/app/${appId}/api/analytics/users/top`, params);
555
1150
  }
556
- async getAnalyticsUserTimeline(appId, userUlid, params) {
557
- return this.get(`/app/${appId}/api/analytics/users/${userUlid}/timeline`, params);
558
- }
559
- async getAnalyticsUserEvents(appId, userUlid, params) {
560
- return this.get(`/app/${appId}/api/analytics/users/${userUlid}/events`, params);
561
- }
562
1151
  async getAnalyticsIntegrationMetrics(appId, params) {
563
1152
  return this.get(`/app/${appId}/api/analytics/integrations`, params);
564
1153
  }
1154
+ async getAnalyticsOverviewDau(appId) {
1155
+ return this.get(`/app/${appId}/api/analytics/overview/dau`);
1156
+ }
1157
+ async getAnalyticsOverviewWau(appId) {
1158
+ return this.get(`/app/${appId}/api/analytics/overview/wau`);
1159
+ }
1160
+ async getAnalyticsOverviewMau(appId) {
1161
+ return this.get(`/app/${appId}/api/analytics/overview/mau`);
1162
+ }
1163
+ async getAnalyticsOverviewGrowth(appId, params) {
1164
+ return this.get(`/app/${appId}/api/analytics/overview/growth`, params);
1165
+ }
1166
+ async getAnalyticsDailyActive(appId, params) {
1167
+ return this.get(`/app/${appId}/api/analytics/daily-active`, params);
1168
+ }
1169
+ async getAnalyticsRollingActive(appId, params) {
1170
+ return this.get(`/app/${appId}/api/analytics/rolling-active`, params);
1171
+ }
1172
+ async getAnalyticsCohortRetention(appId) {
1173
+ return this.get(`/app/${appId}/api/analytics/cohort-retention`);
1174
+ }
1175
+ async getAnalyticsUserSearch(appId, params) {
1176
+ return this.get(`/app/${appId}/api/analytics/users/search`, params);
1177
+ }
1178
+ async getAnalyticsUserDetail(appId, userUlid) {
1179
+ return this.get(`/app/${appId}/api/analytics/users/${userUlid}/detail`);
1180
+ }
1181
+ async getAnalyticsUserSnapshot(appId, userUlid) {
1182
+ return this.get(`/app/${appId}/api/analytics/users/${userUlid}/snapshot`);
1183
+ }
1184
+ async getAnalyticsEvents(appId, params) {
1185
+ return this.get(`/app/${appId}/api/analytics/events`, params);
1186
+ }
1187
+ async getAnalyticsEventsGrouped(appId, params) {
1188
+ return this.get(`/app/${appId}/api/analytics/events/grouped`, params);
1189
+ }
1190
+ async getAnalyticsErrorsGroups(appId, params) {
1191
+ return this.get(`/app/${appId}/api/analytics/errors/groups`, params);
1192
+ }
1193
+ async getAnalyticsTopWorkflows(appId, params) {
1194
+ return this.get(`/app/${appId}/api/analytics/workflows/top`, params);
1195
+ }
1196
+ async getAnalyticsTopPrompts(appId, params) {
1197
+ return this.get(`/app/${appId}/api/analytics/prompts/top`, params);
1198
+ }
565
1199
  // ============================================
566
1200
  // SUPER ADMIN: ADMINS
567
1201
  // ============================================
568
1202
  async listAllAdmins(params) {
569
1203
  const result = await this.get("/admin/api/admins", params);
1204
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias.
1205
+ const nextCursor = result?.nextCursor ?? result?.cursor ?? null;
570
1206
  return {
571
- admins: result?.admins ?? [],
572
- cursor: result?.cursor ?? null,
1207
+ admins: result?.admins ?? result?.items ?? [],
1208
+ nextCursor,
1209
+ cursor: nextCursor,
573
1210
  };
574
1211
  }
575
1212
  async searchAdminByEmail(email) {
@@ -670,6 +1307,24 @@ export class ApiClient {
670
1307
  return this.get(`/admin/api/apps/${appId}/comparisons/${group}`);
671
1308
  }
672
1309
  // ============================================
1310
+ // EMAIL TEMPLATES
1311
+ // ============================================
1312
+ async listEmailTemplates(appId) {
1313
+ return this.get(`/admin/api/apps/${appId}/email-templates`);
1314
+ }
1315
+ async getEmailTemplate(appId, emailType) {
1316
+ return this.get(`/admin/api/apps/${appId}/email-templates/${emailType}`);
1317
+ }
1318
+ async upsertEmailTemplate(appId, emailType, payload) {
1319
+ return this.put(`/admin/api/apps/${appId}/email-templates/${emailType}`, payload);
1320
+ }
1321
+ async deleteEmailTemplate(appId, emailType) {
1322
+ return this.delete(`/admin/api/apps/${appId}/email-templates/${emailType}`);
1323
+ }
1324
+ async testEmailTemplate(appId, emailType, payload) {
1325
+ return this.post(`/admin/api/apps/${appId}/email-templates/${emailType}/test`, payload || {});
1326
+ }
1327
+ // ============================================
673
1328
  // ACCESS TOKENS
674
1329
  // ============================================
675
1330
  async createToken(appId, data) {
@@ -688,8 +1343,42 @@ export class ApiClient {
688
1343
  // ============================================
689
1344
  // DATABASES
690
1345
  // ============================================
691
- async listDatabases(appId) {
692
- return this.get(`/app/${appId}/api/databases`);
1346
+ /**
1347
+ * List an app's databases, following the cursor to the end.
1348
+ *
1349
+ * The endpoint returns the `{ items, hasMore, nextCursor }` envelope and
1350
+ * caps a page at 100 (#1958), so `databases list` needs the follow-up pages
1351
+ * to show every database. `paginateAll` carries the repeat-cursor and
1352
+ * max-page guards, so a server that hands out a non-advancing cursor fails
1353
+ * loudly instead of looping forever.
1354
+ *
1355
+ * `options.owner` narrows the result to the databases that user created; the
1356
+ * server resolves it through the `databasesByCreator` index (#1965).
1357
+ */
1358
+ async listDatabases(appId, options) {
1359
+ return paginateAll(async (cursor) => {
1360
+ const params = new URLSearchParams();
1361
+ if (options?.owner)
1362
+ params.set("owner", options.owner);
1363
+ if (cursor)
1364
+ params.set("cursor", cursor);
1365
+ const qs = params.toString() ? `?${params.toString()}` : "";
1366
+ const resp = await this.get(`/app/${appId}/api/databases${qs}`);
1367
+ // Tolerant read: a server older than #1958 answers with a bare array.
1368
+ // Without this a published CLI pointed at a not-yet-upgraded server
1369
+ // would print nothing at all. Such a server also predates the `owner`
1370
+ // filter (#1965) and ignores the unknown query parameter, so apply the
1371
+ // filter here — the legacy rows carry `createdBy`, so this reproduces
1372
+ // the server's own post-join filter (#2245).
1373
+ if (Array.isArray(resp)) {
1374
+ return {
1375
+ items: options?.owner
1376
+ ? resp.filter((db) => db?.createdBy === options.owner)
1377
+ : resp,
1378
+ };
1379
+ }
1380
+ return { items: resp?.items ?? [], nextCursor: resp?.nextCursor };
1381
+ });
693
1382
  }
694
1383
  async createDatabase(appId, data) {
695
1384
  return this.post(`/app/${appId}/api/databases`, data);
@@ -697,38 +1386,362 @@ export class ApiClient {
697
1386
  async getDatabase(appId, databaseId) {
698
1387
  return this.get(`/app/${appId}/api/databases/${databaseId}`);
699
1388
  }
1389
+ async updateDatabase(appId, databaseId, data) {
1390
+ return this.patch(`/app/${appId}/api/databases/${databaseId}`, data);
1391
+ }
700
1392
  async deleteDatabase(appId, databaseId) {
701
1393
  return this.delete(`/app/${appId}/api/databases/${databaseId}`);
702
1394
  }
1395
+ /**
1396
+ * Read a database's CEL context dict.
1397
+ *
1398
+ * The HTTP path stays `/metadata` because the wire field name is still
1399
+ * `metadata`; only the client/CLI-facing helper names were reframed.
1400
+ */
1401
+ async getDatabaseCelContext(appId, databaseId) {
1402
+ return this.get(`/app/${appId}/api/databases/${databaseId}/metadata`);
1403
+ }
1404
+ /** Update a database's CEL context dict (merge with existing). */
1405
+ async updateDatabaseCelContext(appId, databaseId, celContext) {
1406
+ return this.patch(`/app/${appId}/api/databases/${databaseId}/metadata`, celContext);
1407
+ }
1408
+ /** @deprecated Use {@link getDatabaseCelContext} instead. */
1409
+ async getDatabaseMetadata(appId, databaseId) {
1410
+ return this.getDatabaseCelContext(appId, databaseId);
1411
+ }
1412
+ /** @deprecated Use {@link updateDatabaseCelContext} instead. */
1413
+ async updateDatabaseMetadata(appId, databaseId, metadata) {
1414
+ return this.updateDatabaseCelContext(appId, databaseId, metadata);
1415
+ }
703
1416
  // ============================================
704
1417
  // DATABASE PERMISSIONS
705
1418
  // ============================================
706
1419
  async listDatabasePermissions(appId, databaseId) {
707
1420
  return this.get(`/app/${appId}/api/databases/${databaseId}/permissions`);
708
1421
  }
1422
+ async addDatabaseManager(appId, databaseId, userId) {
1423
+ return this.put(`/app/${appId}/api/databases/${databaseId}/permissions`, {
1424
+ userId,
1425
+ permission: "manager",
1426
+ });
1427
+ }
1428
+ async removeDatabaseManager(appId, databaseId, userId) {
1429
+ return this.delete(`/app/${appId}/api/databases/${databaseId}/permissions/${userId}`);
1430
+ }
1431
+ /** @deprecated Use {@link addDatabaseManager} instead. */
709
1432
  async grantDatabasePermission(appId, databaseId, data) {
710
- return this.put(`/app/${appId}/api/databases/${databaseId}/permissions`, data);
1433
+ return this.addDatabaseManager(appId, databaseId, data.userId);
711
1434
  }
1435
+ /** @deprecated Use {@link removeDatabaseManager} instead. */
712
1436
  async revokeDatabasePermission(appId, databaseId, userId) {
713
1437
  return this.delete(`/app/${appId}/api/databases/${databaseId}/permissions/${userId}`);
714
1438
  }
715
1439
  // ============================================
716
- // DATABASE GROUP PERMISSIONS
1440
+ // DATABASE RECORDS & SCHEMA
717
1441
  // ============================================
718
- async listDatabaseGroupPermissions(appId, databaseId) {
719
- return this.get(`/app/${appId}/api/databases/${databaseId}/group-permissions`);
1442
+ async listDatabaseModels(appId, databaseId) {
1443
+ return this.get(`/app/${appId}/api/databases/${databaseId}/records/models`);
1444
+ }
1445
+ async describeDatabaseModel(appId, databaseId, modelName) {
1446
+ return this.get(`/app/${appId}/api/databases/${databaseId}/records/describe`, { modelName });
1447
+ }
1448
+ /**
1449
+ * Query records in a database model. The Durable Object answers with its own
1450
+ * `{ data, hasMore, nextCursor?, prevCursor? }` envelope; that wire shape is
1451
+ * shared with the JS client, the Swift client and web-admin, so the CLI
1452
+ * normalizes it at its own boundary instead (issue #2357) and hands callers
1453
+ * the same `{ items, hasMore, nextCursor? }` envelope as
1454
+ * {@link queryDocumentRecords}.
1455
+ */
1456
+ async queryDatabaseRecords(appId, databaseId, modelName, queryOptions) {
1457
+ const body = { modelName };
1458
+ if (queryOptions?.filter)
1459
+ body.filter = queryOptions.filter;
1460
+ const options = {};
1461
+ if (queryOptions?.limit)
1462
+ options.limit = queryOptions.limit;
1463
+ if (queryOptions?.cursor)
1464
+ options.uniqueStartKey = queryOptions.cursor;
1465
+ if (Object.keys(options).length > 0)
1466
+ body.options = options;
1467
+ const raw = await this.post(`/app/${appId}/api/databases/${databaseId}/records/query`, body);
1468
+ return normalizeCliListEnvelope(raw);
1469
+ }
1470
+ async countDatabaseRecords(appId, databaseId, modelName, filter) {
1471
+ const body = { modelName };
1472
+ if (filter)
1473
+ body.filter = filter;
1474
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/count`, body);
1475
+ }
1476
+ async aggregateDatabaseRecords(appId, databaseId, modelName, options) {
1477
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/aggregate`, {
1478
+ modelName,
1479
+ options,
1480
+ });
720
1481
  }
721
- async grantDatabaseGroupPermission(appId, databaseId, data) {
722
- return this.post(`/app/${appId}/api/databases/${databaseId}/group-permissions`, data);
1482
+ /**
1483
+ * Upsert one record via `records/save`: creates the record when the id is
1484
+ * new, and merges the supplied fields into it when it already exists (the DO
1485
+ * writes with `ON CONFLICT … json_patch`, so fields you leave out survive).
1486
+ * `patchDatabaseRecord` is the same merge but requires the record to exist.
1487
+ *
1488
+ * `id` is optional: when omitted the body carries no `id`, which the
1489
+ * DatabaseDO only accepts alongside an `upsertOn` field — callers that want a
1490
+ * plain create must supply an id themselves (`databases records save` mints a
1491
+ * ULID, matching the CSV import path).
1492
+ *
1493
+ * Returns the endpoint's flat `{ success, id, appliedFields }` — not the
1494
+ * saved record.
1495
+ */
1496
+ async saveDatabaseRecord(appId, databaseId, modelName, id, data) {
1497
+ const body = { modelName, data };
1498
+ if (id !== undefined)
1499
+ body.id = id;
1500
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/save`, body);
1501
+ }
1502
+ /**
1503
+ * Merge the supplied fields into an existing record via `records/patch`.
1504
+ *
1505
+ * Fields absent from `data` are left as they are. Unlike `saveDatabaseRecord`
1506
+ * the record must already exist — the DatabaseDO answers 404 for an unknown
1507
+ * id rather than creating one. Returns the flat
1508
+ * `{ success, id, appliedFields }`.
1509
+ */
1510
+ async patchDatabaseRecord(appId, databaseId, modelName, id, data) {
1511
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/patch`, {
1512
+ modelName,
1513
+ id,
1514
+ data,
1515
+ });
723
1516
  }
724
- async revokeDatabaseGroupPermission(appId, databaseId, groupType, groupId) {
725
- return this.delete(`/app/${appId}/api/databases/${databaseId}/group-permissions/${groupType}/${groupId}`);
1517
+ // ============================================
1518
+ // DATABASE OPERATIONS (registered operations)
1519
+ // ============================================
1520
+ async listDatabaseOperations(appId, databaseId) {
1521
+ return this.get(`/app/${appId}/api/databases/${databaseId}/operations`);
1522
+ }
1523
+ /**
1524
+ * Execute a registered operation and, when the result is a query page,
1525
+ * normalize it to the CLI's one list envelope (issue #2440).
1526
+ *
1527
+ * The registered operation decides the response shape, so the normalization
1528
+ * is conditional — see {@link normalizeDatabaseOperationResult}. Everything
1529
+ * else (a `count`, an `aggregate`, a mutation, a `returnField: "all"`
1530
+ * pipeline) is returned exactly as the server sent it.
1531
+ */
1532
+ async executeDatabaseOperation(appId, databaseId, operationName, data, token, options) {
1533
+ const path = `/app/${appId}/api/databases/${databaseId}/operations/${encodeURIComponent(operationName)}/execute`;
1534
+ const extraHeaders = {};
1535
+ if (options?.timing) {
1536
+ extraHeaders["X-Timing"] = "true";
1537
+ }
1538
+ if (token) {
1539
+ return normalizeDatabaseOperationResult(await this.requestWithToken(path, token, {
1540
+ method: "POST",
1541
+ body: JSON.stringify(data || {}),
1542
+ headers: extraHeaders,
1543
+ }));
1544
+ }
1545
+ return normalizeDatabaseOperationResult(await this.request(path, {
1546
+ method: "POST",
1547
+ body: JSON.stringify(data || {}),
1548
+ headers: extraHeaders,
1549
+ }));
1550
+ }
1551
+ /**
1552
+ * Execute a registered batch (bulk) database operation. Posts a chunk of
1553
+ * items to the canonical `operations/:name/batch` endpoint (the same one the
1554
+ * client library's `executeBatch` uses — NOT the deprecated `import-bulk`
1555
+ * alias). Used by `databases import-csv`.
1556
+ *
1557
+ * @returns `{ imported, failed }` — DO-level write outcome counts. Per-item
1558
+ * validation/access failures abort the whole chunk with a 4xx (thrown).
1559
+ */
1560
+ async executeBatch(appId, databaseId, operationName, batch) {
1561
+ return this.post(`/app/${appId}/api/databases/${databaseId}/operations/${encodeURIComponent(operationName)}/batch`, { batch });
1562
+ }
1563
+ /**
1564
+ * Make a request using a specific JWT token instead of the CLI's credentials.
1565
+ * Used for executing operations as a different user.
1566
+ */
1567
+ async requestWithToken(path, token, options = {}) {
1568
+ const credentials = await this.ensureAuthenticated();
1569
+ const url = `${credentials.serverUrl}${path}`;
1570
+ const headers = {
1571
+ Authorization: `Bearer ${token}`,
1572
+ "Content-Type": "application/json",
1573
+ ...(options.headers || {}),
1574
+ };
1575
+ const response = await fetchWithTLS(url, { ...options, headers });
1576
+ const text = await response.text();
1577
+ if (!response.ok) {
1578
+ const parsed = parseErrorResponse(response, text, path);
1579
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
1580
+ }
1581
+ return text ? JSON.parse(text) : null;
1582
+ }
1583
+ // ============================================
1584
+ // DATABASE INDEXES
1585
+ // ============================================
1586
+ async listDatabaseIndexes(appId, databaseId, modelName) {
1587
+ return this.get(`/app/${appId}/api/databases/${databaseId}/records/indexes`, modelName ? { modelName } : undefined);
1588
+ }
1589
+ async registerDatabaseIndex(appId, databaseId, data) {
1590
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/index/register`, data);
1591
+ }
1592
+ async dropDatabaseIndex(appId, databaseId, data) {
1593
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/index/drop`, data);
1594
+ }
1595
+ /**
1596
+ * Issue #974: back-provision an existing database instance's schema-declared
1597
+ * unique indexes by reading its type schema and registering any declared-but-
1598
+ * missing unique index. Idempotent.
1599
+ */
1600
+ async reindexDatabaseFromSchema(appId, databaseId) {
1601
+ return this.post(`/app/${appId}/api/databases/${databaseId}/reindex`, {});
1602
+ }
1603
+ // ============================================
1604
+ // DATABASE TYPE CONFIGS
1605
+ // ============================================
1606
+ async listDatabaseTypeConfigs(appId) {
1607
+ return this.get(`/app/${appId}/api/databases/types`);
1608
+ }
1609
+ async getDatabaseTypeConfig(appId, databaseType) {
1610
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}`);
1611
+ }
1612
+ async createDatabaseTypeConfig(appId, data,
1613
+ // Issue #1336 (codex round-1 P2): `dryRun` runs every create-time
1614
+ // validation (inline CEL rule lint, manifest shape, schema TOML parse)
1615
+ // WITHOUT persisting, so a fresh-type `sync push --dry-run` surfaces a
1616
+ // malformed `defaultAccess`/manifest the same way the real POST would.
1617
+ options) {
1618
+ const query = options?.dryRun ? "?dryRun=true" : "";
1619
+ return this.post(`/app/${appId}/api/databases/types${query}`, data);
1620
+ }
1621
+ async updateDatabaseTypeConfig(appId, databaseType, data, expectedModifiedAt, options) {
1622
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
1623
+ const qs = new URLSearchParams();
1624
+ if (options?.dryRun)
1625
+ qs.set("dryRun", "true");
1626
+ if (options?.acceptWarnings)
1627
+ qs.set("acceptWarnings", "true");
1628
+ const query = qs.toString();
1629
+ const path = `/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}${query ? `?${query}` : ""}`;
1630
+ return this.patch(path, body);
1631
+ }
1632
+ async deleteDatabaseTypeConfig(appId, databaseType, options) {
1633
+ const query = options?.force ? "?force=true" : "";
1634
+ return this.delete(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}${query}`);
1635
+ }
1636
+ /**
1637
+ * Issue #666 Phase 3: ask the server to scaffold a TOML schema from
1638
+ * existing ops + DO field introspection. Read-only — does NOT persist.
1639
+ */
1640
+ async scaffoldDatabaseTypeSchema(appId, databaseType) {
1641
+ return this.post(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/schema:scaffold`, {});
1642
+ }
1643
+ // ============================================
1644
+ // DATABASE TYPE OPERATIONS
1645
+ // ============================================
1646
+ async listDatabaseTypeOperations(appId, databaseType) {
1647
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations`);
1648
+ }
1649
+ async getDatabaseTypeOperation(appId, databaseType, name) {
1650
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations/${encodeURIComponent(name)}`);
1651
+ }
1652
+ async createDatabaseTypeOperation(appId, databaseType, data,
1653
+ // Issue #813 (1A): when `dryRun` is set the server runs the op-edit gate
1654
+ // without persisting — used by `sync push --dry-run` to surface gate
1655
+ // failures the real push would hit. `schemaOverride` lets the gate run
1656
+ // against the schema the SAME push is about to land (so an op that depends
1657
+ // on a new field isn't falsely rejected against the stale stored schema).
1658
+ //
1659
+ // Issue #915 (defect a, follow-up): for a FRESH db-type the parent config
1660
+ // does not exist on the server yet, so the server's "access required"
1661
+ // check has no `defaultAccess` to fall back on. Thread the TOML-declared
1662
+ // type-level `defaultAccess` so an op that omits `access` (intending to
1663
+ // inherit it after the type is created) isn't falsely rejected during the
1664
+ // dry-run. Server only trusts this on the fresh-type dry-run path.
1665
+ options) {
1666
+ const query = options?.dryRun ? "?dryRun=true" : "";
1667
+ let body = data;
1668
+ if (options?.dryRun && options.schemaOverride !== undefined) {
1669
+ body = { ...body, schemaOverride: options.schemaOverride };
1670
+ }
1671
+ if (options?.dryRun && options.defaultAccess !== undefined) {
1672
+ body = { ...body, defaultAccess: options.defaultAccess };
1673
+ }
1674
+ if (options?.dryRun && options.metadataManifestOverride !== undefined) {
1675
+ body = { ...body, metadataManifestOverride: options.metadataManifestOverride };
1676
+ }
1677
+ return this.post(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations${query}`, body);
1678
+ }
1679
+ async updateDatabaseTypeOperation(appId, databaseType, name, data, expectedModifiedAt,
1680
+ // Issue #813 (1A): dry-run runs the op-edit gate without persisting.
1681
+ // `schemaOverride` gates against the schema the same push is landing.
1682
+ // Issue #1336: `metadataManifestOverride` gates the op-access lint against
1683
+ // the manifest the same push is landing (see `createDatabaseTypeOperation`).
1684
+ options) {
1685
+ let body = expectedModifiedAt ? { ...data, expectedModifiedAt } : { ...data };
1686
+ if (options?.dryRun && options.schemaOverride !== undefined) {
1687
+ body = { ...body, schemaOverride: options.schemaOverride };
1688
+ }
1689
+ if (options?.dryRun && options.metadataManifestOverride !== undefined) {
1690
+ body = { ...body, metadataManifestOverride: options.metadataManifestOverride };
1691
+ }
1692
+ const query = options?.dryRun ? "?dryRun=true" : "";
1693
+ return this.patch(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations/${encodeURIComponent(name)}${query}`, body);
1694
+ }
1695
+ async deleteDatabaseTypeOperation(appId, databaseType, name) {
1696
+ return this.delete(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations/${encodeURIComponent(name)}`);
1697
+ }
1698
+ // ============================================
1699
+ // DATABASE TYPE SUBSCRIPTIONS (#740 / #803)
1700
+ // ============================================
1701
+ //
1702
+ // Transparent passthroughs against the server's type-scoped subscription
1703
+ // routes (GET/POST/PUT/DELETE `/databases/types/:type/subscriptions[/:key]`).
1704
+ // The wire format is authoritative in the controller
1705
+ // (`database-type-subscriptions-controller.ts`): create requires
1706
+ // `subscriptionKey`, `displayName`, `modelName`, `filter` (CEL), `access`
1707
+ // (CEL); optional `description`, `select` (string[]), `emit`
1708
+ // (enter/update/leave subset), `params` (object, ≤5 entries), `status`.
1709
+ //
1710
+ // The list endpoint wraps results in `{ items: [...] }` (unlike operations,
1711
+ // which returns a bare array). We unwrap here so callers get an array,
1712
+ // matching `listDatabaseTypeOperations`.
1713
+ async listDatabaseTypeSubscriptions(appId, databaseType) {
1714
+ const result = await this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions`);
1715
+ if (Array.isArray(result))
1716
+ return result;
1717
+ return Array.isArray(result?.items) ? result.items : [];
1718
+ }
1719
+ async getDatabaseTypeSubscription(appId, databaseType, subscriptionKey) {
1720
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions/${encodeURIComponent(subscriptionKey)}`);
1721
+ }
1722
+ async createDatabaseTypeSubscription(appId, databaseType, data) {
1723
+ return this.post(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions`, data);
1724
+ }
1725
+ async updateDatabaseTypeSubscription(appId, databaseType, subscriptionKey, data) {
1726
+ return this.put(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions/${encodeURIComponent(subscriptionKey)}`, data);
1727
+ }
1728
+ async deleteDatabaseTypeSubscription(appId, databaseType, subscriptionKey) {
1729
+ return this.delete(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions/${encodeURIComponent(subscriptionKey)}`);
726
1730
  }
727
1731
  // ============================================
728
1732
  // GROUPS
729
1733
  // ============================================
730
1734
  async listGroups(appId, params) {
731
- return this.get(`/app/${appId}/api/groups`, params);
1735
+ const result = await this.get(`/app/${appId}/api/groups`, params);
1736
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias
1737
+ // so the CLI keeps paginating against pre-#1316 servers.
1738
+ const nextCursor = result?.nextCursor ?? result?.cursor;
1739
+ return {
1740
+ items: result?.items ?? [],
1741
+ nextCursor,
1742
+ hasMore: result?.hasMore ?? nextCursor != null,
1743
+ cursor: nextCursor,
1744
+ };
732
1745
  }
733
1746
  async createGroup(appId, data) {
734
1747
  return this.post(`/app/${appId}/api/groups`, data);
@@ -745,8 +1758,18 @@ export class ApiClient {
745
1758
  // ============================================
746
1759
  // GROUP MEMBERS
747
1760
  // ============================================
748
- async listGroupMembers(appId, groupType, groupId) {
749
- return this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/members`);
1761
+ async listGroupMembers(appId, groupType, groupId, options) {
1762
+ const qs = options?.include ? `?include=${options.include}` : "";
1763
+ const result = await this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/members${qs}`);
1764
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias
1765
+ // so the CLI keeps paginating against pre-#1316 servers.
1766
+ const nextCursor = result?.nextCursor ?? result?.cursor;
1767
+ return {
1768
+ items: result?.items ?? [],
1769
+ nextCursor,
1770
+ hasMore: result?.hasMore ?? nextCursor != null,
1771
+ cursor: nextCursor,
1772
+ };
750
1773
  }
751
1774
  async addGroupMember(appId, groupType, groupId, data) {
752
1775
  return this.post(`/app/${appId}/api/groups/${groupType}/${groupId}/members`, data);
@@ -754,18 +1777,12 @@ export class ApiClient {
754
1777
  async removeGroupMember(appId, groupType, groupId, userId) {
755
1778
  return this.delete(`/app/${appId}/api/groups/${groupType}/${groupId}/members/${userId}`);
756
1779
  }
757
- async updateGroupMemberRole(appId, groupType, groupId, userId, data) {
758
- return this.patch(`/app/${appId}/api/groups/${groupType}/${groupId}/members/${userId}`, data);
759
- }
760
1780
  // ============================================
761
1781
  // GROUP RESOURCE LISTINGS
762
1782
  // ============================================
763
1783
  async listGroupDocuments(appId, groupType, groupId) {
764
1784
  return this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/documents`);
765
1785
  }
766
- async listGroupDatabases(appId, groupType, groupId) {
767
- return this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/databases`);
768
- }
769
1786
  // ============================================
770
1787
  // USER MEMBERSHIPS
771
1788
  // ============================================
@@ -784,6 +1801,541 @@ export class ApiClient {
784
1801
  async revokeDocumentGroupPermission(appId, documentId, groupType, groupId) {
785
1802
  return this.delete(`/app/${appId}/api/documents/${documentId}/group-permissions/${groupType}/${groupId}`);
786
1803
  }
1804
+ // ============================================
1805
+ // COLLECTIONS
1806
+ // ============================================
1807
+ async listCollections(appId, params) {
1808
+ const qs = new URLSearchParams();
1809
+ if (params?.limit)
1810
+ qs.set("limit", String(params.limit));
1811
+ if (params?.cursor)
1812
+ qs.set("cursor", params.cursor);
1813
+ const q = qs.toString();
1814
+ const result = await this.get(`/app/${appId}/api/collections${q ? `?${q}` : ""}`);
1815
+ return {
1816
+ items: result?.items ?? [],
1817
+ nextCursor: result?.nextCursor ?? result?.cursor ?? null,
1818
+ };
1819
+ }
1820
+ async listAllCollections(appId, params) {
1821
+ const qs = new URLSearchParams();
1822
+ if (params?.limit)
1823
+ qs.set("limit", String(params.limit));
1824
+ if (params?.cursor)
1825
+ qs.set("cursor", params.cursor);
1826
+ const q = qs.toString();
1827
+ const result = await this.get(`/app/${appId}/api/admin/collections${q ? `?${q}` : ""}`);
1828
+ return {
1829
+ items: result?.items ?? [],
1830
+ nextCursor: result?.nextCursor ?? result?.cursor ?? null,
1831
+ };
1832
+ }
1833
+ async createCollection(appId, data) {
1834
+ return this.post(`/app/${appId}/api/collections`, data);
1835
+ }
1836
+ async getCollection(appId, collectionId) {
1837
+ return this.get(`/app/${appId}/api/collections/${collectionId}`);
1838
+ }
1839
+ async updateCollection(appId, collectionId, data) {
1840
+ return this.patch(`/app/${appId}/api/collections/${collectionId}`, data);
1841
+ }
1842
+ async deleteCollection(appId, collectionId) {
1843
+ return this.delete(`/app/${appId}/api/collections/${collectionId}`);
1844
+ }
1845
+ // ============================================
1846
+ // COLLECTION DOCUMENTS
1847
+ // ============================================
1848
+ async listCollectionDocuments(appId, collectionId, params) {
1849
+ const qs = new URLSearchParams();
1850
+ if (params?.limit)
1851
+ qs.set("limit", String(params.limit));
1852
+ if (params?.cursor)
1853
+ qs.set("cursor", params.cursor);
1854
+ const q = qs.toString();
1855
+ const result = await this.get(`/app/${appId}/api/collections/${collectionId}/documents${q ? `?${q}` : ""}`);
1856
+ return {
1857
+ items: result?.items ?? [],
1858
+ nextCursor: result?.nextCursor ?? result?.cursor ?? null,
1859
+ };
1860
+ }
1861
+ async addCollectionDocument(appId, collectionId, data) {
1862
+ return this.post(`/app/${appId}/api/collections/${collectionId}/documents`, data);
1863
+ }
1864
+ async removeCollectionDocument(appId, collectionId, documentId) {
1865
+ return this.delete(`/app/${appId}/api/collections/${collectionId}/documents/${documentId}`);
1866
+ }
1867
+ async listCollectionsForDocument(appId, documentId, params) {
1868
+ const qs = new URLSearchParams();
1869
+ if (params?.limit)
1870
+ qs.set("limit", String(params.limit));
1871
+ if (params?.cursor)
1872
+ qs.set("cursor", params.cursor);
1873
+ const q = qs.toString();
1874
+ const result = await this.get(`/app/${appId}/api/documents/${documentId}/collections${q ? `?${q}` : ""}`);
1875
+ return {
1876
+ items: result?.items ?? [],
1877
+ nextCursor: result?.nextCursor ?? result?.cursor ?? null,
1878
+ };
1879
+ }
1880
+ // ============================================
1881
+ // COLLECTION ACCESS (GROUPS + MEMBERS)
1882
+ // ============================================
1883
+ async getCollectionAccess(appId, collectionId) {
1884
+ return this.get(`/app/${appId}/api/collections/${collectionId}/access`);
1885
+ }
1886
+ async grantCollectionGroupPermission(appId, collectionId, data) {
1887
+ return this.post(`/app/${appId}/api/collections/${collectionId}/group-permissions`, data);
1888
+ }
1889
+ async revokeCollectionGroupPermission(appId, collectionId, groupType, groupId) {
1890
+ return this.delete(`/app/${appId}/api/collections/${collectionId}/group-permissions/${groupType}/${groupId}`);
1891
+ }
1892
+ async addCollectionMember(appId, collectionId, data) {
1893
+ return this.post(`/app/${appId}/api/collections/${collectionId}/members`, data);
1894
+ }
1895
+ async removeCollectionMember(appId, collectionId, userId) {
1896
+ return this.delete(`/app/${appId}/api/collections/${collectionId}/members/${userId}`);
1897
+ }
1898
+ // ============================================
1899
+ // COLLECTION TYPE CONFIGS
1900
+ // ============================================
1901
+ async listCollectionTypeConfigs(appId) {
1902
+ return this.get(`/app/${appId}/api/collection-type-configs`);
1903
+ }
1904
+ async getCollectionTypeConfig(appId, collectionType) {
1905
+ return this.get(`/app/${appId}/api/collection-type-configs/${collectionType}`);
1906
+ }
1907
+ async createCollectionTypeConfig(appId, data) {
1908
+ return this.post(`/app/${appId}/api/collection-type-configs`, data);
1909
+ }
1910
+ async updateCollectionTypeConfig(appId, collectionType, data, expectedModifiedAt) {
1911
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
1912
+ return this.patch(`/app/${appId}/api/collection-type-configs/${collectionType}`, body);
1913
+ }
1914
+ async deleteCollectionTypeConfig(appId, collectionType) {
1915
+ return this.delete(`/app/${appId}/api/collection-type-configs/${collectionType}`);
1916
+ }
1917
+ // ============================================
1918
+ // METADATA CATEGORY CONFIGS (issue #1304, P-B)
1919
+ // ============================================
1920
+ /**
1921
+ * List all metadata category configs for an app. The route returns
1922
+ * `{ configs: [...] }`; unwrap to a bare array to match the other
1923
+ * `list*Configs` helpers.
1924
+ */
1925
+ async listMetadataCategoryConfigs(appId) {
1926
+ const res = await this.get(`/app/${appId}/api/metadata-categories`);
1927
+ return Array.isArray(res?.configs) ? res.configs : [];
1928
+ }
1929
+ async getMetadataCategoryConfig(appId, resourceType, category) {
1930
+ return this.get(`/app/${appId}/api/metadata-categories/${encodeURIComponent(resourceType)}/${encodeURIComponent(category)}`);
1931
+ }
1932
+ /**
1933
+ * Create or replace a metadata category config (idempotent upsert via the
1934
+ * path-addressed PUT route). `resourceType` / `category` identify the config;
1935
+ * the body carries `schema` / `readRule` / `writeRule` / `description`.
1936
+ */
1937
+ async upsertMetadataCategoryConfig(appId, resourceType, category, data) {
1938
+ return this.put(`/app/${appId}/api/metadata-categories/${encodeURIComponent(resourceType)}/${encodeURIComponent(category)}`, data);
1939
+ }
1940
+ /**
1941
+ * Delete a metadata category config (issue #1426, admin-gated route shipped
1942
+ * in #1364). Orphan semantics: the config row is hard-deleted; any stored
1943
+ * `ResourceMetadata` value rows for the category are left behind and become
1944
+ * unreachable (no query path from a category to its values). Delete the
1945
+ * values first if you need them gone — an orphaned value row can't be
1946
+ * removed through any surface once its config is gone. Returns
1947
+ * `{ resourceType, category, deleted }`; a missing config is a 404.
1948
+ */
1949
+ async deleteMetadataCategoryConfig(appId, resourceType, category) {
1950
+ return this.delete(`/app/${appId}/api/metadata-categories/${encodeURIComponent(resourceType)}/${encodeURIComponent(category)}`);
1951
+ }
1952
+ // ============================================
1953
+ // ACCESS RULE SETS
1954
+ // ============================================
1955
+ async listRuleSets(appId, params) {
1956
+ return this.get(`/app/${appId}/api/rule-sets`, params);
1957
+ }
1958
+ async createRuleSet(appId, data) {
1959
+ return this.post(`/app/${appId}/api/rule-sets`, data);
1960
+ }
1961
+ async getRuleSet(appId, ruleSetId) {
1962
+ return this.get(`/app/${appId}/api/rule-sets/${ruleSetId}`);
1963
+ }
1964
+ async updateRuleSet(appId, ruleSetId, data, expectedModifiedAt) {
1965
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
1966
+ return this.patch(`/app/${appId}/api/rule-sets/${ruleSetId}`, body);
1967
+ }
1968
+ async deleteRuleSet(appId, ruleSetId) {
1969
+ return this.delete(`/app/${appId}/api/rule-sets/${ruleSetId}`);
1970
+ }
1971
+ async getRuleSetSchema(appId) {
1972
+ return this.get(`/app/${appId}/api/rule-sets/schema`);
1973
+ }
1974
+ async getRuleSetResourceTypes(appId) {
1975
+ return this.get(`/app/${appId}/api/rule-sets/resource-types`);
1976
+ }
1977
+ async testRuleSet(appId, ruleSetId, data) {
1978
+ return this.post(`/app/${appId}/api/rule-sets/${ruleSetId}/test`, data);
1979
+ }
1980
+ async debugRuleSet(appId, data) {
1981
+ return this.post(`/app/${appId}/api/rule-sets/debug`, data);
1982
+ }
1983
+ // ============================================
1984
+ // GROUP TYPE CONFIGS
1985
+ // ============================================
1986
+ async listGroupTypeConfigs(appId) {
1987
+ return this.get(`/app/${appId}/api/group-type-configs`);
1988
+ }
1989
+ async getGroupTypeConfig(appId, groupType) {
1990
+ return this.get(`/app/${appId}/api/group-type-configs/${groupType}`);
1991
+ }
1992
+ async createGroupTypeConfig(appId, data) {
1993
+ return this.post(`/app/${appId}/api/group-type-configs`, data);
1994
+ }
1995
+ async updateGroupTypeConfig(appId, groupType, data, expectedModifiedAt) {
1996
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
1997
+ return this.patch(`/app/${appId}/api/group-type-configs/${groupType}`, body);
1998
+ }
1999
+ async deleteGroupTypeConfig(appId, groupType) {
2000
+ return this.delete(`/app/${appId}/api/group-type-configs/${groupType}`);
2001
+ }
2002
+ // ============================================
2003
+ // DOCUMENT EXPORT / IMPORT
2004
+ // ============================================
2005
+ async exportDocumentState(appId, documentId) {
2006
+ return this.get(`/app/${appId}/api/documents/${documentId}/export/state`);
2007
+ }
2008
+ async importDocumentState(appId, documentId, stateBase64) {
2009
+ return this.post(`/app/${appId}/api/documents/${documentId}/import/state`, { state: stateBase64 });
2010
+ }
2011
+ async getDocument(appId, documentId) {
2012
+ return this.get(`/app/${appId}/api/documents/${documentId}`);
2013
+ }
2014
+ /**
2015
+ * Introspect a document's Yjs schema (model names, per-model fields and
2016
+ * indexes). Backs `documents records models` and `documents records
2017
+ * describe`. Reuses the existing `GET documents/:id/schema` endpoint.
2018
+ */
2019
+ async getDocumentSchema(appId, documentId) {
2020
+ return this.get(`/app/${appId}/api/documents/${documentId}/schema`);
2021
+ }
2022
+ /**
2023
+ * Query records in a document model (issue #1964 Phase 3). Reuses the
2024
+ * server-side `GET documents/:id/records/:model` endpoint, which runs
2025
+ * through the caller's document permission (reader+) or the app-admin arm.
2026
+ * Returns the unified `{ items, hasMore, nextCursor? }` envelope. The cursor
2027
+ * is an opaque token — feed `nextCursor` back as `cursor` for the next page.
2028
+ * The server also dual-emits a deprecated `cursor` alias (#1316); the
2029
+ * normalizer drops it so CLI output is already on `nextCursor` when #1982
2030
+ * removes it.
2031
+ */
2032
+ async queryDocumentRecords(appId, documentId, modelName, queryOptions) {
2033
+ const query = {};
2034
+ if (queryOptions?.filter)
2035
+ query.filter = JSON.stringify(queryOptions.filter);
2036
+ // Forward `limit` whenever the caller supplied one (including an invalid
2037
+ // 0/negative) so the server validates and returns a clean 400 rather than
2038
+ // silently applying the default.
2039
+ if (queryOptions?.limit !== undefined)
2040
+ query.limit = queryOptions.limit;
2041
+ if (queryOptions?.cursor)
2042
+ query.cursor = queryOptions.cursor;
2043
+ const raw = await this.get(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}`, query);
2044
+ return normalizeCliListEnvelope(raw);
2045
+ }
2046
+ /**
2047
+ * Count records in a document model (issue #1964 Phase 3). Returns `{ count }`.
2048
+ */
2049
+ async countDocumentRecords(appId, documentId, modelName, queryOptions) {
2050
+ const query = {};
2051
+ if (queryOptions?.filter)
2052
+ query.filter = JSON.stringify(queryOptions.filter);
2053
+ return this.get(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/count`, query);
2054
+ }
2055
+ /**
2056
+ * Aggregate records in a document model (issue #2437) — the documents twin
2057
+ * of {@link aggregateDatabaseRecords}. `POST documents/:id/records/:model/aggregate`
2058
+ * with `{ options: { operations, groupBy?, filter? } }`, answering `{ result }`
2059
+ * in the same shape as the database endpoint.
2060
+ *
2061
+ * `groupBy` takes plain field names only: StringSet facet grouping and
2062
+ * `{ field, contains }` membership grouping are database-only, which is why
2063
+ * this signature is narrower than the databases one.
2064
+ */
2065
+ async aggregateDocumentRecords(appId, documentId, modelName, options) {
2066
+ return this.post(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/aggregate`, { options });
2067
+ }
2068
+ /**
2069
+ * Fetch platform-vocabulary document statistics (issue #1964 Phase 3):
2070
+ * record/model/blob counts, approximate size, and last-modified timestamp.
2071
+ */
2072
+ async getDocumentStats(appId, documentId) {
2073
+ return this.get(`/app/${appId}/api/documents/${documentId}/stats`);
2074
+ }
2075
+ /**
2076
+ * Create or replace a record in a document model (issue #1964 Phase 4).
2077
+ * `POST documents/:id/records/:model` with `{ id, data, options? }` —
2078
+ * server-side write through the document facade (Yjs-first, CRDT-safe,
2079
+ * broadcasts to connected clients). Requires read-write+ on the document
2080
+ * or the app-admin arm. Returns `{ record }`.
2081
+ */
2082
+ async saveDocumentRecord(appId, documentId, modelName, body) {
2083
+ return this.post(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}`, body);
2084
+ }
2085
+ /**
2086
+ * Merge fields into an existing record (issue #1964 Phase 4).
2087
+ * `PATCH documents/:id/records/:model/:recordId` with `{ data, options? }`.
2088
+ * Returns `{ record }`.
2089
+ */
2090
+ async patchDocumentRecord(appId, documentId, modelName, recordId, body) {
2091
+ return this.patch(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/${encodeURIComponent(recordId)}`, body);
2092
+ }
2093
+ /**
2094
+ * Delete a record from a document model (issue #1964 Phase 4).
2095
+ * `DELETE documents/:id/records/:model/:recordId`. A missing record id is
2096
+ * a silent no-op per the facade contract. Returns `{ deleted: true }`.
2097
+ */
2098
+ async deleteDocumentRecord(appId, documentId, modelName, recordId) {
2099
+ return this.delete(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/${encodeURIComponent(recordId)}`);
2100
+ }
2101
+ /**
2102
+ * Apply an ordered multi-model create/patch/delete blob atomically (issue
2103
+ * #1964 Phase 4, wrapping the #1517 `bulkUpdate` facade). All-or-nothing:
2104
+ * a validation failure commits nothing. Returns the facade's
2105
+ * `{ applied, added, updated, deleted }`.
2106
+ */
2107
+ async bulkDocumentRecords(appId, documentId, operations) {
2108
+ return this.post(`/app/${appId}/api/documents/${documentId}/records/bulk`, { operations });
2109
+ }
2110
+ async createDocument(appId, data) {
2111
+ return this.post(`/app/${appId}/api/documents`, data);
2112
+ }
2113
+ async listDocumentPermissions(appId, documentId) {
2114
+ return this.get(`/app/${appId}/api/documents/${documentId}/permissions`);
2115
+ }
2116
+ async grantDocumentPermission(appId, documentId, permissions) {
2117
+ return this.put(`/app/${appId}/api/documents/${documentId}/permissions`, { permissions });
2118
+ }
2119
+ /**
2120
+ * Revoke a user's permission on a document. Mirrors the published client's
2121
+ * `documents.removePermission` wire behavior (`src/client/api/documentsApi.ts`):
2122
+ * a userId targets the path route `DELETE .../permissions/:userId`, while an
2123
+ * email targets the query-param route `DELETE .../permissions?email=...`
2124
+ * (unified email removal, #452). This duplication of the client's wire shape
2125
+ * is deliberate and parity-tested (issue #1964 amendment 8).
2126
+ */
2127
+ async revokeDocumentPermission(appId, documentId, target) {
2128
+ if (target.email) {
2129
+ const email = encodeURIComponent(target.email);
2130
+ return this.delete(`/app/${appId}/api/documents/${documentId}/permissions?email=${email}`);
2131
+ }
2132
+ if (!target.userId) {
2133
+ throw new Error("revokeDocumentPermission: userId or email is required");
2134
+ }
2135
+ return this.delete(`/app/${appId}/api/documents/${documentId}/permissions/${target.userId}`);
2136
+ }
2137
+ async getDocumentLinkAccess(appId, documentId) {
2138
+ return this.get(`/app/${appId}/api/documents/${documentId}/link-access`);
2139
+ }
2140
+ async setDocumentLinkAccess(appId, documentId, level) {
2141
+ return this.put(`/app/${appId}/api/documents/${documentId}/link-access`, { level });
2142
+ }
2143
+ async clearDocumentLinkAccess(appId, documentId) {
2144
+ return this.delete(`/app/${appId}/api/documents/${documentId}/link-access`);
2145
+ }
2146
+ async listDocumentInvitations(appId, documentId) {
2147
+ return this.get(`/app/${appId}/api/documents/${documentId}/invitations`);
2148
+ }
2149
+ async listDocumentBlobs(appId, documentId) {
2150
+ return this.get(`/app/${appId}/api/documents/${documentId}/blobs`);
2151
+ }
2152
+ async downloadBlob(appId, documentId, blobId) {
2153
+ const credentials = await this.ensureAuthenticated();
2154
+ const url = `${credentials.serverUrl}/app/${appId}/api/documents/${documentId}/blobs/${blobId}/download`;
2155
+ const headers = {
2156
+ Authorization: `Bearer ${credentials.accessToken}`,
2157
+ };
2158
+ if (credentials.globalAdminAppId) {
2159
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2160
+ }
2161
+ const response = await fetchWithTLS(url, { headers });
2162
+ if (!response.ok) {
2163
+ throw new ApiError(`Failed to download blob: ${response.statusText}`, response.status);
2164
+ }
2165
+ const arrayBuffer = await response.arrayBuffer();
2166
+ return Buffer.from(arrayBuffer);
2167
+ }
2168
+ async uploadBlob(appId, documentId, blobId, data, meta) {
2169
+ const credentials = await this.ensureAuthenticated();
2170
+ const url = `${credentials.serverUrl}/app/${appId}/api/documents/${documentId}/blobs/${blobId}`;
2171
+ const headers = {
2172
+ Authorization: `Bearer ${credentials.accessToken}`,
2173
+ "Content-Type": meta.contentType,
2174
+ "X-Blob-Filename": encodeURIComponent(meta.filename),
2175
+ "X-Blob-Size": String(data.length),
2176
+ "X-Blob-Sha256": meta.sha256,
2177
+ };
2178
+ if (credentials.globalAdminAppId) {
2179
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2180
+ }
2181
+ const response = await fetchWithTLS(url, {
2182
+ method: "PUT",
2183
+ headers,
2184
+ body: data,
2185
+ });
2186
+ if (!response.ok) {
2187
+ const text = await response.text();
2188
+ throw new ApiError(`Failed to upload blob: ${text}`, response.status);
2189
+ }
2190
+ return response.json();
2191
+ }
2192
+ async listDocumentAliases(appId, documentId) {
2193
+ return this.get(`/app/${appId}/api/documents/${documentId}/aliases`);
2194
+ }
2195
+ async setDocumentAlias(appId, aliasScope, aliasKey, documentId, ownerUserId, mustNotExist) {
2196
+ return this.put(`/app/${appId}/api/document-aliases/${aliasScope}/${encodeURIComponent(aliasKey)}`, {
2197
+ documentId,
2198
+ userId: ownerUserId,
2199
+ mustNotExist,
2200
+ });
2201
+ }
2202
+ async findUserByEmail(appId, email) {
2203
+ try {
2204
+ const result = await this.get(`/app/${appId}/api/users`, { email });
2205
+ const items = result?.items || (Array.isArray(result) ? result : []);
2206
+ return items[0] || null;
2207
+ }
2208
+ catch {
2209
+ return null;
2210
+ }
2211
+ }
2212
+ async listAdminDocuments(appId, userId) {
2213
+ const result = await this.get(`/admin/api/apps/${appId}/documents`, { userId });
2214
+ return result?.documents || result || [];
2215
+ }
2216
+ // ============================================
2217
+ // DATABASE EXPORT / IMPORT
2218
+ // ============================================
2219
+ // `saveDatabaseRecord` lives with the other record verbs under
2220
+ // "DATABASE RECORDS & SCHEMA" above.
2221
+ /**
2222
+ * Apply an ordered batch of record operations via `records/batch`.
2223
+ *
2224
+ * `atomic` (default off, matching the DatabaseDO) makes the whole batch
2225
+ * all-or-nothing: the DO rolls every write back at the first failed
2226
+ * operation and answers with that operation's status. `databases records
2227
+ * bulk` sends `atomic: true` so it matches the documents twin's
2228
+ * all-or-nothing contract (#2437); the CSV/import paths keep the default
2229
+ * partial-success behavior.
2230
+ */
2231
+ async batchDatabaseRecords(appId, databaseId, operations, options) {
2232
+ const body = { operations };
2233
+ if (options?.atomic)
2234
+ body.atomic = true;
2235
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/batch`, body);
2236
+ }
2237
+ async deleteDatabaseRecord(appId, databaseId, modelName, id) {
2238
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/delete`, { modelName, id });
2239
+ }
2240
+ async batchDeleteDatabaseRecords(appId, databaseId, operations) {
2241
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/batch`, { operations });
2242
+ }
2243
+ async listDatabaseUniqueConstraints(appId, databaseId) {
2244
+ const result = await this.get(`/app/${appId}/api/databases/${databaseId}/records/unique-constraints`);
2245
+ return result?.constraints || result || [];
2246
+ }
2247
+ async registerDatabaseUniqueConstraint(appId, databaseId, constraint) {
2248
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/unique-constraint/register`, constraint);
2249
+ }
2250
+ // ============================================
2251
+ // BLOB BUCKETS
2252
+ // ============================================
2253
+ async listBlobBuckets(appId) {
2254
+ return this.get(`/app/${appId}/api/blob-buckets`);
2255
+ }
2256
+ async createBlobBucket(appId, payload) {
2257
+ return this.post(`/app/${appId}/api/blob-buckets`, payload);
2258
+ }
2259
+ async getBlobBucket(appId, bucketIdOrKey) {
2260
+ return this.get(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}`);
2261
+ }
2262
+ async updateBlobBucket(appId, bucketIdOrKey, payload) {
2263
+ return this.patch(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}`, payload);
2264
+ }
2265
+ async deleteBlobBucket(appId, bucketIdOrKey) {
2266
+ return this.delete(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}`);
2267
+ }
2268
+ async listBucketBlobs(appId, bucketIdOrKey, params) {
2269
+ const result = await this.get(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs`, params);
2270
+ // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias
2271
+ // so the CLI keeps paginating against pre-#1316 servers.
2272
+ const nextCursor = result?.nextCursor ?? result?.cursor;
2273
+ return {
2274
+ items: result?.items ?? [],
2275
+ nextCursor,
2276
+ hasMore: result?.hasMore ?? nextCursor != null,
2277
+ cursor: nextCursor,
2278
+ };
2279
+ }
2280
+ async uploadBucketBlob(appId, bucketIdOrKey, data, meta) {
2281
+ const credentials = await this.ensureAuthenticated();
2282
+ const url = `${credentials.serverUrl}/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs`;
2283
+ const headers = {
2284
+ Authorization: `Bearer ${credentials.accessToken}`,
2285
+ "Content-Type": meta.contentType,
2286
+ "X-Blob-Filename": encodeURIComponent(meta.filename),
2287
+ };
2288
+ if (meta.tags && meta.tags.length > 0) {
2289
+ headers["X-Blob-Tags"] = JSON.stringify(meta.tags);
2290
+ }
2291
+ if (credentials.globalAdminAppId) {
2292
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2293
+ }
2294
+ const response = await fetchWithTLS(url, {
2295
+ method: "POST",
2296
+ headers,
2297
+ body: data,
2298
+ });
2299
+ if (!response.ok) {
2300
+ const text = await response.text();
2301
+ throw new ApiError(`Failed to upload blob: ${text}`, response.status);
2302
+ }
2303
+ return response.json();
2304
+ }
2305
+ async downloadBucketBlob(appId, bucketIdOrKey, blobId) {
2306
+ const credentials = await this.ensureAuthenticated();
2307
+ const url = `${credentials.serverUrl}/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}`;
2308
+ const headers = {
2309
+ Authorization: `Bearer ${credentials.accessToken}`,
2310
+ };
2311
+ if (credentials.globalAdminAppId) {
2312
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2313
+ }
2314
+ const response = await fetchWithTLS(url, { headers });
2315
+ if (!response.ok) {
2316
+ throw new ApiError(`Failed to download blob: ${response.statusText}`, response.status);
2317
+ }
2318
+ const arrayBuffer = await response.arrayBuffer();
2319
+ return Buffer.from(arrayBuffer);
2320
+ }
2321
+ async deleteBucketBlob(appId, bucketIdOrKey, blobId) {
2322
+ return this.delete(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}`);
2323
+ }
2324
+ // Batch delete (#1455): one round-trip for N ids via POST .../blobs/delete.
2325
+ async deleteBucketBlobs(appId, bucketIdOrKey, blobIds) {
2326
+ return this.post(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/delete`, { blobIds });
2327
+ }
2328
+ async getBucketBlobSignedUrl(appId, bucketIdOrKey, blobId, expiresInSeconds) {
2329
+ return this.post(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}/signed-url`, {
2330
+ expiresInSeconds: expiresInSeconds || 300,
2331
+ });
2332
+ }
2333
+ // Blob metadata (#1966): head a single blob without downloading its bytes.
2334
+ // Mirrors listBucketBlobs/downloadBucketBlob addressing; the server heads the
2335
+ // R2 object and returns the serialized BlobInfo shape.
2336
+ async getBucketBlobMetadata(appId, bucketIdOrKey, blobId) {
2337
+ return this.get(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}/metadata`);
2338
+ }
787
2339
  }
788
2340
  // Export a singleton instance
789
2341
  export const apiClient = new ApiClient();