@tier0/sdk-v2 0.0.0-stage → 0.2.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 (310) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +7 -0
  3. package/README.md +201 -2
  4. package/dist/cjs/app-identity-contract.generated.d.ts +22 -0
  5. package/dist/cjs/app-identity-contract.generated.js +51 -0
  6. package/dist/cjs/app-identity-contract.generated.js.map +1 -0
  7. package/dist/cjs/capabilities.d.ts +54 -0
  8. package/dist/cjs/capabilities.js +134 -0
  9. package/dist/cjs/capabilities.js.map +1 -0
  10. package/dist/cjs/client.d.ts +604 -0
  11. package/dist/cjs/client.js +35 -0
  12. package/dist/cjs/client.js.map +1 -0
  13. package/dist/cjs/cloud-server.d.ts +31 -0
  14. package/dist/cjs/cloud-server.js +114 -0
  15. package/dist/cjs/cloud-server.js.map +1 -0
  16. package/dist/cjs/cloud-transport.d.ts +67 -0
  17. package/dist/cjs/cloud-transport.js +272 -0
  18. package/dist/cjs/cloud-transport.js.map +1 -0
  19. package/dist/cjs/controls.d.ts +93 -0
  20. package/dist/cjs/controls.js +169 -0
  21. package/dist/cjs/controls.js.map +1 -0
  22. package/dist/cjs/data/bootstrap.d.ts +70 -0
  23. package/dist/cjs/data/bootstrap.js +291 -0
  24. package/dist/cjs/data/bootstrap.js.map +1 -0
  25. package/dist/cjs/data/call.d.ts +33 -0
  26. package/dist/cjs/data/call.js +216 -0
  27. package/dist/cjs/data/call.js.map +1 -0
  28. package/dist/cjs/data/client.d.ts +134 -0
  29. package/dist/cjs/data/client.js +185 -0
  30. package/dist/cjs/data/client.js.map +1 -0
  31. package/dist/cjs/data/collection.d.ts +335 -0
  32. package/dist/cjs/data/collection.js +601 -0
  33. package/dist/cjs/data/collection.js.map +1 -0
  34. package/dist/cjs/data/context.d.ts +12 -0
  35. package/dist/cjs/data/context.js +50 -0
  36. package/dist/cjs/data/context.js.map +1 -0
  37. package/dist/cjs/data/declarations.d.ts +11 -0
  38. package/dist/cjs/data/declarations.js +18 -0
  39. package/dist/cjs/data/declarations.js.map +1 -0
  40. package/dist/cjs/data/define.d.ts +77 -0
  41. package/dist/cjs/data/define.js +31 -0
  42. package/dist/cjs/data/define.js.map +1 -0
  43. package/dist/cjs/data/error.d.ts +78 -0
  44. package/dist/cjs/data/error.js +182 -0
  45. package/dist/cjs/data/error.js.map +1 -0
  46. package/dist/cjs/data/index.d.ts +24 -0
  47. package/dist/cjs/data/index.js +49 -0
  48. package/dist/cjs/data/index.js.map +1 -0
  49. package/dist/cjs/data/schema.d.ts +88 -0
  50. package/dist/cjs/data/schema.js +657 -0
  51. package/dist/cjs/data/schema.js.map +1 -0
  52. package/dist/cjs/data/sort.d.ts +8 -0
  53. package/dist/cjs/data/sort.js +21 -0
  54. package/dist/cjs/data/sort.js.map +1 -0
  55. package/dist/cjs/data/subscribe.d.ts +108 -0
  56. package/dist/cjs/data/subscribe.js +270 -0
  57. package/dist/cjs/data/subscribe.js.map +1 -0
  58. package/dist/cjs/files.d.ts +67 -0
  59. package/dist/cjs/files.js +119 -0
  60. package/dist/cjs/files.js.map +1 -0
  61. package/dist/cjs/framework-scope.d.ts +1 -0
  62. package/dist/cjs/framework-scope.js +14 -0
  63. package/dist/cjs/framework-scope.js.map +1 -0
  64. package/dist/cjs/index.d.ts +14 -0
  65. package/dist/cjs/index.js +33 -0
  66. package/dist/cjs/index.js.map +1 -0
  67. package/dist/cjs/mq/broker.d.ts +65 -0
  68. package/dist/cjs/mq/broker.js +115 -0
  69. package/dist/cjs/mq/broker.js.map +1 -0
  70. package/dist/cjs/mq/client.d.ts +37 -0
  71. package/dist/cjs/mq/client.js +321 -0
  72. package/dist/cjs/mq/client.js.map +1 -0
  73. package/dist/cjs/mq/index.d.ts +5 -0
  74. package/dist/cjs/mq/index.js +11 -0
  75. package/dist/cjs/mq/index.js.map +1 -0
  76. package/dist/cjs/mq/types.d.ts +48 -0
  77. package/dist/cjs/mq/types.js +3 -0
  78. package/dist/cjs/mq/types.js.map +1 -0
  79. package/dist/cjs/openapi/api.generated.d.ts +820 -0
  80. package/dist/cjs/openapi/api.generated.js +607 -0
  81. package/dist/cjs/openapi/api.generated.js.map +1 -0
  82. package/dist/cjs/openapi/client.d.ts +56 -0
  83. package/dist/cjs/openapi/client.js +219 -0
  84. package/dist/cjs/openapi/client.js.map +1 -0
  85. package/dist/cjs/openapi/codecs.generated.d.ts +2234 -0
  86. package/dist/cjs/openapi/codecs.generated.js +6 -0
  87. package/dist/cjs/openapi/codecs.generated.js.map +1 -0
  88. package/dist/cjs/openapi/index.d.ts +5 -0
  89. package/dist/cjs/openapi/index.js +12 -0
  90. package/dist/cjs/openapi/index.js.map +1 -0
  91. package/dist/cjs/openapi/types.generated.d.ts +3227 -0
  92. package/dist/cjs/openapi/types.generated.js +3 -0
  93. package/dist/cjs/openapi/types.generated.js.map +1 -0
  94. package/dist/cjs/package.json +1 -0
  95. package/dist/cjs/react.d.ts +9 -0
  96. package/dist/cjs/react.js +16 -0
  97. package/dist/cjs/react.js.map +1 -0
  98. package/dist/cjs/runtime-context.d.ts +9 -0
  99. package/dist/cjs/runtime-context.js +25 -0
  100. package/dist/cjs/runtime-context.js.map +1 -0
  101. package/dist/cjs/runtime-env.d.ts +1 -0
  102. package/dist/cjs/runtime-env.js +18 -0
  103. package/dist/cjs/runtime-env.js.map +1 -0
  104. package/dist/cjs/source.d.ts +39 -0
  105. package/dist/cjs/source.js +29 -0
  106. package/dist/cjs/source.js.map +1 -0
  107. package/dist/cjs/stream.d.ts +40 -0
  108. package/dist/cjs/stream.js +33 -0
  109. package/dist/cjs/stream.js.map +1 -0
  110. package/dist/cjs/uns-v2/client.d.ts +132 -0
  111. package/dist/cjs/uns-v2/client.js +352 -0
  112. package/dist/cjs/uns-v2/client.js.map +1 -0
  113. package/dist/cjs/uns-v2/codec.d.ts +11 -0
  114. package/dist/cjs/uns-v2/codec.js +290 -0
  115. package/dist/cjs/uns-v2/codec.js.map +1 -0
  116. package/dist/cjs/uns-v2/data-client.d.ts +10 -0
  117. package/dist/cjs/uns-v2/data-client.js +18 -0
  118. package/dist/cjs/uns-v2/data-client.js.map +1 -0
  119. package/dist/cjs/uns-v2/generated.d.ts +18178 -0
  120. package/dist/cjs/uns-v2/generated.js +144 -0
  121. package/dist/cjs/uns-v2/generated.js.map +1 -0
  122. package/dist/cjs/uns-v2/index.d.ts +5 -0
  123. package/dist/cjs/uns-v2/index.js +24 -0
  124. package/dist/cjs/uns-v2/index.js.map +1 -0
  125. package/dist/cjs/uns-v2/sse.d.ts +20 -0
  126. package/dist/cjs/uns-v2/sse.js +65 -0
  127. package/dist/cjs/uns-v2/sse.js.map +1 -0
  128. package/dist/cjs/vue.d.ts +9 -0
  129. package/dist/cjs/vue.js +39 -0
  130. package/dist/cjs/vue.js.map +1 -0
  131. package/dist/esm/app-identity-contract.generated.d.ts +22 -0
  132. package/dist/esm/app-identity-contract.generated.js +48 -0
  133. package/dist/esm/app-identity-contract.generated.js.map +1 -0
  134. package/dist/esm/capabilities.d.ts +54 -0
  135. package/dist/esm/capabilities.js +129 -0
  136. package/dist/esm/capabilities.js.map +1 -0
  137. package/dist/esm/client.d.ts +604 -0
  138. package/dist/esm/client.js +32 -0
  139. package/dist/esm/client.js.map +1 -0
  140. package/dist/esm/cloud-server.d.ts +31 -0
  141. package/dist/esm/cloud-server.js +109 -0
  142. package/dist/esm/cloud-server.js.map +1 -0
  143. package/dist/esm/cloud-transport.d.ts +67 -0
  144. package/dist/esm/cloud-transport.js +267 -0
  145. package/dist/esm/cloud-transport.js.map +1 -0
  146. package/dist/esm/controls.d.ts +93 -0
  147. package/dist/esm/controls.js +163 -0
  148. package/dist/esm/controls.js.map +1 -0
  149. package/dist/esm/data/bootstrap.d.ts +70 -0
  150. package/dist/esm/data/bootstrap.js +286 -0
  151. package/dist/esm/data/bootstrap.js.map +1 -0
  152. package/dist/esm/data/call.d.ts +33 -0
  153. package/dist/esm/data/call.js +211 -0
  154. package/dist/esm/data/call.js.map +1 -0
  155. package/dist/esm/data/client.d.ts +134 -0
  156. package/dist/esm/data/client.js +181 -0
  157. package/dist/esm/data/client.js.map +1 -0
  158. package/dist/esm/data/collection.d.ts +335 -0
  159. package/dist/esm/data/collection.js +594 -0
  160. package/dist/esm/data/collection.js.map +1 -0
  161. package/dist/esm/data/context.d.ts +12 -0
  162. package/dist/esm/data/context.js +44 -0
  163. package/dist/esm/data/context.js.map +1 -0
  164. package/dist/esm/data/declarations.d.ts +11 -0
  165. package/dist/esm/data/declarations.js +10 -0
  166. package/dist/esm/data/declarations.js.map +1 -0
  167. package/dist/esm/data/define.d.ts +77 -0
  168. package/dist/esm/data/define.js +27 -0
  169. package/dist/esm/data/define.js.map +1 -0
  170. package/dist/esm/data/error.d.ts +78 -0
  171. package/dist/esm/data/error.js +176 -0
  172. package/dist/esm/data/error.js.map +1 -0
  173. package/dist/esm/data/index.d.ts +24 -0
  174. package/dist/esm/data/index.js +20 -0
  175. package/dist/esm/data/index.js.map +1 -0
  176. package/dist/esm/data/schema.d.ts +88 -0
  177. package/dist/esm/data/schema.js +646 -0
  178. package/dist/esm/data/schema.js.map +1 -0
  179. package/dist/esm/data/sort.d.ts +8 -0
  180. package/dist/esm/data/sort.js +18 -0
  181. package/dist/esm/data/sort.js.map +1 -0
  182. package/dist/esm/data/subscribe.d.ts +108 -0
  183. package/dist/esm/data/subscribe.js +265 -0
  184. package/dist/esm/data/subscribe.js.map +1 -0
  185. package/dist/esm/files.d.ts +67 -0
  186. package/dist/esm/files.js +113 -0
  187. package/dist/esm/files.js.map +1 -0
  188. package/dist/esm/framework-scope.d.ts +1 -0
  189. package/dist/esm/framework-scope.js +11 -0
  190. package/dist/esm/framework-scope.js.map +1 -0
  191. package/dist/esm/index.d.ts +14 -0
  192. package/dist/esm/index.js +10 -0
  193. package/dist/esm/index.js.map +1 -0
  194. package/dist/esm/mq/broker.d.ts +65 -0
  195. package/dist/esm/mq/broker.js +109 -0
  196. package/dist/esm/mq/broker.js.map +1 -0
  197. package/dist/esm/mq/client.d.ts +37 -0
  198. package/dist/esm/mq/client.js +314 -0
  199. package/dist/esm/mq/client.js.map +1 -0
  200. package/dist/esm/mq/index.d.ts +5 -0
  201. package/dist/esm/mq/index.js +3 -0
  202. package/dist/esm/mq/index.js.map +1 -0
  203. package/dist/esm/mq/types.d.ts +48 -0
  204. package/dist/esm/mq/types.js +2 -0
  205. package/dist/esm/mq/types.js.map +1 -0
  206. package/dist/esm/openapi/api.generated.d.ts +820 -0
  207. package/dist/esm/openapi/api.generated.js +603 -0
  208. package/dist/esm/openapi/api.generated.js.map +1 -0
  209. package/dist/esm/openapi/client.d.ts +56 -0
  210. package/dist/esm/openapi/client.js +210 -0
  211. package/dist/esm/openapi/client.js.map +1 -0
  212. package/dist/esm/openapi/codecs.generated.d.ts +2234 -0
  213. package/dist/esm/openapi/codecs.generated.js +3 -0
  214. package/dist/esm/openapi/codecs.generated.js.map +1 -0
  215. package/dist/esm/openapi/index.d.ts +5 -0
  216. package/dist/esm/openapi/index.js +3 -0
  217. package/dist/esm/openapi/index.js.map +1 -0
  218. package/dist/esm/openapi/types.generated.d.ts +3227 -0
  219. package/dist/esm/openapi/types.generated.js +2 -0
  220. package/dist/esm/openapi/types.generated.js.map +1 -0
  221. package/dist/esm/package.json +1 -0
  222. package/dist/esm/react.d.ts +9 -0
  223. package/dist/esm/react.js +12 -0
  224. package/dist/esm/react.js.map +1 -0
  225. package/dist/esm/runtime-context.d.ts +9 -0
  226. package/dist/esm/runtime-context.js +22 -0
  227. package/dist/esm/runtime-context.js.map +1 -0
  228. package/dist/esm/runtime-env.d.ts +1 -0
  229. package/dist/esm/runtime-env.js +15 -0
  230. package/dist/esm/runtime-env.js.map +1 -0
  231. package/dist/esm/source.d.ts +39 -0
  232. package/dist/esm/source.js +25 -0
  233. package/dist/esm/source.js.map +1 -0
  234. package/dist/esm/stream.d.ts +40 -0
  235. package/dist/esm/stream.js +29 -0
  236. package/dist/esm/stream.js.map +1 -0
  237. package/dist/esm/uns-v2/client.d.ts +132 -0
  238. package/dist/esm/uns-v2/client.js +343 -0
  239. package/dist/esm/uns-v2/client.js.map +1 -0
  240. package/dist/esm/uns-v2/codec.d.ts +11 -0
  241. package/dist/esm/uns-v2/codec.js +284 -0
  242. package/dist/esm/uns-v2/codec.js.map +1 -0
  243. package/dist/esm/uns-v2/data-client.d.ts +10 -0
  244. package/dist/esm/uns-v2/data-client.js +14 -0
  245. package/dist/esm/uns-v2/data-client.js.map +1 -0
  246. package/dist/esm/uns-v2/generated.d.ts +18178 -0
  247. package/dist/esm/uns-v2/generated.js +141 -0
  248. package/dist/esm/uns-v2/generated.js.map +1 -0
  249. package/dist/esm/uns-v2/index.d.ts +5 -0
  250. package/dist/esm/uns-v2/index.js +5 -0
  251. package/dist/esm/uns-v2/index.js.map +1 -0
  252. package/dist/esm/uns-v2/sse.d.ts +20 -0
  253. package/dist/esm/uns-v2/sse.js +60 -0
  254. package/dist/esm/uns-v2/sse.js.map +1 -0
  255. package/dist/esm/vue.d.ts +9 -0
  256. package/dist/esm/vue.js +36 -0
  257. package/dist/esm/vue.js.map +1 -0
  258. package/docs/acceptance-2026-10-22.md +88 -0
  259. package/package.json +243 -4
  260. package/skills/tier0-sdk-v2/SKILL.md +66 -0
  261. package/skills/tier0-sdk-v2/references/integration.md +72 -0
  262. package/skills/tier0-sdk-v2/tier0-sdk-v2-agent/SKILL.md +73 -0
  263. package/skills/tier0-sdk-v2/tier0-sdk-v2-agent/references/results.md +45 -0
  264. package/skills/tier0-sdk-v2/tier0-sdk-v2-controls/SKILL.md +63 -0
  265. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/SKILL.md +58 -0
  266. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/consistency.md +70 -0
  267. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/errors.md +82 -0
  268. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/modeling.md +113 -0
  269. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/read-write.md +168 -0
  270. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/schema-evolution.md +36 -0
  271. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/SKILL.md +85 -0
  272. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/delete.md +22 -0
  273. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/download.md +49 -0
  274. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/multipart.md +42 -0
  275. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/upload.md +27 -0
  276. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/url.md +22 -0
  277. package/skills/tier0-sdk-v2/tier0-sdk-v2-members/SKILL.md +56 -0
  278. package/skills/tier0-sdk-v2/tier0-sdk-v2-members/references/app-members.md +41 -0
  279. package/skills/tier0-sdk-v2/tier0-sdk-v2-members/references/platform-members.md +56 -0
  280. package/skills/tier0-sdk-v2/tier0-sdk-v2-mq/SKILL.md +78 -0
  281. package/skills/tier0-sdk-v2/tier0-sdk-v2-mq/references/quickstart.md +69 -0
  282. package/skills/tier0-sdk-v2/tier0-sdk-v2-notifications/SKILL.md +42 -0
  283. package/skills/tier0-sdk-v2/tier0-sdk-v2-notifications/references/get.md +34 -0
  284. package/skills/tier0-sdk-v2/tier0-sdk-v2-notifications/references/send.md +72 -0
  285. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/SKILL.md +38 -0
  286. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/changes.md +40 -0
  287. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/create.md +63 -0
  288. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/delete.md +47 -0
  289. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/protocols.md +36 -0
  290. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/read.md +34 -0
  291. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/state.md +37 -0
  292. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/update.md +62 -0
  293. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/SKILL.md +43 -0
  294. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/create.md +56 -0
  295. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/delete.md +35 -0
  296. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/deploy.md +64 -0
  297. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/lifecycle.md +26 -0
  298. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/read.md +35 -0
  299. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/update.md +36 -0
  300. package/skills/tier0-sdk-v2/tier0-sdk-v2-system/SKILL.md +64 -0
  301. package/skills/tier0-sdk-v2/tier0-sdk-v2-system/references/info.md +23 -0
  302. package/skills/tier0-sdk-v2/tier0-sdk-v2-system/references/whoami.md +21 -0
  303. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/SKILL.md +55 -0
  304. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/create.md +56 -0
  305. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/data-workflows.md +69 -0
  306. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/delete.md +53 -0
  307. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/namespace.md +38 -0
  308. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/read.md +34 -0
  309. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/restore.md +39 -0
  310. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/update.md +62 -0
