agenttwin 0.3.21 → 0.3.22

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 (408) hide show
  1. package/dist/api.js +2113 -609
  2. package/dist/dashboard/assets/dashboard/agent-home.css +7 -7
  3. package/dist/dashboard/assets/dashboard/bay-morning.webp +0 -0
  4. package/dist/dashboard/assets/dashboard/golden-gate-afternoon.webp +0 -0
  5. package/dist/dashboard/assets/dashboard/golden-gate-portrait.webp +0 -0
  6. package/dist/dashboard/assets/dashboard/moonlit-coast.webp +0 -0
  7. package/dist/dashboard/assets/next/static/chunks/5663-403316746afad10e.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/dashboard/{page-9c11295678539a5f.js → page-0e0392368e0a891e.js} +1 -1
  9. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-4981ea4966b19e3e.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-dd4ac0f5f36e6bfa.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/{page-34574448d210c775.js → page-de0fe6d84be21e6a.js} +1 -1
  12. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-360cbffc57981f6b.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/v2/{page-07c8054d57c9089b.js → page-3e86fffabfa87d88.js} +1 -1
  14. package/dist/dashboard/assets/next/static/chunks/{webpack-40324749d289e4a5.js → webpack-be6e526fd530c797.js} +1 -1
  15. package/dist/dashboard/assets/next/static/css/{42045de5f39b50ca.css → 37d81e1d2804cc5f.css} +1 -1
  16. package/dist/dashboard/assets/next/static/css/69ec1bae997c3bb0.css +1 -0
  17. package/dist/dashboard/assets/next/static/css/ad85402a1595e56e.css +1 -0
  18. package/dist/dashboard/assets/next/static/css/{4bbe78c2fe206b92.css → da981fb878a02b8c.css} +1 -1
  19. package/dist/dashboard/assets/next/static/media/bay-morning.82669113.webp +0 -0
  20. package/dist/dashboard/assets/next/static/media/golden-gate-afternoon.0aa49492.webp +0 -0
  21. package/dist/dashboard/assets/next/static/media/golden-gate-portrait.89fc667a.webp +0 -0
  22. package/dist/dashboard/assets/next/static/media/moonlit-coast.09739ef4.webp +0 -0
  23. package/dist/dashboard/index.html +2 -2
  24. package/dist/engine.js +6385 -4973
  25. package/dist/gateway.js +2194 -604
  26. package/dist/twins/catalog.json +6020 -0
  27. package/dist/twins/engine/v2/THIRD-PARTY.txt +25 -0
  28. package/dist/twins/engine/v2/chunks/2CHBP57N.mjs +8 -0
  29. package/dist/twins/engine/v2/chunks/4CPL6MPF.mjs +30 -0
  30. package/dist/twins/engine/v2/chunks/OYLYKZGD.mjs +2 -0
  31. package/dist/twins/engine/v2/chunks/SQSP35HM.mjs +38 -0
  32. package/dist/twins/engine/v2/chunks/YSJQQVUM.mjs +2 -0
  33. package/dist/twins/engine/v2/react-dom_client.mjs +272 -0
  34. package/dist/twins/engine/v2/react-dom_server.mjs +263 -0
  35. package/dist/twins/engine/v2/react.mjs +2 -0
  36. package/dist/twins/engine/v2/react_jsx-runtime.mjs +31 -0
  37. package/dist/twins/engine/v2/volter_world-core.mjs +195 -0
  38. package/dist/twins/engine/v2/volter_world-core_app-route.mjs +2 -0
  39. package/dist/twins/engine/v2/volter_world-core_network-policy.mjs +2 -0
  40. package/dist/twins/engine/v3/THIRD-PARTY.txt +65 -0
  41. package/dist/twins/engine/v3/chunks/2CHBP57N.mjs +8 -0
  42. package/dist/twins/engine/v3/chunks/2YSSPA5O.mjs +65 -0
  43. package/dist/twins/engine/v3/chunks/5PWRY4UK.mjs +154 -0
  44. package/dist/twins/engine/v3/chunks/7XRKSFFJ.mjs +2 -0
  45. package/dist/twins/engine/v3/chunks/AWOWH2H5.mjs +2 -0
  46. package/dist/twins/engine/v3/chunks/C46M5U3Q.mjs +2 -0
  47. package/dist/twins/engine/v3/chunks/MFH2VZPP.mjs +2 -0
  48. package/dist/twins/engine/v3/chunks/MWCO5UV3.mjs +2 -0
  49. package/dist/twins/engine/v3/chunks/N5BL5RDF.mjs +313 -0
  50. package/dist/twins/engine/v3/chunks/O7HGPMXG.mjs +2 -0
  51. package/dist/twins/engine/v3/chunks/OYLYKZGD.mjs +2 -0
  52. package/dist/twins/engine/v3/chunks/PLB7HTON.mjs +8 -0
  53. package/dist/twins/engine/v3/chunks/TY4LDBVH.mjs +7 -0
  54. package/dist/twins/engine/v3/chunks/VDIRUSCM.mjs +2 -0
  55. package/dist/twins/engine/v3/chunks/WGUCFQK6.mjs +2 -0
  56. package/dist/twins/engine/v3/chunks/WPATONSC.mjs +2 -0
  57. package/dist/twins/engine/v3/react_jsx-runtime.mjs +2 -0
  58. package/dist/twins/engine/v3/volter_world-core.mjs +2 -0
  59. package/dist/twins/engine/v3/volter_world-ui.mjs +559 -0
  60. package/dist/twins/packs/ahrefs/LICENSE +202 -0
  61. package/dist/twins/packs/ahrefs/NOTICE +7 -0
  62. package/dist/twins/packs/ahrefs/index.mjs +2 -0
  63. package/dist/twins/packs/ai-gateway/LICENSE +202 -0
  64. package/dist/twins/packs/ai-gateway/NOTICE +7 -0
  65. package/dist/twins/packs/ai-gateway/index.mjs +14 -0
  66. package/dist/twins/packs/airtable/LICENSE +202 -0
  67. package/dist/twins/packs/airtable/NOTICE +7 -0
  68. package/dist/twins/packs/airtable/index.mjs +2 -0
  69. package/dist/twins/packs/algolia/LICENSE +202 -0
  70. package/dist/twins/packs/algolia/NOTICE +7 -0
  71. package/dist/twins/packs/algolia/index.mjs +2 -0
  72. package/dist/twins/packs/ambientcg/LICENSE +202 -0
  73. package/dist/twins/packs/ambientcg/NOTICE +7 -0
  74. package/dist/twins/packs/ambientcg/index.mjs +2 -0
  75. package/dist/twins/packs/anthropic/LICENSE +202 -0
  76. package/dist/twins/packs/anthropic/NOTICE +7 -0
  77. package/dist/twins/packs/anthropic/index.mjs +18 -0
  78. package/dist/twins/packs/assemblyai/LICENSE +202 -0
  79. package/dist/twins/packs/assemblyai/NOTICE +7 -0
  80. package/dist/twins/packs/assemblyai/index.mjs +11 -0
  81. package/dist/twins/packs/aws/LICENSE +202 -0
  82. package/dist/twins/packs/aws/NOTICE +7 -0
  83. package/dist/twins/packs/aws/index.mjs +2 -0
  84. package/dist/twins/packs/azure/LICENSE +202 -0
  85. package/dist/twins/packs/azure/NOTICE +7 -0
  86. package/dist/twins/packs/azure/index.mjs +38 -0
  87. package/dist/twins/packs/azureformrecognizer/LICENSE +202 -0
  88. package/dist/twins/packs/azureformrecognizer/NOTICE +7 -0
  89. package/dist/twins/packs/azureformrecognizer/index.mjs +3 -0
  90. package/dist/twins/packs/bitly/LICENSE +202 -0
  91. package/dist/twins/packs/bitly/NOTICE +7 -0
  92. package/dist/twins/packs/bitly/index.mjs +2 -0
  93. package/dist/twins/packs/bluesky/LICENSE +202 -0
  94. package/dist/twins/packs/bluesky/NOTICE +7 -0
  95. package/dist/twins/packs/bluesky/index.mjs +30 -0
  96. package/dist/twins/packs/calcom/LICENSE +202 -0
  97. package/dist/twins/packs/calcom/NOTICE +7 -0
  98. package/dist/twins/packs/calcom/index.mjs +2 -0
  99. package/dist/twins/packs/clerk/LICENSE +202 -0
  100. package/dist/twins/packs/clerk/NOTICE +7 -0
  101. package/dist/twins/packs/clerk/index.mjs +5 -0
  102. package/dist/twins/packs/cloudflare/LICENSE +202 -0
  103. package/dist/twins/packs/cloudflare/NOTICE +7 -0
  104. package/dist/twins/packs/cloudflare/index.mjs +79 -0
  105. package/dist/twins/packs/cohere/LICENSE +202 -0
  106. package/dist/twins/packs/cohere/NOTICE +7 -0
  107. package/dist/twins/packs/cohere/index.mjs +2 -0
  108. package/dist/twins/packs/datadog/LICENSE +202 -0
  109. package/dist/twins/packs/datadog/NOTICE +7 -0
  110. package/dist/twins/packs/datadog/index.mjs +3 -0
  111. package/dist/twins/packs/deepinfra/LICENSE +202 -0
  112. package/dist/twins/packs/deepinfra/NOTICE +7 -0
  113. package/dist/twins/packs/deepinfra/index.mjs +13 -0
  114. package/dist/twins/packs/deepseek/LICENSE +202 -0
  115. package/dist/twins/packs/deepseek/NOTICE +7 -0
  116. package/dist/twins/packs/deepseek/index.mjs +12 -0
  117. package/dist/twins/packs/discord/LICENSE +202 -0
  118. package/dist/twins/packs/discord/NOTICE +7 -0
  119. package/dist/twins/packs/discord/index.mjs +2 -0
  120. package/dist/twins/packs/duckduckgo/LICENSE +202 -0
  121. package/dist/twins/packs/duckduckgo/NOTICE +7 -0
  122. package/dist/twins/packs/duckduckgo/index.mjs +532 -0
  123. package/dist/twins/packs/dynadot/LICENSE +202 -0
  124. package/dist/twins/packs/dynadot/NOTICE +7 -0
  125. package/dist/twins/packs/dynadot/index.mjs +2 -0
  126. package/dist/twins/packs/e2b/LICENSE +202 -0
  127. package/dist/twins/packs/e2b/NOTICE +7 -0
  128. package/dist/twins/packs/e2b/index.mjs +2 -0
  129. package/dist/twins/packs/elevenlabs/LICENSE +202 -0
  130. package/dist/twins/packs/elevenlabs/NOTICE +7 -0
  131. package/dist/twins/packs/elevenlabs/index.mjs +4 -0
  132. package/dist/twins/packs/expo/LICENSE +202 -0
  133. package/dist/twins/packs/expo/NOTICE +7 -0
  134. package/dist/twins/packs/expo/index.mjs +2 -0
  135. package/dist/twins/packs/fal/LICENSE +202 -0
  136. package/dist/twins/packs/fal/NOTICE +7 -0
  137. package/dist/twins/packs/fal/index.mjs +2 -0
  138. package/dist/twins/packs/figma/LICENSE +202 -0
  139. package/dist/twins/packs/figma/NOTICE +7 -0
  140. package/dist/twins/packs/figma/index.mjs +2 -0
  141. package/dist/twins/packs/firecrawl/LICENSE +202 -0
  142. package/dist/twins/packs/firecrawl/NOTICE +7 -0
  143. package/dist/twins/packs/firecrawl/index.mjs +9 -0
  144. package/dist/twins/packs/fireworks/LICENSE +202 -0
  145. package/dist/twins/packs/fireworks/NOTICE +7 -0
  146. package/dist/twins/packs/fireworks/index.mjs +13 -0
  147. package/dist/twins/packs/fly/LICENSE +202 -0
  148. package/dist/twins/packs/fly/NOTICE +7 -0
  149. package/dist/twins/packs/fly/index.mjs +2 -0
  150. package/dist/twins/packs/gcs/LICENSE +202 -0
  151. package/dist/twins/packs/gcs/NOTICE +7 -0
  152. package/dist/twins/packs/gcs/index.mjs +8 -0
  153. package/dist/twins/packs/gemini/LICENSE +202 -0
  154. package/dist/twins/packs/gemini/NOTICE +7 -0
  155. package/dist/twins/packs/gemini/index.mjs +7 -0
  156. package/dist/twins/packs/github/LICENSE +202 -0
  157. package/dist/twins/packs/github/NOTICE +7 -0
  158. package/dist/twins/packs/github/index.mjs +75153 -0
  159. package/dist/twins/packs/googleads/LICENSE +202 -0
  160. package/dist/twins/packs/googleads/NOTICE +7 -0
  161. package/dist/twins/packs/googleads/index.mjs +3 -0
  162. package/dist/twins/packs/googlemaps/LICENSE +202 -0
  163. package/dist/twins/packs/googlemaps/NOTICE +7 -0
  164. package/dist/twins/packs/googlemaps/index.mjs +2 -0
  165. package/dist/twins/packs/googleoauth/LICENSE +202 -0
  166. package/dist/twins/packs/googleoauth/NOTICE +7 -0
  167. package/dist/twins/packs/googleoauth/index.mjs +2 -0
  168. package/dist/twins/packs/hackernews/LICENSE +202 -0
  169. package/dist/twins/packs/hackernews/NOTICE +7 -0
  170. package/dist/twins/packs/hackernews/index.mjs +35 -0
  171. package/dist/twins/packs/huggingface/LICENSE +202 -0
  172. package/dist/twins/packs/huggingface/NOTICE +7 -0
  173. package/dist/twins/packs/huggingface/index.mjs +9 -0
  174. package/dist/twins/packs/inngest/LICENSE +202 -0
  175. package/dist/twins/packs/inngest/NOTICE +7 -0
  176. package/dist/twins/packs/inngest/index.mjs +2 -0
  177. package/dist/twins/packs/instagram/LICENSE +202 -0
  178. package/dist/twins/packs/instagram/NOTICE +7 -0
  179. package/dist/twins/packs/instagram/index.mjs +2 -0
  180. package/dist/twins/packs/jira/LICENSE +202 -0
  181. package/dist/twins/packs/jira/NOTICE +7 -0
  182. package/dist/twins/packs/jira/index.mjs +2 -0
  183. package/dist/twins/packs/langfuse/LICENSE +202 -0
  184. package/dist/twins/packs/langfuse/NOTICE +7 -0
  185. package/dist/twins/packs/langfuse/index.mjs +2 -0
  186. package/dist/twins/packs/linear/LICENSE +202 -0
  187. package/dist/twins/packs/linear/NOTICE +7 -0
  188. package/dist/twins/packs/linear/index.mjs +52866 -0
  189. package/dist/twins/packs/linkedin/LICENSE +202 -0
  190. package/dist/twins/packs/linkedin/NOTICE +7 -0
  191. package/dist/twins/packs/linkedin/index.mjs +78 -0
  192. package/dist/twins/packs/livekit/LICENSE +202 -0
  193. package/dist/twins/packs/livekit/NOTICE +7 -0
  194. package/dist/twins/packs/livekit/index.mjs +2 -0
  195. package/dist/twins/packs/mailgun/LICENSE +202 -0
  196. package/dist/twins/packs/mailgun/NOTICE +7 -0
  197. package/dist/twins/packs/mailgun/index.mjs +13 -0
  198. package/dist/twins/packs/mapbox/LICENSE +202 -0
  199. package/dist/twins/packs/mapbox/NOTICE +7 -0
  200. package/dist/twins/packs/mapbox/index.mjs +2 -0
  201. package/dist/twins/packs/merge/LICENSE +202 -0
  202. package/dist/twins/packs/merge/NOTICE +7 -0
  203. package/dist/twins/packs/merge/index.mjs +4 -0
  204. package/dist/twins/packs/mistral/LICENSE +202 -0
  205. package/dist/twins/packs/mistral/NOTICE +7 -0
  206. package/dist/twins/packs/mistral/index.mjs +6 -0
  207. package/dist/twins/packs/mixpanel/LICENSE +202 -0
  208. package/dist/twins/packs/mixpanel/NOTICE +8 -0
  209. package/dist/twins/packs/mixpanel/index.mjs +2 -0
  210. package/dist/twins/packs/mongodb/LICENSE +202 -0
  211. package/dist/twins/packs/mongodb/NOTICE +7 -0
  212. package/dist/twins/packs/mongodb/index.mjs +8 -0
  213. package/dist/twins/packs/moonshot/LICENSE +202 -0
  214. package/dist/twins/packs/moonshot/NOTICE +7 -0
  215. package/dist/twins/packs/moonshot/index.mjs +18 -0
  216. package/dist/twins/packs/notion/LICENSE +202 -0
  217. package/dist/twins/packs/notion/NOTICE +7 -0
  218. package/dist/twins/packs/notion/index.mjs +2 -0
  219. package/dist/twins/packs/npm-registry/LICENSE +202 -0
  220. package/dist/twins/packs/npm-registry/NOTICE +7 -0
  221. package/dist/twins/packs/npm-registry/index.mjs +2 -0
  222. package/dist/twins/packs/oa-treasury/LICENSE +202 -0
  223. package/dist/twins/packs/oa-treasury/NOTICE +8 -0
  224. package/dist/twins/packs/oa-treasury/index.mjs +16 -0
  225. package/dist/twins/packs/openai/LICENSE +202 -0
  226. package/dist/twins/packs/openai/NOTICE +7 -0
  227. package/dist/twins/packs/openai/index.mjs +3473 -0
  228. package/dist/twins/packs/openrouter/LICENSE +202 -0
  229. package/dist/twins/packs/openrouter/NOTICE +7 -0
  230. package/dist/twins/packs/openrouter/index.mjs +2 -0
  231. package/dist/twins/packs/openweather/LICENSE +202 -0
  232. package/dist/twins/packs/openweather/NOTICE +7 -0
  233. package/dist/twins/packs/openweather/index.mjs +2 -0
  234. package/dist/twins/packs/paypal/LICENSE +202 -0
  235. package/dist/twins/packs/paypal/NOTICE +7 -0
  236. package/dist/twins/packs/paypal/index.mjs +51 -0
  237. package/dist/twins/packs/pinecone/LICENSE +202 -0
  238. package/dist/twins/packs/pinecone/NOTICE +7 -0
  239. package/dist/twins/packs/pinecone/index.mjs +2 -0
  240. package/dist/twins/packs/plain/LICENSE +202 -0
  241. package/dist/twins/packs/plain/NOTICE +8 -0
  242. package/dist/twins/packs/plain/index.mjs +18426 -0
  243. package/dist/twins/packs/planetscale/LICENSE +202 -0
  244. package/dist/twins/packs/planetscale/NOTICE +7 -0
  245. package/dist/twins/packs/planetscale/index.mjs +18 -0
  246. package/dist/twins/packs/polar/LICENSE +202 -0
  247. package/dist/twins/packs/polar/NOTICE +7 -0
  248. package/dist/twins/packs/polar/index.mjs +2 -0
  249. package/dist/twins/packs/polyhaven/LICENSE +202 -0
  250. package/dist/twins/packs/polyhaven/NOTICE +7 -0
  251. package/dist/twins/packs/polyhaven/index.mjs +3 -0
  252. package/dist/twins/packs/postmark/LICENSE +202 -0
  253. package/dist/twins/packs/postmark/NOTICE +7 -0
  254. package/dist/twins/packs/postmark/index.mjs +12 -0
  255. package/dist/twins/packs/reddit/LICENSE +202 -0
  256. package/dist/twins/packs/reddit/NOTICE +7 -0
  257. package/dist/twins/packs/reddit/index.mjs +324 -0
  258. package/dist/twins/packs/redis/LICENSE +202 -0
  259. package/dist/twins/packs/redis/NOTICE +7 -0
  260. package/dist/twins/packs/redis/index.mjs +2 -0
  261. package/dist/twins/packs/replicate/LICENSE +202 -0
  262. package/dist/twins/packs/replicate/NOTICE +7 -0
  263. package/dist/twins/packs/replicate/index.mjs +2 -0
  264. package/dist/twins/packs/resend/LICENSE +202 -0
  265. package/dist/twins/packs/resend/NOTICE +7 -0
  266. package/dist/twins/packs/resend/index.mjs +139 -0
  267. package/dist/twins/packs/runhuman/LICENSE +202 -0
  268. package/dist/twins/packs/runhuman/NOTICE +7 -0
  269. package/dist/twins/packs/runhuman/index.mjs +3 -0
  270. package/dist/twins/packs/scrapecreators/LICENSE +202 -0
  271. package/dist/twins/packs/scrapecreators/NOTICE +7 -0
  272. package/dist/twins/packs/scrapecreators/index.mjs +2 -0
  273. package/dist/twins/packs/segment/LICENSE +202 -0
  274. package/dist/twins/packs/segment/NOTICE +8 -0
  275. package/dist/twins/packs/segment/index.mjs +2 -0
  276. package/dist/twins/packs/sendblue/LICENSE +202 -0
  277. package/dist/twins/packs/sendblue/NOTICE +7 -0
  278. package/dist/twins/packs/sendblue/index.mjs +2 -0
  279. package/dist/twins/packs/sendgrid/LICENSE +202 -0
  280. package/dist/twins/packs/sendgrid/NOTICE +8 -0
  281. package/dist/twins/packs/sendgrid/index.mjs +4 -0
  282. package/dist/twins/packs/sentry/LICENSE +202 -0
  283. package/dist/twins/packs/sentry/NOTICE +7 -0
  284. package/dist/twins/packs/sentry/index.mjs +5 -0
  285. package/dist/twins/packs/sigstore/LICENSE +202 -0
  286. package/dist/twins/packs/sigstore/NOTICE +7 -0
  287. package/dist/twins/packs/sigstore/index.mjs +12 -0
  288. package/dist/twins/packs/slack/LICENSE +202 -0
  289. package/dist/twins/packs/slack/NOTICE +7 -0
  290. package/dist/twins/packs/slack/index.mjs +66 -0
  291. package/dist/twins/packs/smtp/LICENSE +202 -0
  292. package/dist/twins/packs/smtp/NOTICE +7 -0
  293. package/dist/twins/packs/smtp/index.mjs +3 -0
  294. package/dist/twins/packs/snowflake/LICENSE +202 -0
  295. package/dist/twins/packs/snowflake/NOTICE +8 -0
  296. package/dist/twins/packs/snowflake/index.mjs +30 -0
  297. package/dist/twins/packs/stigg/LICENSE +202 -0
  298. package/dist/twins/packs/stigg/NOTICE +8 -0
  299. package/dist/twins/packs/stigg/index.mjs +22194 -0
  300. package/dist/twins/packs/stream/LICENSE +202 -0
  301. package/dist/twins/packs/stream/NOTICE +7 -0
  302. package/dist/twins/packs/stream/index.mjs +2 -0
  303. package/dist/twins/packs/stripe/LICENSE +202 -0
  304. package/dist/twins/packs/stripe/NOTICE +7 -0
  305. package/dist/twins/packs/stripe/index.mjs +211 -0
  306. package/dist/twins/packs/supabase/LICENSE +202 -0
  307. package/dist/twins/packs/supabase/NOTICE +7 -0
  308. package/dist/twins/packs/supabase/index.mjs +2 -0
  309. package/dist/twins/packs/supermemory/LICENSE +202 -0
  310. package/dist/twins/packs/supermemory/NOTICE +7 -0
  311. package/dist/twins/packs/supermemory/index.mjs +2 -0
  312. package/dist/twins/packs/svix/LICENSE +202 -0
  313. package/dist/twins/packs/svix/NOTICE +7 -0
  314. package/dist/twins/packs/svix/index.mjs +2 -0
  315. package/dist/twins/packs/tavily/LICENSE +202 -0
  316. package/dist/twins/packs/tavily/NOTICE +7 -0
  317. package/dist/twins/packs/tavily/index.mjs +2 -0
  318. package/dist/twins/packs/telegram/LICENSE +202 -0
  319. package/dist/twins/packs/telegram/NOTICE +7 -0
  320. package/dist/twins/packs/telegram/index.mjs +11 -0
  321. package/dist/twins/packs/temporal/LICENSE +202 -0
  322. package/dist/twins/packs/temporal/NOTICE +7 -0
  323. package/dist/twins/packs/temporal/index.mjs +44 -0
  324. package/dist/twins/packs/tiktok/LICENSE +202 -0
  325. package/dist/twins/packs/tiktok/NOTICE +7 -0
  326. package/dist/twins/packs/tiktok/index.mjs +2 -0
  327. package/dist/twins/packs/tinybird/LICENSE +202 -0
  328. package/dist/twins/packs/tinybird/NOTICE +7 -0
  329. package/dist/twins/packs/tinybird/index.mjs +50 -0
  330. package/dist/twins/packs/togetherai/LICENSE +202 -0
  331. package/dist/twins/packs/togetherai/NOTICE +7 -0
  332. package/dist/twins/packs/togetherai/index.mjs +11 -0
  333. package/dist/twins/packs/tremendous/LICENSE +202 -0
  334. package/dist/twins/packs/tremendous/NOTICE +7 -0
  335. package/dist/twins/packs/tremendous/index.mjs +2 -0
  336. package/dist/twins/packs/tripo/LICENSE +202 -0
  337. package/dist/twins/packs/tripo/NOTICE +7 -0
  338. package/dist/twins/packs/tripo/index.mjs +9 -0
  339. package/dist/twins/packs/tunnel/LICENSE +202 -0
  340. package/dist/twins/packs/tunnel/NOTICE +7 -0
  341. package/dist/twins/packs/tunnel/index.mjs +2 -0
  342. package/dist/twins/packs/twelvelabs/LICENSE +202 -0
  343. package/dist/twins/packs/twelvelabs/NOTICE +7 -0
  344. package/dist/twins/packs/twelvelabs/index.mjs +5 -0
  345. package/dist/twins/packs/twilio/LICENSE +202 -0
  346. package/dist/twins/packs/twilio/NOTICE +7 -0
  347. package/dist/twins/packs/twilio/index.mjs +2 -0
  348. package/dist/twins/packs/twitch/LICENSE +202 -0
  349. package/dist/twins/packs/twitch/NOTICE +7 -0
  350. package/dist/twins/packs/twitch/index.mjs +68 -0
  351. package/dist/twins/packs/upstash/LICENSE +202 -0
  352. package/dist/twins/packs/upstash/NOTICE +7 -0
  353. package/dist/twins/packs/upstash/index.mjs +14 -0
  354. package/dist/twins/packs/upstashvector/LICENSE +202 -0
  355. package/dist/twins/packs/upstashvector/NOTICE +7 -0
  356. package/dist/twins/packs/upstashvector/index.mjs +3 -0
  357. package/dist/twins/packs/vercel/LICENSE +202 -0
  358. package/dist/twins/packs/vercel/NOTICE +7 -0
  359. package/dist/twins/packs/vercel/index.mjs +10 -0
  360. package/dist/twins/packs/veriff/LICENSE +202 -0
  361. package/dist/twins/packs/veriff/NOTICE +7 -0
  362. package/dist/twins/packs/veriff/index.mjs +2 -0
  363. package/dist/twins/packs/vgauth/LICENSE +202 -0
  364. package/dist/twins/packs/vgauth/NOTICE +7 -0
  365. package/dist/twins/packs/vgauth/index.mjs +2 -0
  366. package/dist/twins/packs/vital/LICENSE +202 -0
  367. package/dist/twins/packs/vital/NOTICE +7 -0
  368. package/dist/twins/packs/vital/index.mjs +2 -0
  369. package/dist/twins/packs/volteridentity/LICENSE +202 -0
  370. package/dist/twins/packs/volteridentity/NOTICE +7 -0
  371. package/dist/twins/packs/volteridentity/index.mjs +2 -0
  372. package/dist/twins/packs/webrisk/LICENSE +202 -0
  373. package/dist/twins/packs/webrisk/NOTICE +7 -0
  374. package/dist/twins/packs/webrisk/index.mjs +2 -0
  375. package/dist/twins/packs/worldlabs/LICENSE +202 -0
  376. package/dist/twins/packs/worldlabs/NOTICE +7 -0
  377. package/dist/twins/packs/worldlabs/index.mjs +2 -0
  378. package/dist/twins/packs/x/LICENSE +202 -0
  379. package/dist/twins/packs/x/NOTICE +7 -0
  380. package/dist/twins/packs/x/index.mjs +63 -0
  381. package/dist/twins/packs/xai/LICENSE +202 -0
  382. package/dist/twins/packs/xai/NOTICE +7 -0
  383. package/dist/twins/packs/xai/index.mjs +4 -0
  384. package/dist/twins/packs/xidentity/LICENSE +202 -0
  385. package/dist/twins/packs/xidentity/NOTICE +8 -0
  386. package/dist/twins/packs/xidentity/index.mjs +209 -0
  387. package/dist/twins/packs/youtube/LICENSE +202 -0
  388. package/dist/twins/packs/youtube/NOTICE +7 -0
  389. package/dist/twins/packs/youtube/index.mjs +5 -0
  390. package/dist/worker.js +442 -18
  391. package/dist/world-host.js +928 -91
  392. package/package.json +5 -4
  393. package/dist/dashboard/assets/dashboard/bay-morning.png +0 -0
  394. package/dist/dashboard/assets/dashboard/golden-gate-afternoon.png +0 -0
  395. package/dist/dashboard/assets/dashboard/golden-gate-portrait.png +0 -0
  396. package/dist/dashboard/assets/dashboard/moonlit-coast.png +0 -0
  397. package/dist/dashboard/assets/next/static/chunks/2868-424d32cfc8ae81c9.js +0 -1
  398. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-f9fca2c08f779fa0.js +0 -1
  399. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-bc480c9258e5cc4d.js +0 -1
  400. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-f04c0b236abaead3.js +0 -1
  401. package/dist/dashboard/assets/next/static/css/4af3c8ca0da0f48b.css +0 -1
  402. package/dist/dashboard/assets/next/static/css/6b8edde77e493a51.css +0 -1
  403. package/dist/dashboard/assets/next/static/media/bay-morning.1a9f358c.png +0 -0
  404. package/dist/dashboard/assets/next/static/media/golden-gate-afternoon.3e7cea58.png +0 -0
  405. package/dist/dashboard/assets/next/static/media/golden-gate-portrait.7941528f.png +0 -0
  406. package/dist/dashboard/assets/next/static/media/moonlit-coast.bbe901a1.png +0 -0
  407. /package/dist/dashboard/assets/next/static/{5ub3D2yzS8DE7w2qZd1nv → 8f121VqXS9LLPMmYd1SRn}/_buildManifest.js +0 -0
  408. /package/dist/dashboard/assets/next/static/{5ub3D2yzS8DE7w2qZd1nv → 8f121VqXS9LLPMmYd1SRn}/_ssgManifest.js +0 -0
