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

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 (590) hide show
  1. package/README.md +303 -186
  2. package/assets/skill/skills/primitive-platform/SKILL.md +93 -27
  3. package/dist/bin/primitive.js +15 -89
  4. package/dist/bin/primitive.js.map +1 -1
  5. package/dist/src/commands/admins.js +80 -17
  6. package/dist/src/commands/admins.js.map +1 -1
  7. package/dist/src/commands/agent-sessions.d.ts +129 -0
  8. package/dist/src/commands/agent-sessions.js +532 -20
  9. package/dist/src/commands/agent-sessions.js.map +1 -1
  10. package/dist/src/commands/analytics.js +207 -155
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps-children.js +3 -0
  13. package/dist/src/commands/apps-children.js.map +1 -1
  14. package/dist/src/commands/apps-transitions.d.ts +39 -0
  15. package/dist/src/commands/apps-transitions.js +198 -0
  16. package/dist/src/commands/apps-transitions.js.map +1 -0
  17. package/dist/src/commands/apps.d.ts +17 -0
  18. package/dist/src/commands/apps.js +108 -3
  19. package/dist/src/commands/apps.js.map +1 -1
  20. package/dist/src/commands/auth-sessions.js +2 -0
  21. package/dist/src/commands/auth-sessions.js.map +1 -1
  22. package/dist/src/commands/auth.js +170 -50
  23. package/dist/src/commands/auth.js.map +1 -1
  24. package/dist/src/commands/blob-buckets.js +2 -0
  25. package/dist/src/commands/blob-buckets.js.map +1 -1
  26. package/dist/src/commands/collections.js +318 -256
  27. package/dist/src/commands/collections.js.map +1 -1
  28. package/dist/src/commands/comparisons.js +2 -0
  29. package/dist/src/commands/comparisons.js.map +1 -1
  30. package/dist/src/commands/config.d.ts +2 -2
  31. package/dist/src/commands/config.js +59 -33
  32. package/dist/src/commands/config.js.map +1 -1
  33. package/dist/src/commands/connections.js +2 -0
  34. package/dist/src/commands/connections.js.map +1 -1
  35. package/dist/src/commands/database-type-configs.js +5 -3
  36. package/dist/src/commands/database-type-configs.js.map +1 -1
  37. package/dist/src/commands/databases.js +6 -4
  38. package/dist/src/commands/databases.js.map +1 -1
  39. package/dist/src/commands/db3-types.d.ts +42 -0
  40. package/dist/src/commands/db3-types.js +445 -0
  41. package/dist/src/commands/db3-types.js.map +1 -0
  42. package/dist/src/commands/db3.d.ts +38 -0
  43. package/dist/src/commands/db3.js +2053 -0
  44. package/dist/src/commands/db3.js.map +1 -0
  45. package/dist/src/commands/documents.d.ts +110 -10
  46. package/dist/src/commands/documents.js +1019 -748
  47. package/dist/src/commands/documents.js.map +1 -1
  48. package/dist/src/commands/email-templates.js +74 -0
  49. package/dist/src/commands/email-templates.js.map +1 -1
  50. package/dist/src/commands/env.js +8 -4
  51. package/dist/src/commands/env.js.map +1 -1
  52. package/dist/src/commands/function-trigger-commands.d.ts +28 -0
  53. package/dist/src/commands/function-trigger-commands.js +341 -0
  54. package/dist/src/commands/function-trigger-commands.js.map +1 -0
  55. package/dist/src/commands/functions.js +383 -32
  56. package/dist/src/commands/functions.js.map +1 -1
  57. package/dist/src/commands/groups.js +168 -50
  58. package/dist/src/commands/groups.js.map +1 -1
  59. package/dist/src/commands/guides.js +7 -5
  60. package/dist/src/commands/guides.js.map +1 -1
  61. package/dist/src/commands/hosting.d.ts +8 -0
  62. package/dist/src/commands/hosting.js +509 -0
  63. package/dist/src/commands/hosting.js.map +1 -0
  64. package/dist/src/commands/init.js +129 -38
  65. package/dist/src/commands/init.js.map +1 -1
  66. package/dist/src/commands/integrations.js +82 -53
  67. package/dist/src/commands/integrations.js.map +1 -1
  68. package/dist/src/commands/locks.d.ts +5 -3
  69. package/dist/src/commands/locks.js +19 -61
  70. package/dist/src/commands/locks.js.map +1 -1
  71. package/dist/src/commands/metadata-category-configs.d.ts +2 -2
  72. package/dist/src/commands/metadata-category-configs.js +4 -2
  73. package/dist/src/commands/metadata-category-configs.js.map +1 -1
  74. package/dist/src/commands/metadata.js +55 -6
  75. package/dist/src/commands/metadata.js.map +1 -1
  76. package/dist/src/commands/prompts.js +75 -52
  77. package/dist/src/commands/prompts.js.map +1 -1
  78. package/dist/src/commands/rate-counters.d.ts +19 -0
  79. package/dist/src/commands/rate-counters.js +104 -0
  80. package/dist/src/commands/rate-counters.js.map +1 -0
  81. package/dist/src/commands/rule-sets.d.ts +1 -1
  82. package/dist/src/commands/rule-sets.js +2 -1
  83. package/dist/src/commands/rule-sets.js.map +1 -1
  84. package/dist/src/commands/schemas.d.ts +15 -0
  85. package/dist/src/commands/schemas.js +122 -0
  86. package/dist/src/commands/schemas.js.map +1 -0
  87. package/dist/src/commands/scripts.d.ts +9 -17
  88. package/dist/src/commands/scripts.js +24 -479
  89. package/dist/src/commands/scripts.js.map +1 -1
  90. package/dist/src/commands/secrets.d.ts +38 -0
  91. package/dist/src/commands/secrets.js +148 -6
  92. package/dist/src/commands/secrets.js.map +1 -1
  93. package/dist/src/commands/sessions.js +2 -0
  94. package/dist/src/commands/sessions.js.map +1 -1
  95. package/dist/src/commands/skill.js +2 -0
  96. package/dist/src/commands/skill.js.map +1 -1
  97. package/dist/src/commands/spent-tokens.d.ts +19 -0
  98. package/dist/src/commands/spent-tokens.js +79 -0
  99. package/dist/src/commands/spent-tokens.js.map +1 -0
  100. package/dist/src/commands/sync-app-settings.d.ts +58 -0
  101. package/dist/src/commands/sync-app-settings.js +119 -2
  102. package/dist/src/commands/sync-app-settings.js.map +1 -1
  103. package/dist/src/commands/sync-schemas.d.ts +202 -0
  104. package/dist/src/commands/sync-schemas.js +629 -0
  105. package/dist/src/commands/sync-schemas.js.map +1 -0
  106. package/dist/src/commands/sync-user-properties.d.ts +118 -0
  107. package/dist/src/commands/sync-user-properties.js +276 -0
  108. package/dist/src/commands/sync-user-properties.js.map +1 -0
  109. package/dist/src/commands/sync.d.ts +578 -546
  110. package/dist/src/commands/sync.js +3516 -5134
  111. package/dist/src/commands/sync.js.map +1 -1
  112. package/dist/src/commands/tokens.js +5 -3
  113. package/dist/src/commands/tokens.js.map +1 -1
  114. package/dist/src/commands/transitions.d.ts +54 -0
  115. package/dist/src/commands/transitions.js +418 -0
  116. package/dist/src/commands/transitions.js.map +1 -0
  117. package/dist/src/commands/usage.d.ts +42 -0
  118. package/dist/src/commands/usage.js +397 -0
  119. package/dist/src/commands/usage.js.map +1 -0
  120. package/dist/src/commands/user-properties.d.ts +14 -0
  121. package/dist/src/commands/user-properties.js +79 -0
  122. package/dist/src/commands/user-properties.js.map +1 -0
  123. package/dist/src/commands/users.js +951 -18
  124. package/dist/src/commands/users.js.map +1 -1
  125. package/dist/src/commands/vars.js +2 -0
  126. package/dist/src/commands/vars.js.map +1 -1
  127. package/dist/src/commands/waitlist.js +39 -4
  128. package/dist/src/commands/waitlist.js.map +1 -1
  129. package/dist/src/commands/workflows.d.ts +5 -83
  130. package/dist/src/commands/workflows.js +57 -2282
  131. package/dist/src/commands/workflows.js.map +1 -1
  132. package/dist/src/lib/analytics-query.d.ts +58 -0
  133. package/dist/src/lib/analytics-query.js +134 -0
  134. package/dist/src/lib/analytics-query.js.map +1 -0
  135. package/dist/src/lib/api-client.d.ts +1976 -431
  136. package/dist/src/lib/api-client.js +1095 -550
  137. package/dist/src/lib/api-client.js.map +1 -1
  138. package/dist/src/lib/app-settings-descriptor.d.ts +14 -2
  139. package/dist/src/lib/app-settings-descriptor.js +55 -1
  140. package/dist/src/lib/app-settings-descriptor.js.map +1 -1
  141. package/dist/src/lib/auth-fixtures.d.ts +44 -0
  142. package/dist/src/lib/auth-fixtures.js +61 -0
  143. package/dist/src/lib/auth-fixtures.js.map +1 -0
  144. package/dist/src/lib/auth-flow.d.ts +47 -1
  145. package/dist/src/lib/auth-flow.js +451 -14
  146. package/dist/src/lib/auth-flow.js.map +1 -1
  147. package/dist/src/lib/block-layout.d.ts +12 -23
  148. package/dist/src/lib/block-layout.js +26 -92
  149. package/dist/src/lib/block-layout.js.map +1 -1
  150. package/dist/src/lib/block-selector.d.ts +8 -14
  151. package/dist/src/lib/block-selector.js +8 -19
  152. package/dist/src/lib/block-selector.js.map +1 -1
  153. package/dist/src/lib/child-apps-local.d.ts +3 -1
  154. package/dist/src/lib/child-apps-local.js +9 -1
  155. package/dist/src/lib/child-apps-local.js.map +1 -1
  156. package/dist/src/lib/cli-manifest.d.ts +9 -0
  157. package/dist/src/lib/cli-manifest.js +10 -1
  158. package/dist/src/lib/cli-manifest.js.map +1 -1
  159. package/dist/src/lib/cli-version.d.ts +14 -0
  160. package/dist/src/lib/cli-version.js +38 -0
  161. package/dist/src/lib/cli-version.js.map +1 -0
  162. package/dist/src/lib/codegen-shared/prettierStable.d.ts +41 -0
  163. package/dist/src/lib/codegen-shared/prettierStable.js +146 -24
  164. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -1
  165. package/dist/src/lib/collection-export.d.ts +76 -15
  166. package/dist/src/lib/collection-export.js +116 -23
  167. package/dist/src/lib/collection-export.js.map +1 -1
  168. package/dist/src/lib/collection-principal.d.ts +22 -0
  169. package/dist/src/lib/collection-principal.js +35 -0
  170. package/dist/src/lib/collection-principal.js.map +1 -0
  171. package/dist/src/lib/command-groups.d.ts +30 -0
  172. package/dist/src/lib/command-groups.js +111 -0
  173. package/dist/src/lib/command-groups.js.map +1 -0
  174. package/dist/src/lib/command-status.d.ts +147 -0
  175. package/dist/src/lib/command-status.js +266 -0
  176. package/dist/src/lib/command-status.js.map +1 -0
  177. package/dist/src/lib/config-object-descriptor.d.ts +9 -22
  178. package/dist/src/lib/config-object-descriptor.js +113 -277
  179. package/dist/src/lib/config-object-descriptor.js.map +1 -1
  180. package/dist/src/lib/config-surface.d.ts +3 -7
  181. package/dist/src/lib/config-surface.js +9 -13
  182. package/dist/src/lib/config-surface.js.map +1 -1
  183. package/dist/src/lib/config-toml.d.ts +11 -2
  184. package/dist/src/lib/config-toml.js +25 -2
  185. package/dist/src/lib/config-toml.js.map +1 -1
  186. package/dist/src/lib/credentials-home.d.ts +7 -0
  187. package/dist/src/lib/credentials-home.js +45 -10
  188. package/dist/src/lib/credentials-home.js.map +1 -1
  189. package/dist/src/lib/credentials-lock.d.ts +14 -6
  190. package/dist/src/lib/credentials-lock.js +90 -10
  191. package/dist/src/lib/credentials-lock.js.map +1 -1
  192. package/dist/src/lib/credentials-store.d.ts +142 -70
  193. package/dist/src/lib/credentials-store.js +420 -111
  194. package/dist/src/lib/credentials-store.js.map +1 -1
  195. package/dist/src/lib/custodian.d.ts +8 -0
  196. package/dist/src/lib/custodian.js +18 -0
  197. package/dist/src/lib/custodian.js.map +1 -0
  198. package/dist/src/lib/data-input.d.ts +1 -1
  199. package/dist/src/lib/data-input.js +1 -1
  200. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +1 -1
  201. package/dist/src/lib/db-codegen/dbTsTypes.js +3 -0
  202. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -1
  203. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +40 -1
  204. package/dist/src/lib/db-codegen/dbTypeIR.js +32 -8
  205. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -1
  206. package/dist/src/lib/db-type-records.d.ts +125 -0
  207. package/dist/src/lib/db-type-records.js +237 -0
  208. package/dist/src/lib/db-type-records.js.map +1 -0
  209. package/dist/src/lib/db3-export.d.ts +322 -0
  210. package/dist/src/lib/db3-export.js +767 -0
  211. package/dist/src/lib/db3-export.js.map +1 -0
  212. package/dist/src/lib/db3-index-output.d.ts +116 -0
  213. package/dist/src/lib/db3-index-output.js +223 -0
  214. package/dist/src/lib/db3-index-output.js.map +1 -0
  215. package/dist/src/lib/db3-json-fields.d.ts +49 -0
  216. package/dist/src/lib/db3-json-fields.js +195 -0
  217. package/dist/src/lib/db3-json-fields.js.map +1 -0
  218. package/dist/src/lib/db3-type-archive.d.ts +59 -0
  219. package/dist/src/lib/db3-type-archive.js +95 -0
  220. package/dist/src/lib/db3-type-archive.js.map +1 -0
  221. package/dist/src/lib/db3-type-models.d.ts +148 -0
  222. package/dist/src/lib/db3-type-models.js +583 -0
  223. package/dist/src/lib/db3-type-models.js.map +1 -0
  224. package/dist/src/lib/deprecation.d.ts +2 -2
  225. package/dist/src/lib/deprecation.js +2 -2
  226. package/dist/src/lib/document-export-record-log.d.ts +7 -0
  227. package/dist/src/lib/document-export-record-log.js +9 -0
  228. package/dist/src/lib/document-export-record-log.js.map +1 -1
  229. package/dist/src/lib/document-ingest-artifact.d.ts +19 -0
  230. package/dist/src/lib/document-ingest-artifact.js +55 -6
  231. package/dist/src/lib/document-ingest-artifact.js.map +1 -1
  232. package/dist/src/lib/document-ingest-format2.d.ts +36 -0
  233. package/dist/src/lib/document-ingest-format2.js +78 -0
  234. package/dist/src/lib/document-ingest-format2.js.map +1 -0
  235. package/dist/src/lib/document-ingest-input.d.ts +9 -0
  236. package/dist/src/lib/document-ingest-input.js +28 -1
  237. package/dist/src/lib/document-ingest-input.js.map +1 -1
  238. package/dist/src/lib/document-ingest.d.ts +11 -1
  239. package/dist/src/lib/document-ingest.js +16 -0
  240. package/dist/src/lib/document-ingest.js.map +1 -1
  241. package/dist/src/lib/document-schema-rows.d.ts +42 -0
  242. package/dist/src/lib/document-schema-rows.js +53 -0
  243. package/dist/src/lib/document-schema-rows.js.map +1 -0
  244. package/dist/src/lib/experimental-apis.d.ts +36 -0
  245. package/dist/src/lib/experimental-apis.js +46 -0
  246. package/dist/src/lib/experimental-apis.js.map +1 -0
  247. package/dist/src/lib/file-attachment.d.ts +24 -0
  248. package/dist/src/lib/file-attachment.js +31 -0
  249. package/dist/src/lib/file-attachment.js.map +1 -0
  250. package/dist/src/lib/function-authorize-check.d.ts +142 -0
  251. package/dist/src/lib/function-authorize-check.js +311 -0
  252. package/dist/src/lib/function-authorize-check.js.map +1 -0
  253. package/dist/src/lib/function-authorize-view.d.ts +36 -0
  254. package/dist/src/lib/function-authorize-view.js +110 -0
  255. package/dist/src/lib/function-authorize-view.js.map +1 -0
  256. package/dist/src/lib/function-bundle.d.ts +27 -5
  257. package/dist/src/lib/function-bundle.js +142 -7
  258. package/dist/src/lib/function-bundle.js.map +1 -1
  259. package/dist/src/lib/function-collect.d.ts +112 -12
  260. package/dist/src/lib/function-collect.js +601 -12
  261. package/dist/src/lib/function-collect.js.map +1 -1
  262. package/dist/src/lib/function-db-types.d.ts +65 -11
  263. package/dist/src/lib/function-db-types.js +326 -157
  264. package/dist/src/lib/function-db-types.js.map +1 -1
  265. package/dist/src/lib/function-document-types.d.ts +19 -7
  266. package/dist/src/lib/function-document-types.js +24 -12
  267. package/dist/src/lib/function-document-types.js.map +1 -1
  268. package/dist/src/lib/function-grants-preflight.d.ts +99 -0
  269. package/dist/src/lib/function-grants-preflight.js +154 -2
  270. package/dist/src/lib/function-grants-preflight.js.map +1 -1
  271. package/dist/src/lib/function-lint.d.ts +85 -0
  272. package/dist/src/lib/function-lint.js +442 -0
  273. package/dist/src/lib/function-lint.js.map +1 -0
  274. package/dist/src/lib/function-log-row.js +21 -2
  275. package/dist/src/lib/function-log-row.js.map +1 -1
  276. package/dist/src/lib/function-run.d.ts +13 -21
  277. package/dist/src/lib/function-run.js +14 -27
  278. package/dist/src/lib/function-run.js.map +1 -1
  279. package/dist/src/lib/function-schema-codegen.d.ts +86 -22
  280. package/dist/src/lib/function-schema-codegen.js +194 -88
  281. package/dist/src/lib/function-schema-codegen.js.map +1 -1
  282. package/dist/src/lib/function-schema-refs.d.ts +98 -0
  283. package/dist/src/lib/function-schema-refs.js +177 -0
  284. package/dist/src/lib/function-schema-refs.js.map +1 -0
  285. package/dist/src/lib/function-sync.d.ts +120 -6
  286. package/dist/src/lib/function-sync.js +217 -26
  287. package/dist/src/lib/function-sync.js.map +1 -1
  288. package/dist/src/lib/function-trigger-listing.d.ts +11 -6
  289. package/dist/src/lib/function-trigger-listing.js +32 -11
  290. package/dist/src/lib/function-trigger-listing.js.map +1 -1
  291. package/dist/src/lib/function-typecheck.d.ts +52 -0
  292. package/dist/src/lib/function-typecheck.js +174 -54
  293. package/dist/src/lib/function-typecheck.js.map +1 -1
  294. package/dist/src/lib/function-versions.d.ts +2 -0
  295. package/dist/src/lib/function-versions.js +1 -0
  296. package/dist/src/lib/function-versions.js.map +1 -1
  297. package/dist/src/lib/generated-build-flags.d.ts +13 -0
  298. package/dist/src/lib/generated-build-flags.js +14 -0
  299. package/dist/src/lib/generated-build-flags.js.map +1 -0
  300. package/dist/src/lib/generated-command-status.d.ts +6 -0
  301. package/dist/src/lib/generated-command-status.js +502 -0
  302. package/dist/src/lib/generated-command-status.js.map +1 -0
  303. package/dist/src/lib/generated-config-surfaces.d.ts +804 -140
  304. package/dist/src/lib/generated-config-surfaces.js +2491 -1806
  305. package/dist/src/lib/generated-config-surfaces.js.map +1 -1
  306. package/dist/src/lib/generated-sdk-types.d.ts +1 -1
  307. package/dist/src/lib/generated-sdk-types.js +1 -1
  308. package/dist/src/lib/generated-sdk-types.js.map +1 -1
  309. package/dist/src/lib/hosting-build.d.ts +97 -0
  310. package/dist/src/lib/hosting-build.js +204 -0
  311. package/dist/src/lib/hosting-build.js.map +1 -0
  312. package/dist/src/lib/hosting-client.d.ts +167 -0
  313. package/dist/src/lib/hosting-client.js +340 -0
  314. package/dist/src/lib/hosting-client.js.map +1 -0
  315. package/dist/src/lib/hosting-environments.d.ts +32 -0
  316. package/dist/src/lib/hosting-environments.js +74 -0
  317. package/dist/src/lib/hosting-environments.js.map +1 -0
  318. package/dist/src/lib/hosting-errors.d.ts +30 -0
  319. package/dist/src/lib/hosting-errors.js +43 -0
  320. package/dist/src/lib/hosting-errors.js.map +1 -0
  321. package/dist/src/lib/hosting-token.d.ts +46 -0
  322. package/dist/src/lib/hosting-token.js +60 -0
  323. package/dist/src/lib/hosting-token.js.map +1 -0
  324. package/dist/src/lib/hosting-trust-step.d.ts +67 -0
  325. package/dist/src/lib/hosting-trust-step.js +279 -0
  326. package/dist/src/lib/hosting-trust-step.js.map +1 -0
  327. package/dist/src/lib/hosting-trust.d.ts +77 -0
  328. package/dist/src/lib/hosting-trust.js +194 -0
  329. package/dist/src/lib/hosting-trust.js.map +1 -0
  330. package/dist/src/lib/hosting-wait.d.ts +42 -0
  331. package/dist/src/lib/hosting-wait.js +84 -0
  332. package/dist/src/lib/hosting-wait.js.map +1 -0
  333. package/dist/src/lib/hosting-wfp-upload.d.ts +86 -0
  334. package/dist/src/lib/hosting-wfp-upload.js +149 -0
  335. package/dist/src/lib/hosting-wfp-upload.js.map +1 -0
  336. package/dist/src/lib/init-assets.d.ts +2 -6
  337. package/dist/src/lib/init-assets.js +11 -27
  338. package/dist/src/lib/init-assets.js.map +1 -1
  339. package/dist/src/lib/init-ios-links.d.ts +11 -7
  340. package/dist/src/lib/init-ios-links.js +28 -22
  341. package/dist/src/lib/init-ios-links.js.map +1 -1
  342. package/dist/src/lib/init-login-note.d.ts +13 -0
  343. package/dist/src/lib/init-login-note.js +22 -0
  344. package/dist/src/lib/init-login-note.js.map +1 -0
  345. package/dist/src/lib/init-schema.d.ts +15 -0
  346. package/dist/src/lib/init-schema.js +54 -0
  347. package/dist/src/lib/init-schema.js.map +1 -1
  348. package/dist/src/lib/integration-test-request.d.ts +54 -0
  349. package/dist/src/lib/integration-test-request.js +207 -0
  350. package/dist/src/lib/integration-test-request.js.map +1 -0
  351. package/dist/src/lib/invoker-shared-enums.d.ts +35 -0
  352. package/dist/src/lib/invoker-shared-enums.js +98 -0
  353. package/dist/src/lib/invoker-shared-enums.js.map +1 -0
  354. package/dist/src/lib/json-value.d.ts +6 -0
  355. package/dist/src/lib/json-value.js +13 -0
  356. package/dist/src/lib/json-value.js.map +1 -0
  357. package/dist/src/lib/load-routes.d.ts +33 -0
  358. package/dist/src/lib/load-routes.js +35 -0
  359. package/dist/src/lib/load-routes.js.map +1 -0
  360. package/dist/src/lib/log-inspection.d.ts +23 -4
  361. package/dist/src/lib/log-inspection.js +14 -5
  362. package/dist/src/lib/log-inspection.js.map +1 -1
  363. package/dist/src/lib/login-exchange-check.d.ts +18 -0
  364. package/dist/src/lib/login-exchange-check.js +27 -0
  365. package/dist/src/lib/login-exchange-check.js.map +1 -0
  366. package/dist/src/lib/login-scope-lines.d.ts +17 -7
  367. package/dist/src/lib/login-scope-lines.js +33 -10
  368. package/dist/src/lib/login-scope-lines.js.map +1 -1
  369. package/dist/src/lib/metadata-report.d.ts +85 -0
  370. package/dist/src/lib/metadata-report.js +81 -0
  371. package/dist/src/lib/metadata-report.js.map +1 -0
  372. package/dist/src/lib/object-status-filter.d.ts +9 -1
  373. package/dist/src/lib/object-status-filter.js +9 -1
  374. package/dist/src/lib/object-status-filter.js.map +1 -1
  375. package/dist/src/lib/output.d.ts +1 -1
  376. package/dist/src/lib/output.js +3 -1
  377. package/dist/src/lib/output.js.map +1 -1
  378. package/dist/src/lib/pin-refusal-hint.d.ts +12 -0
  379. package/dist/src/lib/pin-refusal-hint.js +35 -0
  380. package/dist/src/lib/pin-refusal-hint.js.map +1 -0
  381. package/dist/src/lib/platform-owned.js +5 -0
  382. package/dist/src/lib/platform-owned.js.map +1 -1
  383. package/dist/src/lib/primitive-declaration-names.d.ts +21 -0
  384. package/dist/src/lib/primitive-declaration-names.js +22 -0
  385. package/dist/src/lib/primitive-declaration-names.js.map +1 -0
  386. package/dist/src/lib/primitive-declaration.d.ts +174 -0
  387. package/dist/src/lib/primitive-declaration.js +871 -0
  388. package/dist/src/lib/primitive-declaration.js.map +1 -0
  389. package/dist/src/lib/primitive-env-plugin.d.ts +99 -0
  390. package/dist/src/lib/primitive-env-plugin.js +408 -0
  391. package/dist/src/lib/primitive-env-plugin.js.map +1 -0
  392. package/dist/src/lib/project-login-apps.d.ts +8 -0
  393. package/dist/src/lib/project-login-apps.js +27 -0
  394. package/dist/src/lib/project-login-apps.js.map +1 -0
  395. package/dist/src/lib/prompt-schema-codegen.d.ts +36 -12
  396. package/dist/src/lib/prompt-schema-codegen.js +96 -100
  397. package/dist/src/lib/prompt-schema-codegen.js.map +1 -1
  398. package/dist/src/lib/prompt-schema-document.d.ts +35 -0
  399. package/dist/src/lib/prompt-schema-document.js +92 -0
  400. package/dist/src/lib/prompt-schema-document.js.map +1 -0
  401. package/dist/src/lib/prompt-schema-refs.d.ts +173 -0
  402. package/dist/src/lib/prompt-schema-refs.js +478 -0
  403. package/dist/src/lib/prompt-schema-refs.js.map +1 -0
  404. package/dist/src/lib/records-verbs.d.ts +79 -0
  405. package/dist/src/lib/records-verbs.js +45 -0
  406. package/dist/src/lib/records-verbs.js.map +1 -0
  407. package/dist/src/lib/refresh-admin-credentials.d.ts +34 -4
  408. package/dist/src/lib/refresh-admin-credentials.js +85 -29
  409. package/dist/src/lib/refresh-admin-credentials.js.map +1 -1
  410. package/dist/src/lib/refresh-stored-login.d.ts +85 -0
  411. package/dist/src/lib/refresh-stored-login.js +233 -0
  412. package/dist/src/lib/refresh-stored-login.js.map +1 -0
  413. package/dist/src/lib/register-commands.d.ts +36 -0
  414. package/dist/src/lib/register-commands.js +37 -0
  415. package/dist/src/lib/register-commands.js.map +1 -0
  416. package/dist/src/lib/retired-imports.d.ts +53 -0
  417. package/dist/src/lib/retired-imports.js +120 -0
  418. package/dist/src/lib/retired-imports.js.map +1 -0
  419. package/dist/src/lib/row-field-rename.d.ts +18 -0
  420. package/dist/src/lib/row-field-rename.js +32 -0
  421. package/dist/src/lib/row-field-rename.js.map +1 -0
  422. package/dist/src/lib/run-status.d.ts +1 -1
  423. package/dist/src/lib/run-status.generated.d.ts +2 -2
  424. package/dist/src/lib/run-status.generated.js +3 -1
  425. package/dist/src/lib/run-status.generated.js.map +1 -1
  426. package/dist/src/lib/run-status.js +1 -1
  427. package/dist/src/lib/schema-codegen/compiledSpace.d.ts +62 -0
  428. package/dist/src/lib/schema-codegen/compiledSpace.js +103 -0
  429. package/dist/src/lib/schema-codegen/compiledSpace.js.map +1 -0
  430. package/dist/src/lib/schema-codegen/generated-db3-bridge.d.ts +86 -0
  431. package/dist/src/lib/schema-codegen/generated-db3-bridge.js +227 -0
  432. package/dist/src/lib/schema-codegen/generated-db3-bridge.js.map +1 -0
  433. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.d.ts +85 -0
  434. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js +86 -0
  435. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js.map +1 -0
  436. package/dist/src/lib/schema-codegen/generated-field-grammar.d.ts +229 -0
  437. package/dist/src/lib/schema-codegen/generated-field-grammar.js +420 -0
  438. package/dist/src/lib/schema-codegen/generated-field-grammar.js.map +1 -0
  439. package/dist/src/lib/schema-codegen/generated-field-table.d.ts +80 -0
  440. package/dist/src/lib/schema-codegen/generated-field-table.js +542 -0
  441. package/dist/src/lib/schema-codegen/generated-field-table.js.map +1 -0
  442. package/dist/src/lib/schema-codegen/generated-prompt-schemas.d.ts +195 -0
  443. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js +503 -0
  444. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js.map +1 -0
  445. package/dist/src/lib/schema-codegen/generated-schema-descriptor.d.ts +258 -0
  446. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js +422 -0
  447. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js.map +1 -0
  448. package/dist/src/lib/schema-codegen/generated-schema-file.d.ts +129 -0
  449. package/dist/src/lib/schema-codegen/generated-schema-file.js +475 -0
  450. package/dist/src/lib/schema-codegen/generated-schema-file.js.map +1 -0
  451. package/dist/src/lib/schema-codegen/generated-schema-provenance.d.ts +115 -0
  452. package/dist/src/lib/schema-codegen/generated-schema-provenance.js +274 -0
  453. package/dist/src/lib/schema-codegen/generated-schema-provenance.js.map +1 -0
  454. package/dist/src/lib/schema-codegen/generated-schema-refs.d.ts +366 -0
  455. package/dist/src/lib/schema-codegen/generated-schema-refs.js +1789 -0
  456. package/dist/src/lib/schema-codegen/generated-schema-refs.js.map +1 -0
  457. package/dist/src/lib/schema-codegen/generated-schema-shape.d.ts +27 -0
  458. package/dist/src/lib/schema-codegen/generated-schema-shape.js +126 -0
  459. package/dist/src/lib/schema-codegen/generated-schema-shape.js.map +1 -0
  460. package/dist/src/lib/schema-codegen/namedRefs.d.ts +56 -0
  461. package/dist/src/lib/schema-codegen/namedRefs.js +143 -0
  462. package/dist/src/lib/schema-codegen/namedRefs.js.map +1 -0
  463. package/dist/src/lib/schema-codegen/naming.d.ts +35 -0
  464. package/dist/src/lib/schema-codegen/naming.js +83 -0
  465. package/dist/src/lib/schema-codegen/naming.js.map +1 -0
  466. package/dist/src/lib/schema-codegen/schemaChanges.d.ts +74 -0
  467. package/dist/src/lib/schema-codegen/schemaChanges.js +277 -0
  468. package/dist/src/lib/schema-codegen/schemaChanges.js.map +1 -0
  469. package/dist/src/lib/schema-codegen/schemaDocs.d.ts +69 -0
  470. package/dist/src/lib/schema-codegen/schemaDocs.js +219 -0
  471. package/dist/src/lib/schema-codegen/schemaDocs.js.map +1 -0
  472. package/dist/src/lib/schema-codegen/schemaIR.d.ts +158 -0
  473. package/dist/src/lib/schema-codegen/schemaIR.js +279 -0
  474. package/dist/src/lib/schema-codegen/schemaIR.js.map +1 -0
  475. package/dist/src/lib/schema-codegen/schemaToTs.d.ts +109 -0
  476. package/dist/src/lib/schema-codegen/schemaToTs.js +269 -0
  477. package/dist/src/lib/schema-codegen/schemaToTs.js.map +1 -0
  478. package/dist/src/lib/schema-codegen/valuesLists.d.ts +48 -0
  479. package/dist/src/lib/schema-codegen/valuesLists.js +144 -0
  480. package/dist/src/lib/schema-codegen/valuesLists.js.map +1 -0
  481. package/dist/src/lib/schema-defs-module.d.ts +29 -0
  482. package/dist/src/lib/schema-defs-module.js +103 -0
  483. package/dist/src/lib/schema-defs-module.js.map +1 -0
  484. package/dist/src/lib/schema-family-index.d.ts +228 -0
  485. package/dist/src/lib/schema-family-index.js +813 -0
  486. package/dist/src/lib/schema-family-index.js.map +1 -0
  487. package/dist/src/lib/schema-pins.d.ts +82 -0
  488. package/dist/src/lib/schema-pins.js +198 -0
  489. package/dist/src/lib/schema-pins.js.map +1 -0
  490. package/dist/src/lib/schema-preview.d.ts +244 -0
  491. package/dist/src/lib/schema-preview.js +498 -0
  492. package/dist/src/lib/schema-preview.js.map +1 -0
  493. package/dist/src/lib/scope-request.d.ts +23 -11
  494. package/dist/src/lib/scope-request.js +69 -31
  495. package/dist/src/lib/scope-request.js.map +1 -1
  496. package/dist/src/lib/session-scope.d.ts +26 -0
  497. package/dist/src/lib/session-scope.js +58 -0
  498. package/dist/src/lib/session-scope.js.map +1 -0
  499. package/dist/src/lib/skill-installer.d.ts +2 -2
  500. package/dist/src/lib/skill-installer.js +2 -21
  501. package/dist/src/lib/skill-installer.js.map +1 -1
  502. package/dist/src/lib/step-run-table.d.ts +1 -2
  503. package/dist/src/lib/step-run-table.js +1 -2
  504. package/dist/src/lib/step-run-table.js.map +1 -1
  505. package/dist/src/lib/swift-codegen/agentGenerator.d.ts +2 -1
  506. package/dist/src/lib/swift-codegen/agentGenerator.js +25 -23
  507. package/dist/src/lib/swift-codegen/agentGenerator.js.map +1 -1
  508. package/dist/src/lib/swift-codegen/banners.d.ts +12 -0
  509. package/dist/src/lib/swift-codegen/banners.js +12 -0
  510. package/dist/src/lib/swift-codegen/banners.js.map +1 -1
  511. package/dist/src/lib/swift-codegen/functionGenerator.d.ts +36 -1
  512. package/dist/src/lib/swift-codegen/functionGenerator.js +169 -51
  513. package/dist/src/lib/swift-codegen/functionGenerator.js.map +1 -1
  514. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +33 -9
  515. package/dist/src/lib/swift-codegen/schemaToSwift.js +215 -179
  516. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -1
  517. package/dist/src/lib/swift-codegen/sharedGenerator.d.ts +51 -0
  518. package/dist/src/lib/swift-codegen/sharedGenerator.js +239 -0
  519. package/dist/src/lib/swift-codegen/sharedGenerator.js.map +1 -0
  520. package/dist/src/lib/swift-codegen/swiftKeys.d.ts +19 -0
  521. package/dist/src/lib/swift-codegen/swiftKeys.js +31 -0
  522. package/dist/src/lib/swift-codegen/swiftKeys.js.map +1 -0
  523. package/dist/src/lib/swift-codegen/userPropertiesGenerator.d.ts +30 -0
  524. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js +69 -0
  525. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js.map +1 -0
  526. package/dist/src/lib/sync-resource-types.d.ts +117 -31
  527. package/dist/src/lib/sync-resource-types.js +197 -189
  528. package/dist/src/lib/sync-resource-types.js.map +1 -1
  529. package/dist/src/lib/sync-selectors.d.ts +7 -0
  530. package/dist/src/lib/sync-selectors.js +22 -2
  531. package/dist/src/lib/sync-selectors.js.map +1 -1
  532. package/dist/src/lib/template.d.ts +39 -3
  533. package/dist/src/lib/template.js +103 -14
  534. package/dist/src/lib/template.js.map +1 -1
  535. package/dist/src/lib/test-case-file-names.d.ts +3 -5
  536. package/dist/src/lib/test-case-file-names.js +3 -5
  537. package/dist/src/lib/test-case-file-names.js.map +1 -1
  538. package/dist/src/lib/test-runs.d.ts +45 -0
  539. package/dist/src/lib/test-runs.js +150 -0
  540. package/dist/src/lib/test-runs.js.map +1 -0
  541. package/dist/src/lib/test-users.d.ts +25 -0
  542. package/dist/src/lib/test-users.js +36 -0
  543. package/dist/src/lib/test-users.js.map +1 -0
  544. package/dist/src/lib/toml-database-config.d.ts +4 -2
  545. package/dist/src/lib/toml-database-config.js +11 -6
  546. package/dist/src/lib/toml-database-config.js.map +1 -1
  547. package/dist/src/lib/toml-list-edit.d.ts +33 -0
  548. package/dist/src/lib/toml-list-edit.js +481 -0
  549. package/dist/src/lib/toml-list-edit.js.map +1 -0
  550. package/dist/src/lib/toml-scalar-edit.d.ts +9 -0
  551. package/dist/src/lib/toml-scalar-edit.js +73 -5
  552. package/dist/src/lib/toml-scalar-edit.js.map +1 -1
  553. package/dist/src/lib/transition-warnings.d.ts +21 -0
  554. package/dist/src/lib/transition-warnings.js +49 -0
  555. package/dist/src/lib/transition-warnings.js.map +1 -0
  556. package/dist/src/lib/usage-meters.d.ts +16 -0
  557. package/dist/src/lib/usage-meters.js +52 -0
  558. package/dist/src/lib/usage-meters.js.map +1 -0
  559. package/dist/src/lib/user-index.d.ts +80 -0
  560. package/dist/src/lib/user-index.js +166 -0
  561. package/dist/src/lib/user-index.js.map +1 -0
  562. package/dist/src/lib/user-properties/generated-properties-schema.d.ts +159 -0
  563. package/dist/src/lib/user-properties/generated-properties-schema.js +471 -0
  564. package/dist/src/lib/user-properties/generated-properties-schema.js.map +1 -0
  565. package/dist/src/lib/user-properties/user-properties-codegen.d.ts +55 -0
  566. package/dist/src/lib/user-properties/user-properties-codegen.js +129 -0
  567. package/dist/src/lib/user-properties/user-properties-codegen.js.map +1 -0
  568. package/dist/src/lib/user-walk.d.ts +31 -0
  569. package/dist/src/lib/user-walk.js +102 -0
  570. package/dist/src/lib/user-walk.js.map +1 -0
  571. package/dist/src/lib/webhook-capture.d.ts +43 -0
  572. package/dist/src/lib/webhook-capture.js +91 -0
  573. package/dist/src/lib/webhook-capture.js.map +1 -0
  574. package/dist/src/lib/webhook-deliver.d.ts +18 -20
  575. package/dist/src/lib/webhook-deliver.js +34 -89
  576. package/dist/src/lib/webhook-deliver.js.map +1 -1
  577. package/dist/src/lib/webhook-test-run.d.ts +32 -0
  578. package/dist/src/lib/webhook-test-run.js +108 -0
  579. package/dist/src/lib/webhook-test-run.js.map +1 -0
  580. package/dist/src/lib/worker-perf-format.d.ts +22 -0
  581. package/dist/src/lib/worker-perf-format.js +27 -0
  582. package/dist/src/lib/worker-perf-format.js.map +1 -0
  583. package/dist/src/types/index.d.ts +20 -65
  584. package/dist/src/validators.d.ts +7 -55
  585. package/dist/src/validators.js +7 -53
  586. package/dist/src/validators.js.map +1 -1
  587. package/dist/src/vite.d.ts +17 -0
  588. package/dist/src/vite.js +18 -0
  589. package/dist/src/vite.js.map +1 -0
  590. package/package.json +20 -9