@@ -0,0 +1,594 @@
1
+ import { DataError } from './error.js';
2
+ import { validateDocument, validateUpdate } from './schema.js';
3
+ import { toSortPairs } from './sort.js';
4
+ /** UNS page limit for find / aggregate / distinct. */
5
+ export const MAX_PAGE_SIZE = 200;
6
+ /**
7
+ * UNS commits at most 200 items in one synchronous atomic batch
8
+ * (insertMany, bulkWrite, data.transact).
9
+ */
10
+ export const MAX_ATOMIC_ITEMS = 200;
11
+ /** Rejects batches UNS would refuse, before anything is sent. */
12
+ export function assertAtomicBatch(operation, count) {
13
+ if (count > MAX_ATOMIC_ITEMS) {
14
+ throw new DataError({
15
+ message: `${operation} commits at most ${MAX_ATOMIC_ITEMS} items atomically; got ${count}. ` +
16
+ `Split the input into chunks of ${MAX_ATOMIC_ITEMS} (each chunk commits on its own; give each chunk a stable ` +
17
+ 'idempotencyKey or fixed _ids so a retry is safe), or keep all-or-nothing work within one batch.',
18
+ status: 400,
19
+ code: 'BATCH_LIMIT_EXCEEDED',
20
+ });
21
+ }
22
+ }
23
+ export function toDoc(record) {
24
+ return {
25
+ ...record.data,
26
+ _id: record.id,
27
+ _meta: { revision: record.revision, createdAt: record.createdAt, updatedAt: record.updatedAt },
28
+ };
29
+ }
30
+ /**
31
+ * Async-iterable result set. Pages hold at most 200 items; the page source
32
+ * decides whether the next page is reached by cursor or by offset page number.
33
+ */
34
+ export class Cursor {
35
+ fetchPage;
36
+ sortSpec;
37
+ limitCount;
38
+ projection;
39
+ started = false;
40
+ constructor(fetchPage, options = {}) {
41
+ this.fetchPage = fetchPage;
42
+ this.sortSpec = options.sort;
43
+ this.limitCount = options.limit;
44
+ this.projection = options.projection;
45
+ }
46
+ assertNotStarted() {
47
+ if (this.started)
48
+ throw new Error('Cursor options must be set before iteration starts.');
49
+ }
50
+ sort(sort) {
51
+ this.assertNotStarted();
52
+ this.sortSpec = sort;
53
+ return this;
54
+ }
55
+ /** Total number of documents to return (pages are fetched ≤200 at a time). */
56
+ limit(count) {
57
+ this.assertNotStarted();
58
+ this.limitCount = count;
59
+ return this;
60
+ }
61
+ project(projection) {
62
+ this.assertNotStarted();
63
+ this.projection = projection;
64
+ return this;
65
+ }
66
+ async *[Symbol.asyncIterator]() {
67
+ this.started = true;
68
+ const sort = toSortPairs(this.sortSpec);
69
+ let remaining = this.limitCount ?? Number.POSITIVE_INFINITY;
70
+ // One page size for the whole iteration: offset pages are only stable when it never changes.
71
+ const size = Math.min(MAX_PAGE_SIZE, remaining);
72
+ let token = null;
73
+ while (remaining > 0) {
74
+ const page = await this.fetchPage({ token, size, sort, projection: this.projection });
75
+ for (const item of page.items.slice(0, remaining))
76
+ yield item;
77
+ remaining -= page.items.length;
78
+ if (page.next === null || page.items.length === 0)
79
+ return;
80
+ token = page.next;
81
+ }
82
+ }
83
+ async toArray() {
84
+ const out = [];
85
+ for await (const item of this)
86
+ out.push(item);
87
+ return out;
88
+ }
89
+ }
90
+ /** Pipelines made only of `$match` / `$sort` page by cursor; UNS requires offset paging for any other stage. */
91
+ function isDirectPipeline(stages) {
92
+ return stages.every((stage) => Object.keys(stage).every((key) => key === '$match' || key === '$sort'));
93
+ }
94
+ /** UNS reads at most 100 records by ID per request. */
95
+ export const MAX_GET_IDS = 100;
96
+ function compact(value) {
97
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
98
+ }
99
+ function filterOrNothing(filter) {
100
+ return Object.keys(filter).length > 0 ? filter : undefined;
101
+ }
102
+ /** `recordAggregatePipeline` body of one numbered page with its capped total. */
103
+ function pageRequest(filter, options) {
104
+ const page = Math.max(1, Math.trunc(options.page ?? 1));
105
+ const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(1, Math.trunc(options.pageSize ?? 20)));
106
+ const pipeline = [];
107
+ if (Object.keys(filter).length > 0)
108
+ pipeline.push({ $match: filter });
109
+ const sort = toSortPairs(options.sort);
110
+ if (sort)
111
+ pipeline.push({ $sort: sort });
112
+ if (options.projection)
113
+ pipeline.push({ $project: options.projection });
114
+ const body = { pipeline, page: { mode: 'offset', page, size: pageSize }, count: options.maxCount === undefined ? {} : { max: options.maxCount } };
115
+ return { body, page, pageSize };
116
+ }
117
+ function countByPipeline(field, filter) {
118
+ const pipeline = [];
119
+ if (Object.keys(filter).length > 0)
120
+ pipeline.push({ $match: filter });
121
+ // `_id` breaks ties, so offset pages of equal counts neither repeat nor skip a group.
122
+ pipeline.push({ $group: { _id: `$${field}`, count: { $sum: 1 } } }, { $sort: { count: -1, _id: 1 } });
123
+ return pipeline;
124
+ }
125
+ const toValueCount = (row) => ({ value: row._id ?? null, count: row.count });
126
+ function idsInOrder(ids) {
127
+ return Object.entries(ids ?? {})
128
+ .sort(([a], [b]) => Number(a) - Number(b))
129
+ .map(([, id]) => id);
130
+ }
131
+ /**
132
+ * Atomic batches pass no `committed` counts: their write errors rolled the
133
+ * whole batch back. Non-atomic runs pass their cumulative counts; `details`
134
+ * then has the shape `partialWrite` uses.
135
+ */
136
+ function assertNoWriteErrors(result, operation, committed) {
137
+ if (result.writeErrors && result.writeErrors.length > 0) {
138
+ const counts = Object.entries(committed ?? {}).map(([name, value]) => `${name}=${value}`).join(', ');
139
+ const changed = committed !== undefined && Object.values(committed).some((value) => value > 0);
140
+ throw new DataError({
141
+ message: `${operation} stopped on ${result.writeErrors.length} write error(s)${counts ? `; already committed: ${counts}` : ''}.`,
142
+ status: 409,
143
+ code: 'WRITE_ERRORS',
144
+ execution: changed ? 'committed' : 'rolledBack',
145
+ attempts: 1,
146
+ details: committed
147
+ ? { ...committed, status: changed ? 'partiallyCommitted' : 'failed', hasMore: Boolean(result.hasMore), resumeAfter: result.resumeAfter ?? null, writeErrors: result.writeErrors }
148
+ : { writeErrors: result.writeErrors },
149
+ });
150
+ }
151
+ }
152
+ /**
153
+ * A non-atomic run failed after some writes committed: on an earlier page, or
154
+ * within the failed page (UNS then answers `execution: "committed"` with the
155
+ * page's partial result as `data`). Like UNS, the error keeps its code and is
156
+ * `committed` with `retry.safe: false`; `details` is the cumulative result
157
+ * of the whole call in the shape of a success (`matchedCount` …, `status:
158
+ * "partiallyCommitted"`, `hasMore`, `resumeAfter`). Continue by passing
159
+ * `resumeAfter` back; repeating the call would apply `$inc` / `$push` twice.
160
+ */
161
+ function partialWrite(operation, totals, resumeAfter, cause) {
162
+ const counts = Object.entries(totals).map(([name, value]) => `${name}=${value}`).join(', ');
163
+ const writeErrors = Array.isArray(cause.details.writeErrors) ? { writeErrors: cause.details.writeErrors } : {};
164
+ return new DataError({
165
+ message: `${operation} committed ${counts} and then failed: ${cause.message} ` +
166
+ (resumeAfter
167
+ ? `Continue with { resumeAfter: details.resumeAfter }${cause.outcomeUnknown ? ' after checking the failed page, whose outcome is unknown' : ''}; do not repeat the whole call.`
168
+ : 'Read back what changed before writing again; do not repeat the whole call.'),
169
+ status: cause.status,
170
+ code: cause.code,
171
+ reason: cause.reason,
172
+ upstreamStatus: cause.upstreamStatus,
173
+ requestId: cause.requestId,
174
+ // Earlier writes took effect; the failed page too, perhaps, when its outcome is unknown.
175
+ execution: cause.outcomeUnknown ? 'unknown' : 'committed',
176
+ retry: { safe: false },
177
+ attempts: cause.attempts,
178
+ details: { ...totals, status: 'partiallyCommitted', hasMore: true, resumeAfter: resumeAfter ?? null, ...writeErrors },
179
+ cause,
180
+ });
181
+ }
182
+ export class Collection {
183
+ definition;
184
+ runtime;
185
+ constructor(definition, runtime) {
186
+ this.definition = definition;
187
+ this.runtime = runtime;
188
+ }
189
+ get alias() {
190
+ return this.definition.alias;
191
+ }
192
+ /**
193
+ * One call with stale-ID recovery. A call continuing a cursor or
194
+ * resumeAfter token of the old collection is not retried: the token means
195
+ * nothing to a recreated collection.
196
+ */
197
+ post(operation, body, options = {}) {
198
+ const page = body.page;
199
+ const continues = typeof body.cursor === 'string' || typeof body.resumeAfter === 'string' || typeof page?.cursor === 'string';
200
+ return this.runtime.recover(() => this.send(operation, body, options), { retry: !continues });
201
+ }
202
+ async send(operation, body, options = {}) {
203
+ const collectionId = await this.runtime.resolve(this.definition);
204
+ return this.runtime.call(operation, { collectionId, ...compact(body) }, {
205
+ dataSubject: this.runtime.subject(),
206
+ signal: this.runtime.signal(),
207
+ ...options,
208
+ });
209
+ }
210
+ /* ---------------------------------- reads --------------------------------- */
211
+ find(filter = {}, options = {}) {
212
+ return new Cursor(async ({ token, size, sort, projection }) => {
213
+ const result = await this.post('recordFind', {
214
+ filter: Object.keys(filter).length > 0 ? filter : undefined,
215
+ sort,
216
+ projection,
217
+ limit: size,
218
+ cursor: typeof token === 'string' ? token : undefined,
219
+ });
220
+ return {
221
+ items: result.items.map((record) => toDoc(record)),
222
+ next: result.pageInfo.hasMore && result.pageInfo.nextCursor ? result.pageInfo.nextCursor : null,
223
+ };
224
+ }, options);
225
+ }
226
+ async findOne(filter = {}, options = {}) {
227
+ const [first] = await this.find(filter, { ...options, limit: 1 }).toArray();
228
+ return first ?? null;
229
+ }
230
+ /**
231
+ * Records by ID, in the order asked for (each ID once, at its first
232
+ * position); IDs that do not exist, are deleted or are hidden by employee
233
+ * data rules are listed in `missing` alike. More than 100 IDs are read in
234
+ * chunks of 100 (not one snapshot).
235
+ */
236
+ async get(ids, options = {}) {
237
+ const unique = [...new Set(ids)];
238
+ const chunks = [];
239
+ for (let start = 0; start < unique.length; start += MAX_GET_IDS)
240
+ chunks.push(unique.slice(start, start + MAX_GET_IDS));
241
+ const results = await Promise.all(chunks.map((chunk) => this.post('recordGet', { ids: chunk, projection: options.projection })));
242
+ return {
243
+ items: results.flatMap((result) => result.items.map((record) => toDoc(record))),
244
+ missing: results.flatMap((result) => result.missing),
245
+ };
246
+ }
247
+ /**
248
+ * One numbered page plus the total match count, for paged list screens:
249
+ * one `recordAggregatePipeline` offset page whose `count` runs in the same
250
+ * snapshot. Show a capped total as "10000+".
251
+ */
252
+ async findPage(filter = {}, options = {}) {
253
+ const { body, page, pageSize } = pageRequest(filter, options);
254
+ const result = await this.post('recordAggregatePipeline', body);
255
+ return { items: result.items, total: result.total, page, pageSize };
256
+ }
257
+ /**
258
+ * Counts matches up to `maxCount` (1–100000, UNS default 100000). A
259
+ * `capped` result means "at least `count`".
260
+ */
261
+ async countDocuments(filter = {}, options = {}) {
262
+ const result = await this.post('recordCount', { filter: filterOrNothing(filter), maxCount: options.maxCount });
263
+ return { count: result.count, capped: result.capped };
264
+ }
265
+ /**
266
+ * Match counts per value of `field`, largest first: one `$group` pipeline
267
+ * instead of a count per value. Records without the field count under
268
+ * `value: null`.
269
+ */
270
+ async countBy(field, filter = {}) {
271
+ const rows = await this.aggregate(countByPipeline(field, filter)).toArray();
272
+ return rows.map(toValueCount);
273
+ }
274
+ /**
275
+ * Builders for `data.queryBatch`: each describes one read of this
276
+ * collection, run together with the others in one request and one
277
+ * snapshot. Each returns one page (at most 200 rows), unlike the cursor
278
+ * methods; `get` takes at most 100 IDs.
279
+ */
280
+ get query() {
281
+ const one = (op, build, parse) => ({
282
+ collection: this.definition,
283
+ prepare: async () => ({ op, ...compact(await build()) }),
284
+ parse: parse,
285
+ });
286
+ return {
287
+ find: (filter = {}, options = {}) => one('find', async () => ({
288
+ filter: filterOrNothing(filter),
289
+ sort: toSortPairs(options.sort),
290
+ projection: options.projection,
291
+ limit: Math.min(MAX_PAGE_SIZE, options.limit ?? 20),
292
+ count: options.maxCount === undefined ? undefined : { max: options.maxCount },
293
+ }), (data) => ({
294
+ items: data.items.map((record) => toDoc(record)),
295
+ hasMore: data.pageInfo.hasMore,
296
+ ...(data.total ? { total: data.total } : {}),
297
+ })),
298
+ findPage: (filter = {}, options = {}) => {
299
+ const { body, page, pageSize } = pageRequest(filter, options);
300
+ return one('aggregate', async () => body, (data) => ({
301
+ items: data.items, total: data.total, page, pageSize,
302
+ }));
303
+ },
304
+ count: (filter = {}, options = {}) => one('count', async () => ({ filter: filterOrNothing(filter), maxCount: options.maxCount }), (data) => ({ count: data.count, capped: data.capped })),
305
+ countBy: (field, filter = {}) => one('aggregate', async () => ({
306
+ pipeline: await this.prepareStages(countByPipeline(field, filter)),
307
+ page: { mode: 'offset', page: 1, size: MAX_PAGE_SIZE },
308
+ }), (data) => data.items.map(toValueCount)),
309
+ distinct: (field, filter = {}) => one('distinct', async () => ({ field, filter: filterOrNothing(filter), page: { mode: 'offset', page: 1, size: MAX_PAGE_SIZE } }), (data) => data.values),
310
+ aggregate: (pipeline) => one('aggregate', async () => {
311
+ const stages = await this.prepareStages(pipeline);
312
+ const last = stages[stages.length - 1];
313
+ // A final $count returns one row and forbids an explicit page.
314
+ return last !== undefined && '$count' in last
315
+ ? { pipeline: stages }
316
+ : { pipeline: stages, page: isDirectPipeline(stages) ? { mode: 'cursor', size: MAX_PAGE_SIZE } : { mode: 'offset', page: 1, size: MAX_PAGE_SIZE } };
317
+ }, (data) => data.items),
318
+ get: (ids, options = {}) => {
319
+ const unique = [...new Set(ids)];
320
+ if (unique.length < 1 || unique.length > MAX_GET_IDS) {
321
+ throw new TypeError(`query.get takes 1–${MAX_GET_IDS} distinct IDs; use collection.get for more.`);
322
+ }
323
+ return one('get', async () => ({ ids: unique, projection: options.projection }), (data) => ({ items: data.items.map((record) => toDoc(record)), missing: data.missing }));
324
+ },
325
+ };
326
+ }
327
+ /** Distinct values of a field (every page). */
328
+ async distinct(field, filter = {}) {
329
+ const values = [];
330
+ for (let page = 1;; page += 1) {
331
+ const result = await this.post('recordDistinct', {
332
+ field,
333
+ filter: Object.keys(filter).length > 0 ? filter : undefined,
334
+ page: { mode: 'offset', page, size: MAX_PAGE_SIZE },
335
+ });
336
+ values.push(...result.values);
337
+ if (!result.pageInfo.hasMore)
338
+ return values;
339
+ }
340
+ }
341
+ /**
342
+ * Runs a pipeline (`$match`, `$sort`, `$group`, `$project`, `$set`,
343
+ * `$lookup`, `$unwind`, `$skip`, `$limit`, `$count`). `$sort` accepts
344
+ * `{ field: 1 | -1 }`; `$lookup` takes `from` (a declared collection or
345
+ * alias of this App) instead of a collection ID. Rows are whatever the
346
+ * pipeline outputs, not wrapped records.
347
+ *
348
+ * Pipelines of only `$match` / `$sort` page by cursor; any other stage pages
349
+ * by offset (UNS rejects cursors for transformed results). The `$exists`,
350
+ * `$distinct` and `$frequencies` stages are listed in the UNS schema but not
351
+ * executed by the record pipeline; use `countDocuments`, `distinct` or `$group`.
352
+ */
353
+ aggregate(pipeline) {
354
+ // Recovery wraps stage preparation too, so a retry re-resolves `$lookup` IDs.
355
+ return new Cursor(({ token, size }) => this.runtime.recover(() => this.aggregatePage(pipeline, token, size), { retry: typeof token !== 'string' }));
356
+ }
357
+ async aggregatePage(pipeline, token, size) {
358
+ const stages = await this.prepareStages(pipeline);
359
+ const last = stages[stages.length - 1];
360
+ if (last !== undefined && '$count' in last) {
361
+ // A final $count returns one row and forbids an explicit page.
362
+ const result = await this.send('recordAggregatePipeline', { pipeline: stages });
363
+ return { items: result.items, next: null };
364
+ }
365
+ if (isDirectPipeline(stages)) {
366
+ const result = await this.send('recordAggregatePipeline', {
367
+ pipeline: stages,
368
+ page: { mode: 'cursor', size, ...(typeof token === 'string' ? { cursor: token } : {}) },
369
+ });
370
+ return { items: result.items, next: result.pageInfo.hasMore && result.pageInfo.nextCursor ? result.pageInfo.nextCursor : null };
371
+ }
372
+ const page = typeof token === 'number' ? token : 1;
373
+ const result = await this.send('recordAggregatePipeline', {
374
+ pipeline: stages,
375
+ page: { mode: 'offset', page, size },
376
+ });
377
+ return {
378
+ items: result.items,
379
+ next: result.pageInfo.hasMore ? (result.pageInfo.nextPage ?? page + 1) : null,
380
+ };
381
+ }
382
+ /** Converts Mongo-style `$sort` objects and resolves `$lookup.from`, recursively. */
383
+ async prepareStages(pipeline) {
384
+ return Promise.all(pipeline.map(async (stage) => {
385
+ if ('$sort' in stage && !Array.isArray(stage.$sort)) {
386
+ return { ...stage, $sort: toSortPairs(stage.$sort) };
387
+ }
388
+ if ('$lookup' in stage && stage.$lookup && typeof stage.$lookup === 'object') {
389
+ const { from, pipeline: inner, ...lookup } = stage.$lookup;
390
+ const resolved = { ...lookup };
391
+ if (from !== undefined)
392
+ resolved.collectionId = await this.runtime.resolve(from);
393
+ if (Array.isArray(inner))
394
+ resolved.pipeline = await this.prepareStages(inner);
395
+ return { ...stage, $lookup: resolved };
396
+ }
397
+ return stage;
398
+ }));
399
+ }
400
+ /* --------------------------------- writes --------------------------------- */
401
+ async insertOne(document, options = {}) {
402
+ const { id, data } = validateDocument(this.definition, document);
403
+ const result = await this.post('recordInsertOne', { id, data, idempotencyKey: options.idempotencyKey });
404
+ return { insertedId: result.insertedId };
405
+ }
406
+ /** Inserts up to 200 documents atomically (all or none). */
407
+ async insertMany(documents, options = {}) {
408
+ if (documents.length === 0)
409
+ return { insertedCount: 0, insertedIds: [] };
410
+ assertAtomicBatch('insertMany', documents.length);
411
+ const prepared = documents.map((document) => validateDocument(this.definition, document));
412
+ const result = await this.post('recordInsertMany', {
413
+ documents: prepared.map(({ id, data }) => compact({ id, data })),
414
+ ordered: true,
415
+ atomic: true,
416
+ idempotencyKey: options.idempotencyKey,
417
+ });
418
+ assertNoWriteErrors(result, 'insertMany');
419
+ return { insertedCount: result.insertedCount ?? 0, insertedIds: idsInOrder(result.insertedIds) };
420
+ }
421
+ async updateOne(filter, update, options = {}) {
422
+ const result = await this.post('recordUpdateOne', {
423
+ filter,
424
+ update: validateUpdate(this.definition, update),
425
+ upsert: options.upsert,
426
+ expectedRevision: options.expectedRevision,
427
+ sort: toSortPairs(options.sort),
428
+ arrayFilters: options.arrayFilters,
429
+ idempotencyKey: options.idempotencyKey,
430
+ });
431
+ return { matchedCount: result.matchedCount ?? 0, modifiedCount: result.modifiedCount ?? 0, upsertedId: result.upsertedId ?? null };
432
+ }
433
+ /**
434
+ * Updates every match like Mongo's updateMany: documents commit one by one
435
+ * (not atomically), following `resumeAfter` until every match is processed.
436
+ * A failure after some documents committed keeps its code but is
437
+ * `execution: "committed"`, with the cumulative counts and
438
+ * `details.resumeAfter`; pass that back as `resumeAfter` to continue
439
+ * instead of repeating the call. For all-or-nothing multi-document changes
440
+ * use `data.transact` (≤200 items).
441
+ */
442
+ async updateMany(filter, update, options = {}) {
443
+ const validated = validateUpdate(this.definition, update);
444
+ let matchedCount = 0;
445
+ let modifiedCount = 0;
446
+ await this.writeEach('updateMany', 'recordUpdateMany', { filter, update: validated, arrayFilters: options.arrayFilters }, options.resumeAfter, (result) => {
447
+ matchedCount += result.matchedCount ?? 0;
448
+ modifiedCount += result.modifiedCount ?? 0;
449
+ return { matchedCount, modifiedCount };
450
+ });
451
+ return { matchedCount, modifiedCount };
452
+ }
453
+ /** Runs a non-atomic many-write page by page; see updateMany for failures. */
454
+ async writeEach(name, operation, body, from, add) {
455
+ let resumeAfter = from;
456
+ let committed;
457
+ do {
458
+ let result;
459
+ try {
460
+ result = await this.post(operation, { ...body, atomic: false, resumeAfter });
461
+ }
462
+ catch (error) {
463
+ if (!(error instanceof DataError))
464
+ throw error;
465
+ // UNS reports what the failed page itself committed, with where to continue.
466
+ const page = error.execution === 'committed' ? error.details : undefined;
467
+ const totals = page ? add(page) : committed;
468
+ // Nothing of this call took effect: the page's own error tells the truth.
469
+ if (!totals || !Object.values(totals).some((value) => value > 0))
470
+ throw error;
471
+ throw partialWrite(name, totals, page ? (page.resumeAfter ?? undefined) : resumeAfter, error);
472
+ }
473
+ committed = add(result);
474
+ assertNoWriteErrors(result, name, committed);
475
+ resumeAfter = result.hasMore && result.resumeAfter ? result.resumeAfter : undefined;
476
+ } while (resumeAfter);
477
+ }
478
+ /**
479
+ * Replaces the whole body. Fields written by another App version and not in
480
+ * this declaration are lost — prefer `updateOne` with `$set`.
481
+ */
482
+ async replaceOne(filter, replacement, options = {}) {
483
+ const { data } = validateDocument(this.definition, replacement);
484
+ const result = await this.post('recordReplaceOne', {
485
+ filter,
486
+ replacement: data,
487
+ upsert: options.upsert,
488
+ expectedRevision: options.expectedRevision,
489
+ sort: toSortPairs(options.sort),
490
+ idempotencyKey: options.idempotencyKey,
491
+ });
492
+ return { matchedCount: result.matchedCount ?? 0, modifiedCount: result.modifiedCount ?? 0, upsertedId: result.upsertedId ?? null };
493
+ }
494
+ /** Soft-deletes one record; requires `uns.delete` on the App key. */
495
+ async deleteOne(filter, options = {}) {
496
+ const result = await this.post('recordDeleteOne', { filter, expectedRevision: options.expectedRevision, sort: toSortPairs(options.sort), idempotencyKey: options.idempotencyKey });
497
+ return { deletedCount: result.deletedCount ?? 0 };
498
+ }
499
+ /**
500
+ * Soft-deletes every match, one document at a time like Mongo's deleteMany
501
+ * (not atomic), following `resumeAfter`; requires `uns.delete` on the App
502
+ * key. Failures after committed deletes report them as updateMany does.
503
+ */
504
+ async deleteMany(filter, options = {}) {
505
+ let deletedCount = 0;
506
+ await this.writeEach('deleteMany', 'recordDeleteMany', { filter }, options.resumeAfter, (result) => {
507
+ deletedCount += result.deletedCount ?? 0;
508
+ return { deletedCount };
509
+ });
510
+ return { deletedCount };
511
+ }
512
+ /**
513
+ * Atomic read-modify-write. A state transition puts the expected state in
514
+ * the filter: `findOneAndUpdate({ _id, status: "DRAFT" }, { $set: { status: "SUBMITTED" } })`
515
+ * returns null when another request moved the record first.
516
+ */
517
+ async findOneAndUpdate(filter, update, options = {}) {
518
+ const result = await this.post('recordFindOneAndUpdate', {
519
+ filter,
520
+ update: validateUpdate(this.definition, update),
521
+ upsert: options.upsert,
522
+ expectedRevision: options.expectedRevision,
523
+ sort: toSortPairs(options.sort),
524
+ arrayFilters: options.arrayFilters,
525
+ returnDocument: options.returnDocument ?? 'after',
526
+ projection: options.projection,
527
+ idempotencyKey: options.idempotencyKey,
528
+ });
529
+ return result.value ? toDoc(result.value) : null;
530
+ }
531
+ async findOneAndReplace(filter, replacement, options = {}) {
532
+ const { data } = validateDocument(this.definition, replacement);
533
+ const result = await this.post('recordFindOneAndReplace', {
534
+ filter,
535
+ replacement: data,
536
+ upsert: options.upsert,
537
+ expectedRevision: options.expectedRevision,
538
+ sort: toSortPairs(options.sort),
539
+ returnDocument: options.returnDocument ?? 'after',
540
+ projection: options.projection,
541
+ idempotencyKey: options.idempotencyKey,
542
+ });
543
+ return result.value ? toDoc(result.value) : null;
544
+ }
545
+ async findOneAndDelete(filter, options = {}) {
546
+ const result = await this.post('recordFindOneAndDelete', {
547
+ filter,
548
+ expectedRevision: options.expectedRevision,
549
+ sort: toSortPairs(options.sort),
550
+ projection: options.projection,
551
+ idempotencyKey: options.idempotencyKey,
552
+ });
553
+ return result.value ? toDoc(result.value) : null;
554
+ }
555
+ /** Up to 200 mixed single-record writes in one atomic call (insertOne / updateOne / replaceOne / deleteOne). */
556
+ async bulkWrite(operations, options = {}) {
557
+ assertAtomicBatch('bulkWrite', operations.length);
558
+ const mapped = operations.map((operation) => {
559
+ if ('insertOne' in operation) {
560
+ const { id, data } = validateDocument(this.definition, operation.insertOne.document);
561
+ return { insertOne: compact({ id, data }) };
562
+ }
563
+ if ('updateOne' in operation) {
564
+ const { filter, update, upsert, sort } = operation.updateOne;
565
+ return { updateOne: compact({ filter, update: validateUpdate(this.definition, update), upsert, sort: toSortPairs(sort) }) };
566
+ }
567
+ if ('replaceOne' in operation) {
568
+ const { filter, replacement, upsert, sort } = operation.replaceOne;
569
+ const { data } = validateDocument(this.definition, replacement);
570
+ return { replaceOne: compact({ filter, replacement: data, upsert, sort: toSortPairs(sort) }) };
571
+ }
572
+ if ('deleteOne' in operation) {
573
+ return { deleteOne: compact({ filter: operation.deleteOne.filter, sort: toSortPairs(operation.deleteOne.sort) }) };
574
+ }
575
+ throw new Error(`Unsupported bulkWrite operation ${Object.keys(operation).join(', ')}; use updateMany() / deleteMany() or data.transact().`);
576
+ });
577
+ if (mapped.length === 0) {
578
+ return { insertedCount: 0, matchedCount: 0, modifiedCount: 0, deletedCount: 0, upsertedCount: 0, insertedIds: {}, upsertedIds: {} };
579
+ }
580
+ const result = await this.post('recordBulkWrite', { operations: mapped, ordered: true, atomic: true, idempotencyKey: options.idempotencyKey });
581
+ assertNoWriteErrors(result, 'bulkWrite');
582
+ const numericKeys = (ids) => Object.fromEntries(Object.entries(ids ?? {}).map(([index, id]) => [Number(index), id]));
583
+ return {
584
+ insertedCount: result.insertedCount ?? 0,
585
+ matchedCount: result.matchedCount ?? 0,
586
+ modifiedCount: result.modifiedCount ?? 0,
587
+ deletedCount: result.deletedCount ?? 0,
588
+ upsertedCount: result.upsertedCount ?? 0,
589
+ insertedIds: numericKeys(result.insertedIds),
590
+ upsertedIds: numericKeys(result.upsertedIds),
591
+ };
592
+ }
593
+ }
594
+ //# sourceMappingURL=collection.js.map