@@ -0,0 +1,8 @@
1
+ import{createRequire as __atReq}from'node:module';const require=__atReq(import.meta.url);
2
+ import{createHash as xo}from"node:crypto";import{worldNow as ws}from"../../engine/v2/volter_world-core.mjs";import{randomBytes as Ho}from"crypto";var Jo=(()=>{let e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>e.call(t)})();function et(e){return Jo(e)==="Uint8Array"}function En(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&(e[Symbol.toStringTag]==="ArrayBuffer"||e[Symbol.toStringTag]==="SharedArrayBuffer")}function tt(e){return e instanceof RegExp||Object.prototype.toString.call(e)==="[object RegExp]"}function Nn(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&e[Symbol.toStringTag]==="Map"}function nt(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function se(e,t){return JSON.stringify(e,(n,r)=>typeof r=="bigint"?{$numberLong:`${r}`}:Nn(r)?Object.fromEntries(r):r)}function Ko(e){if(e!=null&&typeof e=="object"&&"stylize"in e&&typeof e.stylize=="function")return e.stylize}var qe=6,it=Symbol.for("@@mdb.bson.version"),$t=2147483647,St=-2147483648,br=Math.pow(2,63)-1,$r=-Math.pow(2,63),Sr=Math.pow(2,53),Or=-Math.pow(2,53),Bn=1,Er=2,xn=3,Nr=4,In=5,Go=6,Br=7,xr=8,Ir=9,An=10,_t=11,Zo=12,Tn=13,Ar=14,Tr=15,yt=16,_r=17,_n=18,Lr=19,Mr=255,kr=127,Xo=0,Ln=4,Qo=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127}),g=class extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,n){super(t,n)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}},je=class extends g{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${qe}.x.x`)}},wt=class extends g{get name(){return"BSONRuntimeError"}constructor(t){super(t)}},me=class extends g{get name(){return"BSONOffsetError"}constructor(t,n,r){super(`${t}. offset: ${n}`,r),this.offset=n}},or,ir;function Ur(e,t,n,r){if(r){or??=new TextDecoder("utf8",{fatal:!0});try{return or.decode(e.subarray(t,n))}catch(o){throw new g("Invalid UTF-8 string in BSON document",{cause:o})}}return ir??=new TextDecoder("utf8",{fatal:!1}),ir.decode(e.subarray(t,n))}function Dr(e,t,n){if(e.length===0)return"";let r=n-t;if(r===0)return"";if(r>20)return null;if(r===1&&e[t]<128)return String.fromCharCode(e[t]);if(r===2&&e[t]<128&&e[t+1]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1]);if(r===3&&e[t]<128&&e[t+1]<128&&e[t+2]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1])+String.fromCharCode(e[t+2]);let o=[];for(let i=t;i<n;i++){let s=e[i];if(s>127)return null;o.push(s)}return String.fromCharCode(...o)}function vo(e,t,n){if(t.length===0)return 0;if(t.length>25||e.length-n<t.length)return null;for(let r=0,o=n;r<t.length;r++,o++){let i=t.charCodeAt(r);if(i>127)return null;e[o]=i}return t.length}var Ue={toLocalBufferType(e){if(Buffer.isBuffer(e))return e;if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);let t=e?.[Symbol.toStringTag]??Object.prototype.toString.call(e);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(e);throw new g("Cannot create Buffer from the passed potentialBuffer.")},allocate(e){return Buffer.alloc(e)},allocateUnsafe(e){return Buffer.allocUnsafe(e)},equals(e,t){return Ue.toLocalBufferType(e).equals(t)},fromNumberArray(e){return Buffer.from(e)},fromBase64(e){return Buffer.from(e,"base64")},toBase64(e){return Ue.toLocalBufferType(e).toString("base64")},fromISO88591(e){return Buffer.from(e,"binary")},toISO88591(e){return Ue.toLocalBufferType(e).toString("binary")},fromHex(e){return Buffer.from(e,"hex")},toHex(e){return Ue.toLocalBufferType(e).toString("hex")},toUTF8(e,t,n,r){let o=n-t<=20?Dr(e,t,n):null;if(o!=null)return o;let i=Ue.toLocalBufferType(e).toString("utf8",t,n);if(r){for(let s=0;s<i.length;s++)if(i.charCodeAt(s)===65533){Ur(e,t,n,!0);break}}return i},utf8ByteLength(e){return Buffer.byteLength(e,"utf8")},encodeUTF8Into(e,t,n){let r=vo(e,t,n);return r??Ue.toLocalBufferType(e).write(t,n,void 0,"utf8")},randomBytes:Ho,swap32(e){return Ue.toLocalBufferType(e).swap32()}};function ei(){let{navigator:e}=globalThis;return typeof e=="object"&&e.product==="ReactNative"}function ti(e){if(e<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${e}`);return bt.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}var ni=(()=>{let{crypto:e}=globalThis;if(e!=null&&typeof e.getRandomValues=="function")return t=>e.getRandomValues(bt.allocate(t));if(ei()){let{console:t}=globalThis;t?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return ti})(),sr=/(\d|[a-f])/i,bt={toLocalBufferType(e){let t=e?.[Symbol.toStringTag]??Object.prototype.toString.call(e);if(t==="Uint8Array")return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(e);throw new g("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(e){if(typeof e!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(e)}`);return new Uint8Array(e)},allocateUnsafe(e){return bt.allocate(e)},equals(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},fromNumberArray(e){return Uint8Array.from(e)},fromBase64(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))},toBase64(e){return btoa(bt.toISO88591(e))},fromISO88591(e){return Uint8Array.from(e,t=>t.charCodeAt(0)&255)},toISO88591(e){return Array.from(Uint16Array.from(e),t=>String.fromCharCode(t)).join("")},fromHex(e){let t=e.length%2===0?e:e.slice(0,e.length-1),n=[];for(let r=0;r<t.length;r+=2){let o=t[r],i=t[r+1];if(!sr.test(o)||!sr.test(i))break;let s=Number.parseInt(`${o}${i}`,16);n.push(s)}return Uint8Array.from(n)},toHex(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(e,t,n,r){let o=n-t<=20?Dr(e,t,n):null;return o??Ur(e,t,n,r)},utf8ByteLength(e){return new TextEncoder().encode(e).byteLength},encodeUTF8Into(e,t,n){let r=new TextEncoder().encode(t);return e.set(r,n),r.byteLength},randomBytes:ni,swap32(e){if(e.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e.length;t+=4){let n=e[t],r=e[t+1],o=e[t+2],i=e[t+3];e[t]=i,e[t+1]=o,e[t+2]=r,e[t+3]=n}return e}},ri=typeof Buffer=="function"&&Buffer.prototype?._isBuffer!==!0,h=ri?Ue:bt,ee=class{get[it](){return qe}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return this.inspect(t,n,r)}},rt=new Float64Array(1),R=new Uint8Array(rt.buffer,0,8);rt[0]=-1;var Xt=R[7]===0,I={isBigEndian:Xt,getNonnegativeInt32LE(e,t){if(e[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getInt32LE(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getUint32LE(e,t){return e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216},getUint32BE(e,t){return e[t+3]+e[t+2]*256+e[t+1]*65536+e[t]*16777216},getBigInt64LE(e,t){let n=BigInt(e[t+4]+e[t+5]*256+e[t+6]*65536+(e[t+7]<<24)),r=BigInt(e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216);return(n<<BigInt(32))+r},getFloat64LE:Xt?(e,t)=>(R[7]=e[t],R[6]=e[t+1],R[5]=e[t+2],R[4]=e[t+3],R[3]=e[t+4],R[2]=e[t+5],R[1]=e[t+6],R[0]=e[t+7],rt[0]):(e,t)=>(R[0]=e[t],R[1]=e[t+1],R[2]=e[t+2],R[3]=e[t+3],R[4]=e[t+4],R[5]=e[t+5],R[6]=e[t+6],R[7]=e[t+7],rt[0]),setInt32BE(e,t,n){return e[t+3]=n,n>>>=8,e[t+2]=n,n>>>=8,e[t+1]=n,n>>>=8,e[t]=n,4},setInt32LE(e,t,n){return e[t]=n,n>>>=8,e[t+1]=n,n>>>=8,e[t+2]=n,n>>>=8,e[t+3]=n,4},setBigInt64LE(e,t,n){let r=BigInt(4294967295),o=Number(n&r);e[t]=o,o>>=8,e[t+1]=o,o>>=8,e[t+2]=o,o>>=8,e[t+3]=o;let i=Number(n>>BigInt(32)&r);return e[t+4]=i,i>>=8,e[t+5]=i,i>>=8,e[t+6]=i,i>>=8,e[t+7]=i,8},setFloat64LE:Xt?(e,t,n)=>(rt[0]=n,e[t]=R[7],e[t+1]=R[6],e[t+2]=R[5],e[t+3]=R[4],e[t+4]=R[3],e[t+5]=R[2],e[t+6]=R[1],e[t+7]=R[0],8):(e,t,n)=>(rt[0]=n,e[t]=R[0],e[t+1]=R[1],e[t+2]=R[2],e[t+3]=R[3],e[t+4]=R[4],e[t+5]=R[5],e[t+6]=R[6],e[t+7]=R[7],8)},M=class e extends ee{get _bsontype(){return"Binary"}constructor(t,n){if(super(),t!=null&&typeof t=="string"&&!ArrayBuffer.isView(t)&&!En(t)&&!Array.isArray(t))throw new g("Binary can only be constructed from Uint8Array or number[]");this.sub_type=n??e.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=h.allocate(e.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(t)?h.fromNumberArray(t):h.toLocalBufferType(t),this.position=this.buffer.byteLength)}put(t){if(typeof t=="string"&&t.length!==1)throw new g("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new g("only accepts single character Uint8Array or Array");let n;if(typeof t=="string"?n=t.charCodeAt(0):typeof t=="number"?n=t:n=t[0],n<0||n>255)throw new g("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=n;else{let r=h.allocate(e.BUFFER_SIZE+this.buffer.length);r.set(this.buffer,0),this.buffer=r,this.buffer[this.position++]=n}}write(t,n){if(n=typeof n=="number"?n:this.position,this.buffer.byteLength<n+t.length){let r=h.allocate(this.buffer.byteLength+t.length);r.set(this.buffer,0),this.buffer=r}if(ArrayBuffer.isView(t))this.buffer.set(h.toLocalBufferType(t),n),this.position=n+t.byteLength>this.position?n+t.length:this.position;else if(typeof t=="string")throw new g("input cannot be string")}read(t,n){n=n&&n>0?n:this.position;let r=t+n;return this.buffer.subarray(t,r>this.position?this.position:r)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return h.toBase64(this.buffer.subarray(0,this.position))}toString(t){return t==="hex"?h.toHex(this.buffer.subarray(0,this.position)):t==="base64"?h.toBase64(this.buffer.subarray(0,this.position)):t==="utf8"||t==="utf-8"?h.toUTF8(this.buffer,0,this.position,!1):h.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(t){t=t||{},this.sub_type===e.SUBTYPE_VECTOR&&Oe(this);let n=h.toBase64(this.buffer),r=Number(this.sub_type).toString(16);return t.legacy?{$binary:n,$type:r.length===1?"0"+r:r}:{$binary:{base64:n,subType:r.length===1?"0"+r:r}}}toUUID(){if(this.sub_type===e.SUBTYPE_UUID)return new We(this.buffer.subarray(0,this.position));throw new g(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${e.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(t,n){return new e(h.fromHex(t),n)}static createFromBase64(t,n){return new e(h.fromBase64(t),n)}static fromExtendedJSON(t,n){n=n||{};let r,o;if("$binary"in t?n.legacy&&typeof t.$binary=="string"&&"$type"in t?(o=t.$type?parseInt(t.$type,16):0,r=h.fromBase64(t.$binary)):typeof t.$binary!="string"&&(o=t.$binary.subType?parseInt(t.$binary.subType,16):0,r=h.fromBase64(t.$binary.base64)):"$uuid"in t&&(o=4,r=We.bytesFromString(t.$uuid)),!r)throw new g(`Unexpected Binary Extended JSON format ${JSON.stringify(t)}`);return o===Ln?new We(r):new e(r,o)}inspect(t,n,r){r??=se;let o=h.toBase64(this.buffer.subarray(0,this.position)),i=r(o,n),s=r(this.sub_type,n);return`Binary.createFromBase64(${i}, ${s})`}toInt8Array(){if(this.sub_type!==e.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==e.VECTOR_TYPE.Int8)throw new g("Binary datatype field is not Int8");return Oe(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==e.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==e.VECTOR_TYPE.Float32)throw new g("Binary datatype field is not Float32");Oe(this);let t=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return I.isBigEndian&&h.swap32(t),new Float32Array(t.buffer)}toPackedBits(){if(this.sub_type!==e.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==e.VECTOR_TYPE.PackedBit)throw new g("Binary datatype field is not packed bit");return Oe(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==e.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==e.VECTOR_TYPE.PackedBit)throw new g("Binary datatype field is not packed bit");Oe(this);let n=(this.length()-2)*8-this.buffer[1],r=new Int8Array(n);for(let o=0;o<r.length;o++){let i=o/8|0,s=this.buffer[i+2],a=7-o%8,c=s>>a&1;r[o]=c}return r}static fromInt8Array(t){let n=h.allocate(t.byteLength+2);n[0]=e.VECTOR_TYPE.Int8,n[1]=0;let r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(r,2);let o=new this(n,this.SUBTYPE_VECTOR);return Oe(o),o}static fromFloat32Array(t){let n=h.allocate(t.byteLength+2);n[0]=e.VECTOR_TYPE.Float32,n[1]=0;let r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(r,2),I.isBigEndian&&h.swap32(new Uint8Array(n.buffer,2));let o=new this(n,this.SUBTYPE_VECTOR);return Oe(o),o}static fromPackedBits(t,n=0){let r=h.allocate(t.byteLength+2);r[0]=e.VECTOR_TYPE.PackedBit,r[1]=n,r.set(t,2);let o=new this(r,this.SUBTYPE_VECTOR);return Oe(o),o}static fromBits(t){let n=t.length+7>>>3,r=new Uint8Array(n+2);r[0]=e.VECTOR_TYPE.PackedBit;let o=t.length%8;r[1]=o===0?0:8-o;for(let i=0;i<t.length;i++){let s=i>>>3,a=t[i];if(a!==0&&a!==1)throw new g(`Invalid bit value at ${i}: must be 0 or 1, found ${t[i]}`);if(a===0)continue;let c=7-i%8;r[s+2]|=a<<c}return new this(r,e.SUBTYPE_VECTOR)}};M.BSON_BINARY_SUBTYPE_DEFAULT=0;M.BUFFER_SIZE=256;M.SUBTYPE_DEFAULT=0;M.SUBTYPE_FUNCTION=1;M.SUBTYPE_BYTE_ARRAY=2;M.SUBTYPE_UUID_OLD=3;M.SUBTYPE_UUID=4;M.SUBTYPE_MD5=5;M.SUBTYPE_ENCRYPTED=6;M.SUBTYPE_COLUMN=7;M.SUBTYPE_SENSITIVE=8;M.SUBTYPE_VECTOR=9;M.SUBTYPE_USER_DEFINED=128;M.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function Oe(e){if(e.sub_type!==M.SUBTYPE_VECTOR)return;let t=e.position,n=e.buffer[0],r=e.buffer[1];if((n===M.VECTOR_TYPE.Float32||n===M.VECTOR_TYPE.Int8)&&r!==0)throw new g("Invalid Vector: padding must be zero for int8 and float32 vectors");if(n===M.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new g("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(n===M.VECTOR_TYPE.PackedBit&&r!==0&&t===2)throw new g("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(n===M.VECTOR_TYPE.PackedBit&&r>7)throw new g(`Invalid Vector: padding must be a value between 0 and 7. found: ${r}`)}var Qt=16,oi=/^[0-9A-F]{32}$/i,ii=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,We=class e extends M{constructor(t){let n;if(t==null)n=e.generate();else if(t instanceof e)n=h.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===Qt)n=h.toLocalBufferType(t);else if(typeof t=="string")n=e.bytesFromString(t);else throw new g("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(n,Ln)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[h.toHex(this.buffer.subarray(0,4)),h.toHex(this.buffer.subarray(4,6)),h.toHex(this.buffer.subarray(6,8)),h.toHex(this.buffer.subarray(8,10)),h.toHex(this.buffer.subarray(10,16))].join("-"):h.toHex(this.buffer)}toString(t){return t==="hex"?h.toHex(this.id):t==="base64"?h.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof e)return h.equals(t.id,this.id);try{return h.equals(new e(t).id,this.id)}catch{return!1}}toBinary(){return new M(this.id,M.SUBTYPE_UUID)}static generate(){let t=h.randomBytes(Qt);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?e.isValidUUIDString(t):et(t)?t.byteLength===Qt:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){let n=e.bytesFromString(t);return new e(n)}static createFromBase64(t){return new e(h.fromBase64(t))}static bytesFromString(t){if(!e.isValidUUIDString(t))throw new g("UUID string representation must be 32 hex digits or canonical hyphenated representation");return h.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return oi.test(t)||ii.test(t)}inspect(t,n,r){return r??=se,`new UUID(${r(this.toHexString(),n)})`}},Re=class e extends ee{get _bsontype(){return"Code"}constructor(t,n){super(),this.code=t.toString(),this.scope=n??null}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(t){return new e(t.$code,t.$scope)}inspect(t,n,r){r??=se;let o=r(this.code,n),i=o.includes(`
3
+ `);this.scope!=null&&(o+=`,${i?`
4
+ `:" "}${r(this.scope,n)}`);let s=i&&this.scope===null;return`new Code(${i?`
5
+ `:""}${o}${s?`
6
+ `:""})`}};function jr(e){return e!=null&&typeof e=="object"&&"$id"in e&&e.$id!=null&&"$ref"in e&&typeof e.$ref=="string"&&(!("$db"in e)||"$db"in e&&typeof e.$db=="string")}var Ne=class e extends ee{get _bsontype(){return"DBRef"}constructor(t,n,r,o){super();let i=t.split(".");i.length===2&&(r=i.shift(),t=i.shift()),this.collection=t,this.oid=n,this.db=r,this.fields=o||{}}get namespace(){return this.collection}set namespace(t){this.collection=t}toJSON(){let t=Object.assign({$ref:this.collection,$id:this.oid},this.fields);return this.db!=null&&(t.$db=this.db),t}toExtendedJSON(t){t=t||{};let n={$ref:this.collection,$id:this.oid};return t.legacy||(this.db&&(n.$db=this.db),n=Object.assign(n,this.fields)),n}static fromExtendedJSON(t){let n=Object.assign({},t);return delete n.$ref,delete n.$id,delete n.$db,new e(t.$ref,t.$id,t.$db,n)}inspect(t,n,r){r??=se;let o=[r(this.namespace,n),r(this.oid,n),...this.db?[r(this.db,n)]:[],...Object.keys(this.fields).length>0?[r(this.fields,n)]:[]];return o[1]=r===se?`new ObjectId(${o[1]})`:o[1],`new DBRef(${o.join(", ")})`}};function Rr(e){if(e==="")return e;let t=0,n=e[t]==="-",r=e[t]==="+";(r||n)&&(t+=1);let o=!1;for(;t<e.length&&e[t]==="0";++t)o=!0;return o?`${n?"-":""}${e.length===t?"0":e.slice(t)}`:r?e.slice(1):e}function si(e,t){t=t??10;let n="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,t);return new RegExp(`[^-+${n}]`,"i").test(e)?!1:e}var de;try{de=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var ar=65536,ai=1<<24,ot=ar*ar,Cr=ot*ot,ci=Cr/2,cr={},lr={},li=20,fi=/^(\+?0|(\+|-)?[1-9][0-9]*)$/,w=class e extends ee{get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(t=0,n,r){super();let o=typeof n=="boolean"?n:!!r,i=typeof n=="number"?n:0,s=typeof t=="string"?e.fromString(t,o):typeof t=="bigint"?e.fromBigInt(t,o):{low:t|0,high:i|0,unsigned:o};this.low=s.low,this.high=s.high,this.unsigned=s.unsigned}static fromBits(t,n,r){return new e(t,n,r)}static fromInt(t,n){let r,o,i;return n?(t>>>=0,(i=0<=t&&t<256)&&(o=lr[t],o)?o:(r=e.fromBits(t,(t|0)<0?-1:0,!0),i&&(lr[t]=r),r)):(t|=0,(i=-128<=t&&t<128)&&(o=cr[t],o)?o:(r=e.fromBits(t,t<0?-1:0,!1),i&&(cr[t]=r),r))}static fromNumber(t,n){if(isNaN(t))return n?e.UZERO:e.ZERO;if(n){if(t<0)return e.UZERO;if(t>=Cr)return e.MAX_UNSIGNED_VALUE}else{if(t<=-9223372036854776e3)return e.MIN_VALUE;if(t+1>=ci)return e.MAX_VALUE}return t<0?e.fromNumber(-t,n).neg():e.fromBits(t%ot|0,t/ot|0,n)}static fromBigInt(t,n){let r=BigInt(4294967295),o=BigInt(32);return new e(Number(t&r),Number(t>>o&r),n)}static _fromString(t,n,r){if(t.length===0)throw new g("empty string");if(r<2||36<r)throw new g("radix");let o;if((o=t.indexOf("-"))>0)throw new g("interior hyphen");if(o===0)return e._fromString(t.substring(1),n,r).neg();let i=e.fromNumber(Math.pow(r,8)),s=e.ZERO;for(let a=0;a<t.length;a+=8){let c=Math.min(8,t.length-a),f=parseInt(t.substring(a,a+c),r);if(c<8){let l=e.fromNumber(Math.pow(r,c));s=s.mul(l).add(e.fromNumber(f))}else s=s.mul(i),s=s.add(e.fromNumber(f))}return s.unsigned=n,s}static fromStringStrict(t,n,r){let o=!1;if(typeof n=="number"?(r=n,n=!1):o=!!n,r??=10,t.trim()!==t)throw new g(`Input: '${t}' contains leading and/or trailing whitespace`);if(!si(t,r))throw new g(`Input: '${t}' contains invalid characters for radix: ${r}`);let i=Rr(t),s=e._fromString(i,o,r);if(s.toString(r).toLowerCase()!==i.toLowerCase())throw new g(`Input: ${t} is not representable as ${s.unsigned?"an unsigned":"a signed"} 64-bit Long ${r!=null?`with radix: ${r}`:""}`);return s}static fromString(t,n,r){let o=!1;return typeof n=="number"?(r=n,n=!1):o=!!n,r??=10,t==="NaN"&&r<24||(t==="Infinity"||t==="+Infinity"||t==="-Infinity")&&r<35?e.ZERO:e._fromString(t,o,r)}static fromBytes(t,n,r){return r?e.fromBytesLE(t,n):e.fromBytesBE(t,n)}static fromBytesLE(t,n){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)}static fromBytesBE(t,n){return new e(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)}static isLong(t){return t!=null&&typeof t=="object"&&"__isLong__"in t&&t.__isLong__===!0}static fromValue(t,n){return typeof t=="number"?e.fromNumber(t,n):typeof t=="string"?e.fromString(t,n):e.fromBits(t.low,t.high,typeof n=="boolean"?n:t.unsigned)}add(t){e.isLong(t)||(t=e.fromValue(t));let n=this.high>>>16,r=this.high&65535,o=this.low>>>16,i=this.low&65535,s=t.high>>>16,a=t.high&65535,c=t.low>>>16,f=t.low&65535,l=0,u=0,d=0,p=0;return p+=i+f,d+=p>>>16,p&=65535,d+=o+c,u+=d>>>16,d&=65535,u+=r+a,l+=u>>>16,u&=65535,l+=n+s,l&=65535,e.fromBits(d<<16|p,l<<16|u,this.unsigned)}and(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low&t.low,this.high&t.high,this.unsigned)}compare(t){if(e.isLong(t)||(t=e.fromValue(t)),this.eq(t))return 0;let n=this.isNegative(),r=t.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1}comp(t){return this.compare(t)}divide(t){if(e.isLong(t)||(t=e.fromValue(t)),t.isZero())throw new g("division by zero");if(de){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;let i=(this.unsigned?de.div_u:de.div_s)(this.low,this.high,t.low,t.high);return e.fromBits(i,de.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?e.UZERO:e.ZERO;let n,r,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return e.UZERO;if(t.gt(this.shru(1)))return e.UONE;o=e.UZERO}else{if(this.eq(e.MIN_VALUE))return t.eq(e.ONE)||t.eq(e.NEG_ONE)?e.MIN_VALUE:t.eq(e.MIN_VALUE)?e.ONE:(n=this.shr(1).div(t).shl(1),n.eq(e.ZERO)?t.isNegative()?e.ONE:e.NEG_ONE:(r=this.sub(t.mul(n)),o=n.add(r.div(t)),o));if(t.eq(e.MIN_VALUE))return this.unsigned?e.UZERO:e.ZERO;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=e.ZERO}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));let i=Math.ceil(Math.log(n)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=e.fromNumber(n),c=a.mul(t);for(;c.isNegative()||c.gt(r);)n-=s,a=e.fromNumber(n,this.unsigned),c=a.mul(t);a.isZero()&&(a=e.ONE),o=o.add(a),r=r.sub(c)}return o}div(t){return this.divide(t)}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low}eq(t){return this.equals(t)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(e.MIN_VALUE)?64:this.neg().getNumBitsAbs();let t=this.high!==0?this.high:this.low,n;for(n=31;n>0&&(t&1<<n)===0;n--);return this.high!==0?n+33:n+1}greaterThan(t){return this.comp(t)>0}gt(t){return this.greaterThan(t)}greaterThanOrEqual(t){return this.comp(t)>=0}gte(t){return this.greaterThanOrEqual(t)}ge(t){return this.greaterThanOrEqual(t)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(t){return this.comp(t)<0}lt(t){return this.lessThan(t)}lessThanOrEqual(t){return this.comp(t)<=0}lte(t){return this.lessThanOrEqual(t)}modulo(t){if(e.isLong(t)||(t=e.fromValue(t)),de){let n=(this.unsigned?de.rem_u:de.rem_s)(this.low,this.high,t.low,t.high);return e.fromBits(n,de.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))}mod(t){return this.modulo(t)}rem(t){return this.modulo(t)}multiply(t){if(this.isZero())return e.ZERO;if(e.isLong(t)||(t=e.fromValue(t)),de){let b=de.mul(this.low,this.high,t.low,t.high);return e.fromBits(b,de.get_high(),this.unsigned)}if(t.isZero())return e.ZERO;if(this.eq(e.MIN_VALUE))return t.isOdd()?e.MIN_VALUE:e.ZERO;if(t.eq(e.MIN_VALUE))return this.isOdd()?e.MIN_VALUE:e.ZERO;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(e.TWO_PWR_24)&&t.lt(e.TWO_PWR_24))return e.fromNumber(this.toNumber()*t.toNumber(),this.unsigned);let n=this.high>>>16,r=this.high&65535,o=this.low>>>16,i=this.low&65535,s=t.high>>>16,a=t.high&65535,c=t.low>>>16,f=t.low&65535,l=0,u=0,d=0,p=0;return p+=i*f,d+=p>>>16,p&=65535,d+=o*f,u+=d>>>16,d&=65535,d+=i*c,u+=d>>>16,d&=65535,u+=r*f,l+=u>>>16,u&=65535,u+=o*c,l+=u>>>16,u&=65535,u+=i*a,l+=u>>>16,u&=65535,l+=n*f+r*c+o*a+i*s,l&=65535,e.fromBits(d<<16|p,l<<16|u,this.unsigned)}mul(t){return this.multiply(t)}negate(){return!this.unsigned&&this.eq(e.MIN_VALUE)?e.MIN_VALUE:this.not().add(e.ONE)}neg(){return this.negate()}not(){return e.fromBits(~this.low,~this.high,this.unsigned)}notEquals(t){return!this.equals(t)}neq(t){return this.notEquals(t)}ne(t){return this.notEquals(t)}or(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low|t.low,this.high|t.high,this.unsigned)}shiftLeft(t){return e.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?e.fromBits(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):e.fromBits(0,this.low<<t-32,this.unsigned)}shl(t){return this.shiftLeft(t)}shiftRight(t){return e.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?e.fromBits(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):e.fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)}shr(t){return this.shiftRight(t)}shiftRightUnsigned(t){if(e.isLong(t)&&(t=t.toInt()),t&=63,t===0)return this;{let n=this.high;if(t<32){let r=this.low;return e.fromBits(r>>>t|n<<32-t,n>>>t,this.unsigned)}else return t===32?e.fromBits(n,0,this.unsigned):e.fromBits(n>>>t-32,0,this.unsigned)}}shr_u(t){return this.shiftRightUnsigned(t)}shru(t){return this.shiftRightUnsigned(t)}subtract(t){return e.isLong(t)||(t=e.fromValue(t)),this.add(t.neg())}sub(t){return this.subtract(t)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){return this.unsigned?(this.high>>>0)*ot+(this.low>>>0):this.high*ot+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(t){return t?this.toBytesLE():this.toBytesBE()}toBytesLE(){let t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]}toBytesBE(){let t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]}toSigned(){return this.unsigned?e.fromBits(this.low,this.high,!1):this}toString(t){if(t=t||10,t<2||36<t)throw new g("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(e.MIN_VALUE)){let i=e.fromNumber(t),s=this.div(i),a=s.mul(i).sub(this);return s.toString(t)+a.toInt().toString(t)}else return"-"+this.neg().toString(t);let n=e.fromNumber(Math.pow(t,6),this.unsigned),r=this,o="";for(;;){let i=r.div(n),a=(r.sub(i.mul(n)).toInt()>>>0).toString(t);if(r=i,r.isZero())return a+o;for(;a.length<6;)a="0"+a;o=""+a+o}}toUnsigned(){return this.unsigned?this:e.fromBits(this.low,this.high,!0)}xor(t){return e.isLong(t)||(t=e.fromValue(t)),e.fromBits(this.low^t.low,this.high^t.high,this.unsigned)}eqz(){return this.isZero()}le(t){return this.lessThanOrEqual(t)}toExtendedJSON(t){return t&&t.relaxed?this.toNumber():{$numberLong:this.toString()}}static fromExtendedJSON(t,n){let{useBigInt64:r=!1,relaxed:o=!0}={...n};if(t.$numberLong.length>li)throw new g("$numberLong string is too long");if(!fi.test(t.$numberLong))throw new g(`$numberLong string "${t.$numberLong}" is in an invalid format`);if(r){let s=BigInt(t.$numberLong);return BigInt.asIntN(64,s)}let i=e.fromString(t.$numberLong);return o?i.toNumber():i}inspect(t,n,r){r??=se;let o=r(this.toString(),n),i=this.unsigned?`, ${r(this.unsigned,n)}`:"";return`new Long(${o}${i})`}};w.TWO_PWR_24=w.fromInt(ai);w.MAX_UNSIGNED_VALUE=w.fromBits(-1,-1,!0);w.ZERO=w.fromInt(0);w.UZERO=w.fromInt(0,!0);w.ONE=w.fromInt(1);w.UONE=w.fromInt(1,!0);w.NEG_ONE=w.fromInt(-1);w.MAX_VALUE=w.fromBits(-1,2147483647,!1);w.MIN_VALUE=w.fromBits(0,-2147483648,!1);var ui=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,di=/^(\+|-)?(Infinity|inf)$/i,hi=/^(\+|-)?NaN$/i,Qe=6111,pt=-6176,fr=6176,ur=34,vt=h.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),dr=h.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),hr=h.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),gi=/^([-+])?(\d+)?$/,pi=31,gr=16383,mi=30,yi=31;function pr(e){return!isNaN(parseInt(e,10))}function wi(e){let t=w.fromNumber(1e9),n=w.fromNumber(0);if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3])return{quotient:e,rem:n};for(let r=0;r<=3;r++)n=n.shiftLeft(32),n=n.add(new w(e.parts[r],0)),e.parts[r]=n.div(t).low,n=n.modulo(t);return{quotient:e,rem:n}}function bi(e,t){if(!e&&!t)return{high:w.fromNumber(0),low:w.fromNumber(0)};let n=e.shiftRightUnsigned(32),r=new w(e.getLowBits(),0),o=t.shiftRightUnsigned(32),i=new w(t.getLowBits(),0),s=n.multiply(o),a=n.multiply(i),c=r.multiply(o),f=r.multiply(i);return s=s.add(a.shiftRightUnsigned(32)),a=new w(a.getLowBits(),0).add(c).add(f.shiftRightUnsigned(32)),s=s.add(a.shiftRightUnsigned(32)),f=a.shiftLeft(32).add(new w(f.getLowBits(),0)),{high:s,low:f}}function $i(e,t){let n=e.high>>>0,r=t.high>>>0;if(n<r)return!0;if(n===r){let o=e.low>>>0,i=t.low>>>0;if(o<i)return!0}return!1}function pe(e,t){throw new g(`"${e}" is not a valid Decimal128 string - ${t}`)}var Ye=class e extends ee{get _bsontype(){return"Decimal128"}constructor(t){if(super(),typeof t=="string")this.bytes=e.fromString(t).bytes;else if(t instanceof Uint8Array||et(t)){if(t.byteLength!==16)throw new g("Decimal128 must take a Buffer of 16 bytes");this.bytes=t}else throw new g("Decimal128 must take a Buffer or string")}static fromString(t){return e._fromString(t,{allowRounding:!1})}static fromStringWithRounding(t){return e._fromString(t,{allowRounding:!0})}static _fromString(t,n){let r=!1,o=!1,i=!1,s=!1,a=0,c=0,f=0,l=0,u=0,d=[0],p=0,b=0,B=0,D=0,G=new w(0,0),U=new w(0,0),ie=0,E=0;if(t.length>=7e3)throw new g(""+t+" not a valid Decimal128 string");let x=t.match(ui),T=t.match(di),be=t.match(hi);if(!x&&!T&&!be||t.length===0)throw new g(""+t+" not a valid Decimal128 string");if(x){let O=x[2],j=x[4],ue=x[5],Y=x[6];j&&Y===void 0&&pe(t,"missing exponent power"),j&&O===void 0&&pe(t,"missing exponent base"),j===void 0&&(ue||Y)&&pe(t,"missing e before exponent")}if((t[E]==="+"||t[E]==="-")&&(o=!0,r=t[E++]==="-"),!pr(t[E])&&t[E]!=="."){if(t[E]==="i"||t[E]==="I")return new e(r?dr:hr);if(t[E]==="N")return new e(vt)}for(;pr(t[E])||t[E]===".";){if(t[E]==="."){i&&pe(t,"contains multiple periods"),i=!0,E=E+1;continue}p<ur&&(t[E]!=="0"||s)&&(s||(u=c),s=!0,d[b++]=parseInt(t[E],10),p=p+1),s&&(f=f+1),i&&(l=l+1),c=c+1,E=E+1}if(i&&!c)throw new g(""+t+" not a valid Decimal128 string");if(t[E]==="e"||t[E]==="E"){let O=t.substr(++E).match(gi);if(!O||!O[2])return new e(vt);D=parseInt(O[0],10),E=E+O[0].length}if(t[E])return new e(vt);if(!p)d[0]=0,f=1,p=1,a=0;else if(B=p-1,a=f,a!==1)for(;t[u+a-1+Number(o)+Number(i)]==="0";)a=a-1;for(D<=l&&l>D+16384?D=pt:D=D-l;D>Qe;){if(B=B+1,B>=ur){if(a===0){D=Qe;break}pe(t,"overflow")}D=D-1}if(n.allowRounding){for(;D<pt||p<f;){if(B===0&&a<p){D=pt,a=0;break}if(p<f?f=f-1:B=B-1,D<Qe)D=D+1;else{if(d.join("").match(/^0+$/)){D=Qe;break}pe(t,"overflow")}}if(B+1<a){let O=c;i&&(u=u+1,O=O+1),o&&(u=u+1,O=O+1);let j=parseInt(t[u+B+1],10),ue=0;if(j>=5&&(ue=1,j===5)){ue=d[B]%2===1?1:0;for(let Y=u+B+2;Y<O;Y++)if(parseInt(t[Y],10)){ue=1;break}}if(ue){let Y=B;for(;Y>=0&&++d[Y]>9;Y--)if(d[Y]=0,Y===0)if(D<Qe)D=D+1,d[Y]=1;else return new e(r?dr:hr)}}}else{for(;D<pt||p<f;){if(B===0){if(a===0){D=pt;break}pe(t,"exponent underflow")}p<f?(t[f-1+Number(o)+Number(i)]!=="0"&&a!==0&&pe(t,"inexact rounding"),f=f-1):(d[B]!==0&&pe(t,"inexact rounding"),B=B-1),D<Qe?D=D+1:pe(t,"overflow")}B+1<a&&(i&&(u=u+1),o&&(u=u+1),parseInt(t[u+B+1],10)!==0&&pe(t,"inexact rounding"))}if(G=w.fromNumber(0),U=w.fromNumber(0),a===0)G=w.fromNumber(0),U=w.fromNumber(0);else if(B<17){let O=0;for(U=w.fromNumber(d[O++]),G=new w(0,0);O<=B;O++)U=U.multiply(w.fromNumber(10)),U=U.add(w.fromNumber(d[O]))}else{let O=0;for(G=w.fromNumber(d[O++]);O<=B-17;O++)G=G.multiply(w.fromNumber(10)),G=G.add(w.fromNumber(d[O]));for(U=w.fromNumber(d[O++]);O<=B;O++)U=U.multiply(w.fromNumber(10)),U=U.add(w.fromNumber(d[O]))}let Z=bi(G,w.fromString("100000000000000000"));Z.low=Z.low.add(U),$i(Z.low,U)&&(Z.high=Z.high.add(w.fromNumber(1))),ie=D+fr;let N={low:w.fromNumber(0),high:w.fromNumber(0)};Z.high.shiftRightUnsigned(49).and(w.fromNumber(1)).equals(w.fromNumber(1))?(N.high=N.high.or(w.fromNumber(3).shiftLeft(61)),N.high=N.high.or(w.fromNumber(ie).and(w.fromNumber(16383).shiftLeft(47))),N.high=N.high.or(Z.high.and(w.fromNumber(0x7fffffffffff)))):(N.high=N.high.or(w.fromNumber(ie&16383).shiftLeft(49)),N.high=N.high.or(Z.high.and(w.fromNumber(562949953421311)))),N.low=Z.low,r&&(N.high=N.high.or(w.fromString("9223372036854775808")));let S=h.allocateUnsafe(16);return E=0,S[E++]=N.low.low&255,S[E++]=N.low.low>>8&255,S[E++]=N.low.low>>16&255,S[E++]=N.low.low>>24&255,S[E++]=N.low.high&255,S[E++]=N.low.high>>8&255,S[E++]=N.low.high>>16&255,S[E++]=N.low.high>>24&255,S[E++]=N.high.low&255,S[E++]=N.high.low>>8&255,S[E++]=N.high.low>>16&255,S[E++]=N.high.low>>24&255,S[E++]=N.high.high&255,S[E++]=N.high.high>>8&255,S[E++]=N.high.high>>16&255,S[E++]=N.high.high>>24&255,new e(S)}toString(){let t,n=0,r=new Array(36);for(let E=0;E<r.length;E++)r[E]=0;let o=0,i=!1,s,a={parts:[0,0,0,0]},c,f,l=[];o=0;let u=this.bytes,d=u[o++]|u[o++]<<8|u[o++]<<16|u[o++]<<24,p=u[o++]|u[o++]<<8|u[o++]<<16|u[o++]<<24,b=u[o++]|u[o++]<<8|u[o++]<<16|u[o++]<<24,B=u[o++]|u[o++]<<8|u[o++]<<16|u[o++]<<24;o=0,{low:new w(d,p),high:new w(b,B)}.high.lessThan(w.ZERO)&&l.push("-");let G=B>>26&pi;if(G>>3===3){if(G===mi)return l.join("")+"Infinity";if(G===yi)return"NaN";t=B>>15&gr,s=8+(B>>14&1)}else s=B>>14&7,t=B>>17&gr;let U=t-fr;if(a.parts[0]=(B&16383)+((s&15)<<14),a.parts[1]=b,a.parts[2]=p,a.parts[3]=d,a.parts[0]===0&&a.parts[1]===0&&a.parts[2]===0&&a.parts[3]===0)i=!0;else for(f=3;f>=0;f--){let E=0,x=wi(a);if(a=x.quotient,E=x.rem.low,!!E)for(c=8;c>=0;c--)r[f*9+c]=E%10,E=Math.floor(E/10)}if(i)n=1,r[o]=0;else for(n=36;!r[o];)n=n-1,o=o+1;let ie=n-1+U;if(ie>=34||ie<=-7||U>0){if(n>34)return l.push("0"),U>0?l.push(`E+${U}`):U<0&&l.push(`E${U}`),l.join("");l.push(`${r[o++]}`),n=n-1,n&&l.push(".");for(let E=0;E<n;E++)l.push(`${r[o++]}`);l.push("E"),ie>0?l.push(`+${ie}`):l.push(`${ie}`)}else if(U>=0)for(let E=0;E<n;E++)l.push(`${r[o++]}`);else{let E=n+U;if(E>0)for(let x=0;x<E;x++)l.push(`${r[o++]}`);else l.push("0");for(l.push(".");E++<0;)l.push("0");for(let x=0;x<n-Math.max(E-1,0);x++)l.push(`${r[o++]}`)}return l.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(t){return e.fromString(t.$numberDecimal)}inspect(t,n,r){return r??=se,`new Decimal128(${r(this.toString(),n)})`}},Be=class e extends ee{get _bsontype(){return"Double"}constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t}static fromString(t){let n=Number(t);if(t==="NaN")return new e(NaN);if(t==="Infinity")return new e(1/0);if(t==="-Infinity")return new e(-1/0);if(!Number.isFinite(n))throw new g(`Input: ${t} is not representable as a Double`);if(t.trim()!==t)throw new g(`Input: '${t}' contains whitespace`);if(t==="")throw new g("Input is an empty string");if(/[^-0-9.+eE]/.test(t))throw new g(`Input: '${t}' is not in decimal or exponential notation`);return new e(n)}valueOf(){return this.value}toJSON(){return this.value}toString(t){return this.value.toString(t)}toExtendedJSON(t){return t&&(t.legacy||t.relaxed&&isFinite(this.value))?this.value:Object.is(Math.sign(this.value),-0)?{$numberDouble:"-0.0"}:{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(t,n){let r=parseFloat(t.$numberDouble);return n&&n.relaxed?r:new e(r)}inspect(t,n,r){return r??=se,`new Double(${r(this.value,n)})`}},xe=class e extends ee{get _bsontype(){return"Int32"}constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t|0}static fromString(t){let n=Rr(t),r=Number(t);if($t<r)throw new g(`Input: '${t}' is larger than the maximum value for Int32`);if(St>r)throw new g(`Input: '${t}' is smaller than the minimum value for Int32`);if(Number.isSafeInteger(r)){if(r.toString()!==n)throw new g(`Input: '${t}' is not a valid Int32 string`)}else throw new g(`Input: '${t}' is not a safe integer`);return new e(r)}valueOf(){return this.value}toString(t){return this.value.toString(t)}toJSON(){return this.value}toExtendedJSON(t){return t&&(t.relaxed||t.legacy)?this.value:{$numberInt:this.value.toString()}}static fromExtendedJSON(t,n){return n&&n.relaxed?parseInt(t.$numberInt,10):new e(t.$numberInt)}inspect(t,n,r){return r??=se,`new Int32(${r(this.value,n)})`}},st=class e extends ee{get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new e}inspect(){return"new MaxKey()"}},Ce=class e extends ee{get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new e}inspect(){return"new MinKey()"}},Ve=null,mt=new WeakMap,ae=class e extends ee{get _bsontype(){return"ObjectId"}constructor(t){super();let n;if(typeof t=="object"&&t&&"id"in t){if(typeof t.id!="string"&&!ArrayBuffer.isView(t.id))throw new g("Argument passed in must have an id that is of type string or Buffer");"toHexString"in t&&typeof t.toHexString=="function"?n=h.fromHex(t.toHexString()):n=t.id}else n=t;if(n==null||typeof n=="number")this.buffer=e.generate(typeof n=="number"?n:void 0);else if(ArrayBuffer.isView(n)&&n.byteLength===12)this.buffer=h.toLocalBufferType(n);else if(typeof n=="string")if(e.validateHexString(n))this.buffer=h.fromHex(n),e.cacheHexString&&mt.set(this,n);else throw new g("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new g("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(t){this.buffer=t,e.cacheHexString&&mt.set(this,h.toHex(t))}static validateHexString(t){if(t?.length!==24)return!1;for(let n=0;n<24;n++){let r=t.charCodeAt(n);if(!(r>=48&&r<=57||r>=97&&r<=102||r>=65&&r<=70))return!1}return!0}toHexString(){if(e.cacheHexString){let n=mt.get(this);if(n)return n}let t=h.toHex(this.id);return e.cacheHexString&&mt.set(this,t),t}static getInc(){return e.index=(e.index+1)%16777215}static generate(t){typeof t!="number"&&(t=Math.floor(Date.now()/1e3));let n=e.getInc(),r=h.allocateUnsafe(12);return I.setInt32BE(r,0,t),Ve===null&&(Ve=h.randomBytes(5)),r[4]=Ve[0],r[5]=Ve[1],r[6]=Ve[2],r[7]=Ve[3],r[8]=Ve[4],r[11]=n&255,r[10]=n>>8&255,r[9]=n>>16&255,r}toString(t){return t==="base64"?h.toBase64(this.id):t==="hex"?this.toHexString():this.toHexString()}toJSON(){return this.toHexString()}static is(t){return t!=null&&typeof t=="object"&&"_bsontype"in t&&t._bsontype==="ObjectId"}equals(t){if(t==null)return!1;if(e.is(t))return this.buffer[11]===t.buffer[11]&&h.equals(this.buffer,t.buffer);if(typeof t=="string")return t.toLowerCase()===this.toHexString();if(typeof t=="object"&&typeof t.toHexString=="function"){let n=t.toHexString(),r=this.toHexString();return typeof n=="string"&&n.toLowerCase()===r}return!1}getTimestamp(){let t=new Date,n=I.getUint32BE(this.buffer,0);return t.setTime(Math.floor(n)*1e3),t}static createPk(){return new e}serializeInto(t,n){return t[n]=this.buffer[0],t[n+1]=this.buffer[1],t[n+2]=this.buffer[2],t[n+3]=this.buffer[3],t[n+4]=this.buffer[4],t[n+5]=this.buffer[5],t[n+6]=this.buffer[6],t[n+7]=this.buffer[7],t[n+8]=this.buffer[8],t[n+9]=this.buffer[9],t[n+10]=this.buffer[10],t[n+11]=this.buffer[11],12}static createFromTime(t){let n=h.allocate(12);for(let r=11;r>=4;r--)n[r]=0;return I.setInt32BE(n,0,t),new e(n)}static createFromHexString(t){if(t?.length!==24)throw new g("hex string must be 24 characters");return new e(h.fromHex(t))}static createFromBase64(t){if(t?.length!==16)throw new g("base64 string must be 16 characters");return new e(h.fromBase64(t))}static isValid(t){if(t==null)return!1;if(typeof t=="string")return e.validateHexString(t);try{return new e(t),!0}catch{return!1}}toExtendedJSON(){return this.toHexString?{$oid:this.toHexString()}:{$oid:this.toString("hex")}}static fromExtendedJSON(t){return new e(t.$oid)}isCached(){return e.cacheHexString&&mt.has(this)}inspect(t,n,r){return r??=se,`new ObjectId(${r(this.toHexString(),n)})`}};ae.index=Math.floor(Math.random()*16777215);function At(e,t,n){let r=5;if(Array.isArray(e))for(let o=0;o<e.length;o++)r+=mr(o.toString(),e[o],t,!0,n);else{typeof e?.toBSON=="function"&&(e=e.toBSON());for(let o of Object.keys(e))r+=mr(o,e[o],t,!1,n)}return r}function mr(e,t,n=!1,r=!1,o=!1){switch(typeof t?.toBSON=="function"&&(t=t.toBSON()),typeof t){case"string":return 1+h.utf8ByteLength(e)+1+4+h.utf8ByteLength(t)+1;case"number":return Math.floor(t)===t&&t>=Or&&t<=Sr&&t>=St&&t<=$t?(e!=null?h.utf8ByteLength(e)+1:0)+5:(e!=null?h.utf8ByteLength(e)+1:0)+9;case"undefined":return r||!o?(e!=null?h.utf8ByteLength(e)+1:0)+1:0;case"boolean":return(e!=null?h.utf8ByteLength(e)+1:0)+2;case"object":if(t!=null&&typeof t._bsontype=="string"&&t[it]!==qe)throw new je;if(t==null||t._bsontype==="MinKey"||t._bsontype==="MaxKey")return(e!=null?h.utf8ByteLength(e)+1:0)+1;if(t._bsontype==="ObjectId")return(e!=null?h.utf8ByteLength(e)+1:0)+13;if(t instanceof Date||nt(t))return(e!=null?h.utf8ByteLength(e)+1:0)+9;if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||En(t))return(e!=null?h.utf8ByteLength(e)+1:0)+6+t.byteLength;if(t._bsontype==="Long"||t._bsontype==="Double"||t._bsontype==="Timestamp")return(e!=null?h.utf8ByteLength(e)+1:0)+9;if(t._bsontype==="Decimal128")return(e!=null?h.utf8ByteLength(e)+1:0)+17;if(t._bsontype==="Code")return t.scope!=null&&Object.keys(t.scope).length>0?(e!=null?h.utf8ByteLength(e)+1:0)+1+4+4+h.utf8ByteLength(t.code.toString())+1+At(t.scope,n,o):(e!=null?h.utf8ByteLength(e)+1:0)+1+4+h.utf8ByteLength(t.code.toString())+1;if(t._bsontype==="Binary"){let i=t;return i.sub_type===M.SUBTYPE_BYTE_ARRAY?(e!=null?h.utf8ByteLength(e)+1:0)+(i.position+1+4+1+4):(e!=null?h.utf8ByteLength(e)+1:0)+(i.position+1+4+1)}else{if(t._bsontype==="Symbol")return(e!=null?h.utf8ByteLength(e)+1:0)+h.utf8ByteLength(t.value)+4+1+1;if(t._bsontype==="DBRef"){let i=Object.assign({$ref:t.collection,$id:t.oid},t.fields);return t.db!=null&&(i.$db=t.db),(e!=null?h.utf8ByteLength(e)+1:0)+1+At(i,n,o)}else return t instanceof RegExp||tt(t)?(e!=null?h.utf8ByteLength(e)+1:0)+1+h.utf8ByteLength(t.source)+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t._bsontype==="BSONRegExp"?(e!=null?h.utf8ByteLength(e)+1:0)+1+h.utf8ByteLength(t.pattern)+1+h.utf8ByteLength(t.options)+1:(e!=null?h.utf8ByteLength(e)+1:0)+At(t,n,o)+1}case"function":return n?(e!=null?h.utf8ByteLength(e)+1:0)+1+4+h.utf8ByteLength(t.toString())+1:0;case"bigint":return(e!=null?h.utf8ByteLength(e)+1:0)+9;case"symbol":return 0;default:throw new g(`Unrecognized JS type: ${typeof t}`)}}function Si(e){return e.split("").sort().join("")}var Ie=class e extends ee{get _bsontype(){return"BSONRegExp"}constructor(t,n){if(super(),this.pattern=t,this.options=Si(n??""),this.pattern.indexOf("\0")!==-1)throw new g(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\0")!==-1)throw new g(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let r=0;r<this.options.length;r++)if(!(this.options[r]==="i"||this.options[r]==="m"||this.options[r]==="x"||this.options[r]==="l"||this.options[r]==="s"||this.options[r]==="u"))throw new g(`The regular expression option [${this.options[r]}] is not supported`)}static parseOptions(t){return t?t.split("").sort().join(""):""}toExtendedJSON(t){return t=t||{},t.legacy?{$regex:this.pattern,$options:this.options}:{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(t){if("$regex"in t)if(typeof t.$regex!="string"){if(t.$regex._bsontype==="BSONRegExp")return t}else return new e(t.$regex,e.parseOptions(t.$options));if("$regularExpression"in t)return new e(t.$regularExpression.pattern,e.parseOptions(t.$regularExpression.options));throw new g(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(t)}`)}inspect(t,n,r){let o=Ko(n)??(a=>a);r??=se;let i=o(r(this.pattern),"regexp"),s=o(r(this.options),"regexp");return`new BSONRegExp(${i}, ${s})`}},at=class e extends ee{get _bsontype(){return"BSONSymbol"}constructor(t){super(),this.value=t}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(t){return new e(t.$symbol)}inspect(t,n,r){return r??=se,`new BSONSymbol(${r(this.value,n)})`}},Oi=w,Fe=class e extends Oi{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(t){if(t==null)super(0,0,!0);else if(typeof t=="bigint")super(t,!0);else if(w.isLong(t))super(t.low,t.high,!0);else if(typeof t=="object"&&"t"in t&&"i"in t){if(typeof t.t!="number"&&(typeof t.t!="object"||t.t._bsontype!=="Int32"))throw new g("Timestamp constructed from { t, i } must provide t as a number");if(typeof t.i!="number"&&(typeof t.i!="object"||t.i._bsontype!=="Int32"))throw new g("Timestamp constructed from { t, i } must provide i as a number");let n=Number(t.t),r=Number(t.i);if(n<0||Number.isNaN(n))throw new g("Timestamp constructed from { t, i } must provide a positive t");if(r<0||Number.isNaN(r))throw new g("Timestamp constructed from { t, i } must provide a positive i");if(n>4294967295)throw new g("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(r>4294967295)throw new g("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(r,n,!0)}else throw new g("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(t){return new e(w.fromInt(t,!0))}static fromNumber(t){return new e(w.fromNumber(t,!0))}static fromBits(t,n){return new e({i:t,t:n})}static fromString(t,n){return new e(w.fromString(t,!0,n))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(t){let n=w.isLong(t.$timestamp.i)?t.$timestamp.i.getLowBitsUnsigned():t.$timestamp.i,r=w.isLong(t.$timestamp.t)?t.$timestamp.t.getLowBitsUnsigned():t.$timestamp.t;return new e({t:r,i:n})}inspect(t,n,r){r??=se;let o=r(this.t,n),i=r(this.i,n);return`new Timestamp({ t: ${o}, i: ${i} })`}};Fe.MAX_VALUE=w.MAX_UNSIGNED_VALUE;var Ei=w.fromNumber(Sr),Ni=w.fromNumber(Or);function Fr(e,t,n){t=t??{};let r=t&&t.index?t.index:0,o=I.getInt32LE(e,r);if(o<5)throw new g(`bson size must be >= 5, is ${o}`);if(t.allowObjectSmallerThanBufferSize&&e.length<o)throw new g(`buffer length ${e.length} must be >= bson size ${o}`);if(!t.allowObjectSmallerThanBufferSize&&e.length!==o)throw new g(`buffer length ${e.length} must === bson size ${o}`);if(o+r>e.byteLength)throw new g(`(bson size ${o} + options.index ${r} must be <= buffer length ${e.byteLength})`);if(e[r+o-1]!==0)throw new g("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return Tt(e,r,t,n)}var Bi=/^\$ref$|^\$id$|^\$db$/;function Tt(e,t,n,r=!1){let o=n.fieldsAsRaw==null?null:n.fieldsAsRaw,i=n.raw==null?!1:n.raw,s=typeof n.bsonRegExp=="boolean"?n.bsonRegExp:!1,a=n.promoteBuffers??!1,c=n.promoteLongs??!0,f=n.promoteValues??!0,l=n.useBigInt64??!1;if(l&&!f)throw new g("Must either request bigint or Long for int64 deserialization");if(l&&!c)throw new g("Must either request bigint or Long for int64 deserialization");let u=n.validation==null?{utf8:!0}:n.validation,d=!0,p,b,B=u.utf8;if(typeof B=="boolean")p=B;else{d=!1;let x=Object.keys(B).map(function(T){return B[T]});if(x.length===0)throw new g("UTF-8 validation setting cannot be empty");if(typeof x[0]!="boolean")throw new g("Invalid UTF-8 validation option, must specify boolean values");if(p=x[0],!x.every(T=>T===p))throw new g("Invalid UTF-8 validation option - keys must be all true or all false")}if(!d){b=new Set;for(let x of Object.keys(B))b.add(x)}let D=t;if(e.length<5)throw new g("corrupt bson message < 5 bytes long");let G=I.getInt32LE(e,t);if(t+=4,G<5||G>e.length)throw new g("corrupt bson message");let U=r?[]:{},ie=0,E=r?!1:null;for(;;){let x=e[t++];if(x===0)break;let T=t;for(;e[T]!==0&&T<e.length;)T++;if(T>=e.byteLength)throw new g("Bad BSON Document: illegal CString");let be=r?ie++:h.toUTF8(e,t,T,!1),Z=!0;d||b?.has(be)?Z=p:Z=!p,E!==!1&&be[0]==="$"&&(E=Bi.test(be));let N;if(t=T+1,x===Er){let S=I.getInt32LE(e,t);if(t+=4,S<=0||S>e.length-t||e[t+S-1]!==0)throw new g("bad string length in bson");N=h.toUTF8(e,t,t+S-1,Z),t=t+S}else if(x===Br){let S=h.allocateUnsafe(12);for(let O=0;O<12;O++)S[O]=e[t+O];N=new ae(S),t=t+12}else if(x===yt&&f===!1)N=new xe(I.getInt32LE(e,t)),t+=4;else if(x===yt)N=I.getInt32LE(e,t),t+=4;else if(x===Bn)N=I.getFloat64LE(e,t),t+=8,f===!1&&(N=new Be(N));else if(x===Ir){let S=I.getInt32LE(e,t),O=I.getInt32LE(e,t+4);t+=8,N=new Date(new w(S,O).toNumber())}else if(x===xr){if(e[t]!==0&&e[t]!==1)throw new g("illegal boolean type value");N=e[t++]===1}else if(x===xn){let S=t,O=I.getInt32LE(e,t);if(O<=0||O>e.length-t)throw new g("bad embedded document length in bson");if(i)N=e.subarray(t,t+O);else{let j=n;d||(j={...n,validation:{utf8:Z}}),N=Tt(e,S,j,!1)}t=t+O}else if(x===Nr){let S=t,O=I.getInt32LE(e,t),j=n,ue=t+O;if(o&&o[be]&&(j={...n,raw:!0}),d||(j={...j,validation:{utf8:Z}}),N=Tt(e,S,j,!0),t=t+O,e[t-1]!==0)throw new g("invalid array terminator byte");if(t!==ue)throw new g("corrupted array bson")}else if(x===Go)N=void 0;else if(x===An)N=null;else if(x===_n)if(l)N=I.getBigInt64LE(e,t),t+=8;else{let S=I.getInt32LE(e,t),O=I.getInt32LE(e,t+4);t+=8;let j=new w(S,O);c&&f===!0?N=j.lessThanOrEqual(Ei)&&j.greaterThanOrEqual(Ni)?j.toNumber():j:N=j}else if(x===Lr){let S=h.allocateUnsafe(16);for(let O=0;O<16;O++)S[O]=e[t+O];t=t+16,N=new Ye(S)}else if(x===In){let S=I.getInt32LE(e,t);t+=4;let O=S,j=e[t++];if(S<0)throw new g("Negative binary type element size found");if(S>e.byteLength)throw new g("Binary type size larger than document size");if(j===M.SUBTYPE_BYTE_ARRAY){if(S=I.getInt32LE(e,t),t+=4,S<0)throw new g("Negative binary type element size found for subtype 0x02");if(S>O-4)throw new g("Binary type with subtype 0x02 contains too long binary size");if(S<O-4)throw new g("Binary type with subtype 0x02 contains too short binary size")}a&&f?N=h.toLocalBufferType(e.subarray(t,t+S)):(N=new M(e.subarray(t,t+S),j),j===Ln&&We.isValid(N)&&(N=N.toUUID())),t=t+S}else if(x===_t&&s===!1){for(T=t;e[T]!==0&&T<e.length;)T++;if(T>=e.length)throw new g("Bad BSON Document: illegal CString");let S=h.toUTF8(e,t,T,!1);for(t=T+1,T=t;e[T]!==0&&T<e.length;)T++;if(T>=e.length)throw new g("Bad BSON Document: illegal CString");let O=h.toUTF8(e,t,T,!1);t=T+1;let j=new Array(O.length);for(T=0;T<O.length;T++)switch(O[T]){case"m":j[T]="m";break;case"s":j[T]="g";break;case"i":j[T]="i";break}N=new RegExp(S,j.join(""))}else if(x===_t&&s===!0){for(T=t;e[T]!==0&&T<e.length;)T++;if(T>=e.length)throw new g("Bad BSON Document: illegal CString");let S=h.toUTF8(e,t,T,!1);for(t=T+1,T=t;e[T]!==0&&T<e.length;)T++;if(T>=e.length)throw new g("Bad BSON Document: illegal CString");let O=h.toUTF8(e,t,T,!1);t=T+1,N=new Ie(S,O)}else if(x===Ar){let S=I.getInt32LE(e,t);if(t+=4,S<=0||S>e.length-t||e[t+S-1]!==0)throw new g("bad string length in bson");let O=h.toUTF8(e,t,t+S-1,Z);N=f?O:new at(O),t=t+S}else if(x===_r)N=new Fe({i:I.getUint32LE(e,t),t:I.getUint32LE(e,t+4)}),t+=8;else if(x===Mr)N=new Ce;else if(x===kr)N=new st;else if(x===Tn){let S=I.getInt32LE(e,t);if(t+=4,S<=0||S>e.length-t||e[t+S-1]!==0)throw new g("bad string length in bson");let O=h.toUTF8(e,t,t+S-1,Z);N=new Re(O),t=t+S}else if(x===Tr){let S=I.getInt32LE(e,t);if(t+=4,S<13)throw new g("code_w_scope total size shorter minimum expected length");let O=I.getInt32LE(e,t);if(t+=4,O<=0||O>e.length-t||e[t+O-1]!==0)throw new g("bad string length in bson");let j=h.toUTF8(e,t,t+O-1,Z);t=t+O;let ue=t,Y=I.getInt32LE(e,t),Yo=Tt(e,ue,n,!1);if(t=t+Y,S<8+Y+O)throw new g("code_w_scope total size is too short, truncating scope");if(S>8+Y+O)throw new g("code_w_scope total size is too long, clips outer document");N=new Re(j,Yo)}else if(x===Zo){let S=I.getInt32LE(e,t);if(t+=4,S<=0||S>e.length-t||e[t+S-1]!==0)throw new g("bad string length in bson");let O=h.toUTF8(e,t,t+S-1,Z);t=t+S;let j=h.allocateUnsafe(12);for(let Y=0;Y<12;Y++)j[Y]=e[t+Y];let ue=new ae(j);t=t+12,N=new Ne(O,ue)}else throw new g(`Detected unknown BSON type ${x.toString(16)} for fieldname "${be}"`);be==="__proto__"?Object.defineProperty(U,be,{value:N,writable:!0,enumerable:!0,configurable:!0}):U[be]=N}if(G!==t-D)throw r?new g("corrupt array bson"):new g("corrupt object bson");if(!E)return U;if(jr(U)){let x=Object.assign({},U);return delete x.$ref,delete x.$id,delete x.$db,new Ne(U.$ref,U.$id,U.$db,x)}return U}var Lt=/\x00/,yr=new Set(["$db","$ref","$id","$clusterTime"]);function en(e,t,n,r){e[r++]=Er;let o=h.encodeUTF8Into(e,t,r);r=r+o+1,e[r-1]=0;let i=h.encodeUTF8Into(e,n,r+4);return I.setInt32LE(e,r,i+1),r=r+4+i,e[r++]=0,r}function tn(e,t,n,r){let i=!Object.is(n,-0)&&Number.isSafeInteger(n)&&n<=$t&&n>=St?yt:Bn;e[r++]=i;let s=h.encodeUTF8Into(e,t,r);return r=r+s,e[r++]=0,i===yt?r+=I.setInt32LE(e,r,n):r+=I.setFloat64LE(e,r,n),r}function nn(e,t,n,r){e[r++]=_n;let o=h.encodeUTF8Into(e,t,r);return r+=o,e[r++]=0,r+=I.setBigInt64LE(e,r,n),r}function ve(e,t,n,r){e[r++]=An;let o=h.encodeUTF8Into(e,t,r);return r=r+o,e[r++]=0,r}function rn(e,t,n,r){e[r++]=xr;let o=h.encodeUTF8Into(e,t,r);return r=r+o,e[r++]=0,e[r++]=n?1:0,r}function on(e,t,n,r){e[r++]=Ir;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;let i=w.fromNumber(n.getTime()),s=i.getLowBits(),a=i.getHighBits();return r+=I.setInt32LE(e,r,s),r+=I.setInt32LE(e,r,a),r}function sn(e,t,n,r){e[r++]=_t;let o=h.encodeUTF8Into(e,t,r);if(r=r+o,e[r++]=0,n.source&&n.source.match(Lt)!=null)throw new g("value "+n.source+" must not contain null bytes");return r=r+h.encodeUTF8Into(e,n.source,r),e[r++]=0,n.ignoreCase&&(e[r++]=105),n.global&&(e[r++]=115),n.multiline&&(e[r++]=109),e[r++]=0,r}function an(e,t,n,r){e[r++]=_t;let o=h.encodeUTF8Into(e,t,r);if(r=r+o,e[r++]=0,n.pattern.match(Lt)!=null)throw new g("pattern "+n.pattern+" must not contain null bytes");r=r+h.encodeUTF8Into(e,n.pattern,r),e[r++]=0;let i=n.options.split("").sort().join("");return r=r+h.encodeUTF8Into(e,i,r),e[r++]=0,r}function cn(e,t,n,r){n===null?e[r++]=An:n._bsontype==="MinKey"?e[r++]=Mr:e[r++]=kr;let o=h.encodeUTF8Into(e,t,r);return r=r+o,e[r++]=0,r}function ln(e,t,n,r){e[r++]=Br;let o=h.encodeUTF8Into(e,t,r);return r=r+o,e[r++]=0,r+=n.serializeInto(e,r),r}function fn(e,t,n,r){e[r++]=In;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;let i=n.length;if(r+=I.setInt32LE(e,r,i),e[r++]=Xo,i<=16)for(let s=0;s<i;s++)e[r+s]=n[s];else e.set(n,r);return r=r+i,r}function un(e,t,n,r,o,i,s,a,c){if(c.has(n))throw new g("Cannot convert circular structure to BSON");c.add(n),e[r++]=Array.isArray(n)?Nr:xn;let f=h.encodeUTF8Into(e,t,r);r=r+f,e[r++]=0;let l=Ot(e,n,o,r,i+1,s,a,c);return c.delete(n),l}function dn(e,t,n,r){e[r++]=Lr;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;for(let i=0;i<16;i++)e[r+i]=n.bytes[i];return r+16}function hn(e,t,n,r){e[r++]=n._bsontype==="Long"?_n:_r;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;let i=n.getLowBits(),s=n.getHighBits();return r+=I.setInt32LE(e,r,i),r+=I.setInt32LE(e,r,s),r}function gn(e,t,n,r){n=n.valueOf(),e[r++]=yt;let o=h.encodeUTF8Into(e,t,r);return r=r+o,e[r++]=0,r+=I.setInt32LE(e,r,n),r}function pn(e,t,n,r){e[r++]=Bn;let o=h.encodeUTF8Into(e,t,r);return r=r+o,e[r++]=0,r+=I.setFloat64LE(e,r,n.value),r}function mn(e,t,n,r){e[r++]=Tn;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;let i=n.toString(),s=h.encodeUTF8Into(e,i,r+4)+1;return I.setInt32LE(e,r,s),r=r+4+s-1,e[r++]=0,r}function yn(e,t,n,r,o=!1,i=0,s=!1,a=!0,c){if(n.scope&&typeof n.scope=="object"){e[r++]=Tr;let f=h.encodeUTF8Into(e,t,r);r=r+f,e[r++]=0;let l=r,u=n.code;r=r+4;let d=h.encodeUTF8Into(e,u,r+4)+1;I.setInt32LE(e,r,d),e[r+4+d-1]=0,r=r+d+4;let p=Ot(e,n.scope,o,r,i+1,s,a,c);r=p-1;let b=p-l;l+=I.setInt32LE(e,l,b),e[r++]=0}else{e[r++]=Tn;let f=h.encodeUTF8Into(e,t,r);r=r+f,e[r++]=0;let l=n.code.toString(),u=h.encodeUTF8Into(e,l,r+4)+1;I.setInt32LE(e,r,u),r=r+4+u-1,e[r++]=0}return r}function wn(e,t,n,r){e[r++]=In;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;let i=n.buffer,s=n.position;if(n.sub_type===M.SUBTYPE_BYTE_ARRAY&&(s=s+4),r+=I.setInt32LE(e,r,s),e[r++]=n.sub_type,n.sub_type===M.SUBTYPE_BYTE_ARRAY&&(s=s-4,r+=I.setInt32LE(e,r,s)),n.sub_type===M.SUBTYPE_VECTOR&&Oe(n),s<=16)for(let a=0;a<s;a++)e[r+a]=i[a];else e.set(i,r);return r=r+n.position,r}function bn(e,t,n,r){e[r++]=Ar;let o=h.encodeUTF8Into(e,t,r);r=r+o,e[r++]=0;let i=h.encodeUTF8Into(e,n.value,r+4)+1;return I.setInt32LE(e,r,i),r=r+4+i-1,e[r++]=0,r}function $n(e,t,n,r,o,i,s){e[r++]=xn;let a=h.encodeUTF8Into(e,t,r);r=r+a,e[r++]=0;let c=r,f={$ref:n.collection||n.namespace,$id:n.oid};n.db!=null&&(f.$db=n.db),f=Object.assign(f,n.fields);let l=Ot(e,f,!1,r,o+1,i,!0,s),u=l-c;return c+=I.setInt32LE(e,r,u),l}function Ot(e,t,n,r,o,i,s,a){if(a==null){if(t==null)return e[0]=5,e[1]=0,e[2]=0,e[3]=0,e[4]=0,5;if(Array.isArray(t))throw new g("serialize does not support an array as the root input");if(typeof t!="object")throw new g("serialize does not support non-object as the root input");if("_bsontype"in t&&typeof t._bsontype=="string")throw new g("BSON types cannot be serialized as a document");if(nt(t)||tt(t)||et(t)||En(t))throw new g("date, regexp, typedarray, and arraybuffer cannot be BSON documents");a=new Set}a.add(t);let c=r+4;if(Array.isArray(t))for(let l=0;l<t.length;l++){let u=`${l}`,d=t[l];typeof d?.toBSON=="function"&&(d=d.toBSON());let p=typeof d;if(d===void 0)c=ve(e,u,d,c);else if(d===null)c=ve(e,u,d,c);else if(p==="string")c=en(e,u,d,c);else if(p==="number")c=tn(e,u,d,c);else if(p==="bigint")c=nn(e,u,d,c);else if(p==="boolean")c=rn(e,u,d,c);else if(p==="object"&&d._bsontype==null)d instanceof Date||nt(d)?c=on(e,u,d,c):d instanceof Uint8Array||et(d)?c=fn(e,u,d,c):d instanceof RegExp||tt(d)?c=sn(e,u,d,c):c=un(e,u,d,c,n,o,i,s,a);else if(p==="object"){if(d[it]!==qe)throw new je;if(d._bsontype==="ObjectId")c=ln(e,u,d,c);else if(d._bsontype==="Decimal128")c=dn(e,u,d,c);else if(d._bsontype==="Long"||d._bsontype==="Timestamp")c=hn(e,u,d,c);else if(d._bsontype==="Double")c=pn(e,u,d,c);else if(d._bsontype==="Code")c=yn(e,u,d,c,n,o,i,s,a);else if(d._bsontype==="Binary")c=wn(e,u,d,c);else if(d._bsontype==="BSONSymbol")c=bn(e,u,d,c);else if(d._bsontype==="DBRef")c=$n(e,u,d,c,o,i,a);else if(d._bsontype==="BSONRegExp")c=an(e,u,d,c);else if(d._bsontype==="Int32")c=gn(e,u,d,c);else if(d._bsontype==="MinKey"||d._bsontype==="MaxKey")c=cn(e,u,d,c);else if(typeof d._bsontype<"u")throw new g(`Unrecognized or invalid _bsontype: ${String(d._bsontype)}`)}else p==="function"&&i&&(c=mn(e,u,d,c))}else if(t instanceof Map||Nn(t)){let l=t.entries(),u=!1;for(;!u;){let d=l.next();if(u=!!d.done,u)continue;let p=d.value?d.value[0]:void 0,b=d.value?d.value[1]:void 0;typeof b?.toBSON=="function"&&(b=b.toBSON());let B=typeof b;if(typeof p=="string"&&!yr.has(p)){if(p.match(Lt)!=null)throw new g("key "+p+" must not contain null bytes");if(n){if(p[0]==="$")throw new g("key "+p+" must not start with '$'");if(p.includes("."))throw new g("key "+p+" must not contain '.'")}}if(b===void 0)s===!1&&(c=ve(e,p,b,c));else if(b===null)c=ve(e,p,b,c);else if(B==="string")c=en(e,p,b,c);else if(B==="number")c=tn(e,p,b,c);else if(B==="bigint")c=nn(e,p,b,c);else if(B==="boolean")c=rn(e,p,b,c);else if(B==="object"&&b._bsontype==null)b instanceof Date||nt(b)?c=on(e,p,b,c):b instanceof Uint8Array||et(b)?c=fn(e,p,b,c):b instanceof RegExp||tt(b)?c=sn(e,p,b,c):c=un(e,p,b,c,n,o,i,s,a);else if(B==="object"){if(b[it]!==qe)throw new je;if(b._bsontype==="ObjectId")c=ln(e,p,b,c);else if(b._bsontype==="Decimal128")c=dn(e,p,b,c);else if(b._bsontype==="Long"||b._bsontype==="Timestamp")c=hn(e,p,b,c);else if(b._bsontype==="Double")c=pn(e,p,b,c);else if(b._bsontype==="Code")c=yn(e,p,b,c,n,o,i,s,a);else if(b._bsontype==="Binary")c=wn(e,p,b,c);else if(b._bsontype==="BSONSymbol")c=bn(e,p,b,c);else if(b._bsontype==="DBRef")c=$n(e,p,b,c,o,i,a);else if(b._bsontype==="BSONRegExp")c=an(e,p,b,c);else if(b._bsontype==="Int32")c=gn(e,p,b,c);else if(b._bsontype==="MinKey"||b._bsontype==="MaxKey")c=cn(e,p,b,c);else if(typeof b._bsontype<"u")throw new g(`Unrecognized or invalid _bsontype: ${String(b._bsontype)}`)}else B==="function"&&i&&(c=mn(e,p,b,c))}}else{if(typeof t?.toBSON=="function"&&(t=t.toBSON(),t!=null&&typeof t!="object"))throw new g("toBSON function did not return an object");for(let l of Object.keys(t)){let u=t[l];typeof u?.toBSON=="function"&&(u=u.toBSON());let d=typeof u;if(typeof l=="string"&&!yr.has(l)){if(l.match(Lt)!=null)throw new g("key "+l+" must not contain null bytes");if(n){if(l[0]==="$")throw new g("key "+l+" must not start with '$'");if(l.includes("."))throw new g("key "+l+" must not contain '.'")}}if(u===void 0)s===!1&&(c=ve(e,l,u,c));else if(u===null)c=ve(e,l,u,c);else if(d==="string")c=en(e,l,u,c);else if(d==="number")c=tn(e,l,u,c);else if(d==="bigint")c=nn(e,l,u,c);else if(d==="boolean")c=rn(e,l,u,c);else if(d==="object"&&u._bsontype==null)u instanceof Date||nt(u)?c=on(e,l,u,c):u instanceof Uint8Array||et(u)?c=fn(e,l,u,c):u instanceof RegExp||tt(u)?c=sn(e,l,u,c):c=un(e,l,u,c,n,o,i,s,a);else if(d==="object"){if(u[it]!==qe)throw new je;if(u._bsontype==="ObjectId")c=ln(e,l,u,c);else if(u._bsontype==="Decimal128")c=dn(e,l,u,c);else if(u._bsontype==="Long"||u._bsontype==="Timestamp")c=hn(e,l,u,c);else if(u._bsontype==="Double")c=pn(e,l,u,c);else if(u._bsontype==="Code")c=yn(e,l,u,c,n,o,i,s,a);else if(u._bsontype==="Binary")c=wn(e,l,u,c);else if(u._bsontype==="BSONSymbol")c=bn(e,l,u,c);else if(u._bsontype==="DBRef")c=$n(e,l,u,c,o,i,a);else if(u._bsontype==="BSONRegExp")c=an(e,l,u,c);else if(u._bsontype==="Int32")c=gn(e,l,u,c);else if(u._bsontype==="MinKey"||u._bsontype==="MaxKey")c=cn(e,l,u,c);else if(typeof u._bsontype<"u")throw new g(`Unrecognized or invalid _bsontype: ${String(u._bsontype)}`)}else d==="function"&&i&&(c=mn(e,l,u,c))}}a.delete(t),e[c++]=0;let f=c-r;return r+=I.setInt32LE(e,r,f),c}function xi(e){return e!=null&&typeof e=="object"&&"_bsontype"in e&&typeof e._bsontype=="string"}var Ii={$oid:ae,$binary:M,$uuid:M,$symbol:at,$numberInt:xe,$numberDecimal:Ye,$numberDouble:Be,$numberLong:w,$minKey:Ce,$maxKey:st,$regex:Ie,$regularExpression:Ie,$timestamp:Fe};function Pr(e,t={}){if(typeof e=="number"){let r=e<=$t&&e>=St,o=e<=br&&e>=$r;if(t.relaxed||t.legacy)return e;if(Number.isInteger(e)&&!Object.is(e,-0)){if(r)return new xe(e);if(o)return t.useBigInt64?BigInt(e):w.fromNumber(e)}return new Be(e)}if(e==null||typeof e!="object")return e;if(e.$undefined)return null;let n=Object.keys(e).filter(r=>r.startsWith("$")&&e[r]!=null);for(let r=0;r<n.length;r++){let o=Ii[n[r]];if(o)return o.fromExtendedJSON(e,t)}if(e.$date!=null){let r=e.$date,o=new Date;if(t.legacy)if(typeof r=="number")o.setTime(r);else if(typeof r=="string")o.setTime(Date.parse(r));else if(typeof r=="bigint")o.setTime(Number(r));else throw new wt(`Unrecognized type for EJSON date: ${typeof r}`);else if(typeof r=="string")o.setTime(Date.parse(r));else if(w.isLong(r))o.setTime(r.toNumber());else if(typeof r=="number"&&t.relaxed)o.setTime(r);else if(typeof r=="bigint")o.setTime(Number(r));else throw new wt(`Unrecognized type for EJSON date: ${typeof r}`);return o}if(e.$code!=null){let r=Object.assign({},e);return e.$scope&&(r.$scope=Pr(e.$scope)),Re.fromExtendedJSON(e)}if(jr(e)||e.$dbPointer){let r=e.$ref?e:e.$dbPointer;if(r instanceof Ne)return r;let o=Object.keys(r).filter(s=>s.startsWith("$")),i=!0;if(o.forEach(s=>{["$ref","$id","$db"].indexOf(s)===-1&&(i=!1)}),i)return Ne.fromExtendedJSON(r)}return e}function Ai(e,t){return e.map((n,r)=>{t.seenObjects.push({propertyName:`index ${r}`,obj:null});try{return Ee(n,t)}finally{t.seenObjects.pop()}})}function wr(e){let t=e.toISOString();return e.getUTCMilliseconds()!==0?t:t.slice(0,-5)+"Z"}function Ee(e,t){if(e instanceof Map||Nn(e)){let n=Object.create(null);for(let[r,o]of e){if(typeof r!="string")throw new g("Can only serialize maps with string keys");n[r]=o}return Ee(n,t)}if((typeof e=="object"||typeof e=="function")&&e!==null){let n=t.seenObjects.findIndex(r=>r.obj===e);if(n!==-1){let r=t.seenObjects.map(l=>l.propertyName),o=r.slice(0,n).map(l=>`${l} -> `).join(""),i=r[n],s=" -> "+r.slice(n+1,r.length-1).map(l=>`${l} -> `).join(""),a=r[r.length-1],c=" ".repeat(o.length+i.length/2),f="-".repeat(s.length+(i.length+a.length)/2-1);throw new g(`Converting circular structure to EJSON:
7
+ ${o}${i}${s}${a}
8
+ ${c}\\${f}/`)}t.seenObjects[t.seenObjects.length-1].obj=e}if(Array.isArray(e))return Ai(e,t);if(e===void 0)return null;if(e instanceof Date||nt(e)){let n=e.getTime(),r=n>-1&&n<2534023188e5;return t.legacy?t.relaxed&&r?{$date:e.getTime()}:{$date:wr(e)}:t.relaxed&&r?{$date:wr(e)}:{$date:{$numberLong:e.getTime().toString()}}}if(typeof e=="number"&&(!t.relaxed||!isFinite(e))){if(Number.isInteger(e)&&!Object.is(e,-0)){if(e>=St&&e<=$t)return{$numberInt:e.toString()};if(e>=$r&&e<=br)return{$numberLong:e.toString()}}return{$numberDouble:Object.is(e,-0)?"-0.0":e.toString()}}if(typeof e=="bigint")return t.relaxed?Number(BigInt.asIntN(64,e)):{$numberLong:BigInt.asIntN(64,e).toString()};if(e instanceof RegExp||tt(e)){let n=e.flags;if(n===void 0){let o=e.toString().match(/[gimuy]*$/);o&&(n=o[0])}return new Ie(e.source,n).toExtendedJSON(t)}return e!=null&&typeof e=="object"?_i(e,t):e}var Ti={Binary:e=>new M(e.value(),e.sub_type),Code:e=>new Re(e.code,e.scope),DBRef:e=>new Ne(e.collection||e.namespace,e.oid,e.db,e.fields),Decimal128:e=>new Ye(e.bytes),Double:e=>new Be(e.value),Int32:e=>new xe(e.value),Long:e=>w.fromBits(e.low!=null?e.low:e.low_,e.low!=null?e.high:e.high_,e.low!=null?e.unsigned:e.unsigned_),MaxKey:()=>new st,MinKey:()=>new Ce,ObjectId:e=>new ae(e),BSONRegExp:e=>new Ie(e.pattern,e.options),BSONSymbol:e=>new at(e.value),Timestamp:e=>Fe.fromBits(e.low,e.high)};function _i(e,t){if(e==null||typeof e!="object")throw new g("not an object instance");let n=e._bsontype;if(typeof n>"u"){let r={};for(let o of Object.keys(e)){t.seenObjects.push({propertyName:o,obj:null});try{let i=Ee(e[o],t);o==="__proto__"?Object.defineProperty(r,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):r[o]=i}finally{t.seenObjects.pop()}}return r}else{if(e!=null&&typeof e=="object"&&typeof e._bsontype=="string"&&e[it]!==qe)throw new je;if(xi(e)){let r=e;if(typeof r.toExtendedJSON!="function"){let o=Ti[e._bsontype];if(!o)throw new g("Unrecognized or invalid _bsontype: "+e._bsontype);r=o(r)}return n==="Code"&&r.scope?r=new Re(r.code,Ee(r.scope,t)):n==="DBRef"&&r.oid&&(r=new Ne(Ee(r.collection,t),Ee(r.oid,t),Ee(r.db,t),Ee(r.fields,t))),r.toExtendedJSON(t)}else throw new g("_bsontype must be a string, but was: "+typeof n)}}function zr(e,t){let n={useBigInt64:t?.useBigInt64??!1,relaxed:t?.relaxed??!0,legacy:t?.legacy??!1};return JSON.parse(e,(r,o)=>{if(r.indexOf("\0")!==-1)throw new g(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(r)}`);return Pr(o,n)})}function Vr(e,t,n,r){n!=null&&typeof n=="object"&&(r=n,n=0),t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t,t=void 0,n=0);let o=Object.assign({relaxed:!0,legacy:!1},r,{seenObjects:[{propertyName:"(root)",obj:null}]}),i=Ee(e,o);return JSON.stringify(i,t,n)}function Li(e,t){return t=t||{},JSON.parse(Vr(e,t))}function Mi(e,t){return t=t||{},zr(JSON.stringify(e),t)}var X=Object.create(null);X.parse=zr;X.stringify=Vr;X.serialize=Li;X.deserialize=Mi;Object.freeze(X);var W={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function Sn(e,t){try{return I.getNonnegativeInt32LE(e,t)}catch(n){throw new me("BSON size cannot be negative",t,{cause:n})}}function On(e,t){let n=t;for(;e[n]!==0;n++);if(n===e.length-1)throw new me("Null terminator not found",t);return n}function ki(e,t=0){if(t??=0,e.length<5)throw new me(`Input must be at least 5 bytes, got ${e.length} bytes`,t);let n=Sn(e,t);if(n>e.length-t)throw new me(`Parsed documentSize (${n} bytes) does not match input length (${e.length} bytes)`,t);if(e[t+n-1]!==0)throw new me("BSON documents must end in 0x00",t+n);let r=[],o=t+4;for(;o<=n+t;){let i=e[o];if(o+=1,i===0){if(o-t!==n)throw new me("Invalid 0x00 type byte",o);break}let s=o,a=On(e,o)-s;o+=a+1;let c;if(i===W.double||i===W.long||i===W.date||i===W.timestamp)c=8;else if(i===W.int)c=4;else if(i===W.objectId)c=12;else if(i===W.decimal)c=16;else if(i===W.bool)c=1;else if(i===W.null||i===W.undefined||i===W.maxKey||i===W.minKey)c=0;else if(i===W.regex)c=On(e,On(e,o)+1)+1-o;else if(i===W.object||i===W.array||i===W.javascriptWithScope)c=Sn(e,o);else if(i===W.string||i===W.binData||i===W.dbPointer||i===W.javascript||i===W.symbol)c=Sn(e,o)+4,i===W.binData&&(c+=1),i===W.dbPointer&&(c+=12);else throw new me(`Invalid 0x${i.toString(16).padStart(2,"0")} type byte`,o);if(c>n)throw new me("value reports length larger than document",o);r.push([i,s,a,o,c]),o+=c}return r}var Et=Object.create(null);Et.parseToElements=ki;Et.ByteUtils=h;Et.NumberUtils=I;Object.freeze(Et);var qr=1024*1024*17,De=h.allocate(qr);function Ui(e){De.length<e&&(De=h.allocate(e))}function Di(e,t={}){let n=typeof t.checkKeys=="boolean"?t.checkKeys:!1,r=typeof t.serializeFunctions=="boolean"?t.serializeFunctions:!1,o=typeof t.ignoreUndefined=="boolean"?t.ignoreUndefined:!0,i=typeof t.minInternalBufferSize=="number"?t.minInternalBufferSize:qr;De.length<i&&(De=h.allocate(i));let s=Ot(De,e,n,0,0,r,o,null),a=h.allocateUnsafe(s);return a.set(De.subarray(0,s),0),a}function ji(e,t,n={}){let r=typeof n.checkKeys=="boolean"?n.checkKeys:!1,o=typeof n.serializeFunctions=="boolean"?n.serializeFunctions:!1,i=typeof n.ignoreUndefined=="boolean"?n.ignoreUndefined:!0,s=typeof n.index=="number"?n.index:0,a=Ot(De,e,r,0,0,o,i,null);return t.set(De.subarray(0,a),s),s+a-1}function Ri(e,t={}){return Fr(h.toLocalBufferType(e),t)}function Ci(e,t={}){t=t||{};let n=typeof t.serializeFunctions=="boolean"?t.serializeFunctions:!1,r=typeof t.ignoreUndefined=="boolean"?t.ignoreUndefined:!0;return At(e,n,r)}function Fi(e,t,n,r,o,i){let s=Object.assign({allowObjectSmallerThanBufferSize:!0,index:0},i),a=h.toLocalBufferType(e),c=t;for(let f=0;f<n;f++){let l=I.getInt32LE(a,c);s.index=c,r[o+f]=Fr(a,s),c=c+l}return c}var Mt=Object.freeze({__proto__:null,BSONError:g,BSONOffsetError:me,BSONRegExp:Ie,BSONRuntimeError:wt,BSONSymbol:at,BSONType:Qo,BSONValue:ee,BSONVersionError:je,Binary:M,Code:Re,DBRef:Ne,Decimal128:Ye,Double:Be,EJSON:X,Int32:xe,Long:w,MaxKey:st,MinKey:Ce,ObjectId:ae,Timestamp:Fe,UUID:We,calculateObjectSize:Ci,deserialize:Ri,deserializeStream:Fi,onDemand:Et,serialize:Di,serializeWithBufferAndIndex:ji,setInternalBufferSize:Ui});var m=class extends Error{code;codeName;extra;constructor(t,n,r,o={}){super(r),this.code=t,this.codeName=n,this.extra=o}},A=e=>new m(2,"BadValue",e),Pe=e=>new m(9,"FailedToParse",e);var ce=e=>e!==null&&typeof e=="object"?e._bsontype:void 0,Q=e=>ce(e)==="Long",Hr=e=>ce(e)==="Decimal128",He=e=>ce(e)==="ObjectId",te=e=>e instanceof RegExp||ce(e)==="BSONRegExp",F=e=>typeof e=="number"||Q(e)||Hr(e)||ce(e)==="Int32"||ce(e)==="Double";function y(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date||e instanceof RegExp||e instanceof Uint8Array?!1:ce(e)===void 0}function $(e){if(typeof e=="number")return e;if(Q(e))return e.toNumber();if(Hr(e))return Number.parseFloat(e.toString());let t=ce(e);return t==="Int32"||t==="Double"?e.value:Number.NaN}function Ae(e){if(e==null)return 2;if(typeof e=="number")return 3;if(typeof e=="string")return 4;if(typeof e=="boolean")return 9;if(e instanceof Date)return 10;if(Array.isArray(e))return 6;if(e instanceof RegExp)return 12;if(e instanceof Uint8Array)return 7;switch(ce(e)){case"MinKey":return 1;case"Long":case"Int32":case"Double":case"Decimal128":return 3;case"BSONSymbol":return 4;case"Binary":return 7;case"ObjectId":return 8;case"Timestamp":return 11;case"BSONRegExp":return 12;case"Code":return 12.5;case"MaxKey":return 13;case void 0:return 5;default:return 5}}function P(e){if(e===void 0)return"missing";if(e===null)return"null";if(typeof e=="number")return Number.isInteger(e)&&e>=-2147483648&&e<=2147483647?"int":"double";if(typeof e=="string")return"string";if(typeof e=="boolean")return"bool";if(e instanceof Date)return"date";if(Array.isArray(e))return"array";if(e instanceof RegExp)return"regex";if(e instanceof Uint8Array)return"binData";switch(ce(e)){case"Long":return"long";case"Int32":return"int";case"Double":return"double";case"Decimal128":return"decimal";case"ObjectId":return"objectId";case"Binary":return"binData";case"Timestamp":return"timestamp";case"BSONRegExp":return"regex";case"MinKey":return"minKey";case"MaxKey":return"maxKey";case"Code":return"javascript";case"BSONSymbol":return"symbol";default:return"object"}}var Wr={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127};function Dt(e,t){let n=P(e);if(typeof t=="number")return Wr[n]===t;if(t==="number")return["int","long","double","decimal"].includes(n);if(typeof t=="string"){if(!(t in Wr))throw A(`Unknown type name alias: ${t}`);return n===t}throw A("type must be represented as a number or a string")}function Yr(e){return e instanceof Uint8Array?e:e.buffer}function ct(e,t){return e===t?0:/^[\u0000-퟿]*$/.test(e)&&/^[\u0000-퟿]*$/.test(t)?e<t?-1:1:Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function Pi(e,t){if(Q(e)&&Q(t))return e.compare(t);let n=$(e),r=$(t);return Number.isNaN(n)||Number.isNaN(r)?Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?-1:1:n<r?-1:n>r?1:0}function z(e,t){let n=Ae(e),r=Ae(t);if(n!==r)return n<r?-1:1;switch(n){case 1:case 2:case 13:return 0;case 3:return Pi(e,t);case 4:return ct(String(ce(e)==="BSONSymbol"?e.value:e),String(ce(t)==="BSONSymbol"?t.value:t));case 5:return zi(e,t);case 6:{let o=e,i=t;for(let s=0;s<Math.min(o.length,i.length);s++){let a=z(o[s],i[s]);if(a!==0)return a}return o.length===i.length?0:o.length<i.length?-1:1}case 7:{let o=Yr(e),i=Yr(t);if(o.length!==i.length)return o.length<i.length?-1:1;let s=e instanceof Uint8Array?0:e.sub_type,a=t instanceof Uint8Array?0:t.sub_type;return s!==a?s<a?-1:1:Buffer.compare(Buffer.from(o),Buffer.from(i))}case 8:return ct(e.toHexString(),t.toHexString());case 9:return e===t?0:e?1:-1;case 10:{let o=e.getTime(),i=t.getTime();return o<i?-1:o>i?1:0}case 11:{let o=e,i=t;return o.t!==i.t?o.t<i.t?-1:1:o.i===i.i?0:o.i<i.i?-1:1}case 12:{let[o,i]=kt(e),[s,a]=kt(t);return ct(o,s)||ct(i,a)}default:return ct(String(e),String(t))}}function zi(e,t){let n=Object.keys(e),r=Object.keys(t);for(let o=0;o<Math.min(n.length,r.length);o++){let i=e[n[o]],s=t[r[o]],a=Ae(i)-Ae(s);if(a!==0)return a<0?-1:1;let c=ct(n[o],r[o]);if(c!==0)return c;let f=z(i,s);if(f!==0)return f}return n.length===r.length?0:n.length<r.length?-1:1}var H=(e,t)=>z(e,t)===0&&(Ae(e)!==2||Ae(t)===2);function kt(e){if(e instanceof RegExp)return[e.source,e.flags];let t=e;return[t.pattern,t.options]}function jt(e,t=""){let n=e;t.includes("x")&&(n=n.replace(/\\#/g,"\0").replace(/#[^\n]*/g,"").replace(/\\\s/g,o=>o).replace(/(?<!\\)\s+/g,"").replace(/\u0000/g,"\\#"));let r=[...new Set(t.split("").filter(o=>"imsu".includes(o)))].join("");try{return new RegExp(n,r)}catch(o){throw new m(51091,"Location51091",`Regular expression is invalid: ${o.message}`)}}function Te(e){if(e instanceof RegExp)return e;let[t,n]=kt(e);return jt(t,n)}function L(e){if(Array.isArray(e))return e.map(L);if(y(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=L(r);return t}return e instanceof Date?new Date(e.getTime()):e}function Ut(e){if(typeof e=="number")return Number.isInteger(e)&&e>=-2147483648&&e<=2147483647&&!Object.is(e,-0)?new xe(e):new Be(e);if(Array.isArray(e))return e.map(Ut);if(y(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ut(r);return t}return e}function Mn(e){let t=ce(e);if(t==="Int32"||t==="Double")return e.value;if(Array.isArray(e))return e.map(Mn);if(y(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Mn(o);return n}return e}function v(e){return X.serialize(Ut(e),{relaxed:!1})}function ye(e){return Mn(X.deserialize(e,{relaxed:!1}))}function oe(e){if(F(e)){let t=$(e);return`n:${Object.is(t,-0)?0:t}`}return typeof e=="string"?`s:${e}`:e==null?"null":typeof e=="boolean"?`b:${e}`:e instanceof Date?`d:${e.getTime()}`:He(e)?`o:${e.toHexString()}`:X.stringify({v:Ut(e)},{relaxed:!1})}function Jr(e){return e.length===1?oe(e[0]):JSON.stringify(e.map(oe))}function C(e){if(e===void 0)return"undefined";if(e===null)return"null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e instanceof Date)return`new Date(${e.getTime()})`;if(Array.isArray(e))return`[ ${e.map(C).join(", ")} ]`;if(He(e))return`ObjectId('${e.toHexString()}')`;if(Q(e))return e.toString();if(te(e)){let[t,n]=kt(e);return`/${t}/${n}`}if(y(e)){let t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([n,r])=>`${n}: ${C(r)}`).join(", ")} }`}return String(e)}function K(e,t){let n=t.split("."),r=[],o=(i,s)=>{if(s===n.length){r.push(i);return}let a=n[s];if(Array.isArray(i)){if(/^\d+$/.test(a)){let c=i[Number(a)];c!==void 0&&o(c,s+1)}for(let c of i)y(c)&&o(c,s);return}if(y(i)){o(i[a],s+1);return}r.push(void 0)};return o(e,0),r}function Kr(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/.test(r)){n=n.filter(y).map(i=>i[r]).filter(i=>i!==void 0);continue}n=n[Number(r)]}else if(y(n))n=n[r];else return;return n}function Rt(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){let o=[];for(let i of n)if(Array.isArray(i)){let s=Rt(i,r);Array.isArray(s)&&o.push(s)}else y(i)&&i[r]!==void 0&&o.push(i[r]);n=o}else if(y(n))n=n[r];else return;return n}function ne(e){return e==null||e===!1?!1:F(e)?$(e)!==0:!0}var Ke=Symbol("REMOVE"),Vi=e=>new m(168,"InvalidPipelineOperator",`Unrecognized expression '${e}'`),V=(e,t)=>new m(e,`Location${e}`,t);function Ct(e){return Array.isArray(e)?e:[e]}function k(e){return e==null}function J(e,t,n={}){if(typeof e=="string"){if(e.startsWith("$$")){let[r,...o]=e.slice(2).split("."),i;if(r==="ROOT")i=n.ROOT??t;else if(r==="CURRENT")i=t;else{if(r==="REMOVE")return Ke;if(r==="NOW")i=n.NOW??new Date(0);else if(r in n)i=n[r];else throw V(17276,`Use of undefined variable: ${r}`)}return o.length?Rt(i,o.join(".")):i}if(e.startsWith("$")){if(e.length===1)throw V(16872,"'$' by itself is not a valid FieldPath");return Rt(t,e.slice(1))}return e}if(Array.isArray(e))return e.map(r=>J(r,t,n));if(y(e)){let r=Object.keys(e);if(r.length===1&&r[0].startsWith("$"))return Yi(r[0],e[r[0]],t,n);let o={};for(let i of r){if(i.startsWith("$"))throw V(16410,"FieldPath field names may not start with '$'. Consider using $getField or $setField.");let s=J(e[i],t,n);s!==Ke&&s!==void 0&&(o[i]=s)}return o}return e}function _e(e,t){return e.map(n=>{if(!F(n))throw V(16554,`${t} only supports numeric types, not ${P(n)}`);return $(n)})}function Le(e,t){if(e instanceof Date)return e;if(He(e))return e.getTimestamp();throw V(16006,`can't convert from BSON type ${P(e)} to Date`)}function Je(e,t=2){return String(e).padStart(t,"0")}function qi(e,t){return t.replace(/%([YmdHMSLjwUGVuZz%])/g,(n,r)=>{switch(r){case"Y":return String(e.getUTCFullYear());case"m":return Je(e.getUTCMonth()+1);case"d":return Je(e.getUTCDate());case"H":return Je(e.getUTCHours());case"M":return Je(e.getUTCMinutes());case"S":return Je(e.getUTCSeconds());case"L":return Je(e.getUTCMilliseconds(),3);case"j":{let o=Date.UTC(e.getUTCFullYear(),0,1);return Je(Math.floor((e.getTime()-o)/864e5)+1,3)}case"w":return String(e.getUTCDay()+1);case"u":return String(e.getUTCDay()===0?7:e.getUTCDay());case"Z":return"+0";case"z":return"+0000";case"%":return"%";default:throw V(18536,`Invalid format character '%${r}' in format string`)}})}function Ft(e){if(k(e))return null;if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(e instanceof Date)return e.toISOString();if(He(e))return e.toHexString();if(Q(e))return e.toString();if(F(e))return String($(e));throw V(241,`Unsupported conversion from ${P(e)} to string in $convert with no onError value`)}function Me(e,t){if(k(e))return null;switch(t){case"string":return Ft(e);case"int":case"long":case"double":case"decimal":{if(F(e))return t==="double"||t==="decimal"?$(e):Math.trunc($(e));if(typeof e=="boolean")return e?1:0;if(e instanceof Date)return e.getTime();if(typeof e=="string"&&/^\s*-?\d+(\.\d+)?([eE][-+]?\d+)?\s*$/.test(e))return t==="double"||t==="decimal"?Number(e):Math.trunc(Number(e));throw V(241,`Failed to parse number '${String(e)}' in $convert with no onError value`)}case"bool":return ne(e);case"date":{if(e instanceof Date)return e;if(F(e))return new Date($(e));if(typeof e=="string"){let n=Date.parse(e);if(!Number.isNaN(n))return new Date(n)}if(He(e))return e.getTimestamp();throw V(241,`Error parsing date string '${String(e)}'`)}case"objectId":{if(He(e))return e;if(typeof e=="string"&&/^[0-9a-fA-F]{24}$/.test(e))return new ae(e);throw V(241,`Failed to parse objectId '${String(e)}' in $convert with no onError value: Invalid string length for parsing to OID, expected 24 but found ${String(e).length}`)}default:throw V(Wi,`Unknown type name: ${t}`)}}var Wi=9;function Yi(e,t,n,r){let o=s=>J(s,n,r),i=()=>Ct(t).map(o);switch(e){case"$literal":return t;case"$add":{let s=i();if(s.some(k))return null;let a=s.find(f=>f instanceof Date),c=s.reduce((f,l)=>f+(l instanceof Date?l.getTime():_e([l],"$add")[0]),0);return a?new Date(c):c}case"$subtract":{let[s,a]=i();if(k(s)||k(a))return null;if(s instanceof Date&&a instanceof Date)return s.getTime()-a.getTime();if(s instanceof Date)return new Date(s.getTime()-$(a));let[c,f]=_e([s,a],"$subtract");return c-f}case"$multiply":{let s=i();return s.some(k)?null:_e(s,"$multiply").reduce((a,c)=>a*c,1)}case"$divide":{let[s,a]=i();if(k(s)||k(a))return null;let[c,f]=_e([s,a],"$divide");if(f===0)throw V(16608,"can't $divide by zero");return c/f}case"$mod":{let[s,a]=i();if(k(s)||k(a))return null;let[c,f]=_e([s,a],"$mod");if(f===0)throw V(16610,"can't $mod by zero");return c%f}case"$abs":{let[s]=i();return k(s)?null:Math.abs(_e([s],"$abs")[0])}case"$ceil":{let[s]=i();return k(s)?null:Math.ceil(_e([s],"$ceil")[0])}case"$floor":{let[s]=i();return k(s)?null:Math.floor(_e([s],"$floor")[0])}case"$round":case"$trunc":{let[s,a]=i();if(k(s))return null;let f=10**(k(a)?0:$(a)),l=_e([s],e)[0]*f;return(e==="$trunc"?Math.trunc(l):Math.abs(l%1)===.5?2*Math.round(l/2):Math.round(l))/f}case"$concat":{let s=i();if(s.some(k))return null;for(let a of s)if(typeof a!="string")throw V(16702,`$concat only supports strings, not ${P(a)}`);return s.join("")}case"$toLower":{let[s]=i();return k(s)?"":String(Ft(s)).toLowerCase()}case"$toUpper":{let[s]=i();return k(s)?"":String(Ft(s)).toUpperCase()}case"$trim":case"$ltrim":case"$rtrim":{let s=t,a=o(s.input);if(k(a))return null;let c=String(a),f=s.chars===void 0?null:String(o(s.chars)),l=f===null?"\\s":`[${f.replace(/[\]\\^-]/g,"\\$&")}]`,u=c;return e!=="$rtrim"&&(u=u.replace(new RegExp(`^${l}+`,"u"),"")),e!=="$ltrim"&&(u=u.replace(new RegExp(`${l}+$`,"u"),"")),u}case"$substr":case"$substrCP":case"$substrBytes":{let[s,a,c]=i();if(k(s))return"";let f=String(Ft(s)),l=$(a),u=$(c);return e==="$substrBytes"||e==="$substr"?Buffer.from(f,"utf8").subarray(l,u<0?void 0:l+u).toString("utf8"):[...f].slice(l,u<0?void 0:l+u).join("")}case"$strLenCP":{let[s]=i();if(typeof s!="string")throw V(34471,`$strLenCP requires a string argument, found: ${P(s)}`);return[...s].length}case"$strLenBytes":{let[s]=i();if(typeof s!="string")throw V(34473,`$strLenBytes requires a string argument, found: ${P(s)}`);return Buffer.byteLength(s,"utf8")}case"$split":{let[s,a]=i();return k(s)?null:String(s).split(String(a))}case"$indexOfBytes":case"$indexOfCP":{let[s,a]=i();return k(s)?null:String(s).indexOf(String(a))}case"$regexMatch":case"$regexFind":{let s=t,a=o(s.input),c=o(s.regex),f=s.options===void 0?"":String(o(s.options)),l=te(c)?f?jt(Te(c).source,f):Te(c):jt(String(c),f);if(k(a))return e==="$regexMatch"?!1:null;if(typeof a!="string")throw V(51104,`${e} needs 'input' to be of type string`);let u=l.exec(a);return e==="$regexMatch"?u!==null:u===null?null:{match:u[0],idx:u.index,captures:u.slice(1).map(d=>d??null)}}case"$eq":case"$ne":case"$gt":case"$gte":case"$lt":case"$lte":case"$cmp":{let[s,a]=i(),c=z(s??null,a??null);return e==="$cmp"?c:e==="$eq"?c===0:e==="$ne"?c!==0:e==="$gt"?c>0:e==="$gte"?c>=0:e==="$lt"?c<0:c<=0}case"$and":return Ct(t).every(s=>ne(o(s)));case"$or":return Ct(t).some(s=>ne(o(s)));case"$not":return!ne(i()[0]);case"$cond":{let[s,a,c]=Array.isArray(t)?t:[t.if,t.then,t.else];return ne(o(s))?o(a):o(c)}case"$ifNull":{let s=Ct(t);for(let a=0;a<s.length-1;a++){let c=o(s[a]);if(!k(c))return c}return o(s[s.length-1])}case"$switch":{let s=t;for(let a of s.branches??[])if(ne(o(a.case)))return o(a.then);if(s.default===void 0)throw V(40066,"$switch could not find a matching branch for an input, and no default was specified.");return o(s.default)}case"$in":{let[s,a]=i();if(!Array.isArray(a))throw V(40081,`$in requires an array as a second argument, found: ${P(a)}`);return a.some(c=>H(c,s))}case"$size":{let[s]=i();if(!Array.isArray(s))throw V(17124,`The argument to $size must be an array. Was of type: ${P(s)}`);return s.length}case"$isArray":return Array.isArray(i()[0]);case"$arrayElemAt":{let[s,a]=i();if(k(s))return null;if(!Array.isArray(s))throw V(28689,`$arrayElemAt's first argument must be an array, but is ${P(s)}`);let c=$(a),f=c<0?s.length+c:c;return s[f]}case"$first":case"$last":{let[s]=i();if(k(s))return null;if(!Array.isArray(s))throw V(28689,`${e}'s argument must be an array, but is ${P(s)}`);return e==="$first"?s[0]:s[s.length-1]}case"$slice":{let[s,a,c]=i();if(k(s))return null;if(!Array.isArray(s))throw V(28724,`First argument to $slice must be an array, but is of type: ${P(s)}`);if(c===void 0){let l=$(a);return l>=0?s.slice(0,l):s.slice(l)}let f=$(a)<0?Math.max(0,s.length+$(a)):$(a);return s.slice(f,f+$(c))}case"$concatArrays":{let s=i();if(s.some(k))return null;for(let a of s)if(!Array.isArray(a))throw V(28664,`$concatArrays only supports arrays, not ${P(a)}`);return s.flat(1)}case"$reverseArray":{let[s]=i();return k(s)?null:[...s].reverse()}case"$indexOfArray":{let[s,a]=i();return k(s)?null:s.findIndex(c=>H(c,a))}case"$filter":{let s=t,a=o(s.input);if(k(a))return null;if(!Array.isArray(a))throw V(28651,`input to $filter must be an array not ${P(a)}`);let c=typeof s.as=="string"?s.as:"this",f=a.filter(l=>ne(J(s.cond,n,{...r,[c]:l})));return s.limit===void 0?f:f.slice(0,$(o(s.limit)))}case"$map":{let s=t,a=o(s.input);if(k(a))return null;if(!Array.isArray(a))throw V(16883,`input to $map must be an array not ${P(a)}`);let c=typeof s.as=="string"?s.as:"this";return a.map(f=>J(s.in,n,{...r,[c]:f}))}case"$reduce":{let s=t,a=o(s.input);if(k(a))return null;if(!Array.isArray(a))throw V(40080,`$reduce requires that 'input' be an array, found: ${P(a)}`);let c=o(s.initialValue);for(let f of a)c=J(s.in,n,{...r,value:c,this:f});return c}case"$let":{let s=t,a={...r};for(let[c,f]of Object.entries(s.vars??{}))a[c]=o(f);return J(s.in,n,a)}case"$mergeObjects":{let s={};for(let a of i())if(!k(a)){if(!y(a))throw V(40400,`$mergeObjects requires object inputs, but input ${JSON.stringify(a)} is of type ${P(a)}`);Object.assign(s,a)}return s}case"$objectToArray":{let[s]=i();return k(s)?null:Object.entries(s).map(([a,c])=>({k:a,v:c}))}case"$arrayToObject":{let[s]=i();if(k(s))return null;let a={};for(let c of s)Array.isArray(c)?a[String(c[0])]=c[1]:y(c)&&(a[String(c.k)]=c.v);return a}case"$setUnion":{let s=[];for(let a of i())for(let c of a??[])s.some(f=>H(f,c))||s.push(c);return s}case"$setIntersection":{let[s,...a]=i();return(s??[]).filter((c,f,l)=>l.findIndex(u=>H(u,c))===f&&a.every(u=>u.some(d=>H(d,c))))}case"$setDifference":{let[s,a]=i();return(s??[]).filter(c=>!(a??[]).some(f=>H(f,c)))}case"$setIsSubset":{let[s,a]=i();return(s??[]).every(c=>(a??[]).some(f=>H(f,c)))}case"$anyElementTrue":{let[s]=i();return s.some(ne)}case"$allElementsTrue":{let[s]=i();return s.every(ne)}case"$sum":case"$avg":case"$min":case"$max":{let s=i(),a=s.length===1&&Array.isArray(s[0])?s[0]:s;if(e==="$min"||e==="$max"){let f=a.filter(l=>!k(l));return f.length===0?null:f.reduce((l,u)=>e==="$min"?z(u,l)<0?u:l:z(u,l)>0?u:l)}let c=a.filter(F).map($);return e==="$sum"?c.reduce((f,l)=>f+l,0):c.length===0?null:c.reduce((f,l)=>f+l,0)/c.length}case"$type":return P(i()[0]);case"$isNumber":return F(i()[0]);case"$toString":return Me(i()[0],"string");case"$toInt":return Me(i()[0],"int");case"$toLong":return Me(i()[0],"long");case"$toDouble":return Me(i()[0],"double");case"$toDecimal":return Me(i()[0],"decimal");case"$toBool":return Me(i()[0],"bool");case"$toDate":return Me(i()[0],"date");case"$toObjectId":return Me(i()[0],"objectId");case"$convert":{let s=t,a=o(s.input);if(k(a))return s.onNull===void 0?null:o(s.onNull);try{return Me(a,String(o(s.to)))}catch(c){if(s.onError!==void 0)return o(s.onError);throw c}}case"$dateToString":{let s=t,a=o(s.date);if(k(a))return s.onNull===void 0?null:o(s.onNull);if(s.timezone!==void 0&&!["UTC","GMT","Z","+00:00"].includes(String(o(s.timezone))))throw new m(115,"CommandNotSupported","the MongoDB twin formats dates in UTC only");return qi(Le(a,e),s.format===void 0?"%Y-%m-%dT%H:%M:%S.%LZ":String(o(s.format)))}case"$year":return Le(i()[0],e).getUTCFullYear();case"$month":return Le(i()[0],e).getUTCMonth()+1;case"$dayOfMonth":return Le(i()[0],e).getUTCDate();case"$dayOfWeek":return Le(i()[0],e).getUTCDay()+1;case"$hour":return Le(i()[0],e).getUTCHours();case"$minute":return Le(i()[0],e).getUTCMinutes();case"$second":return Le(i()[0],e).getUTCSeconds();case"$millisecond":return Le(i()[0],e).getUTCMilliseconds();case"$getField":{let s=y(t)?t:{field:t},a=s.input===void 0?n:o(s.input);return y(a)?a[String(o(s.field))]:null}default:throw Vi(e)}}function Gr(e,t,n){let r=o=>J(t,o,n);switch(e){case"$sum":{let o=0;return{add:i=>{let s=r(i);F(s)&&(o+=$(s))},result:()=>o}}case"$avg":{let o=0,i=0;return{add:s=>{let a=r(s);F(a)&&(o+=$(a),i+=1)},result:()=>i===0?null:o/i}}case"$min":case"$max":{let o,i=!1;return{add:s=>{let a=r(s);a!=null&&(!i||(e==="$min"?z(a,o)<0:z(a,o)>0))&&(o=a,i=!0)},result:()=>i?o:null}}case"$first":{let o,i=!1;return{add:s=>{i||(o=r(s),i=!0)},result:()=>o===void 0?null:o}}case"$last":{let o;return{add:i=>{o=r(i)},result:()=>o===void 0?null:o}}case"$push":{let o=[];return{add:i=>{let s=r(i);s!==void 0&&o.push(L(s))},result:()=>o}}case"$addToSet":{let o=[];return{add:i=>{let s=r(i);s!==void 0&&!o.some(a=>H(a,s))&&o.push(L(s))},result:()=>o}}case"$count":{let o=0;return{add:()=>{o+=1},result:()=>o}}case"$mergeObjects":{let o={};return{add:i=>{let s=r(i);y(s)&&Object.assign(o,s)},result:()=>o}}default:throw new m(15952,"Location15952",`unknown group operator '${e}'`)}}var Hi=new Set(["$and","$or","$nor","$expr","$comment","$text","$where","$jsonSchema","$alwaysTrue","$alwaysFalse"]);function q(e,t={}){if(e==null)return()=>!0;if(!y(e))throw A("filter must be an object");let n=[];for(let[r,o]of Object.entries(e)){if(r.startsWith("$")){if(!Hi.has(r))throw A(`unknown top level operator: ${r}. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.`);n.push(Ji(r,o,t));continue}n.push(kn(r,o))}return n.length===0?()=>!0:n.length===1?n[0]:r=>n.every(o=>o(r))}function Ji(e,t,n){switch(e){case"$and":case"$or":case"$nor":{if(!Array.isArray(t))throw A(`${e} must be an array`);if(t.length===0)throw A("$and/$or/$nor must be a nonempty array");let r=t.map(o=>{if(!y(o))throw A(`${e}/$or/$nor entries need to be full objects`);return q(o,n)});return e==="$and"?o=>r.every(i=>i(o)):e==="$or"?o=>r.some(i=>i(o)):o=>!r.some(i=>i(o))}case"$expr":return r=>ne(J(t,r,{...n,ROOT:r}));case"$comment":return()=>!0;case"$alwaysTrue":return()=>!0;case"$alwaysFalse":return()=>!1;case"$text":throw new m(115,"CommandNotSupported","$text search is not supported by the MongoDB twin");case"$where":throw new m(2,"BadValue","$where is not allowed in this context: the MongoDB twin runs no server-side JavaScript");default:throw new m(2,"BadValue",`${e} is not supported by the MongoDB twin`)}}function le(e){if(!y(e))return!1;let t=Object.keys(e);return t.length>0&&t[0].startsWith("$")}function ke(e,t){for(let n of e){if(t(n))return!0;if(Array.isArray(n)){for(let r of n)if(t(r))return!0}}return!1}function Zr(e){if(te(e)){let t=Te(e);return n=>typeof n=="string"&&(t.lastIndex=0,t.test(n))||te(n)&&H(n,e)}return e===null?t=>t==null:t=>t!==void 0&&H(t,e)}function zt(e,t){let n=Zr(t);return r=>ke(K(r,e),n)}function Pt(e,t){let n=Ae(e);return r=>r===void 0?e===null&&t(0):Ae(r)!==n?!1:t(z(r,e))}function kn(e,t){if(!le(t))return zt(e,t);let n=[],r=Object.entries(t);for(let[o,i]of r){if(!o.startsWith("$"))throw A(`unknown operator: ${o}`);n.push(Un(e,o,i,t))}return o=>n.every(i=>i(o))}function Un(e,t,n,r){switch(t){case"$eq":return zt(e,n);case"$ne":{let o=zt(e,n);return i=>!o(i)}case"$gt":return o=>ke(K(o,e),Pt(n,i=>i>0));case"$gte":return o=>ke(K(o,e),Pt(n,i=>i>=0));case"$lt":return o=>ke(K(o,e),Pt(n,i=>i<0));case"$lte":return o=>ke(K(o,e),Pt(n,i=>i<=0));case"$in":{if(!Array.isArray(n))throw A("$in needs an array");let o=n.map(i=>{if(le(i))throw A("cannot nest $ under $in");return Zr(i)});return i=>ke(K(i,e),s=>o.some(a=>a(s)))}case"$nin":{if(!Array.isArray(n))throw A("$nin needs an array");let o=Un(e,"$in",n,r);return i=>!o(i)}case"$exists":{let o=ne(n);return i=>K(i,e).some(s=>s!==void 0)===o}case"$type":{let o=Array.isArray(n)?n:[n];for(let i of o)Dt(null,i);return i=>K(i,e).some(s=>s!==void 0&&(o.some(a=>Dt(s,a))||Array.isArray(s)&&s.some(a=>o.some(c=>Dt(a,c)))))}case"$regex":{let o=typeof r.$options=="string"?r.$options:"",i=te(n)?Te(n):typeof n=="string"?Te({_bsontype:"BSONRegExp",pattern:n,options:o}):(()=>{throw A("$regex has to be a string")})(),s=o&&te(n)?Te({_bsontype:"BSONRegExp",pattern:i.source,options:o}):i;return a=>ke(K(a,e),c=>typeof c=="string"&&(s.lastIndex=0,s.test(c)))}case"$options":{if(!("$regex"in r))throw A("$options needs a $regex");return()=>!0}case"$not":{if(te(n)){let i=Te(n),s=a=>ke(K(a,e),c=>typeof c=="string"&&(i.lastIndex=0,i.test(c)));return a=>!s(a)}if(!le(n))throw A("$not needs a regex or a document");let o=kn(e,n);return i=>!o(i)}case"$size":{if(!F(n)||!Number.isInteger($(n)))throw A("$size needs a number");let o=$(n);return i=>K(i,e).some(s=>Array.isArray(s)&&s.length===o)}case"$all":{if(!Array.isArray(n))throw A("$all needs an array");if(n.length===0)return()=>!1;let o=n.map(i=>y(i)&&"$elemMatch"in i?Un(e,"$elemMatch",i.$elemMatch,i):zt(e,i));return i=>o.every(s=>s(i))}case"$elemMatch":{if(!y(n))throw A("$elemMatch needs an Object");let i=le(n)&&Object.keys(n).every(s=>!["$and","$or","$nor","$expr","$where","$text"].includes(s))?(()=>{let s=kn("v",n);return a=>s({v:a})})():(()=>{let s=q(n);return a=>y(a)&&s(a)})();return s=>K(s,e).some(a=>Array.isArray(a)&&a.some(i))}case"$mod":{if(!Array.isArray(n)||n.length!==2)throw A("malformed mod, needs to be an array");let o=Math.trunc($(n[0])),i=Math.trunc($(n[1]));if(o===0)throw A("divisor cannot be 0");return s=>ke(K(s,e),a=>F(a)&&Math.trunc($(a))%o===i)}case"$comment":return()=>!0;default:throw A(`unknown operator: ${t}`)}}function Dn(e){let t=[];if(!y(e))return t;for(let[n,r]of Object.entries(e)){if(n==="$and"&&Array.isArray(r)){for(let o of r)t.push(...Dn(o));continue}if(!n.startsWith("$")){if(!le(r)){te(r)||t.push([n,r]);continue}"$eq"in r?t.push([n,r.$eq]):"$in"in r&&Array.isArray(r.$in)&&r.$in.length===1&&!te(r.$in[0])&&t.push([n,r.$in[0]])}}return t}function Xr(e){if(!y(e)||!("_id"in e))return;let t=e._id;if(le(t)){let n=Object.keys(t);return n.length===1&&n[0]==="$eq"&&!te(t.$eq)&&!y(t.$eq)?{id:t.$eq}:void 0}if(!(te(t)||t===null||Array.isArray(t)||y(t)))return{id:t}}var vr=()=>({children:new Map});function Qr(e,t,n){let r=t.split("."),o=e;for(let i=0;i<r.length;i++){let s=r[i];if(o.leaf&&o!==e)throw new m(31249,"Location31249",`Path collision at ${t}`);let a=o.children.get(s);a||(a=vr(),o.children.set(s,a)),o=a}if(o.leaf||o.children.size>0)throw new m(31250,"Location31250",`Path collision at ${t}`);o.leaf=n}function lt(e,t,n={},r){if(e==null)return l=>l;if(!y(e))throw A("projection must be an object");let o=Object.entries(e);if(t==="find"&&o.length===0)return l=>l;if(t==="project"&&o.length===0)throw new m(51272,"Location51272","Invalid $project :: caused by :: projection specification must have at least one field");let i=vr(),s,a,c;for(let[l,u]of o){let d=l.endsWith(".$")?l.slice(0,-2):l;if(l.endsWith(".$")){if(t!=="find")throw new m(31324,"Location31324","Cannot use positional projection in aggregation projection");if(s===!1)throw new m(31395,"Location31395","Cannot specify positional operator in exclusion projection");Qr(i,d,{kind:"positional",arg:Ki(d,r)}),s=!0;continue}let p,b;if(y(u)&&"$slice"in u&&t==="find"?(p="slice",b=u.$slice):y(u)&&"$elemMatch"in u&&t==="find"?(p="elemMatch",b=q(u.$elemMatch)):typeof u=="boolean"||F(u)?p=ne(u)?"include":"exclude":(p="expr",b=u),d==="_id"&&p!=="slice"&&p!=="elemMatch"){a=p==="include"?"include":p==="exclude"?"exclude":"expr",p==="expr"&&(c=b,s=!0);continue}if(p==="elemMatch"&&s===void 0&&(s=!0),p==="include"||p==="expr"){if(s===!1)throw new m(31253,"Location31253",`Cannot do inclusion on field ${d} in exclusion projection`);s=!0}else if(p==="exclude"){if(s===!0)throw new m(31254,"Location31254",`Cannot do exclusion on field ${d} in inclusion projection`);s=!1}Qr(i,d,{kind:p,arg:b})}let f=s??a==="include";return l=>{let u;if(f){if(u={},a==="expr"){let d=J(c,l,n);d!==Ke&&d!==void 0&&(u._id=d)}else a!=="exclude"&&l._id!==void 0&&(u._id=L(l._id));Vt(l,i,u,l,n)}else u=L(l),a==="exclude"&&delete u._id,jn(u,i,l,n);return u}}function Vt(e,t,n,r,o){for(let i of Object.keys(e)){let s=t.children.get(i);if(!s)continue;if(s.leaf){let c=s.leaf;if(c.kind==="include")n[i]=L(e[i]);else if(c.kind==="slice")n[i]=to(e[i],c.arg);else if(c.kind==="elemMatch"){let f=no(e[i],c.arg);f!==void 0&&(n[i]=f)}else if(c.kind==="positional"){let f=e[i];if(!Array.isArray(f)){n[i]=L(f);continue}let l=c.arg(f);if(l<0)throw new m(51246,"Location51246","Executor error during find command :: caused by :: positional operator '.$' couldn't find a matching element in the array");n[i]=[L(f[l])]}continue}let a=e[i];if(y(a)){let c={};Vt(a,s,c,r,o),n[i]=c}else Array.isArray(a)&&(n[i]=a.filter(c=>y(c)||Array.isArray(c)).map(c=>{if(!y(c))return c;let f={};return Vt(c,s,f,r,o),f}))}for(let[i,s]of t.children)if(s.leaf?.kind==="expr"){let a=J(s.leaf.arg,r,o);a!==Ke&&a!==void 0&&(n[i]=a)}else if(!s.leaf&&!(i in n)&&eo(s)){let a={};Vt({},s,a,r,o),n[i]=a}}function eo(e){for(let t of e.children.values())if(t.leaf?.kind==="expr"||eo(t))return!0;return!1}function jn(e,t,n,r){for(let[o,i]of t.children){if(i.leaf){if(i.leaf.kind==="exclude")delete e[o];else if(i.leaf.kind==="slice")e[o]!==void 0&&(e[o]=to(e[o],i.leaf.arg));else if(i.leaf.kind==="elemMatch"){let a=no(e[o],i.leaf.arg);a===void 0?delete e[o]:e[o]=a}continue}let s=e[o];if(y(s))jn(s,i,n,r);else if(Array.isArray(s))for(let a of s)y(a)&&jn(a,i,n,r)}}function Ki(e,t){let n=Object.entries(t??{}).filter(([o])=>o===e||o.startsWith(`${e}.`));if(n.length===0)throw new m(51050,"Location51050",`Executor error during find command :: caused by :: positional operator '${e}.$' requires corresponding field in query specifier`);let r=n.map(([o,i])=>{if(o===e){let a=q({v:i});return c=>a({v:[c]})}let s=q({[o.slice(e.length+1)]:i});return a=>y(a)&&s(a)});return o=>o.findIndex(i=>r.every(s=>s(i)))}function to(e,t){if(!Array.isArray(e))return e;if(Array.isArray(t)){let r=$(t[0]),o=$(t[1]);if(o<=0)throw A("$slice limit must be positive");let i=r<0?Math.max(0,e.length+r):r;return e.slice(i,i+o)}let n=$(t);return n>=0?e.slice(0,n):e.slice(n)}function no(e,t){if(!Array.isArray(e))return;let n=e.find(r=>y(r)&&t(r));return n===void 0?void 0:[L(n)]}function Ge(e){if(e==null)return[];if(!y(e))throw A("sort must be an object");return Object.entries(e).map(([t,n])=>{if(y(n))throw"$meta"in n?new m(115,"CommandNotSupported",`$meta sort by "${String(n.$meta)}" is not supported by the MongoDB twin`):A(`Illegal key in $sort specification: ${t}: ${JSON.stringify(n)}`);if(t.startsWith("$")&&t!=="$natural")throw A("FieldPath field names may not start with '$'. Consider using $getField or $setField.");let r=$(n);if(r!==1&&r!==-1)throw new m(15975,"Location15975","$sort key ordering must be 1 (for ascending) or -1 (for descending)");return[t,r]})}var Gi=new Ce;function Zi(e,t,n){let r=[];for(let i of K(e,t))Array.isArray(i)?i.length===0?r.push(Gi):r.push(...i):r.push(i);if(r.length===0)return null;let o=r[0]??null;for(let i of r.slice(1)){let s=z(i??null,o);(n===1?s<0:s>0)&&(o=i??null)}return o}function ze(e,t){if(t.length===0)return e;let n=e.map((r,o)=>({doc:r,i:o,keys:t.map(([i,s])=>i==="$natural"?o:Zi(r,i,s))}));return n.sort((r,o)=>{for(let i=0;i<t.length;i++){let s=z(r.keys[i],o.keys[i]);if(s!==0)return s*t[i][1]}return r.i-o.i}),n.map(r=>r.doc)}var Xi=e=>new m(40324,"Location40324",`Unrecognized pipeline stage name: '${e}'`);function ft(e,t,n){let r=e,o=n.vars??{};for(let i of t){if(!y(i))throw new m(40323,"Location40323","A pipeline stage specification object must contain exactly one field.");let s=Object.keys(i);if(s.length!==1)throw new m(40323,"Location40323","A pipeline stage specification object must contain exactly one field.");let a=s[0];r=vi(a,i[a],r,n,o)}return r}function Qi(e,t,n){let r=L(e);for(let[o,i]of Object.entries(t)){let s=J(i,e,n),a=o.split("."),c=r;for(let l of a.slice(0,-1))y(c[l])||(c[l]={}),c=c[l];let f=a[a.length-1];s===Ke?delete c[f]:s!==void 0&&(c[f]=s)}return r}function vi(e,t,n,r,o){switch(e){case"$match":{let i=q(t,o);return n.filter(s=>i(s))}case"$project":{let i=lt(t,"project",o);return n.map(s=>i(s))}case"$addFields":case"$set":{if(!y(t))throw new m(40272,"Location40272",`${e} specification stage must be an object, got ${typeof t}`);return n.map(i=>Qi(i,t,{...o,ROOT:i}))}case"$unset":{let i=Array.isArray(t)?t:[t],s=lt(Object.fromEntries(i.map(a=>[String(a),0])),"project",o);return n.map(a=>s(a))}case"$sort":return ze([...n],Ge(t));case"$limit":{if(!F(t)||$(t)<=0)throw new m(15958,"Location15958","the limit must be positive");return n.slice(0,$(t))}case"$skip":{if(!F(t)||$(t)<0)throw new m(15956,"Location15956","Argument to $skip cannot be negative");return n.slice($(t))}case"$count":{if(typeof t!="string"||t===""||t.startsWith("$")||t.includes("."))throw new m(40156,"Location40156","the count field must be a non-empty string that does not start with $ and does not contain .");return n.length===0?[]:[{[t]:n.length}]}case"$group":return ro(t,n,o);case"$sortByCount":{let i=ro({_id:t,count:{$sum:1}},n,o);return ze(i,[["count",-1]])}case"$unwind":return es(t,n);case"$lookup":return ts(t,n,r,o);case"$replaceRoot":case"$replaceWith":{let i=e==="$replaceRoot"?t?.newRoot:t;return n.map(s=>{let a=J(i,s,{...o,ROOT:s});if(!y(a))throw new m(40228,"Location40228",`'newRoot' expression must evaluate to an object, but resulting value was: ${JSON.stringify(a)}. Type of resulting value: '${typeof a}'.`);return a})}case"$facet":{if(!y(t))throw new m(40169,"Location40169","the $facet specification must be a non-empty object");let i={};for(let[s,a]of Object.entries(t))i[s]=ft(n,a,r);return[i]}default:throw Xi(e)}}function ro(e,t,n){if(!y(e))throw new m(15947,"Location15947","a group's fields must be specified in an object");if(!("_id"in e))throw new m(15955,"Location15955","a group specification must include an _id");let r=Object.entries(e).filter(([s])=>s!=="_id").map(([s,a])=>{if(!y(a)||Object.keys(a).length!==1)throw new m(40234,"Location40234",`The field '${s}' must be an accumulator object`);let c=Object.keys(a)[0];return{k:s,op:c,expr:a[c]}}),o=new Map;for(let s of t){let a=J(e._id,s,{...n,ROOT:s});a===void 0&&(a=null);let c=oe(a),f=o.get(c);f||(f={id:a,accs:r.map(l=>Gr(l.op,l.expr,n))},o.set(c,f));for(let l of f.accs)l.add(s)}let i=[];for(let s of o.values()){let a={_id:s.id};r.forEach((c,f)=>{a[c.k]=s.accs[f].result()}),i.push(a)}return i}function es(e,t){let n=typeof e=="string"?{path:e}:y(e)?e:{},r=n.path;if(typeof r!="string"||!r.startsWith("$"))throw new m(28818,"Location28818","path option to $unwind stage should be prefixed with a '$': "+String(r));let o=r.slice(1),i=typeof n.includeArrayIndex=="string"?n.includeArrayIndex:void 0,s=n.preserveNullAndEmptyArrays===!0,a=[];for(let c of t){let f=J(r,c);if(Array.isArray(f)){if(f.length===0){if(s){let l=L(c);oo(l,o,void 0),i&&(l[i]=null),a.push(l)}continue}f.forEach((l,u)=>{let d=L(c);oo(d,o,L(l)),i&&(d[i]=u),a.push(d)})}else if(f==null){if(s){let l=L(c);i&&(l[i]=null),a.push(l)}}else{let l=L(c);i&&(l[i]=null),a.push(l)}}return a}function oo(e,t,n){let r=t.split("."),o=e;for(let i of r.slice(0,-1))y(o[i])||(o[i]={}),o=o[i];n===void 0?delete o[r[r.length-1]]:o[r[r.length-1]]=n}function ts(e,t,n,r){if(!y(e))throw new m(40319,"Location40319","the $lookup specification must be an Object");let o=e.from,i=e.as;if(typeof i!="string")throw new m(40449,"Location40449","must specify 'as' field for a $lookup");if(o!==void 0&&typeof o!="string")throw new m(115,"CommandNotSupported","$lookup from another database is not supported by the MongoDB twin");let s=typeof o=="string"?n.collection(o):[],a=Array.isArray(e.pipeline)?e.pipeline:void 0,c=typeof e.localField=="string"||typeof e.foreignField=="string";if(!a&&!c)throw new m(40450,"Location40450","$lookup requires either 'pipeline' or both 'localField' and 'foreignField' to be specified");return t.map(f=>{let l=s;if(c){if(typeof e.localField!="string"||typeof e.foreignField!="string")throw new m(40450,"Location40450","$lookup requires both or neither of 'localField' and 'foreignField' to be specified");let u=J(`$${e.localField}`,f),d=Array.isArray(u)?u.length?u:[null]:[u??null],p=q({[e.foreignField]:{$in:d.map(b=>b===void 0?null:b)}});l=l.filter(b=>p(b))}if(a){let u={...r};if(y(e.let))for(let[d,p]of Object.entries(e.let))u[d]=J(p,f,r);l=ft(l.map(L),a,{...n,vars:u})}return{...L(f),[i]:l.map(L)}})}function io(e){if(!Array.isArray(e))throw new m(14,"TypeMismatch","'pipeline' option must be specified as an array");return e}import{applyTwinWrite as ns,getActiveWorldStore as rs,ownFields as os,treeChangesSince as is,treeStamp as ss,twinResources as as}from"../../engine/v2/volter_world-core.mjs";var Ze="mongodb",_=(e,t)=>`${e}.${t}`,Fn=(e,t)=>_(e,t),Rn=encodeURIComponent,Pn=(e,t,n)=>`${e}.${Rn(t)}#${Rn(n)}`,Wt=(e,t,n)=>`${e}.${Rn(t)}/${n}`,Yt={v:2,key:{_id:1},name:"_id_"};function ao(e,t,n){return co(e,t,n)}var so=new WeakMap;function co(e,t,n){return{db:e,name:t,uuid:n,docs:new Map,indexes:new Map([[Yt.name,Yt]]),written:new Map}}function Cn(e,t){let n=os(t),r=n.deleted===!0,o=String(n.db??""),i=String(t.type==="collection"?n.name??"":n.collection??"");if(!o||!i)return!0;let s=_(o,i);if(t.type==="collection"){if(r)return e.collections.delete(s),!0;let a=e.collections.get(s);return a?a.uuid=String(n.uuid??a.uuid):e.collections.set(s,co(o,i,String(n.uuid??""))),!0}if(t.type==="index"){let a=e.collections.get(s);if(!a)return!!r;let c=String(n.name??"");return r?a.indexes.delete(c):a.indexes.set(c,ye(n.spec)),!0}if(t.type==="document"){let a=e.collections.get(s),c=String(n.key??""),f=e.known.get(s);return f||(f=new Set,e.known.set(s,f)),f.add(c),a?r?(a.docs.delete(c),a.written.delete(c),!0):(a.docs.set(c,ye(n.document)),a.written.set(c,Date.parse(t.updatedAt)),!0):r}return!0}function cs(e){let t={collections:new Map,known:new Map},n=as(Ze,e);for(let r of n)r.type==="collection"&&Cn(t,r);for(let r of n)r.type!=="collection"&&Cn(t,r);return t}function lo(e){let t=new Map;for(let[n,r]of e.collections)t.set(n,{...r,docs:new Map(r.docs),indexes:new Map(r.indexes),written:new Map(r.written)});return{collections:t,known:e.known}}function ls(e){let t=lo(e);return t.known=new Map([...e.known].map(([n,r])=>[n,new Set(r)])),t}function zn(e){return lo(fe(e))}function fe(e){let t=rs(),n=so.get(t)??so.set(t,new Map).get(t),r=e??"",o=n.get(r),i=o?is(Ze,e,o.stamp):void 0;if(o&&i&&i.removed.length===0){let a=ls(o.image);if([...i.changed].sort((f,l)=>(f.type==="collection"?0:1)-(l.type==="collection"?0:1)).every(f=>Cn(a,f)))return o={stamp:i.stamp,image:a},n.set(r,o),o.image}let s=ss(Ze,e);return(!o||o.stamp!==s)&&(o={stamp:s,image:cs(e)},n.set(r,o)),o.image}function fs(e){switch(e.kind){case"collection":return{type:"collection",id:Fn(e.db,e.name),fields:{db:e.db,name:e.name,uuid:e.uuid,deleted:e.deleted===!0}};case"index":return{type:"index",id:Pn(e.db,e.collection,e.spec.name),fields:{db:e.db,collection:e.collection,name:e.spec.name,spec:v(e.spec),deleted:e.deleted===!0}};case"document":return e.doc===null?{type:"document",id:Wt(e.db,e.collection,e.key),fields:{db:e.db,collection:e.collection,key:e.key,document_id:v({_id:e.id})._id,deleted:!0}}:{type:"document",id:Wt(e.db,e.collection,e.key),fields:{db:e.db,collection:e.collection,key:e.key,document_id:v({_id:e.id})._id,document:v(e.doc),deleted:!1}}}}async function fo(e,t,n,r,o){if(n.length===0)return;let i=new Map;for(let c of n){let f=fs(c),l=`${f.type}:${f.id}`;i.delete(l),i.set(l,f)}let[s,...a]=[...i.values()];await ns(Ze,{operation:t,subjectType:s.type,subjectId:s.id,fields:s.fields,...a.length?{projection:{updates:a.map(c=>({type:c.type,id:c.id,fields:c.fields}))}}:{},...o?{input:o}:{},occurredAt:r,actor:{kind:"agent"}},e)}var qt=new Map;function uo(e,t){let n=e??"",o=(qt.get(n)??Promise.resolve()).then(t,t),i=o.then(()=>{},()=>{});return qt.set(n,i),i.then(()=>{qt.get(n)===i&&qt.delete(n)}),o}var po=new Set(["$and","$or","$nor"]);function mo(e,t){return Object.entries(e).some(([n,r])=>n===t||n.startsWith(`${t}.`)||po.has(n)&&Array.isArray(r)&&r.some(o=>y(o)&&mo(o,t)))}function yo(e,t){let n={};for(let[r,o]of Object.entries(e))po.has(r)&&Array.isArray(o)?n[r]=o.map(i=>y(i)?yo(i,t):i):r===t?n.v=o:r.startsWith(`${t}.`)?n[`v.${r.slice(t.length+1)}`]=o:n[r]=o;return n}var us=new Set(["$set","$unset","$inc","$mul","$min","$max","$rename","$push","$pull","$pullAll","$addToSet","$pop","$setOnInsert","$currentDate","$bit"]);function Nt(e){if(Array.isArray(e))return"pipeline";if(!y(e))throw Pe("Update argument must be either an object or an array");let t=Object.keys(e);if(t.length>0&&t[0].startsWith("$"))return"operators";for(let n of t)if(n.startsWith("$"))throw Pe(`The dollar ($) prefixed field '${n}' in '${n}' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith.`);return"replacement"}function Wn(e){let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("$"))throw Pe(`Unknown modifier: ${n}. Expected a valid update modifier or pipeline-style update specified as an array`);if(!us.has(n))throw Pe(`Unknown modifier: ${n}. Expected a valid update modifier or pipeline-style update specified as an array`);if(!y(r))throw Pe(`Modifiers operate on fields but we found type ${P(r)} instead. For example: {$mod: {<field>: ...}} not {$set: <field>}`);for(let[o,i]of Object.entries(r)){if(o==="")throw new m(56,"EmptyFieldName","An update path 'field.path' cannot be empty");let s=n==="$rename"?[o,String(i)]:[o];for(let a of s){let c=a.replace(/\.\$(\[[^\]]*\])?/g,".$");for(let f of t)if(hs(c,f))throw new m(40,"ConflictingUpdateOperators",`Updating the path '${a}' would create a conflict at '${gs(c,f)}'`);t.push(c)}if(n==="$rename"&&typeof i!="string")throw A(`The 'to' field for $rename must be a string: ${o}: ${C(i)}`);if((n==="$inc"||n==="$mul")&&!F(i))throw qn(`Cannot ${n==="$inc"?"increment":"multiply"} with non-numeric argument: {${o}: ${C(i)}}`)}}}function qn(e){return new m(14,"TypeMismatch",e)}function ds(e,t){let n=e.split("."),r=t.split(".");for(let o=0;o<Math.min(n.length,r.length);o++)if(n[o]!==r[o])return n[o]<r[o]?-1:1;return n.length-r.length}function hs(e,t){return e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`)}function gs(e,t){return e.length<=t.length?e:t}function he(e,t,n,r){let o=t.split("."),i=[e];for(let c=0;c<o.length-1;c++){let f=o[c],l=[];for(let u of i)for(let d of ho(u,f,o.slice(0,c).join("."),n)){let p=u[d];if(p==null){if(!r)continue;Array.isArray(u)&&Number(d)>u.length&&wo(u,Number(d)),p={},u[d]=p}if(y(p)||Array.isArray(p))l.push(p);else if(r)throw new m(28,"PathNotViable",`Cannot create field '${o[c+1]}' in element {${f}: ${C(p)}}`)}i=l}let s=o[o.length-1],a=[];for(let c of i)for(let f of ho(c,s,o.slice(0,-1).join("."),n))a.push({parent:c,key:f});return a}function wo(e,t){for(;e.length<t;)e.push(null)}function ho(e,t,n,r){if(t==="$"){if(!Array.isArray(e))throw A("The positional operator did not find the match needed from the query.");let i=r.positions?.get(n);if(i===void 0){let s=r.original===void 0?e:Kr(r.original,n);i=ps(Array.isArray(s)?s:e,n,r),r.positions?.set(n,i)}if(i<0)throw A("The positional operator did not find the match needed from the query.");return[String(i)]}if(t==="$[]"){if(!Array.isArray(e))throw A(`The path '${n}' must exist in the document in order to apply array updates.`);return e.map((i,s)=>String(s))}let o=t.match(/^\$\[([a-z][a-zA-Z0-9]*)\]$/);if(o){if(!Array.isArray(e))throw A(`The path '${n}' must exist in the document in order to apply array updates.`);let i=o[1],s=(r.arrayFilters??[]).find(c=>mo(c,i));if(!s)throw A(`No array filter found for identifier '${i}' in path '${n}.${t}'`);let a=q(yo(s,i));return e.flatMap((c,f)=>a({v:c})?[String(f)]:[])}if(Array.isArray(e)&&!/^\d+$/.test(t))throw new m(28,"PathNotViable",`Cannot create field '${t}' in element {${n}: ${C(e)}}`);return[t]}function ps(e,t,n){if(!n.query)return-1;for(let[r,o]of Object.entries(n.query))if(r===t){let i=q({v:o});for(let s=0;s<e.length;s++)if(i({v:[e[s]]}))return s}else if(r.startsWith(`${t}.`)){let i=q({[r.slice(t.length+1)]:o});for(let s=0;s<e.length;s++){let a=e[s];if(y(a)&&i(a))return s}}return-1}function Xe(e){return e.parent[e.key]}function $e(e,t){Array.isArray(e.parent)&&Number(e.key)>e.parent.length&&wo(e.parent,Number(e.key)),e.parent[e.key]=t}function go(e){Array.isArray(e.parent)?Number(e.key)<e.parent.length&&(e.parent[Number(e.key)]=null):delete e.parent[e.key]}function Vn(e){return`{_id: ${C(e._id)}}`}function ms(e,t,n){if(Q(e)||Q(t)){let r=Q(e)?e:w.fromNumber($(e)),o=Q(t)?t:w.fromNumber($(t));return!Number.isInteger($(e))||!Number.isInteger($(t))?n==="$inc"?$(e)+$(t):$(e)*$(t):n==="$inc"?r.add(o):r.multiply(o)}return n==="$inc"?$(e)+$(t):$(e)*$(t)}function Yn(e,t,n){let r=L(e),o=e._id,i={...n,original:r,positions:new Map},s=[];for(let[a,c]of Object.entries(t))for(let[f,l]of Object.entries(c))s.push([a,f,l]);s.sort(([,a],[,c])=>ds(a,c));for(let[a,c,f]of s)ys(e,a,c,f,i);if(o!==void 0&&!H(e._id,o))throw new m(66,"ImmutableField","Performing an update on the path '_id' would modify the immutable field '_id'");return z(r,e)!==0||Object.keys(r).join("\0")!==Object.keys(e).join("\0")}function ys(e,t,n,r,o){switch(t){case"$set":for(let i of he(e,n,o,!0))$e(i,L(r));return;case"$setOnInsert":if(o.inserting)for(let i of he(e,n,o,!0))$e(i,L(r));return;case"$unset":for(let i of he(e,n,o,!1))go(i);return;case"$currentDate":{let i=r;if(y(i)&&(Object.keys(i).length!==1||!("$type"in i)||i.$type!=="date"&&i.$type!=="timestamp"))throw A("The '$type' string field is required to be 'date' or 'timestamp': {$currentDate: {field : {$type: 'date'}}}");if(!y(i)&&typeof i!="boolean")throw A(`${P(i)} is not valid type for $currentDate. Please use a boolean ('true') or a $type expression ({$type: 'timestamp/date'}).`);if(y(i)&&i.$type==="timestamp")throw new m(115,"CommandNotSupported","$currentDate with $type timestamp is not supported by the MongoDB twin");for(let s of he(e,n,o,!0))$e(s,new Date(o.now.getTime()));return}case"$inc":case"$mul":{for(let i of he(e,n,o,!0)){let s=Xe(i);if(s===void 0){$e(i,t==="$inc"?r:Q(r)?w.ZERO:0);continue}if(!F(s))throw qn(`Cannot apply ${t} to a value of non-numeric type. ${Vn(e)} has the field '${i.key}' of non-numeric type ${P(s)}`);$e(i,ms(s,r,t))}return}case"$min":case"$max":{for(let i of he(e,n,o,!0)){let s=Xe(i);if(s===void 0){$e(i,L(r));continue}let a=z(r,s);(t==="$min"?a<0:a>0)&&$e(i,L(r))}return}case"$rename":{let i=String(r),s=he(e,n,o,!1);for(let a of s){if(Array.isArray(a.parent))throw A(`The source field cannot be an array element, '${n}' in doc with _id: ${C(e._id)} has an array field called '${a.key}'`);let c=Xe(a);if(c!==void 0){go(a);for(let f of he(e,i,o,!0))$e(f,c)}}return}case"$push":case"$addToSet":{let i=y(r)&&"$each"in r,s=i?Array.isArray(r.$each)?r.$each:(()=>{throw A(`The argument to $each in ${t} must be an array but it was of type: ${P(r.$each)}`)})():[r];if(t==="$addToSet"&&i){for(let a of Object.keys(r))if(a!=="$each")throw A(`Found unexpected fields after $each in $addToSet: ${C(r)}`)}if(t==="$push"&&i){for(let a of Object.keys(r))if(!["$each","$slice","$sort","$position"].includes(a))throw A(`Unrecognized clause in $push: ${a}`)}for(let a of he(e,n,o,!0)){let c=Xe(a);if(c===void 0&&(c=[],$e(a,c)),!Array.isArray(c))throw A(`The field '${a.key}' must be an array but is of type ${P(c)} in document ${Vn(e)}`);if(t==="$addToSet"){for(let d of s)c.some(p=>H(p,d))||c.push(L(d));continue}let f=i?r:{},l=f.$position===void 0?c.length:$(f.$position),u=l<0?Math.max(0,c.length+l):Math.min(l,c.length);if(c.splice(u,0,...s.map(L)),f.$sort!==void 0){let d=y(f.$sort)?ze(c,Ge(f.$sort)):[...c].sort((p,b)=>z(p,b)*($(f.$sort)===-1?-1:1));c.splice(0,c.length,...d)}if(f.$slice!==void 0){let d=$(f.$slice),p=d>=0?c.slice(0,d):c.slice(d);c.splice(0,c.length,...p)}}return}case"$pop":{if(!F(r)||$(r)!==1&&$(r)!==-1)throw Pe(`$pop expects 1 or -1, found: ${C(r)}`);for(let i of he(e,n,o,!1)){let s=Xe(i);if(s!==void 0){if(!Array.isArray(s))throw qn(`Path '${n}' contains an element of non-array type '${P(s)}'`);$(r)===-1?s.shift():s.pop()}}return}case"$pull":case"$pullAll":{let i=t==="$pullAll"?Array.isArray(r)?r:(()=>{throw A(`$pullAll requires an array argument but was given a ${P(r)}`)})():null,s=i===null?y(r)&&!le(r)?(()=>{let a=q(r);return c=>y(c)&&a(c)})():le(r)?(()=>{let a=q({v:r});return c=>a({v:c})})():a=>H(a,r):a=>i.some(c=>H(a,c));for(let a of he(e,n,o,!1)){let c=Xe(a);if(c===void 0)continue;if(!Array.isArray(c))throw A(`Cannot apply ${t} to a non-array value`);let f=c.filter(l=>!s(l));c.splice(0,c.length,...f)}return}case"$bit":{let i=s=>Q(s)||typeof s=="number"&&Number.isInteger(s)&&s>=-2147483648&&s<=2147483647;if(!y(r))throw A(`The $bit modifier is not compatible with a ${P(r)}. You must pass in an embedded document: {$bit: {field: {and/or/xor: #}}`);for(let[s,a]of Object.entries(r)){if(!["and","or","xor"].includes(s))throw A(`The $bit modifier only supports 'and', 'or', and 'xor', not '${s}' which is an unknown operator: {${s}: ${C(a)}}`);if(!i(a))throw A(`The $bit modifier field must be an Integer(32/64 bit); a '${P(a)}' is not supported here: {${s}: ${C(a)}}`)}for(let s of he(e,n,o,!0)){let a=Xe(s)??0;if(!i(a))throw A(`Cannot apply $bit to a value of non-integral type.${Vn(e)} has the field ${s.key} of non-integer type ${P(a)}`);let c=Q(a),f=BigInt(Q(a)?a.toString():a);for(let[l,u]of Object.entries(r)){Q(u)&&(c=!0);let d=BigInt(Q(u)?u.toString():u);f=l==="and"?f&d:l==="or"?f|d:f^d}$e(s,c?w.fromBigInt(BigInt.asIntN(64,f)):Number(BigInt.asIntN(32,f)))}return}default:throw Pe(`Unknown modifier: ${t}. Expected a valid update modifier or pipeline-style update specified as an array`)}}function bo(e,t){if(t._id!==void 0&&e._id!==void 0&&!H(t._id,e._id))throw new m(66,"ImmutableField",`After applying the update, the (immutable) field '_id' was found to have been altered to _id: ${C(t._id)}`);let n={_id:e._id};for(let[r,o]of Object.entries(t))r!=="_id"&&(n[r]=L(o));return n._id===void 0&&delete n._id,n}function Hn(e,t,n,r){let o=new Set(["$addFields","$set","$project","$unset","$replaceRoot","$replaceWith"]);for(let s of t){let a=y(s)?Object.keys(s)[0]:void 0;if(!a||!o.has(a))throw new m(72,"InvalidOptions",`${a??"stage"} is not allowed to be used within an update`)}let[i]=r([e],t);if(!i)return e;if(e._id!==void 0&&i._id!==void 0&&!H(i._id,e._id))throw new m(66,"ImmutableField","Performing an update on the path '_id' would modify the immutable field '_id'");return i._id===void 0&&e._id!==void 0?{_id:e._id,...i}:i}var Xn="7.0.0",Qn=21,Kt=16*1024*1024,vn=48e6,Jt=1e5,Io=101;function xt(){return{cursors:new Map,nextCursor:0,nextConnection:0,nextSession:0}}var $o=new Set(["insert","update","delete","findAndModify","findandmodify","create","drop","dropDatabase","createIndexes","dropIndexes","deleteIndexes"]);function Ao(e){let t=X.parse(e,{relaxed:!1});return ye(X.serialize(t,{relaxed:!1}))}async function Gt(e){let t=e.path.split("?")[0].replace(/\/+$/,"")||"/";if(e.method==="GET"&&t==="/")return{status:200,body:{service:"mongodb",version:Xn,maxWireVersion:Qn,door:"POST /command with a command document as canonical Extended JSON ($db names the database)"}};if(e.method!=="POST"||t!=="/command")return{status:404,body:{ok:0,errmsg:`the MongoDB twin serves commands at POST /command (got ${e.method} ${t})`,code:59,codeName:"CommandNotFound"}};let n=typeof e.body=="string"||e.body===void 0,r;try{r=n?Ao(String(e.body??"")):e.body}catch(i){return{status:400,body:{ok:0,errmsg:`invalid Extended JSON command: ${i.message}`,code:9,codeName:"FailedToParse"}}}let o=await To(r,{...e.root!==void 0?{root:e.root}:{},now:e.occurredAt??ws(),readOnly:e.readOnly??!1,server:e.server??xt(),connection:e.connection??{id:0}});return{status:200,body:n?X.serialize(v(o),{relaxed:!1}):o}}function Ht(e){return e instanceof m?{ok:0,errmsg:e.message,code:e.code,codeName:e.codeName,...e.extra}:{ok:0,errmsg:String(e?.message??e),code:1,codeName:"InternalError"}}var Se=e=>new m(115,"CommandNotSupported",`${e} is not supported by the MongoDB twin`);async function To(e,t){let n=Object.keys(e)[0];if(n===void 0)return Ht(new m(59,"CommandNotFound","no such command: ''"));let r=Vo[n];if(!r)return Ht(new m(59,"CommandNotFound",`no such command: '${n}'`));let o=typeof e.$db=="string"?e.$db:"admin";try{if(!/^[^/\\. "$*<>:|?\0]{1,63}$/.test(o))throw new m(73,"InvalidNamespace",`Invalid database name: '${o}'`);if(e.txnNumber!==void 0||e.startTransaction!==void 0||e.autocommit!==void 0)throw new m(20,"IllegalOperation","Transaction numbers are only allowed on a replica set member or mongos");if(t.readOnly&&$o.has(n))throw new m(13,"Unauthorized",`not authorized on ${o} to execute command { ${n}: ... }: this MongoDB twin was started read-only`);let i=y(e.writeConcern)?e.writeConcern.w:void 0;if(F(i)&&$(i)>1)throw new m(2,"BadValue","cannot use 'w' > 1 when a host is not replicated");let s=e.collation;if(y(s)&&s.locale!=="simple")throw Se(`collation ${C(s)}`);let a=async()=>r(e,o,t);return $o.has(n)?await uo(t.root,a):await a()}catch(i){return Ht(i)}}function re(e,t){let n=e[t];if(typeof n!="string")throw new m(73,"InvalidNamespace",`collection name has invalid type ${typeof n}`);if(n===""||n.includes("$")||n.includes("\0"))throw new m(73,"InvalidNamespace",`Invalid namespace specified '${n}'`);return n}var So=6e4;function _o(e){return[...e.indexes.values()].filter(t=>typeof t.expireAfterSeconds=="number"&&Object.keys(t.key).length===1)}function dt(e,t){if(!e)return[];let n=_o(e);if(n.length===0)return[...e.docs.values()];let r=[];for(let[o,i]of e.docs)Lo(i,e.written.get(o)??0,n,t)||r.push(i);return r}function Lo(e,t,n,r){for(let o of n){if(y(o.partialFilterExpression)&&!q(o.partialFilterExpression)(e))continue;let i=Object.keys(o.key)[0],s=K(e,i).flatMap(f=>Array.isArray(f)?f:[f]).filter(f=>f instanceof Date);if(s.length===0)continue;let a=Math.min(...s.map(f=>f.getTime()))+$(o.expireAfterSeconds)*1e3;if((Math.floor(Math.max(a,t)/So)+1)*So<=r.getTime())return!0}return!1}function Mo(e,t){let n=t===void 0?Number.POSITIVE_INFINITY:t,r=[],o=0,i=0;for(;i<e.length&&r.length<n;i++){let s=Mt.calculateObjectSize(e[i]);if(r.length>0&&o+s>Kt-16*1024)break;r.push(e[i]),o+=s}return{batch:r,rest:e.slice(i)}}function Zt(e,t,n,r,o=!1,i=!0){let{batch:s,rest:a}=Mo(n,r),c=w.ZERO;return a.length>0&&!o&&(e.server.nextCursor+=1,c=w.fromNumber(e.server.nextCursor),e.server.cursors.set(c.toString(),{ns:t,docs:a})),{cursor:{[i?"firstBatch":"nextBatch"]:s,id:c,ns:t},ok:1}}function It(e,t="batchSize"){let n=e[t];if(n!==void 0){if(!F(n)||$(n)<0)throw new m(51024,"Location51024",`BSON field '${t}' value must be >= 0, actual value '${C(n)}'`);return $(n)}}function bs(e,t){let n=Buffer.alloc(12);return n.writeUInt32BE(Math.floor(t.getTime()/1e3)>>>0,0),xo("sha256").update(e).digest().copy(n,4,0,8),new ae(n)}function ko(e){let t=xo("sha256").update(e).digest().subarray(0,16);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,new M(Buffer.from(t),M.SUBTYPE_UUID)}function $s(e,t){let r=Object.keys(t).map(i=>{let s=K(e,i).flatMap(a=>Array.isArray(a)?a.length?a:[void 0]:[a]);return s.length?s:[void 0]}),o=[[]];for(let i of r)o=o.flatMap(s=>i.map(a=>[...s,a]));return o}function ut(e,t){if(y(e.partialFilterExpression)&&!q(e.partialFilterExpression)(t))return[];let n=$s(t,e.key)??[];return e.sparse&&n.every(r=>r.every(o=>o===void 0))?[]:n.map(r=>({key:Jr(r),values:r}))}function Zn(e,t,n,r=""){let o={},i={};return Object.keys(t.key).forEach((s,a)=>{o[s]=t.key[s],i[s]=n[a]===void 0?null:n[a]}),new m(11e3,"DuplicateKey",`${r}E11000 duplicate key error collection: ${e} index: ${t.name} dup key: ${C(i)}`,{keyPattern:o,keyValue:i})}var we=class{image;changes=[];now;minted=0;unique=new Map;ctx;constructor(t){this.ctx=t,this.image=zn(t.root),this.now=new Date(t.now)}get(t,n){return this.image.collections.get(_(t,n))}ensure(t,n){let r=this.get(t,n);if(r)return{coll:r,created:!1};let o=ko(`${_(t,n)}|${this.now.toISOString()}`).toString("hex"),i=ao(t,n,o);return this.image.collections.set(_(t,n),i),this.changes.push({kind:"collection",db:t,name:n,uuid:o}),this.purgeExpired(i),{coll:i,created:!0}}newId(t){this.minted+=1;let n=_(t.db,t.name);return bs(`${n}|${(this.image.known.get(n)?.size??0)+this.minted}`,this.now)}docs(t){return dt(t,this.now)}purgeExpired(t){let n=_o(t);if(n.length!==0)for(let[r,o]of[...t.docs])Lo(o,t.written.get(r)??0,n,this.now)&&this.remove(t,r)}uniqueMap(t,n){let r=`${_(t.db,t.name)}#${n.name}`,o=this.unique.get(r);if(!o){o=new Map;for(let[i,s]of t.docs)for(let a of ut(n,s))o.has(a.key)||o.set(a.key,i);this.unique.set(r,o)}return o}put(t,n){let r=_(t.db,t.name),o=oe(n._id),i=t.docs.get(o),s=[...t.indexes.values()].filter(a=>a.unique===!0);for(let a of s){let c=this.uniqueMap(t,a);for(let f of ut(a,n)){let l=c.get(f.key);if(l!==void 0&&l!==o)throw Zn(r,a,f.values)}}for(let a of s){let c=this.uniqueMap(t,a);if(i)for(let f of ut(a,i))c.get(f.key)===o&&c.delete(f.key);for(let f of ut(a,n))c.set(f.key,o)}t.docs.set(o,n),t.written.set(o,this.now.getTime()),this.changes.push({kind:"document",db:t.db,collection:t.name,key:o,id:n._id,doc:n})}insertNew(t,n){let r=oe(n._id);if(t.docs.has(r))throw Zn(_(t.db,t.name),Yt,[n._id]);this.put(t,n)}remove(t,n){let r=t.docs.get(n);if(r){for(let o of t.indexes.values()){if(o.unique!==!0)continue;let i=this.uniqueMap(t,o);for(let s of ut(o,r))i.get(s.key)===n&&i.delete(s.key)}t.docs.delete(n),this.changes.push({kind:"document",db:t.db,collection:t.name,key:n,id:r._id,doc:null})}}async land(t,n){await fo(this.ctx.root,t,this.changes,this.ctx.now,n),this.changes=[]}};function Bt(e,t){return{_id:t,...Object.fromEntries(Object.entries(e).filter(([n])=>n!=="_id"))}}function Uo(e){if(Array.isArray(e))throw new m(53,"InvalidIdField","The '_id' value cannot be of type array");if(te(e))throw new m(53,"InvalidIdField","can't use a regex for _id");if(e===void 0)throw new m(53,"InvalidIdField","The '_id' value cannot be undefined")}function er(e,t){let n=Ht(t),{ok:r,codeName:o,...i}=n;return{index:e,...i}}function ht(e,t,n){let r=Xr(t);if(r&&n){let i=n.docs.get(oe(r.id)),s=q(t);return i&&e.includes(i)&&s(i)?[i]:[]}let o=q(t);return e.filter(i=>o(i))}function Jn(e){let t={};for(let[n,r]of Dn(e)){if(le(r))continue;let o=n.split("."),i=t;for(let s of o.slice(0,-1))y(i[s])||(i[s]={}),i=i[s];i[o[o.length-1]]=L(r)}return t}function Do(e,t){return(n,r)=>ft(n,r,{collection:o=>e.docs(e.get(t,o)),vars:{NOW:e.now}})}function Kn(e,t,n){let r="isMaster"in e||"ismaster"in e;return n.connection.id===0&&(n.server.nextConnection+=1,n.connection.id=n.server.nextConnection),{...e.helloOk===!0?{helloOk:!0}:{},[r?"ismaster":"isWritablePrimary"]:!0,maxBsonObjectSize:Kt,maxMessageSizeBytes:vn,maxWriteBatchSize:Jt,localTime:new Date(n.now),logicalSessionTimeoutMinutes:30,connectionId:n.connection.id,minWireVersion:0,maxWireVersion:Qn,readOnly:n.readOnly,ok:1}}function Oo(){return{version:Xn,gitVersion:"volter-twin",modules:[],allocator:"system",javascriptEngine:"none",sysInfo:"deprecated",versionArray:[7,0,0,0],openssl:{running:"disabled",compiled:"disabled"},buildEnvironment:{},bits:64,debug:!1,maxBsonObjectSize:Kt,storageEngines:["volter-world"],ok:1}}function jo(e,t){if(e!=="admin")throw new m(13,"Unauthorized",`${t} may only be run against the admin database.`)}var Gn={featureCompatibilityVersion:{version:"7.0"},maxBSONDepth:200,internalQueryMaxBlockingSortMemoryUsageBytes:104857600};function Ss(e,t){jo(t,"getParameter");let n={};(e.getParameter==="*"||y(e.getParameter)&&e.getParameter.allParameters===!0)&&Object.assign(n,Gn);for(let r of Object.keys(e))r!=="getParameter"&&!r.startsWith("$")&&r!=="lsid"&&r!=="comment"&&r in Gn&&(n[r]=Gn[r]);if(Object.keys(n).length===0)throw new m(72,"InvalidOptions","no option found to get");return{...n,ok:1}}function Ro(e){let t=0;for(let n of e.docs.values())t+=Mt.calculateObjectSize(n);return t}function Os(e,t,n){jo(t,"listDatabases");let r=fe(n.root),o=new Map;for(let a of r.collections.values())o.set(a.db,(o.get(a.db)??0)+Ro(a)+4096);let i=[...o.entries()].sort(([a],[c])=>a.localeCompare(c)).map(([a,c])=>({name:a,sizeOnDisk:c,empty:!1}));if(e.filter!==void 0){let a=q(e.filter);i=i.filter(c=>a(c))}if(e.nameOnly===!0)return{databases:i.map(a=>({name:a.name})),ok:1};let s=i.reduce((a,c)=>a+$(c.sizeOnDisk),0);return{databases:i,totalSize:s,totalSizeMb:Math.floor(s/(1024*1024)),ok:1}}function Es(e,t,n){let o=[...fe(n.root).collections.values()].filter(s=>s.db===t).map(s=>({name:s.name,type:"collection",options:{},info:{readOnly:!1,uuid:new M(Buffer.from(s.uuid,"hex"),M.SUBTYPE_UUID)},idIndex:{v:2,key:{_id:1},name:"_id_"}}));if(o.sort((s,a)=>String(s.name).localeCompare(String(a.name))),e.filter!==void 0){let s=q(e.filter);o=o.filter(a=>s(a))}e.nameOnly===!0&&(o=o.map(s=>({name:s.name,type:s.type})));let i=y(e.cursor)?e.cursor:{};return Zt(n,`${t}.$cmd.listCollections`,o,It(i))}var Ns=new Set(["create","$db","lsid","writeConcern","comment","$readPreference","$clusterTime","apiVersion","apiStrict","apiDeprecationErrors"]);async function Bs(e,t,n){let r=re(e,"create");for(let i of Object.keys(e))if(!Ns.has(i)&&!(i==="collation"&&y(e.collation)&&e.collation.locale==="simple"))throw Se(`create option '${i}'`);let o=new we(n);return o.get(t,r)?{ok:1}:(o.ensure(t,r),await o.land("create",{ns:_(t,r)}),{ok:1})}async function xs(e,t,n){let r=re(e,"drop"),o=new we(n),i=o.get(t,r);if(!i)return{ok:1};let s=i.indexes.size;return Co(o,i),await o.land("drop",{ns:_(t,r)}),{nIndexesWas:s,ns:_(t,r),ok:1}}function Co(e,t){for(let n of[...t.docs.keys()])e.remove(t,n);for(let n of t.indexes.values())n.name!=="_id_"&&e.changes.push({kind:"index",db:t.db,collection:t.name,spec:n,deleted:!0});e.changes.push({kind:"collection",db:t.db,name:t.name,uuid:t.uuid,deleted:!0}),e.image.collections.delete(_(t.db,t.name))}async function Is(e,t,n){let r=new we(n),o=[...r.image.collections.values()].filter(i=>i.db===t);for(let i of o)Co(r,i);return await r.land("dropDatabase",{db:t}),{dropped:t,ok:1}}async function As(e,t,n){let r=re(e,"insert"),o=e.documents;if(!Array.isArray(o))throw new m(40414,"Location40414","BSON field 'insert.documents' is missing but a required field");if(o.length>Jt)throw new m(16,"InvalidLength",`Write batch sizes must be between 1 and ${Jt}. Got ${o.length} operations.`);let i=e.ordered!==!1,s=new we(n),{coll:a}=s.ensure(t,r);s.purgeExpired(a);let c=[],f=0;for(let l=0;l<o.length;l++)try{let u=o[l];if(!y(u))throw new m(2,"BadValue","document to insert must be an object");let d=u._id===void 0?Bt(L(u),s.newId(a)):Bt(L(u),L(u._id));Uo(d._id),s.insertNew(a,d),f+=1}catch(u){if(c.push(er(l,u)),i)break}return await s.land("insert",{ns:_(t,r),n:f}),{n:f,...c.length?{writeErrors:c}:{},ok:1}}function gt(e,t){if(!(t===void 0||e===void 0)){if(typeof t=="string"){if(!e.indexes.has(t))throw new m(2,"BadValue","hint provided does not correspond to an existing index");return}if(y(t)){if(Object.keys(t).length===0)return;if("$natural"in t)return $(t.$natural)<0?-1:1;if(![...e.indexes.values()].some(n=>z(n.key,t)===0))throw new m(2,"BadValue","hint provided does not correspond to an existing index");return}throw new m(9,"FailedToParse","hint must be a string or an object")}}function Ts(e,t){let n=gt(e.coll,t.hint),r=ht(e.docs,t.filter,e.coll);n===-1&&t.sort===void 0&&(r=[...r].reverse()),r=ze(r,Ge(t.sort));let o=t.skip===void 0?0:$(t.skip);if(o<0)throw new m(51024,"Location51024",`BSON field 'skip' value must be >= 0, actual value '${o}'`);o&&(r=r.slice(o));let i=t.limit===void 0?0:Math.abs($(t.limit));if(i&&(r=r.slice(0,i)),t.projection!==void 0){let s=lt(t.projection,"find",{},y(t.filter)?t.filter:{});r=r.map(a=>s(a))}return r}function _s(e,t,n){let r=re(e,"find");if(e.tailable===!0)throw new m(2,"BadValue",`error processing query: ns=${_(t,r)} tailable cursor requested on non capped collection`);if(e.returnKey===!0||e.showRecordId===!0)throw Se(e.returnKey===!0?"find option returnKey":"find option showRecordId");if(e.min!==void 0||e.max!==void 0)throw Se("find options min/max");let i=fe(n.root).collections.get(_(t,r)),s=Ts({docs:dt(i,new Date(n.now)),coll:i},e),a=e.singleBatch===!0||F(e.limit)&&$(e.limit)<0,c=It(e)??Io;return Zt(n,_(t,r),s,a?void 0:c,a)}function Ls(e,t,n){let r=e.getMore,o=F(r)?w.isLong(r)?r.toString():String($(r)):String(r),i=re(e,"collection"),s=n.server.cursors.get(o);if(!s)throw new m(43,"CursorNotFound",`cursor id ${o} not found`);if(s.ns!==_(t,i)&&!s.ns.startsWith(`${t}.$cmd`))throw new m(13,"Unauthorized",`Requested getMore on namespace '${_(t,i)}', but cursor belongs to a different namespace ${s.ns}`);let{batch:a,rest:c}=Mo(s.docs,It(e));return c.length===0?n.server.cursors.delete(o):s.docs=c,{cursor:{nextBatch:a,id:c.length===0?w.ZERO:w.fromString(o),ns:s.ns},ok:1}}function Ms(e,t,n){re(e,"killCursors");let r=Array.isArray(e.cursors)?e.cursors:[],o=[],i=[];for(let s of r){let a=w.isLong(s)?s.toString():String($(s));n.server.cursors.delete(a)?o.push(s):i.push(s)}return{cursorsKilled:o,cursorsNotFound:i,cursorsAlive:[],cursorsUnknown:[],ok:1}}async function ks(e,t,n){let r=re(e,"update"),o=e.updates;if(!Array.isArray(o))throw new m(40414,"Location40414","BSON field 'update.updates' is missing but a required field");let i=e.ordered!==!1,s=new we(n),a=s.get(t,r);a&&s.purgeExpired(a);let c=[],f=[],l=0,u=0;for(let d=0;d<o.length;d++)try{let p=o[d];if(!y(p))throw new m(2,"BadValue","update statement must be an object");let b=Ds(s,t,r,p);l+=b.n,u+=b.nModified,b.upserted!==void 0&&f.push({index:d,_id:b.upserted})}catch(p){if(c.push(er(d,p)),i)break}return await s.land("update",{ns:_(t,r),n:l,nModified:u}),{n:l,nModified:u,...f.length?{upserted:f}:{},...c.length?{writeErrors:c}:{},ok:1}}function Us(e,t,n){return{now:e.now,query:n,...Array.isArray(t.arrayFilters)?{arrayFilters:t.arrayFilters}:{}}}function Fo(e,t,n,r,o){let i=Nt(r);if(i==="operators"){let a=L(n),c=Yn(a,r,o);return{doc:a,changed:c}}if(i==="replacement"){let a=bo(n,r);return{doc:a,changed:z(a,n)!==0}}let s=Hn(n,r,o,Do(e,t));return{doc:s,changed:z(s,n)!==0}}function Ds(e,t,n,r){let o=y(r.q)?r.q:{},i=r.u,s=Nt(i);if(s==="operators"&&Wn(i),s==="replacement"&&r.multi===!0)throw new m(9,"FailedToParse","multi update is not supported for replacement-style update");if(y(r.collation)&&r.collation.locale!=="simple")throw Se(`collation ${C(r.collation)}`);if(r.sort!==void 0)throw Se("update statement sort");let a=e.get(t,n);gt(a,r.hint);let c=Us(e,r,o),f=ht(e.docs(a),o,a),l=r.multi===!0?f:f.slice(0,1);if(l.length>0&&a){let p=0;for(let b of l){let{doc:B,changed:D}=Fo(e,t,b,i,c);D&&(e.put(a,B),p+=1)}return{n:l.length,nModified:p}}if(r.upsert!==!0)return{n:0,nModified:0};let u=Po(e,t,n,o,i,c),{coll:d}=e.ensure(t,n);return e.insertNew(d,u),{n:1,nModified:0,upserted:u._id}}function Po(e,t,n,r,o,i){let s=Nt(o),a;if(s==="replacement"){let c=Jn(r);a=L(o),a._id===void 0&&c._id!==void 0&&(a=Bt(a,c._id))}else s==="operators"?(a=Jn(r),Yn(a,o,{...i,inserting:!0})):a=Hn(Jn(r),o,i,Do(e,t));return a=a._id===void 0?Bt(a,e.newId(e.ensure(t,n).coll)):Bt(a,a._id),Uo(a._id),a}async function js(e,t,n){let r=re(e,"delete"),o=e.deletes;if(!Array.isArray(o))throw new m(40414,"Location40414","BSON field 'delete.deletes' is missing but a required field");let i=e.ordered!==!1,s=new we(n),a=s.get(t,r);a&&s.purgeExpired(a);let c=[],f=0;for(let l=0;l<o.length;l++)try{let u=o[l];if(!y(u))throw new m(2,"BadValue","delete statement must be an object");let d=$(u.limit??0);if(d!==0&&d!==1)throw new m(9,"FailedToParse",`The limit field in delete objects must be 0 or 1. Got ${d}`);if(y(u.collation)&&u.collation.locale!=="simple")throw Se(`collation ${C(u.collation)}`);if(!a)continue;gt(a,u.hint);let p=ht(s.docs(a),u.q??{},a);for(let b of d===1?p.slice(0,1):p)s.remove(a,oe(b._id)),f+=1}catch(u){if(c.push(er(l,u)),i)break}return await s.land("delete",{ns:_(t,r),n:f}),{n:f,...c.length?{writeErrors:c}:{},ok:1}}async function Eo(e,t,n){let r=re(e,Object.keys(e)[0]),o=e.remove===!0,i=e.update!==void 0;if(o&&i)throw new m(9,"FailedToParse","Cannot specify both an update and remove=true");if(!o&&!i)throw new m(9,"FailedToParse","Either an update or remove=true must be specified");if(o&&e.upsert===!0)throw new m(9,"FailedToParse","Cannot specify both upsert=true and remove=true");if(o&&e.new===!0)throw new m(9,"FailedToParse","Cannot specify both new=true and remove=true; 'remove' always returns the deleted document");let s=y(e.query)?e.query:{},a=e.fields??e.projection,c=a===void 0?U=>U:lt(a,"find",{},s),f=new we(n),l=f.get(t,r);gt(l,e.hint),l&&f.purgeExpired(l);let u=ht(f.docs(l),s,l);u=ze(u,Ge(e.sort));let d=u[0];if(o)return!d||!l?{lastErrorObject:{n:0},value:null,ok:1}:(f.remove(l,oe(d._id)),await f.land("findAndModify",{ns:_(t,r),remove:!0}),{lastErrorObject:{n:1},value:c(d),ok:1});let p=e.update;Nt(p)==="operators"&&Wn(p);let B={now:f.now,query:s,...Array.isArray(e.arrayFilters)?{arrayFilters:e.arrayFilters}:{}};if(d&&l){let{doc:U,changed:ie}=Fo(f,t,d,p,B);return ie&&f.put(l,U),await f.land("findAndModify",{ns:_(t,r)}),{lastErrorObject:{n:1,updatedExisting:!0},value:c(e.new===!0?U:d),ok:1}}if(e.upsert!==!0)return{lastErrorObject:{n:0,updatedExisting:!1},value:null,ok:1};let D=Po(f,t,r,s,p,B),{coll:G}=f.ensure(t,r);return f.insertNew(G,D),await f.land("findAndModify",{ns:_(t,r),upsert:!0}),{lastErrorObject:{n:1,updatedExisting:!1,upserted:D._id},value:e.new===!0?c(D):null,ok:1}}function Rs(e,t,n){let r=re(e,"count"),i=fe(n.root).collections.get(_(t,r));gt(i,e.hint);let s=ht(dt(i,new Date(n.now)),e.query??{},i),a=e.skip===void 0?0:$(e.skip);if(a<0)throw new m(51024,"Location51024",`BSON field 'skip' value must be >= 0, actual value '${a}'`);s=s.slice(a);let c=e.limit===void 0?0:Math.abs($(e.limit));return c&&(s=s.slice(0,c)),{n:s.length,ok:1}}function Cs(e,t,n){let r=re(e,"distinct");if(typeof e.key!="string")throw new m(40414,"Location40414","BSON field 'distinct.key' is missing but a required field");let i=fe(n.root).collections.get(_(t,r)),s=ht(dt(i,new Date(n.now)),e.query??{},i),a=[];for(let c of s)for(let f of K(c,e.key))for(let l of Array.isArray(f)?f:[f])l!==void 0&&(a.some(u=>H(l,u)&&l===null==(u===null))||a.push(l));return a.sort(z),{values:a,ok:1}}var Fs=new Set(["$out","$merge","$bucket","$bucketAuto","$geoNear","$graphLookup","$sample","$search","$searchMeta","$vectorSearch","$indexStats","$collStats","$currentOp","$listSessions","$listLocalSessions","$redact","$setWindowFields","$densify","$fill","$unionWith","$documents","$changeStream","$planCacheStats","$listSearchIndexes"]);function Ps(e,t,n){let r=io(e.pipeline);if(e.explain===!0)throw Se("aggregate explain");if(!y(e.cursor))throw new m(9,"FailedToParse","The 'cursor' option is required, except for aggregate with the explain argument");for(let f of r){let l=y(f)?Object.keys(f)[0]:void 0;if(l&&Fs.has(l))throw Se(`the ${l} aggregation stage`)}let o=fe(n.root),i=new Date(n.now),s,a;if(e.aggregate===1||F(e.aggregate)&&$(e.aggregate)===1)throw new m(73,"InvalidNamespace",`{aggregate: 1} is not valid for '${y(r[0])?Object.keys(r[0])[0]:"this pipeline"}'; a collection is required.`);{let f=re(e,"aggregate");a=_(t,f),s=dt(o.collections.get(a),i),gt(o.collections.get(a),e.hint)===-1&&(s=[...s].reverse())}let c=ft(s,r,{collection:f=>dt(o.collections.get(_(t,f)),i),vars:{NOW:i}});return Zt(n,a,c,It(e.cursor)??Io)}var zs=new Set(["text","hashed","2dsphere","2d"]),Vs=new Set(["key","name","unique","sparse","expireAfterSeconds","partialFilterExpression","background","v","hidden","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","collation","ns"]);function qs(e){if(!y(e))throw new m(2,"BadValue","index specification must be an object");let t=e.key;if(!y(t)||Object.keys(t).length===0)throw new m(67,"CannotCreateIndex","Index keys cannot be an empty field.");for(let[o,i]of Object.entries(t))if(!(F(i)&&$(i)!==0||typeof i=="string"&&zs.has(i)))throw new m(67,"CannotCreateIndex",`Values in the index key pattern can only be numbers or strings, and strings must be one of 2d, 2dsphere, hashed, text; found ${C(i)} for ${o}`);if(typeof e.name!="string"||e.name==="")throw new m(9,"FailedToParse","Error in specification { key: "+C(t)+" } :: caused by :: The 'name' field is a required property of an index specification");for(let o of Object.keys(e))if(!Vs.has(o))throw new m(197,"InvalidIndexSpecificationOption",`The field '${o}' is not valid for an index specification. Specification: ${C(e)}`);if(y(e.collation)&&e.collation.locale!=="simple")throw Se(`index collation ${C(e.collation)}`);let n={v:2,key:L(t),name:e.name};e.unique===!0&&(n.unique=!0),e.sparse===!0&&(n.sparse=!0);let r=o=>new m(67,"CannotCreateIndex",`Error in specification ${C(e)} :: caused by :: ${o}`);if(e.unique===!0&&Object.values(t).includes("hashed"))throw r("Currently hashed indexes cannot guarantee uniqueness. Use a regular index.");if(e.sparse===!0&&e.partialFilterExpression!==void 0)throw r('cannot mix "partialFilterExpression" and "sparse" options');if(e.expireAfterSeconds!==void 0){let o=e.expireAfterSeconds;if(!F(o)||!Number.isFinite($(o)))throw r("TTL index 'expireAfterSeconds' option must be numeric");if($(o)<0||$(o)>2147483647)throw r(`TTL index 'expireAfterSeconds' option must be within an acceptable range, try a lower number: ${$(o)}`);n.expireAfterSeconds=$(o)}if(e.partialFilterExpression!==void 0){if(!y(e.partialFilterExpression))throw r("'partialFilterExpression' option must be an object");zo(e.partialFilterExpression,r),q(e.partialFilterExpression),n.partialFilterExpression=L(e.partialFilterExpression)}e.hidden===!0&&(n.hidden=!0);for(let o of["weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion"])e[o]!==void 0&&(n[o]=L(e[o]));return n}function zo(e,t){for(let[n,r]of Object.entries(e)){if(n==="$and"||n==="$or"){if(!Array.isArray(r))throw t(`${n} must be an array`);for(let o of r)y(o)&&zo(o,t);continue}if(n.startsWith("$"))throw t(`Expression not supported in partial index: ${n}`);if(le(r)){for(let[o,i]of Object.entries(r))if(!(["$eq","$gt","$gte","$lt","$lte","$type","$in"].includes(o)||o==="$exists"&&i===!0))throw t(`Expression not supported in partial index: ${C({[n]:{[o]:i}})}`)}}}function No(e,t){let n=r=>{let{v:o,name:i,key:s,background:a,...c}=r;return c};return z(n(e),n(t))===0}async function Ws(e,t,n){let r=re(e,"createIndexes");if(!Array.isArray(e.indexes)||e.indexes.length===0)throw new m(2,"BadValue","Must specify at least one index to create");let o=e.indexes.map(qs),i=new we(n),{coll:s,created:a}=i.ensure(t,r),c=s.indexes.size,f=0;for(let l of o){let u=s.indexes.get(l.name),d=[...s.indexes.values()].find(p=>z(p.key,l.key)===0);if(u&&z(u.key,l.key)===0){if(!No(u,l))throw new m(86,"IndexKeySpecsConflict",`An existing index has the same name as the requested index. When index names are not specified, they are auto generated and can cause conflicts. Please refer to our documentation. Requested index: ${C(l)}, existing index: ${C(u)}`);continue}if(u)throw new m(86,"IndexKeySpecsConflict",`An existing index has the same name as the requested index. When index names are not specified, they are auto generated and can cause conflicts. Please refer to our documentation. Requested index: ${C(l)}, existing index: ${C(u)}`);if(d&&z(d.partialFilterExpression??null,l.partialFilterExpression??null)===0)throw No(d,l)?new m(85,"IndexOptionsConflict",`Index already exists with a different name: ${d.name}`):new m(85,"IndexOptionsConflict",`An equivalent index already exists with a different name and options. Requested index: ${C(l)}, existing index: ${C(d)}`);if(l.unique){let p=new Map;for(let b of i.docs(s))for(let B of ut(l,b)){if(p.has(B.key))throw Zn(_(t,r),l,B.values,"Index build failed: ");p.set(B.key,!0)}}s.indexes.set(l.name,l),i.changes.push({kind:"index",db:t,collection:r,spec:l}),f+=1}return await i.land("createIndexes",{ns:_(t,r),indexes:o.map(l=>l.name)}),{numIndexesBefore:c,numIndexesAfter:s.indexes.size,...f===0?{note:"all indexes already exist"}:{},createdCollectionAutomatically:a,ok:1}}function Ys(e,t,n){let r=re(e,"listIndexes"),o=fe(n.root).collections.get(_(t,r));if(!o)throw new m(26,"NamespaceNotFound",`ns does not exist: ${_(t,r)}`);let i=[...o.indexes.values()].map(a=>({...L(a)})),s=y(e.cursor)?e.cursor:{};return Zt(n,_(t,r),i,It(s))}async function Bo(e,t,n){let r="dropIndexes"in e?"dropIndexes":"deleteIndexes",o=re(e,r),i=new we(n),s=i.get(t,o);if(!s)throw new m(26,"NamespaceNotFound",`ns not found ${_(t,o)}`);let a=s.indexes.size,c=e.index,f;if(c==="*")f=[...s.indexes.values()].filter(l=>l.name!=="_id_");else if(typeof c=="string"||Array.isArray(c))f=(Array.isArray(c)?c.map(String):[c]).map(u=>{if(u==="_id_")throw new m(72,"InvalidOptions","cannot drop _id index");let d=s.indexes.get(u);if(!d)throw new m(27,"IndexNotFound",`index not found with name [${u}]`);return d});else if(y(c)){let l=[...s.indexes.values()].find(u=>z(u.key,c)===0);if(!l)throw new m(27,"IndexNotFound",`can't find index with key: ${C(c)}`);if(l.name==="_id_")throw new m(72,"InvalidOptions","cannot drop _id index");f=[l]}else throw new m(14,"TypeMismatch","BSON field 'dropIndexes.index' is the wrong type");for(let l of f)s.indexes.delete(l.name),i.changes.push({kind:"index",db:t,collection:o,spec:l,deleted:!0});return await i.land("dropIndexes",{ns:_(t,o),indexes:f.map(l=>l.name)}),{nIndexesWas:a,ok:1}}function Hs(e,t,n){let r=[...fe(n.root).collections.values()].filter(a=>a.db===t),o=r.reduce((a,c)=>a+c.docs.size,0),i=r.reduce((a,c)=>a+Ro(c),0),s=r.reduce((a,c)=>a+c.indexes.size,0);return{db:t,collections:r.length,views:0,objects:o,avgObjSize:o?i/o:0,dataSize:i,storageSize:i,indexes:s,indexSize:0,totalSize:i,scaleFactor:1,ok:1}}function Js(e,t,n){return n.server.nextSession+=1,{id:{id:ko(`session|${n.server.nextSession}`)},timeoutMinutes:30,ok:1}}var Vo={hello:Kn,isMaster:Kn,ismaster:Kn,ping:()=>({ok:1}),buildInfo:Oo,buildinfo:Oo,getParameter:Ss,listDatabases:Os,listCollections:Es,create:Bs,drop:xs,dropDatabase:Is,insert:As,find:_s,getMore:Ls,killCursors:Ms,update:ks,delete:js,findAndModify:Eo,findandmodify:Eo,count:Rs,distinct:Cs,aggregate:Ps,createIndexes:Ws,listIndexes:Ys,dropIndexes:Bo,deleteIndexes:Bo,dbStats:Hs,startSession:Js,endSessions:()=>({ok:1}),refreshSessions:()=>({ok:1}),killSessions:()=>({ok:1}),killAllSessions:()=>({ok:1}),connectionStatus:()=>({authInfo:{authenticatedUsers:[],authenticatedUserRoles:[]},ok:1}),whatsmyuri:(e,t,n)=>({you:n.connection.peer??"127.0.0.1:0",ok:1})};import{createTwinFetchFromHandler as Gs,statefulTwinManifest as Zs}from"../../engine/v2/volter_world-core.mjs";function qo(e={}){let t=e.server??xt();return Gs(n=>Gt({...n,server:t}),{...e.root!==void 0?{root:e.root}:{},...e.readOnly!==void 0?{readOnly:e.readOnly}:{},manifest:Zs({vendor:"mongodb",twinOf:"a standalone MongoDB 7.0 server (the wire protocol and its commands)",stores:"databases, collections, indexes and documents, one kernel subject each"}),stores:{collections:()=>[...fe(e.root).collections.values()].sort((n,r)=>_(n.db,n.name).localeCompare(_(r.db,r.name))).map(n=>({ns:_(n.db,n.name),db:n.db,name:n.name,documents:n.docs.size,indexes:X.serialize(v({list:[...n.indexes.values()]}),{relaxed:!1}).list})),documents:()=>Object.fromEntries([...fe(e.root).collections.values()].sort((n,r)=>_(n.db,n.name).localeCompare(_(r.db,r.name))).map(n=>[_(n.db,n.name),[...n.docs.values()].map(r=>v(r))]))},responseHeaders:{"content-type":"application/json"}})}import{observeResource as ra}from"../../engine/v2/volter_world-core.mjs";import{declareRateBudget as Xs,rateBudgetPath as ic,rateBudgetWeight as sc,RateBudget as ac}from"../../engine/v2/volter_world-core.mjs";import{RateBudgetError as fc}from"../../engine/v2/volter_world-core.mjs";var Qs="mongodb",vs=6e4,ea=60,ta=300,Wo={scan:4,list:2},na={windowMs:vs,ceiling:ea,defaultWeight:Wo.list,maxRetryAfterSeconds:ta,rules:[{match:"^find ",weight:Wo.scan}],reason:'MongoDB Atlas free clusters are limited to 100 operations per second (https://www.mongodb.com/docs/atlas/reference/free-shared-limitations/, live-fetched 2026-09-27, "Throughput"); a self-hosted mongod publishes no limit. A pull copies a whole deployment on explicit request, so this stays at the kernel fallback: 60 weighted units per minute; listings 2, a collection scan (find) 4.'};Xs(Qs,na);var oa=new Set(["admin","config","local"]);function ia(e,t,n){for(let r of e)ra(Ze,{type:r.type,id:r.id,fields:r.fields},{...t!==void 0?{root:t}:{},at:n})}function sa(e){return e&&typeof e=="object"&&"toString"in e&&e.sub_type!==void 0?e.toString("hex"):""}function aa(e,t){let n=[],r={databases:1,collections:0,indexes:0,documents:0};for(let o of t){r.collections+=1,n.push({type:"collection",id:Fn(e,o.name),fields:{db:e,name:o.name,uuid:o.uuid,deleted:!1}});for(let i of o.indexes)i.name!=="_id_"&&(r.indexes+=1,n.push({type:"index",id:Pn(e,o.name,String(i.name)),fields:{db:e,collection:o.name,name:i.name,spec:v(i),deleted:!1}}));for(let i of o.documents){r.documents+=1;let s=oe(i._id);n.push({type:"document",id:Wt(e,o.name,s),fields:{db:e,collection:o.name,key:s,document_id:v({_id:i._id})._id,document:v(i),deleted:!1}})}}return{resources:n,report:r}}async function ge(e,t){let n=await e({method:"POST",path:"/command",headers:{"content-type":"application/json"},body:X.stringify(v(t),{relaxed:!1})});if(n.status!==200)throw new Error(`mongodb command door answered ${n.status}: ${n.body.slice(0,200)}`);let r=ye(JSON.parse(n.body));if(r.ok!==1)throw new Error(`mongodb command ${Object.keys(t)[0]} failed: ${String(r.errmsg)} (code ${String(r.code)})`);return r}async function tr(e,t,n){let r=t.cursor,o=[...r.firstBatch??[]],i=r.id,s=String(r.ns).slice(n.length+1);for(;i&&String(i)!=="0";){let c=(await ge(e,{getMore:i,collection:s,$db:n})).cursor;o.push(...c.nextBatch??[]),i=c.id}return o}async function nr(e,t={}){let n=await ge(e,{listDatabases:1,nameOnly:!0,$db:"admin"}),r={databases:0,collections:0,indexes:0,documents:0},o=new Date().toISOString();for(let{name:i}of n.databases){if(oa.has(i))continue;let s=await tr(e,await ge(e,{listCollections:1,cursor:{},$db:i}),i),a=[];for(let l of s){let u=String(l.name),d=await tr(e,await ge(e,{listIndexes:u,cursor:{},$db:i}),i),p=await tr(e,await ge(e,{find:u,filter:{},$db:i}),i);a.push({name:u,uuid:sa(l.info?.uuid),indexes:d,documents:p})}let{resources:c,report:f}=aa(i,a);ia(c,t.root,o),r.databases+=1,r.collections+=f.collections,r.indexes+=f.indexes,r.documents+=f.documents}return r}function ca(e){let t=[];e.fields&&t.push({type:e.subject.type,id:e.subject.id,fields:e.fields});for(let n of e.projection?.updates??[])t.push({type:n.type,id:n.id,fields:n.fields});for(let n of e.projection?.creates??[])t.push({type:n.type,id:n.id,fields:n.fields});return t}async function rr(e,t){let n=ca(t),r=o=>o==="collection"?0:o==="index"?1:2;for(let o of[...n].sort((i,s)=>r(i.type)-r(s.type))){let i=o.fields,s=String(i.db);if(o.type==="collection")i.deleted===!0?await ge(e,{drop:String(i.name),$db:s}):(await ge(e,{listCollections:1,filter:{name:String(i.name)},nameOnly:!0,cursor:{},$db:s})).cursor.firstBatch.length===0&&await ge(e,{create:String(i.name),$db:s});else if(o.type==="index"){let a=ye(i.spec);i.deleted===!0?await ge(e,{dropIndexes:String(i.collection),index:a.name,$db:s}).catch(()=>{}):await ge(e,{createIndexes:String(i.collection),indexes:[a],$db:s})}else if(o.type==="document")if(i.deleted===!0){let a=ye({_id:i.document_id})._id;await ge(e,{delete:String(i.collection),deletes:[{q:{_id:a},limit:1}],$db:s})}else{let a=ye(i.document);await ge(e,{update:String(i.collection),updates:[{q:{_id:a._id},u:a,upsert:!0}],$db:s})}}return{externalId:t.subject.id}}import{registerPack as la}from"../../engine/v2/volter_world-core.mjs";var fa={vendor:"mongodb",transport:"raw-tcp",protocol:"2",archetype:"crud",bin:"world-mongodb",resources:["collection","index","document"],stateSystem:{perform:rr,refresh:nr},refresh:{onDemand:{atMost:"60s"}},shapeParity:"held",parityOrigin:"http://twin",roundTrip:{method:"POST",path:"/command",body:{insert:"round_trip",documents:[{body:"round trip"}],$db:"twin"}},specSource:"the MongoDB manual: the wire protocol (https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/), the database command reference (https://www.mongodb.com/docs/manual/reference/command/) as the capability denominator, the query/update/aggregation operator references, and the BSON comparison order; errors as MongoDB 7.0 answers them, driven through the unmodified mongodb@6.20 driver and mongoose@8.24.",description:`MongoDB twin \u2014 a standalone MongoDB 7.0 (wire version 21) over the World state kernel: OP_MSG and the OP_QUERY handshake on a loopback TCP listener; CRUD with cursors, the common query/update operators, upserts, findAndModify, count/distinct, an aggregation subset ($match $project $group $lookup $unwind $sort \u2026), indexes with unique enforcement (E11000) and TTL expiry. No transactions (the standalone server's own IllegalOperation), no auth; an unimplemented command answers "no such command" (59), an unimplemented option or stage CommandNotSupported (115).`,adoption:{pypi:[],sdks:[]},hostsNone:"RAW-PROTOCOL pack \u2014 there is no host to map. MongoDB clients speak the wire protocol over a raw TCP socket to whatever host the connection string names, which the injector (http/fetch patching) cannot see; a World reaches this twin through the connection string itself (MONGO_URI and its kin), which World-managed infrastructure injects.",endpointEnvNone:"no vendor base-URL variable: the application reads its own connection-string variable (MONGO_URI, MONGODB_URL, DATABASE_URL, \u2026), and World-managed infrastructure (`volter-world init` \u2192 `volter-world-infra`) injects that variable pointing at this twin's listener."};la(fa);export{qo as createTwinFetch};