@@ -0,0 +1,767 @@
1
+ /**
2
+ * `primitive db3 export` and `primitive db3 import` (#4889): a db3 written
3
+ * to a directory, and a directory loaded into a db3.
4
+ *
5
+ * An export is a directory holding `db3.json` (the manifest: the db3's id,
6
+ * title and tags, its type by name and revision, its declaration as
7
+ * `GET db3/:id/schema` answers it, the indexes registered through the index
8
+ * routes, the log number the rows are at), the rows under `snapshot/` (a
9
+ * renamed field under its current name, which an import loads back under
10
+ * its stored name) and `chain.json` as `documents export` writes a
11
+ * record-log document's, and the blobs under `blobs/`. It carries no grant,
12
+ * custody, sync state or alias: those belong to the app the db3 lives in.
13
+ *
14
+ * An import does every check before any write: the manifest's type must be
15
+ * one the app has, with an equal declaration (or `--untyped`); a `--into`
16
+ * target must be of the manifest's type and declare its models alike; and
17
+ * blobs are imported under their ids, so the source db3 must be gone from the
18
+ * app first. Then it creates the db3 (or confirms `--into`), registers the
19
+ * indexes an untyped target needs before any row, loads the rows through the
20
+ * db3's bulk-load session and uploads the blobs.
21
+ *
22
+ * The planner (`planDb3Import`) and the comparison (`compareDeclarations`)
23
+ * are pure; the verbs in `../commands/db3.ts` read what they need and drive
24
+ * the steps.
25
+ */
26
+ import fs from "fs";
27
+ import path from "path";
28
+ import { loadSchemaFromTomlString } from "js-bao";
29
+ import { db3IndexKindAndPlacement } from "./db3-index-output.js";
30
+ import { exportRecordLogDocument } from "./document-export-record-log.js";
31
+ import { discoverIngestInput } from "./document-ingest-input.js";
32
+ import { buildIngestArtifact, ingestSchemaFromIntrospection } from "./document-ingest-artifact.js";
33
+ import { driveDocumentIngest } from "./document-ingest.js";
34
+ /** The manifest file an export writes and an import reads. */
35
+ export const DB3_MANIFEST = "db3.json";
36
+ const isText = (registration) => registration.kind === "text";
37
+ /**
38
+ * The indexes an export records, out of the db3's index list: each one a
39
+ * registration keeps, with the registration's own uniqueness (a
40
+ * declaration's unique on the same index is the declaration's),
41
+ * `members: true` on a member index, its `kind` and `on` as the list
42
+ * gives them (#5220), and a text index's options (#5222).
43
+ */
44
+ export function exportedIndexesOf(listed) {
45
+ return listed.flatMap((index) => {
46
+ const named = (index.origins ?? []).find((origin) => origin?.kind === "named");
47
+ if (!named)
48
+ return [];
49
+ const row = {
50
+ name: index.name,
51
+ model: index.model,
52
+ fields: [...index.fields],
53
+ unique: named.unique === true,
54
+ ...(index.members === true ? { members: true } : {}),
55
+ ...(typeof index.kind === "string" ? { kind: index.kind } : {}),
56
+ ...(typeof index.on === "string" ? { on: index.on } : {}),
57
+ ...(index.kind === "text" && index.text && typeof index.text === "object"
58
+ ? {
59
+ text: {
60
+ tokenizer: index.text.tokenizer,
61
+ prefix: [...(index.text.prefix ?? [])],
62
+ weights: { ...(index.text.weights ?? {}) },
63
+ },
64
+ }
65
+ : {}),
66
+ };
67
+ return [row];
68
+ });
69
+ }
70
+ /** `index`'s kind and placement as the export recorded them, for its registration. */
71
+ const placedOf = (index) => ({
72
+ ...(index.kind !== undefined ? { kind: index.kind } : {}),
73
+ ...(index.on !== undefined ? { on: index.on } : {}),
74
+ });
75
+ /** A model's declaration out of a schema answer's model: its fields and constraints, without `observed`. */
76
+ function modelDeclaration(model) {
77
+ const fields = {};
78
+ for (const [name, options] of Object.entries(model?.fields ?? {}))
79
+ fields[name] = { ...(options ?? {}) };
80
+ const constraints = {};
81
+ for (const [name, c] of Object.entries(model?.constraints ?? {})) {
82
+ if (c && Array.isArray(c.fields))
83
+ constraints[name] = { type: "unique", fields: [...c.fields] };
84
+ }
85
+ return { fields, ...(Object.keys(constraints).length ? { constraints } : {}) };
86
+ }
87
+ /**
88
+ * The declaration `GET db3/:id/schema` answers. The answer gives a declared
89
+ * model with no fields and a live undeclared model alike, `{ fields: {} }`,
90
+ * so such a model is kept only when `declaredModels` names it: the models a
91
+ * typed db3's type declares ({@link declaredModelNames}). A type that
92
+ * declares no models holds any model undeclared, and an untyped db3
93
+ * declares none.
94
+ */
95
+ export function declarationOfSchemaAnswer(answer, options = {}) {
96
+ const declaredModels = new Set(options.declaredModels ?? []);
97
+ const models = {};
98
+ for (const [name, model] of Object.entries(answer?.schema?.models ?? {})) {
99
+ const declaration = modelDeclaration(model);
100
+ const declared = declaredModels.has(name) && model && typeof model === "object" && "fields" in model;
101
+ if (declared || Object.keys(declaration.fields).length || declaration.constraints)
102
+ models[name] = declaration;
103
+ }
104
+ return { models };
105
+ }
106
+ /** The models a db3 type's schema TOML declares, by name. */
107
+ export function declaredModelNames(schema) {
108
+ return Object.keys(declarationOfTypeSchema(schema).models);
109
+ }
110
+ /** The declaration a db3 type's schema TOML installs (`GET db3-types/:name`'s `schema`). */
111
+ export function declarationOfTypeSchema(schema) {
112
+ if (typeof schema !== "string" || !schema.trim())
113
+ return { models: {} };
114
+ const defined = loadSchemaFromTomlString(schema, { strict: false, rejectUniqueStringset: false, vectors: true });
115
+ const models = {};
116
+ for (const model of defined) {
117
+ const fields = {};
118
+ for (const [field, options] of Object.entries(model.fields ?? {})) {
119
+ const kept = {};
120
+ for (const [key, value] of Object.entries(options ?? {})) {
121
+ if (value !== undefined && typeof value !== "function")
122
+ kept[key] = value;
123
+ }
124
+ fields[field] = kept;
125
+ }
126
+ const constraints = {};
127
+ for (const c of model.options?.uniqueConstraints ?? [])
128
+ constraints[c.name] = { type: "unique", fields: [...c.fields] };
129
+ models[model.name] = { fields, ...(Object.keys(constraints).length ? { constraints } : {}) };
130
+ }
131
+ return { models };
132
+ }
133
+ /**
134
+ * `declaration` and `indexes` keyed by stored names: each field under its
135
+ * `storedAs` (or its key), without `storedAs`, and every constraint field
136
+ * and index field that names a renamed field by its key, or by a former
137
+ * name in `formerNames` (a type file's constraint may still name one),
138
+ * named by its stored name. A declaration that renames nothing comes back
139
+ * equal. An export taken before a rename, between two renames or after the
140
+ * latest one normalizes to the same declaration, so the import compares
141
+ * them by what records hold.
142
+ */
143
+ export function storedKeyed(declaration, indexes = [], formerNames = {}) {
144
+ const storedOf = new Map();
145
+ const models = {};
146
+ for (const [name, model] of Object.entries(declaration.models)) {
147
+ const map = new Map();
148
+ // Former names first, so a field's own key wins when a name is both.
149
+ const former = Object.prototype.hasOwnProperty.call(formerNames, name) ? formerNames[name] : undefined;
150
+ for (const [stored, names] of Object.entries(former ?? {})) {
151
+ for (const formerName of Array.isArray(names) ? names : [])
152
+ if (typeof formerName === "string")
153
+ map.set(formerName, stored);
154
+ }
155
+ const fields = {};
156
+ for (const [field, options] of Object.entries(model.fields)) {
157
+ const storedAs = typeof options?.storedAs === "string" && options.storedAs ? options.storedAs : field;
158
+ map.set(field, storedAs);
159
+ const { storedAs: _storedAs, ...rest } = options ?? {};
160
+ Object.defineProperty(fields, storedAs, { value: rest, enumerable: true, writable: true, configurable: true });
161
+ }
162
+ storedOf.set(name, map);
163
+ const toStored = (field) => map.get(field) ?? field;
164
+ const constraints = model.constraints
165
+ ? Object.fromEntries(Object.entries(model.constraints).map(([cname, c]) => [cname, { ...c, fields: c.fields.map(toStored) }]))
166
+ : undefined;
167
+ models[name] = { fields, ...(constraints ? { constraints } : {}) };
168
+ }
169
+ const keyedIndexes = indexes.map((index) => {
170
+ const map = storedOf.get(index.model);
171
+ return map ? { ...index, fields: index.fields.map((field) => map.get(field) ?? field) } : index;
172
+ });
173
+ return { declaration: { models }, indexes: keyedIndexes };
174
+ }
175
+ /**
176
+ * A db3's declaration as an export writes it: the room's declaration (keyed
177
+ * by stored names) with each field a type file renames under its current
178
+ * key, keeping its `storedAs`, and constraint fields named by current keys.
179
+ * The declaration as it is when the type renames nothing.
180
+ */
181
+ export function currentKeyedDeclaration(roomDeclaration, typeSchema) {
182
+ const typed = declarationOfTypeSchema(typeSchema);
183
+ let renames = false;
184
+ const models = {};
185
+ for (const [name, model] of Object.entries(roomDeclaration.models)) {
186
+ const currentOf = new Map();
187
+ for (const [key, options] of Object.entries(typed.models[name]?.fields ?? {})) {
188
+ const storedAs = typeof options?.storedAs === "string" ? options.storedAs : undefined;
189
+ if (storedAs && storedAs !== key)
190
+ currentOf.set(storedAs, key);
191
+ }
192
+ if (!currentOf.size) {
193
+ models[name] = model;
194
+ continue;
195
+ }
196
+ renames = true;
197
+ const fields = {};
198
+ for (const [stored, options] of Object.entries(model.fields)) {
199
+ const key = currentOf.get(stored);
200
+ fields[key ?? stored] = key ? { ...options, storedAs: stored } : options;
201
+ }
202
+ const toCurrent = (field) => currentOf.get(field) ?? field;
203
+ const constraints = model.constraints
204
+ ? Object.fromEntries(Object.entries(model.constraints).map(([cname, c]) => [cname, { ...c, fields: c.fields.map(toCurrent) }]))
205
+ : undefined;
206
+ models[name] = { fields, ...(constraints ? { constraints } : {}) };
207
+ }
208
+ return renames ? { models } : roomDeclaration;
209
+ }
210
+ /**
211
+ * Per model, each field `declaration` renames: its current key and its stored
212
+ * name (`storedAs`). A model that renames nothing is left out, so a
213
+ * declaration that renames nothing gives `{}`.
214
+ */
215
+ export function renamedFieldsOf(declaration) {
216
+ const renamed = {};
217
+ for (const [name, model] of Object.entries(declaration.models)) {
218
+ const names = {};
219
+ for (const [field, options] of Object.entries(model.fields)) {
220
+ const storedAs = options?.storedAs;
221
+ if (typeof storedAs === "string" && storedAs && storedAs !== field) {
222
+ Object.defineProperty(names, field, { value: storedAs, enumerable: true, writable: true, configurable: true });
223
+ }
224
+ }
225
+ if (Object.keys(names).length)
226
+ Object.defineProperty(renamed, name, { value: names, enumerable: true, writable: true, configurable: true });
227
+ }
228
+ return renamed;
229
+ }
230
+ /** `renames` turned around: each model's names map from the name each key took back to the key. */
231
+ function invertedRenames(renames) {
232
+ const inverted = {};
233
+ for (const [model, names] of Object.entries(renames)) {
234
+ const back = {};
235
+ for (const [from, to] of Object.entries(names))
236
+ Object.defineProperty(back, to, { value: from, enumerable: true, writable: true, configurable: true });
237
+ Object.defineProperty(inverted, model, { value: back, enumerable: true, writable: true, configurable: true });
238
+ }
239
+ return inverted;
240
+ }
241
+ /**
242
+ * What a field's declaration is compared by: its kind and its two index
243
+ * flags, and a vector field's encoding too (#5225), which two encodings of
244
+ * the same byte length would otherwise hide.
245
+ */
246
+ function fieldShape(options) {
247
+ return JSON.stringify({
248
+ type: options?.type ?? null,
249
+ indexed: options?.indexed === true,
250
+ unique: options?.unique === true,
251
+ ...(options?.type === "vector" ? { dims: options.dims ?? null, element: options.element ?? null } : {}),
252
+ });
253
+ }
254
+ /** A field's declaration as a difference line names it: a vector field by its encoding (`2 × f32`), any other by its shape. */
255
+ function fieldText(options) {
256
+ if (options?.type !== "vector")
257
+ return fieldShape(options);
258
+ const flags = [options.indexed === true ? "indexed" : "", options.unique === true ? "unique" : ""].filter(Boolean);
259
+ return `a vector of ${String(options.dims)} × ${String(options.element)}${flags.length ? ` (${flags.join(", ")})` : ""}`;
260
+ }
261
+ /** A model's compound constraints, compared by their fields in any order. */
262
+ function constraintKeys(model) {
263
+ return Object.values(model?.constraints ?? {})
264
+ .map((c) => `unique(${[...c.fields].sort().join(", ")})`)
265
+ .sort();
266
+ }
267
+ /**
268
+ * The differences between the declaration an export holds and the one a
269
+ * type or a target installs, one line per model, field or constraint; none
270
+ * when they are equal. Order is ignored: of models, fields, constraints and
271
+ * a constraint's fields. A field compares by its kind and its `indexed` and
272
+ * `unique` flags. With `only: "installed"`, only the models `installed`
273
+ * declares are compared (an `--untyped` import into a target that already
274
+ * declares some of them).
275
+ */
276
+ export function compareDeclarations(exported, installed, options = {}) {
277
+ const where = options.installedName ?? "the target";
278
+ const lines = [];
279
+ const models = new Set([...Object.keys(installed.models), ...(options.only === "installed" ? [] : Object.keys(exported.models))]);
280
+ for (const name of [...models].sort()) {
281
+ const mine = exported.models[name];
282
+ const theirs = installed.models[name];
283
+ if (!theirs) {
284
+ lines.push(`model ${name}: declared by the export, not by ${where}`);
285
+ continue;
286
+ }
287
+ if (!mine) {
288
+ lines.push(`model ${name}: declared by ${where}, not by the export`);
289
+ continue;
290
+ }
291
+ const fields = new Set([...Object.keys(mine.fields), ...Object.keys(theirs.fields)]);
292
+ for (const field of [...fields].sort()) {
293
+ if (!(field in theirs.fields))
294
+ lines.push(`model ${name} field ${field}: declared by the export, not by ${where}`);
295
+ else if (!(field in mine.fields))
296
+ lines.push(`model ${name} field ${field}: declared by ${where}, not by the export`);
297
+ else if (fieldShape(mine.fields[field]) !== fieldShape(theirs.fields[field])) {
298
+ lines.push(`model ${name} field ${field}: the export has ${fieldText(mine.fields[field])}, ${where} has ${fieldText(theirs.fields[field])}`);
299
+ }
300
+ }
301
+ const a = constraintKeys(mine);
302
+ const b = constraintKeys(theirs);
303
+ for (const key of a)
304
+ if (!b.includes(key))
305
+ lines.push(`model ${name} constraint ${key}: declared by the export, not by ${where}`);
306
+ for (const key of b)
307
+ if (!a.includes(key))
308
+ lines.push(`model ${name} constraint ${key}: declared by ${where}, not by the export`);
309
+ }
310
+ return lines;
311
+ }
312
+ /**
313
+ * The index registrations that install `declaration`'s indexes and uniques,
314
+ * and `indexes`, on an untyped db3: one per model and set of fields, unique
315
+ * when either source holds it unique (a registration over the same fields
316
+ * replaces the earlier one's uniqueness, so a later non-unique one would
317
+ * lift it), each compound name a valid identifier no other of the model's
318
+ * registrations takes. A member index wins its field over a declaration's
319
+ * field index, as the room keeps the member row and builds no index for the
320
+ * declaration (#5150); so does an index placed `server` or `device` over a
321
+ * declaration's field index, for the same reason (#5220). A text index
322
+ * stands beside any other kind over the same fields (#5222): it is keyed
323
+ * apart, keeps its fields' order, and is registered with no name or unique.
324
+ * So does a `vector` index (#5225).
325
+ */
326
+ export function registrationsFor(declaration, indexes = []) {
327
+ const out = [];
328
+ const byFields = new Map();
329
+ const names = new Map();
330
+ const add = (registration) => {
331
+ // A `text` or `vector` index stands beside another kind over the same
332
+ // fields (#5222, #5225), so its key names its kind; a scalar and a member
333
+ // index share one, a member index winning its field.
334
+ const kind = registrationPlacement(registration).kind;
335
+ const key = JSON.stringify([registration.model, [...fieldsOf(registration)].sort(), ...(kind === "text" || kind === "vector" ? [kind] : [])]);
336
+ const at = byFields.get(key);
337
+ if (at !== undefined) {
338
+ const held = out[at];
339
+ if ("members" in registration && !("members" in held)) {
340
+ out[at] = registration;
341
+ return;
342
+ }
343
+ const wanted = registrationPlacement(registration);
344
+ const holding = registrationPlacement(held);
345
+ if (registration.on !== undefined && wanted.kind === holding.kind && wanted.on !== holding.on) {
346
+ out[at] = registration;
347
+ return;
348
+ }
349
+ const uniqueWanted = "unique" in registration && registration.unique === true;
350
+ if (uniqueWanted && "field" in held && !("members" in held) && !isText(held) && held.unique !== true)
351
+ out[at] = { ...held, unique: true };
352
+ return;
353
+ }
354
+ if ("name" in registration) {
355
+ const taken = names.get(registration.model) ?? new Set();
356
+ names.set(registration.model, taken);
357
+ // The physical name lower-cases the registration's, so two names a case apart would collide.
358
+ let name = registration.name;
359
+ for (let n = 2; taken.has(name.toLowerCase()); n++)
360
+ name = `${registration.name}_${n}`;
361
+ taken.add(name.toLowerCase());
362
+ registration = { ...registration, name };
363
+ }
364
+ byFields.set(key, out.length);
365
+ out.push(registration);
366
+ };
367
+ for (const model of Object.keys(declaration.models).sort()) {
368
+ const declared = declaration.models[model];
369
+ for (const field of Object.keys(declared.fields).sort()) {
370
+ const options = declared.fields[field];
371
+ // The primary key serves `id`, and a set field takes no index: the room refuses both.
372
+ if (field === "id" || options.type === "stringset")
373
+ continue;
374
+ if (options.unique === true)
375
+ add({ model, field, unique: true });
376
+ else if (options.indexed === true)
377
+ add({ model, field });
378
+ }
379
+ for (const name of Object.keys(declared.constraints ?? {}).sort()) {
380
+ const fields = declared.constraints[name].fields;
381
+ if (fields.length === 1 && fields[0] === "id")
382
+ continue;
383
+ if (fields.length === 1)
384
+ add({ model, field: fields[0], unique: true });
385
+ else
386
+ add({ model, fields: [...fields], name: registrationName(model, name), unique: true });
387
+ }
388
+ }
389
+ for (const index of indexes) {
390
+ const placed = placedOf(index);
391
+ if (index.kind === "text") {
392
+ const covered = index.fields.length === 1 ? { field: index.fields[0] } : { fields: [...index.fields] };
393
+ add({ model: index.model, ...covered, kind: "text", ...(index.on !== undefined ? { on: index.on } : {}), ...(index.text ? { text: index.text } : {}) });
394
+ }
395
+ else if (index.members === true)
396
+ add({ model: index.model, field: index.fields[0], members: true, ...placed });
397
+ else if (index.fields.length === 1) {
398
+ add(index.unique ? { model: index.model, field: index.fields[0], unique: true, ...placed } : { model: index.model, field: index.fields[0], ...placed });
399
+ }
400
+ else
401
+ add({ model: index.model, fields: [...index.fields], name: registrationName(index.model, index.name), unique: true, ...placed });
402
+ }
403
+ return out;
404
+ }
405
+ /** The physical name a registration named `name` on `model` gets (`idx_named_<model>_<name>`, lower-cased). */
406
+ const namedIndexPrefix = (model) => `idx_named_${model.toLowerCase()}_`;
407
+ /**
408
+ * The name to register an index under: the name it was registered with,
409
+ * read back out of the physical name the index list answers; a constraint's
410
+ * own name with the characters an index name cannot hold replaced, and
411
+ * `c_` before one that would not start with a letter or `_` (as the room
412
+ * names a constraint's own index).
413
+ */
414
+ function registrationName(model, name) {
415
+ const prefix = namedIndexPrefix(model);
416
+ const bare = name.startsWith(prefix) && name.length > prefix.length ? name.slice(prefix.length) : name;
417
+ const replaced = bare.replace(/[^A-Za-z0-9_]/g, "_");
418
+ return /^[A-Za-z_]/.test(replaced) ? replaced : `c_${replaced}`;
419
+ }
420
+ const fieldsOf = (registration) => ("fields" in registration ? registration.fields : [registration.field]);
421
+ const sameFields = (a, b) => a.length === b.length && [...a].sort().join("\0") === [...b].sort().join("\0");
422
+ /** A registration's kind and placement, its defaults filled in as the room fills them. */
423
+ function registrationPlacement(registration) {
424
+ return db3IndexKindAndPlacement({ members: "members" in registration, kind: registration.kind, on: registration.on });
425
+ }
426
+ /** Whether two kinds may index the same fields side by side: a `text` or `vector` index beside another kind (#5220). */
427
+ const coexist = (a, b) => a !== b && (a === "text" || a === "vector" || b === "text" || b === "vector");
428
+ /**
429
+ * `register` against the indexes a target already has: a registration an
430
+ * index of its kind over the same fields already serves, as unique or more,
431
+ * is left out (so an existing unique index is never registered again
432
+ * without `unique`, which would lift it, and a constraint the target holds
433
+ * is not registered a second time under another name); a named
434
+ * registration whose name the target gives an index over other fields is a
435
+ * conflict. A member index is served only by a member index on its field,
436
+ * and a field index only by a field index: a target holding the other kind
437
+ * on the field is a conflict. So is a holder of the same kind placed
438
+ * elsewhere (#5220): a placement changes only by drop and register. A
439
+ * registration is pending beside a holder only when their kinds may index
440
+ * the same fields side by side.
441
+ */
442
+ export function pendingRegistrations(register, existing) {
443
+ const out = [];
444
+ const kept = [];
445
+ const conflicts = [];
446
+ for (const registration of register) {
447
+ const fields = fieldsOf(registration);
448
+ // A model has one text index (#5222): the target's over other fields is a conflict.
449
+ const otherText = isText(registration)
450
+ ? existing.find((index) => index.model === registration.model && index.kind === "text" && !sameFields(index.fields, fields))
451
+ : undefined;
452
+ if (otherText) {
453
+ conflicts.push(`${registration.model} (${fields.join(", ")}): the export's text index; the target's ${otherText.name} is over (${otherText.fields.join(", ")}), ` +
454
+ "and a model has one text index");
455
+ continue;
456
+ }
457
+ const wanted = "unique" in registration && registration.unique === true;
458
+ const placement = registrationPlacement(registration);
459
+ const holders = existing.filter((index) => index.model === registration.model && sameFields(index.fields, fields));
460
+ const clash = holders.find((index) => {
461
+ const kind = db3IndexKindAndPlacement(index).kind;
462
+ return kind !== placement.kind && !coexist(kind, placement.kind);
463
+ });
464
+ if (clash) {
465
+ const members = placement.kind === "members";
466
+ conflicts.push(`${registration.model} (${fields.join(", ")}): the export's is ${members ? "a set-element index" : "a field index"}, ` +
467
+ `the target's ${clash.name} ${clash.members === true ? "a set-element index" : "a field index"}`);
468
+ continue;
469
+ }
470
+ const holder = holders.find((index) => db3IndexKindAndPlacement(index).kind === placement.kind);
471
+ const held = holder ? db3IndexKindAndPlacement(holder) : null;
472
+ if (holder && held.on !== placement.on) {
473
+ conflicts.push(`${registration.model} (${fields.join(", ")}): the export's is placed ${placement.on}, the target's ${holder.name} ${held.on}; ` +
474
+ "a placement changes only by dropping the index and registering it again");
475
+ continue;
476
+ }
477
+ if (holder && (holder.unique || !wanted)) {
478
+ kept.push(`${registration.model} (${fields.join(", ")}): the target's ${holder.name} already ` +
479
+ `${holder.unique ? "enforces it as unique" : "indexes it"}; not registered again.`);
480
+ continue;
481
+ }
482
+ if ("name" in registration) {
483
+ const physical = `${namedIndexPrefix(registration.model)}${registration.name.toLowerCase()}`;
484
+ const taken = existing.find((index) => index.model === registration.model && index.name === physical && !sameFields(index.fields, fields));
485
+ if (taken) {
486
+ conflicts.push(`${registration.model} index ${registration.name}: the export's is over (${fields.join(", ")}), ` +
487
+ `the target's over (${taken.fields.join(", ")})`);
488
+ continue;
489
+ }
490
+ }
491
+ out.push(registration);
492
+ }
493
+ return { register: out, kept, conflicts };
494
+ }
495
+ /** The type name an import resolves: `--type`, else the manifest's; none under `--untyped` without one. */
496
+ export function resolvedTypeName(manifest, flags) {
497
+ return flags.type ?? manifest.type?.name ?? null;
498
+ }
499
+ /**
500
+ * Decide an import from what was read, before any write: a refusal naming
501
+ * what to do, or the steps.
502
+ */
503
+ export function planDb3Import(given, flags, facts) {
504
+ // Every side is compared by stored names: a rename alone never makes an export unimportable.
505
+ const keyed = storedKeyed(given.declaration, given.indexes ?? []);
506
+ const manifest = { ...given, declaration: keyed.declaration, ...(given.indexes ? { indexes: keyed.indexes } : {}) };
507
+ const named = resolvedTypeName(manifest, flags);
508
+ const typeName = flags.untyped && !flags.into ? null : named;
509
+ const notes = [];
510
+ if (flags.keepId && flags.into) {
511
+ return {
512
+ ok: false,
513
+ refusal: "--keep-id creates a db3 under the export's id, and --into loads into one that exists: pass one of them. Nothing was written.",
514
+ };
515
+ }
516
+ if (flags.keepId && facts.sourceExists) {
517
+ return {
518
+ ok: false,
519
+ refusal: `This app already holds a db3 with the export's id ${manifest.id}. Delete it first, import into another app, ` +
520
+ "or import without --keep-id to create it under a new id. Nothing was written.",
521
+ };
522
+ }
523
+ if (named && !flags.untyped) {
524
+ if (!facts.type) {
525
+ return {
526
+ ok: false,
527
+ refusal: `This app has no db3 type ${JSON.stringify(named)}. Push it first (primitive db3-types push), ` +
528
+ "or import the rows into an untyped db3 with --untyped. Nothing was written.",
529
+ };
530
+ }
531
+ const exportedHash = manifest.type?.revision?.hash;
532
+ const currentHash = facts.type.revision?.hash;
533
+ if (exportedHash && currentHash && exportedHash !== currentHash) {
534
+ notes.push(`The export was taken at type revision ${exportedHash}; the app's ${named} is at ${currentHash}.`);
535
+ }
536
+ if (!flags.into) {
537
+ const typeDeclaration = storedKeyed(declarationOfTypeSchema(facts.type.schema), [], facts.type.formerNames ?? {}).declaration;
538
+ const lines = compareDeclarations(manifest.declaration, typeDeclaration, {
539
+ installedName: `type ${named}`,
540
+ });
541
+ if (lines.length) {
542
+ return {
543
+ ok: false,
544
+ refusal: `The export's declaration differs from type ${named}'s. Nothing was written; ` +
545
+ "re-run with --untyped to load the rows into an untyped db3.",
546
+ lines,
547
+ };
548
+ }
549
+ }
550
+ }
551
+ if (flags.into) {
552
+ const target = facts.target;
553
+ if (!target)
554
+ return { ok: false, refusal: `The target db3 ${flags.into} could not be read. Nothing was written.` };
555
+ if (!flags.untyped) {
556
+ const theirs = target.row?.type ?? null;
557
+ if (theirs !== (named ?? null)) {
558
+ return {
559
+ ok: false,
560
+ refusal: `The target db3 ${flags.into} is ${theirs ? `of type ${theirs}` : "untyped"}; the export is ` +
561
+ `${named ? `of type ${named}` : "untyped"}. Nothing was written.`,
562
+ };
563
+ }
564
+ }
565
+ const lines = compareDeclarations(manifest.declaration, storedKeyed(target.declaration).declaration, {
566
+ ...(flags.untyped ? { only: "installed" } : {}),
567
+ installedName: `db3 ${flags.into}`,
568
+ });
569
+ if (lines.length) {
570
+ return { ok: false, refusal: `The export's declaration differs from db3 ${flags.into}'s. Nothing was written.`, lines };
571
+ }
572
+ }
573
+ const blobs = !flags.noBlobs && facts.blobCount > 0;
574
+ if (blobs && facts.sourceExists) {
575
+ return {
576
+ ok: false,
577
+ refusal: `The export's db3 ${manifest.id} is still in this app, and its blobs would collide with theirs under their ids. ` +
578
+ "Delete it first, import into another app, or re-run with --no-blobs. Nothing was written.",
579
+ };
580
+ }
581
+ const untypedTarget = flags.into ? !(facts.target?.row?.type) : !typeName;
582
+ // A vector index needs its field declared `vector`, and only a type declares one over HTTP (#5225).
583
+ const vectorIndexes = untypedTarget
584
+ ? (manifest.indexes ?? [])
585
+ .filter((index) => index.kind === "vector")
586
+ .map((index) => `${index.model}.${index.fields.join(", ")}: a vector index`)
587
+ .sort()
588
+ : [];
589
+ if (vectorIndexes.length) {
590
+ return {
591
+ ok: false,
592
+ refusal: `The export holds vector indexes, and ${flags.into ? `db3 ${flags.into}` : "the db3 this import would create"} is untyped: ` +
593
+ "a vector index covers a field a type declares vector. Import with --type <name>, a type declaring the model, " +
594
+ "or --into a db3 typed with the model. Nothing was written.",
595
+ lines: vectorIndexes,
596
+ };
597
+ }
598
+ let register = untypedTarget
599
+ ? registrationsFor(manifest.declaration, manifest.indexes ?? [])
600
+ : registrationsFor({ models: {} }, manifest.indexes ?? []);
601
+ if (flags.into && facts.target?.indexes) {
602
+ const pending = pendingRegistrations(register, facts.target.indexes);
603
+ if (pending.conflicts.length) {
604
+ return {
605
+ ok: false,
606
+ refusal: `The export's indexes clash with db3 ${flags.into}'s by name. Nothing was written.`,
607
+ lines: pending.conflicts,
608
+ };
609
+ }
610
+ register = pending.register;
611
+ notes.push(...pending.kept);
612
+ }
613
+ return {
614
+ ok: true,
615
+ typeName,
616
+ ...(flags.into
617
+ ? { into: flags.into }
618
+ : {
619
+ create: {
620
+ title: flags.title ?? manifest.title ?? "Imported db3",
621
+ ...(typeName ? { type: typeName } : {}),
622
+ tags: [...(manifest.tags ?? [])],
623
+ ...(flags.keepId ? { id: manifest.id } : {}),
624
+ },
625
+ }),
626
+ register,
627
+ blobs,
628
+ notes,
629
+ };
630
+ }
631
+ /** Read `<dir>/db3.json`, or `null` when the directory has none. */
632
+ export function readDb3Manifest(dir) {
633
+ const file = path.join(dir, DB3_MANIFEST);
634
+ if (!fs.existsSync(file))
635
+ return null;
636
+ const manifest = JSON.parse(fs.readFileSync(file, "utf8"));
637
+ if (manifest?.kind !== "db3-export")
638
+ throw new Error(`${file} is not a db3 export's manifest (kind ${JSON.stringify(manifest?.kind)}).`);
639
+ return manifest;
640
+ }
641
+ /** The blobs `<dir>/blobs/index.json` lists; none without one. */
642
+ export function readExportedBlobs(dir) {
643
+ const file = path.join(dir, "blobs", "index.json");
644
+ if (!fs.existsSync(file))
645
+ return [];
646
+ const listed = JSON.parse(fs.readFileSync(file, "utf8"));
647
+ return Array.isArray(listed) ? listed : [];
648
+ }
649
+ /** Every blob of a db3, page by page. */
650
+ async function listAllDb3Blobs(client, appId, db3Id) {
651
+ const blobs = [];
652
+ const seen = new Set();
653
+ let cursor;
654
+ for (;;) {
655
+ const page = await client.listDb3Blobs(appId, db3Id, cursor ? { cursor } : undefined);
656
+ if (Array.isArray(page))
657
+ return [...blobs, ...page];
658
+ blobs.push(...(page?.items ?? page?.blobs ?? []));
659
+ if (!page?.hasMore)
660
+ return blobs;
661
+ cursor = page?.nextCursor || undefined;
662
+ if (!cursor || seen.has(cursor))
663
+ throw new Error(`db3 ${db3Id}: its blob list said more follow but gave no new cursor; nothing was exported.`);
664
+ seen.add(cursor);
665
+ }
666
+ }
667
+ /**
668
+ * Write db3 `db3Id` to `dir`: the rows (a segment export, as `documents
669
+ * export` writes a record-log document's), `chain.json`, the blobs unless
670
+ * `blobs` is false, and `db3.json` last, so a directory with a manifest is a
671
+ * finished export.
672
+ */
673
+ export async function exportDb3(client, appId, db3Id, dir, options) {
674
+ fs.mkdirSync(dir, { recursive: true });
675
+ fs.rmSync(path.join(dir, DB3_MANIFEST), { force: true });
676
+ const row = await client.getDb3(appId, db3Id);
677
+ const type = await client.getDb3Type(appId, db3Id);
678
+ const typeSchema = type?.type ? (await client.getDb3TypeConfig(appId, String(type.type)))?.schema : undefined;
679
+ const declaredModels = type?.type ? declaredModelNames(typeSchema) : [];
680
+ // A renamed field is declared under its current name, keeping its storedAs, and its rows carry the current name.
681
+ const declaration = currentKeyedDeclaration(declarationOfSchemaAnswer(await client.getDb3Schema(appId, db3Id), { declaredModels }), typeSchema);
682
+ const listed = await client.listDb3Indexes(appId, db3Id);
683
+ // The registered origin's own uniqueness: a declaration's unique on the same index is the declaration's.
684
+ const indexes = exportedIndexesOf(listed?.indexes ?? []);
685
+ const exported = await exportRecordLogDocument({
686
+ client: {
687
+ requestSegment: () => client.requestDb3Snapshot(appId, db3Id),
688
+ getSegment: (segmentId) => client.getDb3Snapshot(appId, db3Id, segmentId),
689
+ listSegments: () => client.listDb3Snapshots(appId, db3Id, { limit: 100 }),
690
+ exportChain: () => client.exportDb3Chain(appId, db3Id),
691
+ download: (artifactPath) => client.downloadDocumentArtifact(appId, artifactPath),
692
+ },
693
+ documentId: db3Id,
694
+ docDir: dir,
695
+ renameFields: invertedRenames(renamedFieldsOf(declaration)),
696
+ onProgress: options.onProgress,
697
+ });
698
+ let blobCount = 0;
699
+ fs.rmSync(path.join(dir, "blobs"), { recursive: true, force: true });
700
+ if (options.blobs) {
701
+ const blobs = await listAllDb3Blobs(client, appId, db3Id);
702
+ const blobsDir = path.join(dir, "blobs");
703
+ fs.mkdirSync(blobsDir, { recursive: true });
704
+ const index = blobs.map((b) => ({
705
+ blobId: b.blobId,
706
+ filename: b.filename,
707
+ contentType: b.contentType,
708
+ sha256: b.sha256,
709
+ numBytes: b.numBytes,
710
+ }));
711
+ fs.writeFileSync(path.join(blobsDir, "index.json"), JSON.stringify(index, null, 2));
712
+ for (const blob of index) {
713
+ fs.writeFileSync(path.join(blobsDir, `${blob.blobId}.bin`), await client.downloadDb3Blob(appId, db3Id, blob.blobId));
714
+ }
715
+ blobCount = index.length;
716
+ }
717
+ const manifest = {
718
+ kind: "db3-export",
719
+ version: 1,
720
+ id: row.id ?? db3Id,
721
+ title: row.title ?? null,
722
+ tags: Array.isArray(row.tags) ? row.tags : [],
723
+ type: type?.type ? { name: String(type.type), revision: type.revision ?? null } : null,
724
+ declaration,
725
+ indexes,
726
+ lsn: exported.lsn,
727
+ exportedAt: new Date().toISOString(),
728
+ };
729
+ fs.writeFileSync(path.join(dir, DB3_MANIFEST), JSON.stringify(manifest, null, 2));
730
+ return { manifest, dir, rows: exported.segment.rows, blobs: blobCount };
731
+ }
732
+ /**
733
+ * Load an export's rows into `db3Id` through its bulk-load session (merge,
734
+ * the epoch reserved at open), waited to a terminal state. A field the
735
+ * export's `declaration` renames is loaded under its stored name, so an
736
+ * export whose rows carry current names and one whose rows carry stored
737
+ * names load alike. Answers the session's outcome, or `null` when the export
738
+ * holds no rows.
739
+ */
740
+ export async function loadDb3Rows(client, appId, db3Id, dir, onProgress, declaration) {
741
+ const input = discoverIngestInput(dir, db3Id);
742
+ const schema = ingestSchemaFromIntrospection(await client.getDb3Schema(appId, db3Id));
743
+ const renameFields = declaration ? renamedFieldsOf(declaration) : {};
744
+ const plan = await buildIngestArtifact({ input, schema, open: true, renameFields });
745
+ try {
746
+ if (plan.rows === 0)
747
+ return null;
748
+ return await driveDocumentIngest({
749
+ client: {
750
+ createIngest: (id) => client.createDb3Ingest(appId, id, {}),
751
+ uploadIngestChunk: (id, sessionId, chunk) => client.uploadDb3IngestChunk(appId, id, sessionId, chunk),
752
+ commitIngest: (id, sessionId) => client.commitDb3Ingest(appId, id, sessionId),
753
+ abortIngest: (id, sessionId) => client.abortDb3Ingest(appId, id, sessionId),
754
+ getIngest: (id, sessionId) => client.getDb3Ingest(appId, id, sessionId),
755
+ },
756
+ documentId: db3Id,
757
+ plan,
758
+ wait: true,
759
+ timeoutMs: null,
760
+ onProgress,
761
+ });
762
+ }
763
+ finally {
764
+ await plan.cleanup().catch(() => undefined);
765
+ }
766
+ }
767
+ //# sourceMappingURL=db3-export.js.map