@powerhousedao/workflow 6.2.3-dev.79 → 6.2.3-dev.81

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 (223) hide show
  1. package/dist/browser/{BlockSelector-DFX-DZHl.js → BlockSelector-DHVzUGjW.js} +3 -3
  2. package/dist/browser/BlockSelector-DHVzUGjW.js.map +1 -0
  3. package/dist/browser/{connection-Ci_pI3kD.js → connection-PaKXHYz9.js} +2 -2
  4. package/dist/browser/{connection-Ci_pI3kD.js.map → connection-PaKXHYz9.js.map} +1 -1
  5. package/dist/browser/{connection-form-BuW6qOAF.js → connection-form-D2qAEHsl.js} +33 -13
  6. package/dist/browser/connection-form-D2qAEHsl.js.map +1 -0
  7. package/dist/browser/{data-tree-BLn565V5.js → data-tree-BOuPR-2J.js} +2 -2
  8. package/dist/browser/{data-tree-BLn565V5.js.map → data-tree-BOuPR-2J.js.map} +1 -1
  9. package/dist/browser/document-models/connection/index.js +2 -2
  10. package/dist/browser/document-models/index.js +3 -3
  11. package/dist/browser/document-models/workflow/index.js +3 -3
  12. package/dist/browser/{document-models-B2IDRvBZ.js → document-models-DSK5cn8B.js} +6 -3
  13. package/dist/browser/{document-models-B2IDRvBZ.js.map → document-models-DSK5cn8B.js.map} +1 -1
  14. package/dist/browser/{editor-DBcq58Fr.js → editor--59WtNaj.js} +271 -87
  15. package/dist/browser/editor--59WtNaj.js.map +1 -0
  16. package/dist/browser/{editor-B1-_KRbr.js → editor-0XPrGeLT.js} +8 -8
  17. package/dist/browser/{editor-B1-_KRbr.js.map → editor-0XPrGeLT.js.map} +1 -1
  18. package/dist/browser/{editor-DPGuck1V.js → editor-BD-5ClkW.js} +10 -10
  19. package/dist/browser/editor-BD-5ClkW.js.map +1 -0
  20. package/dist/browser/editors/connection-editor/module.js +1 -1
  21. package/dist/browser/editors/runtime/index.js +1 -1
  22. package/dist/browser/editors/workflow-editor/module.js +1 -1
  23. package/dist/browser/editors/workflow-studio/module.js +1 -1
  24. package/dist/browser/index.js +5 -5
  25. package/dist/browser/{module-FuSfFXPT.js → module-DJz6oTX0.js} +56 -56
  26. package/dist/browser/module-DJz6oTX0.js.map +1 -0
  27. package/dist/browser/{module-DFCANOuI.js → module-eOpxJVIl.js} +48 -6
  28. package/dist/browser/module-eOpxJVIl.js.map +1 -0
  29. package/dist/{node/piece-auth-BS5CtQOG.mjs → browser/piece-auth-63iuNFTs.js} +11 -3
  30. package/dist/browser/piece-auth-63iuNFTs.js.map +1 -0
  31. package/dist/browser/reactor/index.js +2 -2
  32. package/dist/browser/{runtime-queries-C9SoXGm2.js → runtime-queries-LAcyniYz.js} +18 -7
  33. package/dist/browser/runtime-queries-LAcyniYz.js.map +1 -0
  34. package/dist/browser/{trigger-text-B2mo1fiB.js → trigger-text-Co-dn9x-.js} +25 -5
  35. package/dist/browser/trigger-text-Co-dn9x-.js.map +1 -0
  36. package/dist/browser/upgrade-manifests-CLYUPqBs.js +8 -0
  37. package/dist/browser/{upgrade-manifests-B62uqKVp.js.map → upgrade-manifests-CLYUPqBs.js.map} +1 -1
  38. package/dist/browser/{workflow-DjTleFFO.js → workflow-Cn1UP-eJ.js} +4 -3
  39. package/dist/browser/workflow-Cn1UP-eJ.js.map +1 -0
  40. package/dist/node/{BlockSelector-DosVPXzD.mjs → BlockSelector-D2UAnFpN.mjs} +3 -3
  41. package/dist/node/BlockSelector-D2UAnFpN.mjs.map +1 -0
  42. package/dist/node/{connection-i6ISRY0F.mjs → connection-BZxipUlb.mjs} +2 -2
  43. package/dist/node/{connection-i6ISRY0F.mjs.map → connection-BZxipUlb.mjs.map} +1 -1
  44. package/dist/node/{connection-form-Z-pLxxrT.mjs → connection-form-Btmejfyn.mjs} +33 -13
  45. package/dist/node/connection-form-Btmejfyn.mjs.map +1 -0
  46. package/dist/node/{data-tree-CqBvXMpm.mjs → data-tree-rZiK2Ev-.mjs} +2 -2
  47. package/dist/node/{data-tree-CqBvXMpm.mjs.map → data-tree-rZiK2Ev-.mjs.map} +1 -1
  48. package/dist/node/document-models/connection/index.mjs +2 -2
  49. package/dist/node/document-models/index.mjs +3 -3
  50. package/dist/node/document-models/workflow/index.mjs +3 -3
  51. package/dist/node/{editor-DF1FOgnC.mjs → editor-C_eWGGi8.mjs} +11 -11
  52. package/dist/node/editor-C_eWGGi8.mjs.map +1 -0
  53. package/dist/node/{editor-BIpWFiaF.mjs → editor-ChJMxbeM.mjs} +8 -8
  54. package/dist/node/{editor-BIpWFiaF.mjs.map → editor-ChJMxbeM.mjs.map} +1 -1
  55. package/dist/node/{editor-DM9cnkfv.mjs → editor-U6trS0QO.mjs} +271 -87
  56. package/dist/node/editor-U6trS0QO.mjs.map +1 -0
  57. package/dist/node/editors/connection-editor/module.mjs +1 -1
  58. package/dist/node/editors/runtime/index.mjs +1 -1
  59. package/dist/node/editors/workflow-editor/module.mjs +1 -1
  60. package/dist/node/editors/workflow-studio/module.mjs +1 -1
  61. package/dist/node/index.mjs +8 -5
  62. package/dist/node/index.mjs.map +1 -1
  63. package/dist/node/{module-weVJEMpP.mjs → module-BEEASith.mjs} +56 -56
  64. package/dist/node/module-BEEASith.mjs.map +1 -0
  65. package/dist/node/{module-DV3LLvxo.mjs → module-D9Zx5Zow.mjs} +47 -5
  66. package/dist/node/module-D9Zx5Zow.mjs.map +1 -0
  67. package/dist/{browser/piece-auth-BS5CtQOG.js → node/piece-auth-C0u0XTO8.mjs} +11 -3
  68. package/dist/node/piece-auth-C0u0XTO8.mjs.map +1 -0
  69. package/dist/node/pieces/ai/descriptor.json +788 -0
  70. package/dist/node/pieces/ai/index.mjs +401 -0
  71. package/dist/node/pieces/ai/package.json +9 -0
  72. package/dist/node/pieces/index.mjs +3 -0
  73. package/dist/node/pieces/index.mjs.map +1 -1
  74. package/dist/node/pieces/reactor/descriptor.json +37 -2
  75. package/dist/node/pieces/reactor/index.mjs +39 -250
  76. package/dist/node/pieces/reactor/package.json +2 -2
  77. package/dist/node/{runtime-queries-CJSpbsBq.mjs → runtime-queries-CmrHBPRw.mjs} +18 -7
  78. package/dist/node/runtime-queries-CmrHBPRw.mjs.map +1 -0
  79. package/dist/node/{trigger-text-BRqIHmRS.mjs → trigger-text-CAiRCG2X.mjs} +25 -5
  80. package/dist/node/trigger-text-CAiRCG2X.mjs.map +1 -0
  81. package/dist/node/upgrade-manifests-C4akaA_X.mjs +8 -0
  82. package/dist/node/{upgrade-manifests-CO9zzPnE.mjs.map → upgrade-manifests-C4akaA_X.mjs.map} +1 -1
  83. package/dist/node/{workflow-BS5m4jtr.mjs → workflow-DqF9VsBQ.mjs} +4 -3
  84. package/dist/node/workflow-DqF9VsBQ.mjs.map +1 -0
  85. package/dist/powerhouse.manifest.json +10 -2
  86. package/dist/style.css +1 -1
  87. package/dist/types/document-models/document-models.d.ts +1 -0
  88. package/dist/types/document-models/document-models.d.ts.map +1 -1
  89. package/dist/types/document-models/workflow/v1/actions.d.ts +1 -0
  90. package/dist/types/document-models/workflow/v1/actions.d.ts.map +1 -1
  91. package/dist/types/document-models/workflow/v1/gen/document-model.d.ts.map +1 -1
  92. package/dist/types/document-models/workflow/v1/gen/document-schema.d.ts +3 -0
  93. package/dist/types/document-models/workflow/v1/gen/document-schema.d.ts.map +1 -1
  94. package/dist/types/document-models/workflow/v1/gen/ph-factories.d.ts.map +1 -1
  95. package/dist/types/document-models/workflow/v1/gen/reducer.d.ts.map +1 -1
  96. package/dist/types/document-models/workflow/v1/gen/schema/types.d.ts +16 -0
  97. package/dist/types/document-models/workflow/v1/gen/schema/types.d.ts.map +1 -1
  98. package/dist/types/document-models/workflow/v1/gen/schema/zod.d.ts +3 -1
  99. package/dist/types/document-models/workflow/v1/gen/schema/zod.d.ts.map +1 -1
  100. package/dist/types/document-models/workflow/v1/gen/utils.d.ts.map +1 -1
  101. package/dist/types/document-models/workflow/v1/gen/workflow/actions.d.ts +6 -2
  102. package/dist/types/document-models/workflow/v1/gen/workflow/actions.d.ts.map +1 -1
  103. package/dist/types/document-models/workflow/v1/gen/workflow/creators.d.ts +3 -2
  104. package/dist/types/document-models/workflow/v1/gen/workflow/creators.d.ts.map +1 -1
  105. package/dist/types/document-models/workflow/v1/gen/workflow/operations.d.ts +2 -1
  106. package/dist/types/document-models/workflow/v1/gen/workflow/operations.d.ts.map +1 -1
  107. package/dist/types/document-models/workflow/v1/module.d.ts +1 -0
  108. package/dist/types/document-models/workflow/v1/module.d.ts.map +1 -1
  109. package/dist/types/document-models/workflow/v1/src/reducers/workflow.d.ts.map +1 -1
  110. package/dist/types/document-models/workflow/v1/tests/managed-by.test.d.ts +2 -0
  111. package/dist/types/document-models/workflow/v1/tests/managed-by.test.d.ts.map +1 -0
  112. package/dist/types/editors/connection-editor/connection-form.d.ts.map +1 -1
  113. package/dist/types/editors/connection-editor/piece-auth.d.ts +6 -1
  114. package/dist/types/editors/connection-editor/piece-auth.d.ts.map +1 -1
  115. package/dist/types/editors/shared/DocumentErrorBoundary.d.ts.map +1 -1
  116. package/dist/types/editors/workflow-editor/document/useWorkflowModel.d.ts.map +1 -1
  117. package/dist/types/editors/workflow-editor/editor.d.ts.map +1 -1
  118. package/dist/types/editors/workflow-editor/runtime-client.d.ts +3 -1
  119. package/dist/types/editors/workflow-editor/runtime-client.d.ts.map +1 -1
  120. package/dist/types/editors/workflow-editor/runtime-context.d.ts +1 -1
  121. package/dist/types/editors/workflow-editor/runtime-context.d.ts.map +1 -1
  122. package/dist/types/editors/workflow-editor/ui/PanelResizer.d.ts +12 -0
  123. package/dist/types/editors/workflow-editor/ui/PanelResizer.d.ts.map +1 -0
  124. package/dist/types/editors/workflow-editor/ui/PropertyForm.d.ts +1 -0
  125. package/dist/types/editors/workflow-editor/ui/PropertyForm.d.ts.map +1 -1
  126. package/dist/types/editors/workflow-editor/ui/PublishControls.d.ts +4 -0
  127. package/dist/types/editors/workflow-editor/ui/PublishControls.d.ts.map +1 -1
  128. package/dist/types/editors/workflow-editor/ui/StepPanel.d.ts.map +1 -1
  129. package/dist/types/editors/workflow-editor/ui/WorkflowEditorApp.d.ts.map +1 -1
  130. package/dist/types/editors/workflow-editor/ui/forms.d.ts +5 -0
  131. package/dist/types/editors/workflow-editor/ui/forms.d.ts.map +1 -1
  132. package/dist/types/editors/workflow-editor/ui/item-summary.test.d.ts +2 -0
  133. package/dist/types/editors/workflow-editor/ui/item-summary.test.d.ts.map +1 -0
  134. package/dist/types/editors/workflow-editor/ui/model.d.ts +6 -0
  135. package/dist/types/editors/workflow-editor/ui/model.d.ts.map +1 -1
  136. package/dist/types/editors/workflow-editor/ui/retry-policy.d.ts +8 -0
  137. package/dist/types/editors/workflow-editor/ui/retry-policy.d.ts.map +1 -0
  138. package/dist/types/editors/workflow-editor/ui/retry-policy.test.d.ts +2 -0
  139. package/dist/types/editors/workflow-editor/ui/retry-policy.test.d.ts.map +1 -0
  140. package/dist/types/pieces/ai/ai-actions.test.d.ts +2 -0
  141. package/dist/types/pieces/ai/ai-actions.test.d.ts.map +1 -0
  142. package/dist/types/pieces/ai/ai-documents.test.d.ts +2 -0
  143. package/dist/types/pieces/ai/ai-documents.test.d.ts.map +1 -0
  144. package/dist/types/pieces/ai/ai.test.d.ts +2 -0
  145. package/dist/types/pieces/ai/ai.test.d.ts.map +1 -0
  146. package/dist/types/pieces/ai/index.d.ts +7 -0
  147. package/dist/types/pieces/ai/index.d.ts.map +1 -0
  148. package/dist/types/pieces/ai/lib/action-schema.d.ts +11 -0
  149. package/dist/types/pieces/ai/lib/action-schema.d.ts.map +1 -0
  150. package/dist/types/pieces/ai/lib/actions/ask-ai.d.ts +38 -0
  151. package/dist/types/pieces/ai/lib/actions/ask-ai.d.ts.map +1 -0
  152. package/dist/types/pieces/ai/lib/actions/decide-on-documents.d.ts +45 -0
  153. package/dist/types/pieces/ai/lib/actions/decide-on-documents.d.ts.map +1 -0
  154. package/dist/types/pieces/ai/lib/actions/decide.d.ts +39 -0
  155. package/dist/types/pieces/ai/lib/actions/decide.d.ts.map +1 -0
  156. package/dist/types/pieces/ai/lib/actions/extract.d.ts +41 -0
  157. package/dist/types/pieces/ai/lib/actions/extract.d.ts.map +1 -0
  158. package/dist/types/pieces/ai/lib/actions/propose-actions.d.ts +55 -0
  159. package/dist/types/pieces/ai/lib/actions/propose-actions.d.ts.map +1 -0
  160. package/dist/types/pieces/ai/lib/actions/summarize.d.ts +38 -0
  161. package/dist/types/pieces/ai/lib/actions/summarize.d.ts.map +1 -0
  162. package/dist/types/pieces/ai/lib/auth.d.ts +16 -0
  163. package/dist/types/pieces/ai/lib/auth.d.ts.map +1 -0
  164. package/dist/types/pieces/ai/lib/decision-model.d.ts +17 -0
  165. package/dist/types/pieces/ai/lib/decision-model.d.ts.map +1 -0
  166. package/dist/types/pieces/ai/lib/documents.d.ts +11 -0
  167. package/dist/types/pieces/ai/lib/documents.d.ts.map +1 -0
  168. package/dist/types/pieces/ai/lib/model-list.d.ts +8 -0
  169. package/dist/types/pieces/ai/lib/model-list.d.ts.map +1 -0
  170. package/dist/types/pieces/ai/lib/models.d.ts +19 -0
  171. package/dist/types/pieces/ai/lib/models.d.ts.map +1 -0
  172. package/dist/types/pieces/ai/lib/props.d.ts +16 -0
  173. package/dist/types/pieces/ai/lib/props.d.ts.map +1 -0
  174. package/dist/types/pieces/ai/lib/providers.d.ts +9 -0
  175. package/dist/types/pieces/ai/lib/providers.d.ts.map +1 -0
  176. package/dist/types/pieces/ai/lib/questions.d.ts +7 -0
  177. package/dist/types/pieces/ai/lib/questions.d.ts.map +1 -0
  178. package/dist/types/pieces/index.d.ts.map +1 -1
  179. package/dist/types/pieces/reactor/index.d.ts.map +1 -1
  180. package/dist/types/pieces/reactor/lib/actions/document-create.d.ts +4 -2
  181. package/dist/types/pieces/reactor/lib/actions/document-create.d.ts.map +1 -1
  182. package/dist/types/pieces/reactor/lib/actions/document-dispatch.d.ts +4 -2
  183. package/dist/types/pieces/reactor/lib/actions/document-dispatch.d.ts.map +1 -1
  184. package/dist/types/pieces/reactor/lib/actions/document-find.d.ts +4 -2
  185. package/dist/types/pieces/reactor/lib/actions/document-find.d.ts.map +1 -1
  186. package/dist/types/pieces/reactor/lib/actions/document-get.d.ts +4 -2
  187. package/dist/types/pieces/reactor/lib/actions/document-get.d.ts.map +1 -1
  188. package/dist/types/pieces/reactor/lib/actions/document-schema.d.ts +4 -2
  189. package/dist/types/pieces/reactor/lib/actions/document-schema.d.ts.map +1 -1
  190. package/dist/types/pieces/reactor/lib/actions/document-types.d.ts +3 -1
  191. package/dist/types/pieces/reactor/lib/actions/document-types.d.ts.map +1 -1
  192. package/dist/types/pieces/reactor/lib/actions/index-query.d.ts +14 -0
  193. package/dist/types/pieces/reactor/lib/actions/index-query.d.ts.map +1 -0
  194. package/dist/types/pieces/reactor/lib/input-schema.d.ts.map +1 -1
  195. package/dist/types/pieces/reactor/lib/reactor.d.ts +12 -0
  196. package/dist/types/pieces/reactor/lib/reactor.d.ts.map +1 -1
  197. package/dist/types/pieces/reactor/lib/writes.d.ts +7 -0
  198. package/dist/types/pieces/reactor/lib/writes.d.ts.map +1 -0
  199. package/dist/types/scripts/ui-stack.d.ts +8 -2
  200. package/dist/types/scripts/ui-stack.d.ts.map +1 -1
  201. package/package.json +15 -8
  202. package/dist/browser/BlockSelector-DFX-DZHl.js.map +0 -1
  203. package/dist/browser/connection-form-BuW6qOAF.js.map +0 -1
  204. package/dist/browser/editor-DBcq58Fr.js.map +0 -1
  205. package/dist/browser/editor-DPGuck1V.js.map +0 -1
  206. package/dist/browser/module-DFCANOuI.js.map +0 -1
  207. package/dist/browser/module-FuSfFXPT.js.map +0 -1
  208. package/dist/browser/piece-auth-BS5CtQOG.js.map +0 -1
  209. package/dist/browser/runtime-queries-C9SoXGm2.js.map +0 -1
  210. package/dist/browser/trigger-text-B2mo1fiB.js.map +0 -1
  211. package/dist/browser/upgrade-manifests-B62uqKVp.js +0 -8
  212. package/dist/browser/workflow-DjTleFFO.js.map +0 -1
  213. package/dist/node/BlockSelector-DosVPXzD.mjs.map +0 -1
  214. package/dist/node/connection-form-Z-pLxxrT.mjs.map +0 -1
  215. package/dist/node/editor-DF1FOgnC.mjs.map +0 -1
  216. package/dist/node/editor-DM9cnkfv.mjs.map +0 -1
  217. package/dist/node/module-DV3LLvxo.mjs.map +0 -1
  218. package/dist/node/module-weVJEMpP.mjs.map +0 -1
  219. package/dist/node/piece-auth-BS5CtQOG.mjs.map +0 -1
  220. package/dist/node/runtime-queries-CJSpbsBq.mjs.map +0 -1
  221. package/dist/node/trigger-text-BRqIHmRS.mjs.map +0 -1
  222. package/dist/node/upgrade-manifests-CO9zzPnE.mjs +0 -8
  223. package/dist/node/workflow-BS5m4jtr.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"BlockSelector-DosVPXzD.mjs","names":["React","React","React","React","React","trim","Tabs"],"sources":["../../../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/queryObserver.js","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/infiniteQueryObserver.js","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/queriesObserver.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/IsRestoringProvider.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/suspense.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/useQueries.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/useBaseQuery.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/useQuery.js","../../../../node_modules/.pnpm/@tanstack+react-query@5.90.21_react@19.2.6/node_modules/@tanstack/react-query/build/modern/useInfiniteQuery.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js","../../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js","../../editors/shared/DocumentErrorBoundary.tsx","../../editors/shared/icons.tsx","../../editors/shared/controls.tsx","../../editors/shared/url-param.ts","../../editors/workflow-editor/runtime-persist.ts","../../editors/workflow-editor/ui/piece-source.ts","../../../reactor/dist/drive-container-types-CC0dU3AF.js","../../editors/workflow-editor/use-runtime-url.ts","../../editors/workflow-editor/runtime-context.tsx","../../editors/workflow-editor/ui/validation.ts","../../editors/workflow-editor/ui/design-time.tsx","../../editors/workflow-studio/components/run-format.ts","../../editors/workflow-editor/ui/block-meta.ts","../../editors/workflow-editor/ui/version-badge.tsx","../../editors/workflow-editor/ui/picker-placement.ts","../../editors/workflow-editor/ui/PickerPopover.tsx","../../editors/workflow-editor/ui/picker-recent.ts","../../editors/workflow-editor/ui/VirtualList.tsx","../../editors/workflow-editor/ui/BlockSelector.tsx"],"sourcesContent":["// src/queryObserver.ts\nimport { focusManager } from \"./focusManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { fetchState } from \"./query.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { pendingThenable } from \"./thenable.js\";\nimport {\n isServer,\n isValidTimeout,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n shallowEqualObjects,\n timeUntilStale\n} from \"./utils.js\";\nimport { timeoutManager } from \"./timeoutManager.js\";\nvar QueryObserver = class extends Subscribable {\n constructor(client, options) {\n super();\n this.options = options;\n this.#client = client;\n this.#selectError = null;\n this.#currentThenable = pendingThenable();\n this.bindMethods();\n this.setOptions(options);\n }\n #client;\n #currentQuery = void 0;\n #currentQueryInitialState = void 0;\n #currentResult = void 0;\n #currentResultState;\n #currentResultOptions;\n #currentThenable;\n #selectError;\n #selectFn;\n #selectResult;\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData;\n #staleTimeoutId;\n #refetchIntervalId;\n #currentRefetchInterval;\n #trackedProps = /* @__PURE__ */ new Set();\n bindMethods() {\n this.refetch = this.refetch.bind(this);\n }\n onSubscribe() {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this);\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch();\n } else {\n this.updateResult();\n }\n this.#updateTimers();\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.destroy();\n }\n }\n shouldFetchOnReconnect() {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect\n );\n }\n shouldFetchOnWindowFocus() {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus\n );\n }\n destroy() {\n this.listeners = /* @__PURE__ */ new Set();\n this.#clearStaleTimeout();\n this.#clearRefetchInterval();\n this.#currentQuery.removeObserver(this);\n }\n setOptions(options) {\n const prevOptions = this.options;\n const prevQuery = this.#currentQuery;\n this.options = this.#client.defaultQueryOptions(options);\n if (this.options.enabled !== void 0 && typeof this.options.enabled !== \"boolean\" && typeof this.options.enabled !== \"function\" && typeof resolveEnabled(this.options.enabled, this.#currentQuery) !== \"boolean\") {\n throw new Error(\n \"Expected enabled to be a boolean or a callback that returns a boolean\"\n );\n }\n this.#updateQuery();\n this.#currentQuery.setOptions(this.options);\n if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getQueryCache().notify({\n type: \"observerOptionsUpdated\",\n query: this.#currentQuery,\n observer: this\n });\n }\n const mounted = this.hasListeners();\n if (mounted && shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions\n )) {\n this.#executeFetch();\n }\n this.updateResult();\n if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {\n this.#updateStaleTimeout();\n }\n const nextRefetchInterval = this.#computeRefetchInterval();\n if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {\n this.#updateRefetchInterval(nextRefetchInterval);\n }\n }\n getOptimisticResult(options) {\n const query = this.#client.getQueryCache().build(this.#client, options);\n const result = this.createResult(query, options);\n if (shouldAssignObserverCurrentProperties(this, result)) {\n this.#currentResult = result;\n this.#currentResultOptions = this.options;\n this.#currentResultState = this.#currentQuery.state;\n }\n return result;\n }\n getCurrentResult() {\n return this.#currentResult;\n }\n trackResult(result, onPropTracked) {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key);\n onPropTracked?.(key);\n if (key === \"promise\") {\n this.trackProp(\"data\");\n if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === \"pending\") {\n this.#currentThenable.reject(\n new Error(\n \"experimental_prefetchInRender feature flag is not enabled\"\n )\n );\n }\n }\n return Reflect.get(target, key);\n }\n });\n }\n trackProp(key) {\n this.#trackedProps.add(key);\n }\n getCurrentQuery() {\n return this.#currentQuery;\n }\n refetch({ ...options } = {}) {\n return this.fetch({\n ...options\n });\n }\n fetchOptimistic(options) {\n const defaultedOptions = this.#client.defaultQueryOptions(options);\n const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);\n return query.fetch().then(() => this.createResult(query, defaultedOptions));\n }\n fetch(fetchOptions) {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true\n }).then(() => {\n this.updateResult();\n return this.#currentResult;\n });\n }\n #executeFetch(fetchOptions) {\n this.#updateQuery();\n let promise = this.#currentQuery.fetch(\n this.options,\n fetchOptions\n );\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop);\n }\n return promise;\n }\n #updateStaleTimeout() {\n this.#clearStaleTimeout();\n const staleTime = resolveStaleTime(\n this.options.staleTime,\n this.#currentQuery\n );\n if (isServer || this.#currentResult.isStale || !isValidTimeout(staleTime)) {\n return;\n }\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);\n const timeout = time + 1;\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult();\n }\n }, timeout);\n }\n #computeRefetchInterval() {\n return (typeof this.options.refetchInterval === \"function\" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;\n }\n #updateRefetchInterval(nextInterval) {\n this.#clearRefetchInterval();\n this.#currentRefetchInterval = nextInterval;\n if (isServer || resolveEnabled(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {\n return;\n }\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {\n this.#executeFetch();\n }\n }, this.#currentRefetchInterval);\n }\n #updateTimers() {\n this.#updateStaleTimeout();\n this.#updateRefetchInterval(this.#computeRefetchInterval());\n }\n #clearStaleTimeout() {\n if (this.#staleTimeoutId) {\n timeoutManager.clearTimeout(this.#staleTimeoutId);\n this.#staleTimeoutId = void 0;\n }\n }\n #clearRefetchInterval() {\n if (this.#refetchIntervalId) {\n timeoutManager.clearInterval(this.#refetchIntervalId);\n this.#refetchIntervalId = void 0;\n }\n }\n createResult(query, options) {\n const prevQuery = this.#currentQuery;\n const prevOptions = this.options;\n const prevResult = this.#currentResult;\n const prevResultState = this.#currentResultState;\n const prevResultOptions = this.#currentResultOptions;\n const queryChange = query !== prevQuery;\n const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;\n const { state } = query;\n let newState = { ...state };\n let isPlaceholderData = false;\n let data;\n if (options._optimisticResults) {\n const mounted = this.hasListeners();\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options);\n const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options)\n };\n }\n if (options._optimisticResults === \"isRestoring\") {\n newState.fetchStatus = \"idle\";\n }\n }\n let { error, errorUpdatedAt, status } = newState;\n data = newState.data;\n let skipSelect = false;\n if (options.placeholderData !== void 0 && data === void 0 && status === \"pending\") {\n let placeholderData;\n if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {\n placeholderData = prevResult.data;\n skipSelect = true;\n } else {\n placeholderData = typeof options.placeholderData === \"function\" ? options.placeholderData(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData\n ) : options.placeholderData;\n }\n if (placeholderData !== void 0) {\n status = \"success\";\n data = replaceData(\n prevResult?.data,\n placeholderData,\n options\n );\n isPlaceholderData = true;\n }\n }\n if (options.select && data !== void 0 && !skipSelect) {\n if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {\n data = this.#selectResult;\n } else {\n try {\n this.#selectFn = options.select;\n data = options.select(data);\n data = replaceData(prevResult?.data, data, options);\n this.#selectResult = data;\n this.#selectError = null;\n } catch (selectError) {\n this.#selectError = selectError;\n }\n }\n }\n if (this.#selectError) {\n error = this.#selectError;\n data = this.#selectResult;\n errorUpdatedAt = Date.now();\n status = \"error\";\n }\n const isFetching = newState.fetchStatus === \"fetching\";\n const isPending = status === \"pending\";\n const isError = status === \"error\";\n const isLoading = isPending && isFetching;\n const hasData = data !== void 0;\n const result = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === \"success\",\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,\n isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === \"paused\",\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n promise: this.#currentThenable,\n isEnabled: resolveEnabled(options.enabled, query) !== false\n };\n const nextResult = result;\n if (this.options.experimental_prefetchInRender) {\n const hasResultData = nextResult.data !== void 0;\n const isErrorWithoutData = nextResult.status === \"error\" && !hasResultData;\n const finalizeThenableIfPossible = (thenable) => {\n if (isErrorWithoutData) {\n thenable.reject(nextResult.error);\n } else if (hasResultData) {\n thenable.resolve(nextResult.data);\n }\n };\n const recreateThenable = () => {\n const pending = this.#currentThenable = nextResult.promise = pendingThenable();\n finalizeThenableIfPossible(pending);\n };\n const prevThenable = this.#currentThenable;\n switch (prevThenable.status) {\n case \"pending\":\n if (query.queryHash === prevQuery.queryHash) {\n finalizeThenableIfPossible(prevThenable);\n }\n break;\n case \"fulfilled\":\n if (isErrorWithoutData || nextResult.data !== prevThenable.value) {\n recreateThenable();\n }\n break;\n case \"rejected\":\n if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {\n recreateThenable();\n }\n break;\n }\n }\n return nextResult;\n }\n updateResult() {\n const prevResult = this.#currentResult;\n const nextResult = this.createResult(this.#currentQuery, this.options);\n this.#currentResultState = this.#currentQuery.state;\n this.#currentResultOptions = this.options;\n if (this.#currentResultState.data !== void 0) {\n this.#lastQueryWithDefinedData = this.#currentQuery;\n }\n if (shallowEqualObjects(nextResult, prevResult)) {\n return;\n }\n this.#currentResult = nextResult;\n const shouldNotifyListeners = () => {\n if (!prevResult) {\n return true;\n }\n const { notifyOnChangeProps } = this.options;\n const notifyOnChangePropsValue = typeof notifyOnChangeProps === \"function\" ? notifyOnChangeProps() : notifyOnChangeProps;\n if (notifyOnChangePropsValue === \"all\" || !notifyOnChangePropsValue && !this.#trackedProps.size) {\n return true;\n }\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps\n );\n if (this.options.throwOnError) {\n includedProps.add(\"error\");\n }\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key;\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey];\n return changed && includedProps.has(typedKey);\n });\n };\n this.#notify({ listeners: shouldNotifyListeners() });\n }\n #updateQuery() {\n const query = this.#client.getQueryCache().build(this.#client, this.options);\n if (query === this.#currentQuery) {\n return;\n }\n const prevQuery = this.#currentQuery;\n this.#currentQuery = query;\n this.#currentQueryInitialState = query.state;\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this);\n query.addObserver(this);\n }\n }\n onQueryUpdate() {\n this.updateResult();\n if (this.hasListeners()) {\n this.#updateTimers();\n }\n }\n #notify(notifyOptions) {\n notifyManager.batch(() => {\n if (notifyOptions.listeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult);\n });\n }\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: \"observerResultsUpdated\"\n });\n });\n }\n};\nfunction shouldLoadOnMount(query, options) {\n return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === \"error\" && options.retryOnMount === false);\n}\nfunction shouldFetchOnMount(query, options) {\n return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);\n}\nfunction shouldFetchOn(query, options, field) {\n if (resolveEnabled(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== \"static\") {\n const value = typeof field === \"function\" ? field(query) : field;\n return value === \"always\" || value !== false && isStale(query, options);\n }\n return false;\n}\nfunction shouldFetchOptionally(query, prevQuery, options, prevOptions) {\n return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== \"error\") && isStale(query, options);\n}\nfunction isStale(query, options) {\n return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));\n}\nfunction shouldAssignObserverCurrentProperties(observer, optimisticResult) {\n if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {\n return true;\n }\n return false;\n}\nexport {\n QueryObserver\n};\n//# sourceMappingURL=queryObserver.js.map","// src/infiniteQueryObserver.ts\nimport { QueryObserver } from \"./queryObserver.js\";\nimport {\n hasNextPage,\n hasPreviousPage,\n infiniteQueryBehavior\n} from \"./infiniteQueryBehavior.js\";\nvar InfiniteQueryObserver = class extends QueryObserver {\n constructor(client, options) {\n super(client, options);\n }\n bindMethods() {\n super.bindMethods();\n this.fetchNextPage = this.fetchNextPage.bind(this);\n this.fetchPreviousPage = this.fetchPreviousPage.bind(this);\n }\n setOptions(options) {\n super.setOptions({\n ...options,\n behavior: infiniteQueryBehavior()\n });\n }\n getOptimisticResult(options) {\n options.behavior = infiniteQueryBehavior();\n return super.getOptimisticResult(options);\n }\n fetchNextPage(options) {\n return this.fetch({\n ...options,\n meta: {\n fetchMore: { direction: \"forward\" }\n }\n });\n }\n fetchPreviousPage(options) {\n return this.fetch({\n ...options,\n meta: {\n fetchMore: { direction: \"backward\" }\n }\n });\n }\n createResult(query, options) {\n const { state } = query;\n const parentResult = super.createResult(query, options);\n const { isFetching, isRefetching, isError, isRefetchError } = parentResult;\n const fetchDirection = state.fetchMeta?.fetchMore?.direction;\n const isFetchNextPageError = isError && fetchDirection === \"forward\";\n const isFetchingNextPage = isFetching && fetchDirection === \"forward\";\n const isFetchPreviousPageError = isError && fetchDirection === \"backward\";\n const isFetchingPreviousPage = isFetching && fetchDirection === \"backward\";\n const result = {\n ...parentResult,\n fetchNextPage: this.fetchNextPage,\n fetchPreviousPage: this.fetchPreviousPage,\n hasNextPage: hasNextPage(options, state.data),\n hasPreviousPage: hasPreviousPage(options, state.data),\n isFetchNextPageError,\n isFetchingNextPage,\n isFetchPreviousPageError,\n isFetchingPreviousPage,\n isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,\n isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage\n };\n return result;\n }\n};\nexport {\n InfiniteQueryObserver\n};\n//# sourceMappingURL=infiniteQueryObserver.js.map","// src/queriesObserver.ts\nimport { notifyManager } from \"./notifyManager.js\";\nimport { QueryObserver } from \"./queryObserver.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { replaceEqualDeep, shallowEqualObjects } from \"./utils.js\";\nfunction difference(array1, array2) {\n const excludeSet = new Set(array2);\n return array1.filter((x) => !excludeSet.has(x));\n}\nfunction replaceAt(array, index, value) {\n const copy = array.slice(0);\n copy[index] = value;\n return copy;\n}\nvar QueriesObserver = class extends Subscribable {\n #client;\n #result;\n #queries;\n #options;\n #observers;\n #combinedResult;\n #lastCombine;\n #lastResult;\n #lastQueryHashes;\n #observerMatches = [];\n constructor(client, queries, options) {\n super();\n this.#client = client;\n this.#options = options;\n this.#queries = [];\n this.#observers = [];\n this.#result = [];\n this.setQueries(queries);\n }\n onSubscribe() {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result);\n });\n });\n }\n }\n onUnsubscribe() {\n if (!this.listeners.size) {\n this.destroy();\n }\n }\n destroy() {\n this.listeners = /* @__PURE__ */ new Set();\n this.#observers.forEach((observer) => {\n observer.destroy();\n });\n }\n setQueries(queries, options) {\n this.#queries = queries;\n this.#options = options;\n if (process.env.NODE_ENV !== \"production\") {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash\n );\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n \"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.\"\n );\n }\n }\n notifyManager.batch(() => {\n const prevObservers = this.#observers;\n const newObserverMatches = this.#findMatchingObservers(this.#queries);\n newObserverMatches.forEach(\n (match) => match.observer.setOptions(match.defaultedQueryOptions)\n );\n const newObservers = newObserverMatches.map((match) => match.observer);\n const newResult = newObservers.map(\n (observer) => observer.getCurrentResult()\n );\n const hasLengthChange = prevObservers.length !== newObservers.length;\n const hasIndexChange = newObservers.some(\n (observer, index) => observer !== prevObservers[index]\n );\n const hasStructuralChange = hasLengthChange || hasIndexChange;\n const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {\n const prev = this.#result[index];\n return !prev || !shallowEqualObjects(result, prev);\n });\n if (!hasStructuralChange && !hasResultChange) return;\n if (hasStructuralChange) {\n this.#observerMatches = newObserverMatches;\n this.#observers = newObservers;\n }\n this.#result = newResult;\n if (!this.hasListeners()) return;\n if (hasStructuralChange) {\n difference(prevObservers, newObservers).forEach((observer) => {\n observer.destroy();\n });\n difference(newObservers, prevObservers).forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result);\n });\n });\n }\n this.#notify();\n });\n }\n getCurrentResult() {\n return this.#result;\n }\n getQueries() {\n return this.#observers.map((observer) => observer.getCurrentQuery());\n }\n getObservers() {\n return this.#observers;\n }\n getOptimisticResult(queries, combine) {\n const matches = this.#findMatchingObservers(queries);\n const result = matches.map(\n (match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)\n );\n const queryHashes = matches.map(\n (match) => match.defaultedQueryOptions.queryHash\n );\n return [\n result,\n (r) => {\n return this.#combineResult(r ?? result, combine, queryHashes);\n },\n () => {\n return this.#trackResult(result, matches);\n }\n ];\n }\n #trackResult(result, matches) {\n return matches.map((match, index) => {\n const observerResult = result[index];\n return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {\n matches.forEach((m) => {\n m.observer.trackProp(accessedProp);\n });\n }) : observerResult;\n });\n }\n #combineResult(input, combine, queryHashes) {\n if (combine) {\n const lastHashes = this.#lastQueryHashes;\n const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));\n if (!this.#combinedResult || this.#result !== this.#lastResult || queryHashesChanged || combine !== this.#lastCombine) {\n this.#lastCombine = combine;\n this.#lastResult = this.#result;\n if (queryHashes !== void 0) {\n this.#lastQueryHashes = queryHashes;\n }\n this.#combinedResult = replaceEqualDeep(\n this.#combinedResult,\n combine(input)\n );\n }\n return this.#combinedResult;\n }\n return input;\n }\n #findMatchingObservers(queries) {\n const prevObserversMap = /* @__PURE__ */ new Map();\n this.#observers.forEach((observer) => {\n const key = observer.options.queryHash;\n if (!key) return;\n const previousObservers = prevObserversMap.get(key);\n if (previousObservers) {\n previousObservers.push(observer);\n } else {\n prevObserversMap.set(key, [observer]);\n }\n });\n const observers = [];\n queries.forEach((options) => {\n const defaultedOptions = this.#client.defaultQueryOptions(options);\n const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift();\n const observer = match ?? new QueryObserver(this.#client, defaultedOptions);\n observers.push({\n defaultedQueryOptions: defaultedOptions,\n observer\n });\n });\n return observers;\n }\n #onUpdate(observer, result) {\n const index = this.#observers.indexOf(observer);\n if (index !== -1) {\n this.#result = replaceAt(this.#result, index, result);\n this.#notify();\n }\n }\n #notify() {\n if (this.hasListeners()) {\n const previousResult = this.#combinedResult;\n const newTracked = this.#trackResult(this.#result, this.#observerMatches);\n const newResult = this.#combineResult(newTracked, this.#options?.combine);\n if (previousResult !== newResult) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(this.#result);\n });\n });\n }\n }\n }\n};\nexport {\n QueriesObserver\n};\n//# sourceMappingURL=queriesObserver.js.map","\"use client\";\n\n// src/QueryClientProvider.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nvar QueryClientContext = React.createContext(\n void 0\n);\nvar useQueryClient = (queryClient) => {\n const client = React.useContext(QueryClientContext);\n if (queryClient) {\n return queryClient;\n }\n if (!client) {\n throw new Error(\"No QueryClient set, use QueryClientProvider to set one\");\n }\n return client;\n};\nvar QueryClientProvider = ({\n client,\n children\n}) => {\n React.useEffect(() => {\n client.mount();\n return () => {\n client.unmount();\n };\n }, [client]);\n return /* @__PURE__ */ jsx(QueryClientContext.Provider, { value: client, children });\n};\nexport {\n QueryClientContext,\n QueryClientProvider,\n useQueryClient\n};\n//# sourceMappingURL=QueryClientProvider.js.map","\"use client\";\n\n// src/IsRestoringProvider.ts\nimport * as React from \"react\";\nvar IsRestoringContext = React.createContext(false);\nvar useIsRestoring = () => React.useContext(IsRestoringContext);\nvar IsRestoringProvider = IsRestoringContext.Provider;\nexport {\n IsRestoringProvider,\n useIsRestoring\n};\n//# sourceMappingURL=IsRestoringProvider.js.map","\"use client\";\n\n// src/QueryErrorResetBoundary.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nfunction createValue() {\n let isReset = false;\n return {\n clearReset: () => {\n isReset = false;\n },\n reset: () => {\n isReset = true;\n },\n isReset: () => {\n return isReset;\n }\n };\n}\nvar QueryErrorResetBoundaryContext = React.createContext(createValue());\nvar useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext);\nvar QueryErrorResetBoundary = ({\n children\n}) => {\n const [value] = React.useState(() => createValue());\n return /* @__PURE__ */ jsx(QueryErrorResetBoundaryContext.Provider, { value, children: typeof children === \"function\" ? children(value) : children });\n};\nexport {\n QueryErrorResetBoundary,\n useQueryErrorResetBoundary\n};\n//# sourceMappingURL=QueryErrorResetBoundary.js.map","\"use client\";\n\n// src/errorBoundaryUtils.ts\nimport * as React from \"react\";\nimport { shouldThrowError } from \"@tanstack/query-core\";\nvar ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {\n const throwOnError = query?.state.error && typeof options.throwOnError === \"function\" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;\n if (options.suspense || options.experimental_prefetchInRender || throwOnError) {\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false;\n }\n }\n};\nvar useClearResetErrorBoundary = (errorResetBoundary) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset();\n }, [errorResetBoundary]);\n};\nvar getHasError = ({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense\n}) => {\n return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));\n};\nexport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n};\n//# sourceMappingURL=errorBoundaryUtils.js.map","// src/suspense.ts\nvar defaultThrowOnError = (_error, query) => query.state.data === void 0;\nvar ensureSuspenseTimers = (defaultedOptions) => {\n if (defaultedOptions.suspense) {\n const MIN_SUSPENSE_TIME_MS = 1e3;\n const clamp = (value) => value === \"static\" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);\n const originalStaleTime = defaultedOptions.staleTime;\n defaultedOptions.staleTime = typeof originalStaleTime === \"function\" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);\n if (typeof defaultedOptions.gcTime === \"number\") {\n defaultedOptions.gcTime = Math.max(\n defaultedOptions.gcTime,\n MIN_SUSPENSE_TIME_MS\n );\n }\n }\n};\nvar willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;\nvar shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;\nvar fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {\n errorResetBoundary.clearReset();\n});\nexport {\n defaultThrowOnError,\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch\n};\n//# sourceMappingURL=suspense.js.map","\"use client\";\n\n// src/useQueries.ts\nimport * as React from \"react\";\nimport {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager\n} from \"@tanstack/query-core\";\nimport { useQueryClient } from \"./QueryClientProvider.js\";\nimport { useIsRestoring } from \"./IsRestoringProvider.js\";\nimport { useQueryErrorResetBoundary } from \"./QueryErrorResetBoundary.js\";\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n} from \"./errorBoundaryUtils.js\";\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend\n} from \"./suspense.js\";\nfunction useQueries({\n queries,\n ...options\n}, queryClient) {\n const client = useQueryClient(queryClient);\n const isRestoring = useIsRestoring();\n const errorResetBoundary = useQueryErrorResetBoundary();\n const defaultedQueries = React.useMemo(\n () => queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts\n );\n defaultedOptions._optimisticResults = isRestoring ? \"isRestoring\" : \"optimistic\";\n return defaultedOptions;\n }),\n [queries, client, isRestoring]\n );\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions);\n const query = client.getQueryCache().get(queryOptions.queryHash);\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query);\n });\n useClearResetErrorBoundary(errorResetBoundary);\n const [observer] = React.useState(\n () => new QueriesObserver(\n client,\n defaultedQueries,\n options\n )\n );\n const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(\n defaultedQueries,\n options.combine\n );\n const shouldSubscribe = !isRestoring && options.subscribed !== false;\n React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop,\n [observer, shouldSubscribe]\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult()\n );\n React.useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options\n );\n }, [defaultedQueries, options, observer]);\n const shouldAtLeastOneSuspend = optimisticResult.some(\n (result, index) => shouldSuspend(defaultedQueries[index], result)\n );\n const suspensePromises = shouldAtLeastOneSuspend ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index];\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts);\n return fetchOptimistic(opts, queryObserver, errorResetBoundary);\n }\n return [];\n }) : [];\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises);\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index];\n return query && getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense\n });\n }\n );\n if (firstSingleResultWhichShouldThrow?.error) {\n throw firstSingleResultWhichShouldThrow.error;\n }\n return getCombinedResult(trackResult());\n}\nexport {\n useQueries\n};\n//# sourceMappingURL=useQueries.js.map","\"use client\";\n\n// src/useBaseQuery.ts\nimport * as React from \"react\";\nimport { isServer, noop, notifyManager } from \"@tanstack/query-core\";\nimport { useQueryClient } from \"./QueryClientProvider.js\";\nimport { useQueryErrorResetBoundary } from \"./QueryErrorResetBoundary.js\";\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n} from \"./errorBoundaryUtils.js\";\nimport { useIsRestoring } from \"./IsRestoringProvider.js\";\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch\n} from \"./suspense.js\";\nfunction useBaseQuery(options, Observer, queryClient) {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof options !== \"object\" || Array.isArray(options)) {\n throw new Error(\n 'Bad argument type. Starting with v5, only the \"Object\" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'\n );\n }\n }\n const isRestoring = useIsRestoring();\n const errorResetBoundary = useQueryErrorResetBoundary();\n const client = useQueryClient(queryClient);\n const defaultedOptions = client.defaultQueryOptions(options);\n client.getDefaultOptions().queries?._experimental_beforeQuery?.(\n defaultedOptions\n );\n const query = client.getQueryCache().get(defaultedOptions.queryHash);\n if (process.env.NODE_ENV !== \"production\") {\n if (!defaultedOptions.queryFn) {\n console.error(\n `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`\n );\n }\n }\n defaultedOptions._optimisticResults = isRestoring ? \"isRestoring\" : \"optimistic\";\n ensureSuspenseTimers(defaultedOptions);\n ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);\n useClearResetErrorBoundary(errorResetBoundary);\n const isNewCacheEntry = !client.getQueryCache().get(defaultedOptions.queryHash);\n const [observer] = React.useState(\n () => new Observer(\n client,\n defaultedOptions\n )\n );\n const result = observer.getOptimisticResult(defaultedOptions);\n const shouldSubscribe = !isRestoring && options.subscribed !== false;\n React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;\n observer.updateResult();\n return unsubscribe;\n },\n [observer, shouldSubscribe]\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult()\n );\n React.useEffect(() => {\n observer.setOptions(defaultedOptions);\n }, [defaultedOptions, observer]);\n if (shouldSuspend(defaultedOptions, result)) {\n throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);\n }\n if (getHasError({\n result,\n errorResetBoundary,\n throwOnError: defaultedOptions.throwOnError,\n query,\n suspense: defaultedOptions.suspense\n })) {\n throw result.error;\n }\n ;\n client.getDefaultOptions().queries?._experimental_afterQuery?.(\n defaultedOptions,\n result\n );\n if (defaultedOptions.experimental_prefetchInRender && !isServer && willFetch(result, isRestoring)) {\n const promise = isNewCacheEntry ? (\n // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted\n fetchOptimistic(defaultedOptions, observer, errorResetBoundary)\n ) : (\n // subscribe to the \"cache promise\" so that we can finalize the currentThenable once data comes in\n query?.promise\n );\n promise?.catch(noop).finally(() => {\n observer.updateResult();\n });\n }\n return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;\n}\nexport {\n useBaseQuery\n};\n//# sourceMappingURL=useBaseQuery.js.map","\"use client\";\n\n// src/useQuery.ts\nimport { QueryObserver } from \"@tanstack/query-core\";\nimport { useBaseQuery } from \"./useBaseQuery.js\";\nfunction useQuery(options, queryClient) {\n return useBaseQuery(options, QueryObserver, queryClient);\n}\nexport {\n useQuery\n};\n//# sourceMappingURL=useQuery.js.map","\"use client\";\n\n// src/useInfiniteQuery.ts\nimport { InfiniteQueryObserver } from \"@tanstack/query-core\";\nimport { useBaseQuery } from \"./useBaseQuery.js\";\nfunction useInfiniteQuery(options, queryClient) {\n return useBaseQuery(\n options,\n InfiniteQueryObserver,\n queryClient\n );\n}\nexport {\n useInfiniteQuery\n};\n//# sourceMappingURL=useInfiniteQuery.js.map","/// <reference types=\"./object-utils.d.ts\" />\nexport function isEmpty(obj) {\n if (Array.isArray(obj) || isString(obj) || isBuffer(obj)) {\n return obj.length === 0;\n }\n else if (obj) {\n return Object.keys(obj).length === 0;\n }\n return false;\n}\nexport function isUndefined(obj) {\n return typeof obj === 'undefined' || obj === undefined;\n}\nexport function isString(obj) {\n return typeof obj === 'string';\n}\nexport function isNumber(obj) {\n return typeof obj === 'number';\n}\nexport function isBoolean(obj) {\n return typeof obj === 'boolean';\n}\nexport function isNull(obj) {\n return obj === null;\n}\nexport function isDate(obj) {\n return obj instanceof Date;\n}\nexport function isBigInt(obj) {\n return typeof obj === 'bigint';\n}\n// Don't change the returnd type to `obj is Buffer` to not create a\n// hard dependency to node.\nexport function isBuffer(obj) {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(obj);\n}\nexport function isFunction(obj) {\n return typeof obj === 'function';\n}\nexport function isObject(obj) {\n return typeof obj === 'object' && obj !== null;\n}\nexport function isArrayBufferOrView(obj) {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\nexport function isPlainObject(obj) {\n if (!isObject(obj) || getTag(obj) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(obj) === null) {\n return true;\n }\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto;\n}\nexport function getLast(arr) {\n return arr[arr.length - 1];\n}\nexport function freeze(obj) {\n return Object.freeze(obj);\n}\nexport function asArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return [arg];\n }\n}\nexport function asReadonlyArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return freeze([arg]);\n }\n}\nexport function isReadonlyArray(arg) {\n return Array.isArray(arg);\n}\nexport function noop(obj) {\n return obj;\n}\nexport function compare(obj1, obj2) {\n if (isReadonlyArray(obj1) && isReadonlyArray(obj2)) {\n return compareArrays(obj1, obj2);\n }\n else if (isObject(obj1) && isObject(obj2)) {\n return compareObjects(obj1, obj2);\n }\n return obj1 === obj2;\n}\nfunction compareArrays(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0; i < arr1.length; ++i) {\n if (!compare(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nfunction compareObjects(obj1, obj2) {\n if (isBuffer(obj1) && isBuffer(obj2)) {\n return compareBuffers(obj1, obj2);\n }\n else if (isDate(obj1) && isDate(obj2)) {\n return compareDates(obj1, obj2);\n }\n return compareGenericObjects(obj1, obj2);\n}\nfunction compareBuffers(buf1, buf2) {\n return Buffer.compare(buf1, buf2) === 0;\n}\nfunction compareDates(date1, date2) {\n return date1.getTime() === date2.getTime();\n}\nfunction compareGenericObjects(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (const key of keys1) {\n if (!compare(obj1[key], obj2[key])) {\n return false;\n }\n }\n return true;\n}\nconst toString = Object.prototype.toString;\nfunction getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return toString.call(value);\n}\n","/// <reference types=\"./identifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const IdentifierNode = freeze({\n is(node) {\n return node.kind === 'IdentifierNode';\n },\n create(name) {\n return freeze({\n kind: 'IdentifierNode',\n name,\n });\n },\n});\n","/// <reference types=\"./schemable-identifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const SchemableIdentifierNode = freeze({\n is(node) {\n return node.kind === 'SchemableIdentifierNode';\n },\n create(identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n identifier: IdentifierNode.create(identifier),\n });\n },\n createWithSchema(schema, identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n schema: IdentifierNode.create(schema),\n identifier: IdentifierNode.create(identifier),\n });\n },\n});\n","/// <reference types=\"./alias-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AliasNode = freeze({\n is(node) {\n return node.kind === 'AliasNode';\n },\n create(node, alias) {\n return freeze({\n kind: 'AliasNode',\n node,\n alias,\n });\n },\n});\n","/// <reference types=\"./table-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const TableNode = freeze({\n is(node) {\n return node.kind === 'TableNode';\n },\n create(table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.create(table),\n });\n },\n createWithSchema(schema, table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.createWithSchema(schema, table),\n });\n },\n});\n","/// <reference types=\"./operation-node-source.d.ts\" />\nimport { isFunction, isObject } from '../util/object-utils.js';\nexport function isOperationNodeSource(obj) {\n return isObject(obj) && isFunction(obj.toOperationNode);\n}\n","/// <reference types=\"./expression.d.ts\" />\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport function isExpression(obj) {\n return isObject(obj) && 'expressionType' in obj && isOperationNodeSource(obj);\n}\nexport function isAliasedExpression(obj) {\n return (isObject(obj) &&\n 'expression' in obj &&\n isString(obj.alias) &&\n isOperationNodeSource(obj));\n}\n","/// <reference types=\"./select-modifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectModifierNode = freeze({\n is(node) {\n return node.kind === 'SelectModifierNode';\n },\n create(modifier, of) {\n return freeze({\n kind: 'SelectModifierNode',\n modifier,\n of,\n });\n },\n createWithExpression(modifier) {\n return freeze({\n kind: 'SelectModifierNode',\n rawModifier: modifier,\n });\n },\n});\n","/// <reference types=\"./and-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AndNode = freeze({\n is(node) {\n return node.kind === 'AndNode';\n },\n create(left, right) {\n return freeze({\n kind: 'AndNode',\n left,\n right,\n });\n },\n});\n","/// <reference types=\"./or-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrNode = freeze({\n is(node) {\n return node.kind === 'OrNode';\n },\n create(left, right) {\n return freeze({\n kind: 'OrNode',\n left,\n right,\n });\n },\n});\n","/// <reference types=\"./on-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const OnNode = freeze({\n is(node) {\n return node.kind === 'OnNode';\n },\n create(filter) {\n return freeze({\n kind: 'OnNode',\n on: filter,\n });\n },\n cloneWithOperation(onNode, operator, operation) {\n return freeze({\n ...onNode,\n on: operator === 'And'\n ? AndNode.create(onNode.on, operation)\n : OrNode.create(onNode.on, operation),\n });\n },\n});\n","/// <reference types=\"./join-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { OnNode } from './on-node.js';\n/**\n * @internal\n */\nexport const JoinNode = freeze({\n is(node) {\n return node.kind === 'JoinNode';\n },\n create(joinType, table) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: undefined,\n });\n },\n createWithOn(joinType, table, on) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: OnNode.create(on),\n });\n },\n cloneWithOn(joinNode, operation) {\n return freeze({\n ...joinNode,\n on: joinNode.on\n ? OnNode.cloneWithOperation(joinNode.on, 'And', operation)\n : OnNode.create(operation),\n });\n },\n});\n","/// <reference types=\"./binary-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const BinaryOperationNode = freeze({\n is(node) {\n return node.kind === 'BinaryOperationNode';\n },\n create(leftOperand, operator, rightOperand) {\n return freeze({\n kind: 'BinaryOperationNode',\n leftOperand,\n operator,\n rightOperand,\n });\n },\n});\n","/// <reference types=\"./operator-node.d.ts\" />\nimport { freeze, isString } from '../util/object-utils.js';\nexport const COMPARISON_OPERATORS = [\n '=',\n '==',\n '!=',\n '<>',\n '>',\n '>=',\n '<',\n '<=',\n 'in',\n 'not in',\n 'is',\n 'is not',\n 'like',\n 'not like',\n 'match',\n 'ilike',\n 'not ilike',\n '@>',\n '<@',\n '^@',\n '&&',\n '?',\n '?&',\n '?|',\n '!<',\n '!>',\n '<=>',\n '!~',\n '~',\n '~*',\n '!~*',\n '@@',\n '@@@',\n '!!',\n '<->',\n 'regexp',\n 'is distinct from',\n 'is not distinct from',\n];\nexport const ARITHMETIC_OPERATORS = [\n '+',\n '-',\n '*',\n '/',\n '%',\n '^',\n '&',\n '|',\n '#',\n '<<',\n '>>',\n];\nexport const JSON_OPERATORS = ['->', '->>'];\nexport const BINARY_OPERATORS = [\n ...COMPARISON_OPERATORS,\n ...ARITHMETIC_OPERATORS,\n '&&',\n '||',\n];\nexport const UNARY_FILTER_OPERATORS = ['exists', 'not exists'];\nexport const UNARY_OPERATORS = ['not', '-', ...UNARY_FILTER_OPERATORS];\nexport const OPERATORS = [\n ...BINARY_OPERATORS,\n ...JSON_OPERATORS,\n ...UNARY_OPERATORS,\n 'between',\n 'between symmetric',\n];\n/**\n * @internal\n */\nexport const OperatorNode = freeze({\n is(node) {\n return node.kind === 'OperatorNode';\n },\n create(operator) {\n return freeze({\n kind: 'OperatorNode',\n operator,\n });\n },\n});\nexport function isOperator(op) {\n return isString(op) && OPERATORS.includes(op);\n}\nexport function isBinaryOperator(op) {\n return isString(op) && BINARY_OPERATORS.includes(op);\n}\nexport function isComparisonOperator(op) {\n return isString(op) && COMPARISON_OPERATORS.includes(op);\n}\nexport function isArithmeticOperator(op) {\n return isString(op) && ARITHMETIC_OPERATORS.includes(op);\n}\nexport function isJSONOperator(op) {\n return isString(op) && JSON_OPERATORS.includes(op);\n}\n","/// <reference types=\"./column-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const ColumnNode = freeze({\n is(node) {\n return node.kind === 'ColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ColumnNode',\n column: IdentifierNode.create(column),\n });\n },\n});\n","/// <reference types=\"./select-all-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectAllNode = freeze({\n is(node) {\n return node.kind === 'SelectAllNode';\n },\n create() {\n return freeze({\n kind: 'SelectAllNode',\n });\n },\n});\n","/// <reference types=\"./reference-node.d.ts\" />\nimport { SelectAllNode } from './select-all-node.js';\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReferenceNode = freeze({\n is(node) {\n return node.kind === 'ReferenceNode';\n },\n create(column, table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column,\n });\n },\n createSelectAll(table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column: SelectAllNode.create(),\n });\n },\n});\n","/// <reference types=\"./dynamic-reference-builder.d.ts\" />\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseSimpleReferenceExpression } from '../parser/reference-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicReferenceBuilder {\n #dynamicReference;\n get dynamicReference() {\n return this.#dynamicReference;\n }\n /**\n * @private\n *\n * This needs to be here just so that the typings work. Without this\n * the generated .d.ts file contains no reference to the type param R\n * which causes this type to be equal to DynamicReferenceBuilder with\n * any R.\n */\n get refType() {\n return undefined;\n }\n constructor(reference) {\n this.#dynamicReference = reference;\n }\n toOperationNode() {\n return parseSimpleReferenceExpression(this.#dynamicReference);\n }\n}\nexport function isDynamicReferenceBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.dynamicReference));\n}\n","/// <reference types=\"./order-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByItemNode = freeze({\n is(node) {\n return node.kind === 'OrderByItemNode';\n },\n create(orderBy, direction) {\n return freeze({\n kind: 'OrderByItemNode',\n orderBy,\n direction,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n","/// <reference types=\"./raw-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const RawNode = freeze({\n is(node) {\n return node.kind === 'RawNode';\n },\n create(sqlFragments, parameters) {\n return freeze({\n kind: 'RawNode',\n sqlFragments: freeze(sqlFragments),\n parameters: freeze(parameters),\n });\n },\n createWithSql(sql) {\n return RawNode.create([sql], []);\n },\n createWithChild(child) {\n return RawNode.create(['', ''], [child]);\n },\n createWithChildren(children) {\n return RawNode.create(new Array(children.length + 1).fill(''), children);\n },\n});\n","/// <reference types=\"./collate-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CollateNode = freeze({\n is(node) {\n return node.kind === 'CollateNode';\n },\n create(collation) {\n return freeze({\n kind: 'CollateNode',\n collation: IdentifierNode.create(collation),\n });\n },\n});\n","/// <reference types=\"./order-by-item-builder.d.ts\" />\nimport { CollateNode } from '../operation-node/collate-node.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OrderByItemBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds `desc` to the `order by` item.\n *\n * See {@link asc} for the opposite.\n */\n desc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('desc'),\n }),\n });\n }\n /**\n * Adds `asc` to the `order by` item.\n *\n * See {@link desc} for the opposite.\n */\n asc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('asc'),\n }),\n });\n }\n /**\n * Adds `nulls last` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsFirst} for the opposite.\n */\n nullsLast() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'last' }),\n });\n }\n /**\n * Adds `nulls first` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsLast} for the opposite.\n */\n nullsFirst() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'first' }),\n });\n }\n /**\n * Adds `collate <collationName>` to the `order by` item.\n */\n collate(collation) {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n collation: CollateNode.create(collation),\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n","/// <reference types=\"./log-once.d.ts\" />\nconst LOGGED_MESSAGES = new Set();\n/**\n * Use for system-level logging, such as deprecation messages.\n * Logs a message and ensures it won't be logged again.\n */\nexport function logOnce(message) {\n if (LOGGED_MESSAGES.has(message)) {\n return;\n }\n LOGGED_MESSAGES.add(message);\n console.log(message);\n}\n","/// <reference types=\"./order-by-parser.d.ts\" />\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { isExpression } from '../expression/expression.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { OrderByItemBuilder } from '../query-builder/order-by-item-builder.js';\nimport { logOnce } from '../util/log-once.js';\nimport { isExpressionOrFactory, parseExpression, } from './expression-parser.js';\nimport { parseStringReference, } from './reference-parser.js';\nexport function isOrderByDirection(thing) {\n return thing === 'asc' || thing === 'desc';\n}\nexport function parseOrderBy(args) {\n if (args.length === 2) {\n return [parseOrderByItem(args[0], args[1])];\n }\n if (args.length === 1) {\n const [orderBy] = args;\n if (Array.isArray(orderBy)) {\n logOnce('orderBy(array) is deprecated, use multiple orderBy calls instead.');\n return orderBy.map((item) => parseOrderByItem(item));\n }\n return [parseOrderByItem(orderBy)];\n }\n throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);\n}\nexport function parseOrderByItem(expr, modifiers) {\n const parsedRef = parseOrderByExpression(expr);\n if (OrderByItemNode.is(parsedRef)) {\n if (modifiers) {\n throw new Error('Cannot specify direction twice!');\n }\n return parsedRef;\n }\n return parseOrderByWithModifiers(parsedRef, modifiers);\n}\nfunction parseOrderByExpression(expr) {\n if (isExpressionOrFactory(expr)) {\n return parseExpression(expr);\n }\n if (isDynamicReferenceBuilder(expr)) {\n return expr.toOperationNode();\n }\n const [ref, direction] = expr.split(' ');\n if (direction) {\n logOnce(\"`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.\");\n return parseOrderByWithModifiers(parseStringReference(ref), direction);\n }\n return parseStringReference(expr);\n}\nfunction parseOrderByWithModifiers(expr, modifiers) {\n if (typeof modifiers === 'string') {\n if (!isOrderByDirection(modifiers)) {\n throw new Error(`Invalid order by direction: ${modifiers}`);\n }\n return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));\n }\n if (isExpression(modifiers)) {\n logOnce(\"`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.\");\n return OrderByItemNode.create(expr, modifiers.toOperationNode());\n }\n const node = OrderByItemNode.create(expr);\n if (!modifiers) {\n return node;\n }\n return modifiers(new OrderByItemBuilder({ node })).toOperationNode();\n}\n","/// <reference types=\"./json-reference-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONReferenceNode = freeze({\n is(node) {\n return node.kind === 'JSONReferenceNode';\n },\n create(reference, traversal) {\n return freeze({\n kind: 'JSONReferenceNode',\n reference,\n traversal,\n });\n },\n cloneWithTraversal(node, traversal) {\n return freeze({\n ...node,\n traversal,\n });\n },\n});\n","/// <reference types=\"./json-operator-chain-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONOperatorChainNode = freeze({\n is(node) {\n return node.kind === 'JSONOperatorChainNode';\n },\n create(operator) {\n return freeze({\n kind: 'JSONOperatorChainNode',\n operator,\n values: freeze([]),\n });\n },\n cloneWithValue(node, value) {\n return freeze({\n ...node,\n values: freeze([...node.values, value]),\n });\n },\n});\n","/// <reference types=\"./json-path-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathNode = freeze({\n is(node) {\n return node.kind === 'JSONPathNode';\n },\n create(inOperator) {\n return freeze({\n kind: 'JSONPathNode',\n inOperator,\n pathLegs: freeze([]),\n });\n },\n cloneWithLeg(jsonPathNode, pathLeg) {\n return freeze({\n ...jsonPathNode,\n pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]),\n });\n },\n});\n","/// <reference types=\"./reference-parser.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ReferenceNode } from '../operation-node/reference-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOrderByDirection, parseOrderBy, } from './order-by-parser.js';\nimport { OperatorNode, isJSONOperator, } from '../operation-node/operator-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nexport function parseSimpleReferenceExpression(exp) {\n if (isString(exp)) {\n return parseStringReference(exp);\n }\n return exp.toOperationNode();\n}\nexport function parseReferenceExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return arg.map((it) => parseReferenceExpression(it));\n }\n else {\n return [parseReferenceExpression(arg)];\n }\n}\nexport function parseReferenceExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return parseSimpleReferenceExpression(exp);\n}\nexport function parseJSONReference(ref, op) {\n const referenceNode = parseStringReference(ref);\n if (isJSONOperator(op)) {\n return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op)));\n }\n const opWithoutLastChar = op.slice(0, -1);\n if (isJSONOperator(opWithoutLastChar)) {\n return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar)));\n }\n throw new Error(`Invalid JSON operator: ${op}`);\n}\nexport function parseStringReference(ref) {\n const COLUMN_SEPARATOR = '.';\n if (!ref.includes(COLUMN_SEPARATOR)) {\n return ReferenceNode.create(ColumnNode.create(ref));\n }\n const parts = ref.split(COLUMN_SEPARATOR).map(trim);\n if (parts.length === 3) {\n return parseStringReferenceWithTableAndSchema(parts);\n }\n if (parts.length === 2) {\n return parseStringReferenceWithTable(parts);\n }\n throw new Error(`invalid column reference ${ref}`);\n}\nexport function parseAliasedStringReference(ref) {\n const ALIAS_SEPARATOR = ' as ';\n if (ref.includes(ALIAS_SEPARATOR)) {\n const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));\n }\n else {\n return parseStringReference(ref);\n }\n}\nexport function parseColumnName(column) {\n return ColumnNode.create(column);\n}\nexport function parseOrderedColumnName(column) {\n const ORDER_SEPARATOR = ' ';\n if (column.includes(ORDER_SEPARATOR)) {\n const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim);\n if (!isOrderByDirection(order)) {\n throw new Error(`invalid order direction \"${order}\" next to \"${columnName}\"`);\n }\n return parseOrderBy([columnName, order])[0];\n }\n else {\n return parseColumnName(column);\n }\n}\nfunction parseStringReferenceWithTableAndSchema(parts) {\n const [schema, table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));\n}\nfunction parseStringReferenceWithTable(parts) {\n const [table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));\n}\nfunction trim(str) {\n return str.trim();\n}\n","/// <reference types=\"./primitive-value-list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PrimitiveValueListNode = freeze({\n is(node) {\n return node.kind === 'PrimitiveValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'PrimitiveValueListNode',\n values: freeze([...values]),\n });\n },\n});\n","/// <reference types=\"./value-list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueListNode = freeze({\n is(node) {\n return node.kind === 'ValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'ValueListNode',\n values: freeze(values),\n });\n },\n});\n","/// <reference types=\"./value-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueNode = freeze({\n is(node) {\n return node.kind === 'ValueNode';\n },\n create(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n });\n },\n createImmediate(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n immediate: true,\n });\n },\n});\n","/// <reference types=\"./value-parser.d.ts\" />\nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { isBoolean, isNull, isNumber, isReadonlyArray, } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nexport function parseValueExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return parseValueExpressionList(arg);\n }\n return parseValueExpression(arg);\n}\nexport function parseValueExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return ValueNode.create(exp);\n}\nexport function isSafeImmediateValue(value) {\n return isNumber(value) || isBoolean(value) || isNull(value);\n}\nexport function parseSafeImmediateValue(value) {\n if (!isSafeImmediateValue(value)) {\n throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);\n }\n return ValueNode.createImmediate(value);\n}\nfunction parseValueExpressionList(arg) {\n if (arg.some(isExpressionOrFactory)) {\n return ValueListNode.create(arg.map((it) => parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(arg);\n}\n","/// <reference types=\"./parens-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ParensNode = freeze({\n is(node) {\n return node.kind === 'ParensNode';\n },\n create(node) {\n return freeze({\n kind: 'ParensNode',\n node,\n });\n },\n});\n","/// <reference types=\"./binary-operation-parser.d.ts\" />\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { isBoolean, isNull, isString, isUndefined, } from '../util/object-utils.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { OperatorNode, OPERATORS, } from '../operation-node/operator-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nimport { parseValueExpression, parseValueExpressionOrList, } from './value-parser.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { OrNode } from '../operation-node/or-node.js';\nexport function parseValueBinaryOperationOrExpression(args) {\n if (args.length === 3) {\n return parseValueBinaryOperation(args[0], args[1], args[2]);\n }\n else if (args.length === 1) {\n return parseValueExpression(args[0]);\n }\n throw new Error(`invalid arguments: ${JSON.stringify(args)}`);\n}\nexport function parseValueBinaryOperation(left, operator, right) {\n if (isIsOperator(operator) && needsIsOperator(right)) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right));\n }\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right));\n}\nexport function parseReferentialBinaryOperation(left, operator, right) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right));\n}\nexport function parseFilterObject(obj, combinator) {\n return parseFilterList(Object.entries(obj)\n .filter(([, v]) => !isUndefined(v))\n .map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? 'is' : '=', v)), combinator);\n}\nexport function parseFilterList(list, combinator, withParens = true) {\n const combine = combinator === 'and' ? AndNode.create : OrNode.create;\n if (list.length === 0) {\n return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create('='), ValueNode.createImmediate(combinator === 'and' ? 1 : 0));\n }\n let node = toOperationNode(list[0]);\n for (let i = 1; i < list.length; ++i) {\n node = combine(node, toOperationNode(list[i]));\n }\n if (list.length > 1 && withParens) {\n return ParensNode.create(node);\n }\n return node;\n}\nfunction isIsOperator(operator) {\n return operator === 'is' || operator === 'is not';\n}\nfunction needsIsOperator(value) {\n return isNull(value) || isBoolean(value);\n}\nfunction parseOperator(operator) {\n if (isString(operator) && OPERATORS.includes(operator)) {\n return OperatorNode.create(operator);\n }\n if (isOperationNodeSource(operator)) {\n return operator.toOperationNode();\n }\n throw new Error(`invalid operator ${JSON.stringify(operator)}`);\n}\nfunction toOperationNode(nodeOrSource) {\n return isOperationNodeSource(nodeOrSource)\n ? nodeOrSource.toOperationNode()\n : nodeOrSource;\n}\n","/// <reference types=\"./order-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByNode = freeze({\n is(node) {\n return node.kind === 'OrderByNode';\n },\n create(items) {\n return freeze({\n kind: 'OrderByNode',\n items: freeze([...items]),\n });\n },\n cloneWithItems(orderBy, items) {\n return freeze({\n ...orderBy,\n items: freeze([...orderBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./partition-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByNode = freeze({\n is(node) {\n return node.kind === 'PartitionByNode';\n },\n create(items) {\n return freeze({\n kind: 'PartitionByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(partitionBy, items) {\n return freeze({\n ...partitionBy,\n items: freeze([...partitionBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./over-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { OrderByNode } from './order-by-node.js';\nimport { PartitionByNode } from './partition-by-node.js';\n/**\n * @internal\n */\nexport const OverNode = freeze({\n is(node) {\n return node.kind === 'OverNode';\n },\n create() {\n return freeze({\n kind: 'OverNode',\n });\n },\n cloneWithOrderByItems(overNode, items) {\n return freeze({\n ...overNode,\n orderBy: overNode.orderBy\n ? OrderByNode.cloneWithItems(overNode.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithPartitionByItems(overNode, items) {\n return freeze({\n ...overNode,\n partitionBy: overNode.partitionBy\n ? PartitionByNode.cloneWithItems(overNode.partitionBy, items)\n : PartitionByNode.create(items),\n });\n },\n});\n","/// <reference types=\"./from-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FromNode = freeze({\n is(node) {\n return node.kind === 'FromNode';\n },\n create(froms) {\n return freeze({\n kind: 'FromNode',\n froms: freeze(froms),\n });\n },\n cloneWithFroms(from, froms) {\n return freeze({\n ...from,\n froms: freeze([...from.froms, ...froms]),\n });\n },\n});\n","/// <reference types=\"./group-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByNode = freeze({\n is(node) {\n return node.kind === 'GroupByNode';\n },\n create(items) {\n return freeze({\n kind: 'GroupByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(groupBy, items) {\n return freeze({\n ...groupBy,\n items: freeze([...groupBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./having-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const HavingNode = freeze({\n is(node) {\n return node.kind === 'HavingNode';\n },\n create(filter) {\n return freeze({\n kind: 'HavingNode',\n having: filter,\n });\n },\n cloneWithOperation(havingNode, operator, operation) {\n return freeze({\n ...havingNode,\n having: operator === 'And'\n ? AndNode.create(havingNode.having, operation)\n : OrNode.create(havingNode.having, operation),\n });\n },\n});\n","/// <reference types=\"./insert-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const InsertQueryNode = freeze({\n is(node) {\n return node.kind === 'InsertQueryNode';\n },\n create(into, withNode, replace) {\n return freeze({\n kind: 'InsertQueryNode',\n into,\n ...(withNode && { with: withNode }),\n replace,\n });\n },\n createWithoutInto() {\n return freeze({\n kind: 'InsertQueryNode',\n });\n },\n cloneWith(insertQuery, props) {\n return freeze({\n ...insertQuery,\n ...props,\n });\n },\n});\n","/// <reference types=\"./list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ListNode = freeze({\n is(node) {\n return node.kind === 'ListNode';\n },\n create(items) {\n return freeze({\n kind: 'ListNode',\n items: freeze(items),\n });\n },\n});\n","/// <reference types=\"./update-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { ListNode } from './list-node.js';\n/**\n * @internal\n */\nexport const UpdateQueryNode = freeze({\n is(node) {\n return node.kind === 'UpdateQueryNode';\n },\n create(tables, withNode) {\n return freeze({\n kind: 'UpdateQueryNode',\n // For backwards compatibility, use the raw table node when there's only one table\n // and don't rename the property to something like `tables`.\n table: tables.length === 1 ? tables[0] : ListNode.create(tables),\n ...(withNode && { with: withNode }),\n });\n },\n createWithoutTable() {\n return freeze({\n kind: 'UpdateQueryNode',\n });\n },\n cloneWithFromItems(updateQuery, fromItems) {\n return freeze({\n ...updateQuery,\n from: updateQuery.from\n ? FromNode.cloneWithFroms(updateQuery.from, fromItems)\n : FromNode.create(fromItems),\n });\n },\n cloneWithUpdates(updateQuery, updates) {\n return freeze({\n ...updateQuery,\n updates: updateQuery.updates\n ? freeze([...updateQuery.updates, ...updates])\n : updates,\n });\n },\n cloneWithLimit(updateQuery, limit) {\n return freeze({\n ...updateQuery,\n limit,\n });\n },\n});\n","/// <reference types=\"./using-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UsingNode = freeze({\n is(node) {\n return node.kind === 'UsingNode';\n },\n create(tables) {\n return freeze({\n kind: 'UsingNode',\n tables: freeze(tables),\n });\n },\n cloneWithTables(using, tables) {\n return freeze({\n ...using,\n tables: freeze([...using.tables, ...tables]),\n });\n },\n});\n","/// <reference types=\"./delete-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { UsingNode } from './using-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const DeleteQueryNode = freeze({\n is(node) {\n return node.kind === 'DeleteQueryNode';\n },\n create(fromItems, withNode) {\n return freeze({\n kind: 'DeleteQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithLimit(deleteNode, limit) {\n return freeze({\n ...deleteNode,\n limit,\n });\n },\n cloneWithoutLimit(deleteNode) {\n return freeze({\n ...deleteNode,\n limit: undefined,\n });\n },\n cloneWithUsing(deleteNode, tables) {\n return freeze({\n ...deleteNode,\n using: deleteNode.using !== undefined\n ? UsingNode.cloneWithTables(deleteNode.using, tables)\n : UsingNode.create(tables),\n });\n },\n});\n","/// <reference types=\"./where-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const WhereNode = freeze({\n is(node) {\n return node.kind === 'WhereNode';\n },\n create(filter) {\n return freeze({\n kind: 'WhereNode',\n where: filter,\n });\n },\n cloneWithOperation(whereNode, operator, operation) {\n return freeze({\n ...whereNode,\n where: operator === 'And'\n ? AndNode.create(whereNode.where, operation)\n : OrNode.create(whereNode.where, operation),\n });\n },\n});\n","/// <reference types=\"./returning-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReturningNode = freeze({\n is(node) {\n return node.kind === 'ReturningNode';\n },\n create(selections) {\n return freeze({\n kind: 'ReturningNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(returning, selections) {\n return freeze({\n ...returning,\n selections: returning.selections\n ? freeze([...returning.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n","/// <reference types=\"./explain-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ExplainNode = freeze({\n is(node) {\n return node.kind === 'ExplainNode';\n },\n create(format, options) {\n return freeze({\n kind: 'ExplainNode',\n format,\n options,\n });\n },\n});\n","/// <reference types=\"./when-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WhenNode = freeze({\n is(node) {\n return node.kind === 'WhenNode';\n },\n create(condition) {\n return freeze({\n kind: 'WhenNode',\n condition,\n });\n },\n cloneWithResult(whenNode, result) {\n return freeze({\n ...whenNode,\n result,\n });\n },\n});\n","/// <reference types=\"./merge-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const MergeQueryNode = freeze({\n is(node) {\n return node.kind === 'MergeQueryNode';\n },\n create(into, withNode) {\n return freeze({\n kind: 'MergeQueryNode',\n into,\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithUsing(mergeNode, using) {\n return freeze({\n ...mergeNode,\n using,\n });\n },\n cloneWithWhen(mergeNode, when) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([...mergeNode.whens, when])\n : freeze([when]),\n });\n },\n cloneWithThen(mergeNode, then) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([\n ...mergeNode.whens.slice(0, -1),\n WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then),\n ])\n : undefined,\n });\n },\n});\n","/// <reference types=\"./output-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OutputNode = freeze({\n is(node) {\n return node.kind === 'OutputNode';\n },\n create(selections) {\n return freeze({\n kind: 'OutputNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(output, selections) {\n return freeze({\n ...output,\n selections: output.selections\n ? freeze([...output.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n","/// <reference types=\"./query-node.d.ts\" />\nimport { InsertQueryNode } from './insert-query-node.js';\nimport { SelectQueryNode } from './select-query-node.js';\nimport { UpdateQueryNode } from './update-query-node.js';\nimport { DeleteQueryNode } from './delete-query-node.js';\nimport { WhereNode } from './where-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { ReturningNode } from './returning-node.js';\nimport { ExplainNode } from './explain-node.js';\nimport { MergeQueryNode } from './merge-query-node.js';\nimport { OutputNode } from './output-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const QueryNode = freeze({\n is(node) {\n return (SelectQueryNode.is(node) ||\n InsertQueryNode.is(node) ||\n UpdateQueryNode.is(node) ||\n DeleteQueryNode.is(node) ||\n MergeQueryNode.is(node));\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithWhere(node, operation) {\n return freeze({\n ...node,\n where: node.where\n ? WhereNode.cloneWithOperation(node.where, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithJoin(node, join) {\n return freeze({\n ...node,\n joins: node.joins ? freeze([...node.joins, join]) : freeze([join]),\n });\n },\n cloneWithReturning(node, selections) {\n return freeze({\n ...node,\n returning: node.returning\n ? ReturningNode.cloneWithSelections(node.returning, selections)\n : ReturningNode.create(selections),\n });\n },\n cloneWithoutReturning(node) {\n return freeze({\n ...node,\n returning: undefined,\n });\n },\n cloneWithoutWhere(node) {\n return freeze({\n ...node,\n where: undefined,\n });\n },\n cloneWithExplain(node, format, options) {\n return freeze({\n ...node,\n explain: ExplainNode.create(format, options?.toOperationNode()),\n });\n },\n cloneWithTop(node, top) {\n return freeze({\n ...node,\n top,\n });\n },\n cloneWithOutput(node, selections) {\n return freeze({\n ...node,\n output: node.output\n ? OutputNode.cloneWithSelections(node.output, selections)\n : OutputNode.create(selections),\n });\n },\n cloneWithOrderByItems(node, items) {\n return freeze({\n ...node,\n orderBy: node.orderBy\n ? OrderByNode.cloneWithItems(node.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithoutOrderBy(node) {\n return freeze({\n ...node,\n orderBy: undefined,\n });\n },\n});\n","/// <reference types=\"./select-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { GroupByNode } from './group-by-node.js';\nimport { HavingNode } from './having-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const SelectQueryNode = freeze({\n is(node) {\n return node.kind === 'SelectQueryNode';\n },\n create(withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n ...(withNode && { with: withNode }),\n });\n },\n createFrom(fromItems, withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithSelections(select, selections) {\n return freeze({\n ...select,\n selections: select.selections\n ? freeze([...select.selections, ...selections])\n : freeze(selections),\n });\n },\n cloneWithDistinctOn(select, expressions) {\n return freeze({\n ...select,\n distinctOn: select.distinctOn\n ? freeze([...select.distinctOn, ...expressions])\n : freeze(expressions),\n });\n },\n cloneWithFrontModifier(select, modifier) {\n return freeze({\n ...select,\n frontModifiers: select.frontModifiers\n ? freeze([...select.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n cloneWithGroupByItems(selectNode, items) {\n return freeze({\n ...selectNode,\n groupBy: selectNode.groupBy\n ? GroupByNode.cloneWithItems(selectNode.groupBy, items)\n : GroupByNode.create(items),\n });\n },\n cloneWithLimit(selectNode, limit) {\n return freeze({\n ...selectNode,\n limit,\n });\n },\n cloneWithOffset(selectNode, offset) {\n return freeze({\n ...selectNode,\n offset,\n });\n },\n cloneWithFetch(selectNode, fetch) {\n return freeze({\n ...selectNode,\n fetch,\n });\n },\n cloneWithHaving(selectNode, operation) {\n return freeze({\n ...selectNode,\n having: selectNode.having\n ? HavingNode.cloneWithOperation(selectNode.having, 'And', operation)\n : HavingNode.create(operation),\n });\n },\n cloneWithSetOperations(selectNode, setOperations) {\n return freeze({\n ...selectNode,\n setOperations: selectNode.setOperations\n ? freeze([...selectNode.setOperations, ...setOperations])\n : freeze([...setOperations]),\n });\n },\n cloneWithoutSelections(select) {\n return freeze({\n ...select,\n selections: [],\n });\n },\n cloneWithoutLimit(select) {\n return freeze({\n ...select,\n limit: undefined,\n });\n },\n cloneWithoutOffset(select) {\n return freeze({\n ...select,\n offset: undefined,\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithoutGroupBy(select) {\n return freeze({\n ...select,\n groupBy: undefined,\n });\n },\n});\n","/// <reference types=\"./join-builder.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class JoinBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n on(...args) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Just like {@link WhereInterface.whereRef} but adds an item to the join's\n * `on` clause instead.\n *\n * See {@link WhereInterface.whereRef} for documentation and examples.\n */\n onRef(lhs, op, rhs) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds `on true`.\n */\n onTrue() {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql('true')),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.joinNode;\n }\n}\n","/// <reference types=\"./partition-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByItemNode = freeze({\n is(node) {\n return node.kind === 'PartitionByItemNode';\n },\n create(partitionBy) {\n return freeze({\n kind: 'PartitionByItemNode',\n partitionBy,\n });\n },\n});\n","/// <reference types=\"./partition-by-parser.d.ts\" />\nimport { PartitionByItemNode } from '../operation-node/partition-by-item-node.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parsePartitionBy(partitionBy) {\n return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);\n}\n","/// <reference types=\"./over-builder.d.ts\" />\nimport { OverNode } from '../operation-node/over-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parsePartitionBy, } from '../parser/partition-by-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OverBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n orderBy(...args) {\n return new OverBuilder({\n overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new OverBuilder({\n overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode),\n });\n }\n partitionBy(partitionBy) {\n return new OverBuilder({\n overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.overNode;\n }\n}\n","/// <reference types=\"./selection-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { ReferenceNode } from './reference-node.js';\nimport { SelectAllNode } from './select-all-node.js';\n/**\n * @internal\n */\nexport const SelectionNode = freeze({\n is(node) {\n return node.kind === 'SelectionNode';\n },\n create(selection) {\n return freeze({\n kind: 'SelectionNode',\n selection: selection,\n });\n },\n createSelectAll() {\n return freeze({\n kind: 'SelectionNode',\n selection: SelectAllNode.create(),\n });\n },\n createSelectAllFromTable(table) {\n return freeze({\n kind: 'SelectionNode',\n selection: ReferenceNode.createSelectAll(table),\n });\n },\n});\n","/// <reference types=\"./select-parser.d.ts\" />\nimport { isFunction, isReadonlyArray, isString } from '../util/object-utils.js';\nimport { SelectionNode } from '../operation-node/selection-node.js';\nimport { parseAliasedStringReference } from './reference-parser.js';\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { parseTable } from './table-parser.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseSelectArg(selection) {\n if (isFunction(selection)) {\n return parseSelectArg(selection(expressionBuilder()));\n }\n else if (isReadonlyArray(selection)) {\n return selection.map((it) => parseSelectExpression(it));\n }\n else {\n return [parseSelectExpression(selection)];\n }\n}\nfunction parseSelectExpression(selection) {\n if (isString(selection)) {\n return SelectionNode.create(parseAliasedStringReference(selection));\n }\n else if (isDynamicReferenceBuilder(selection)) {\n return SelectionNode.create(selection.toOperationNode());\n }\n else {\n return SelectionNode.create(parseAliasedExpression(selection));\n }\n}\nexport function parseSelectAll(table) {\n if (!table) {\n return [SelectionNode.createSelectAll()];\n }\n else if (Array.isArray(table)) {\n return table.map(parseSelectAllArg);\n }\n else {\n return [parseSelectAllArg(table)];\n }\n}\nfunction parseSelectAllArg(table) {\n if (isString(table)) {\n return SelectionNode.createSelectAllFromTable(parseTable(table));\n }\n throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);\n}\n","/// <reference types=\"./no-result-error.d.ts\" />\nexport class NoResultError extends Error {\n /**\n * The operation node tree of the query that was executed.\n */\n node;\n constructor(node) {\n super('no result');\n this.node = node;\n }\n}\nexport function isNoResultErrorConstructor(fn) {\n return Object.prototype.hasOwnProperty.call(fn, 'prototype');\n}\n","/// <reference types=\"./top-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TopNode = freeze({\n is(node) {\n return node.kind === 'TopNode';\n },\n create(expression, modifiers) {\n return freeze({\n kind: 'TopNode',\n expression,\n modifiers,\n });\n },\n});\n","/// <reference types=\"./top-parser.d.ts\" />\nimport { TopNode } from '../operation-node/top-node.js';\nimport { isBigInt, isNumber, isUndefined } from '../util/object-utils.js';\nexport function parseTop(expression, modifiers) {\n if (!isNumber(expression) && !isBigInt(expression)) {\n throw new Error(`Invalid top expression: ${expression}`);\n }\n if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) {\n throw new Error(`Invalid top modifiers: ${modifiers}`);\n }\n return TopNode.create(expression, modifiers);\n}\nfunction isTopModifiers(modifiers) {\n return (modifiers === 'percent' ||\n modifiers === 'with ties' ||\n modifiers === 'percent with ties');\n}\n","/// <reference types=\"./limit-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const LimitNode = freeze({\n is(node) {\n return node.kind === 'LimitNode';\n },\n create(limit) {\n return freeze({\n kind: 'LimitNode',\n limit,\n });\n },\n});\n","/// <reference types=\"./random-string.d.ts\" />\nconst CHARS = [\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n];\nexport function randomString(length) {\n let chars = '';\n for (let i = 0; i < length; ++i) {\n chars += randomChar();\n }\n return chars;\n}\nfunction randomChar() {\n return CHARS[~~(Math.random() * CHARS.length)];\n}\n","/// <reference types=\"./query-id.d.ts\" />\nimport { randomString } from './random-string.js';\nexport function createQueryId() {\n return new LazyQueryId();\n}\nclass LazyQueryId {\n #queryId;\n get queryId() {\n if (this.#queryId === undefined) {\n this.#queryId = randomString(8);\n }\n return this.#queryId;\n }\n}\n","/// <reference types=\"./require-all-props.d.ts\" />\n/**\n * Helper function to check listed properties according to given type. Check if all properties has been used when object is initialised.\n *\n * Example use:\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n *\n * // propB has to be mentioned even it is optional. It still should be initialized with undefined.\n * const a: SomeType = requireAllProps<SomeType>({ propA: \"value A\", propB: undefined });\n *\n * // checked type is implicit for variable.\n * const b = requireAllProps<SomeType>({ propA: \"value A\", propB: undefined });\n * ```\n *\n * Wrong use of this helper:\n *\n * 1. Omit checked type - all checked properties will be expect as of type never\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * // const z: SomeType = requireAllProps({ propC: \"no type will work\" }); // Property 'propA' is missing in type '{ propC: string; }' but required in type 'SomeType'.\n * ```\n *\n * 2. Apply to spreaded object - there is no way how to check in compile time if spreaded object contains all properties\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * const y: SomeType = { propA: \"\" }; // valid object according to SomeType declaration\n * // const x = requireAllProps<SomeType>({ ...y }); // Argument of type '{ propA: string; propB?: number; }' is not assignable to parameter of type 'AllProps<SomeType>'.\n * ```\n *\n * @param obj object to check if all properties has been used\n * @returns untouched obj parameter is returned\n */\nexport function requireAllProps(obj) {\n return obj;\n}\n","/// <reference types=\"./operation-node-transformer.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { requireAllProps } from '../util/require-all-props.js';\n/**\n * Transforms an operation node tree into another one.\n *\n * Kysely queries are expressed internally as a tree of objects (operation nodes).\n * `OperationNodeTransformer` takes such a tree as its input and returns a\n * transformed deep copy of it. By default the `OperationNodeTransformer`\n * does nothing. You need to override one or more methods to make it do\n * something.\n *\n * There's a method for each node type. For example if you'd like to convert\n * each identifier (table name, column name, alias etc.) from camelCase to\n * snake_case, you'd do something like this:\n *\n * ```ts\n * import { type IdentifierNode, OperationNodeTransformer } from 'kysely'\n * import snakeCase from 'lodash/snakeCase'\n *\n * class CamelCaseTransformer extends OperationNodeTransformer {\n * override transformIdentifier(node: IdentifierNode): IdentifierNode {\n * node = super.transformIdentifier(node)\n *\n * return {\n * ...node,\n * name: snakeCase(node.name),\n * }\n * }\n * }\n *\n * const transformer = new CamelCaseTransformer()\n *\n * const query = db.selectFrom('person').select(['first_name', 'last_name'])\n *\n * const tree = transformer.transformNode(query.toOperationNode())\n * ```\n */\nexport class OperationNodeTransformer {\n nodeStack = [];\n #transformers = freeze({\n AliasNode: this.transformAlias.bind(this),\n ColumnNode: this.transformColumn.bind(this),\n IdentifierNode: this.transformIdentifier.bind(this),\n SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),\n RawNode: this.transformRaw.bind(this),\n ReferenceNode: this.transformReference.bind(this),\n SelectQueryNode: this.transformSelectQuery.bind(this),\n SelectionNode: this.transformSelection.bind(this),\n TableNode: this.transformTable.bind(this),\n FromNode: this.transformFrom.bind(this),\n SelectAllNode: this.transformSelectAll.bind(this),\n AndNode: this.transformAnd.bind(this),\n OrNode: this.transformOr.bind(this),\n ValueNode: this.transformValue.bind(this),\n ValueListNode: this.transformValueList.bind(this),\n PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),\n ParensNode: this.transformParens.bind(this),\n JoinNode: this.transformJoin.bind(this),\n OperatorNode: this.transformOperator.bind(this),\n WhereNode: this.transformWhere.bind(this),\n InsertQueryNode: this.transformInsertQuery.bind(this),\n DeleteQueryNode: this.transformDeleteQuery.bind(this),\n ReturningNode: this.transformReturning.bind(this),\n CreateTableNode: this.transformCreateTable.bind(this),\n AddColumnNode: this.transformAddColumn.bind(this),\n ColumnDefinitionNode: this.transformColumnDefinition.bind(this),\n DropTableNode: this.transformDropTable.bind(this),\n DataTypeNode: this.transformDataType.bind(this),\n OrderByNode: this.transformOrderBy.bind(this),\n OrderByItemNode: this.transformOrderByItem.bind(this),\n GroupByNode: this.transformGroupBy.bind(this),\n GroupByItemNode: this.transformGroupByItem.bind(this),\n UpdateQueryNode: this.transformUpdateQuery.bind(this),\n ColumnUpdateNode: this.transformColumnUpdate.bind(this),\n LimitNode: this.transformLimit.bind(this),\n OffsetNode: this.transformOffset.bind(this),\n OnConflictNode: this.transformOnConflict.bind(this),\n OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),\n CreateIndexNode: this.transformCreateIndex.bind(this),\n DropIndexNode: this.transformDropIndex.bind(this),\n ListNode: this.transformList.bind(this),\n PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.transformUniqueConstraint.bind(this),\n ReferencesNode: this.transformReferences.bind(this),\n CheckConstraintNode: this.transformCheckConstraint.bind(this),\n WithNode: this.transformWith.bind(this),\n CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),\n HavingNode: this.transformHaving.bind(this),\n CreateSchemaNode: this.transformCreateSchema.bind(this),\n DropSchemaNode: this.transformDropSchema.bind(this),\n AlterTableNode: this.transformAlterTable.bind(this),\n DropColumnNode: this.transformDropColumn.bind(this),\n RenameColumnNode: this.transformRenameColumn.bind(this),\n AlterColumnNode: this.transformAlterColumn.bind(this),\n ModifyColumnNode: this.transformModifyColumn.bind(this),\n AddConstraintNode: this.transformAddConstraint.bind(this),\n DropConstraintNode: this.transformDropConstraint.bind(this),\n RenameConstraintNode: this.transformRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),\n CreateViewNode: this.transformCreateView.bind(this),\n RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),\n DropViewNode: this.transformDropView.bind(this),\n GeneratedNode: this.transformGenerated.bind(this),\n DefaultValueNode: this.transformDefaultValue.bind(this),\n OnNode: this.transformOn.bind(this),\n ValuesNode: this.transformValues.bind(this),\n SelectModifierNode: this.transformSelectModifier.bind(this),\n CreateTypeNode: this.transformCreateType.bind(this),\n DropTypeNode: this.transformDropType.bind(this),\n ExplainNode: this.transformExplain.bind(this),\n DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.transformAggregateFunction.bind(this),\n OverNode: this.transformOver.bind(this),\n PartitionByNode: this.transformPartitionBy.bind(this),\n PartitionByItemNode: this.transformPartitionByItem.bind(this),\n SetOperationNode: this.transformSetOperation.bind(this),\n BinaryOperationNode: this.transformBinaryOperation.bind(this),\n UnaryOperationNode: this.transformUnaryOperation.bind(this),\n UsingNode: this.transformUsing.bind(this),\n FunctionNode: this.transformFunction.bind(this),\n CaseNode: this.transformCase.bind(this),\n WhenNode: this.transformWhen.bind(this),\n JSONReferenceNode: this.transformJSONReference.bind(this),\n JSONPathNode: this.transformJSONPath.bind(this),\n JSONPathLegNode: this.transformJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),\n TupleNode: this.transformTuple.bind(this),\n MergeQueryNode: this.transformMergeQuery.bind(this),\n MatchedNode: this.transformMatched.bind(this),\n AddIndexNode: this.transformAddIndex.bind(this),\n CastNode: this.transformCast.bind(this),\n FetchNode: this.transformFetch.bind(this),\n TopNode: this.transformTop.bind(this),\n OutputNode: this.transformOutput.bind(this),\n OrActionNode: this.transformOrAction.bind(this),\n CollateNode: this.transformCollate.bind(this),\n });\n transformNode(node, queryId) {\n if (!node) {\n return node;\n }\n this.nodeStack.push(node);\n const out = this.transformNodeImpl(node, queryId);\n this.nodeStack.pop();\n return freeze(out);\n }\n transformNodeImpl(node, queryId) {\n return this.#transformers[node.kind](node, queryId);\n }\n transformNodeList(list, queryId) {\n if (!list) {\n return list;\n }\n return freeze(list.map((node) => this.transformNode(node, queryId)));\n }\n transformSelectQuery(node, queryId) {\n return requireAllProps({\n kind: 'SelectQueryNode',\n from: this.transformNode(node.from, queryId),\n selections: this.transformNodeList(node.selections, queryId),\n distinctOn: this.transformNodeList(node.distinctOn, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n groupBy: this.transformNode(node.groupBy, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n where: this.transformNode(node.where, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n limit: this.transformNode(node.limit, queryId),\n offset: this.transformNode(node.offset, queryId),\n with: this.transformNode(node.with, queryId),\n having: this.transformNode(node.having, queryId),\n explain: this.transformNode(node.explain, queryId),\n setOperations: this.transformNodeList(node.setOperations, queryId),\n fetch: this.transformNode(node.fetch, queryId),\n top: this.transformNode(node.top, queryId),\n });\n }\n transformSelection(node, queryId) {\n return requireAllProps({\n kind: 'SelectionNode',\n selection: this.transformNode(node.selection, queryId),\n });\n }\n transformColumn(node, queryId) {\n return requireAllProps({\n kind: 'ColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAlias(node, queryId) {\n return requireAllProps({\n kind: 'AliasNode',\n node: this.transformNode(node.node, queryId),\n alias: this.transformNode(node.alias, queryId),\n });\n }\n transformTable(node, queryId) {\n return requireAllProps({\n kind: 'TableNode',\n table: this.transformNode(node.table, queryId),\n });\n }\n transformFrom(node, queryId) {\n return requireAllProps({\n kind: 'FromNode',\n froms: this.transformNodeList(node.froms, queryId),\n });\n }\n transformReference(node, queryId) {\n return requireAllProps({\n kind: 'ReferenceNode',\n column: this.transformNode(node.column, queryId),\n table: this.transformNode(node.table, queryId),\n });\n }\n transformAnd(node, queryId) {\n return requireAllProps({\n kind: 'AndNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformOr(node, queryId) {\n return requireAllProps({\n kind: 'OrNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformValueList(node, queryId) {\n return requireAllProps({\n kind: 'ValueListNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformParens(node, queryId) {\n return requireAllProps({\n kind: 'ParensNode',\n node: this.transformNode(node.node, queryId),\n });\n }\n transformJoin(node, queryId) {\n return requireAllProps({\n kind: 'JoinNode',\n joinType: node.joinType,\n table: this.transformNode(node.table, queryId),\n on: this.transformNode(node.on, queryId),\n });\n }\n transformRaw(node, queryId) {\n return requireAllProps({\n kind: 'RawNode',\n sqlFragments: freeze([...node.sqlFragments]),\n parameters: this.transformNodeList(node.parameters, queryId),\n });\n }\n transformWhere(node, queryId) {\n return requireAllProps({\n kind: 'WhereNode',\n where: this.transformNode(node.where, queryId),\n });\n }\n transformInsertQuery(node, queryId) {\n return requireAllProps({\n kind: 'InsertQueryNode',\n into: this.transformNode(node.into, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n values: this.transformNode(node.values, queryId),\n returning: this.transformNode(node.returning, queryId),\n onConflict: this.transformNode(node.onConflict, queryId),\n onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n ignore: node.ignore,\n orAction: this.transformNode(node.orAction, queryId),\n replace: node.replace,\n explain: this.transformNode(node.explain, queryId),\n defaultValues: node.defaultValues,\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformValues(node, queryId) {\n return requireAllProps({\n kind: 'ValuesNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformDeleteQuery(node, queryId) {\n return requireAllProps({\n kind: 'DeleteQueryNode',\n from: this.transformNode(node.from, queryId),\n using: this.transformNode(node.using, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n limit: this.transformNode(node.limit, queryId),\n explain: this.transformNode(node.explain, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformReturning(node, queryId) {\n return requireAllProps({\n kind: 'ReturningNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformCreateTable(node, queryId) {\n return requireAllProps({\n kind: 'CreateTableNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n constraints: this.transformNodeList(node.constraints, queryId),\n temporary: node.temporary,\n ifNotExists: node.ifNotExists,\n onCommit: node.onCommit,\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n selectQuery: this.transformNode(node.selectQuery, queryId),\n });\n }\n transformColumnDefinition(node, queryId) {\n return requireAllProps({\n kind: 'ColumnDefinitionNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n references: this.transformNode(node.references, queryId),\n primaryKey: node.primaryKey,\n autoIncrement: node.autoIncrement,\n unique: node.unique,\n notNull: node.notNull,\n unsigned: node.unsigned,\n defaultTo: this.transformNode(node.defaultTo, queryId),\n check: this.transformNode(node.check, queryId),\n generated: this.transformNode(node.generated, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n identity: node.identity,\n ifNotExists: node.ifNotExists,\n });\n }\n transformAddColumn(node, queryId) {\n return requireAllProps({\n kind: 'AddColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformDropTable(node, queryId) {\n return requireAllProps({\n kind: 'DropTableNode',\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformOrderBy(node, queryId) {\n return requireAllProps({\n kind: 'OrderByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformOrderByItem(node, queryId) {\n return requireAllProps({\n kind: 'OrderByItemNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n direction: this.transformNode(node.direction, queryId),\n collation: this.transformNode(node.collation, queryId),\n nulls: node.nulls,\n });\n }\n transformGroupBy(node, queryId) {\n return requireAllProps({\n kind: 'GroupByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformGroupByItem(node, queryId) {\n return requireAllProps({\n kind: 'GroupByItemNode',\n groupBy: this.transformNode(node.groupBy, queryId),\n });\n }\n transformUpdateQuery(node, queryId) {\n return requireAllProps({\n kind: 'UpdateQueryNode',\n table: this.transformNode(node.table, queryId),\n from: this.transformNode(node.from, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n explain: this.transformNode(node.explain, queryId),\n limit: this.transformNode(node.limit, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n });\n }\n transformColumnUpdate(node, queryId) {\n return requireAllProps({\n kind: 'ColumnUpdateNode',\n column: this.transformNode(node.column, queryId),\n value: this.transformNode(node.value, queryId),\n });\n }\n transformLimit(node, queryId) {\n return requireAllProps({\n kind: 'LimitNode',\n limit: this.transformNode(node.limit, queryId),\n });\n }\n transformOffset(node, queryId) {\n return requireAllProps({\n kind: 'OffsetNode',\n offset: this.transformNode(node.offset, queryId),\n });\n }\n transformOnConflict(node, queryId) {\n return requireAllProps({\n kind: 'OnConflictNode',\n columns: this.transformNodeList(node.columns, queryId),\n constraint: this.transformNode(node.constraint, queryId),\n indexExpression: this.transformNode(node.indexExpression, queryId),\n indexWhere: this.transformNode(node.indexWhere, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n updateWhere: this.transformNode(node.updateWhere, queryId),\n doNothing: node.doNothing,\n });\n }\n transformOnDuplicateKey(node, queryId) {\n return requireAllProps({\n kind: 'OnDuplicateKeyNode',\n updates: this.transformNodeList(node.updates, queryId),\n });\n }\n transformCreateIndex(node, queryId) {\n return requireAllProps({\n kind: 'CreateIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n where: this.transformNode(node.where, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n });\n }\n transformList(node, queryId) {\n return requireAllProps({\n kind: 'ListNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformDropIndex(node, queryId) {\n return requireAllProps({\n kind: 'DropIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformPrimaryKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'PrimaryKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformUniqueConstraint(node, queryId) {\n return requireAllProps({\n kind: 'UniqueConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformForeignKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'ForeignKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n references: this.transformNode(node.references, queryId),\n name: this.transformNode(node.name, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformSetOperation(node, queryId) {\n return requireAllProps({\n kind: 'SetOperationNode',\n operator: node.operator,\n expression: this.transformNode(node.expression, queryId),\n all: node.all,\n });\n }\n transformReferences(node, queryId) {\n return requireAllProps({\n kind: 'ReferencesNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n });\n }\n transformCheckConstraint(node, queryId) {\n return requireAllProps({\n kind: 'CheckConstraintNode',\n expression: this.transformNode(node.expression, queryId),\n name: this.transformNode(node.name, queryId),\n });\n }\n transformWith(node, queryId) {\n return requireAllProps({\n kind: 'WithNode',\n expressions: this.transformNodeList(node.expressions, queryId),\n recursive: node.recursive,\n });\n }\n transformCommonTableExpression(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNode',\n name: this.transformNode(node.name, queryId),\n materialized: node.materialized,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformCommonTableExpressionName(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNameNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n });\n }\n transformHaving(node, queryId) {\n return requireAllProps({\n kind: 'HavingNode',\n having: this.transformNode(node.having, queryId),\n });\n }\n transformCreateSchema(node, queryId) {\n return requireAllProps({\n kind: 'CreateSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformDropSchema(node, queryId) {\n return requireAllProps({\n kind: 'DropSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformAlterTable(node, queryId) {\n return requireAllProps({\n kind: 'AlterTableNode',\n table: this.transformNode(node.table, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n setSchema: this.transformNode(node.setSchema, queryId),\n columnAlterations: this.transformNodeList(node.columnAlterations, queryId),\n addConstraint: this.transformNode(node.addConstraint, queryId),\n dropConstraint: this.transformNode(node.dropConstraint, queryId),\n renameConstraint: this.transformNode(node.renameConstraint, queryId),\n addIndex: this.transformNode(node.addIndex, queryId),\n dropIndex: this.transformNode(node.dropIndex, queryId),\n });\n }\n transformDropColumn(node, queryId) {\n return requireAllProps({\n kind: 'DropColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformRenameColumn(node, queryId) {\n return requireAllProps({\n kind: 'RenameColumnNode',\n column: this.transformNode(node.column, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n });\n }\n transformAlterColumn(node, queryId) {\n return requireAllProps({\n kind: 'AlterColumnNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),\n setDefault: this.transformNode(node.setDefault, queryId),\n dropDefault: node.dropDefault,\n setNotNull: node.setNotNull,\n dropNotNull: node.dropNotNull,\n });\n }\n transformModifyColumn(node, queryId) {\n return requireAllProps({\n kind: 'ModifyColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAddConstraint(node, queryId) {\n return requireAllProps({\n kind: 'AddConstraintNode',\n constraint: this.transformNode(node.constraint, queryId),\n });\n }\n transformDropConstraint(node, queryId) {\n return requireAllProps({\n kind: 'DropConstraintNode',\n constraintName: this.transformNode(node.constraintName, queryId),\n ifExists: node.ifExists,\n modifier: node.modifier,\n });\n }\n transformRenameConstraint(node, queryId) {\n return requireAllProps({\n kind: 'RenameConstraintNode',\n oldName: this.transformNode(node.oldName, queryId),\n newName: this.transformNode(node.newName, queryId),\n });\n }\n transformCreateView(node, queryId) {\n return requireAllProps({\n kind: 'CreateViewNode',\n name: this.transformNode(node.name, queryId),\n temporary: node.temporary,\n orReplace: node.orReplace,\n ifNotExists: node.ifNotExists,\n materialized: node.materialized,\n columns: this.transformNodeList(node.columns, queryId),\n as: this.transformNode(node.as, queryId),\n });\n }\n transformRefreshMaterializedView(node, queryId) {\n return requireAllProps({\n kind: 'RefreshMaterializedViewNode',\n name: this.transformNode(node.name, queryId),\n concurrently: node.concurrently,\n withNoData: node.withNoData,\n });\n }\n transformDropView(node, queryId) {\n return requireAllProps({\n kind: 'DropViewNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n materialized: node.materialized,\n cascade: node.cascade,\n });\n }\n transformGenerated(node, queryId) {\n return requireAllProps({\n kind: 'GeneratedNode',\n byDefault: node.byDefault,\n always: node.always,\n identity: node.identity,\n stored: node.stored,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformDefaultValue(node, queryId) {\n return requireAllProps({\n kind: 'DefaultValueNode',\n defaultValue: this.transformNode(node.defaultValue, queryId),\n });\n }\n transformOn(node, queryId) {\n return requireAllProps({\n kind: 'OnNode',\n on: this.transformNode(node.on, queryId),\n });\n }\n transformSelectModifier(node, queryId) {\n return requireAllProps({\n kind: 'SelectModifierNode',\n modifier: node.modifier,\n rawModifier: this.transformNode(node.rawModifier, queryId),\n of: this.transformNodeList(node.of, queryId),\n });\n }\n transformCreateType(node, queryId) {\n return requireAllProps({\n kind: 'CreateTypeNode',\n name: this.transformNode(node.name, queryId),\n enum: this.transformNode(node.enum, queryId),\n });\n }\n transformDropType(node, queryId) {\n return requireAllProps({\n kind: 'DropTypeNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n });\n }\n transformExplain(node, queryId) {\n return requireAllProps({\n kind: 'ExplainNode',\n format: node.format,\n options: this.transformNode(node.options, queryId),\n });\n }\n transformSchemableIdentifier(node, queryId) {\n return requireAllProps({\n kind: 'SchemableIdentifierNode',\n schema: this.transformNode(node.schema, queryId),\n identifier: this.transformNode(node.identifier, queryId),\n });\n }\n transformAggregateFunction(node, queryId) {\n return requireAllProps({\n kind: 'AggregateFunctionNode',\n func: node.func,\n aggregated: this.transformNodeList(node.aggregated, queryId),\n distinct: node.distinct,\n orderBy: this.transformNode(node.orderBy, queryId),\n withinGroup: this.transformNode(node.withinGroup, queryId),\n filter: this.transformNode(node.filter, queryId),\n over: this.transformNode(node.over, queryId),\n });\n }\n transformOver(node, queryId) {\n return requireAllProps({\n kind: 'OverNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformPartitionBy(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformPartitionByItem(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByItemNode',\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformBinaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'BinaryOperationNode',\n leftOperand: this.transformNode(node.leftOperand, queryId),\n operator: this.transformNode(node.operator, queryId),\n rightOperand: this.transformNode(node.rightOperand, queryId),\n });\n }\n transformUnaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'UnaryOperationNode',\n operator: this.transformNode(node.operator, queryId),\n operand: this.transformNode(node.operand, queryId),\n });\n }\n transformUsing(node, queryId) {\n return requireAllProps({\n kind: 'UsingNode',\n tables: this.transformNodeList(node.tables, queryId),\n });\n }\n transformFunction(node, queryId) {\n return requireAllProps({\n kind: 'FunctionNode',\n func: node.func,\n arguments: this.transformNodeList(node.arguments, queryId),\n });\n }\n transformCase(node, queryId) {\n return requireAllProps({\n kind: 'CaseNode',\n value: this.transformNode(node.value, queryId),\n when: this.transformNodeList(node.when, queryId),\n else: this.transformNode(node.else, queryId),\n isStatement: node.isStatement,\n });\n }\n transformWhen(node, queryId) {\n return requireAllProps({\n kind: 'WhenNode',\n condition: this.transformNode(node.condition, queryId),\n result: this.transformNode(node.result, queryId),\n });\n }\n transformJSONReference(node, queryId) {\n return requireAllProps({\n kind: 'JSONReferenceNode',\n reference: this.transformNode(node.reference, queryId),\n traversal: this.transformNode(node.traversal, queryId),\n });\n }\n transformJSONPath(node, queryId) {\n return requireAllProps({\n kind: 'JSONPathNode',\n inOperator: this.transformNode(node.inOperator, queryId),\n pathLegs: this.transformNodeList(node.pathLegs, queryId),\n });\n }\n transformJSONPathLeg(node, _queryId) {\n return requireAllProps({\n kind: 'JSONPathLegNode',\n type: node.type,\n value: node.value,\n });\n }\n transformJSONOperatorChain(node, queryId) {\n return requireAllProps({\n kind: 'JSONOperatorChainNode',\n operator: this.transformNode(node.operator, queryId),\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformTuple(node, queryId) {\n return requireAllProps({\n kind: 'TupleNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformMergeQuery(node, queryId) {\n return requireAllProps({\n kind: 'MergeQueryNode',\n into: this.transformNode(node.into, queryId),\n using: this.transformNode(node.using, queryId),\n whens: this.transformNodeList(node.whens, queryId),\n with: this.transformNode(node.with, queryId),\n top: this.transformNode(node.top, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n output: this.transformNode(node.output, queryId),\n returning: this.transformNode(node.returning, queryId),\n });\n }\n transformMatched(node, _queryId) {\n return requireAllProps({\n kind: 'MatchedNode',\n not: node.not,\n bySource: node.bySource,\n });\n }\n transformAddIndex(node, queryId) {\n return requireAllProps({\n kind: 'AddIndexNode',\n name: this.transformNode(node.name, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformCast(node, queryId) {\n return requireAllProps({\n kind: 'CastNode',\n expression: this.transformNode(node.expression, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n });\n }\n transformFetch(node, queryId) {\n return requireAllProps({\n kind: 'FetchNode',\n rowCount: this.transformNode(node.rowCount, queryId),\n modifier: node.modifier,\n });\n }\n transformTop(node, _queryId) {\n return requireAllProps({\n kind: 'TopNode',\n expression: node.expression,\n modifiers: node.modifiers,\n });\n }\n transformOutput(node, queryId) {\n return requireAllProps({\n kind: 'OutputNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformDataType(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformSelectAll(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformIdentifier(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformPrimitiveValueList(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOperator(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformDefaultInsertValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOrAction(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformCollate(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n}\n","/// <reference types=\"./with-schema-transformer.d.ts\" />\nimport { AliasNode } from '../../operation-node/alias-node.js';\nimport { IdentifierNode } from '../../operation-node/identifier-node.js';\nimport { JoinNode } from '../../operation-node/join-node.js';\nimport { ListNode } from '../../operation-node/list-node.js';\nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { SchemableIdentifierNode } from '../../operation-node/schemable-identifier-node.js';\nimport { TableNode } from '../../operation-node/table-node.js';\nimport { UsingNode } from '../../operation-node/using-node.js';\nimport { freeze } from '../../util/object-utils.js';\n// This object exist only so that we get a type error when a new RootOperationNode\n// is added. If you get a type error here, make sure to add the new root node and\n// handle it correctly in the transformer.\n//\n// DO NOT REFACTOR THIS EVEN IF IT SEEMS USELESS TO YOU!\nconst ROOT_OPERATION_NODES = freeze({\n AlterTableNode: true,\n CreateIndexNode: true,\n CreateSchemaNode: true,\n CreateTableNode: true,\n CreateTypeNode: true,\n CreateViewNode: true,\n RefreshMaterializedViewNode: true,\n DeleteQueryNode: true,\n DropIndexNode: true,\n DropSchemaNode: true,\n DropTableNode: true,\n DropTypeNode: true,\n DropViewNode: true,\n InsertQueryNode: true,\n RawNode: true,\n SelectQueryNode: true,\n UpdateQueryNode: true,\n MergeQueryNode: true,\n});\nconst SCHEMALESS_FUNCTIONS = {\n json_agg: true,\n to_json: true,\n};\nexport class WithSchemaTransformer extends OperationNodeTransformer {\n #schema;\n #schemableIds = new Set();\n #ctes = new Set();\n constructor(schema) {\n super();\n this.#schema = schema;\n }\n transformNodeImpl(node, queryId) {\n if (!this.#isRootOperationNode(node)) {\n return super.transformNodeImpl(node, queryId);\n }\n const ctes = this.#collectCTEs(node);\n for (const cte of ctes) {\n this.#ctes.add(cte);\n }\n const tables = this.#collectSchemableIds(node);\n for (const table of tables) {\n this.#schemableIds.add(table);\n }\n const transformed = super.transformNodeImpl(node, queryId);\n for (const table of tables) {\n this.#schemableIds.delete(table);\n }\n for (const cte of ctes) {\n this.#ctes.delete(cte);\n }\n return transformed;\n }\n transformSchemableIdentifier(node, queryId) {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) {\n return transformed;\n }\n return {\n ...transformed,\n schema: IdentifierNode.create(this.#schema),\n };\n }\n transformReferences(node, queryId) {\n const transformed = super.transformReferences(node, queryId);\n if (transformed.table.table.schema) {\n return transformed;\n }\n return {\n ...transformed,\n table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name),\n };\n }\n transformAggregateFunction(node, queryId) {\n return {\n ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId),\n aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, 'aggregated'),\n };\n }\n transformFunction(node, queryId) {\n return {\n ...super.transformFunction({ ...node, arguments: [] }, queryId),\n arguments: this.#transformTableArgsWithoutSchemas(node, queryId, 'arguments'),\n };\n }\n transformSelectModifier(node, queryId) {\n return {\n ...super.transformSelectModifier({ ...node, of: undefined }, queryId),\n of: node.of?.map((item) => TableNode.is(item) && !item.table.schema\n ? {\n ...item,\n table: this.transformIdentifier(item.table.identifier, queryId),\n }\n : this.transformNode(item, queryId)),\n };\n }\n #transformTableArgsWithoutSchemas(node, queryId, argsKey) {\n return SCHEMALESS_FUNCTIONS[node.func]\n ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema\n ? this.transformNode(arg, queryId)\n : {\n ...arg,\n table: this.transformIdentifier(arg.table.identifier, queryId),\n })\n : this.transformNodeList(node[argsKey], queryId);\n }\n #isRootOperationNode(node) {\n return node.kind in ROOT_OPERATION_NODES;\n }\n #collectSchemableIds(node) {\n const schemableIds = new Set();\n if ('name' in node && node.name && SchemableIdentifierNode.is(node.name)) {\n this.#collectSchemableId(node.name, schemableIds);\n }\n if ('from' in node && node.from) {\n for (const from of node.from.froms) {\n this.#collectSchemableIdsFromTableExpr(from, schemableIds);\n }\n }\n if ('into' in node && node.into) {\n this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);\n }\n if ('table' in node && node.table) {\n this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);\n }\n if ('joins' in node && node.joins) {\n for (const join of node.joins) {\n this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);\n }\n }\n if ('using' in node && node.using) {\n if (JoinNode.is(node.using)) {\n this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);\n }\n else {\n this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);\n }\n }\n return schemableIds;\n }\n #collectCTEs(node) {\n const ctes = new Set();\n if ('with' in node && node.with) {\n this.#collectCTEIds(node.with, ctes);\n }\n return ctes;\n }\n #collectSchemableIdsFromTableExpr(node, schemableIds) {\n if (TableNode.is(node)) {\n return this.#collectSchemableId(node.table, schemableIds);\n }\n if (AliasNode.is(node) && TableNode.is(node.node)) {\n return this.#collectSchemableId(node.node.table, schemableIds);\n }\n if (ListNode.is(node)) {\n for (const table of node.items) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n if (UsingNode.is(node)) {\n for (const table of node.tables) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n }\n #collectSchemableId(node, schemableIds) {\n const id = node.identifier.name;\n if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) {\n schemableIds.add(id);\n }\n }\n #collectCTEIds(node, ctes) {\n for (const expr of node.expressions) {\n const cteId = expr.name.table.table.identifier.name;\n if (!this.#ctes.has(cteId)) {\n ctes.add(cteId);\n }\n }\n }\n}\n","/// <reference types=\"./with-schema-plugin.d.ts\" />\nimport { WithSchemaTransformer } from './with-schema-transformer.js';\nexport class WithSchemaPlugin {\n #transformer;\n constructor(schema) {\n this.#transformer = new WithSchemaTransformer(schema);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n","/// <reference types=\"./deferred.d.ts\" />\nexport class Deferred {\n #promise;\n #resolve;\n #reject;\n constructor() {\n this.#promise = new Promise((resolve, reject) => {\n this.#reject = reject;\n this.#resolve = resolve;\n });\n }\n get promise() {\n return this.#promise;\n }\n resolve = (value) => {\n if (this.#resolve) {\n this.#resolve(value);\n }\n };\n reject = (reason) => {\n if (this.#reject) {\n this.#reject(reason);\n }\n };\n}\n","/// <reference types=\"./provide-controlled-connection.d.ts\" />\nimport { Deferred } from './deferred.js';\nimport { freeze } from './object-utils.js';\nexport async function provideControlledConnection(connectionProvider) {\n const connectionDefer = new Deferred();\n const connectionReleaseDefer = new Deferred();\n connectionProvider\n .provideConnection(async (connection) => {\n connectionDefer.resolve(connection);\n return await connectionReleaseDefer.promise;\n })\n .catch((ex) => connectionDefer.reject(ex));\n // Create composite of the connection and the release method instead of\n // modifying the connection or creating a new nesting `DatabaseConnection`.\n // This way we don't accidentally override any methods of 3rd party\n // connections and don't return wrapped connections to drivers that\n // expect a certain specific connection class.\n return freeze({\n connection: await connectionDefer.promise,\n release: connectionReleaseDefer.resolve,\n });\n}\n","/// <reference types=\"./query-executor-base.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { provideControlledConnection } from '../util/provide-controlled-connection.js';\nimport { logOnce } from '../util/log-once.js';\nconst NO_PLUGINS = freeze([]);\nexport class QueryExecutorBase {\n #plugins;\n constructor(plugins = NO_PLUGINS) {\n this.#plugins = plugins;\n }\n get plugins() {\n return this.#plugins;\n }\n transformQuery(node, queryId) {\n for (const plugin of this.#plugins) {\n const transformedNode = plugin.transformQuery({ node, queryId });\n // We need to do a runtime check here. There is no good way\n // to write types that enforce this constraint.\n if (transformedNode.kind === node.kind) {\n node = transformedNode;\n }\n else {\n throw new Error([\n `KyselyPlugin.transformQuery must return a node`,\n `of the same kind that was given to it.`,\n `The plugin was given a ${node.kind}`,\n `but it returned a ${transformedNode.kind}`,\n ].join(' '));\n }\n }\n return node;\n }\n async executeQuery(compiledQuery) {\n return await this.provideConnection(async (connection) => {\n const result = await connection.executeQuery(compiledQuery);\n if ('numUpdatedOrDeletedRows' in result) {\n logOnce('kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.');\n }\n return await this.#transformResult(result, compiledQuery.queryId);\n });\n }\n async *stream(compiledQuery, chunkSize) {\n const { connection, release } = await provideControlledConnection(this);\n try {\n for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {\n yield await this.#transformResult(result, compiledQuery.queryId);\n }\n }\n finally {\n release();\n }\n }\n async #transformResult(result, queryId) {\n for (const plugin of this.#plugins) {\n result = await plugin.transformResult({ result, queryId });\n }\n return result;\n }\n}\n","/// <reference types=\"./noop-query-executor.d.ts\" />\nimport { QueryExecutorBase } from './query-executor-base.js';\n/**\n * A {@link QueryExecutor} subclass that can be used when you don't\n * have a {@link QueryCompiler}, {@link ConnectionProvider} or any\n * other needed things to actually execute queries.\n */\nexport class NoopQueryExecutor extends QueryExecutorBase {\n get adapter() {\n throw new Error('this query cannot be compiled to SQL');\n }\n compileQuery() {\n throw new Error('this query cannot be compiled to SQL');\n }\n provideConnection() {\n throw new Error('this query cannot be executed');\n }\n withConnectionProvider() {\n throw new Error('this query cannot have a connection provider');\n }\n withPlugin(plugin) {\n return new NoopQueryExecutor([...this.plugins, plugin]);\n }\n withPlugins(plugins) {\n return new NoopQueryExecutor([...this.plugins, ...plugins]);\n }\n withPluginAtFront(plugin) {\n return new NoopQueryExecutor([plugin, ...this.plugins]);\n }\n withoutPlugins() {\n return new NoopQueryExecutor([]);\n }\n}\nexport const NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();\n","/// <reference types=\"./parse-utils.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { OverNode } from '../operation-node/over-node.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { JoinBuilder } from '../query-builder/join-builder.js';\nimport { OverBuilder } from '../query-builder/over-builder.js';\nimport { createSelectQueryBuilder as newSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { QueryCreator } from '../query-creator.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { parseTableExpression, parseTableExpressionOrList, } from './table-parser.js';\nexport function createSelectQueryBuilder() {\n return newSelectQueryBuilder({\n queryId: createQueryId(),\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList([])),\n });\n}\nexport function createQueryCreator() {\n return new QueryCreator({\n executor: NOOP_QUERY_EXECUTOR,\n });\n}\nexport function createJoinBuilder(joinType, table) {\n return new JoinBuilder({\n joinNode: JoinNode.create(joinType, parseTableExpression(table)),\n });\n}\nexport function createOverBuilder() {\n return new OverBuilder({\n overNode: OverNode.create(),\n });\n}\n","/// <reference types=\"./join-parser.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { parseReferentialBinaryOperation } from './binary-operation-parser.js';\nimport { createJoinBuilder } from './parse-utils.js';\nimport { parseTableExpression, } from './table-parser.js';\nexport function parseJoin(joinType, args) {\n if (args.length === 3) {\n return parseSingleOnJoin(joinType, args[0], args[1], args[2]);\n }\n else if (args.length === 2) {\n return parseCallbackJoin(joinType, args[0], args[1]);\n }\n else if (args.length === 1) {\n return parseOnlessJoin(joinType, args[0]);\n }\n else {\n throw new Error('not implemented');\n }\n}\nfunction parseCallbackJoin(joinType, from, callback) {\n return callback(createJoinBuilder(joinType, from)).toOperationNode();\n}\nfunction parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {\n return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, '=', rhsColumn));\n}\nfunction parseOnlessJoin(joinType, from) {\n return JoinNode.create(joinType, parseTableExpression(from));\n}\n","/// <reference types=\"./offset-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OffsetNode = freeze({\n is(node) {\n return node.kind === 'OffsetNode';\n },\n create(offset) {\n return freeze({\n kind: 'OffsetNode',\n offset,\n });\n },\n});\n","/// <reference types=\"./group-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByItemNode = freeze({\n is(node) {\n return node.kind === 'GroupByItemNode';\n },\n create(groupBy) {\n return freeze({\n kind: 'GroupByItemNode',\n groupBy,\n });\n },\n});\n","/// <reference types=\"./group-by-parser.d.ts\" />\nimport { GroupByItemNode } from '../operation-node/group-by-item-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parseGroupBy(groupBy) {\n groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;\n return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);\n}\n","/// <reference types=\"./set-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SetOperationNode = freeze({\n is(node) {\n return node.kind === 'SetOperationNode';\n },\n create(operator, expression, all) {\n return freeze({\n kind: 'SetOperationNode',\n operator,\n expression,\n all,\n });\n },\n});\n","/// <reference types=\"./set-operation-parser.d.ts\" />\nimport { createExpressionBuilder, } from '../expression/expression-builder.js';\nimport { SetOperationNode, } from '../operation-node/set-operation-node.js';\nimport { isFunction, isReadonlyArray } from '../util/object-utils.js';\nimport { parseExpression } from './expression-parser.js';\nexport function parseSetOperations(operator, expression, all) {\n if (isFunction(expression)) {\n expression = expression(createExpressionBuilder());\n }\n if (!isReadonlyArray(expression)) {\n expression = [expression];\n }\n return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));\n}\n","/// <reference types=\"./expression-wrapper.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { OrNode } from '../operation-node/or-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nexport class ExpressionWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `ExpressionWrapper` with a new output type.\n */\n $castTo() {\n return new ExpressionWrapper(this.#node);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new ExpressionWrapper(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedExpressionWrapper {\n #expr;\n #alias;\n constructor(expr, alias) {\n this.#expr = expr;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#expr;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\nexport class OrWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `OrWrapper` with a new output type.\n */\n $castTo() {\n return new OrWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\nexport class AndWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AndWrapper` with a new output type.\n */\n $castTo() {\n return new AndWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\n","/// <reference types=\"./fetch-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const FetchNode = freeze({\n is(node) {\n return node.kind === 'FetchNode';\n },\n create(rowCount, modifier) {\n return {\n kind: 'FetchNode',\n rowCount: ValueNode.create(rowCount),\n modifier,\n };\n },\n});\n","/// <reference types=\"./fetch-parser.d.ts\" />\nimport { FetchNode } from '../operation-node/fetch-node.js';\nimport { isBigInt, isNumber } from '../util/object-utils.js';\nexport function parseFetch(rowCount, modifier) {\n if (!isNumber(rowCount) && !isBigInt(rowCount)) {\n throw new Error(`Invalid fetch row count: ${rowCount}`);\n }\n if (!isFetchModifier(modifier)) {\n throw new Error(`Invalid fetch modifier: ${modifier}`);\n }\n return FetchNode.create(rowCount, modifier);\n}\nfunction isFetchModifier(value) {\n return value === 'only' || value === 'with ties';\n}\n","/// <reference types=\"./select-query-builder.d.ts\" />\nvar _a;\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { SelectModifierNode } from '../operation-node/select-modifier-node.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { OffsetNode } from '../operation-node/offset-node.js';\nimport { asArray, freeze } from '../util/object-utils.js';\nimport { parseGroupBy } from '../parser/group-by-parser.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { parseSetOperations, } from '../parser/set-operation-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseFetch } from '../parser/fetch-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nclass SelectQueryBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isSelectQueryBuilder() {\n return true;\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n having(...args) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n havingRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n select(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n distinctOn(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)),\n });\n }\n modifyFront(modifier) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n distinct() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create('Distinct')),\n });\n }\n forUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forKeyShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForKeyShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forNoKeyUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForNoKeyUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n skipLocked() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('SkipLocked')),\n });\n }\n noWait() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('NoWait')),\n });\n }\n selectAll(table) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n crossJoin(...args) {\n return this.#join('CrossJoin', args);\n }\n innerJoinLateral(...args) {\n return this.#join('LateralInnerJoin', args);\n }\n leftJoinLateral(...args) {\n return this.#join('LateralLeftJoin', args);\n }\n crossJoinLateral(...args) {\n return this.#join('LateralCrossJoin', args);\n }\n crossApply(...args) {\n return this.#join('CrossApply', args);\n }\n outerApply(...args) {\n return this.#join('OuterApply', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n groupBy(groupBy) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)),\n });\n }\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n offset(offset) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))),\n });\n }\n fetch(rowCount, modifier = 'only') {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)),\n });\n }\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n union(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, false)),\n });\n }\n unionAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, true)),\n });\n }\n intersect(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, false)),\n });\n }\n intersectAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, true)),\n });\n }\n except(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, false)),\n });\n }\n exceptAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, true)),\n });\n }\n as(alias) {\n return new AliasedSelectQueryBuilderImpl(this, alias);\n }\n clearSelect() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n clearOffset() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n clearGroupBy() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode),\n });\n }\n $call(func) {\n return func(this);\n }\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n $castTo() {\n return new _a(this.#props);\n }\n $narrowType() {\n return new _a(this.#props);\n }\n $assertType() {\n return new _a(this.#props);\n }\n $asTuple() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n $asScalar() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n return result.rows;\n }\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = SelectQueryBuilderImpl;\nexport function createSelectQueryBuilder(props) {\n return new SelectQueryBuilderImpl(props);\n}\n/**\n * {@link SelectQueryBuilder} with an alias. The result of calling {@link SelectQueryBuilder.as}.\n */\nclass AliasedSelectQueryBuilderImpl {\n #queryBuilder;\n #alias;\n constructor(queryBuilder, alias) {\n this.#queryBuilder = queryBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#queryBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get isAliasedSelectQueryBuilder() {\n return true;\n }\n toOperationNode() {\n return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./aggregate-function-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const AggregateFunctionNode = freeze({\n is(node) {\n return node.kind === 'AggregateFunctionNode';\n },\n create(aggregateFunction, aggregated = []) {\n return freeze({\n kind: 'AggregateFunctionNode',\n func: aggregateFunction,\n aggregated,\n });\n },\n cloneWithDistinct(aggregateFunctionNode) {\n return freeze({\n ...aggregateFunctionNode,\n distinct: true,\n });\n },\n cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {\n const prop = withinGroup ? 'withinGroup' : 'orderBy';\n return freeze({\n ...aggregateFunctionNode,\n [prop]: aggregateFunctionNode[prop]\n ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems)\n : OrderByNode.create(orderItems),\n });\n },\n cloneWithFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'And', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOrFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'Or', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOver(aggregateFunctionNode, over) {\n return freeze({\n ...aggregateFunctionNode,\n over,\n });\n },\n});\n","/// <reference types=\"./function-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FunctionNode = freeze({\n is(node) {\n return node.kind === 'FunctionNode';\n },\n create(func, args) {\n return freeze({\n kind: 'FunctionNode',\n func,\n arguments: args,\n });\n },\n});\n","/// <reference types=\"./aggregate-function-builder.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { createOverBuilder } from '../parser/parse-utils.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nexport class AggregateFunctionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n /**\n * Returns an aliased version of the function.\n *\n * In addition to slapping `as \"the_alias\"` to the end of the SQL,\n * this method also provides strict typing:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.count<number>('id').as('person_count')\n * )\n * .executeTakeFirstOrThrow()\n *\n * // `person_count: number` field exists in the result type.\n * console.log(result.person_count)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(\"id\") as \"person_count\"\n * from \"person\"\n * ```\n */\n as(alias) {\n return new AliasedAggregateFunctionBuilder(this, alias);\n }\n /**\n * Adds a `distinct` clause inside the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) =>\n * eb.fn.count<number>('first_name').distinct().as('first_name_count')\n * )\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(distinct \"first_name\") as \"first_name_count\"\n * from \"person\"\n * ```\n */\n distinct() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode),\n });\n }\n orderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode),\n });\n }\n withinGroupOrderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true),\n });\n }\n filterWhere(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Adds a `filter` clause with a nested `where` clause after the function, where\n * both sides of the operator are references to columns.\n *\n * Similar to {@link WhereInterface}'s `whereRef` method.\n *\n * ### Examples\n *\n * Count people with same first and last names versus general public:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * eb.fn\n * .count<number>('id')\n * .filterWhereRef('first_name', '=', 'last_name')\n * .as('repeat_name_count'),\n * eb.fn.count<number>('id').as('total_count'),\n * ])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select\n * count(\"id\") filter(where \"first_name\" = \"last_name\") as \"repeat_name_count\",\n * count(\"id\") as \"total_count\"\n * from \"person\"\n * ```\n */\n filterWhereRef(lhs, op, rhs) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds an `over` clause (window functions) after the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg<number>('age').over().as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over() as \"average_age\"\n * from \"person\"\n * ```\n *\n * Also supports passing a callback that returns an over builder,\n * allowing to add partition by and sort by clauses inside over.\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg<number>('age').over(\n * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')\n * ).as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over(partition by \"last_name\" order by \"first_name\" asc) as \"average_age\"\n * from \"person\"\n * ```\n */\n over(over) {\n const builder = createOverBuilder();\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n /**\n * Casts the expression to the given type.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AggregateFunctionBuilder` with a new output type.\n */\n $castTo() {\n return new AggregateFunctionBuilder(this.#props);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new AggregateFunctionBuilder(this.#props);\n }\n toOperationNode() {\n return this.#props.aggregateFunctionNode;\n }\n}\n/**\n * {@link AggregateFunctionBuilder} with an alias. The result of calling {@link AggregateFunctionBuilder.as}.\n */\nexport class AliasedAggregateFunctionBuilder {\n #aggregateFunctionBuilder;\n #alias;\n constructor(aggregateFunctionBuilder, alias) {\n this.#aggregateFunctionBuilder = aggregateFunctionBuilder;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#aggregateFunctionBuilder;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./function-module.d.ts\" />\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { FunctionNode } from '../operation-node/function-node.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { parseSelectAll } from '../parser/select-parser.js';\nimport { AggregateFunctionBuilder } from './aggregate-function-builder.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseTable } from '../parser/table-parser.js';\nexport function createFunctionModule() {\n const fn = (name, args) => {\n return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));\n };\n const agg = (name, args) => {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : undefined),\n });\n };\n return Object.assign(fn, {\n agg,\n avg(column) {\n return agg('avg', [column]);\n },\n coalesce(...values) {\n return fn('coalesce', values);\n },\n count(column) {\n return agg('count', [column]);\n },\n countAll(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('count', parseSelectAll(table)),\n });\n },\n max(column) {\n return agg('max', [column]);\n },\n min(column) {\n return agg('min', [column]);\n },\n sum(column) {\n return agg('sum', [column]);\n },\n any(column) {\n return fn('any', [column]);\n },\n jsonAgg(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('json_agg', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]),\n });\n },\n toJson(table) {\n return new ExpressionWrapper(FunctionNode.create('to_json', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]));\n },\n });\n}\n","/// <reference types=\"./unary-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UnaryOperationNode = freeze({\n is(node) {\n return node.kind === 'UnaryOperationNode';\n },\n create(operator, operand) {\n return freeze({\n kind: 'UnaryOperationNode',\n operator,\n operand,\n });\n },\n});\n","/// <reference types=\"./unary-operation-parser.d.ts\" />\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { UnaryOperationNode } from '../operation-node/unary-operation-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseExists(operand) {\n return parseUnaryOperation('exists', operand);\n}\nexport function parseNotExists(operand) {\n return parseUnaryOperation('not exists', operand);\n}\nexport function parseUnaryOperation(operator, operand) {\n return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));\n}\n","/// <reference types=\"./case-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const CaseNode = freeze({\n is(node) {\n return node.kind === 'CaseNode';\n },\n create(value) {\n return freeze({\n kind: 'CaseNode',\n value,\n });\n },\n cloneWithWhen(caseNode, when) {\n return freeze({\n ...caseNode,\n when: freeze(caseNode.when ? [...caseNode.when, when] : [when]),\n });\n },\n cloneWithThen(caseNode, then) {\n return freeze({\n ...caseNode,\n when: caseNode.when\n ? freeze([\n ...caseNode.when.slice(0, -1),\n WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then),\n ])\n : undefined,\n });\n },\n cloneWith(caseNode, props) {\n return freeze({\n ...caseNode,\n ...props,\n });\n },\n});\n","/// <reference types=\"./case-builder.d.ts\" />\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { freeze } from '../util/object-utils.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { isSafeImmediateValue, parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nexport class CaseBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n}\nexport class CaseThenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n then(valueExpression) {\n return new CaseWhenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression)),\n });\n }\n}\nexport class CaseWhenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n else(valueExpression) {\n return new CaseEndBuilder({\n ...this.#props,\n node: CaseNode.cloneWith(this.#props.node, {\n else: isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression),\n }),\n });\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\nexport class CaseEndBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\n","/// <reference types=\"./json-path-leg-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathLegNode = freeze({\n is(node) {\n return node.kind === 'JSONPathLegNode';\n },\n create(type, value) {\n return freeze({\n kind: 'JSONPathLegNode',\n type,\n value,\n });\n },\n});\n","/// <reference types=\"./json-path-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathLegNode, } from '../operation-node/json-path-leg-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport class JSONPathBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Access an element of a JSON array in a specific location.\n *\n * Since there's no guarantee an element exists in the given array location, the\n * resulting type is always nullable. If you're sure the element exists, you\n * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.\n *\n * See also {@link key} to access properties of JSON objects.\n *\n * ### Examples\n *\n * ```ts\n * await db.selectFrom('person')\n * .select(eb =>\n * eb.ref('nicknames', '->').at(0).as('primary_nickname')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"nicknames\"->0 as \"primary_nickname\" from \"person\"\n *```\n *\n * Combined with {@link key}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('experience', '->').at(0).key('role').as('first_role')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"experience\"->0->'role' as \"first_role\" from \"person\"\n * ```\n *\n * You can use `'last'` to access the last element of the array in MySQL:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->$').at('last').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `nicknames`->'$[last]' as `last_nickname` from `person`\n * ```\n *\n * Or `'#-1'` in SQLite:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"nicknames\"->>'$[#-1]' as `last_nickname` from `person`\n * ```\n */\n at(index) {\n return this.#createBuilderWithPathLeg('ArrayLocation', index);\n }\n /**\n * Access a property of a JSON object.\n *\n * If a field is optional, the resulting type will be nullable.\n *\n * See also {@link at} to access elements of JSON arrays.\n *\n * ### Examples\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('address', '->').key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"address\"->'city' as \"city\" from \"person\"\n * ```\n *\n * Going deeper:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->$').key('website').key('url').as('website_url')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `profile`->'$.website.url' as `website_url` from `person`\n * ```\n *\n * Combined with {@link at}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"profile\"->'addresses'->0->'city' as \"city\" from \"person\"\n * ```\n */\n key(key) {\n return this.#createBuilderWithPathLeg('Member', key);\n }\n #createBuilderWithPathLeg(legType, value) {\n if (JSONReferenceNode.is(this.#node)) {\n return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal)\n ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value))\n : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));\n }\n return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));\n }\n}\nexport class TraversedJSONPathBuilder extends JSONPathBuilder {\n #node;\n constructor(node) {\n super(node);\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedJSONPathBuilder(this, alias);\n }\n /**\n * Change the output type of the json path.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `JSONPathBuilder` with a new output type.\n */\n $castTo() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n $notNull() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedJSONPathBuilder {\n #jsonPath;\n #alias;\n constructor(jsonPath, alias) {\n this.#jsonPath = jsonPath;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#jsonPath;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./tuple-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TupleNode = freeze({\n is(node) {\n return node.kind === 'TupleNode';\n },\n create(values) {\n return freeze({\n kind: 'TupleNode',\n values: freeze(values),\n });\n },\n});\n","/// <reference types=\"./data-type-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nconst SIMPLE_COLUMN_DATA_TYPES = [\n 'varchar',\n 'char',\n 'text',\n 'integer',\n 'int2',\n 'int4',\n 'int8',\n 'smallint',\n 'bigint',\n 'boolean',\n 'real',\n 'double precision',\n 'float4',\n 'float8',\n 'decimal',\n 'numeric',\n 'binary',\n 'bytea',\n 'date',\n 'datetime',\n 'time',\n 'timetz',\n 'timestamp',\n 'timestamptz',\n 'serial',\n 'bigserial',\n 'uuid',\n 'json',\n 'jsonb',\n 'blob',\n 'varbinary',\n 'int4range',\n 'int4multirange',\n 'int8range',\n 'int8multirange',\n 'numrange',\n 'nummultirange',\n 'tsrange',\n 'tsmultirange',\n 'tstzrange',\n 'tstzmultirange',\n 'daterange',\n 'datemultirange',\n];\nconst COLUMN_DATA_TYPE_REGEX = [\n /^varchar\\(\\d+\\)$/,\n /^char\\(\\d+\\)$/,\n /^decimal\\(\\d+, \\d+\\)$/,\n /^numeric\\(\\d+, \\d+\\)$/,\n /^binary\\(\\d+\\)$/,\n /^datetime\\(\\d+\\)$/,\n /^time\\(\\d+\\)$/,\n /^timetz\\(\\d+\\)$/,\n /^timestamp\\(\\d+\\)$/,\n /^timestamptz\\(\\d+\\)$/,\n /^varbinary\\(\\d+\\)$/,\n];\n/**\n * @internal\n */\nexport const DataTypeNode = freeze({\n is(node) {\n return node.kind === 'DataTypeNode';\n },\n create(dataType) {\n return freeze({\n kind: 'DataTypeNode',\n dataType,\n });\n },\n});\nexport function isColumnDataType(dataType) {\n if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) {\n return true;\n }\n if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) {\n return true;\n }\n return false;\n}\n","/// <reference types=\"./data-type-parser.d.ts\" />\nimport { DataTypeNode, isColumnDataType, } from '../operation-node/data-type-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nexport function parseDataTypeExpression(dataType) {\n if (isOperationNodeSource(dataType)) {\n return dataType.toOperationNode();\n }\n if (isColumnDataType(dataType)) {\n return DataTypeNode.create(dataType);\n }\n throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);\n}\n","/// <reference types=\"./cast-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CastNode = freeze({\n is(node) {\n return node.kind === 'CastNode';\n },\n create(expression, dataType) {\n return freeze({\n kind: 'CastNode',\n expression,\n dataType,\n });\n },\n});\n","/// <reference types=\"./expression-builder.d.ts\" />\nimport { createSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { parseTableExpressionOrList, parseTable, } from '../parser/table-parser.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createFunctionModule, } from '../query-builder/function-module.js';\nimport { parseJSONReference, parseReferenceExpression, parseStringReference, } from '../parser/reference-parser.js';\nimport { parseFilterList, parseFilterObject, parseValueBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { ExpressionWrapper } from './expression-wrapper.js';\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { parseUnaryOperation } from '../parser/unary-operation-parser.js';\nimport { parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { CaseBuilder } from '../query-builder/case-builder.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { isReadonlyArray, isUndefined } from '../util/object-utils.js';\nimport { JSONPathBuilder } from '../query-builder/json-path-builder.js';\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { TupleNode } from '../operation-node/tuple-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { CastNode } from '../operation-node/cast-node.js';\nexport function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {\n function binary(lhs, op, rhs) {\n return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));\n }\n function unary(op, expr) {\n return new ExpressionWrapper(parseUnaryOperation(op, expr));\n }\n const eb = Object.assign(binary, {\n fn: undefined,\n eb: undefined,\n selectFrom(table) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)),\n });\n },\n case(reference) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(reference)\n ? undefined\n : parseReferenceExpression(reference)),\n });\n },\n ref(reference, op) {\n if (isUndefined(op)) {\n return new ExpressionWrapper(parseStringReference(reference));\n }\n return new JSONPathBuilder(parseJSONReference(reference, op));\n },\n jsonPath() {\n return new JSONPathBuilder(JSONPathNode.create());\n },\n table(table) {\n return new ExpressionWrapper(parseTable(table));\n },\n val(value) {\n return new ExpressionWrapper(parseValueExpression(value));\n },\n refTuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));\n },\n tuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));\n },\n lit(value) {\n return new ExpressionWrapper(parseSafeImmediateValue(value));\n },\n unary,\n not(expr) {\n return unary('not', expr);\n },\n exists(expr) {\n return unary('exists', expr);\n },\n neg(expr) {\n return unary('-', expr);\n },\n between(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n betweenSymmetric(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between symmetric'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n and(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'and'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'and'));\n },\n or(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'or'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'or'));\n },\n parens(...args) {\n const node = parseValueBinaryOperationOrExpression(args);\n if (ParensNode.is(node)) {\n // No double wrapping.\n return new ExpressionWrapper(node);\n }\n else {\n return new ExpressionWrapper(ParensNode.create(node));\n }\n },\n cast(expr, dataType) {\n return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));\n },\n withSchema(schema) {\n return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n },\n });\n eb.fn = createFunctionModule();\n eb.eb = eb;\n return eb;\n}\nexport function expressionBuilder(_) {\n return createExpressionBuilder();\n}\n","/// <reference types=\"./expression-parser.d.ts\" />\nimport { isAliasedExpression, isExpression, } from '../expression/expression.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nexport function parseExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid expression: ${JSON.stringify(exp)}`);\n}\nexport function parseAliasedExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);\n}\nexport function isExpressionOrFactory(obj) {\n return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);\n}\n","/// <reference types=\"./dynamic-table-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicTableBuilder {\n #table;\n get table() {\n return this.#table;\n }\n constructor(table) {\n this.#table = table;\n }\n as(alias) {\n return new AliasedDynamicTableBuilder(this.#table, alias);\n }\n}\nexport class AliasedDynamicTableBuilder {\n #table;\n #alias;\n get table() {\n return this.#table;\n }\n get alias() {\n return this.#alias;\n }\n constructor(table, alias) {\n this.#table = table;\n this.#alias = alias;\n }\n toOperationNode() {\n return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));\n }\n}\nexport function isAliasedDynamicTableBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.table) &&\n isString(obj.alias));\n}\n","/// <reference types=\"./table-parser.d.ts\" />\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isAliasedDynamicTableBuilder, } from '../dynamic/dynamic-table-builder.js';\nexport function parseTableExpressionOrList(table) {\n if (isReadonlyArray(table)) {\n return table.map((it) => parseTableExpression(it));\n }\n else {\n return [parseTableExpression(table)];\n }\n}\nexport function parseTableExpression(table) {\n if (isString(table)) {\n return parseAliasedTable(table);\n }\n else if (isAliasedDynamicTableBuilder(table)) {\n return table.toOperationNode();\n }\n else {\n return parseAliasedExpression(table);\n }\n}\nexport function parseAliasedTable(from) {\n const ALIAS_SEPARATOR = ' as ';\n if (from.includes(ALIAS_SEPARATOR)) {\n const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseTable(table), IdentifierNode.create(alias));\n }\n else {\n return parseTable(from);\n }\n}\nexport function parseTable(from) {\n const SCHEMA_SEPARATOR = '.';\n if (from.includes(SCHEMA_SEPARATOR)) {\n const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim);\n return TableNode.createWithSchema(schema, table);\n }\n else {\n return TableNode.create(from);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n","/// <reference types=\"./raw-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nclass RawBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isRawBuilder() {\n return true;\n }\n as(alias) {\n return new AliasedRawBuilderImpl(this, alias);\n }\n $castTo() {\n return new RawBuilderImpl({ ...this.#props });\n }\n $notNull() {\n return new RawBuilderImpl(this.#props);\n }\n withPlugin(plugin) {\n return new RawBuilderImpl({\n ...this.#props,\n plugins: this.#props.plugins !== undefined\n ? freeze([...this.#props.plugins, plugin])\n : freeze([plugin]),\n });\n }\n toOperationNode() {\n return this.#toOperationNode(this.#getExecutor());\n }\n compile(executorProvider) {\n return this.#compile(this.#getExecutor(executorProvider));\n }\n async execute(executorProvider) {\n const executor = this.#getExecutor(executorProvider);\n return executor.executeQuery(this.#compile(executor));\n }\n #getExecutor(executorProvider) {\n const executor = executorProvider !== undefined\n ? executorProvider.getExecutor()\n : NOOP_QUERY_EXECUTOR;\n return this.#props.plugins !== undefined\n ? executor.withPlugins(this.#props.plugins)\n : executor;\n }\n #toOperationNode(executor) {\n return executor.transformQuery(this.#props.rawNode, this.#props.queryId);\n }\n #compile(executor) {\n return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);\n }\n}\nexport function createRawBuilder(props) {\n return new RawBuilderImpl(props);\n}\nclass AliasedRawBuilderImpl {\n #rawBuilder;\n #alias;\n constructor(rawBuilder, alias) {\n this.#rawBuilder = rawBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#rawBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get rawBuilder() {\n return this.#rawBuilder;\n }\n toOperationNode() {\n return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./sql.d.ts\" />\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseValueExpression } from '../parser/value-parser.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createRawBuilder } from './raw-builder.js';\nexport const sql = Object.assign((sqlFragments, ...parameters) => {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []),\n });\n}, {\n ref(columnReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseStringReference(columnReference)),\n });\n },\n val(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseValueExpression(value)),\n });\n },\n value(value) {\n return this.val(value);\n },\n table(tableReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseTable(tableReference)),\n });\n },\n id(...ids) {\n const fragments = new Array(ids.length + 1).fill('.');\n fragments[0] = '';\n fragments[fragments.length - 1] = '';\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)),\n });\n },\n lit(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)),\n });\n },\n literal(value) {\n return this.lit(value);\n },\n raw(sql) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithSql(sql),\n });\n },\n join(array, separator = sql `, `) {\n const nodes = new Array(Math.max(2 * array.length - 1, 0));\n const sep = separator.toOperationNode();\n for (let i = 0; i < array.length; ++i) {\n nodes[2 * i] = parseParameter(array[i]);\n if (i !== array.length - 1) {\n nodes[2 * i + 1] = sep;\n }\n }\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChildren(nodes),\n });\n },\n});\nfunction parseParameter(param) {\n if (isOperationNodeSource(param)) {\n return param.toOperationNode();\n }\n return parseValueExpression(param);\n}\n","// Keeps a broken document from taking down the studio: a drive node can point\n// at a document the reactor no longer serves (deleted, or with unreadable\n// history), and the document hooks throw for it. Everything that renders such a\n// document goes inside a boundary so the failure stays in that one pane.\nimport { Component, Fragment, type ErrorInfo, type ReactNode } from \"react\";\n\n/** Best-effort message for anything thrown, without stringifying an object. */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n return \"Unknown error\";\n}\n\n/** Inline \"could not load\" panel, also used for hook-level (non-thrown) failures. */\nexport function DocumentLoadError(props: {\n title?: string;\n label?: string | null;\n documentId?: string | null;\n error: unknown;\n onRetry?: () => void;\n onDismiss?: () => void;\n}) {\n return (\n <div className=\"m-3 rounded border border-solid border-wf-fail/40 bg-wf-fail/10 p-3\">\n <p className=\"text-sm font-medium text-wf-fail\">\n {props.title ?? \"This document could not be loaded\"}\n </p>\n {props.label ? (\n <p className=\"mt-0.5 text-xs text-wf-fail\">{props.label}</p>\n ) : null}\n {props.documentId ? (\n <p className=\"mt-0.5 font-mono text-[11px] text-wf-fail\">\n {props.documentId}\n </p>\n ) : null}\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {errorMessage(props.error)}\n </p>\n <div className=\"mt-2 flex gap-2\">\n {props.onRetry ? (\n <button\n type=\"button\"\n className=\"rounded border border-solid border-wf-fail/40 px-2 py-0.5 text-xs font-medium text-wf-fail\"\n onClick={props.onRetry}\n >\n Retry\n </button>\n ) : null}\n {props.onDismiss ? (\n <button\n type=\"button\"\n className=\"rounded border border-solid border-foreground/15 px-2 py-0.5 text-xs text-muted-foreground\"\n onClick={props.onDismiss}\n >\n Dismiss\n </button>\n ) : null}\n </div>\n </div>\n );\n}\n\ntype Props = {\n /** Human-readable name of the node being rendered, when known. */\n label?: string | null;\n /** Document id, shown so a broken node can be identified in the drive. */\n documentId?: string | null;\n /** Called when the user dismisses the error (e.g. to close the pane). */\n onDismiss?: () => void;\n children: ReactNode;\n};\n\ntype State = { error: unknown; attempt: number };\n\nexport class DocumentErrorBoundary extends Component<Props, State> {\n state: State = { error: undefined, attempt: 0 };\n\n static getDerivedStateFromError(error: unknown): Partial<State> {\n return { error };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo) {\n console.error(\n `Failed to render document ${this.props.documentId ?? \"(unknown id)\"}:`,\n error,\n info.componentStack,\n );\n }\n\n private retry = () => {\n this.setState((state) => ({\n error: undefined,\n attempt: state.attempt + 1,\n }));\n };\n\n private dismiss = () => {\n this.setState({ error: undefined });\n this.props.onDismiss?.();\n };\n\n render() {\n if (this.state.error !== undefined) {\n return (\n <DocumentLoadError\n label={this.props.label}\n documentId={this.props.documentId}\n error={this.state.error}\n onRetry={this.retry}\n onDismiss={this.props.onDismiss ? this.dismiss : undefined}\n />\n );\n }\n // Remounting on retry drops the failed subtree's state and refetches.\n return <Fragment key={this.state.attempt}>{this.props.children}</Fragment>;\n }\n}\n","// Stroke icons on a 24px grid; they inherit colour from the text.\nconst ICON_PATHS = {\n pencil: \"M4 20h4L19 9l-4-4L4 16v4zM14 6l4 4\",\n trash: \"M5 7h14M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3\",\n plus: \"M12 5v14M5 12h14\",\n minus: \"M5 12h14\",\n list: \"M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01\",\n play: \"M7 5v14l12-7z\",\n chevron: \"M9 6l6 6-6 6\",\n chevronDown: \"M6 9l6 6 6-6\",\n retry: \"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4\",\n back: \"M15 6l-6 6 6 6\",\n close: \"M6 6l12 12M18 6L6 18\",\n check: \"M5 12l5 5 9-10\",\n search: \"M11 18a7 7 0 1 0 0-14 7 7 0 0 0 0 14zM20 20l-4-4\",\n braces:\n \"M8 4c-2 0-3 1-3 3v2c0 1.5-1 3-2 3 1 0 2 1.5 2 3v2c0 2 1 3 3 3M16 4c2 0 3 1 3 3v2c0 1.5 1 3 2 3-1 0-2 1.5-2 3v2c0 2-1 3-3 3\",\n link: \"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1\",\n arrowRight: \"M5 12h14M13 6l6 6-6 6\",\n alert:\n \"M12 8v5M12 16.5v.01M10.3 4l-7.6 13.2A2 2 0 0 0 4.4 20h15.2a2 2 0 0 0 1.7-2.8L13.7 4a2 2 0 0 0-3.4 0z\",\n copy: \"M9 9h10v10H9zM5 15V5h10\",\n sliders: \"M4 7h10M18 7h2M4 17h4M12 17h8M14 5v4M8 15v4\",\n eye: \"M2.5 12s3.5-6.5 9.5-6.5 9.5 6.5 9.5 6.5-3.5 6.5-9.5 6.5S2.5 12 2.5 12zM12 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z\",\n eyeOff:\n \"M3 3l18 18M10.6 5.6A10 10 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a17 17 0 0 1-3 3.7M6.6 6.6C4 8.3 2.5 12 2.5 12s3.5 6.5 9.5 6.5a9.6 9.6 0 0 0 4.4-1M9.9 9.9a3 3 0 0 0 4.2 4.2\",\n undo: \"M9 14L4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3\",\n redo: \"M15 14l5-5-5-5M20 9H10a6 6 0 0 0 0 12h3\",\n clock: \"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 7v5l3 2\",\n bolt: \"M13 3L5 13h6l-1 8 8-10h-6l1-8z\",\n branch:\n \"M6 4v10M6 14a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM18 4a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM18 10c0 4-6 3-11 6\",\n lock: \"M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 7 0v3M12 15v2\",\n more: \"M5 11a1 1 0 1 0 0 2 1 1 0 0 0 0-2zM12 11a1 1 0 1 0 0 2 1 1 0 0 0 0-2zM19 11a1 1 0 1 0 0 2 1 1 0 0 0 0-2z\",\n archive: \"M4 5h16v4H4zM6 9v10h12V9M10 13h4\",\n};\n\nexport type IconName = keyof typeof ICON_PATHS;\n\n// A piece names icons by string; only the ones this set draws are shown.\nexport function isIconName(name: unknown): name is IconName {\n return typeof name === \"string\" && name in ICON_PATHS;\n}\n\nexport function Icon(props: {\n name: IconName;\n className?: string;\n // Pixel size; otherwise 16px, overridable through className.\n size?: number;\n}) {\n return (\n <svg\n aria-hidden\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={1.75}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n width={props.size}\n height={props.size}\n className={`shrink-0 ${props.size ? \"\" : \"h-4 w-4\"} ${props.className ?? \"\"}`}\n >\n <path d={ICON_PATHS[props.name]} />\n </svg>\n );\n}\n","// Form and action primitives for the workflow editors, drawn from Connect's\n// theme tokens so they work in both themes.\nimport {\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ButtonHTMLAttributes,\n type KeyboardEvent,\n type ReactNode,\n type Ref,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { Icon, type IconName } from \"./icons.js\";\n\nconst FOCUS_RING =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\n\n// ─── buttons ────────────────────────────────────────────────────────────────\n\nconst BUTTON_SIZE = {\n sm: \"h-7 gap-1 rounded-md px-2 text-xs\",\n md: \"h-8 gap-1.5 rounded-md px-3 text-[13px]\",\n};\n\nconst BUTTON_VARIANT = {\n primary: \"bg-primary text-primary-foreground hover:opacity-90\",\n secondary:\n \"border border-solid border-foreground/15 bg-card text-foreground hover:bg-accent\",\n ghost: \"text-muted-foreground hover:bg-accent hover:text-foreground\",\n danger: \"text-wf-fail hover:bg-wf-fail/10\",\n destructive: \"bg-wf-fail text-white hover:opacity-90\",\n};\n\nexport function Button(\n props: ButtonHTMLAttributes<HTMLButtonElement> & {\n ref?: Ref<HTMLButtonElement>;\n variant?: keyof typeof BUTTON_VARIANT;\n size?: keyof typeof BUTTON_SIZE;\n },\n) {\n const { variant = \"secondary\", size = \"md\", className = \"\", ...rest } = props;\n return (\n <button\n type=\"button\"\n className={`inline-flex shrink-0 items-center font-medium transition-colors disabled:pointer-events-none disabled:opacity-50 ${FOCUS_RING} ${BUTTON_SIZE[size]} ${BUTTON_VARIANT[variant]} ${className}`}\n {...rest}\n />\n );\n}\n\nexport function IconButton(\n props: ButtonHTMLAttributes<HTMLButtonElement> & {\n icon: IconName;\n label: string;\n active?: boolean;\n },\n) {\n const { icon, label, active, className = \"\", ...rest } = props;\n return (\n <button\n type=\"button\"\n title={label}\n aria-label={label}\n className={`inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-colors disabled:pointer-events-none disabled:opacity-50 ${FOCUS_RING} ${\n active\n ? \"bg-wf-run/10 text-wf-run\"\n : \"text-muted-foreground hover:bg-accent hover:text-foreground\"\n } ${className}`}\n {...rest}\n >\n <Icon name={icon} className=\"h-3.5 w-3.5\" />\n </button>\n );\n}\n\n// ─── fields ─────────────────────────────────────────────────────────────────\n\nexport const inputClass =\n \"w-full rounded-md border border-solid border-foreground/15 bg-card px-2.5 text-[13px] text-foreground placeholder:text-muted-foreground/70 transition-colors hover:border-foreground/25 focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/25 disabled:cursor-not-allowed disabled:opacity-60\";\n\nexport const textInputClass = `${inputClass} h-9`;\nexport const textAreaClass = `${inputClass} min-h-20 py-2 leading-relaxed`;\nexport const invalidClass = \"border-wf-warn/70 hover:border-wf-warn\";\n\n/** Label row above a control: name, optional marker, and a trailing action. */\nexport function FieldLabel(props: {\n htmlFor?: string;\n label: ReactNode;\n optional?: boolean;\n needsValue?: boolean;\n action?: ReactNode;\n}) {\n // A <label> only when pointed at a control; callers that wrap the control\n // in their own <label> get a span, so labels never nest.\n const LabelTag = props.htmlFor ? \"label\" : \"span\";\n return (\n <div className=\"mb-1.5 flex min-h-6 items-center justify-between gap-2\">\n <LabelTag\n htmlFor={props.htmlFor}\n className=\"flex min-w-0 items-baseline gap-1.5 text-[13px] font-medium text-foreground\"\n >\n <span className=\"truncate\">{props.label}</span>\n {props.optional ? (\n <span className=\"shrink-0 text-xs font-normal text-muted-foreground\">\n Optional\n </span>\n ) : null}\n {props.needsValue ? (\n <span className=\"shrink-0 text-xs font-normal text-wf-warn\">\n Needs a value\n </span>\n ) : null}\n </LabelTag>\n {props.action ? (\n <span className=\"flex shrink-0 items-center gap-0.5\">\n {props.action}\n </span>\n ) : null}\n </div>\n );\n}\n\nconst LONG_HINT = 140;\n\n/** Help text under a control; long piece descriptions fold to two lines. */\nexport function Hint(props: { children?: ReactNode; text?: string }) {\n const [open, setOpen] = useState(false);\n const text = props.text;\n if (text !== undefined) {\n if (!text.trim()) return null;\n const long = text.length > LONG_HINT;\n return (\n <p className=\"mt-1.5 text-xs leading-relaxed text-muted-foreground\">\n <span className={long && !open ? \"line-clamp-2\" : undefined}>\n {text}\n </span>\n {long ? (\n <button\n type=\"button\"\n className=\"mt-0.5 block font-medium text-foreground/70 hover:text-foreground\"\n onClick={() => setOpen((value) => !value)}\n >\n {open ? \"Show less\" : \"Show more\"}\n </button>\n ) : null}\n </p>\n );\n }\n return (\n <p className=\"mt-1.5 text-xs leading-relaxed text-muted-foreground\">\n {props.children}\n </p>\n );\n}\n\nexport function FieldError(props: { children?: ReactNode }) {\n if (!props.children) return null;\n return <p className=\"mt-1.5 text-xs text-wf-fail\">{props.children}</p>;\n}\n\nexport function Switch(props: {\n checked: boolean;\n onChange: (checked: boolean) => void;\n label: ReactNode;\n description?: string;\n disabled?: boolean;\n}) {\n const id = useId();\n return (\n <div className=\"flex items-start justify-between gap-4\">\n <label htmlFor={id} className=\"min-w-0\">\n <span className=\"block text-[13px] font-medium text-foreground\">\n {props.label}\n </span>\n {props.description ? <Hint text={props.description} /> : null}\n </label>\n <button\n id={id}\n type=\"button\"\n role=\"switch\"\n aria-checked={props.checked}\n disabled={props.disabled}\n className={`relative mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors disabled:opacity-50 ${FOCUS_RING} ${\n props.checked ? \"bg-primary\" : \"bg-foreground/20\"\n }`}\n onClick={() => props.onChange(!props.checked)}\n >\n <span\n className={`inline-block h-4 w-4 rounded-full bg-card shadow-sm transition-transform ${\n props.checked ? \"translate-x-[18px]\" : \"translate-x-0.5\"\n }`}\n />\n </button>\n </div>\n );\n}\n\n// A bare switch for toolbars; the label is for assistive tech and the title.\nexport function Toggle(props: {\n checked: boolean;\n onChange: (checked: boolean) => void;\n label: string;\n disabled?: boolean;\n}) {\n return (\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={props.checked}\n aria-label={props.label}\n disabled={props.disabled}\n className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${FOCUS_RING} ${\n props.checked ? \"bg-wf-ok\" : \"bg-foreground/20\"\n }`}\n onClick={(event) => {\n event.stopPropagation();\n props.onChange(!props.checked);\n }}\n >\n <span\n className={`inline-block h-4 w-4 rounded-full bg-card shadow-sm transition-transform ${\n props.checked ? \"translate-x-[18px]\" : \"translate-x-0.5\"\n }`}\n />\n </button>\n );\n}\n\n// Shows `content` on hover or focus; it stays open while the pointer is on it,\n// so it can hold a link. Disabled controls inside still trigger it.\nexport function Tooltip(props: {\n content: ReactNode;\n children: ReactNode;\n // Off renders the children alone.\n enabled?: boolean;\n align?: \"start\" | \"end\";\n // Left of the control, for rows inside a clipping container.\n side?: \"below\" | \"left\";\n}) {\n if (props.enabled === false) return <>{props.children}</>;\n const place =\n props.side === \"left\"\n ? \"right-full top-1/2 -translate-y-1/2 pr-1.5\"\n : `top-full pt-1.5 ${props.align === \"start\" ? \"left-0\" : \"right-0\"}`;\n return (\n <span className=\"group/tip relative inline-flex\">\n {props.children}\n <span\n className={`invisible absolute z-50 opacity-0 transition-opacity group-focus-within/tip:visible group-focus-within/tip:opacity-100 group-hover/tip:visible group-hover/tip:opacity-100 ${place}`}\n >\n <span\n role=\"tooltip\"\n className=\"block w-max max-w-64 rounded-md border border-solid border-foreground/10 bg-card px-2.5 py-1.5 text-xs text-foreground shadow-lg\"\n >\n {props.content}\n </span>\n </span>\n </span>\n );\n}\n\n// ─── tabs ───────────────────────────────────────────────────────────────────\n\nexport function Tabs<T extends string>(props: {\n value: T;\n onChange: (value: T) => void;\n tabs: { value: T; label: string; badge?: ReactNode }[];\n}) {\n return (\n <div role=\"tablist\" className=\"flex gap-4\">\n {props.tabs.map((tab) => {\n const selected = tab.value === props.value;\n return (\n <button\n key={tab.value}\n type=\"button\"\n role=\"tab\"\n aria-selected={selected}\n className={`-mb-px flex items-center gap-1.5 border-b-2 border-solid pb-2 text-[13px] font-medium transition-colors ${FOCUS_RING} ${\n selected\n ? \"border-foreground text-foreground\"\n : \"border-transparent text-muted-foreground hover:text-foreground\"\n }`}\n onClick={() => props.onChange(tab.value)}\n >\n {tab.label}\n {tab.badge}\n </button>\n );\n })}\n </div>\n );\n}\n\n// ─── segmented ──────────────────────────────────────────────────────────────\n\n/** Two or three short, mutually exclusive choices shown side by side. */\nexport function Segmented(props: {\n value: string;\n options: { value: string; label: string }[];\n onChange: (value: string) => void;\n invalid?: boolean;\n}) {\n return (\n <div\n role=\"radiogroup\"\n className={`flex h-9 w-full items-center gap-0.5 rounded-md bg-muted p-0.5 ${\n props.invalid ? \"ring-1 ring-wf-warn/60\" : \"\"\n }`}\n >\n {props.options.map((option) => {\n const selected = option.value === props.value;\n return (\n <button\n key={option.value}\n type=\"button\"\n role=\"radio\"\n aria-checked={selected}\n className={`h-8 min-w-0 flex-1 truncate rounded px-2 text-[13px] transition-colors ${FOCUS_RING} ${\n selected\n ? \"bg-card font-medium text-foreground shadow-sm\"\n : \"text-muted-foreground hover:text-foreground\"\n }`}\n onClick={() => props.onChange(option.value)}\n >\n {option.label}\n </button>\n );\n })}\n </div>\n );\n}\n\n// ─── select ─────────────────────────────────────────────────────────────────\n\nexport interface SelectOption {\n value: string;\n label: string;\n description?: string;\n icon?: ReactNode;\n disabled?: boolean;\n}\n\n// Past this many options the list gets a search box.\nconst SEARCH_THRESHOLD = 7;\n\ninterface SelectProps {\n options: SelectOption[];\n placeholder?: string;\n loading?: boolean;\n disabled?: boolean;\n invalid?: boolean;\n id?: string;\n // Names the control when no <label> points at it.\n ariaLabel?: string;\n // Reloads options from their source; shown in the list header.\n onRefresh?: () => void;\n emptyText?: string;\n // Always show the search box, not only once the list is long.\n searchable?: boolean;\n // Search happens at the source: every keystroke is reported, and the list\n // shown is the options given, unfiltered.\n onQueryChange?: (query: string) => void;\n // Extra actions at the foot of the list; each closes it when chosen.\n actions?: SelectAction[];\n // Shown for a value the options don't list yet, instead of the raw value.\n valueLabel?: ReactNode;\n}\n\nexport interface SelectAction {\n label: string;\n icon?: IconName;\n onSelect: () => void;\n}\n\ntype SingleSelectProps = SelectProps & {\n multiple?: false;\n value: string;\n onChange: (value: string) => void;\n clearable?: boolean;\n};\n\ntype MultiSelectProps = SelectProps & {\n multiple: true;\n value: string[];\n onChange: (value: string[]) => void;\n};\n\n// A listbox in a popover, portalled to the body so a scrolling side panel\n// never clips it; searchable once the list is long.\nexport function Select(props: SingleSelectProps | MultiSelectProps) {\n const [open, setOpen] = useState(false);\n const [query, setQuery] = useState(\"\");\n const [active, setActive] = useState(0);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const popoverRef = useRef<HTMLDivElement>(null);\n const searchRef = useRef<HTMLInputElement>(null);\n const listId = useId();\n const [position, setPosition] = useState<{\n left: number;\n width: number;\n top?: number;\n bottom?: number;\n maxHeight: number;\n } | null>(null);\n\n const selected = props.multiple\n ? props.value\n : props.value\n ? [props.value]\n : [];\n const selectedSet = new Set(selected);\n const searchable =\n props.searchable ||\n Boolean(props.onQueryChange) ||\n props.options.length > SEARCH_THRESHOLD;\n const needle = query.trim().toLowerCase();\n const serverSide = Boolean(props.onQueryChange);\n const visible = useMemo(\n () =>\n needle && !serverSide\n ? props.options.filter((option) =>\n `${option.label} ${option.description ?? \"\"}`\n .toLowerCase()\n .includes(needle),\n )\n : props.options,\n [needle, props.options, serverSide],\n );\n\n const onQueryChange = props.onQueryChange;\n // Closing also ends a source search, so the next opening starts unfiltered.\n const dismiss = () => {\n setOpen(false);\n setQuery(\"\");\n onQueryChange?.(\"\");\n };\n\n const close = () => {\n dismiss();\n triggerRef.current?.focus();\n };\n\n const place = () => {\n const rect = triggerRef.current?.getBoundingClientRect();\n if (!rect) return;\n const below = window.innerHeight - rect.bottom - 8;\n const above = rect.top - 8;\n const flip = below < 240 && above > below;\n setPosition({\n left: rect.left,\n width: rect.width,\n top: flip ? undefined : rect.bottom + 4,\n bottom: flip ? window.innerHeight - rect.top + 4 : undefined,\n maxHeight: Math.min(320, flip ? above : below),\n });\n };\n\n const openList = () => {\n const index = props.options.findIndex((option) =>\n selectedSet.has(option.value),\n );\n setActive(Math.max(0, index));\n setOpen(true);\n };\n\n useLayoutEffect(() => {\n if (!open) return;\n place();\n // Placed once per opening; scroll and resize re-place it below.\n }, [open]);\n\n // The popover mounts once placed; a long list then takes focus in its search\n // box, a short one leaves focus on the trigger, which handles the keys.\n const placed = position !== null;\n useEffect(() => {\n if (open && placed && searchable) searchRef.current?.focus();\n }, [open, placed, searchable]);\n\n useEffect(() => {\n if (!open) return;\n const onPointer = (event: MouseEvent) => {\n const target = event.target as globalThis.Node;\n if (\n !popoverRef.current?.contains(target) &&\n !triggerRef.current?.contains(target)\n ) {\n setOpen(false);\n setQuery(\"\");\n onQueryChange?.(\"\");\n }\n };\n window.addEventListener(\"mousedown\", onPointer);\n window.addEventListener(\"resize\", place);\n window.addEventListener(\"scroll\", place, true);\n return () => {\n window.removeEventListener(\"mousedown\", onPointer);\n window.removeEventListener(\"resize\", place);\n window.removeEventListener(\"scroll\", place, true);\n };\n }, [open, searchable, onQueryChange]);\n\n useEffect(() => {\n popoverRef.current\n ?.querySelector(`[data-index=\"${active}\"]`)\n ?.scrollIntoView({ block: \"nearest\" });\n }, [active]);\n\n const choose = (option: SelectOption) => {\n if (option.disabled) return;\n if (props.multiple) {\n props.onChange(\n selectedSet.has(option.value)\n ? props.value.filter((value) => value !== option.value)\n : [...props.value, option.value],\n );\n return;\n }\n props.onChange(option.value);\n close();\n };\n\n const onListKey = (event: KeyboardEvent) => {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n setActive((index) => Math.min(visible.length - 1, index + 1));\n } else if (event.key === \"ArrowUp\") {\n event.preventDefault();\n setActive((index) => Math.max(0, index - 1));\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n const option = visible[active] as SelectOption | undefined;\n if (option) choose(option);\n } else if (event.key === \"Escape\") {\n event.preventDefault();\n close();\n } else if (event.key === \"Tab\") {\n // Let focus move on as usual.\n dismiss();\n }\n };\n\n const labels = props.options\n .filter((option) => selectedSet.has(option.value))\n .map((option) => option.label);\n // A saved value the current options don't list still shows as itself.\n const unknown = selected.filter(\n (value) => !props.options.some((option) => option.value === value),\n );\n const shown = [...labels, ...unknown];\n const selectedIcon = props.multiple\n ? undefined\n : props.options.find((option) => option.value === props.value)?.icon;\n\n return (\n <>\n <button\n ref={triggerRef}\n id={props.id}\n aria-label={props.ariaLabel}\n type=\"button\"\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={open ? listId : undefined}\n aria-activedescendant={\n open && visible.length > 0 ? `${listId}-${active}` : undefined\n }\n aria-haspopup=\"listbox\"\n disabled={props.disabled}\n className={`${textInputClass} flex items-center gap-2 text-left ${\n props.invalid ? invalidClass : \"\"\n } ${open ? \"border-ring ring-2 ring-ring/25\" : \"\"}`}\n onClick={() => (open ? close() : openList())}\n onKeyDown={(event) => {\n if (open) {\n onListKey(event);\n return;\n }\n if (\n event.key === \"ArrowDown\" ||\n event.key === \"Enter\" ||\n event.key === \" \"\n ) {\n event.preventDefault();\n openList();\n }\n }}\n >\n {selectedIcon}\n <span\n className={`min-w-0 flex-1 truncate ${shown.length ? \"\" : \"text-muted-foreground/70\"}`}\n >\n {labels.length === 0 &&\n unknown.length > 0 &&\n props.valueLabel !== undefined\n ? props.valueLabel\n : shown.length > 0\n ? shown.join(\", \")\n : props.loading\n ? \"Loading…\"\n : (props.placeholder ?? \"Choose…\")}\n </span>\n {props.multiple && shown.length > 1 ? (\n <span className=\"shrink-0 rounded bg-muted px-1.5 text-[11px] tabular-nums text-muted-foreground\">\n {shown.length}\n </span>\n ) : null}\n <Icon\n name=\"chevronDown\"\n className={`h-3.5 w-3.5 text-muted-foreground transition-transform ${open ? \"rotate-180\" : \"\"}`}\n />\n </button>\n {open && position\n ? createPortal(\n <div\n ref={popoverRef}\n tabIndex={-1}\n className=\"workflow-select-popover fixed flex flex-col overflow-hidden rounded-lg border border-solid border-foreground/10 bg-popover text-popover-foreground shadow-lg outline-none\"\n style={{\n left: position.left,\n width: Math.max(position.width, 220),\n top: position.top,\n bottom: position.bottom,\n maxHeight: position.maxHeight,\n }}\n onKeyDown={onListKey}\n >\n {searchable || props.onRefresh ? (\n <div className=\"flex items-center gap-1 border-b border-solid border-foreground/10 px-2\">\n {searchable ? (\n <>\n <Icon\n name=\"search\"\n className=\"h-3.5 w-3.5 text-muted-foreground\"\n />\n <input\n ref={searchRef}\n className=\"h-9 min-w-0 flex-1 bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/70 focus:outline-none\"\n placeholder=\"Search\"\n value={query}\n onChange={(event) => {\n setQuery(event.target.value);\n setActive(0);\n props.onQueryChange?.(event.target.value);\n }}\n />\n </>\n ) : (\n <span className=\"h-9 flex-1\" />\n )}\n {props.onRefresh ? (\n <IconButton\n icon=\"retry\"\n label=\"Reload options\"\n disabled={props.loading}\n onClick={props.onRefresh}\n />\n ) : null}\n </div>\n ) : null}\n <div\n id={listId}\n role=\"listbox\"\n aria-multiselectable={props.multiple || undefined}\n className=\"min-h-0 flex-1 overflow-y-auto p-1\"\n >\n {props.loading && props.options.length === 0 ? (\n <p className=\"px-2 py-2 text-[13px] text-muted-foreground\">\n Loading options…\n </p>\n ) : visible.length === 0 ? (\n <p className=\"px-2 py-2 text-[13px] text-muted-foreground\">\n {needle\n ? \"Nothing matches.\"\n : (props.emptyText ?? \"No options.\")}\n </p>\n ) : (\n visible.map((option, index) => {\n const isSelected = selectedSet.has(option.value);\n return (\n <div\n key={option.value}\n id={`${listId}-${index}`}\n role=\"option\"\n aria-selected={isSelected}\n aria-disabled={option.disabled || undefined}\n data-index={index}\n className={`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-[13px] ${\n index === active ? \"bg-accent\" : \"\"\n } ${option.disabled ? \"cursor-not-allowed opacity-50\" : \"\"}`}\n onMouseEnter={() => setActive(index)}\n onMouseDown={(event) => {\n event.preventDefault();\n choose(option);\n }}\n >\n {props.multiple ? (\n <span\n className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border border-solid ${\n isSelected\n ? \"border-primary bg-primary text-primary-foreground\"\n : \"border-foreground/25\"\n }`}\n >\n {isSelected ? (\n <Icon name=\"check\" className=\"h-3 w-3\" />\n ) : null}\n </span>\n ) : null}\n {option.icon}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate\">{option.label}</span>\n {option.description ? (\n <span className=\"block truncate text-xs text-muted-foreground\">\n {option.description}\n </span>\n ) : null}\n </span>\n {!props.multiple && isSelected ? (\n <Icon\n name=\"check\"\n className=\"h-3.5 w-3.5 text-foreground\"\n />\n ) : null}\n </div>\n );\n })\n )}\n </div>\n {props.actions?.length ? (\n <div className=\"border-t border-solid border-foreground/10 p-1\">\n {props.actions.map((action) => (\n <button\n key={action.label}\n type=\"button\"\n className=\"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground\"\n onMouseDown={(event) => {\n event.preventDefault();\n dismiss();\n action.onSelect();\n }}\n >\n {action.icon ? (\n <Icon name={action.icon} className=\"h-3.5 w-3.5\" />\n ) : null}\n {action.label}\n </button>\n ))}\n </div>\n ) : null}\n {!props.multiple && props.clearable && props.value ? (\n <div className=\"border-t border-solid border-foreground/10 p-1\">\n {\n <button\n type=\"button\"\n className=\"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground\"\n onMouseDown={(event) => {\n event.preventDefault();\n props.onChange(\"\");\n close();\n }}\n >\n <Icon name=\"close\" className=\"h-3.5 w-3.5\" />\n Clear selection\n </button>\n }\n </div>\n ) : null}\n </div>,\n document.body,\n )\n : null}\n </>\n );\n}\n","// Editor view state kept in the URL's query params through the host navigation,\n// so it survives a refresh and is dropped when the document is left.\nimport type { PHSearchUpdate } from \"@powerhousedao/reactor-browser\";\nimport {\n useSearchParams,\n useSetSearchParams,\n} from \"@powerhousedao/reactor-browser\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** The studio's sidebar selection. */\nexport const ITEM_PARAM = \"item\";\n\nexport type SetParam<T extends string> = (\n value: T,\n options?: { replace?: boolean; also?: PHSearchUpdate },\n) => void;\n\n/** A query param read as one of `allowed`, else `fallback`; the fallback is\n * kept out of the URL. `also` updates other params in the same entry. */\nexport function useSearchParam<T extends string>(\n key: string,\n fallback: T,\n allowed?: readonly T[],\n): [T, SetParam<T>] {\n const params = useSearchParams();\n const setParams = useSetSearchParams();\n const raw = params[key] as string | undefined;\n const value =\n raw !== undefined && (!allowed || allowed.includes(raw as T))\n ? (raw as T)\n : fallback;\n\n const set = useCallback<SetParam<T>>(\n (next, options) => {\n if (next === value && !options?.also) return;\n setParams(\n { ...options?.also, [key]: next === fallback ? undefined : next },\n { replace: options?.replace },\n );\n },\n [key, fallback, value, setParams],\n );\n return [value, set];\n}\n\n/** A text param with a local draft, so typing never waits on a navigation;\n * the draft follows other URL changes, e.g. back and forward. */\nexport function useSearchParamDraft(\n key: string,\n): [string, (value: string) => void] {\n const [param, setParam] = useSearchParam<string>(key, \"\");\n const [draft, setDraft] = useState(param);\n // Values written from the draft, in order; their arrival in the URL is no\n // change, and drops those written before it that the URL skipped.\n const written = useRef<string[]>([]);\n\n useEffect(() => {\n const index = written.current.indexOf(param);\n written.current = index === -1 ? [] : written.current.slice(index + 1);\n if (index === -1) setDraft(param);\n }, [param]);\n\n const set = useCallback(\n (value: string) => {\n setDraft(value);\n if (value === param) return;\n written.current.push(value);\n setParam(value, { replace: true });\n },\n [param, setParam],\n );\n return [draft, set];\n}\n","// Browser cache for runtime data that is the same for every caller: the piece\n// catalog and piece block forms. Nothing caller-scoped is ever written.\nimport type { Query, QueryClient, QueryKey } from \"@tanstack/react-query\";\nimport { CORE_PIECE_NAME } from \"@powerhousedao/pieces-framework/workflow\";\nimport { queryKind } from \"./ui/query-keys.js\";\n\n// Bump when the cached shapes, or how forms are derived, change.\nexport const RUNTIME_CACHE_VERSION = 2;\nexport const RUNTIME_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60_000;\n\nexport interface PersistedQuery {\n id: string;\n url: string;\n queryKey: QueryKey;\n data: unknown;\n updatedAt: number;\n version: number;\n}\n\nexport interface RuntimeCacheStore {\n load: (url: string) => Promise<PersistedQuery[]>;\n save: (entry: PersistedQuery) => Promise<void>;\n remove: (id: string) => Promise<void>;\n}\n\nexport function shouldPersistQuery(queryKey: QueryKey): boolean {\n if (typeof queryKey[0] !== \"string\") return false;\n const kind = queryKind(queryKey);\n if (kind === \"catalog\") return queryKey.length === 2;\n if (kind === \"form\") {\n const block = queryKey[2];\n // Core forms change with each reactor build; never pin a copy.\n return Array.isArray(block) && block[0] !== CORE_PIECE_NAME;\n }\n return false;\n}\n\n// Hydrates `url`'s entries, then writes every persistable fetch back.\nexport function persistRuntimeQueries(\n queryClient: QueryClient,\n url: string,\n store: RuntimeCacheStore | null,\n now: () => number = Date.now,\n): { ready: Promise<void>; dispose: () => void } {\n if (!store) return { ready: Promise.resolve(), dispose: () => undefined };\n const ready = hydrate(queryClient, url, store, now());\n const unsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type !== \"updated\" || event.action.type !== \"success\") return;\n // Manual writes are hydration or optimistic updates, not fetches.\n if (event.action.manual) return;\n const query = event.query as Query<unknown, Error, unknown, QueryKey>;\n const { queryKey, state } = query;\n if (!shouldPersistQuery(queryKey) || state.data === undefined) return;\n store\n .save({\n id: JSON.stringify(queryKey),\n url: queryKey[0] as string,\n queryKey,\n data: state.data,\n updatedAt: state.dataUpdatedAt,\n version: RUNTIME_CACHE_VERSION,\n })\n .catch(() => undefined);\n });\n return { ready, dispose: unsubscribe };\n}\n\nasync function hydrate(\n queryClient: QueryClient,\n url: string,\n store: RuntimeCacheStore,\n at: number,\n): Promise<void> {\n let entries: PersistedQuery[];\n try {\n entries = await store.load(url);\n } catch {\n return;\n }\n for (const entry of entries) {\n const expired =\n entry.version !== RUNTIME_CACHE_VERSION ||\n at - entry.updatedAt > RUNTIME_CACHE_MAX_AGE_MS ||\n !shouldPersistQuery(entry.queryKey);\n if (expired) {\n store.remove(entry.id).catch(() => undefined);\n continue;\n }\n const current = queryClient.getQueryState(entry.queryKey);\n // A fetch that landed first is newer than anything on disk.\n if (current && current.dataUpdatedAt >= entry.updatedAt) continue;\n queryClient.setQueryData(entry.queryKey, entry.data, {\n updatedAt: entry.updatedAt,\n });\n }\n}\n\nconst DB_NAME = \"ph-workflow-runtime-cache\";\nconst STORE = \"queries\";\n\nfunction request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req.result);\n req.onerror = () =>\n reject(req.error ?? new Error(\"IndexedDB request failed\"));\n });\n}\n\n// Null when the browser has no IndexedDB; every call rejects when it throws.\nexport function openIdbCacheStore(): RuntimeCacheStore | null {\n const idb = (globalThis as { indexedDB?: IDBFactory }).indexedDB;\n if (!idb) return null;\n let db: Promise<IDBDatabase> | undefined;\n const open = () => {\n db ??= new Promise<IDBDatabase>((resolve, reject) => {\n const req = idb.open(DB_NAME, 1);\n req.onupgradeneeded = () => {\n const store = req.result.createObjectStore(STORE, { keyPath: \"id\" });\n store.createIndex(\"url\", \"url\");\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () =>\n reject(req.error ?? new Error(\"IndexedDB unavailable\"));\n req.onblocked = () => reject(new Error(\"IndexedDB blocked\"));\n });\n db.catch(() => (db = undefined));\n return db;\n };\n const withStore = async <T>(\n mode: IDBTransactionMode,\n run: (store: IDBObjectStore) => IDBRequest<T>,\n ): Promise<T> => {\n const database = await open();\n return request(run(database.transaction(STORE, mode).objectStore(STORE)));\n };\n return {\n load: (url) =>\n withStore(\"readonly\", (store) =>\n store.index(\"url\").getAll(url),\n ) as Promise<PersistedQuery[]>,\n save: (entry) =>\n withStore(\"readwrite\", (store) => store.put(entry)).then(() => undefined),\n remove: (id) =>\n withStore(\"readwrite\", (store) => store.delete(id)).then(() => undefined),\n };\n}\n","// Catalog source for the block selector's piece browser. Provided by the\n// editor shell's RuntimeProvider through context, to keep ui/ decoupled.\nimport { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\nimport { createContext, useContext } from \"react\";\n\nexport interface PieceSummaryUi {\n name: string;\n displayName: string;\n description: string;\n logoUrl: string;\n actionCount: number;\n triggerCount: number;\n // Activepieces category ids; empty for uncategorised pieces.\n categories: string[];\n // Absent from older runtimes, which list Activepieces pieces only.\n source?: PieceSourceKind;\n // Why none of the piece's blocks can run on this reactor.\n unsupported?: string | null;\n // Retired by its publisher: still listed, marked as such.\n deprecated?: boolean;\n // The installed version; pins the blocks picked from it.\n version?: string;\n // A local package shadowing a published piece: the version published.\n publishedVersion?: string;\n}\n\nexport interface BlockSearchHitUi {\n pieceName: string;\n pieceVersion: string;\n // The action or trigger name.\n name: string;\n pieceDisplayName: string;\n logoUrl: string;\n displayName: string;\n description: string;\n kind: \"action\" | \"trigger\";\n strategy: string | null;\n unsupported?: string | null;\n}\n\n// Where a piece is listed from: a reactor package, the Powerhouse registry,\n// or the Activepieces cloud catalog.\nexport type PieceSourceKind = \"local\" | \"registry\" | \"activepieces\";\n\nexport interface PieceSearchMatchUi {\n pieceName: string;\n pieceVersion: string;\n displayName: string;\n description: string;\n logoUrl: string;\n categories: string[];\n source: PieceSourceKind;\n deprecated?: boolean | null;\n unsupported?: string | null;\n // Every query token matched the piece's own name.\n namedPiece: boolean;\n // Matching blocks, best first.\n blocks: BlockSearchHitUi[];\n}\n\nexport interface PieceSearchResultUi {\n status: \"ready\" | \"indexing\" | \"error\";\n pieces: PieceSearchMatchUi[];\n error: string | null;\n}\n\nexport interface PieceSearchFilterUi {\n kind: \"action\" | \"trigger\";\n // Any of; all when absent.\n sources?: readonly PieceSourceKind[];\n // Category ids, any of; all when absent.\n categories?: readonly string[];\n}\n\n// One action of a piece, at the version its listing answered with.\nexport interface PieceActionUi {\n pieceName: string;\n pieceVersion: string;\n name: string;\n displayName: string;\n description: string;\n unsupported?: string | null;\n}\n\nexport interface PieceTriggerUi {\n pieceName: string;\n pieceVersion: string;\n name: string;\n displayName: string;\n description: string;\n // Read through checkTriggerStrategy.\n strategy: string;\n unsupported?: string | null;\n}\n\n// Why a listed block cannot be picked, or undefined when it can: the\n// runtime's own reason first, then a trigger strategy it cannot serve.\nexport function blockUnavailable(entry: {\n unsupported?: string | null;\n kind?: \"action\" | \"trigger\";\n strategy?: string | null;\n}): string | undefined {\n if (entry.unsupported) return entry.unsupported;\n if (entry.kind !== \"trigger\") return undefined;\n const strategy = checkTriggerStrategy(entry.strategy);\n return \"issue\" in strategy ? strategy.issue : undefined;\n}\n\nexport interface PieceCatalogSource {\n loadCatalog: () => Promise<PieceSummaryUi[]>;\n // Refetches past any cached answer; loadCatalog is used when absent.\n reloadCatalog?: () => Promise<PieceSummaryUi[]>;\n loadActions: (packageName: string) => Promise<PieceActionUi[]>;\n loadTriggers: (packageName: string) => Promise<PieceTriggerUi[]>;\n // Catalog-wide search grouped by piece; optional for offline sources.\n searchPieces?: (\n query: string,\n filter: PieceSearchFilterUi,\n ) => Promise<PieceSearchResultUi>;\n}\n\nconst PieceSourceContext = createContext<PieceCatalogSource | undefined>(\n undefined,\n);\n\nexport const PieceSourceProvider = PieceSourceContext.Provider;\n\nexport function usePieceSource(): PieceCatalogSource | undefined {\n return useContext(PieceSourceContext);\n}\n","import { B as withDeadline, F as TIMED_OUT, I as delay, V as yieldToMain, _ as acquirePurgeLocks, k as AppendConditionFailedError, v as findPurged } from \"./forwarding-logger-D-blgfWu.js\";\nimport { B as DocumentDeletedError, C as createOperation, D as refusalError, E as jobWriteIds, G as GroupInUseError, H as DocumentNotFoundError, K as InvalidOperationTimestampError, L as AuthTimestampNotMonotonicError, M as updateDocumentRevision, N as writeIdentityRows, O as relationshipTarget, Q as UnsupportedProtocolVersionError, R as AuthorizationDeniedError, T as isGenesisOperation, U as DocumentPurgedError, V as DocumentNotDeletedError, W as ExcessiveReshuffleError, Y as PurgeTooLargeError, Z as ReservedActionError, _ as applyUpgradeDocumentAction$1, d as DOCUMENT_SCOPE_ACTIONS, et as UpgradePreconditionFailedError, f as FencedWriteCache, g as applyDeleteDocumentAction$1, h as TouchedStreams, j as targetDocumentId, k as submittedActionIds, m as PurgeFence, p as GATED_DOCUMENT_ACTIONS, q as InvalidSignatureError, u as ReactorEventTypes, v as buildErrorResult, w as getNextIndexForScope, x as createDocumentFromAction, y as buildSuccessResult } from \"./load-spec-BS34dxCu.js\";\nimport { a as isCursorProtectedLoad } from \"./types-D-o5gygj.js\";\nimport { AUTH_ACTION_TYPES, AUTH_DENIED_BY_GRANT_REASON, AUTH_NO_GRANT_REASON, AUTH_VERSION_UNSUPPORTED_REASON, DOCUMENT_DELETED_REASON, PEER_CAPABILITIES, actionSignerIdentity, actionSigningTarget, applyAuthAction, applyDeleteDocumentAction, base58Decode, baseReducerVersion, buildOperationSignatureMessage, buildOperationSignatureParams, canonicalJson, decide, deriveDocumentId, deriveOperationId, evaluate, garbageCollect, groupDocumentType, groupMembershipActionTypes, hashActionV2, hashBrowser, hashDocumentStateForScope, isDenied, isDerivedDocumentId, isPurgeMarker, isUndoRedo, isV2ActionHash, localSupports, mentionedGroupIds, normalizeDocumentModelVersion, purgeDocumentAction, purgeMarkerOperation, referencedGroupIds, signaturePolicyOf, sortOperations, v2TupleProblem, withProtocolVersions } from \"@powerhousedao/shared/document-model\";\nimport { sql } from \"kysely\";\n//#region src/decision/build-decision-model.ts\n/**\n* Reads each projection's stream through the supplied reader, recording the\n* revision observed. Static projections resolve first; derived projections\n* see only those and contribute a map from document id to state. Each\n* distinct stream is read once and yields one append condition entry.\n*/\nasync function buildDecisionModel(reader, definition, target, signal) {\n\tconst decisionModel = definition(target);\n\tconst projections = Object.entries(decisionModel.projections);\n\tconst reads = /* @__PURE__ */ new Map();\n\tconst model = {};\n\tfor (const [key, projection] of projections) {\n\t\tif (typeof projection.query === \"function\") continue;\n\t\tmodel[key] = (await readStream(reader, projection.query, reads, signal)).state;\n\t}\n\tconst staticModel = { ...model };\n\tconst derived = [];\n\tfor (const [key, projection] of projections) {\n\t\tif (typeof projection.query !== \"function\") continue;\n\t\tderived.push([key, projection.query(staticModel)]);\n\t}\n\tif (derived.length > 0 && reader.fence) await reader.fence(derived.flatMap(([, queries]) => queries.map((q) => q.documentId)));\n\tfor (const [key, queries] of derived) {\n\t\tconst value = {};\n\t\tfor (const query of queries) {\n\t\t\tlet read;\n\t\t\ttry {\n\t\t\t\tread = await readStream(reader, query, reads, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DocumentNotFoundError) {\n\t\t\t\t\trecordEmptyStream(query, reads);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tvalue[query.documentId] = read.state;\n\t\t}\n\t\tmodel[key] = value;\n\t}\n\treturn {\n\t\tmodel,\n\t\tappendCondition: { streams: [...reads.values()].map((read) => read.stream) }\n\t};\n}\n/** Guards a stream that holds nothing yet: any operation appearing is growth. */\nfunction recordEmptyStream(query, reads) {\n\tconst key = `${query.documentId}:${query.scope}:${query.branch}`;\n\tif (reads.has(key)) return;\n\treads.set(key, {\n\t\tstate: void 0,\n\t\tstream: {\n\t\t\tdocumentId: query.documentId,\n\t\t\tscope: query.scope,\n\t\t\tbranch: query.branch,\n\t\t\trevision: -1\n\t\t}\n\t});\n}\nasync function readStream(reader, query, reads, signal) {\n\tconst key = `${query.documentId}:${query.scope}:${query.branch}`;\n\tconst existing = reads.get(key);\n\tif (existing) return existing;\n\tconst document = await reader.getState(query.documentId, query.scope, query.branch, void 0, signal);\n\tconst read = {\n\t\tstate: document.state[query.scope],\n\t\tstream: {\n\t\t\tdocumentId: query.documentId,\n\t\t\tscope: query.scope,\n\t\t\tbranch: query.branch,\n\t\t\trevision: observedRevision(document, query.scope)\n\t\t}\n\t};\n\treads.set(key, read);\n\treturn read;\n}\n/**\n* The highest operation index the document reflects for the scope, or -1 if\n* empty. `header.revision` is authoritative, not the rebuilt operation list.\n*/\nfunction observedRevision(document, scope) {\n\tif (scope in document.header.revision) return document.header.revision[scope] - 1;\n\tif (scope in document.operations) {\n\t\tconst operations = document.operations[scope];\n\t\tif (operations.length > 0) return operations[operations.length - 1].index;\n\t}\n\tif (!(scope in document.header.revision)) return -1;\n\treturn document.header.revision[scope] - 1;\n}\n/**\n* The projections whose queries depend on folded state. A positional walk\n* resolves their streams through `queryOverHistory`; a projection without one\n* contributes no streams to a walk.\n*/\nfunction derivedReadSet(definition) {\n\tconst projections = [];\n\tfor (const [name, projection] of Object.entries(definition.projections)) {\n\t\tif (typeof projection.query !== \"function\") continue;\n\t\tprojections.push({\n\t\t\tname,\n\t\t\tdecidingActions: projection.decidingActions,\n\t\t\tapply: projection.apply,\n\t\t\tqueryOverHistory: projection.queryOverHistory\n\t\t});\n\t}\n\treturn projections;\n}\n/**\n* The streams a model reads whose queries are known before it is built. A\n* derived query needs the statically-queried projections first, so it is not\n* included here.\n*/\nfunction staticReadSet(definition) {\n\tconst streams = [];\n\tfor (const [name, projection] of Object.entries(definition.projections)) {\n\t\tif (typeof projection.query === \"function\") continue;\n\t\tstreams.push({\n\t\t\tname,\n\t\t\tquery: projection.query,\n\t\t\tdecidingActions: projection.decidingActions,\n\t\t\tapply: projection.apply\n\t\t});\n\t}\n\treturn streams;\n}\n//#endregion\n//#region src/decision/auth-decision-model.ts\nfunction refusalReason(refusal) {\n\tswitch (refusal) {\n\t\tcase \"version-unsupported\": return AUTH_VERSION_UNSUPPORTED_REASON;\n\t\tcase \"denied-by-grant\": return AUTH_DENIED_BY_GRANT_REASON;\n\t\tcase \"no-applicable-grant\": return AUTH_NO_GRANT_REASON;\n\t}\n}\nfunction decideAuthModel(model, subject, request, groups, conditions) {\n\tif (request.verb === \"execute\" && model.document.isDeleted) return {\n\t\tdecision: \"deny\",\n\t\treason: DOCUMENT_DELETED_REASON\n\t};\n\tconst evaluation = evaluate(model.auth, subject, request, groups, conditions);\n\tif (evaluation.decision === \"allow\") return { decision: \"allow\" };\n\treturn {\n\t\tdecision: \"deny\",\n\t\treason: refusalReason(evaluation.refusal)\n\t};\n}\nfunction documentProjection(target) {\n\treturn {\n\t\tdecidingActions: [\"DELETE_DOCUMENT\"],\n\t\tapply: (document, operation) => operation.action.type === \"DELETE_DOCUMENT\" ? applyDeleteDocumentAction({\n\t\t\t...document,\n\t\t\tstate: { ...document.state }\n\t\t}, operation.action) : document,\n\t\tquery: {\n\t\t\tdocumentId: target.documentId,\n\t\t\tbranch: target.branch,\n\t\t\tscope: \"document\"\n\t\t}\n\t};\n}\nfunction authProjection(target) {\n\treturn {\n\t\tdecidingActions: [...AUTH_ACTION_TYPES],\n\t\tapply: (document, operation) => applyAuthAction(document, operation.action),\n\t\tquery: {\n\t\t\tdocumentId: target.documentId,\n\t\t\tbranch: target.branch,\n\t\t\tscope: \"auth\"\n\t\t}\n\t};\n}\n/** This decision model uses both the document and the auth streams. */\nfunction authDecisionModel(target) {\n\treturn {\n\t\tprojections: {\n\t\t\tdocument: documentProjection(target),\n\t\t\tauth: authProjection(target)\n\t\t},\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request) {\n\t\t\treturn decideAuthModel(model, subject, request);\n\t\t}\n\t};\n}\n/**\n* Folds one group-stream operation with the registered group model's reducer.\n* A reactor without the module registered folds nothing, so the member list\n* stays as read and a missing reducer never widens access.\n*/\nfunction applyGroupOperation(registry, document, operation) {\n\tlet reducer;\n\ttry {\n\t\treducer = registry.getModule(groupDocumentType).reducer;\n\t} catch {\n\t\treturn document;\n\t}\n\treturn reducer(document, operation.action);\n}\n/**\n* Folds one evaluated-scope operation with the reducer registered for the\n* document's own type, at the document's stamped version. A reactor without\n* that module folds nothing, so conditions read the base state and an\n* unresolvable reducer never widens access.\n*/\nfunction applyModelOperation(registry, document, operation) {\n\tlet reducer;\n\ttry {\n\t\tconst version = normalizeDocumentModelVersion(document.state.document?.version);\n\t\treducer = registry.getModule(document.header.documentType, version).reducer;\n\t} catch {\n\t\treturn document;\n\t}\n\treturn reducer(document, operation.action);\n}\n/**\n* The auth model extended with a derived groups projection: the streams it\n* reads are the group documents the folded grant list names, so adding a\n* grant that names a new group pulls that group's stream into the read-set.\n* Group queries pin the main branch, because a group's member list lives on\n* its main branch no matter which branch the referencing document is on.\n*/\nfunction groupsProjection(registry) {\n\treturn {\n\t\tdecidingActions: [...groupMembershipActionTypes],\n\t\tapply: (document, operation) => applyGroupOperation(registry, document, operation),\n\t\tquery: (model) => referencedGroupIds(model.auth?.grants ?? []).map((id) => ({\n\t\t\tdocumentId: id,\n\t\t\tbranch: \"main\",\n\t\t\tscope: \"global\"\n\t\t})),\n\t\tqueryOverHistory: (reads) => {\n\t\t\tconst ids = [];\n\t\t\tfor (const read of reads) {\n\t\t\t\tif (read.name !== \"auth\") continue;\n\t\t\t\tfor (const operation of read.operations) for (const id of mentionedGroupIds(operation.action)) if (!ids.includes(id)) ids.push(id);\n\t\t\t}\n\t\t\treturn ids.map((id) => ({\n\t\t\t\tdocumentId: id,\n\t\t\t\tbranch: \"main\",\n\t\t\t\tscope: \"global\"\n\t\t\t}));\n\t\t}\n\t};\n}\nfunction authGroupsDecisionModel(registry) {\n\treturn (target) => ({\n\t\tprojections: {\n\t\t\tdocument: documentProjection(target),\n\t\t\tauth: authProjection(target),\n\t\t\tgroups: groupsProjection(registry)\n\t\t},\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request) {\n\t\t\treturn decideAuthModel(model, subject, request, model.groups);\n\t\t}\n\t});\n}\n/**\n* The groups model with conditions live: decide hands the executing scope's\n* state and the action input through to the evaluator, so `where` clauses\n* and { match } principals apply. The model folds the evaluated scope during\n* a positional walk, so a condition reads the state as it stood at each\n* operation's position.\n*/\nfunction authConditionsDecisionModel(registry) {\n\treturn (target) => ({\n\t\tprojections: {\n\t\t\tdocument: documentProjection(target),\n\t\t\tauth: authProjection(target),\n\t\t\tgroups: groupsProjection(registry)\n\t\t},\n\t\tfoldEvaluatedScope: (document, operation) => applyModelOperation(registry, document, operation),\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request, ctx) {\n\t\t\treturn decideAuthModel(model, subject, request, model.groups, {\n\t\t\t\tscopeState: ctx.scopeState,\n\t\t\t\tactionInput: ctx.actionInput\n\t\t\t});\n\t\t}\n\t});\n}\n//#endregion\n//#region src/decision/document-decision-model.ts\n/**\n* The simplest decision model: one projection over the document scope, which\n* rejects on a deleted document.\n*/\nfunction documentDecisionModel(target) {\n\treturn {\n\t\tprojections: { document: {\n\t\t\tdecidingActions: [\"DELETE_DOCUMENT\"],\n\t\t\tapply: (document, operation) => operation.action.type === \"DELETE_DOCUMENT\" ? applyDeleteDocumentAction({\n\t\t\t\t...document,\n\t\t\t\tstate: { ...document.state }\n\t\t\t}, operation.action) : document,\n\t\t\tquery: {\n\t\t\t\tdocumentId: target.documentId,\n\t\t\t\tbranch: target.branch,\n\t\t\t\tscope: \"document\"\n\t\t\t}\n\t\t} },\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request) {\n\t\t\treturn request.verb === \"execute\" && model.document.isDeleted ? {\n\t\t\t\tdecision: \"deny\",\n\t\t\t\treason: DOCUMENT_DELETED_REASON\n\t\t\t} : { decision: \"allow\" };\n\t\t}\n\t};\n}\n//#endregion\n//#region src/decision/registered-model.ts\n/**\n* Builds the model at the stream heads and decides one request against it. The\n* append condition it returns is the read-set the store enforces at write time.\n*\n* With `conditions` supplied, the executing scope's state is read at the head\n* for `doc.<scope>.*` paths, or taken from the run's carried document when the\n* caller has already reduced earlier writes into it. That read carries no\n* append-condition entry of its own: the written stream's expected-revision\n* check already refuses a write whose scope grew between the read and the\n* append.\n*/\nasync function decideAtHead(model, cache, target, subject, request, signal, conditions) {\n\tconst built = await buildDecisionModel(cache, model, target, signal);\n\tlet scopeState;\n\tif (conditions !== void 0) scopeState = (conditions.carriedDocument ?? await cache.getState(target.documentId, request.scope, target.branch, void 0, signal)).state[request.scope];\n\treturn {\n\t\tevaluation: model(target).decide(built.model, subject, request, {\n\t\t\tscopeState,\n\t\t\tactionInput: conditions?.actionInput\n\t\t}),\n\t\tappendCondition: built.appendCondition,\n\t\tdocumentVersion: built.model.document.version,\n\t\tdeletedAtUtcIso: built.model.document.deletedAtUtcIso ?? null\n\t};\n}\n/**\n* The model this reactor enforces. With `authEnforcement` off the auth scope is\n* absent from every append condition and no load walks it; with `authGroups`\n* on, the group documents the grant list names join the read-set and the\n* registry supplies the reducer that folds them.\n*/\nfunction selectDecisionModel(flags, registry) {\n\tif (flags.authConditions) return authConditionsDecisionModel(registry);\n\tif (flags.authGroups) return authGroupsDecisionModel(registry);\n\treturn flags.authEnforcement ? authDecisionModel : documentDecisionModel;\n}\n//#endregion\n//#region src/cache/operation-index-types.ts\nconst DRIVE_COLLECTION_PREFIX = \"drive.\";\n/**\n* Identifies the collection a remote synchronizes. Collections are drive-level\n* abstractions (document-drive and reactor-drive), so a collection id is the\n* drive document id plus the branch it scopes to rather than an opaque string.\n*\n* The canonical string form (`drive.${branch}.${driveId}`) is produced only by\n* `key` and parsed only by `fromKey`; that string is the wire and storage\n* representation and is byte-for-byte identical to the legacy\n* `driveCollectionId(branch, driveId)` output, so existing `document_collections`\n* rows and persisted remotes remain valid without migration.\n*/\nvar DriveCollectionId = class DriveCollectionId {\n\tdriveId;\n\tbranch;\n\tconstructor(driveId, branch) {\n\t\tthis.driveId = driveId;\n\t\tthis.branch = branch;\n\t}\n\tstatic forDrive(driveId, branch = \"main\") {\n\t\treturn new DriveCollectionId(driveId, branch);\n\t}\n\t/**\n\t* The single deserializer for the wire/storage form. `branch` may contain\n\t* dots, while `driveId` is a dot-free document id, so the drive id is the\n\t* final dot-delimited segment.\n\t*\n\t* That asymmetry is a real constraint, not a convention: a drive id\n\t* containing a dot does NOT survive `key` -> `fromKey`, because the split\n\t* takes the LAST dot and so hands the tail of the drive id back as the drive\n\t* id and everything before it as the branch. The key format is the wire and\n\t* storage representation of existing `document_collections` rows, so it\n\t* cannot be changed; callers that accept a drive id or branch from outside\n\t* (a UI field, an RPC payload) must reject dots in the drive id at their own\n\t* boundary. The round-trip is verifiable without parsing rules:\n\t* `DriveCollectionId.fromKey(id.key).key === id.key`.\n\t*/\n\tstatic fromKey(key) {\n\t\tif (!key.startsWith(DRIVE_COLLECTION_PREFIX)) throw new Error(`Unsupported collection id: ${key}`);\n\t\tconst rest = key.slice(6);\n\t\tconst lastDot = rest.lastIndexOf(\".\");\n\t\tif (lastDot === -1 || lastDot === rest.length - 1) throw new Error(`Malformed drive collection id: ${key}`);\n\t\treturn new DriveCollectionId(rest.slice(lastDot + 1), rest.slice(0, lastDot));\n\t}\n\tget key() {\n\t\treturn `${DRIVE_COLLECTION_PREFIX}${this.branch}.${this.driveId}`;\n\t}\n\ttoString() {\n\t\treturn this.key;\n\t}\n\tequals(other) {\n\t\treturn this.driveId === other.driveId && this.branch === other.branch;\n\t}\n};\n//#endregion\n//#region src/executor/types.ts\n/** 200k operations purge in 1.6 s on local Postgres; jobs time out at 30 s. */\nconst DEFAULT_MAX_PURGE_OPERATIONS = 2e5;\n/** How long a deferred job waits for its document before it fails. */\nconst DEFAULT_DEFERRED_JOB_TTL_MS = 3e4;\nconst DEFAULT_JOB_TIMEOUT_MS = 3e4;\n/**\n* Event types for the job executor\n*/\nconst JobExecutorEventTypes = {\n\tJOB_STARTED: 3e4,\n\tJOB_COMPLETED: 30001,\n\tJOB_FAILED: 30002,\n\tEXECUTOR_STARTED: 30003,\n\tEXECUTOR_STOPPED: 30004\n};\n//#endregion\n//#region src/core/feature-flags.ts\n/**\n* Every flag this reactor knows, with the flags it requires. A stage adds its\n* flag here when it ships, so asking an older reactor for a later stage's flag\n* is an unrecognized name rather than a flag that quietly does nothing.\n*/\nconst FLAG_PREREQUISITES = {\n\tdocumentDecisions: [],\n\tauthEnforcement: [\"documentDecisions\"],\n\tauthGroups: [\"authEnforcement\"],\n\tauthConditions: [\"authGroups\"]\n};\n/**\n* The flags as plain booleans, with anything unset off, validated. Callers hold\n* a partial set, because that is what crosses to a pooled worker, and every\n* consumer needs the same resolution of it.\n*/\nfunction resolveFeatureFlags(flags = {}) {\n\tconst resolved = {\n\t\tdocumentDecisions: flags.documentDecisions ?? false,\n\t\tauthEnforcement: flags.authEnforcement ?? false,\n\t\tauthGroups: flags.authGroups ?? false,\n\t\tauthConditions: flags.authConditions ?? false\n\t};\n\tvalidateFeatureFlags(flags, FLAG_PREREQUISITES);\n\treturn resolved;\n}\n/**\n* Throws when the flags ask for enforcement the reactor cannot deliver. Either\n* failure would otherwise read as enforcement being on while the reactor\n* applies less than the caller asked for.\n*/\nfunction validateFeatureFlags(flags, prerequisites) {\n\tconst known = Object.keys(prerequisites);\n\tconst unrecognized = Object.keys(flags).filter((name) => !known.includes(name));\n\tif (unrecognized.length > 0) throw new Error(`Unrecognized reactor feature flag: ${unrecognized.join(\", \")}. This reactor knows: ${known.join(\", \")}.`);\n\tfor (const name of known) {\n\t\tif (flags[name] !== true) continue;\n\t\tconst missing = prerequisites[name].filter((required) => flags[required] !== true);\n\t\tif (missing.length > 0) throw new Error(`Reactor feature flag ${name} requires ${missing.join(\", \")}.`);\n\t}\n}\n//#endregion\n//#region src/storage/kysely/document-purger.ts\n/** An `Operation` row whose DELETE_DOCUMENT applied: not errored, not denied. */\nconst appliedDelete = sql`action->>'type' = 'DELETE_DOCUMENT' and coalesce(error, '') = '' and coalesce(\"deniedReason\", '') = ''`;\n/** Rows removed per statement from the tables a document can fill. */\nconst DEFAULT_PURGE_DELETE_BATCH = 5e3;\n/** A purge transaction's statements; bound to the job's transaction. */\nvar KyselyDocumentPurger = class {\n\tbatchSize;\n\tdb;\n\tconstructor(db, batchSize = DEFAULT_PURGE_DELETE_BATCH) {\n\t\tthis.batchSize = batchSize;\n\t\tthis.db = db;\n\t}\n\t/** Every stream the document holds operations in. */\n\tasync streams(documentId) {\n\t\treturn this.db.selectFrom(\"Operation\").select([\"scope\", \"branch\"]).distinct().where(\"documentId\", \"=\", documentId).orderBy(\"scope\").orderBy(\"branch\").execute();\n\t}\n\tasync operationCount(documentId) {\n\t\tconst row = await this.db.selectFrom(\"operation_index_operations\").select((eb) => eb.fn.countAll().as(\"count\")).where(\"documentId\", \"=\", documentId).executeTakeFirst();\n\t\treturn Number(row?.count ?? 0);\n\t}\n\t/** Untombstoned documents group_references records as naming the group. */\n\tasync groupReferencers(groupId) {\n\t\tconst ids = (await this.db.selectFrom(\"group_references\").select(\"documentId\").where(\"groupId\", \"=\", groupId).where(\"documentId\", \"<>\", groupId).orderBy(\"documentId\").execute()).map((row) => row.documentId);\n\t\tconst purged = await findPurged(this.db, ids);\n\t\treturn ids.filter((id) => !purged.has(id));\n\t}\n\t/** Survivors whose accepted auth history names the group; refusals do not. */\n\tasync groupReferencersInHistory(groupId) {\n\t\tconst referencing = [];\n\t\tfor (const documentId of await this.groupReferencers(groupId)) if ([...(await this.authOperations(documentId)).values()].some((operations) => garbageCollect(sortOperations(operations)).some((operation) => operation.deniedReason === void 0 && operation.error === void 0 && mentionedGroupIds(operation.action).includes(groupId)))) referencing.push(documentId);\n\t\treturn referencing;\n\t}\n\t/** The document's auth-scope operations, per branch, in index order. */\n\tasync authOperations(documentId) {\n\t\tconst rows = await this.db.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", \"auth\").orderBy(\"branch\").orderBy(\"index\").execute();\n\t\tconst byBranch = /* @__PURE__ */ new Map();\n\t\tfor (const row of rows) {\n\t\t\tconst operations = byBranch.get(row.branch) ?? [];\n\t\t\toperations.push({\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\terror: row.error || void 0,\n\t\t\t\tdeniedReason: row.deniedReason || void 0,\n\t\t\t\tid: row.opId,\n\t\t\t\taction: row.action\n\t\t\t});\n\t\t\tbyBranch.set(row.branch, operations);\n\t\t}\n\t\treturn byBranch;\n\t}\n\t/** Every document ever in the collection, but its owner and its own row. */\n\tasync collectionMembers(collectionId, ownerId, branch) {\n\t\treturn (await this.db.selectFrom(\"document_collections as dc\").select(\"dc.documentId\").select(sql`dc.\"leftOrdinal\" is null`.as(\"openHere\")).select((eb) => eb.exists(eb.selectFrom(\"Operation as op\").select(\"op.opId\").whereRef(\"op.documentId\", \"=\", \"dc.documentId\").where(\"op.branch\", \"=\", branch).where(\"op.scope\", \"=\", \"document\").where(appliedDelete)).as(\"deleted\")).select((eb) => eb.exists(eb.selectFrom(\"document_collections as other\").select(\"other.documentId\").whereRef(\"other.documentId\", \"=\", \"dc.documentId\").where(\"other.collectionId\", \"<>\", collectionId).where(\"other.leftOrdinal\", \"is\", null)).as(\"openElsewhere\")).where(\"dc.collectionId\", \"=\", collectionId).where(\"dc.documentId\", \"not in\", [ownerId, collectionId]).orderBy(\"dc.documentId\").execute()).map((row) => {\n\t\t\tconst openElsewhere = Boolean(row.openElsewhere);\n\t\t\treturn {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\topenElsewhere,\n\t\t\t\trequired: !openElsewhere && (Boolean(row.openHere) || Boolean(row.deleted))\n\t\t\t};\n\t\t});\n\t}\n\tasync remoteCollection(remoteName) {\n\t\treturn (await this.db.selectFrom(\"sync_remotes\").select(\"collection_id\").where(\"name\", \"=\", remoteName).executeTakeFirst())?.collection_id;\n\t}\n\t/** Deletes every row about the document; the counts are per table. */\n\tasync deleteRows(documentId) {\n\t\tconst removed = {};\n\t\tremoved.Operation = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"Operation\").where(\"id\", \"in\", (eb) => eb.selectFrom(\"Operation\").select(\"id\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.operation_index_operations = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"operation_index_operations\").where(\"ordinal\", \"in\", (eb) => eb.selectFrom(\"operation_index_operations\").select(\"ordinal\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.Keyframe = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"Keyframe\").where(\"id\", \"in\", (eb) => eb.selectFrom(\"Keyframe\").select(\"id\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.DocumentSnapshot = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"DocumentSnapshot\").where(\"id\", \"in\", (eb) => eb.selectFrom(\"DocumentSnapshot\").select(\"id\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.SlugMapping = await this.deleteWhere(\"SlugMapping\", \"documentId\", documentId);\n\t\tremoved.WriteIdentity = await this.deleteWhere(\"WriteIdentity\", \"documentId\", documentId);\n\t\tremoved.DocumentPermission = await this.deleteWhere(\"DocumentPermission\", \"documentId\", documentId);\n\t\tremoved.OperationUserPermission = await this.deleteWhere(\"OperationUserPermission\", \"documentId\", documentId);\n\t\tremoved.DocumentProtection = await this.deleteWhere(\"DocumentProtection\", \"documentId\", documentId);\n\t\tconst relationships = await this.db.selectFrom(\"DocumentRelationship\").select((eb) => eb.fn.countAll().as(\"count\")).where((eb) => eb.or([eb(\"sourceId\", \"=\", documentId), eb(\"targetId\", \"=\", documentId)])).executeTakeFirst();\n\t\tremoved.DocumentRelationship = Number(relationships?.count ?? 0);\n\t\tremoved.Document = await this.deleteWhere(\"Document\", \"id\", documentId);\n\t\tremoved.group_references = await this.deleteWhere(\"group_references\", \"documentId\", documentId);\n\t\tremoved.sync_dead_letters = await this.deleteWhere(\"sync_dead_letters\", \"document_id\", documentId);\n\t\tremoved.sync_holds = await this.deleteWhere(\"sync_holds\", \"document_id\", documentId);\n\t\treturn removed;\n\t}\n\tasync writeTombstone(tombstone) {\n\t\tconst values = {\n\t\t\tdocumentId: tombstone.documentId,\n\t\t\tordinal: tombstone.ordinal,\n\t\t\tremovedRows: JSON.stringify(tombstone.removedRows),\n\t\t\tpurgedAtUtc: tombstone.purgedAtUtc,\n\t\t\trequestId: tombstone.requestId\n\t\t};\n\t\tawait this.db.insertInto(\"document_purges\").values(values).onConflict((oc) => oc.column(\"documentId\").doUpdateSet({\n\t\t\tordinal: values.ordinal,\n\t\t\tremovedRows: values.removedRows,\n\t\t\tpurgedAtUtc: values.purgedAtUtc,\n\t\t\trequestId: values.requestId\n\t\t})).execute();\n\t}\n\t/** Reopens every membership at the marker ordinal, plus `collectionIds`. */\n\tasync reopenMemberships(documentId, ordinal, collectionIds = []) {\n\t\tawait this.db.updateTable(\"document_collections\").set({\n\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\tleftOrdinal: null\n\t\t}).where(\"documentId\", \"=\", documentId).execute();\n\t\tfor (const collectionId of new Set(collectionIds)) await this.db.insertInto(\"document_collections\").values({\n\t\t\tdocumentId,\n\t\t\tcollectionId,\n\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\tleftOrdinal: null\n\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\tleftOrdinal: null\n\t\t})).execute();\n\t\treturn (await this.db.selectFrom(\"document_collections\").select(\"collectionId\").where(\"documentId\", \"=\", documentId).orderBy(\"collectionId\").execute()).map((row) => row.collectionId);\n\t}\n\tasync deleteBatched(step) {\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst deleted = await step();\n\t\t\ttotal += deleted;\n\t\t\tif (deleted < this.batchSize) return total;\n\t\t}\n\t}\n\tasync deleteWhere(table, column, documentId) {\n\t\tconst result = await this.db.deleteFrom(table).where(column, \"=\", documentId).executeTakeFirst();\n\t\treturn Number(result.numDeletedRows);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/write-identity-store.ts\nvar KyselyWriteIdentityStore = class KyselyWriteIdentityStore {\n\tdb;\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyWriteIdentityStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync upsert(rows) {\n\t\tif (rows.length === 0) return;\n\t\tif (this.trx) {\n\t\t\tawait this.upsertIn(this.trx, rows);\n\t\t\treturn;\n\t\t}\n\t\tawait this.db.transaction().execute((trx) => this.upsertIn(trx, rows));\n\t}\n\tasync resolve(identifier, branch) {\n\t\tconst rows = await this.queryExecutor.selectFrom(\"WriteIdentity\").selectAll().where(\"branch\", \"=\", branch).where((eb) => eb.or([eb(\"documentId\", \"=\", identifier), eb(\"slug\", \"=\", identifier)])).execute();\n\t\tconst idMatch = rows.find((row) => row.documentId === identifier);\n\t\tconst slugMatch = rows.find((row) => row.slug === identifier);\n\t\tif (idMatch && slugMatch && idMatch.documentId !== slugMatch.documentId) throw new Error(`Ambiguous identifier \"${identifier}\": matches both document ID \"${idMatch.documentId}\" and slug for document ID \"${slugMatch.documentId}\". Please use get() for ID or resolveSlug() + get() for slug to be explicit.`);\n\t\tconst match = idMatch ?? slugMatch;\n\t\treturn match ? toRecord(match) : void 0;\n\t}\n\tasync describe(documentId, branch) {\n\t\tconst row = await this.queryExecutor.selectFrom(\"WriteIdentity\").selectAll().where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).executeTakeFirst();\n\t\treturn row ? toRecord(row) : void 0;\n\t}\n\tasync delete(documentId) {\n\t\tawait this.queryExecutor.deleteFrom(\"WriteIdentity\").where(\"documentId\", \"=\", documentId).execute();\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\t/**\n\t* A slug is unique per branch, and the last document to claim it keeps it,\n\t* as the view's SlugMapping upsert does: the claim first clears the slug\n\t* from any other document on the branch.\n\t*/\n\tasync upsertIn(trx, rows) {\n\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\tfor (const row of rows) {\n\t\t\tif (row.slug !== null) await trx.updateTable(\"WriteIdentity\").set({\n\t\t\t\tslug: null,\n\t\t\t\tupdatedAtUtcIso: now\n\t\t\t}).where(\"slug\", \"=\", row.slug).where(\"branch\", \"=\", row.branch).where(\"documentId\", \"<>\", row.documentId).execute();\n\t\t\tawait trx.insertInto(\"WriteIdentity\").values({\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tslug: row.slug,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tisDeleted: row.isDeleted,\n\t\t\t\tcreatedAtUtcIso: now,\n\t\t\t\tupdatedAtUtcIso: now\n\t\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"branch\"]).doUpdateSet({\n\t\t\t\tslug: row.slug,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tisDeleted: row.isDeleted,\n\t\t\t\tupdatedAtUtcIso: now\n\t\t\t})).execute();\n\t\t}\n\t}\n};\nfunction toRecord(row) {\n\treturn {\n\t\tdocumentId: row.documentId,\n\t\tbranch: row.branch,\n\t\tslug: row.slug,\n\t\tdocumentType: row.documentType,\n\t\tisDeleted: row.isDeleted,\n\t\tcreatedAtUtcIso: row.createdAtUtcIso,\n\t\tupdatedAtUtcIso: row.updatedAtUtcIso\n\t};\n}\n//#endregion\n//#region src/executor/execution-scope.ts\n/** For scopes without a transaction to hold a lock in. */\nconst NOOP_DOCUMENT_LOCKS = {\n\tshared: () => Promise.resolve(),\n\texclusive: () => Promise.resolve(),\n\tpurged: () => Promise.resolve(/* @__PURE__ */ new Set())\n};\n/** For scopes without a store to record identity in; resolves nothing. */\nconst NOOP_WRITE_IDENTITY_STORE = {\n\tupsert: () => Promise.resolve(),\n\tresolve: () => Promise.resolve(void 0),\n\tdescribe: () => Promise.resolve(void 0),\n\tdelete: () => Promise.resolve()\n};\nvar DefaultExecutionScope = class {\n\toperationStore;\n\toperationIndex;\n\twriteCache;\n\tdocumentMetaCache;\n\tcollectionMembershipCache;\n\twriteIdentity;\n\tconstructor(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache, writeIdentity = NOOP_WRITE_IDENTITY_STORE) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.writeIdentity = writeIdentity;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn fn({\n\t\t\toperationStore: this.operationStore,\n\t\t\toperationIndex: this.operationIndex,\n\t\t\twriteCache: this.writeCache,\n\t\t\tdocumentMetaCache: this.documentMetaCache,\n\t\t\tcollectionMembershipCache: this.collectionMembershipCache,\n\t\t\tdocumentLocks: NOOP_DOCUMENT_LOCKS,\n\t\t\twriteIdentity: this.writeIdentity\n\t\t});\n\t}\n};\nvar KyselyExecutionScope = class {\n\tdb;\n\toperationStore;\n\toperationIndex;\n\tkeyframeStore;\n\twriteCache;\n\tdocumentMetaCache;\n\tcollectionMembershipCache;\n\twriteIdentityStore;\n\tconstructor(db, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache, writeIdentityStore = new KyselyWriteIdentityStore(db)) {\n\t\tthis.db = db;\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.writeIdentityStore = writeIdentityStore;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn this.db.transaction().execute(async (trx) => {\n\t\t\tconst sharedLocked = /* @__PURE__ */ new Set();\n\t\t\tconst liveIds = /* @__PURE__ */ new Set();\n\t\t\tconst scopedOperationStore = this.operationStore.withTransaction(trx, liveIds);\n\t\t\tconst scopedOperationIndex = this.operationIndex.withTransaction(trx, liveIds);\n\t\t\tconst scopedKeyframeStore = this.keyframeStore.withTransaction(trx);\n\t\t\treturn fn({\n\t\t\t\toperationStore: scopedOperationStore,\n\t\t\t\toperationIndex: scopedOperationIndex,\n\t\t\t\twriteCache: this.writeCache.withScopedStores(scopedOperationStore, scopedKeyframeStore),\n\t\t\t\tdocumentMetaCache: this.documentMetaCache.withScopedStore(scopedOperationStore),\n\t\t\t\tcollectionMembershipCache: this.collectionMembershipCache.withScopedIndex(scopedOperationIndex),\n\t\t\t\tdocumentLocks: {\n\t\t\t\t\tshared: async (ids) => {\n\t\t\t\t\t\tconst list = [...ids];\n\t\t\t\t\t\tawait acquirePurgeLocks(trx, list, \"shared\");\n\t\t\t\t\t\tfor (const id of list) sharedLocked.add(id);\n\t\t\t\t\t},\n\t\t\t\t\texclusive: (id) => acquirePurgeLocks(trx, [id], \"exclusive\"),\n\t\t\t\t\tpurged: async (ids) => {\n\t\t\t\t\t\tconst list = [...ids];\n\t\t\t\t\t\tconst found = await findPurged(trx, list);\n\t\t\t\t\t\tfor (const id of list) if (sharedLocked.has(id) && !found.has(id)) liveIds.add(id);\n\t\t\t\t\t\treturn found;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\twriteIdentity: this.writeIdentityStore.withTransaction(trx),\n\t\t\t\tpurger: new KyselyDocumentPurger(trx)\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/storage/storage-flush.ts\n/** The store's session is poisoned; only a host restart recovers it. */\nvar StoragePoisonedError = class extends Error {\n\tconstructor(message, cause) {\n\t\tsuper(message, { cause });\n\t\tthis.name = \"StoragePoisonedError\";\n\t}\n};\nvar NoopStorageFlusher = class {\n\tflush() {\n\t\treturn Promise.resolve();\n\t}\n};\n//#endregion\n//#region src/utils/reshuffle.ts\nconst STRICT_ORDER_ACTION_TYPES = /* @__PURE__ */ new Set([\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\",\n\t\"PURGE_DOCUMENT\",\n\t\"ADD_FOLDER\",\n\t\"UPDATE_FOLDER\",\n\t\"REMOVE_FOLDER\"\n]);\n/**\n* Reshuffles operations by timestamp, then applies deterministic tie-breaking.\n* Used for merging concurrent operations from different branches.\n*\n* For strict document-structure actions (e.g., CREATE_DOCUMENT/UPGRADE_DOCUMENT),\n* logical index (index - skip) is prioritized to preserve causal replay order.\n*\n* For other actions, action ID is prioritized to ensure a canonical cross-reactor order\n* for concurrent operations that may have diverged local indices due to prior reshuffles.\n* Logical index and operation ID are then used as deterministic tie-breakers.\n*\n* Example:\n* [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n* GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n* Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n* Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n* merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n*/\nfunction reshuffleByTimestamp(startIndex, opsA, opsB) {\n\treturn [...opsA, ...opsB].sort((a, b) => {\n\t\tconst timestampDiff = new Date(a.timestampUtcMs).getTime() - new Date(b.timestampUtcMs).getTime();\n\t\tif (timestampDiff !== 0) return timestampDiff;\n\t\tconst rank = (op) => STRICT_ORDER_ACTION_TYPES.has(op.action?.type ?? \"\") ? 0 : 1;\n\t\tconst rankDiff = rank(a) - rank(b);\n\t\tif (rankDiff !== 0) return rankDiff;\n\t\tif (rank(a) === 0) {\n\t\t\tconst logicalIndexDiff = a.index - a.skip - (b.index - b.skip);\n\t\t\tif (logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\t}\n\t\tconst actionIdDiff = (a.action?.id ?? \"\").localeCompare(b.action?.id ?? \"\");\n\t\tif (actionIdDiff !== 0) return actionIdDiff;\n\t\treturn a.id.localeCompare(b.id);\n\t}).map((op, i) => ({\n\t\t...op,\n\t\tindex: startIndex.index + i,\n\t\tskip: i === 0 ? startIndex.skip : 0\n\t}));\n}\n//#endregion\n//#region src/decision/merged-order.ts\n/** Identifies a stream within a walk. */\nfunction streamKey(query) {\n\treturn `${query.documentId}:${query.scope}:${query.branch}`;\n}\n/**\n* Orders two operations from different streams by position. Timestamp decides;\n* an equal timestamp puts an auth operation first, and otherwise falls to the\n* action id and then the operation id, so that two replicas holding the same\n* operations agree on the order whatever order they happen to store them in.\n*/\nfunction comparePositions(a, b) {\n\tconst aTime = Date.parse(a.operation.timestampUtcMs);\n\tconst bTime = Date.parse(b.operation.timestampUtcMs);\n\tif (aTime !== bTime) return aTime - bTime;\n\tif (a.streamKey === b.streamKey) return a.operation.index - b.operation.index;\n\tconst aAuth = a.scope === \"auth\";\n\tif (aAuth !== (b.scope === \"auth\")) return aAuth ? -1 : 1;\n\tconst actionIds = (a.operation.action.id ?? \"\").localeCompare(b.operation.action.id ?? \"\");\n\tif (actionIds !== 0) return actionIds;\n\treturn (a.operation.id ?? \"\").localeCompare(b.operation.id ?? \"\");\n}\n/**\n* Merges the read-set streams into one sequence by position. An operation's\n* place in the result is the bound a decision at that operation reads to: every\n* operation before it has been applied, and it has not.\n*/\nfunction mergeByPosition(streams) {\n\tconst merged = [];\n\tfor (const stream of streams) for (const operation of stream.operations) merged.push({\n\t\tstreamKey: stream.streamKey,\n\t\tscope: stream.scope,\n\t\toperation\n\t});\n\treturn merged.sort(comparePositions);\n}\n/**\n* The skip that retracts everything from `firstRetractedIndex` up to where the\n* re-appended operation lands. It spans the indexes rather than counting the\n* operations, because a stream with a gap in it makes those differ.\n*/\nfunction retractionSkip(nextIndex, firstRetractedIndex) {\n\treturn nextIndex - firstRetractedIndex;\n}\n//#endregion\n//#region src/decision/walk.ts\n/**\n* A single forward pass is only correct while a stream's effective operations\n* are ordered.\n*/\nfunction assertPositionOrder(streamKey, scope, operations) {\n\tfor (let i = 1; i < operations.length; i++) {\n\t\tconst previous = operations[i - 1];\n\t\tconst current = operations[i];\n\t\tif (comparePositions({\n\t\t\tstreamKey,\n\t\t\tscope,\n\t\t\toperation: previous\n\t\t}, {\n\t\t\tstreamKey,\n\t\t\tscope,\n\t\t\toperation: current\n\t\t}) > 0) throw new Error(`Stream ${streamKey} is out of position order: index ${previous.index} at ${previous.timestampUtcMs} precedes index ${current.index} at ${current.timestampUtcMs}`);\n\t}\n}\n/**\n* Visits every operation in the read-set once, in the order their positions\n* fall, and hands back the state each stream held just before it. That state is\n* what a decision at that operation reads.\n*\n* Skips are resolved first (i.e. this is performed on a garbage collected\n* stream), which means we can do a single forward pass.\n*\n* An operation that contributes no state, whether denied or holding a reducer\n* error, is visited but not applied (this matches the write cache's rebuild).\n*\n* The consumer sends back whether it refused the operation it was handed: a\n* refusal this pass produced must suppress it the same way a stored one does.\n*/\nfunction* walkByPosition(streams) {\n\tconst merged = mergeByPosition(streams.map((stream) => {\n\t\tconst operations = garbageCollect(sortOperations([...stream.operations]));\n\t\tassertPositionOrder(stream.streamKey, stream.scope, operations);\n\t\treturn {\n\t\t\tstreamKey: stream.streamKey,\n\t\t\tscope: stream.scope,\n\t\t\toperations\n\t\t};\n\t}));\n\tconst byKey = new Map(streams.map((stream) => [stream.streamKey, stream]));\n\tconst states = new Map(streams.map((stream) => [stream.streamKey, stream.document]));\n\tfor (const { streamKey, operation } of merged) {\n\t\tif ((yield {\n\t\t\tstreamKey,\n\t\t\toperation,\n\t\t\tstates: new Map(states)\n\t\t}) || operation.error !== void 0 || isDenied(operation)) continue;\n\t\tconst stream = byKey.get(streamKey);\n\t\tconst before = states.get(streamKey);\n\t\tif (before === void 0 || stream === void 0) throw new Error(`No state for stream ${streamKey}`);\n\t\tstates.set(streamKey, stream.apply(before, operation));\n\t}\n}\n//#endregion\n//#region src/decision/evaluation.ts\n/** The stream key for evaluated operations whose scope no projection reads. */\nconst EVALUATED_ONLY = \"evaluated\";\n/**\n* Whether any stream the model reads declares this operation's action type as\n* one that can change an evaluation.\n*/\nfunction isDecidingAction(operation, readSet) {\n\treturn readSet.some((stream) => stream.decidingActions.includes(operation.action.type));\n}\n/**\n* Who an operation acts as. A replayed operation is evaluated as its own signer,\n* so an address-scoped policy does not deny its own author's history.\n*/\nfunction subjectOf(operation) {\n\tconst signer = operation.action.context?.signer;\n\treturn {\n\t\taddress: signer?.user.address,\n\t\tkey: signer?.app.key\n\t};\n}\n/**\n* The model as the walk reached this operation: each static projection's value\n* is its own scope's state, and each derived projection's value maps document\n* id to that document's state, holding only the streams this replica walked. A\n* derived stream it does not hold stays out of the map, which fails closed.\n*/\nfunction modelAt(readSet, derivedNames, derived, states) {\n\tconst model = {};\n\tfor (const stream of readSet) {\n\t\tconst document = states.get(streamKey(stream.query));\n\t\tif (document === void 0) throw new Error(`No state walked for projection ${stream.name}`);\n\t\tmodel[stream.name] = document.state[stream.query.scope];\n\t}\n\tfor (const name of derivedNames) model[name] = {};\n\tfor (const entry of derived) {\n\t\tconst map = model[entry.name];\n\t\tconst document = states.get(streamKey(entry.query));\n\t\tif (document !== void 0) map[entry.query.documentId] = document.state[entry.query.scope];\n\t}\n\treturn model;\n}\n/**\n* Evaluates each operation at its own position and returns the refusals in an\n* array parallel to the operations, where undefined means allowed.\n*\n* A position is a timestamp, so an operation refused by a delete is one that\n* sorts after it, and the operations before it are left alone. That holds\n* whether the delete is already stored or is among the operations passed in.\n*/\nasync function evaluateByPosition(model, target, subject, stores, signal) {\n\tconst { scope, operations } = subject;\n\tconst { writeCache, operationStore } = stores;\n\tconst definition = model(target);\n\tconst readSet = staticReadSet(definition);\n\tconst derivedSet = derivedReadSet(definition);\n\tif (!definition.evaluatesScope(scope)) return operations.map(() => void 0);\n\tconst evaluating = new Set(operations.map((operation) => operation.id));\n\tconst creation = operations.find((operation) => operation.action.type === \"CREATE_DOCUMENT\" && operation.action.input.documentId === target.documentId);\n\tasync function stateBefore(query) {\n\t\ttry {\n\t\t\treturn await writeCache.getState(query.documentId, query.scope, query.branch, -1, signal);\n\t\t} catch (error) {\n\t\t\tif (creation !== void 0 && query.documentId === target.documentId && error instanceof DocumentNotFoundError && !(error instanceof DocumentPurgedError)) return createDocumentFromAction(creation.action);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst readStreams = await Promise.all(readSet.map(async (stream) => ({\n\t\tstream,\n\t\toperations: (await operationStore.getSince(stream.query.documentId, stream.query.scope, stream.query.branch, -1, { actionTypes: stream.decidingActions }, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id))\n\t})));\n\tconst decidingOperations = operations.filter((operation) => isDecidingAction(operation, readSet));\n\tif (readStreams.every((read) => read.operations.length === 0) && decidingOperations.length === 0) return operations.map(() => void 0);\n\tif (readStreams.length === 0) throw new Error(`Decision model for ${target.documentId} reads no stream whose query is known before it is built`);\n\tconst writtenProjection = readSet.find((stream) => stream.query.scope === scope);\n\tconst walked = [];\n\tconst histories = [];\n\tfor (const read of readStreams) {\n\t\tconst streamOperations = read.stream === writtenProjection ? [...read.operations, ...operations] : read.operations;\n\t\tconst before = await stateBefore(read.stream.query);\n\t\twalked.push({\n\t\t\tstreamKey: streamKey(read.stream.query),\n\t\t\tscope: read.stream.query.scope,\n\t\t\tdocument: before,\n\t\t\toperations: streamOperations,\n\t\t\tapply: read.stream.apply\n\t\t});\n\t\thistories.push({\n\t\t\tname: read.stream.name,\n\t\t\toperations: streamOperations\n\t\t});\n\t}\n\tlet evaluatedStateKey;\n\tif (writtenProjection !== void 0) evaluatedStateKey = streamKey(writtenProjection.query);\n\telse if (definition.foldEvaluatedScope !== void 0) {\n\t\tconst query = {\n\t\t\tdocumentId: target.documentId,\n\t\t\tscope,\n\t\t\tbranch: target.branch\n\t\t};\n\t\tconst storedOperations = (await operationStore.getSince(query.documentId, query.scope, query.branch, -1, void 0, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id));\n\t\tconst before = await stateBefore(query);\n\t\tevaluatedStateKey = streamKey(query);\n\t\twalked.push({\n\t\t\tstreamKey: evaluatedStateKey,\n\t\t\tscope,\n\t\t\tdocument: before,\n\t\t\toperations: [...storedOperations, ...operations],\n\t\t\tapply: definition.foldEvaluatedScope\n\t\t});\n\t} else walked.push({\n\t\tstreamKey: EVALUATED_ONLY,\n\t\tscope,\n\t\tdocument: walked[0].document,\n\t\toperations,\n\t\tapply: (document) => document\n\t});\n\tconst derivedEntries = [];\n\tconst walkedKeys = new Set(walked.map((stream) => stream.streamKey));\n\tfor (const projection of derivedSet) {\n\t\tconst queries = projection.queryOverHistory?.(histories) ?? [];\n\t\tfor (const query of queries) {\n\t\t\tconst key = streamKey(query);\n\t\t\tif (walkedKeys.has(key)) continue;\n\t\t\tlet before;\n\t\t\ttry {\n\t\t\t\tbefore = await writeCache.getState(query.documentId, query.scope, query.branch, -1, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DocumentNotFoundError) continue;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst streamOperations = (await operationStore.getSince(query.documentId, query.scope, query.branch, -1, { actionTypes: projection.decidingActions }, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id));\n\t\t\twalkedKeys.add(key);\n\t\t\twalked.push({\n\t\t\t\tstreamKey: key,\n\t\t\t\tscope: query.scope,\n\t\t\t\tdocument: before,\n\t\t\t\toperations: streamOperations,\n\t\t\t\tapply: projection.apply\n\t\t\t});\n\t\t\tderivedEntries.push({\n\t\t\t\tname: projection.name,\n\t\t\t\tquery\n\t\t\t});\n\t\t}\n\t}\n\tconst reasons = /* @__PURE__ */ new Map();\n\tconst walk = walkByPosition(walked);\n\tlet step = walk.next(false);\n\twhile (!step.done) {\n\t\tconst position = step.value;\n\t\tif (!evaluating.has(position.operation.id)) {\n\t\t\tstep = walk.next(false);\n\t\t\tcontinue;\n\t\t}\n\t\tconst evaluatedDocument = evaluatedStateKey === void 0 ? void 0 : position.states.get(evaluatedStateKey);\n\t\tconst scopeState = evaluatedDocument === void 0 ? void 0 : evaluatedDocument.state[scope];\n\t\tconst evaluation = definition.decide(modelAt(readSet, derivedSet.map((projection) => projection.name), derivedEntries, position.states), subjectOf(position.operation), {\n\t\t\tverb: \"execute\",\n\t\t\tscope: position.operation.action.scope,\n\t\t\toperation: position.operation.action.type\n\t\t}, {\n\t\t\tscopeState,\n\t\t\tactionInput: position.operation.action.input\n\t\t});\n\t\tconst denied = evaluation.decision === \"deny\";\n\t\treasons.set(position.operation.id, denied ? evaluation.reason : void 0);\n\t\tstep = walk.next(denied);\n\t}\n\treturn operations.map((operation) => reasons.get(operation.id));\n}\n//#endregion\n//#region src/executor/document-action-handler.ts\nvar DocumentActionHandler = class {\n\tregistry;\n\tlogger;\n\tdriveContainerTypes;\n\tfeatureFlags;\n\tdecisionModel;\n\tprotocolSupport;\n\tloggedUnregisteredProtocols = /* @__PURE__ */ new Set();\n\tconstructor(registry, logger, driveContainerTypes, featureFlags, decisionModel, protocolSupport) {\n\t\tthis.registry = registry;\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.featureFlags = featureFlags;\n\t\tthis.decisionModel = decisionModel;\n\t\tthis.protocolSupport = protocolSupport;\n\t}\n\t/** Keys this reactor does not register are admitted: it cannot judge them. */\n\tunsupportedProtocol(documentId, protocolVersions) {\n\t\tfor (const [protocol, version] of Object.entries(protocolVersions ?? {})) {\n\t\t\tconst supported = this.protocolSupport[protocol];\n\t\t\tif (supported === void 0) {\n\t\t\t\tif (!this.loggedUnregisteredProtocols.has(protocol)) {\n\t\t\t\t\tthis.loggedUnregisteredProtocols.add(protocol);\n\t\t\t\t\tthis.logger.info(\"Admitting document @documentId with unregistered protocol @protocol @version\", documentId, protocol, version);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!supported.includes(version)) return new UnsupportedProtocolVersionError(documentId, protocol, version);\n\t\t}\n\t}\n\t/** Whether the write arrives with its evaluation already decided. */\n\talreadyEvaluated(executing) {\n\t\treturn this.featureFlags.documentDecisions && (executing.replayingAcceptedHistory || executing.evaluatedByPosition);\n\t}\n\tasync execute(write, executing) {\n\t\tconst { action } = write;\n\t\tif (write.deniedReason !== void 0) return this.writeDenied(write, executing);\n\t\tconst refusal = await this.refuseIfPolicyDenies(write, executing);\n\t\tif (refusal) return refusal;\n\t\tswitch (action.type) {\n\t\t\tcase \"CREATE_DOCUMENT\": return this.executeCreate(write, executing);\n\t\t\tcase \"DELETE_DOCUMENT\": return this.executeDelete(write, executing);\n\t\t\tcase \"UPGRADE_DOCUMENT\": return this.executeUpgrade(write, executing);\n\t\t\tcase \"ADD_RELATIONSHIP\": return this.executeAddRelationship(write, executing);\n\t\t\tcase \"REMOVE_RELATIONSHIP\": return this.executeRemoveRelationship(write, executing);\n\t\t\tcase \"UPDATE_RELATIONSHIP\": return this.executeUpdateRelationship(write, executing);\n\t\t\tcase \"PURGE_DOCUMENT\": return buildErrorResult(executing.job, new ReservedActionError(executing.job.documentId, action.type), executing.startTime);\n\t\t\tdefault: return buildErrorResult(executing.job, /* @__PURE__ */ new Error(`Unknown document action type: ${action.type}`), executing.startTime);\n\t\t}\n\t}\n\t/**\n\t* Refuses a document-scope write the policy denies, or undefined to proceed.\n\t* Without this an `execute`-on-`document` grant is unenforceable.\n\t*/\n\tasync refuseIfPolicyDenies(write, executing) {\n\t\tconst { action } = write;\n\t\tconst { job, startTime, stores, signal } = executing;\n\t\tif (!this.featureFlags.documentDecisions || !this.featureFlags.authEnforcement || this.alreadyEvaluated(executing) || !GATED_DOCUMENT_ACTIONS.has(action.type)) return;\n\t\tconst documentId = targetDocumentId(action, job.documentId);\n\t\tlet admission;\n\t\ttry {\n\t\t\tadmission = await decideAtHead(this.decisionModel, stores.writeCache, {\n\t\t\t\tdocumentId,\n\t\t\t\tbranch: job.branch\n\t\t\t}, {\n\t\t\t\taddress: action.context?.signer?.user.address,\n\t\t\t\tkey: action.context?.signer?.app.key\n\t\t\t}, {\n\t\t\t\tverb: \"execute\",\n\t\t\t\tscope: action.scope,\n\t\t\t\toperation: action.type\n\t\t\t}, signal, this.featureFlags.authConditions ? { actionInput: action.input } : void 0);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (admission.evaluation.decision === \"allow\") return;\n\t\treturn buildErrorResult(job, refusalError(admission.evaluation.reason, documentId, admission.deletedAtUtcIso, action), startTime);\n\t}\n\t/** A refused operation holds a position in the stream but changes nothing. */\n\tasync writeDenied(write, executing) {\n\t\tconst { action, skip, sourceRemote, deniedReason } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tconst index = getNextIndexForScope(document, job.scope);\n\t\tlet standing = document;\n\t\tif (skip > 0) try {\n\t\t\tstanding = await stores.writeCache.getState(job.documentId, job.scope, job.branch, index - skip - 1, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, index, skip, {\n\t\t\tdocumentId: job.documentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\toperation.deniedReason = deniedReason;\n\t\toperation.hash = hashDocumentStateForScope(standing, job.scope);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(standing, job.scope, operation.index);\n\t\tstanding.operations = {\n\t\t\t...standing.operations,\n\t\t\t[job.scope]: [...standing.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(job.documentId, job.scope, job.branch);\n\t\tstores.writeCache.putState(job.documentId, job.scope, job.branch, operation.index, standing, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(job.documentId, job.branch, {\n\t\t\tstate: standing.state.document,\n\t\t\tdocumentType: standing.header.documentType,\n\t\t\tprotocolVersions: standing.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, job.documentId, standing.header.documentType, JSON.stringify({\n\t\t\theader: standing.header,\n\t\t\tdocument: standing.state.document\n\t\t}), startTime);\n\t}\n\tasync executeCreate(write, executing) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tif (job.scope !== \"document\") return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`CREATE_DOCUMENT must be in \"document\" scope, got \"${job.scope}\"`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst input = action.input;\n\t\tconst unsupported = this.unsupportedProtocol(input.documentId, input.protocolVersions);\n\t\tif (unsupported) return buildErrorResult(job, unsupported, startTime);\n\t\tconst document = createDocumentFromAction(action);\n\t\tlet operation = createOperation(action, 0, skip, {\n\t\t\tdocumentId: document.header.id,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\t...document.state,\n\t\t\theader: document.header\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(document.header.id, job.scope, job.branch);\n\t\tstores.writeCache.putState(document.header.id, job.scope, job.branch, operation.index, document, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (this.driveContainerTypes.has(document.header.documentType)) {\n\t\t\tconst collectionId = DriveCollectionId.forDrive(document.header.id, job.branch).key;\n\t\t\tindexTxn.createCollection(collectionId);\n\t\t\tindexTxn.addToCollection(collectionId, document.header.id);\n\t\t}\n\t\tstores.documentMetaCache.putDocumentMeta(document.header.id, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tprotocolVersions: document.header.protocolVersions,\n\t\t\tdocumentScopeRevision: 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, document.header.id, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeDelete(write, executing) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"DELETE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document before deletion: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted && !this.alreadyEvaluated(executing)) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tconst nextIndex = getNextIndexForScope(document, job.scope);\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tapplyDeleteDocumentAction$1(document, action);\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\tdocument: document.state.document\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(documentId, job.scope, job.branch);\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tprotocolVersions: document.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeUpgrade(write, executing) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"UPGRADE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tconst fromVersion = input.fromVersion;\n\t\tconst toVersion = input.toVersion;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted && !this.alreadyEvaluated(executing)) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tif (fromVersion === toVersion && fromVersion > 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst arrivesDecided = executing.replayingAcceptedHistory || executing.evaluatedByPosition;\n\t\tif (fromVersion > 0 && !arrivesDecided) {\n\t\t\tconst stampedVersion = normalizeDocumentModelVersion(documentState.version);\n\t\t\tif (fromVersion !== stampedVersion) return buildErrorResult(job, new UpgradePreconditionFailedError(documentId, `fromVersion ${fromVersion} does not match the document's version ${stampedVersion}`), startTime);\n\t\t\tif (input.revision !== void 0) {\n\t\t\t\tlet actualRevisions;\n\t\t\t\ttry {\n\t\t\t\t\tactualRevisions = (await stores.operationStore.getRevisions(documentId, job.branch, signal)).revision;\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch revisions for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t\t\t}\n\t\t\t\tconst revisionScopes = /* @__PURE__ */ new Set([...Object.keys(input.revision), ...Object.keys(actualRevisions)]);\n\t\t\t\tfor (const revisionScope of revisionScopes) {\n\t\t\t\t\tconst snapshot = input.revision[revisionScope] ?? 0;\n\t\t\t\t\tconst actual = actualRevisions[revisionScope] ?? 0;\n\t\t\t\t\tif (snapshot !== actual) return buildErrorResult(job, new UpgradePreconditionFailedError(documentId, `revision snapshot for scope \"${revisionScope}\" is ${snapshot} but the document is at ${actual}`), startTime);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet upgradePath;\n\t\tif (fromVersion > 0 && fromVersion < toVersion) try {\n\t\t\tupgradePath = this.registry.computeUpgradePath(document.header.documentType, fromVersion, toVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tconst otherScopes = Object.keys(document.state).filter((scope) => scope !== job.scope);\n\t\tif (fromVersion > 0) for (const scope of otherScopes) {\n\t\t\tlet scopedDocument;\n\t\t\ttry {\n\t\t\t\tscopedDocument = await stores.writeCache.getState(documentId, scope, job.branch, void 0, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch ${scope} scope for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t\t}\n\t\t\tdocument = {\n\t\t\t\t...document,\n\t\t\t\tstate: {\n\t\t\t\t\t...document.state,\n\t\t\t\t\t[scope]: scopedDocument.state[scope]\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tconst nextIndex = getNextIndexForScope(document, job.scope);\n\t\ttry {\n\t\t\tdocument = applyUpgradeDocumentAction$1(document, action, upgradePath);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\t...document.state,\n\t\t\theader: document.header\n\t\t};\n\t\tif (fromVersion > 0) resultingStateObj.__migrated = true;\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(documentId, job.scope, job.branch);\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document, \"head\");\n\t\tfor (const scope of otherScopes) executing.postCommitInvalidations.push({\n\t\t\tdocumentId,\n\t\t\tscope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tprotocolVersions: document.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\t/** A submitted write naming a purged target was refused at job start. */\n\tasync isTargetPurged(write, executing) {\n\t\tconst target = relationshipTarget(write.action);\n\t\tif (target === void 0 || !executing.purgeFence) return false;\n\t\treturn executing.purgeFence.isPurged(target);\n\t}\n\tasync executeAddRelationship(write, executing) {\n\t\tlet targetPurged;\n\t\ttry {\n\t\t\ttargetPurged = await this.isTargetPurged(write, executing);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(executing.job, error instanceof Error ? error : new Error(String(error)), executing.startTime);\n\t\t}\n\t\treturn this.withRelationshipAction(\"ADD_RELATIONSHIP\", write, executing, (input) => input.sourceId === input.targetId ? /* @__PURE__ */ new Error(\"ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)\") : null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (!targetPurged && this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;\n\t\t\t\ttxn.addToCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\tasync executeRemoveRelationship(write, executing) {\n\t\tlet targetPurged;\n\t\ttry {\n\t\t\ttargetPurged = await this.isTargetPurged(write, executing);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(executing.job, error instanceof Error ? error : new Error(String(error)), executing.startTime);\n\t\t}\n\t\treturn this.withRelationshipAction(\"REMOVE_RELATIONSHIP\", write, executing, null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (!targetPurged && this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;\n\t\t\t\ttxn.removeFromCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteUpdateRelationship(write, executing) {\n\t\treturn this.withRelationshipAction(\"UPDATE_RELATIONSHIP\", write, executing, null, null);\n\t}\n\tasync withRelationshipAction(actionTypeName, write, executing, preValidate, postWrite) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tif (job.scope !== \"document\") return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} must be in \"document\" scope, got \"${job.scope}\"`), startTime);\n\t\tconst input = action.input;\n\t\tif (!input.sourceId || !input.targetId || !input.relationshipType) return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} action requires sourceId, targetId, and relationshipType in input`), startTime);\n\t\tif (preValidate !== null) {\n\t\t\tconst validationError = preValidate(input);\n\t\t\tif (validationError !== null) return buildErrorResult(job, validationError, startTime);\n\t\t}\n\t\tlet sourceDoc;\n\t\ttry {\n\t\t\tsourceDoc = await stores.writeCache.getState(input.sourceId, \"document\", job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\tif (DocumentPurgedError.isError(error)) return buildErrorResult(job, error, startTime);\n\t\t\tif (DocumentNotFoundError.isError(error)) return buildErrorResult(job, new DocumentNotFoundError(input.sourceId, `${actionTypeName}: source document ${input.sourceId} not found`), startTime);\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName}: source document ${input.sourceId} not found: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst nextIndex = getNextIndexForScope(sourceDoc, job.scope);\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId: input.sourceId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tsourceDoc.header.lastModifiedAtUtcIso = operation.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();\n\t\tupdateDocumentRevision(sourceDoc, job.scope, operation.index);\n\t\tsourceDoc.operations = {\n\t\t\t...sourceDoc.operations,\n\t\t\t[job.scope]: [...sourceDoc.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tconst scopeState = sourceDoc.state[job.scope];\n\t\tconst resultingStateObj = {\n\t\t\theader: structuredClone(sourceDoc.header),\n\t\t\t[job.scope]: scopeState === void 0 ? {} : structuredClone(scopeState)\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\texecuting.touchedStreams.add(input.sourceId, job.scope, job.branch);\n\t\texecuting.touchedStreams.add(input.targetId, job.scope, job.branch);\n\t\tstores.writeCache.putState(input.sourceId, job.scope, job.branch, operation.index, sourceDoc, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (postWrite !== null) postWrite({\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsourceDoc,\n\t\t\tinput,\n\t\t\tjob\n\t\t});\n\t\tstores.documentMetaCache.putDocumentMeta(input.sourceId, job.branch, {\n\t\t\tstate: sourceDoc.state.document,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tprotocolVersions: sourceDoc.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, input.sourceId, sourceDoc.header.documentType, resultingState, startTime);\n\t}\n\tasync writeOperationToStore(target, operation, executing) {\n\t\tconst { documentId, documentType, scope, branch } = target;\n\t\tconst { job, startTime, stores, signal } = executing;\n\t\texecuting.touchedStreams.add(documentId, scope, branch);\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(documentId, documentType, scope, branch, operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(operation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to write operation to IOperationStore (@documentId @scope @branch): @Operation @Error\", documentId, scope, branch, operation, error);\n\t\t\tstores.writeCache.invalidate(documentId, scope, branch);\n\t\t\tif (AppendConditionFailedError.isError(error)) for (const stream of error.condition.streams) stores.writeCache.invalidate(stream.documentId, stream.scope, stream.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\treturn storedOperations;\n\t}\n};\n//#endregion\n//#region src/signer/passthrough-signer.ts\n/**\n* A no-op signer that returns empty values for all methods.\n* Used when signing is not required.\n*/\nvar PassthroughSigner = class {\n\tpublicKey = {};\n\tsign() {\n\t\treturn Promise.resolve(/* @__PURE__ */ new Uint8Array(0));\n\t}\n\tverify() {\n\t\treturn Promise.resolve();\n\t}\n\tsignAction() {\n\t\treturn Promise.resolve([\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"\n\t\t]);\n\t}\n};\n//#endregion\n//#region src/signer/trust-policy.ts\n/**\n* The policy admission asks: the reactor's own key signing as its own user is\n* accepted, then the host's policy decides, else the default does. `own` is\n* read on every ask, since its user changes on login.\n*/\nfunction admissionTrustPolicy(own, authEnforcement, policy) {\n\treturn { authorizeSigner(signer, key, documentId) {\n\t\tconst identity = actionSignerIdentity(own);\n\t\tif (identity.app.key !== \"\" && key === identity.app.key) {\n\t\t\tif (sameUser(actionSignerIdentity(signer).user, identity.user)) return Promise.resolve(true);\n\t\t}\n\t\tif (policy) return policy.authorizeSigner(signer, key, documentId);\n\t\treturn Promise.resolve(!authEnforcement);\n\t} };\n}\nfunction sameUser(a, b) {\n\treturn a.address.toLowerCase() === b.address.toLowerCase() && a.networkId === b.networkId && a.chainId === b.chainId;\n}\n//#endregion\n//#region src/signer/did-key.ts\nconst DID_KEY_PREFIX = \"did:key:z\";\nconst P256_MULTICODEC = [128, 36];\nconst MAX_CACHED_KEYS = 1024;\nconst P = BigInt(\"0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff\");\nconst A = BigInt(\"0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc\");\nconst B = BigInt(\"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b\");\n/** A did:key that is not a compressed P-256 public key. */\nvar MalformedDidKeyError = class extends Error {\n\tconstructor(did, detail) {\n\t\tsuper(`Malformed did:key ${did}: ${detail}`);\n\t\tthis.name = \"MalformedDidKeyError\";\n\t}\n};\nconst keyCache = /* @__PURE__ */ new Map();\n/** Cached per process: decompressing the point costs a BigInt modPow. */\nasync function importDidKey(did) {\n\tconst cached = keyCache.get(did);\n\tif (cached) {\n\t\tkeyCache.delete(did);\n\t\tkeyCache.set(did, cached);\n\t\treturn cached;\n\t}\n\tconst raw = decompressP256(compressedPointFromDid(did), did);\n\tconst key = await crypto.subtle.importKey(\"raw\", raw.buffer, {\n\t\tname: \"ECDSA\",\n\t\tnamedCurve: \"P-256\"\n\t}, false, [\"verify\"]);\n\tkeyCache.set(did, key);\n\tif (keyCache.size > MAX_CACHED_KEYS) {\n\t\tconst oldest = keyCache.keys().next().value;\n\t\tif (oldest !== void 0) keyCache.delete(oldest);\n\t}\n\treturn key;\n}\nfunction compressedPointFromDid(did) {\n\tif (!did.startsWith(DID_KEY_PREFIX)) throw new MalformedDidKeyError(did, \"not a base58btc did:key\");\n\tconst decoded = base58Decode(did.slice(9));\n\tif (!decoded || decoded.length !== 35) throw new MalformedDidKeyError(did, \"not a compressed P-256 key\");\n\tif (decoded[0] !== P256_MULTICODEC[0] || decoded[1] !== P256_MULTICODEC[1]) throw new MalformedDidKeyError(did, \"not a P-256 multicodec\");\n\treturn decoded.subarray(2);\n}\nfunction decompressP256(compressed, did) {\n\tconst prefix = compressed[0];\n\tif (prefix !== 2 && prefix !== 3) throw new MalformedDidKeyError(did, `compression prefix ${prefix}`);\n\tlet x = BigInt(0);\n\tfor (let i = 1; i < compressed.length; i++) x = x << BigInt(8) | BigInt(compressed[i]);\n\tif (x >= P) throw new MalformedDidKeyError(did, \"x outside the field\");\n\tconst ySquared = (modPow(x, BigInt(3), P) + A * x + B) % P;\n\tlet y = modPow(ySquared, (P + BigInt(1)) / BigInt(4), P);\n\tif (y * y % P !== ySquared) throw new MalformedDidKeyError(did, \"x is not on the curve\");\n\tif (y % BigInt(2) === BigInt(0) !== (prefix === 2)) y = P - y;\n\tconst uncompressed = /* @__PURE__ */ new Uint8Array(65);\n\tuncompressed[0] = 4;\n\tuncompressed.set(bigIntToBytes(x), 1);\n\tuncompressed.set(bigIntToBytes(y), 33);\n\treturn uncompressed;\n}\nfunction modPow(base, exp, mod) {\n\tlet result = BigInt(1);\n\tlet b = base % mod;\n\tlet e = exp;\n\twhile (e > BigInt(0)) {\n\t\tif (e & BigInt(1)) result = result * b % mod;\n\t\te >>= BigInt(1);\n\t\tb = b * b % mod;\n\t}\n\treturn result;\n}\nfunction bigIntToBytes(value) {\n\tconst bytes = /* @__PURE__ */ new Uint8Array(32);\n\tlet v = value;\n\tfor (let i = 31; i >= 0; i--) {\n\t\tbytes[i] = Number(v & BigInt(255));\n\t\tv >>= BigInt(8);\n\t}\n\treturn bytes;\n}\n//#endregion\n//#region src/signer/verify-action-signature.ts\nconst RENOWN_HASH_LENGTH = 44;\nconst SHARED_HASH_LENGTH = 28;\nconst HEX_SIGNATURE = /^(0x)?([0-9a-fA-F]{2})+$/;\n/**\n* Integrity only: identity binding and the live-id check sit with the caller.\n* `operation` is the incoming operation at load admission.\n*/\nasync function verifyActionSignature(action, target, path, operation) {\n\tconst policy = target.policy ?? \"legacy\";\n\tconst refusal = policyRefusal(action, policy);\n\tif (refusal) return refusal;\n\tconst shape = signerShape(action.context?.signer);\n\tif (shape.kind === \"unsigned\") return policy === \"v2-required\" ? refuse(\"unsigned\", \"UNSIGNED_REQUIRED\", `action ${action.id} is unsigned but ${target.documentId} requires v2 signatures`) : {\n\t\tok: true,\n\t\tscheme: \"unsigned\"\n\t};\n\tif (shape.kind === \"malformed\") return refuse(\"legacy-unknown\", \"MALFORMED_TUPLE\", `action ${action.id} ${shape.reason}`);\n\tconst { signer, tuple } = shape;\n\tconst scheme = schemeOf(tuple[2]);\n\tif (tuple[1] !== signer.app.key) return refuse(scheme, \"KEY_MISMATCH\", `action ${action.id} tuple key does not match signer.app.key`);\n\tif (scheme !== \"v2\" && policy === \"v2-required\") return refuse(scheme, \"SCHEME_BELOW_POLICY\", `action ${action.id} carries a legacy tuple but ${target.documentId} requires v2 signatures`);\n\tif (scheme === \"legacy-unknown\" && path === \"mutation\") return refuse(scheme, \"MALFORMED_TUPLE\", `action ${action.id} carries a hash of unknown length ${tuple[2].length}`);\n\tif (scheme === \"v2\") {\n\t\tconst refusal = await checkV2(action, tuple, target, operation);\n\t\tif (refusal) return refusal;\n\t} else if (path === \"mutation\") {\n\t\tif (await legacyHash(scheme, action, target) !== tuple[2]) return refuse(scheme, \"HASH_MISMATCH\", `action ${action.id} does not match the hash its signature covers`);\n\t}\n\treturn verifyEcdsa(tuple, scheme, action.id);\n}\n/** Refusals a document's policy makes before any tuple is read. */\nfunction policyRefusal(action, policy) {\n\tif (action.type !== \"CREATE_DOCUMENT\") return;\n\tconst scheme = schemeOfAction(action);\n\tconst input = action.input;\n\tconst documentId = input?.documentId ?? \"\";\n\tif (policy === \"legacy\") return isDerivedDocumentId(documentId) ? refuse(scheme, \"ID_MISMATCH\", `action ${action.id}: a legacy document cannot take the content-addressed id ${documentId}`) : void 0;\n\tconst expected = derivedCreateId(input);\n\tif (expected === documentId) return;\n\treturn refuse(scheme, \"ID_MISMATCH\", expected === void 0 ? `action ${action.id} creates v2-required ${documentId} without the header params its id is derived from` : `action ${action.id} creates v2-required ${documentId}, but its header params derive ${expected}`);\n}\nfunction derivedCreateId(input) {\n\tif (!input?.signing || !input.protocolVersions) return;\n\ttry {\n\t\treturn deriveDocumentId({\n\t\t\tdocumentType: input.model,\n\t\t\tcreatedAtUtcIso: input.signing.createdAtUtcIso,\n\t\t\tnonce: input.signing.nonce,\n\t\t\tprotocolVersions: input.protocolVersions\n\t\t});\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction schemeOfAction(action) {\n\tconst shape = signerShape(action.context?.signer);\n\tif (shape.kind === \"unsigned\") return \"unsigned\";\n\treturn shape.kind === \"signed\" ? schemeOf(shape.tuple[2]) : \"legacy-unknown\";\n}\n/** Peers send arbitrary JSON, so nothing past `context` is assumed. */\nfunction signerShape(value) {\n\tif (value === void 0 || value === null) return { kind: \"unsigned\" };\n\tif (!isRecord(value)) return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer that is not an object\"\n\t};\n\tconst { app, user, signatures } = value;\n\tif (app !== void 0 && app !== null && !isRecord(app)) return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer.app that is not an object\"\n\t};\n\tconst key = isRecord(app) ? app.key : void 0;\n\tif (key !== void 0 && key !== null && typeof key !== \"string\") return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer.app.key that is not a string\"\n\t};\n\tif (!key) return { kind: \"unsigned\" };\n\tif (!isRecord(user) || typeof user.address !== \"string\") return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer without a user address\"\n\t};\n\tif (!Array.isArray(signatures)) return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer whose signatures are not a list\"\n\t};\n\tconst tuple = signatures.at(-1);\n\tif (!isTuple(tuple)) return {\n\t\tkind: \"malformed\",\n\t\treason: signatures.length === 0 ? \"has a signer but no signatures\" : \"carries a malformed signature tuple\"\n\t};\n\treturn {\n\t\tkind: \"signed\",\n\t\tsigner: value,\n\t\ttuple\n\t};\n}\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nasync function checkV2(action, tuple, target, operation) {\n\tconst problem = v2TupleProblem(tuple);\n\tif (problem) return refuse(\"v2\", \"MALFORMED_TUPLE\", `action ${action.id}: ${problem}`);\n\tif (operation && !sameInstant(operation.timestampUtcMs, action.timestampUtcMs)) return refuse(\"v2\", \"TIMESTAMP_MISMATCH\", `action ${action.id} is stamped ${action.timestampUtcMs} but its operation ${operation.timestampUtcMs}`);\n\tlet expected;\n\ttry {\n\t\texpected = await hashActionV2(action, target, action.context.signer);\n\t} catch (error) {\n\t\treturn refuse(\"v2\", \"HASH_MISMATCH\", `action ${action.id} has no v2 hash: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tif (expected !== tuple[2]) return refuse(\"v2\", \"HASH_MISMATCH\", `action ${action.id} does not match the hash its signature covers`);\n}\nfunction sameInstant(a, b) {\n\tconst left = Date.parse(a);\n\treturn !Number.isNaN(left) && left === Date.parse(b);\n}\nfunction schemeOf(hash) {\n\tif (isV2ActionHash(hash)) return \"v2\";\n\tif (hash.length === RENOWN_HASH_LENGTH) return \"legacy-renown\";\n\tif (hash.length === SHARED_HASH_LENGTH) return \"legacy-shared\";\n\treturn \"legacy-unknown\";\n}\nasync function legacyHash(scheme, action, target) {\n\tif (scheme === \"legacy-renown\") {\n\t\tconst payload = [\n\t\t\taction.scope,\n\t\t\taction.type,\n\t\t\tJSON.stringify(action.input)\n\t\t].join(\"\");\n\t\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(payload));\n\t\treturn bytesToBase64(new Uint8Array(digest));\n\t}\n\tconst signer = action.context.signer;\n\treturn buildOperationSignatureParams({\n\t\tdocumentId: target.documentId,\n\t\tsigner,\n\t\taction,\n\t\tpreviousStateHash: \"\"\n\t})[2];\n}\nasync function verifyEcdsa(tuple, scheme, actionId) {\n\tconst [timestamp, key, hash, prevStateHash, signatureHex] = tuple;\n\tif (!HEX_SIGNATURE.test(signatureHex)) return refuse(scheme, \"MALFORMED_TUPLE\", `action ${actionId} signature is not hex`);\n\tlet cryptoKey;\n\ttry {\n\t\tcryptoKey = await importDidKey(key);\n\t} catch (error) {\n\t\treturn refuse(scheme, \"MALFORMED_TUPLE\", `action ${actionId}: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tconst message = buildOperationSignatureMessage([\n\t\ttimestamp,\n\t\tkey,\n\t\thash,\n\t\tprevStateHash\n\t]);\n\tlet valid;\n\ttry {\n\t\tvalid = await crypto.subtle.verify({\n\t\t\tname: \"ECDSA\",\n\t\t\thash: \"SHA-256\"\n\t\t}, cryptoKey, hexToBytes(signatureHex).buffer, message.buffer);\n\t} catch {\n\t\tvalid = false;\n\t}\n\tif (!valid) return refuse(scheme, \"BAD_SIGNATURE\", `action ${actionId} signature does not verify under its key`);\n\treturn {\n\t\tok: true,\n\t\tscheme\n\t};\n}\nfunction isTuple(value) {\n\treturn Array.isArray(value) && value.length === 5 && value.every((element) => typeof element === \"string\");\n}\nfunction refuse(scheme, code, reason) {\n\treturn {\n\t\tok: false,\n\t\tscheme,\n\t\tcode,\n\t\treason\n\t};\n}\nfunction hexToBytes(hex) {\n\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\tconst bytes = new Uint8Array(clean.length / 2);\n\tfor (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);\n\treturn bytes;\n}\nfunction bytesToBase64(bytes) {\n\tlet binary = \"\";\n\tfor (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);\n\treturn btoa(binary);\n}\n//#endregion\n//#region src/executor/synthesized-signing.ts\n/** Submitted types whose stored action the reducer writes in their place. */\nconst SYNTHESIZING_TYPES = /* @__PURE__ */ new Set([\"UNDO\", \"REDO\"]);\n/**\n* The id of the action synthesized from `submittedId`. Derived, so the stored\n* operation answers for the submitted id at the live-id check.\n*/\nfunction synthesizedActionId(submittedId) {\n\treturn hashBrowser(`synthesized:${submittedId}`, \"sha1\", \"hex\").slice(0, 32);\n}\n/**\n* Whether `operation` stores an action the reducer made from `submitted`\n* rather than `submitted` itself or an operation already in `history`.\n*/\nfunction isSynthesized(submitted, operation, history) {\n\tif (!SYNTHESIZING_TYPES.has(submitted.type)) return false;\n\tconst id = operation.action.id;\n\tif (!id) return true;\n\tif (id === submitted.id) return false;\n\treturn !history.some((existing) => existing.action.id === id);\n}\n/**\n* Signs the synthesized action of `operation` in place as `signer`, under the\n* id {@link synthesizedActionId} derives from the submitted one. A REDO's\n* rebuilt action has no timestamp, so it takes the submitted one; the\n* operation timestamp is set to the action's, which a peer requires of a v2\n* tuple.\n*/\nasync function signSynthesized(operation, submitted, target, signer, signal) {\n\tconst synthesized = operation.action;\n\tconst id = synthesizedActionId(submitted.id);\n\tconst timestampUtcMs = operation.timestampUtcMs || synthesized.timestampUtcMs || submitted.timestampUtcMs;\n\tconst action = {\n\t\tid,\n\t\ttimestampUtcMs,\n\t\ttype: synthesized.type,\n\t\tinput: synthesized.input,\n\t\tscope: synthesized.scope\n\t};\n\tconst signature = await signer.signAction(action, {\n\t\tdocumentId: target.documentId,\n\t\tbranch: target.branch\n\t}, signal);\n\toperation.action = {\n\t\t...action,\n\t\tcontext: { signer: {\n\t\t\t...actionSignerIdentity(signer),\n\t\t\tsignatures: [signature]\n\t\t} }\n\t};\n\toperation.id = deriveOperationId(target.documentId, target.scope, target.branch, id);\n\toperation.timestampUtcMs = timestampUtcMs;\n}\n//#endregion\n//#region src/executor/signature-admission.ts\nconst DEFAULT_TRUST_TIMEOUT_MS = 1e4;\n/** Runs once per write, when this reactor first stores it; never on re-appends. */\nvar SignatureAdmission = class {\n\tmode;\n\tlogger;\n\teventBus;\n\tpolicySource;\n\ttrustPolicy;\n\ttrustTimeoutMs;\n\tconstructor(mode, logger, eventBus, policySource = \"meta\", trust = {\n\t\tauthEnforcement: false,\n\t\ttimeoutMs: DEFAULT_TRUST_TIMEOUT_MS\n\t}) {\n\t\tthis.mode = mode;\n\t\tthis.logger = logger;\n\t\tthis.eventBus = eventBus;\n\t\tthis.policySource = policySource;\n\t\tthis.trustPolicy = admissionTrustPolicy(trust.signer ?? new PassthroughSigner(), trust.authEnforcement, trust.policy);\n\t\tthis.trustTimeoutMs = trust.timeoutMs;\n\t}\n\t/** The first refusal of a mutation's submitted actions, when enforcing. */\n\tasync admitMutation(job, stores, signal) {\n\t\tconst { operationStore } = stores;\n\t\tconst candidates = job.actions.map((action) => candidate(action, mutationStream(action, job)));\n\t\tconst live = await this.liveOperationIds(candidates, operationStore, signal);\n\t\tconst committed = await this.storedAsSubmitted(candidates, live, isRetry(job), operationStore, signal);\n\t\tawait resolvePolicies(candidates, job.actions, (documentId, branch) => storedPolicy(stores, this.policySource, documentId, branch, signal));\n\t\tconst submitted = /* @__PURE__ */ new Set();\n\t\tfor (const entry of candidates) {\n\t\t\tif (committed.has(entry)) continue;\n\t\t\tconst verdict = await this.verdict(entry, live, submitted, \"mutation\", signal);\n\t\t\tsubmitted.add(entry.opId);\n\t\t\tif (verdict.ok) continue;\n\t\t\tconst refusal = this.record(job, entry, verdict, \"mutation\");\n\t\t\tif (refusal) return {\n\t\t\t\tkind: \"refused\",\n\t\t\t\terror: refusal\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: \"admitted\",\n\t\t\tcommitted: [...committed.values()]\n\t\t};\n\t}\n\t/** The incoming operations a load drops, empty unless enforcing. */\n\tasync admitLoad(job, operations, stores, signal) {\n\t\tconst { operationStore } = stores;\n\t\tconst stream = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t};\n\t\tconst candidates = operations.map((operation) => ({\n\t\t\t...candidate(operation.action, stream),\n\t\t\toperation\n\t\t}));\n\t\tconst live = await this.liveOperationIds(candidates, operationStore, signal);\n\t\tconst redelivered = await this.redelivered(candidates, live, operationStore, signal);\n\t\tawait resolvePolicies(candidates, job.operations.map((operation) => operation.action), (documentId, branch) => storedPolicy(stores, this.policySource, documentId, branch, signal));\n\t\tconst dropped = /* @__PURE__ */ new Set();\n\t\tfor (let i = 0; i < candidates.length; i++) {\n\t\t\tconst verdict = await this.verdict(candidates[i], live, void 0, \"load\", signal, redelivered.has(candidates[i]));\n\t\t\tif (verdict.ok) continue;\n\t\t\tif (this.record(job, candidates[i], verdict, \"load\")) dropped.add(operations[i]);\n\t\t}\n\t\treturn dropped;\n\t}\n\t/** A marker is held to v2 and enforced whatever the policy and mode. */\n\tasync admitMarker(job, marker, signal) {\n\t\tconst entry = {\n\t\t\t...candidate(marker.action, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope: \"document\",\n\t\t\t\tbranch: job.branch\n\t\t\t}),\n\t\t\toperation: marker,\n\t\t\tpolicy: \"v2-required\"\n\t\t};\n\t\tconst verdict = await this.verdict(entry, /* @__PURE__ */ new Set(), void 0, \"load\", signal);\n\t\tif (verdict.ok) return;\n\t\treturn this.record(job, entry, verdict, \"load\", true);\n\t}\n\tasync verdict(entry, live, submitted, path, signal, known = false) {\n\t\tconst verdict = await verifyActionSignature(entry.action, {\n\t\t\tdocumentId: entry.stream.documentId,\n\t\t\tbranch: entry.stream.branch,\n\t\t\tpolicy: entry.policy\n\t\t}, path, entry.operation);\n\t\tif (!verdict.ok) return verdict;\n\t\tif (!known && (isLive(entry, live) || submitted?.has(entry.opId))) return {\n\t\t\tok: false,\n\t\t\tscheme: verdict.scheme,\n\t\t\tcode: \"DUPLICATE_ACTION\",\n\t\t\treason: `action ${entry.action.id} is already in the stream`\n\t\t};\n\t\tif (verdict.scheme === \"unsigned\") {\n\t\t\tconst address = entry.action.context?.signer?.user?.address;\n\t\t\treturn address ? {\n\t\t\t\tok: false,\n\t\t\t\tscheme: \"unsigned\",\n\t\t\t\tcode: \"UNSIGNED_IDENTITY\",\n\t\t\t\treason: `action ${entry.action.id} is unsigned but claims to act as ${address}`\n\t\t\t} : verdict;\n\t\t}\n\t\tif (known) return verdict;\n\t\tconst signer = entry.action.context.signer;\n\t\tif (!await this.authorize(signer, entry.stream.documentId, signal)) return {\n\t\t\tok: false,\n\t\t\tscheme: verdict.scheme,\n\t\t\tcode: \"SIGNER_UNAUTHORIZED\",\n\t\t\treason: `action ${entry.action.id}: key ${signer.app.key} may not sign as ${signer.user.address}`\n\t\t};\n\t\treturn verdict;\n\t}\n\t/** Throws when the policy does, times out or the job is aborted. */\n\tasync authorize(signer, documentId, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tlet timer;\n\t\tlet onAbort;\n\t\tconst stop = new Promise((_, reject) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\treject(/* @__PURE__ */ new Error(`signature trust policy did not answer for ${signer.app.key} within ${this.trustTimeoutMs}ms`));\n\t\t\t}, this.trustTimeoutMs);\n\t\t\tif (signal) {\n\t\t\t\tonAbort = () => reject(signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason)));\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\t\t});\n\t\ttry {\n\t\t\treturn await Promise.race([this.trustPolicy.authorizeSigner(signer, signer.app.key, documentId), stop]);\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tif (onAbort) signal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\t/**\n\t* The live candidates stored exactly as submitted and still standing: one\n\t* an undo or a reshuffle has since superseded is refused, not re-emitted with\n\t* the state it once produced. A synthesized operation\n\t* holds another action, so it cannot be compared; only a retry, whose first\n\t* attempt this job was, takes it as committed.\n\t*/\n\tasync storedAsSubmitted(candidates, live, retry, operationStore, signal) {\n\t\tconst committed = /* @__PURE__ */ new Map();\n\t\tconst toCompare = [];\n\t\tfor (const entry of candidates) if (entry.synthesizedOpId && live.has(entry.synthesizedOpId)) {\n\t\t\tif (retry) committed.set(entry, committedWrite(entry, entry.synthesizedOpId));\n\t\t} else if (live.has(entry.opId)) toCompare.push(entry);\n\t\tfor (const [stream, entries] of byStream(toCompare)) {\n\t\t\tconst stored = await operationStore.getOperationsByIds(stream.documentId, stream.scope, stream.branch, entries.map((entry) => entry.opId), signal);\n\t\t\tconst byId = new Map(stored.map((operation) => [operation.id, operation]));\n\t\t\tconst matching = entries.filter((entry) => {\n\t\t\t\tconst operation = byId.get(entry.opId);\n\t\t\t\treturn operation && sameContent(operation.action, entry.action);\n\t\t\t});\n\t\t\tif (matching.length === 0) continue;\n\t\t\tconst later = await operationStore.getSince(stream.documentId, stream.scope, stream.branch, Math.min(...matching.map((entry) => byId.get(entry.opId).index)), void 0, void 0, signal);\n\t\t\tfor (const entry of matching) if (!isSuperseded(byId.get(entry.opId), later.results)) committed.set(entry, committedWrite(entry, entry.opId));\n\t\t}\n\t\treturn committed;\n\t}\n\t/**\n\t* The load candidates stored exactly as they arrive, timestamp included: a\n\t* peer re-sending what this stream holds, not a replay of its action.\n\t*/\n\tasync redelivered(candidates, live, operationStore, signal) {\n\t\tconst found = /* @__PURE__ */ new Set();\n\t\tconst toCompare = candidates.filter((entry) => live.has(entry.opId) && !(entry.synthesizedOpId && live.has(entry.synthesizedOpId)));\n\t\tfor (const [stream, entries] of byStream(toCompare)) {\n\t\t\tconst stored = await operationStore.getOperationsByIds(stream.documentId, stream.scope, stream.branch, entries.map((entry) => entry.opId), signal);\n\t\t\tfor (const entry of entries) if (stored.some((operation) => operation.id === entry.opId && Date.parse(operation.timestampUtcMs) === Date.parse(entry.operation?.timestampUtcMs ?? \"\") && sameContent(operation.action, entry.action))) found.add(entry);\n\t\t}\n\t\treturn found;\n\t}\n\tasync liveOperationIds(candidates, operationStore, signal) {\n\t\tconst live = /* @__PURE__ */ new Set();\n\t\tfor (const [stream, entries] of byStream(candidates)) {\n\t\t\tconst found = await operationStore.findOperationIds(stream.documentId, stream.scope, stream.branch, entries.flatMap((entry) => entry.synthesizedOpId ? [entry.opId, entry.synthesizedOpId] : [entry.opId]), signal);\n\t\t\tfor (const opId of found) live.add(opId);\n\t\t}\n\t\treturn live;\n\t}\n\t/** Logs and counts a refusal; returns the error only when enforcing. */\n\trecord(job, entry, refusal, path, enforced = this.mode === \"enforce\") {\n\t\tconst event = {\n\t\t\tjobId: job.id,\n\t\t\tdocumentId: entry.stream.documentId,\n\t\t\tscope: entry.stream.scope,\n\t\t\tbranch: entry.stream.branch,\n\t\t\tactionId: entry.action.id,\n\t\t\tcode: refusal.code,\n\t\t\tscheme: refusal.scheme,\n\t\t\tpath,\n\t\t\tenforced,\n\t\t\treason: refusal.reason\n\t\t};\n\t\tthis.logger.warn(enforced ? \"Signature refused: @Refusal\" : \"Signature refusal logged, write admitted: @Refusal\", event);\n\t\tthis.eventBus.emit(ReactorEventTypes.SIGNATURE_REFUSED, event).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit SIGNATURE_REFUSED: @Error\", error);\n\t\t});\n\t\treturn enforced ? new InvalidSignatureError(entry.stream.documentId, refusal.code, refusal.reason) : void 0;\n\t}\n};\n/**\n* A CREATE_DOCUMENT is verified under its own input. Anything else takes the\n* stored document's policy, or, for a document this job creates, that CREATE's.\n*/\nasync function resolvePolicies(candidates, jobActions, stored) {\n\tconst resolved = /* @__PURE__ */ new Map();\n\tfor (const entry of candidates) {\n\t\tif (entry.action.type === \"CREATE_DOCUMENT\") {\n\t\t\tentry.policy = createPolicy(entry.action);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { documentId, branch } = entry.stream;\n\t\tconst key = `${documentId}\\u0000${branch}`;\n\t\tlet policy = resolved.get(key);\n\t\tif (policy === void 0) {\n\t\t\tpolicy = await stored(documentId, branch) ?? createdPolicy(jobActions, documentId) ?? \"legacy\";\n\t\t\tresolved.set(key, policy);\n\t\t}\n\t\tentry.policy = policy;\n\t}\n}\nasync function storedPolicy(stores, source, documentId, branch, signal) {\n\ttry {\n\t\tif (source === \"write-cache\") {\n\t\t\tconst document = await stores.writeCache.getState(documentId, \"document\", branch, void 0, signal);\n\t\t\treturn signaturePolicyOf(document.header);\n\t\t}\n\t\tconst meta = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);\n\t\treturn signaturePolicyOf(meta.protocolVersions);\n\t} catch (error) {\n\t\tif (DocumentNotFoundError.isError(error)) return;\n\t\tthrow error;\n\t}\n}\nfunction createdPolicy(actions, documentId) {\n\tconst create = actions.find((action) => action.type === \"CREATE_DOCUMENT\" && action.input?.documentId === documentId);\n\treturn create ? createPolicy(create) : void 0;\n}\nfunction createPolicy(action) {\n\treturn signaturePolicyOf(action.input);\n}\nfunction candidate(action, stream) {\n\tconst opId = (actionId) => deriveOperationId(stream.documentId, stream.scope, stream.branch, actionId);\n\treturn {\n\t\taction,\n\t\tstream,\n\t\topId: opId(action.id),\n\t\tsynthesizedOpId: SYNTHESIZING_TYPES.has(action.type) ? opId(synthesizedActionId(action.id)) : void 0\n\t};\n}\nfunction isLive(entry, live) {\n\treturn live.has(entry.opId) || entry.synthesizedOpId !== void 0 && live.has(entry.synthesizedOpId);\n}\nfunction mutationStream(action, job) {\n\treturn {\n\t\t...actionSigningTarget(action, job.documentId, job.branch),\n\t\tscope: job.scope\n\t};\n}\nfunction byStream(candidates) {\n\tconst groups = /* @__PURE__ */ new Map();\n\tfor (const entry of candidates) {\n\t\tconst key = `${entry.stream.documentId}\\u0000${entry.stream.scope}\\u0000${entry.stream.branch}`;\n\t\tconst group = groups.get(key) ?? [entry.stream, []];\n\t\tgroup[1].push(entry);\n\t\tgroups.set(key, group);\n\t}\n\treturn [...groups.values()];\n}\nfunction isRetry(job) {\n\treturn job.errorHistory.length > 0 || (job.retryCount ?? 0) > 0;\n}\nfunction committedWrite(entry, opId) {\n\treturn {\n\t\t...entry.stream,\n\t\tactionId: entry.action.id,\n\t\topId\n\t};\n}\nfunction isSuperseded(operation, later) {\n\treturn later.some((next) => next.index > operation.index && next.skip > 0 && next.index - next.skip <= operation.index);\n}\nfunction sameContent(stored, submitted) {\n\ttry {\n\t\treturn canonicalJson(stored) === canonicalJson(submitted);\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/executor/simple-job-executor.ts\nconst MAX_SKIP_THRESHOLD = 1e3;\n/** Retries of a failed flush before a committed job's write-ready is withheld. */\nconst MAX_ANNOUNCE_FLUSH_ATTEMPTS = 5;\nconst ISO_TIMESTAMP_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\nfunction isValidISOTimestamp(value) {\n\tif (!ISO_TIMESTAMP_REGEX.test(value)) return false;\n\treturn !isNaN(new Date(value).getTime());\n}\n/**\n* Carries a failed job out of the execution scope so its transaction rolls\n* back. A scope callback that returns commits, whatever result it returns, so\n* a returned failure would leave the writes the job made before it failed\n* standing. Never escapes executeJob: the failure goes back to being a\n* returned JobResult there, which is what the queue, the worker protocol and\n* every test expect a failed job to look like.\n*/\n/** The ids of a purge job's request, which a drive purge may precede. */\nfunction purgeRequestDocumentIds(job) {\n\tconst ids = job.meta.purgeRequestDocumentIds;\n\treturn Array.isArray(ids) ? ids.filter((id) => typeof id === \"string\") : [];\n}\nconst MARKER_INPUT_KEYS = /* @__PURE__ */ new Set([\n\t\"documentId\",\n\t\"documentType\",\n\t\"purgedAtUtcIso\",\n\t\"requestId\"\n]);\n/** A peer's marker must name this job's id on main and carry nothing else. */\nfunction malformedMarker(job) {\n\tconst action = job.operations.find((operation) => isPurgeMarker(operation))?.action;\n\tconst input = action?.input;\n\tconst refuse = (reason) => new InvalidSignatureError(job.documentId, \"ID_MISMATCH\", `marker ${action?.id ?? \"?\"} ${reason}`);\n\tif (typeof input !== \"object\" || input === null) return refuse(\"carries no input\");\n\tconst extra = Object.keys(input).filter((key) => !MARKER_INPUT_KEYS.has(key));\n\tif (extra.length > 0) return refuse(`carries unexpected input ${extra.join(\", \")}`);\n\tfor (const key of MARKER_INPUT_KEYS) if (typeof input[key] !== \"string\" || input[key] === \"\") return refuse(`input.${key} is not a non-empty string`);\n\tconst purgedAt = Date.parse(input.purgedAtUtcIso);\n\tif (Number.isNaN(purgedAt) || new Date(purgedAt).toISOString() !== input.purgedAtUtcIso) return refuse(\"input.purgedAtUtcIso is not an ISO timestamp\");\n\tif (input.documentId !== job.documentId || job.branch !== \"main\" || action?.scope !== \"document\") return refuse(`does not purge ${job.documentId} on document/main`);\n}\nvar JobRollbackSignal = class extends Error {\n\tresult;\n\tconstructor(result) {\n\t\tsuper(\"job rolled back\");\n\t\tthis.result = result;\n\t\tthis.name = \"JobRollbackSignal\";\n\t}\n};\nvar SimpleJobExecutor = class {\n\tlogger;\n\tregistry;\n\toperationStore;\n\teventBus;\n\twriteCache;\n\toperationIndex;\n\tdocumentMetaCache;\n\tcollectionMembershipCache;\n\tdriveContainerTypes;\n\tconfig;\n\tfeatureFlags;\n\tdecisionModel;\n\tsignatureAdmission;\n\tdocumentActionHandler;\n\texecutionScope;\n\tsigner;\n\tflusher;\n\t/**\n\t* `signer` signs the operations the reducer synthesizes; unsigned if omitted.\n\t* `trustPolicy` decides which keys may sign as which users at admission.\n\t* `flusher` makes a job durable before its write-ready is announced.\n\t*/\n\tconstructor(logger, registry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, driveContainerTypes, config, executionScope, signer, trustPolicy, flusher = new NoopStorageFlusher()) {\n\t\tthis.logger = logger;\n\t\tthis.registry = registry;\n\t\tthis.operationStore = operationStore;\n\t\tthis.eventBus = eventBus;\n\t\tthis.writeCache = writeCache;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.flusher = flusher;\n\t\tthis.signer = signer ?? new PassthroughSigner();\n\t\tthis.featureFlags = resolveFeatureFlags(config.featureFlags);\n\t\tthis.config = {\n\t\t\tfeatureFlags: config.featureFlags ?? {},\n\t\t\tmaxSkipThreshold: config.maxSkipThreshold ?? MAX_SKIP_THRESHOLD,\n\t\t\tmaxConcurrency: config.maxConcurrency ?? 1,\n\t\t\tjobTimeoutMs: config.jobTimeoutMs ?? 3e4,\n\t\t\tdeferredJobTtlMs: config.deferredJobTtlMs ?? 3e4,\n\t\t\tretryBaseDelayMs: config.retryBaseDelayMs ?? 100,\n\t\t\tretryMaxDelayMs: config.retryMaxDelayMs ?? 5e3,\n\t\t\tyieldDeadlineMs: config.yieldDeadlineMs ?? 50,\n\t\t\tbatchApplies: config.batchApplies ?? true,\n\t\t\tsignatureVerification: config.signatureVerification ?? \"enforce\",\n\t\t\tprotocolSupport: config.protocolSupport ?? localSupports(PEER_CAPABILITIES, this.featureFlags).protocols,\n\t\t\tmaxPurgeOperations: config.maxPurgeOperations ?? 2e5,\n\t\t\tdurabilityWaitMs: config.durabilityWaitMs ?? 0\n\t\t};\n\t\tthis.decisionModel = selectDecisionModel(this.featureFlags, registry);\n\t\tthis.signatureAdmission = new SignatureAdmission(this.config.signatureVerification, logger, eventBus, this.featureFlags.documentDecisions ? \"write-cache\" : \"meta\", {\n\t\t\tsigner: this.signer,\n\t\t\tauthEnforcement: this.featureFlags.authEnforcement,\n\t\t\tpolicy: trustPolicy,\n\t\t\ttimeoutMs: Math.min(DEFAULT_TRUST_TIMEOUT_MS, this.config.jobTimeoutMs / 2)\n\t\t});\n\t\tthis.documentActionHandler = new DocumentActionHandler(registry, logger, driveContainerTypes, this.featureFlags, this.decisionModel, this.config.protocolSupport);\n\t\tthis.executionScope = executionScope ?? new DefaultExecutionScope(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache);\n\t}\n\t/**\n\t* Execute a single job by applying all its actions through the appropriate reducers.\n\t* Actions are processed sequentially in order.\n\t*\n\t* The whole job runs inside one execution scope, and a scope callback that\n\t* returns commits. A failed job must therefore leave the scope by throwing,\n\t* or the writes it made before it failed would be durable: JobRollbackSignal\n\t* carries the failure out through the transaction and this method turns it\n\t* back into the returned JobResult every caller expects. A job either fully\n\t* applies or leaves nothing durable behind.\n\t*\n\t* Durable is the whole of the guarantee. The caches are shared with the\n\t* copies the scope hands the job, so a failed job's writes sit in them from\n\t* the moment it makes them until the eviction below, and a concurrent read\n\t* in that window sees a write that is never going to commit. The window is\n\t* not new -- it has always been there for a job that failed by throwing --\n\t* but nothing here closes it, and a caller that needs to know a write is\n\t* real has the job status to ask.\n\t*/\n\tasync executeJob(job, signal, onCommitting) {\n\t\tconst startTime = Date.now();\n\t\tconst touchedStreams = new TouchedStreams();\n\t\tconst postCommitInvalidations = [];\n\t\tconst postCommitMembershipInvalidations = [];\n\t\tconst postCommitMetaInvalidations = [];\n\t\tlet outcome;\n\t\ttry {\n\t\t\toutcome = await this.executionScope.run(async (stores) => {\n\t\t\t\tconst scoped = await this.executeInScope({\n\t\t\t\t\tjob,\n\t\t\t\t\tstartTime,\n\t\t\t\t\tstores,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttouchedStreams,\n\t\t\t\t\tpostCommitInvalidations,\n\t\t\t\t\tpostCommitMembershipInvalidations,\n\t\t\t\t\tpostCommitMetaInvalidations\n\t\t\t\t});\n\t\t\t\tif (!scoped.result.success) throw new JobRollbackSignal(scoped.result);\n\t\t\t\tawait stores.writeIdentity.upsert(writeIdentityRows(scoped.pendingEvent?.operations ?? []));\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tonCommitting?.();\n\t\t\t\treturn scoped;\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.evictTouchedStreams(touchedStreams);\n\t\t\tif (error instanceof JobRollbackSignal) return error.result;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of postCommitInvalidations) this.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\tfor (const documentId of postCommitMembershipInvalidations) this.collectionMembershipCache.invalidate(documentId);\n\t\tfor (const documentId of postCommitMetaInvalidations) this.documentMetaCache.invalidate(documentId);\n\t\tconst { pendingEvent } = outcome;\n\t\tif (pendingEvent && await this.awaitDurable(job, signal)) this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, pendingEvent).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit JOB_WRITE_READY event: @Event : @Error\", pendingEvent, error);\n\t\t});\n\t\treturn outcome.result;\n\t}\n\t/**\n\t* Waits for a flush covering the committed job before its write-ready goes\n\t* out; false withholds the announcement. A failed flush is never a failed\n\t* job, since the commit stands: it is retried, and the announcement is\n\t* withheld once the store is poisoned (the host restarts), the attempts run\n\t* out, the wait outlives `durabilityWaitMs`, or the job's signal aborts.\n\t*/\n\tasync awaitDurable(job, signal) {\n\t\tif (isCursorProtectedLoad(job)) return true;\n\t\tconst budgetMs = this.config.durabilityWaitMs;\n\t\tconst deadline = budgetMs > 0 ? Date.now() + budgetMs : Infinity;\n\t\tfor (let attempt = 1;; attempt++) {\n\t\t\ttry {\n\t\t\t\tif (await this.withinDurabilityWait(this.flusher.flush(), deadline, signal) !== TIMED_OUT) return true;\n\t\t\t\tthis.logger.error(\"Job @JobId committed but its flush outlived the durability wait or the job was aborted; its write-ready is withheld\", job.id);\n\t\t\t\treturn false;\n\t\t\t} catch (error) {\n\t\t\t\tthis.logger.error(\"Flush before announcing job @JobId failed (attempt @Attempt): @Error\", job.id, attempt, error);\n\t\t\t\tif (error instanceof StoragePoisonedError || attempt >= MAX_ANNOUNCE_FLUSH_ATTEMPTS) {\n\t\t\t\t\tthis.logger.error(\"Job @JobId committed but is not durable; its write-ready is withheld\", job.id);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (await this.withinDurabilityWait(delay(Math.min(this.config.retryMaxDelayMs, this.config.retryBaseDelayMs * 2 ** (attempt - 1))), deadline, signal) === TIMED_OUT) return false;\n\t\t}\n\t}\n\t/** Settles with TIMED_OUT at the deadline or on abort; the wait itself is abandoned. */\n\tasync withinDurabilityWait(pending, deadline, signal) {\n\t\tpending.catch(() => void 0);\n\t\tif (signal?.aborted) return TIMED_OUT;\n\t\tlet onAbort;\n\t\tconst aborted = new Promise((resolve) => {\n\t\t\tonAbort = () => resolve(TIMED_OUT);\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t\ttry {\n\t\t\tconst raced = Promise.race([pending, aborted]);\n\t\t\treturn deadline === Infinity ? await raced : await withDeadline(raced, Math.max(0, deadline - Date.now()));\n\t\t} finally {\n\t\t\tif (onAbort) signal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\t/**\n\t* The body of a job, run inside the execution scope's transaction.\n\t*\n\t* The stores and caches it works through are the copies scoped to that\n\t* transaction, so nothing it does is durable until the scope commits. The\n\t* write-ready event is handed back rather than emitted, because a job that\n\t* has not committed yet has nothing to announce.\n\t*/\n\tasync executeInScope(params) {\n\t\tconst { job, startTime, stores: scopeStores, signal, touchedStreams, postCommitInvalidations, postCommitMembershipInvalidations } = params;\n\t\tlet pendingEvent;\n\t\tif (job.kind === \"mutation\") {\n\t\t\tconst reserved = job.actions.find((action) => isPurgeMarker(action));\n\t\t\tif (reserved) return { result: buildErrorResult(job, new ReservedActionError(job.documentId, reserved.type), startTime) };\n\t\t}\n\t\tif (job.kind === \"purge\" || job.kind === \"load\" && job.operations.some((op) => isPurgeMarker(op))) return this.executePurge(params);\n\t\tconst lockedIds = jobWriteIds(job);\n\t\tconst lockFailure = (error) => ({ result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) });\n\t\ttry {\n\t\t\tawait scopeStores.documentLocks.shared(lockedIds);\n\t\t} catch (error) {\n\t\t\treturn lockFailure(error);\n\t\t}\n\t\tlet purged;\n\t\ttry {\n\t\t\tpurged = await scopeStores.documentLocks.purged(lockedIds);\n\t\t} catch (error) {\n\t\t\treturn lockFailure(error);\n\t\t}\n\t\tconst purgedRefusal = this.purgedRefusal(job, purged);\n\t\tif (purgedRefusal) return { result: buildErrorResult(job, purgedRefusal, startTime) };\n\t\tconst purgeFence = new PurgeFence(scopeStores.documentLocks, new Set(lockedIds), purged);\n\t\tconst stores = {\n\t\t\t...scopeStores,\n\t\t\twriteCache: new FencedWriteCache(scopeStores.writeCache, purgeFence, (documentId) => {\n\t\t\t\tscopeStores.writeCache.invalidate(documentId);\n\t\t\t\tscopeStores.documentMetaCache.invalidate(documentId);\n\t\t\t})\n\t\t};\n\t\tconst unsupported = await this.unsupportedStoredProtocol(job, stores, signal);\n\t\tif (unsupported) return { result: buildErrorResult(job, unsupported, startTime) };\n\t\tconst indexTxn = stores.operationIndex.start();\n\t\tif (job.kind === \"load\") {\n\t\t\tconst loadResult = await this.executeLoadJob({\n\t\t\t\tjob,\n\t\t\t\tstartTime,\n\t\t\t\tindexTxn,\n\t\t\t\tstores,\n\t\t\t\tsignal,\n\t\t\t\treplayingAcceptedHistory: true,\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\tpostCommitInvalidations,\n\t\t\t\tpostCommitMembershipInvalidations,\n\t\t\t\ttouchedStreams,\n\t\t\t\tpurgeFence\n\t\t\t});\n\t\t\tif (loadResult.success && loadResult.operationsWithContext) {\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tpostCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());\n\t\t\t\tfor (let i = 0; i < loadResult.operationsWithContext.length; i++) loadResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\tconst collectionMemberships = loadResult.operationsWithContext.length > 0 ? await this.getCollectionMembershipsForOperations(loadResult.operationsWithContext, stores) : {};\n\t\t\t\tpendingEvent = {\n\t\t\t\t\tjobId: job.id,\n\t\t\t\t\toperations: loadResult.operationsWithContext,\n\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\tcollectionMemberships\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult: loadResult,\n\t\t\t\tpendingEvent\n\t\t\t};\n\t\t}\n\t\tif (job.kind === \"reevaluation\") {\n\t\t\tconst reevalResult = await this.executeReevaluationJob({\n\t\t\t\tjob,\n\t\t\t\tstartTime,\n\t\t\t\tindexTxn,\n\t\t\t\tstores,\n\t\t\t\tsignal,\n\t\t\t\treplayingAcceptedHistory: false,\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\tpostCommitInvalidations,\n\t\t\t\tpostCommitMembershipInvalidations,\n\t\t\t\ttouchedStreams,\n\t\t\t\tpurgeFence\n\t\t\t});\n\t\t\tif (reevalResult.success && reevalResult.operationsWithContext) {\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tpostCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());\n\t\t\t\tfor (let i = 0; i < reevalResult.operationsWithContext.length; i++) reevalResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\tif (reevalResult.operationsWithContext.length > 0) {\n\t\t\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(reevalResult.operationsWithContext, stores);\n\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\toperations: reevalResult.operationsWithContext,\n\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult: reevalResult,\n\t\t\t\tpendingEvent\n\t\t\t};\n\t\t}\n\t\tlet admission;\n\t\ttry {\n\t\t\tadmission = await this.signatureAdmission.admitMutation(job, stores, signal);\n\t\t} catch (error) {\n\t\t\treturn { result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) };\n\t\t}\n\t\tif (admission.kind === \"refused\") return { result: buildErrorResult(job, admission.error, startTime) };\n\t\tlet committed;\n\t\ttry {\n\t\t\tcommitted = await this.reloadCommitted(admission.committed, stores, signal);\n\t\t} catch (error) {\n\t\t\treturn { result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) };\n\t\t}\n\t\tconst committedIds = new Set(admission.committed.map((write) => write.actionId));\n\t\tconst fresh = committedIds.size === 0 ? job : {\n\t\t\t...job,\n\t\t\tactions: job.actions.filter((action) => !committedIds.has(action.id))\n\t\t};\n\t\tif (fresh.actions.length === 0) return this.committedOutcome(job, committed, [], [], stores, startTime);\n\t\tconst positioned = await this.positionByTimestamp(fresh, stores, signal);\n\t\tif (positioned.error) return { result: buildErrorResult(job, positioned.error, startTime) };\n\t\tconst executing = {\n\t\t\tjob: fresh,\n\t\t\tstartTime,\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsignal,\n\t\t\treplayingAcceptedHistory: false,\n\t\t\tevaluatedByPosition: positioned.evaluatedByPosition,\n\t\t\tpostCommitInvalidations,\n\t\t\tpostCommitMembershipInvalidations,\n\t\t\ttouchedStreams,\n\t\t\tpurgeFence\n\t\t};\n\t\tconst actionResult = await this.processActions(positioned.writes, executing);\n\t\tif (!actionResult.success) return { result: {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: actionResult.error,\n\t\t\tduration: Date.now() - startTime\n\t\t} };\n\t\tconst reevaluation = await this.reevaluateIfCriteriaMet({\n\t\t\tscope: job.scope,\n\t\t\toperations: actionResult.generatedOperations\n\t\t}, executing);\n\t\tif (reevaluation.error) return { result: {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: reevaluation.error,\n\t\t\tduration: Date.now() - startTime\n\t\t} };\n\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\tpostCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());\n\t\tconst written = [...actionResult.operationsWithContext, ...reevaluation.operationsWithContext];\n\t\tfor (let i = 0; i < written.length; i++) written[i].context.ordinal = ordinals[i];\n\t\treturn this.committedOutcome(job, committed, written, [...actionResult.generatedOperations, ...reevaluation.operationsWithContext.map((owc) => owc.operation)], stores, startTime);\n\t}\n\t/** A load names only its own id purged; a foreign one is ID_MISMATCH. */\n\tpurgedRefusal(job, purged) {\n\t\tif (purged.size === 0) return;\n\t\tif (purged.has(job.documentId)) return new DocumentPurgedError(job.documentId);\n\t\tconst actions = [...job.actions, ...job.operations.map((operation) => operation.action)];\n\t\tfor (const action of actions) {\n\t\t\tif (!DOCUMENT_SCOPE_ACTIONS.has(action.type)) continue;\n\t\t\tconst target = targetDocumentId(action, job.documentId);\n\t\t\tif (!purged.has(target)) continue;\n\t\t\tif (job.kind === \"mutation\") return new DocumentPurgedError(target);\n\t\t\treturn new InvalidSignatureError(job.documentId, \"ID_MISMATCH\", `${action.type} ${action.id} in ${job.documentId} writes purged ${target}`);\n\t\t}\n\t\tif (job.kind !== \"mutation\") return;\n\t\tfor (const action of job.actions) {\n\t\t\tconst target = relationshipTarget(action);\n\t\t\tif (action.type === \"ADD_RELATIONSHIP\" && target !== void 0 && purged.has(target)) return new DocumentPurgedError(target, `${action.type} target ${target} was purged`);\n\t\t\tif (action.scope !== \"auth\") continue;\n\t\t\tconst group = mentionedGroupIds(action).find((id) => purged.has(id));\n\t\t\tif (group !== void 0) return new DocumentPurgedError(group, `${action.type} names purged group ${group}`);\n\t\t}\n\t}\n\t/** A purge job or a marker load: the exclusive lock is the job's only lock. */\n\tasync executePurge(params) {\n\t\tconst { job, startTime, stores } = params;\n\t\tconst fail = (error) => ({ result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) });\n\t\tif (job.kind === \"load\") {\n\t\t\tconst malformed = malformedMarker(job);\n\t\t\tif (malformed) return fail(malformed);\n\t\t}\n\t\tconst purger = stores.purger;\n\t\tif (!purger) return fail(/* @__PURE__ */ new Error(`Purge of ${job.documentId} needs a transactional scope`));\n\t\ttry {\n\t\t\tawait stores.documentLocks.exclusive(job.documentId);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t\tlet alreadyPurged;\n\t\ttry {\n\t\t\talreadyPurged = (await stores.documentLocks.purged([job.documentId])).has(job.documentId);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t\tif (alreadyPurged) return {\n\t\t\tresult: {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [],\n\t\t\t\toperationsWithContext: [],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t},\n\t\t\tpendingEvent: {\n\t\t\t\tjobId: job.id,\n\t\t\t\toperations: [],\n\t\t\t\tjobMeta: job.meta,\n\t\t\t\tcollectionMemberships: {}\n\t\t\t}\n\t\t};\n\t\tlet commit;\n\t\ttry {\n\t\t\tcommit = job.kind === \"purge\" ? await this.preparePurgeJob(params, purger) : await this.preparePurgeLoad(params, purger);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t\tif (commit instanceof Error) return fail(commit);\n\t\ttry {\n\t\t\treturn await this.commitPurge(params, commit);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t}\n\t/** Preconditions 1-5, then the marker this host signs. */\n\tasync preparePurgeJob(params, purger) {\n\t\tconst { job, stores, signal } = params;\n\t\tconst documentId = job.documentId;\n\t\tif (!job.purge) return /* @__PURE__ */ new Error(`Purge job ${job.id} carries no purge options`);\n\t\tconst held = await this.heldStreams(purger, documentId);\n\t\tif (held.branches.length === 0) return new DocumentNotDeletedError(documentId, `Document ${documentId} is not held here`);\n\t\tlet documentType;\n\t\tfor (const branch of held.branches) {\n\t\t\tlet meta;\n\t\t\ttry {\n\t\t\t\tmeta = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn new DocumentNotDeletedError(documentId, `Document ${documentId} has no readable state on ${branch}: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t}\n\t\t\tif (!meta.state.isDeleted) return new DocumentNotDeletedError(documentId, `Document ${documentId} is not deleted on branch ${branch}`);\n\t\t\tdocumentType ??= meta.documentType;\n\t\t}\n\t\tif (documentType === void 0) return new DocumentNotDeletedError(documentId);\n\t\tif (documentType === groupDocumentType) {\n\t\t\tconst referencers = await purger.groupReferencersInHistory(documentId);\n\t\t\tif (referencers.length > 0) return new GroupInUseError(documentId, referencers);\n\t\t}\n\t\tlet survivors = [];\n\t\tif (this.driveContainerTypes.has(documentType)) {\n\t\t\tconst requested = new Set(purgeRequestDocumentIds(job));\n\t\t\tconst members = await this.driveMembers(purger, stores, documentId, held.branches);\n\t\t\tconst blocking = members.required.filter((id) => !requested.has(id));\n\t\t\tif (blocking.length > 0) return new DocumentNotDeletedError(documentId, `Drive ${documentId} cannot be purged: ${blocking.join(\", \")} neither purged nor in the request`);\n\t\t\tsurvivors = members.survivors;\n\t\t}\n\t\tconst operationCount = await purger.operationCount(documentId);\n\t\tif (operationCount > this.config.maxPurgeOperations && !job.purge.allowLarge) return new PurgeTooLargeError(documentId, operationCount, this.config.maxPurgeOperations);\n\t\treturn {\n\t\t\tpurger,\n\t\t\tmarker: await this.signMarker(documentId, documentType, job.purge.requestId, signal),\n\t\t\tdocumentType,\n\t\t\theld,\n\t\t\tsourceRemote: \"\",\n\t\t\tcollectionIds: [],\n\t\t\tsurvivors\n\t\t};\n\t}\n\t/** A peer's marker, admitted alone; a receiver cannot refuse an erasure. */\n\tasync preparePurgeLoad(params, purger) {\n\t\tconst { job, stores, signal } = params;\n\t\tconst documentId = job.documentId;\n\t\tconst marker = job.operations.find((operation) => isPurgeMarker(operation));\n\t\tconst refusal = await this.signatureAdmission.admitMarker(job, marker, signal);\n\t\tif (refusal) return refusal;\n\t\tconst held = await this.heldStreams(purger, documentId);\n\t\tlet documentType = marker.action.input.documentType;\n\t\tlet appliedDeletion = held.branches.length > 0;\n\t\tif (held.branches.length > 0) try {\n\t\t\tconst meta = await stores.documentMetaCache.getDocumentMeta(documentId, held.branches.includes(\"main\") ? \"main\" : held.branches[0], signal);\n\t\t\tdocumentType = meta.documentType;\n\t\t\tappliedDeletion = !meta.state.isDeleted;\n\t\t} catch {}\n\t\tlet survivors = [];\n\t\tif (this.driveContainerTypes.has(documentType)) {\n\t\t\tconst members = await this.driveMembers(purger, stores, documentId, held.branches);\n\t\t\tsurvivors = [...members.required, ...members.survivors];\n\t\t}\n\t\tconst sourceRemote = typeof job.meta.sourceRemote === \"string\" ? job.meta.sourceRemote : \"\";\n\t\tconst collectionId = sourceRemote ? await purger.remoteCollection(sourceRemote) : void 0;\n\t\treturn {\n\t\t\tpurger,\n\t\t\tmarker: purgeMarkerOperation(marker.action),\n\t\t\tdocumentType,\n\t\t\theld,\n\t\t\tsourceRemote,\n\t\t\tcollectionIds: collectionId === void 0 ? [] : [collectionId],\n\t\t\tsurvivors,\n\t\t\t...appliedDeletion ? { appliedDeletion: true } : {}\n\t\t};\n\t}\n\t/** Execution: delete, write the marker and its twin, tombstone, reopen. */\n\tasync commitPurge(params, commit) {\n\t\tconst { job, startTime, stores, signal, touchedStreams } = params;\n\t\tconst { purger, marker, documentType, held, sourceRemote } = commit;\n\t\tconst documentId = job.documentId;\n\t\tconst streams = [...held.streams, {\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\"\n\t\t}];\n\t\tfor (const stream of streams) {\n\t\t\ttouchedStreams.add(documentId, stream.scope, stream.branch);\n\t\t\tparams.postCommitInvalidations.push({\n\t\t\t\tdocumentId,\n\t\t\t\t...stream\n\t\t\t});\n\t\t}\n\t\tparams.postCommitMetaInvalidations.push(documentId);\n\t\tconst removedRows = await purger.deleteRows(documentId);\n\t\tconst [stored] = await stores.operationStore.apply(documentId, documentType, \"document\", \"main\", 0, (txn) => {\n\t\t\ttxn.addOperations(marker);\n\t\t}, signal);\n\t\tconst indexTxn = stores.operationIndex.start();\n\t\tindexTxn.write([{\n\t\t\t...stored,\n\t\t\tdocumentId,\n\t\t\tdocumentType,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tsourceRemote\n\t\t}]);\n\t\tconst [ordinal] = await stores.operationIndex.commit(indexTxn, signal);\n\t\tawait purger.writeTombstone({\n\t\t\tdocumentId,\n\t\t\tordinal,\n\t\t\tremovedRows,\n\t\t\tpurgedAtUtc: marker.action.input.purgedAtUtcIso,\n\t\t\trequestId: marker.action.input.requestId\n\t\t});\n\t\tconst collections = await purger.reopenMemberships(documentId, ordinal, commit.collectionIds);\n\t\tparams.postCommitMembershipInvalidations.push(documentId, ...commit.survivors, ...indexTxn.getMembershipInvalidations());\n\t\tconst operationWithContext = {\n\t\t\toperation: stored,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: \"document\",\n\t\t\t\tbranch: \"main\",\n\t\t\t\tdocumentType,\n\t\t\t\tordinal,\n\t\t\t\t...commit.appliedDeletion ? { appliedDeletion: true } : {}\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [stored],\n\t\t\t\toperationsWithContext: [operationWithContext],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t},\n\t\t\tpendingEvent: {\n\t\t\t\tjobId: job.id,\n\t\t\t\toperations: [operationWithContext],\n\t\t\t\tjobMeta: job.meta,\n\t\t\t\tcollectionMemberships: { [documentId]: collections }\n\t\t\t}\n\t\t};\n\t}\n\tasync heldStreams(purger, documentId) {\n\t\tconst streams = await purger.streams(documentId);\n\t\treturn {\n\t\t\tstreams,\n\t\t\tbranches: [...new Set(streams.filter((stream) => stream.scope === \"document\").map((stream) => stream.branch))]\n\t\t};\n\t}\n\t/** Members a drive purge needs gone, and those living on elsewhere. */\n\tasync driveMembers(purger, stores, driveId, branches) {\n\t\tconst required = /* @__PURE__ */ new Set();\n\t\tconst survivors = /* @__PURE__ */ new Set();\n\t\tfor (const branch of branches.length > 0 ? branches : [\"main\"]) {\n\t\t\tconst collectionId = DriveCollectionId.forDrive(driveId, branch).key;\n\t\t\tconst members = await purger.collectionMembers(collectionId, driveId, branch);\n\t\t\tconst purged = await stores.documentLocks.purged(members.map((member) => member.documentId));\n\t\t\tfor (const member of members) {\n\t\t\t\tif (purged.has(member.documentId)) continue;\n\t\t\t\tif (member.required) required.add(member.documentId);\n\t\t\t\telse survivors.add(member.documentId);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\trequired: [...required],\n\t\t\tsurvivors: [...survivors]\n\t\t};\n\t}\n\t/** The marker, signed by this executor's signer as any peer admits it. */\n\tasync signMarker(documentId, documentType, requestId, signal) {\n\t\tconst action = purgeDocumentAction({\n\t\t\tdocumentId,\n\t\t\tdocumentType,\n\t\t\trequestId\n\t\t});\n\t\tconst signature = await this.signer.signAction(action, {\n\t\t\tdocumentId,\n\t\t\tbranch: \"main\"\n\t\t}, signal);\n\t\treturn purgeMarkerOperation({\n\t\t\t...action,\n\t\t\tcontext: { signer: {\n\t\t\t\t...actionSignerIdentity(this.signer),\n\t\t\t\tsignatures: [signature]\n\t\t\t} }\n\t\t});\n\t}\n\t/** A stored document at a version this reactor does not run is read-only here. */\n\tasync unsupportedStoredProtocol(job, stores, signal) {\n\t\tlet versions;\n\t\ttry {\n\t\t\tversions = this.featureFlags.documentDecisions && job.kind !== \"load\" ? (await stores.writeCache.getState(job.documentId, \"document\", job.branch, void 0, signal)).header.protocolVersions : (await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal)).protocolVersions;\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\treturn this.documentActionHandler.unsupportedProtocol(job.documentId, versions);\n\t}\n\t/**\n\t* A successful mutation's result and the write-ready event it owes, carrying\n\t* what earlier attempts committed ahead of what this one wrote.\n\t*/\n\tasync committedOutcome(job, reloaded, written, generated, stores, startTime) {\n\t\tconst operationsWithContext = [...reloaded, ...written];\n\t\tlet pendingEvent;\n\t\tif (operationsWithContext.length > 0) {\n\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(operationsWithContext, stores);\n\t\t\tpendingEvent = {\n\t\t\t\tjobId: job.id,\n\t\t\t\toperations: operationsWithContext,\n\t\t\t\tjobMeta: job.meta,\n\t\t\t\tsubmittedActionIds: submittedActionIds(job),\n\t\t\t\tcollectionMemberships\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [...reloaded.map((entry) => entry.operation), ...generated],\n\t\t\t\toperationsWithContext,\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t},\n\t\t\tpendingEvent\n\t\t};\n\t}\n\t/**\n\t* The stored operations of writes an earlier attempt committed, as a fresh\n\t* write would report them. State is rebuilt from the write cache, and left\n\t* out when it cannot be.\n\t*/\n\tasync reloadCommitted(writes, stores, signal) {\n\t\tconst streams = /* @__PURE__ */ new Map();\n\t\tfor (const write of writes) {\n\t\t\tconst key = `${write.documentId}\\u0000${write.scope}\\u0000${write.branch}`;\n\t\t\tstreams.set(key, [...streams.get(key) ?? [], write]);\n\t\t}\n\t\tconst reloaded = [];\n\t\tfor (const group of streams.values()) {\n\t\t\tconst { documentId, scope, branch } = group[0];\n\t\t\tconst opIds = [...new Set(group.map((write) => write.opId))];\n\t\t\tconst operations = await stores.operationStore.getOperationsByIds(documentId, scope, branch, opIds, signal);\n\t\t\tconst ordinals = await stores.operationIndex.getOrdinalsByOpIds(documentId, scope, branch, opIds, signal);\n\t\t\tconst { documentType } = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);\n\t\t\tfor (const operation of operations.sort((a, b) => a.index - b.index)) reloaded.push({\n\t\t\t\toperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch,\n\t\t\t\t\tdocumentType,\n\t\t\t\t\tresultingState: await this.rebuiltState(stores, {\n\t\t\t\t\t\tdocumentId,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tbranch\n\t\t\t\t\t}, operation, signal),\n\t\t\t\t\tordinal: ordinals.get(operation.id) ?? 0\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn reloaded;\n\t}\n\tasync rebuiltState(stores, stream, operation, signal) {\n\t\ttry {\n\t\t\tconst document = await stores.writeCache.getState(stream.documentId, stream.scope, stream.branch, operation.index, signal);\n\t\t\treturn JSON.stringify({\n\t\t\t\t...document.state,\n\t\t\t\theader: document.header\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.logger.warn(\"No state for committed operation @OperationId in @Stream: @Error\", operation.id, stream, error);\n\t\t\treturn;\n\t\t}\n\t}\n\t/**\n\t* Drops the cached state of every stream a job wrote, after its transaction\n\t* did not commit.\n\t*\n\t* The caches are shared by reference with the copies the scope hands the job,\n\t* so a rollback undoes nothing in them: what the job put there survives, as\n\t* does anything a read filled from the store while the job's own writes were\n\t* still uncommitted. An eviction that throws is swallowed rather than allowed\n\t* to replace the failure the caller is owed, and the remaining streams are\n\t* still evicted.\n\t*/\n\tevictTouchedStreams(touchedStreams) {\n\t\tfor (const entry of touchedStreams) try {\n\t\t\tthis.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\t\tthis.documentMetaCache.invalidate(entry.documentId, entry.branch);\n\t\t\tthis.collectionMembershipCache.invalidate(entry.documentId);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to evict cached state for rolled back @Stream : @Error\", entry, error);\n\t\t}\n\t}\n\tasync getCollectionMembershipsForOperations(operations, stores) {\n\t\tconst documentIds = [...new Set(operations.map((op) => op.context.documentId))];\n\t\treturn stores.collectionMembershipCache.getCollectionsForDocuments(documentIds);\n\t}\n\tasync processActions(writes, executing) {\n\t\tconst { job, signal } = executing;\n\t\tconst actions = writes.map((write) => write.action);\n\t\tconst generatedOperations = [];\n\t\tconst operationsWithContext = [];\n\t\tfor (const action of actions) if (action.timestampUtcMs && !isValidISOTimestamp(action.timestampUtcMs)) return {\n\t\t\tsuccess: false,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext,\n\t\t\terror: new InvalidOperationTimestampError(job.documentId, action.scope, action.timestampUtcMs, `action ${action.type} (id: ${action.id})`)\n\t\t};\n\t\tlet lastYield = performance.now();\n\t\tif (this.config.batchApplies && this.canBatch(writes, executing)) {\n\t\t\tconst batched = await this.executeRegularActionsBatched(writes, executing);\n\t\t\tconst error = this.accumulateResultOrReturnError(batched, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext\n\t\t\t};\n\t\t}\n\t\tfor (const write of writes) {\n\t\t\tconst result = DOCUMENT_SCOPE_ACTIONS.has(write.action.type) ? await this.documentActionHandler.execute(write, executing) : await this.executeRegularAction(write, executing);\n\t\t\tconst error = this.accumulateResultOrReturnError(result, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (signal?.aborted) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tgeneratedOperations,\n\t\t\t\t\toperationsWithContext,\n\t\t\t\t\terror: /* @__PURE__ */ new Error(\"Aborted\")\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext\n\t\t};\n\t}\n\t/**\n\t* Decides a write and reduces it, without persisting anything.\n\t*\n\t* Split from the commit so one write and a batch of them share this logic\n\t* rather than keeping two copies of it. `baseDocument` lets a batch thread\n\t* the previous action's result forward instead of reading its own write back\n\t* out of the cache, which is the only reason the reduce has to be sequential.\n\t*/\n\tasync prepareRegularWrite(write, executing, baseDocument) {\n\t\tconst { action, skip, sourceOperation, sourceRemote, deniedReason } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tlet appendCondition;\n\t\tlet documentVersion;\n\t\tconst alreadyEvaluated = this.featureFlags.documentDecisions && (executing.replayingAcceptedHistory || executing.evaluatedByPosition);\n\t\tif (this.featureFlags.documentDecisions && !alreadyEvaluated) {\n\t\t\tconst target = {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tbranch: job.branch\n\t\t\t};\n\t\t\tlet admission;\n\t\t\ttry {\n\t\t\t\tadmission = await decideAtHead(this.decisionModel, stores.writeCache, target, {\n\t\t\t\t\taddress: action.context?.signer?.user.address,\n\t\t\t\t\tkey: action.context?.signer?.app.key\n\t\t\t\t}, {\n\t\t\t\t\tverb: \"execute\",\n\t\t\t\t\tscope: action.scope,\n\t\t\t\t\toperation: action.type\n\t\t\t\t}, signal, this.featureFlags.authConditions ? {\n\t\t\t\t\tactionInput: action.input,\n\t\t\t\t\tcarriedDocument: baseDocument\n\t\t\t\t} : void 0);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tif (admission.evaluation.decision === \"deny\") return buildErrorResult(job, refusalError(admission.evaluation.reason, job.documentId, admission.deletedAtUtcIso, action), startTime);\n\t\t\tappendCondition = admission.appendCondition;\n\t\t\tdocumentVersion = admission.documentVersion;\n\t\t} else if (alreadyEvaluated) documentVersion = (await stores.writeCache.getState(job.documentId, \"document\", job.branch, void 0, signal)).state.document.version;\n\t\telse {\n\t\t\tlet docMeta;\n\t\t\ttry {\n\t\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tif (docMeta.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\t\tdocumentVersion = docMeta.state.version;\n\t\t}\n\t\tif (isUndoRedo(action) || skip > 0) stores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tlet document;\n\t\tif (baseDocument !== void 0) document = baseDocument;\n\t\telse try {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (!this.featureFlags.authEnforcement && !executing.replayingAcceptedHistory) {\n\t\t\tconst subject = {\n\t\t\t\taddress: write.action.context?.signer?.user.address,\n\t\t\t\tkey: write.action.context?.signer?.app.key\n\t\t\t};\n\t\t\tif (decide(document.state.auth, subject, {\n\t\t\t\tverb: \"execute\",\n\t\t\t\tscope: action.scope,\n\t\t\t\toperation: action.type\n\t\t\t}) === \"deny\") return buildErrorResult(job, new AuthorizationDeniedError(job.documentId, action.scope, action.type, subject.address), startTime);\n\t\t}\n\t\tlet module;\n\t\ttry {\n\t\t\tmodule = this.registry.getModule(document.header.documentType, normalizeDocumentModelVersion(documentVersion));\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet updatedDocument;\n\t\tif (deniedReason !== void 0) {\n\t\t\tconst index = getNextIndexForScope(document, job.scope);\n\t\t\tconst denied = createOperation(action, index, skip, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch\n\t\t\t});\n\t\t\tdenied.deniedReason = deniedReason;\n\t\t\tlet standing = document;\n\t\t\tif (skip > 0) try {\n\t\t\t\tstanding = await stores.writeCache.getState(job.documentId, job.scope, job.branch, index - skip - 1, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tdenied.hash = hashDocumentStateForScope(standing, job.scope);\n\t\t\tupdatedDocument = {\n\t\t\t\t...standing,\n\t\t\t\toperations: {\n\t\t\t\t\t...standing.operations,\n\t\t\t\t\t[job.scope]: [...standing.operations[job.scope] ?? [], denied]\n\t\t\t\t}\n\t\t\t};\n\t\t} else try {\n\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\tconst reducerOptions = sourceOperation ? {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\treplayOptions: { operation: sourceOperation },\n\t\t\t\tprotocolVersion\n\t\t\t} : {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tprotocolVersion\n\t\t\t};\n\t\t\tupdatedDocument = withProtocolVersions(module.reducer(document, action, void 0, reducerOptions), document.header.protocolVersions);\n\t\t} catch (error) {\n\t\t\tconst contextMessage = `Failed to apply action to document:\\n Action type: ${action.type}\\n Document ID: ${job.documentId}\\n Document type: ${document.header.documentType}\\n Scope: ${job.scope}\\n Original error: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\tconst enhancedError = new Error(contextMessage);\n\t\t\tif (error instanceof Error && error.stack) enhancedError.stack = `${contextMessage}\\n\\nOriginal stack trace:\\n${error.stack}`;\n\t\t\treturn buildErrorResult(job, enhancedError, startTime);\n\t\t}\n\t\tconst scope = job.scope;\n\t\tconst operations = updatedDocument.operations[scope];\n\t\tif (operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"No operation generated from action\"), startTime);\n\t\tconst newOperation = operations[operations.length - 1];\n\t\tif (!isUndoRedo(action)) newOperation.skip = skip;\n\t\tif (deniedReason === void 0 && sourceOperation === void 0 && !executing.replayingAcceptedHistory && isSynthesized(action, newOperation, document.operations[scope] ?? [])) try {\n\t\t\tawait signSynthesized(newOperation, action, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope,\n\t\t\t\tbranch: job.branch\n\t\t\t}, this.signer, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tconst resultingState = JSON.stringify({\n\t\t\t...updatedDocument.state,\n\t\t\theader: updatedDocument.header\n\t\t});\n\t\treturn {\n\t\t\taction,\n\t\t\tsourceRemote,\n\t\t\tscope,\n\t\t\tdocument,\n\t\t\tupdatedDocument,\n\t\t\toperation: newOperation,\n\t\t\tresultingState,\n\t\t\tappendCondition,\n\t\t\tdenied: deniedReason !== void 0\n\t\t};\n\t}\n\t/**\n\t* Persists a run of prepared writes in one store transaction.\n\t*\n\t* The store has always accepted many operations per apply; the executor only\n\t* ever handed it one. Passing the whole run means one advisory lock over the\n\t* read set and one guarded insert for the batch, instead of one of each per\n\t* operation.\n\t*\n\t* The append condition is taken from the first write. Every write in a run\n\t* reads the same streams at the same revisions, because nothing outside the\n\t* run can change them mid-batch, and the caller has already refused to batch\n\t* the scopes where that does not hold.\n\t*/\n\tasync commitPreparedWrites(prepared, executing) {\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tconst first = prepared[0];\n\t\tconst last = prepared[prepared.length - 1];\n\t\tconst scope = first.scope;\n\t\tconst documentType = first.document.header.documentType;\n\t\tconst operations = prepared.map((write) => write.operation);\n\t\texecuting.touchedStreams.add(job.documentId, scope, job.branch);\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(job.documentId, documentType, scope, job.branch, first.operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(...operations);\n\t\t\t}, signal, first.appendCondition);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to write operation to IOperationStore (@documentId @scope @branch): @Operation @Error\", job.documentId, scope, job.branch, operations, error);\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\tif (AppendConditionFailedError.isError(error)) for (const stream of error.condition.streams) stores.writeCache.invalidate(stream.documentId, stream.scope, stream.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tstoredOperations = storedOperations.map((operation, position) => withReducerErrorIdentity(operation, operations[position]));\n\t\tconst head = storedOperations[storedOperations.length - 1];\n\t\tlast.updatedDocument.header.revision = {\n\t\t\t...last.updatedDocument.header.revision,\n\t\t\t[scope]: head.index + 1\n\t\t};\n\t\tstores.writeCache.putRun(job.documentId, scope, job.branch, storedOperations.map((operation, position) => ({\n\t\t\trevision: operation.index,\n\t\t\tdocument: prepared[position].updatedDocument\n\t\t})));\n\t\tindexTxn.write(storedOperations.map((operation, position) => ({\n\t\t\t...operation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope,\n\t\t\tsourceRemote: prepared[position].sourceRemote\n\t\t})));\n\t\tif (scope === \"auth\") for (const write of prepared) indexTxn.recordGroupReferences(job.documentId, mentionedGroupIds(write.action));\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: storedOperations,\n\t\t\toperationsWithContext: storedOperations.map((operation, position) => ({\n\t\t\t\toperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId: job.documentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch: job.branch,\n\t\t\t\t\tdocumentType,\n\t\t\t\t\tresultingState: prepared[position].resultingState,\n\t\t\t\t\tordinal: 0\n\t\t\t\t}\n\t\t\t})),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\t/**\n\t* Whether a job's writes may share one store transaction.\n\t*\n\t* Deliberately narrow. Batching changes only how many transactions the\n\t* operations arrive in, and every condition below is a case where that would\n\t* change something else as well:\n\t*\n\t* - A document-scope action goes through its own handler, which has its own\n\t* apply and its own reasons for it.\n\t* - A positional or replayed run carries skips and re-appended operations,\n\t* whose indices are not a simple ascending run from the head.\n\t* - UNDO, REDO and NOOP-with-skip each invalidate the write cache to\n\t* force a full-history rebuild, so they cannot be reduced against state\n\t* threaded from the write before them.\n\t* - The auth scope decides later writes against the policy earlier ones\n\t* install, so a batch would decide them all against the policy as it stood\n\t* before the batch.\n\t* - The document scope is read by every decision model, so writing it is\n\t* writing part of the read set; the per-write conditions would not agree.\n\t*\n\t* A run that fails any of these is executed one write at a time, unchanged.\n\t*/\n\tcanBatch(writes, executing) {\n\t\tif (writes.length < 2) return false;\n\t\tif (executing.evaluatedByPosition || executing.replayingAcceptedHistory) return false;\n\t\tconst scope = executing.job.scope;\n\t\tif (scope === \"auth\" || scope === \"document\") return false;\n\t\treturn writes.every((write) => {\n\t\t\tconst type = write.action.type;\n\t\t\treturn write.skip === 0 && write.deniedReason === void 0 && write.sourceOperation === void 0 && !DOCUMENT_SCOPE_ACTIONS.has(type) && !isUndoRedo(write.action) && type !== \"NOOP\";\n\t\t});\n\t}\n\t/**\n\t* Decides and reduces a run of writes, then persists them together.\n\t*\n\t* The reduce stays sequential - each action needs the state the one before it\n\t* produced - but the result is threaded in memory rather than read back from\n\t* the cache, and the whole run reaches the store in a single apply.\n\t*\n\t* A write that turns out to be denied abandons the batch and replays the run\n\t* one write at a time, because a denied write holds a position of its own and\n\t* that is the path where the per-write behaviour is load-bearing. A write\n\t* that cannot be prepared fails the job outright: preparing is a read, so the\n\t* replay would only reach the same failure, and the job leaves nothing behind\n\t* either way.\n\t*/\n\tasync executeRegularActionsBatched(writes, executing) {\n\t\tconst prepared = [];\n\t\tlet carried;\n\t\tlet lastYield = performance.now();\n\t\tfor (const write of writes) {\n\t\t\tconst outcome = await this.prepareRegularWrite(write, executing, carried);\n\t\t\tif (\"success\" in outcome) return outcome;\n\t\t\tif (outcome.denied) return this.executeRegularActionsSequentially(writes, executing);\n\t\t\tprepared.push(outcome);\n\t\t\tcarried = outcome.updatedDocument;\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (executing.signal?.aborted) return buildErrorResult(executing.job, /* @__PURE__ */ new Error(\"Aborted\"), executing.startTime);\n\t\t\t}\n\t\t}\n\t\tif (!this.conditionsAgree(prepared)) return this.executeRegularActionsSequentially(writes, executing);\n\t\treturn this.commitPreparedWrites(prepared, executing);\n\t}\n\t/** Whether every prepared write carries the same read-set condition. */\n\tconditionsAgree(prepared) {\n\t\tconst shape = (write) => write.appendCondition === void 0 ? \"none\" : JSON.stringify([...write.appendCondition.streams].map((stream) => [\n\t\t\tstream.documentId,\n\t\t\tstream.scope,\n\t\t\tstream.branch,\n\t\t\tstream.revision\n\t\t]).sort());\n\t\tconst first = shape(prepared[0]);\n\t\treturn prepared.every((write) => shape(write) === first);\n\t}\n\t/**\n\t* The unbatched path, for a run that turned out not to qualify after its\n\t* writes were prepared. Nothing has been persisted at that point, so\n\t* replaying the whole run per write is safe.\n\t*/\n\tasync executeRegularActionsSequentially(writes, executing) {\n\t\tconst operations = [];\n\t\tconst contexts = [];\n\t\tlet lastYield = performance.now();\n\t\tfor (const write of writes) {\n\t\t\tconst result = await this.executeRegularAction(write, executing);\n\t\t\tif (!result.success) return result;\n\t\t\toperations.push(...result.operations ?? []);\n\t\t\tcontexts.push(...result.operationsWithContext ?? []);\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (executing.signal?.aborted) return buildErrorResult(executing.job, /* @__PURE__ */ new Error(\"Aborted\"), executing.startTime);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tjob: executing.job,\n\t\t\tsuccess: true,\n\t\t\toperations,\n\t\t\toperationsWithContext: contexts,\n\t\t\tduration: Date.now() - executing.startTime\n\t\t};\n\t}\n\t/** Decides, reduces and persists one write. */\n\tasync executeRegularAction(write, executing) {\n\t\tconst prepared = await this.prepareRegularWrite(write, executing);\n\t\tif (\"success\" in prepared) return prepared;\n\t\treturn this.commitPreparedWrites([prepared], executing);\n\t}\n\t/**\n\t* Orders a write by timestamp and decides it where it lands. The caller\n\t* supplies the timestamp, so a write can belong before operations already\n\t* stored; those are re-appended alongside it, the way a load reshuffles.\n\t*\n\t* Deciding a backdated write at the stream heads instead of at its position\n\t* would overwrite the verdict every other replica computes for it.\n\t*/\n\tasync positionByTimestamp(submitted, stores, signal) {\n\t\tlet job = submitted;\n\t\tconst plain = () => ({\n\t\t\twrites: job.actions.map((action) => ({\n\t\t\t\taction,\n\t\t\t\tskip: 0,\n\t\t\t\tsourceRemote: \"\"\n\t\t\t})),\n\t\t\tevaluatedByPosition: false\n\t\t});\n\t\tif (!this.featureFlags.documentDecisions || job.actions.length === 0) return plain();\n\t\tjob = {\n\t\t\t...job,\n\t\t\tactions: [...job.actions].sort((a, b) => Date.parse(a.timestampUtcMs) - Date.parse(b.timestampUtcMs))\n\t\t};\n\t\tlet earliest = job.actions[0].timestampUtcMs;\n\t\tlet earliestAt = Date.parse(earliest);\n\t\tfor (const action of job.actions) {\n\t\t\tconst at = Date.parse(action.timestampUtcMs);\n\t\t\tif (at < earliestAt) {\n\t\t\t\tearliest = action.timestampUtcMs;\n\t\t\t\tearliestAt = at;\n\t\t\t}\n\t\t}\n\t\tconst revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);\n\t\tconst backdated = earliestAt < Date.parse(revisions.latestTimestamp);\n\t\tif (this.featureFlags.authEnforcement && job.scope === \"auth\") {\n\t\t\tconst newest = await stores.operationStore.getStreamLatestTimestamp(job.documentId, \"auth\", job.branch, signal);\n\t\t\tconst violation = this.firstNonMonotonicTimestamp(submitted.actions, newest, job.documentId, job.branch);\n\t\t\tif (violation) return {\n\t\t\t\twrites: [],\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\terror: violation\n\t\t\t};\n\t\t\tif (!backdated) return plain();\n\t\t\treturn this.evaluatePositioned(job, stores, this.appendedOperations(job, revisions.revision[job.scope] ?? 0), signal);\n\t\t}\n\t\tif (!backdated) return plain();\n\t\tconst conflicting = (await stores.operationStore.getConflicting(job.documentId, job.scope, job.branch, earliest, void 0, signal)).results.filter((operation) => !isGenesisOperation(operation));\n\t\tconst nothingToMove = async () => {\n\t\t\tif (!this.featureFlags.authEnforcement) return plain();\n\t\t\treturn this.evaluatePositioned(job, stores, this.appendedOperations(job, revisions.revision[job.scope] ?? 0), signal);\n\t\t};\n\t\tif (conflicting.length === 0) return nothingToMove();\n\t\tconst nextIndex = revisions.revision[job.scope] ?? 0;\n\t\tlet firstConflicting = conflicting[0].index;\n\t\tfor (const operation of conflicting) if (operation.index < firstConflicting) firstConflicting = operation.index;\n\t\tconst stored = (await stores.operationStore.getSince(job.documentId, job.scope, job.branch, firstConflicting - 1, void 0, void 0, signal)).results;\n\t\tconst conflictingIds = new Set(conflicting.map((operation) => operation.id));\n\t\tconst effective = garbageCollect(sortOperations(stored)).filter((operation) => !isGenesisOperation(operation));\n\t\tconst firstMoving = effective.findIndex((operation) => conflictingIds.has(operation.id));\n\t\tconst moving = firstMoving === -1 ? [] : effective.slice(firstMoving);\n\t\tif (moving.length === 0) return nothingToMove();\n\t\tlet firstRetracted = moving[0].index;\n\t\tfor (const operation of moving) firstRetracted = Math.min(firstRetracted, operation.index - operation.skip);\n\t\tconst incoming = job.actions.map((action, i) => ({\n\t\t\tid: action.id,\n\t\t\tindex: nextIndex + i,\n\t\t\tskip: 0,\n\t\t\thash: \"\",\n\t\t\ttimestampUtcMs: action.timestampUtcMs,\n\t\t\taction\n\t\t}));\n\t\tconst merged = reshuffleByTimestamp({\n\t\t\tindex: nextIndex,\n\t\t\tskip: retractionSkip(nextIndex, firstRetracted)\n\t\t}, moving, incoming);\n\t\tstores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tif (!this.featureFlags.authEnforcement) return {\n\t\t\twrites: merged.map((operation) => ({\n\t\t\t\taction: operation.action,\n\t\t\t\tskip: operation.skip,\n\t\t\t\tsourceRemote: \"\"\n\t\t\t})),\n\t\t\tevaluatedByPosition: false\n\t\t};\n\t\treturn this.evaluatePositioned(job, stores, merged, signal);\n\t}\n\t/**\n\t* Decides each operation where it lands and carries the verdict on it. A\n\t* refused submitted action is reported to the caller and nothing is stored; a\n\t* refused operation the reshuffle merely moved keeps its verdict, because it\n\t* already holds a position.\n\t*\n\t* The operations carry the indexes and skips they will be stored at, because\n\t* the walk resolves skips before it orders them.\n\t*/\n\tasync evaluatePositioned(job, stores, operations, signal) {\n\t\tconst reasons = await evaluateByPosition(this.decisionModel, {\n\t\t\tdocumentId: job.documentId,\n\t\t\tbranch: job.branch\n\t\t}, {\n\t\t\tscope: job.scope,\n\t\t\toperations\n\t\t}, stores, signal);\n\t\tconst submitted = new Set(job.actions.map((action) => action.id));\n\t\tfor (let i = 0; i < operations.length; i++) {\n\t\t\tconst reason = reasons[i];\n\t\t\tif (reason !== void 0 && submitted.has(operations[i].action.id)) return {\n\t\t\t\twrites: [],\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\terror: refusalError(reason, job.documentId, null, operations[i].action)\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\twrites: operations.map((operation, i) => ({\n\t\t\t\taction: operation.action,\n\t\t\t\tskip: operation.skip,\n\t\t\t\tsourceRemote: \"\",\n\t\t\t\tdeniedReason: reasons[i]\n\t\t\t})),\n\t\t\tevaluatedByPosition: true\n\t\t};\n\t}\n\t/**\n\t* The scopes a re-evaluation pass visits, in a fixed order.\n\t*\n\t* The revisions map comes from a query with no ORDER BY, and the order is\n\t* load-bearing: each scope's pass re-reads the auth stream, and the walk skips\n\t* an operation by its stored denial, so a denial this pass just wrote is\n\t* visible to a later-visited scope and invisible to an earlier one. The model's\n\t* own projection order leads, then the rest sorted, so the pass is reproducible\n\t* across replicas and across runs.\n\t*/\n\tevaluationOrder(target, revision) {\n\t\tconst definition = this.decisionModel(target);\n\t\tconst evaluated = Object.keys(revision).filter((scope) => definition.evaluatesScope(scope));\n\t\tconst leading = [];\n\t\tfor (const stream of staticReadSet(definition)) {\n\t\t\tconst scope = stream.query.scope;\n\t\t\tif (evaluated.includes(scope) && !leading.includes(scope)) leading.push(scope);\n\t\t}\n\t\tconst rest = evaluated.filter((scope) => !leading.includes(scope)).sort((a, b) => a.localeCompare(b));\n\t\treturn [...leading, ...rest];\n\t}\n\t/**\n\t* The first timestamp in the batch that does not strictly exceed everything\n\t* ahead of it, or undefined when the whole batch is monotonic.\n\t*\n\t* The bound is carried forward rather than compared against one stored maximum,\n\t* because a single execute can carry several auth actions stamped in the same\n\t* millisecond. Letting a tie through would store a stream the position walk\n\t* then refuses to read, with no repair path.\n\t*/\n\tfirstNonMonotonicTimestamp(entries, newest, documentId, branch) {\n\t\tlet boundIso = newest;\n\t\tlet bound = newest === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(newest);\n\t\tfor (const entry of entries) {\n\t\t\tif (!isValidISOTimestamp(entry.timestampUtcMs)) return new InvalidOperationTimestampError(documentId, \"auth\", entry.timestampUtcMs, \"auth operation\");\n\t\t\tconst at = Date.parse(entry.timestampUtcMs);\n\t\t\tif (boundIso !== void 0 && at <= bound) return new AuthTimestampNotMonotonicError(documentId, branch, entry.timestampUtcMs, boundIso);\n\t\t\tbound = at;\n\t\t\tboundIso = entry.timestampUtcMs;\n\t\t}\n\t}\n\t/** The operations a batch of submitted actions appends at the scope's tail. */\n\tappendedOperations(job, nextIndex) {\n\t\treturn job.actions.map((action, i) => ({\n\t\t\tid: action.id,\n\t\t\tindex: nextIndex + i,\n\t\t\tskip: 0,\n\t\t\thash: \"\",\n\t\t\ttimestampUtcMs: action.timestampUtcMs,\n\t\t\taction\n\t\t}));\n\t}\n\t/**\n\t* Re-evaluates the document when a write meets both criteria: it was written\n\t* to a stream the model reads, and it is timestamped before an operation\n\t* already stored. The caller supplies the timestamp and the reactor does not replace\n\t* it, so a mutation job can write such an operation just as a load job can,\n\t* which is why both executeJob and executeLoadJob call this.\n\t*/\n\tasync reevaluateIfCriteriaMet(criteria, executing) {\n\t\tconst skipped = { operationsWithContext: [] };\n\t\tif (!this.featureFlags.documentDecisions) return skipped;\n\t\tconst { job, stores, signal } = executing;\n\t\tconst target = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tbranch: job.branch\n\t\t};\n\t\tif (!staticReadSet(this.decisionModel(target)).some((stream) => stream.query.documentId === job.documentId && stream.query.scope === criteria.scope && stream.query.branch === job.branch)) return skipped;\n\t\tconst revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);\n\t\tconst latest = Date.parse(revisions.latestTimestamp);\n\t\tif (!criteria.operations.some((operation) => Date.parse(operation.timestampUtcMs) < latest)) return skipped;\n\t\treturn this.reevaluateDocument(executing);\n\t}\n\t/**\n\t* Re-evaluates every scope the model evaluates. Where an operation's\n\t* evaluation differs from what is stored, the tail from that operation is\n\t* re-appended, carrying a skip that spans the indices it supersedes.\n\t*/\n\tasync reevaluateDocument(executing) {\n\t\tconst { job, stores, signal } = executing;\n\t\tconst target = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tbranch: job.branch\n\t\t};\n\t\tconst reappended = [];\n\t\tconst revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);\n\t\tfor (const scope of this.evaluationOrder(target, revisions.revision)) {\n\t\t\tconst stored = (await stores.operationStore.getSince(job.documentId, scope, job.branch, -1, void 0, void 0, signal)).results;\n\t\t\tconst effective = garbageCollect(sortOperations([...stored]));\n\t\t\tif (effective.length === 0) continue;\n\t\t\tconst reevaluated = await evaluateByPosition(this.decisionModel, target, {\n\t\t\t\tscope,\n\t\t\t\toperations: effective\n\t\t\t}, stores, signal);\n\t\t\tconst firstChange = effective.findIndex((operation, i) => operation.deniedReason !== reevaluated[i]);\n\t\t\tif (firstChange === -1) continue;\n\t\t\tconst tail = effective.slice(firstChange);\n\t\t\tconst nextIndex = revisions.revision[scope];\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\tconst result = await this.processActions(tail.map((operation, i) => ({\n\t\t\t\taction: operation.action,\n\t\t\t\tskip: i === 0 ? retractionSkip(nextIndex, tail[0].index - tail[0].skip) : 0,\n\t\t\t\tsourceRemote: \"\",\n\t\t\t\tdeniedReason: reevaluated[firstChange + i]\n\t\t\t})), {\n\t\t\t\t...executing,\n\t\t\t\tjob: {\n\t\t\t\t\t...job,\n\t\t\t\t\tscope\n\t\t\t\t},\n\t\t\t\treplayingAcceptedHistory: true,\n\t\t\t\tevaluatedByPosition: true\n\t\t\t});\n\t\t\tif (!result.success) return {\n\t\t\t\terror: result.error ?? /* @__PURE__ */ new Error(`Re-evaluation of ${job.documentId} ${scope} failed`),\n\t\t\t\toperationsWithContext: reappended\n\t\t\t};\n\t\t\treappended.push(...result.operationsWithContext);\n\t\t}\n\t\treturn { operationsWithContext: reappended };\n\t}\n\t/**\n\t* Re-judges a document's stored operations because a read-set stream in\n\t* another document (a group) gained an operation. The trigger timestamp\n\t* bounds the work: an operation later than everything this document holds\n\t* cannot change any evaluation, so the pass is skipped.\n\t*/\n\tasync executeReevaluationJob(executing) {\n\t\tconst { job, startTime, stores, signal } = executing;\n\t\tif (!this.featureFlags.documentDecisions) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst trigger = job.meta.triggerTimestampUtcMs;\n\t\tif (typeof trigger === \"string\") {\n\t\t\tlet latestTimestamp;\n\t\t\ttry {\n\t\t\t\tlatestTimestamp = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).latestTimestamp;\n\t\t\t} catch {\n\t\t\t\treturn {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\toperations: [],\n\t\t\t\t\toperationsWithContext: [],\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (Date.parse(trigger) > Date.parse(latestTimestamp)) return {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [],\n\t\t\t\toperationsWithContext: [],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst outcome = await this.reevaluateDocument(executing);\n\t\tif (outcome.error) return buildErrorResult(job, outcome.error, startTime);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: outcome.operationsWithContext.map((owc) => owc.operation),\n\t\t\toperationsWithContext: outcome.operationsWithContext,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\tasync executeLoadJob(executing) {\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tif (job.operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"Load job must include at least one operation\"), startTime);\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch {}\n\t\tif (docMeta?.state.isDeleted && !this.featureFlags.documentDecisions) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tconst scope = job.scope;\n\t\tconst monotonicAuthStream = this.featureFlags.authEnforcement && scope === \"auth\";\n\t\tlet latestRevision;\n\t\ttry {\n\t\t\tlatestRevision = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).revision[scope] ?? 0;\n\t\t} catch {\n\t\t\tlatestRevision = 0;\n\t\t}\n\t\tfor (const operation of job.operations) if (operation.timestampUtcMs && !isValidISOTimestamp(operation.timestampUtcMs)) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: new InvalidOperationTimestampError(job.documentId, scope, operation.timestampUtcMs, `operation (index: ${operation.index})`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst dropped = /* @__PURE__ */ new Set();\n\t\tconst admitted = /* @__PURE__ */ new Set();\n\t\tlet selection = await this.selectLoadWrites(job, job.operations, stores, signal);\n\t\tfor (;;) {\n\t\t\tconst unadmitted = selection.incomingOpsToApply.filter((operation) => !admitted.has(operation));\n\t\t\tif (unadmitted.length === 0) break;\n\t\t\tlet refused;\n\t\t\ttry {\n\t\t\t\trefused = await this.signatureAdmission.admitLoad(job, unadmitted, stores, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tfor (const operation of unadmitted) if (refused.has(operation)) dropped.add(operation);\n\t\t\telse admitted.add(operation);\n\t\t\tif (refused.size === 0) break;\n\t\t\tconst remaining = job.operations.filter((operation) => !dropped.has(operation));\n\t\t\tif (remaining.length === 0) return {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [],\n\t\t\t\toperationsWithContext: [],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t\tselection = await this.selectLoadWrites(job, remaining, stores, signal);\n\t\t}\n\t\tconst { nonSupersededOps, allOpsFromMinConflictingIndex, incomingOpsToApply } = selection;\n\t\tif (incomingOpsToApply.length === 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst existingOpsToReshuffle = monotonicAuthStream ? [] : nonSupersededOps.filter((operation) => !isGenesisOperation(operation));\n\t\tconst actionIdCounts = /* @__PURE__ */ new Map();\n\t\tfor (const operation of allOpsFromMinConflictingIndex) actionIdCounts.set(operation.action.id, (actionIdCounts.get(operation.action.id) ?? 0) + 1);\n\t\tconst reshuffleCost = existingOpsToReshuffle.filter((operation) => (actionIdCounts.get(operation.action.id) ?? 0) < 2).length;\n\t\tif (reshuffleCost > this.config.maxSkipThreshold) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: new ExcessiveReshuffleError(job.documentId, scope, reshuffleCost, this.config.maxSkipThreshold),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet skipCount = existingOpsToReshuffle.length;\n\t\tif (existingOpsToReshuffle.length > 0) {\n\t\t\tlet minLogicalIndex = Number.POSITIVE_INFINITY;\n\t\t\tfor (const op of existingOpsToReshuffle) {\n\t\t\t\tconst logical = op.index - op.skip;\n\t\t\t\tif (logical < minLogicalIndex) minLogicalIndex = logical;\n\t\t\t}\n\t\t\tconst logicalSkip = latestRevision - minLogicalIndex;\n\t\t\tif (logicalSkip > skipCount) skipCount = logicalSkip;\n\t\t}\n\t\tif (monotonicAuthStream) {\n\t\t\tconst newest = await stores.operationStore.getStreamLatestTimestamp(job.documentId, \"auth\", job.branch, signal);\n\t\t\tconst violation = this.firstNonMonotonicTimestamp([...incomingOpsToApply].sort((a, b) => a.index - b.index), newest, job.documentId, job.branch);\n\t\t\tif (violation) return {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: violation,\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst reshuffledOperations = existingOpsToReshuffle.length === 0 && skipCount === 0 ? incomingOpsToApply.slice().sort((a, b) => a.index - b.index).map((operation, i) => ({\n\t\t\t...operation,\n\t\t\tindex: latestRevision + i\n\t\t})) : reshuffleByTimestamp({\n\t\t\tindex: latestRevision,\n\t\t\tskip: skipCount\n\t\t}, existingOpsToReshuffle, incomingOpsToApply.map((operation) => ({\n\t\t\t...operation,\n\t\t\tid: operation.id\n\t\t})));\n\t\tconst incomingIds = new Set(incomingOpsToApply.map((operation) => operation.action.id));\n\t\tfor (const operation of reshuffledOperations) if (operation.action.type === \"NOOP\" && operation.skip === 0 && incomingIds.has(operation.action.id)) operation.skip = 1;\n\t\tlet deniedReasons;\n\t\tif (this.featureFlags.documentDecisions) try {\n\t\t\tdeniedReasons = await evaluateByPosition(this.decisionModel, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tbranch: job.branch\n\t\t\t}, {\n\t\t\t\tscope,\n\t\t\t\toperations: reshuffledOperations\n\t\t\t}, stores, signal);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst effectiveSourceRemote = skipCount > 0 ? \"\" : job.meta.sourceRemote || \"\";\n\t\tconst result = await this.processActions(reshuffledOperations.map((operation, i) => ({\n\t\t\taction: operation.action,\n\t\t\tskip: operation.skip,\n\t\t\tsourceOperation: operation,\n\t\t\tsourceRemote: effectiveSourceRemote,\n\t\t\tdeniedReason: deniedReasons?.[i]\n\t\t})), executing);\n\t\tif (!result.success) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: result.error,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\tif (scope === \"document\") stores.documentMetaCache.invalidate(job.documentId, job.branch);\n\t\tconst reevaluation = await this.reevaluateIfCriteriaMet({\n\t\t\tscope,\n\t\t\toperations: result.generatedOperations\n\t\t}, executing);\n\t\tif (reevaluation.error) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: reevaluation.error,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [...result.generatedOperations, ...reevaluation.operationsWithContext.map((owc) => owc.operation)],\n\t\t\toperationsWithContext: [...result.operationsWithContext, ...reevaluation.operationsWithContext],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\t/** The conflicting window a load opens, and which of its operations are new. */\n\tasync selectLoadWrites(job, operations, stores, signal) {\n\t\tconst scope = job.scope;\n\t\tlet minIncomingIndex = Number.POSITIVE_INFINITY;\n\t\tlet minIncomingTimestamp = operations[0]?.timestampUtcMs || \"\";\n\t\tfor (const operation of operations) {\n\t\t\tminIncomingIndex = Math.min(minIncomingIndex, operation.index);\n\t\t\tconst ts = operation.timestampUtcMs || \"\";\n\t\t\tif (Date.parse(ts) < Date.parse(minIncomingTimestamp)) minIncomingTimestamp = ts;\n\t\t}\n\t\tlet conflictingOps;\n\t\ttry {\n\t\t\tconflictingOps = (await stores.operationStore.getConflicting(job.documentId, scope, job.branch, minIncomingTimestamp, void 0, signal)).results;\n\t\t} catch {\n\t\t\tconflictingOps = [];\n\t\t}\n\t\tlet allOpsFromMinConflictingIndex = conflictingOps;\n\t\tif (conflictingOps.length > 0) {\n\t\t\tconst minConflictingIndex = Math.min(...conflictingOps.map((op) => op.index));\n\t\t\ttry {\n\t\t\t\tallOpsFromMinConflictingIndex = (await stores.operationStore.getSince(job.documentId, scope, job.branch, minConflictingIndex - 1, void 0, void 0, signal)).results;\n\t\t\t} catch {\n\t\t\t\tallOpsFromMinConflictingIndex = conflictingOps;\n\t\t\t}\n\t\t}\n\t\tconst incomingActionIds = new Set(operations.map((op) => op.action.id));\n\t\tconst supersededBy = (op) => {\n\t\t\tlet nearest;\n\t\t\tfor (const laterOp of allOpsFromMinConflictingIndex) if (laterOp.index > op.index && laterOp.skip > 0 && laterOp.index - laterOp.skip <= op.index && (nearest === void 0 || laterOp.index < nearest.index)) nearest = laterOp;\n\t\t\treturn nearest;\n\t\t};\n\t\tconst undoneActionIds = /* @__PURE__ */ new Set();\n\t\tconst minIncomingTime = Date.parse(minIncomingTimestamp);\n\t\tlet predecessorBound = minIncomingIndex;\n\t\tconst rowsByActionId = /* @__PURE__ */ new Map();\n\t\tfor (const op of conflictingOps) if (incomingActionIds.has(op.action.id)) rowsByActionId.set(op.action.id, [...rowsByActionId.get(op.action.id) ?? [], op]);\n\t\tconst liveOps = /* @__PURE__ */ new Set();\n\t\tfor (const op of conflictingOps) if (supersededBy(op) === void 0) liveOps.add(op);\n\t\tfor (const [actionId, rows] of rowsByActionId) {\n\t\t\tif (rows.some((row) => liveOps.has(row))) continue;\n\t\t\tif (rows.some((row) => supersededBy(row)?.action.type === \"NOOP\")) undoneActionIds.add(actionId);\n\t\t\telse predecessorBound = Math.min(predecessorBound, Math.max(...rows.map((row) => row.index)));\n\t\t}\n\t\tconst nonSupersededOps = conflictingOps.filter((op) => {\n\t\t\tif (!incomingActionIds.has(op.action.id) && (!this.featureFlags.documentDecisions || Date.parse(op.timestampUtcMs) === minIncomingTime) && op.index < predecessorBound) return false;\n\t\t\treturn liveOps.has(op);\n\t\t});\n\t\tlet rewoundFrom = Number.POSITIVE_INFINITY;\n\t\tfor (const op of nonSupersededOps) if (!isGenesisOperation(op)) rewoundFrom = Math.min(rewoundFrom, op.index - op.skip);\n\t\tconst reappended = new Set(nonSupersededOps.map((op) => op.index));\n\t\tfor (const op of allOpsFromMinConflictingIndex) if (op.index >= rewoundFrom && !reappended.has(op.index) && supersededBy(op) === void 0) nonSupersededOps.push(op);\n\t\tconst existingActionIds = new Set(nonSupersededOps.map((op) => op.action.id));\n\t\tconst seenIncomingActionIds = /* @__PURE__ */ new Set();\n\t\tconst incomingOpsToApply = operations.filter((op) => {\n\t\t\tif (existingActionIds.has(op.action.id)) return false;\n\t\t\tif (undoneActionIds.has(op.action.id)) return false;\n\t\t\tif (seenIncomingActionIds.has(op.action.id)) return false;\n\t\t\tseenIncomingActionIds.add(op.action.id);\n\t\t\treturn true;\n\t\t});\n\t\treturn {\n\t\t\tnonSupersededOps,\n\t\t\tallOpsFromMinConflictingIndex,\n\t\t\tincomingOpsToApply\n\t\t};\n\t}\n\taccumulateResultOrReturnError(result, generatedOperations, operationsWithContext) {\n\t\tif (!result.success) return result;\n\t\tif (result.operations && result.operations.length > 0) generatedOperations.push(...result.operations);\n\t\tif (result.operationsWithContext) operationsWithContext.push(...result.operationsWithContext);\n\t\treturn null;\n\t}\n};\nfunction withReducerErrorIdentity(stored, applied) {\n\tif (applied === void 0 || stored.error === void 0 || applied.errorName === void 0 && applied.errorCode === void 0) return stored;\n\treturn {\n\t\t...stored,\n\t\t...applied.errorName !== void 0 && { errorName: applied.errorName },\n\t\t...applied.errorCode !== void 0 && { errorCode: applied.errorCode }\n\t};\n}\n//#endregion\n//#region src/core/drive-container-types.ts\nconst DEFAULT_DRIVE_CONTAINER_TYPES = /* @__PURE__ */ new Set([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"]);\n//#endregion\nexport { buildDecisionModel as S, DriveCollectionId as _, NoopStorageFlusher as a, documentDecisionModel as b, KyselyWriteIdentityStore as c, appliedDelete as d, resolveFeatureFlags as f, JobExecutorEventTypes as g, DEFAULT_MAX_PURGE_OPERATIONS as h, PassthroughSigner as i, DEFAULT_PURGE_DELETE_BATCH as l, DEFAULT_JOB_TIMEOUT_MS as m, SimpleJobExecutor as n, StoragePoisonedError as o, DEFAULT_DEFERRED_JOB_TTL_MS as p, verifyActionSignature as r, KyselyExecutionScope as s, DEFAULT_DRIVE_CONTAINER_TYPES as t, KyselyDocumentPurger as u, decideAtHead as v, authDecisionModel as x, selectDecisionModel as y };\n\n//# sourceMappingURL=drive-container-types-CC0dU3AF.js.map","// Resolves the workflow-runtime subgraph URL for the selected drive:\n// remote sync channel, then vetra default-drive URL, then the default.\nimport {\n DriveCollectionId,\n type GqlRequestChannel,\n} from \"@powerhousedao/reactor\";\nimport {\n DEFAULT_SWITCHBOARD_URL,\n parseDriveUrl,\n subgraphUrlFromGraphqlUrl,\n useDefaultDrivesUrl,\n useSelectedDriveSafe,\n useSyncList,\n} from \"@powerhousedao/reactor-browser\";\nimport { useMemo } from \"react\";\n\nconst SUBGRAPH_NAME = \"workflow-runtime\";\n\n// Channel URLs end in /graphql/r; strip only that suffix so a proxy\n// sub-path in the base survives.\nfunction baseFromChannelUrl(channelUrl: string): string | undefined {\n try {\n const url = new URL(channelUrl);\n url.search = \"\";\n url.hash = \"\";\n url.pathname = url.pathname.replace(/\\/r\\/?$/, \"\");\n return url.toString();\n } catch {\n return undefined;\n }\n}\n\nexport function useWorkflowRuntimeUrl(): string {\n const [drive] = useSelectedDriveSafe();\n const remotes = useSyncList();\n const defaultDrivesUrl = useDefaultDrivesUrl();\n const driveId = drive?.header.id;\n\n return useMemo(() => {\n let base: string | undefined;\n if (driveId) {\n const remote = remotes.find((entry) =>\n entry.meta.collectionId.equals(DriveCollectionId.forDrive(driveId)),\n );\n const channelUrl = (remote?.channel as GqlRequestChannel | undefined)\n ?.config.url;\n if (typeof channelUrl === \"string\") {\n base = baseFromChannelUrl(channelUrl);\n }\n }\n // Local drive: under `ph vetra` the switchboard is still reachable\n // through the default drive URL.\n if (!base && defaultDrivesUrl) {\n try {\n base = parseDriveUrl(defaultDrivesUrl).graphqlEndpoint.replace(\n /\\/r$/,\n \"\",\n );\n } catch {\n // Malformed default drive URL; fall through to the constant.\n }\n }\n return subgraphUrlFromGraphqlUrl(\n base ?? DEFAULT_SWITCHBOARD_URL,\n SUBGRAPH_NAME,\n );\n }, [driveId, remotes, defaultDrivesUrl]);\n}\n","// One runtime client and query cache per editor instance. Hooks pass the\n// client explicitly, leaving the host's QueryClientProvider alone.\nimport {\n useInfiniteQuery,\n useQuery,\n type QueryClient,\n} from \"@tanstack/react-query\";\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from \"react\";\nimport {\n createRuntimeClient,\n type OAuthAttempt,\n type RunsScope,\n type RuntimeClient,\n type SecretStat,\n} from \"./runtime-client.js\";\nimport {\n openIdbCacheStore,\n persistRuntimeQueries,\n type RuntimeCacheStore,\n} from \"./runtime-persist.js\";\nimport {\n catalogQuery,\n createRuntimeQueryClient,\n pieceActionsQuery,\n pieceTriggersQuery,\n runPagesQuery,\n runQuery,\n runsQuery,\n secretStatQuery,\n} from \"./runtime-queries.js\";\nimport {\n PieceSourceProvider,\n type PieceCatalogSource,\n} from \"./ui/piece-source.js\";\nimport { runtimeKeys } from \"./ui/query-keys.js\";\nimport { useWorkflowRuntimeUrl } from \"./use-runtime-url.js\";\n\nexport interface RuntimeContextValue {\n client: RuntimeClient;\n queryClient: QueryClient;\n}\n\nconst RuntimeContext = createContext<RuntimeContextValue | null>(null);\n\n// A repeated query while the picker is open answers at once.\nconst SEARCH_STALE_MS = 5 * 60_000;\n\n// The block selector's catalog seam, answered from this editor's cache.\nfunction runtimePieceSource(\n client: RuntimeClient,\n queryClient: QueryClient,\n): PieceCatalogSource {\n return {\n loadCatalog: () => queryClient.fetchQuery(catalogQuery(client)),\n reloadCatalog: () =>\n queryClient.fetchQuery({ ...catalogQuery(client), staleTime: 0 }),\n loadActions: (packageName) =>\n queryClient.fetchQuery(pieceActionsQuery(client, packageName)),\n loadTriggers: (packageName) =>\n queryClient.fetchQuery(pieceTriggersQuery(client, packageName)),\n searchPieces: async (query, filter) => {\n const key = runtimeKeys.searchPieces(client.url, query, filter);\n const result = await queryClient.fetchQuery({\n queryKey: key,\n queryFn: () => client.searchPieces(query, filter),\n staleTime: SEARCH_STALE_MS,\n });\n // Only a finished index is worth keeping; the caller polls the rest.\n if (result.status !== \"ready\")\n queryClient.removeQueries({ queryKey: key });\n return result;\n },\n };\n}\n\nexport function RuntimeProvider(props: {\n url: string;\n children: ReactNode;\n // The browser cache; defaults to IndexedDB, null turns it off.\n store?: RuntimeCacheStore | null;\n}) {\n const { url } = props;\n const [queryClient] = useState(createRuntimeQueryClient);\n const [store] = useState(() =>\n props.store === undefined ? openIdbCacheStore() : props.store,\n );\n const client = useMemo(() => createRuntimeClient(url), [url]);\n\n useEffect(\n () => persistRuntimeQueries(queryClient, url, store).dispose,\n [queryClient, url, store],\n );\n\n const value = useMemo(() => ({ client, queryClient }), [client, queryClient]);\n const pieceSource = useMemo(\n () => runtimePieceSource(client, queryClient),\n [client, queryClient],\n );\n return (\n <RuntimeContext.Provider value={value}>\n <PieceSourceProvider value={pieceSource}>\n {props.children}\n </PieceSourceProvider>\n </RuntimeContext.Provider>\n );\n}\n\n// Resolves the selected drive's runtime URL and provides a client for it.\nexport function WorkflowRuntimeProvider(props: { children: ReactNode }) {\n const url = useWorkflowRuntimeUrl();\n return <RuntimeProvider url={url}>{props.children}</RuntimeProvider>;\n}\n\nexport function useRuntime(): RuntimeContextValue {\n const context = useContext(RuntimeContext);\n if (!context) throw new Error(\"useRuntime needs a RuntimeProvider\");\n return context;\n}\n\nexport function usePieceCatalog() {\n const { client, queryClient } = useRuntime();\n return useQuery(catalogQuery(client), queryClient);\n}\n\n// Polled while `active`; inactive feeds hold no subscription.\nexport function useRunsQuery(\n scope: RunsScope,\n options: { active?: boolean; pollMs?: number } = {},\n) {\n const { client, queryClient } = useRuntime();\n return useQuery(\n {\n ...runsQuery(client, scope),\n enabled: options.active ?? true,\n refetchInterval: options.pollMs ?? false,\n },\n queryClient,\n );\n}\n\n// The paged listing; polling refetches every loaded page.\nexport function useRunPagesQuery(\n scope: RunsScope,\n options: { active?: boolean; pollMs?: number } = {},\n) {\n const { client, queryClient } = useRuntime();\n return useInfiniteQuery(\n {\n ...runPagesQuery(client, scope),\n enabled: options.active ?? true,\n refetchInterval: options.pollMs ?? false,\n },\n queryClient,\n );\n}\n\n// One run with its steps' input and output; polled until it finishes.\nexport function useRunQuery(runId: string, options: { pollMs?: number } = {}) {\n const { client, queryClient } = useRuntime();\n return useQuery(\n {\n ...runQuery(client, runId),\n refetchInterval: (query) =>\n options.pollMs && query.state.data?.endedAt == null\n ? options.pollMs\n : false,\n },\n queryClient,\n );\n}\n\n// Undefined while the stat loads; null when the ref doesn't resolve.\nexport function useSecretStat(\n ref: string,\n enabled: boolean,\n): SecretStat | null | undefined {\n const { client, queryClient } = useRuntime();\n const query = useQuery(\n { ...secretStatQuery(client, ref), enabled, gcTime: 0 },\n queryClient,\n );\n if (!enabled) return null;\n if (query.status === \"pending\") return undefined;\n return query.status === \"error\" ? null : query.data;\n}\n\n// Absolute; null when the host serves no OAuth2 callback.\nexport function useOAuthRedirectUri() {\n const { client, queryClient } = useRuntime();\n return useQuery(\n {\n queryKey: [client.url, \"oauthRedirectUri\"],\n queryFn: () => client.fetchOAuthRedirectUri(),\n staleTime: Infinity,\n },\n queryClient,\n );\n}\n\n// Polled until the sign-in finishes. Undefined while loading; null for no\n// state, or one the switchboard does not know (or could not be asked about).\nexport function useOAuthAttempt(\n state: string | null,\n): OAuthAttempt | null | undefined {\n const { client, queryClient } = useRuntime();\n const query = useQuery(\n {\n queryKey: [client.url, \"oauthAttempt\", state],\n queryFn: () => client.fetchOAuthAttempt(state!),\n enabled: state !== null,\n gcTime: 0,\n refetchInterval: (current) => {\n if (current.state.status === \"error\") return false;\n const data = current.state.data;\n if (data === null) return false;\n return data?.status === \"OK\" || data?.status === \"ERROR\" ? false : 1000;\n },\n },\n queryClient,\n );\n if (state === null || query.isError) return null;\n return query.data;\n}\n\n// Writes that change runtime state, each dropping the queries it affects.\nexport function useRuntimeActions() {\n const { client, queryClient } = useRuntime();\n return useMemo(() => {\n const invalidate = (queryKey: readonly unknown[]) =>\n void queryClient.invalidateQueries({ queryKey });\n const runsChanged = () => {\n invalidate(runtimeKeys.allRuns(client.url));\n invalidate([client.url, \"latestRun\"]);\n };\n const secretSaved = (stat: SecretStat) => {\n queryClient.setQueryData(runtimeKeys.secret(client.url, stat.ref), stat);\n return stat;\n };\n return {\n fireWorkflow: (workflowId: string, payload?: unknown) =>\n client.fireWorkflow(workflowId, payload).finally(runsChanged),\n rerunRun: (runId: string) => client.rerunRun(runId).finally(runsChanged),\n createSecret: (value: string, label?: string) =>\n client.createSecret(value, label).then(secretSaved),\n rotateSecret: (ref: string, value: string) =>\n client.rotateSecret(ref, value).then(secretSaved),\n checkConnection: (connectionId: string) =>\n client\n .checkConnection(connectionId)\n .finally(() => invalidate(runtimeKeys.connections(client.url))),\n connectionsChanged: () => invalidate(runtimeKeys.connections(client.url)),\n startOAuth: (\n connectionId: string,\n options?: { redirectUri?: string; returnUrl?: string },\n ) => client.startOAuth(connectionId, options),\n };\n }, [client, queryClient]);\n}\n","// Lean required-field check shared by the property form, the side panel\n// header and the canvas badge. No schema validation: {{}} values defeat it.\nimport { scheduleConfigIssue } from \"@powerhousedao/pieces-framework/workflow\";\nimport type { BlockRef } from \"./blocks.js\";\nimport type { BlockForm, BlockFormProp } from \"./forms.js\";\nimport type { PropertyModeValue, PropertySettingModel } from \"./model.js\";\nimport type { ResolverKeyInput } from \"./query-keys.js\";\n\nexport function isEmptyValue(value: unknown): boolean {\n if (value === undefined || value === null) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n return false;\n}\n\n// Whether a prop's `showWhen` is met; shared with the property form so one rule\n// decides render and required — else a hidden field warns with nothing to fix.\nexport function isPropVisible(\n prop: BlockFormProp,\n config: Record<string, unknown>,\n): boolean {\n const rule = prop.showWhen;\n if (!rule) return true;\n return rule.oneOf.includes(config[rule.prop] ?? undefined);\n}\n\nfunction asRecord(config: unknown): Record<string, unknown> {\n return config !== null && typeof config === \"object\" && !Array.isArray(config)\n ? (config as Record<string, unknown>)\n : {};\n}\n\n// Display names of required props with no value; MARKDOWN is informational.\nexport function missingRequired(\n props: BlockFormProp[],\n config: unknown,\n): string[] {\n const record = asRecord(config);\n return props\n .filter(\n (prop) =>\n prop.required &&\n prop.type !== \"MARKDOWN\" &&\n isPropVisible(prop, record) &&\n isEmptyValue(record[prop.name]),\n )\n .map((prop) => prop.displayName);\n}\n\n// What a prop's resolver answer depends on: its refreshers and the connection.\nexport function resolverInputFor(\n block: BlockRef,\n prop: BlockFormProp,\n config: Record<string, unknown>,\n connectionId: string | null | undefined,\n reactorConnectionId?: string | null,\n): ResolverKeyInput {\n const refreshers = (prop.refreshers ?? []).filter((name) => name !== \"auth\");\n return {\n block,\n propName: prop.name,\n refreshers: refreshers.map((name) => config[name] ?? null),\n connectionId: connectionId ?? null,\n ...(reactorConnectionId ? { reactorConnectionId } : {}),\n };\n}\n\nexport function settingFor(\n settings: readonly PropertySettingModel[] | null | undefined,\n prop: string,\n): PropertySettingModel | undefined {\n return settings?.find((setting) => setting.prop === prop);\n}\n\n// A DYNAMIC resolver's answer as a prop list.\nexport function parsePropList(result: unknown): BlockFormProp[] {\n if (!Array.isArray(result)) throw new Error(\"Unexpected properties result\");\n return result.filter(\n (entry): entry is BlockFormProp =>\n entry !== null &&\n typeof entry === \"object\" &&\n typeof (entry as BlockFormProp).name === \"string\",\n );\n}\n\n// A stored DYNAMIC schema, when it parses as a prop list.\nexport function storedSchema(\n settings: readonly PropertySettingModel[] | null | undefined,\n prop: string,\n): BlockFormProp[] | undefined {\n const schema = settingFor(settings, prop)?.schema;\n if (!Array.isArray(schema)) return undefined;\n return schema.filter(\n (entry): entry is BlockFormProp =>\n entry !== null &&\n typeof entry === \"object\" &&\n typeof (entry as BlockFormProp).name === \"string\",\n );\n}\n\n// Children as stored: dropdown options go, they are the resolver's to answer.\nexport function stripOptions(props: BlockFormProp[]): BlockFormProp[] {\n return props.map((prop) => {\n const { staticOptions: _options, properties, ...rest } = prop;\n return properties\n ? { ...rest, properties: stripOptions(properties) }\n : rest;\n });\n}\n\n// Settings with one prop's entry replaced; null drops the schema only.\nexport function withSetting(\n settings: readonly PropertySettingModel[] | null | undefined,\n prop: string,\n patch: { mode?: PropertyModeValue; schema?: unknown },\n): PropertySettingModel[] {\n const list = [...(settings ?? [])];\n const index = list.findIndex((setting) => setting.prop === prop);\n const current = index >= 0 ? list[index] : { prop, mode: \"MANUAL\" as const };\n const next: PropertySettingModel = {\n prop,\n mode: patch.mode ?? current.mode,\n schema:\n \"schema\" in patch ? (patch.schema ?? null) : (current.schema ?? null),\n };\n if (index >= 0) list[index] = next;\n else list.push(next);\n return list;\n}\n\nexport interface ValidityInput {\n form: BlockForm | null | \"loading\" | undefined;\n block: BlockRef;\n config: unknown;\n connectionId: string | null | undefined;\n reactorConnectionId?: string | null;\n propertySettings?: readonly PropertySettingModel[] | null;\n skip?: boolean | null;\n // DYNAMIC children already resolved for a key; undefined when not cached.\n resolveDynamic?: (input: ResolverKeyInput) => BlockFormProp[] | undefined;\n}\n\nexport const REACTOR_CONNECTION_LABEL = \"Reactor connection\";\n\n// What a block still needs before it can run. [] is complete; null is\n// unknown: the form isn't there, or a DYNAMIC prop is unresolved.\nexport function blockMissing(input: ValidityInput): string[] | null {\n if (input.skip) return [];\n const { form } = input;\n if (!form || form === \"loading\") return null;\n const record = asRecord(input.config);\n const missing: string[] = [];\n let unknown = false;\n if (form.auth === \"required\" && !input.connectionId) {\n missing.push(\"Connection\");\n }\n if (form.requireReactor && !input.reactorConnectionId) {\n missing.push(REACTOR_CONNECTION_LABEL);\n }\n for (const prop of form.props) {\n if (prop.type === \"MARKDOWN\" || !isPropVisible(prop, record)) continue;\n const value = record[prop.name];\n const bound =\n settingFor(input.propertySettings, prop.name)?.mode === \"EXPRESSION\";\n if (prop.type !== \"DYNAMIC\" || bound) {\n if (prop.required && isEmptyValue(value)) missing.push(prop.displayName);\n continue;\n }\n const children =\n input.resolveDynamic?.(\n resolverInputFor(\n input.block,\n prop,\n record,\n input.connectionId,\n input.reactorConnectionId,\n ),\n ) ?? storedSchema(input.propertySettings, prop.name);\n if (children === undefined) {\n unknown = true;\n continue;\n }\n missing.push(...missingRequired(children, value));\n }\n if (missing.length > 0) return missing;\n // The builder's config is checked by the parser the runtime arms with.\n if (form.display === \"schedule\") {\n const issue = scheduleConfigIssue(input.config);\n if (issue) return [issue.replace(/^Schedule: /, \"\")];\n }\n return unknown ? null : [];\n}\n\n// Edges leaving on a port the block does not declare: no run takes them.\nexport function undeclaredPortIssues(\n form: BlockForm | null | \"loading\" | undefined,\n outgoingPorts: readonly string[] | undefined,\n): string[] {\n const ports = form && form !== \"loading\" ? form.ports : undefined;\n if (!ports || !outgoingPorts) return [];\n return [...new Set(outgoingPorts)]\n .filter((port) => !ports.includes(port))\n .map((port) => `An edge leaves on \"${port}\", which this block never takes`);\n}\n\nexport interface WorkflowReadiness {\n // A trigger, and every non-skipped block checked and complete.\n ready: boolean;\n hasTrigger: boolean;\n // First block, in the order given, with a field left to fill.\n firstIncomplete: string | null;\n // Some block is not checked yet: its form or a DYNAMIC schema is unknown.\n checking: boolean;\n}\n\n// Folds per-block blockMissing results, trigger first then flow order.\nexport function workflowReadiness(\n blocks: readonly { id: string; missing: string[] | null }[],\n hasTrigger: boolean,\n): WorkflowReadiness {\n const firstIncomplete =\n blocks.find((block) => block.missing && block.missing.length > 0)?.id ??\n null;\n const checking = blocks.some((block) => block.missing === null);\n return {\n ready: hasTrigger && !checking && firstIncomplete === null,\n hasTrigger,\n firstIncomplete,\n checking,\n };\n}\n","// The step form's runtime seam: a DesignTimeService plus the query cache its\n// answers live in, provided by the editor shell (or a test harness).\nimport {\n keepPreviousData,\n QueryClient,\n useQueries,\n useQuery,\n type Query,\n type QueryKey,\n} from \"@tanstack/react-query\";\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport type {\n BlockForm,\n BlockFormProp,\n BlockResolutionView,\n ConnectionSummary,\n DesignTimeService,\n LatestRun,\n StepTestOutcome,\n WebhookEndpoint,\n} from \"./forms.js\";\nimport { parsePropList } from \"./validation.js\";\nimport { isSyncingError } from \"../runtime-client.js\";\nimport type { BlockRef } from \"./blocks.js\";\nimport {\n blockRefKey,\n RESOLVER_STALE_MS,\n runtimeKeys,\n SHARED_STALE_MS,\n type ResolverKeyInput,\n} from \"./query-keys.js\";\n\ninterface DesignTimeContextValue {\n service?: DesignTimeService;\n queryClient: QueryClient;\n // Leads every query key; the runtime URL in the editor.\n scope: string;\n}\n\nconst DesignTimeContext = createContext<DesignTimeContextValue | null>(null);\n\nexport function DesignTimeProvider(props: {\n service?: DesignTimeService;\n queryClient: QueryClient;\n scope: string;\n children: ReactNode;\n}) {\n const { service, queryClient, scope } = props;\n const value = useMemo(\n () => ({ service, queryClient, scope }),\n [service, queryClient, scope],\n );\n return (\n <DesignTimeContext.Provider value={value}>\n {props.children}\n </DesignTimeContext.Provider>\n );\n}\n\nexport function useDesignTime(): DesignTimeService | undefined {\n return useContext(DesignTimeContext)?.service;\n}\n\n// Outside a provider nothing loads; the private client only satisfies hooks.\nfunction useDesignTimeScope(): DesignTimeContextValue {\n const context = useContext(DesignTimeContext);\n const [detached] = useState(() =>\n context ? null : { queryClient: new QueryClient(), scope: \"\" },\n );\n return context ?? detached!;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// Null means \"no form, fall back to JSON\"; a refusal keeps its message.\nexport function useBlockForm(block: BlockRef): {\n form: BlockForm | null | \"loading\";\n error?: string;\n} {\n const { service, queryClient, scope } = useDesignTimeScope();\n const query = useQuery(\n {\n queryKey: runtimeKeys.form(scope, block),\n queryFn: () => service!.getBlockForm(block),\n enabled: Boolean(service),\n staleTime: SHARED_STALE_MS,\n },\n queryClient,\n );\n if (!service) return { form: null };\n if (query.data !== undefined) return { form: query.data };\n if (query.status === \"error\") {\n return { form: null, error: messageOf(query.error) };\n }\n return { form: \"loading\" };\n}\n\nfunction formQuery(service: DesignTimeService, scope: string, block: BlockRef) {\n return {\n queryKey: runtimeKeys.form(scope, block),\n queryFn: () => service.getBlockForm(block),\n staleTime: SHARED_STALE_MS,\n };\n}\n\n// Fetches a block's form through the shared cache; null when none loads.\nexport function useBlockFormLoader(): (\n block: BlockRef,\n) => Promise<BlockForm | null> {\n const { service, queryClient, scope } = useDesignTimeScope();\n return useMemo(\n () => async (block: BlockRef) => {\n if (!service) return null;\n try {\n return await queryClient.fetchQuery(formQuery(service, scope, block));\n } catch {\n return null;\n }\n },\n [service, queryClient, scope],\n );\n}\n\n// A block's form only if the cache already holds it; never fetches.\nexport function useCachedBlockForm(): (\n block: BlockRef,\n) => BlockForm | null | undefined {\n const { queryClient, scope } = useDesignTimeScope();\n return useMemo(\n () => (block: BlockRef) =>\n queryClient.getQueryData<BlockForm | null>(\n runtimeKeys.form(scope, block),\n ),\n [queryClient, scope],\n );\n}\n\n// Warms a block's form, e.g. while its picker row is hovered.\nexport function useBlockFormPrefetch(): (block: BlockRef) => void {\n const { service, queryClient, scope } = useDesignTimeScope();\n return useMemo(\n () => (block: BlockRef) => {\n if (!service) return;\n void queryClient.prefetchQuery(formQuery(service, scope, block));\n },\n [service, queryClient, scope],\n );\n}\n\n// useBlockForm for many blocks at once, keyed by blockRefKey.\nexport function useBlockForms(\n blocks: readonly BlockRef[],\n): ReadonlyMap<string, BlockForm | null | \"loading\"> {\n const { service, queryClient, scope } = useDesignTimeScope();\n const unique = [\n ...new Map(blocks.map((block) => [blockRefKey(block), block])).values(),\n ];\n const results = useQueries(\n {\n queries: unique.map((block) => ({\n queryKey: runtimeKeys.form(scope, block),\n queryFn: () => service!.getBlockForm(block),\n enabled: Boolean(service),\n staleTime: SHARED_STALE_MS,\n })),\n },\n queryClient,\n );\n const forms = new Map<string, BlockForm | null | \"loading\">();\n unique.forEach((block, index) => {\n const query = results[index];\n forms.set(\n blockRefKey(block),\n !service\n ? null\n : query.data !== undefined\n ? query.data\n : query.status === \"error\"\n ? null\n : \"loading\",\n );\n });\n return forms;\n}\n\n// Each block's declared ports, once its form has loaded.\nexport function useBlockPorts(\n blocks: readonly BlockRef[],\n): (block: BlockRef) => readonly string[] | undefined {\n const forms = useBlockForms(blocks);\n return (block) => {\n const form = forms.get(blockRefKey(block));\n return form && form !== \"loading\" ? form.ports : undefined;\n };\n}\n\nexport type LoadState<T> =\n | { kind: \"idle\" }\n | { kind: \"loading\" }\n | { kind: \"ready\"; result: T }\n | { kind: \"error\"; message: string };\n\nfunction keyHash(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n// A just-bound reactor connection the runtime doesn't hold yet reads as forbidden.\n// A just-made document the Switchboard doesn't hold yet; never a sign-in.\nconst SYNC_REFUSAL = /forbidden|document\\b.*not found|was not found/i;\nconst SYNC_RETRIES_MAX = 4;\n\nfunction retryWhileSyncing(input: ResolverKeyInput) {\n if (!input.reactorConnectionId) return {};\n return {\n retry: (failures: number, error: unknown) =>\n failures < SYNC_RETRIES_MAX && SYNC_REFUSAL.test(messageOf(error)),\n retryDelay: 1000,\n };\n}\n\n// The first value passes straight through; later changes settle after `ms`.\nfunction useSettled<T>(value: T, ms: number): T {\n const hash = keyHash(value);\n const latest = useRef(value);\n useEffect(() => {\n latest.current = value;\n });\n const [settled, setSettled] = useState({ hash, value });\n useEffect(() => {\n if (hash === settled.hash) return;\n const timer = setTimeout(\n () => setSettled({ hash, value: latest.current }),\n ms,\n );\n return () => clearTimeout(timer);\n }, [hash, settled.hash, ms]);\n return settled.value;\n}\n\n// A DROPDOWN's options or a DYNAMIC prop's fields, cached per resolver key;\n// a changed key re-resolves after `debounceMs`. `reload` is the manual retry.\nexport function useResolvedProp<T>(options: {\n kind: \"options\" | \"dynamic\";\n input: ResolverKeyInput;\n load: (() => Promise<unknown>) | undefined;\n parse: (raw: unknown) => T;\n debounceMs: number;\n}): { state: LoadState<T>; reload: () => void; syncing: boolean } {\n const { queryClient, scope } = useDesignTimeScope();\n const input = useSettled(options.input, options.debounceMs);\n const loadRef = useRef(options);\n useEffect(() => {\n loadRef.current = options;\n });\n const enabled = Boolean(options.load);\n const query = useQuery(\n {\n queryKey: runtimeKeys[options.kind](scope, input),\n queryFn: async () => {\n const current = loadRef.current;\n if (!current.load) throw new Error(\"No resolver\");\n return current.parse(await current.load());\n },\n enabled,\n staleTime: RESOLVER_STALE_MS,\n ...retryWhileSyncing(input),\n },\n queryClient,\n );\n const reload = () => void query.refetch();\n // Retrying a refusal that reads as a document still syncing.\n const syncing = query.isFetching && query.failureCount > 0;\n if (!enabled) return { state: { kind: \"idle\" }, reload, syncing: false };\n if (query.isFetching) return { state: { kind: \"loading\" }, reload, syncing };\n if (query.status === \"error\") {\n return {\n state: { kind: \"error\", message: messageOf(query.error) },\n reload,\n syncing,\n };\n }\n if (query.status === \"success\") {\n return { state: { kind: \"ready\", result: query.data }, reload, syncing };\n }\n return { state: { kind: \"loading\" }, reload, syncing };\n}\n\n// refreshOnSearch: the resolver re-runs with what the author types, debounced.\n// The previous answer stays up until the new one lands.\nexport function useOptionSearch<T>(options: {\n input: ResolverKeyInput;\n query: string;\n load: ((searchValue: string) => Promise<unknown>) | undefined;\n parse: (raw: unknown) => T;\n debounceMs: number;\n}): T | null {\n const { queryClient, scope } = useDesignTimeScope();\n const typed = options.query.trim() === \"\" ? \"\" : options.query;\n const settled = useSettled(typed, options.debounceMs);\n const loadRef = useRef(options);\n useEffect(() => {\n loadRef.current = options;\n });\n const query = useQuery(\n {\n queryKey: runtimeKeys.options(scope, {\n ...options.input,\n searchValue: settled,\n }),\n queryFn: async () => {\n const current = loadRef.current;\n if (!current.load) throw new Error(\"No resolver\");\n return current.parse(await current.load(settled));\n },\n enabled: Boolean(options.load) && settled !== \"\" && typed !== \"\",\n staleTime: RESOLVER_STALE_MS,\n ...retryWhileSyncing(options.input),\n placeholderData: keepPreviousData,\n },\n queryClient,\n );\n return typed === \"\" ? null : (query.data ?? null);\n}\n\n// DYNAMIC fields already resolved for `input`, straight from the cache.\nexport function getResolvedDynamicProps(\n queryClient: QueryClient,\n scope: string,\n input: ResolverKeyInput,\n): BlockFormProp[] | undefined {\n return queryClient.getQueryData<BlockFormProp[]>(\n runtimeKeys.dynamic(scope, input) as unknown as QueryKey,\n );\n}\n\n// Resolves a DYNAMIC prop into the cache the form reads, so the canvas can\n// check a step without its panel open.\nexport function useDynamicPrefetch(): (\n input: ResolverKeyInput,\n config: Record<string, unknown>,\n) => void {\n const { service, queryClient, scope } = useDesignTimeScope();\n return useMemo(\n () => (input: ResolverKeyInput, config: Record<string, unknown>) => {\n if (!service) return;\n void queryClient.prefetchQuery({\n queryKey: runtimeKeys.dynamic(scope, input),\n queryFn: () =>\n service\n .loadOptions(\n input.block,\n input.propName,\n config,\n input.connectionId ?? undefined,\n undefined,\n input.reactorConnectionId ?? undefined,\n )\n .then(parsePropList),\n staleTime: RESOLVER_STALE_MS,\n ...retryWhileSyncing(input),\n });\n },\n [service, queryClient, scope],\n );\n}\n\n// A cache lookup for DYNAMIC fields, read when the caller asks.\nexport function useDynamicCache(): (\n input: ResolverKeyInput,\n) => BlockFormProp[] | undefined {\n const { queryClient, scope } = useDesignTimeScope();\n return useMemo(\n () => (input: ResolverKeyInput) =>\n getResolvedDynamicProps(queryClient, scope, input),\n [queryClient, scope],\n );\n}\n\n// A cache lookup for DYNAMIC fields that re-renders as resolver answers land.\nexport function useDynamicLookup(): (\n input: ResolverKeyInput,\n) => BlockFormProp[] | undefined {\n const { queryClient, scope } = useDesignTimeScope();\n const [version, setVersion] = useState(0);\n useEffect(\n () =>\n queryClient.getQueryCache().subscribe((event) => {\n if (event.type !== \"updated\") return;\n const key = (event.query as Query).queryKey;\n if (key[0] === scope && key[1] === \"dynamic\") setVersion((v) => v + 1);\n }),\n [queryClient, scope],\n );\n // A fresh function per landed answer, so dependents recompute.\n return useMemo(\n () => (input: ResolverKeyInput) =>\n version >= 0\n ? getResolvedDynamicProps(queryClient, scope, input)\n : undefined,\n [queryClient, scope, version],\n );\n}\n\n// One journaled run, e.g. the trigger's last test; undefined while unknown.\nexport function useRunById(\n runId: string | null | undefined,\n): LatestRun | null | undefined {\n const { service, queryClient, scope } = useDesignTimeScope();\n const fetchRun = service?.fetchRun;\n const query = useQuery(\n {\n queryKey: runtimeKeys.run(scope, runId ?? \"\"),\n queryFn: () => fetchRun!(runId!),\n enabled: Boolean(fetchRun && runId),\n staleTime: Infinity,\n },\n queryClient,\n );\n if (!runId) return null;\n return query.data;\n}\n\nexport type LatestRunState =\n | { kind: \"loading\" }\n | { kind: \"ready\"; run: LatestRun | null };\n\n// The workflow's most recent run; null when the service can't say.\nexport function useLatestRun(enabled = true): LatestRunState | null {\n const { service, queryClient, scope } = useDesignTimeScope();\n const active = enabled && Boolean(service?.latestRun);\n const query = useQuery(\n {\n queryKey: runtimeKeys.latestRun(scope, service?.workflowId ?? \"\"),\n queryFn: () => service!.latestRun!(),\n enabled: active,\n staleTime: 0,\n },\n queryClient,\n );\n if (!active) return null;\n if (query.status === \"pending\") return { kind: \"loading\" };\n return { kind: \"ready\", run: query.data ?? null };\n}\n\n// The runtime already waits for the document; these cover a slower sync.\nconst SYNC_RETRIES = 5;\nconst SYNC_RETRY_MS = 2_000;\n\nexport type EndpointState =\n | { kind: \"loading\" }\n | { kind: \"syncing\" }\n | { kind: \"empty\" }\n | { kind: \"error\"; message: string }\n | { kind: \"ready\"; endpoint: WebhookEndpoint };\n\n// Never kept: the runtime mints the endpoint on first ask, and `armed`\n// follows the workflow's status.\nexport function useWebhookEndpoint(enabled: boolean): EndpointState {\n const { service, queryClient, scope } = useDesignTimeScope();\n const active = enabled && Boolean(service?.webhookEndpoint);\n const query = useQuery(\n {\n queryKey: runtimeKeys.webhook(scope, service?.workflowId ?? \"\"),\n queryFn: () => service!.webhookEndpoint!(),\n enabled: active,\n staleTime: 0,\n gcTime: 0,\n // A new workflow may not have reached the runtime yet.\n retry: (failures, error) =>\n isSyncingError(error) && failures < SYNC_RETRIES,\n retryDelay: SYNC_RETRY_MS,\n },\n queryClient,\n );\n if (query.status === \"pending\" && isSyncingError(query.failureReason)) {\n return { kind: \"syncing\" };\n }\n if (query.status === \"error\") {\n return { kind: \"error\", message: messageOf(query.error) };\n }\n if (query.status === \"pending\") return { kind: \"loading\" };\n return query.data\n ? { kind: \"ready\", endpoint: query.data }\n : { kind: \"empty\" };\n}\n\n// Connection documents for the picker. Never kept: the server scopes the\n// listing to the caller.\nexport function useConnectionList(): {\n connections: ConnectionSummary[];\n refetch: () => void;\n // Drops every connection listing for this runtime.\n invalidate: () => void;\n // Fetches afresh into the cache; creating a connection polls this.\n fetchNow: () => Promise<ConnectionSummary[]>;\n} {\n const { service, queryClient, scope } = useDesignTimeScope();\n const list = service?.listConnections;\n const options = {\n queryKey: runtimeKeys.connections(scope, service?.connectionScope ?? null),\n queryFn: () => list!(),\n staleTime: 0,\n gcTime: 0,\n };\n const query = useQuery({ ...options, enabled: Boolean(list) }, queryClient);\n return {\n connections: query.data ?? [],\n refetch: () => {\n if (list) void query.refetch();\n },\n invalidate: () =>\n void queryClient.invalidateQueries({\n queryKey: runtimeKeys.connections(scope),\n }),\n fetchNow: () =>\n list\n ? queryClient.fetchQuery({ ...options, staleTime: 0 })\n : Promise.resolve([]),\n };\n}\n\n// A step test is a new run and a new sample for the output trees.\nexport function useTestStepRunner():\n | ((stepId: string) => Promise<StepTestOutcome>)\n | undefined {\n const { service, queryClient, scope } = useDesignTimeScope();\n const test = service?.testStep;\n if (!test) return undefined;\n return (stepId) =>\n test(stepId).finally(() => {\n for (const queryKey of [\n runtimeKeys.allRuns(scope),\n [scope, \"latestRun\"],\n runtimeKeys.outputTrees(scope),\n ]) {\n void queryClient.invalidateQueries({ queryKey });\n }\n });\n}\n\n// Runs the trigger's test hook; its samples can change the output trees.\nexport function useTestTrigger(): (() => Promise<unknown>) | undefined {\n const { service, queryClient, scope } = useDesignTimeScope();\n const test = service?.testTrigger;\n if (!test) return undefined;\n return () =>\n test().finally(\n () =>\n void queryClient.invalidateQueries({\n queryKey: runtimeKeys.outputTrees(scope),\n }),\n );\n}\n\nclass DraftNotSynced extends Error {}\n\n// Retries while the runtime still reads an older draft than the editor holds.\nconst DRAFT_SYNC_RETRIES = 10;\n\n/**\n * The piece version each draft block runs, trigger first; `blocks` is the\n * draft in that order. Empty outside a runtime, or until the runtime answers.\n */\nexport function useBlockResolutions(\n workflowId: string,\n blocks: readonly { id: string; block: BlockRef }[],\n): BlockResolutionView[] {\n const { service, queryClient, scope } = useDesignTimeScope();\n const fetchResolutions = service?.blockResolutions;\n const expected = blocks.map(\n (entry) => `${entry.id}=${blockRefKey(entry.block)}`,\n );\n const query = useQuery(\n {\n queryKey: runtimeKeys.blockResolutions(\n scope,\n workflowId,\n blocks.map((entry) => entry.block),\n ),\n queryFn: async () => {\n const resolutions = await fetchResolutions!();\n const answered = resolutions.map(\n (resolution) => `${resolution.stepId}=${blockRefKey(resolution)}`,\n );\n if (keyHash(answered) !== keyHash(expected)) {\n throw new DraftNotSynced();\n }\n return resolutions;\n },\n enabled: Boolean(fetchResolutions && workflowId),\n retry: (count, error) =>\n error instanceof DraftNotSynced && count < DRAFT_SYNC_RETRIES,\n retryDelay: 300,\n placeholderData: keepPreviousData,\n staleTime: 0,\n },\n queryClient,\n );\n return query.data ?? EMPTY_RESOLUTIONS;\n}\n\nconst EMPTY_RESOLUTIONS: BlockResolutionView[] = [];\n","// Shared run vocabulary: one set of formatters and status colours so the\n// header, the table and the editor toolbar never disagree about a run.\nimport type { RunRecord } from \"../../workflow-editor/runtime-client.js\";\n\nexport const RUN_STATUSES = [\"RUNNING\", \"SUCCEEDED\", \"FAILED\"] as const;\n\n// Every status maps to one of five tones; colour carries meaning nowhere else.\nexport type Tone = \"ok\" | \"fail\" | \"warn\" | \"run\" | \"idle\";\n\nexport const TONE_TEXT: Record<Tone, string> = {\n ok: \"text-wf-ok\",\n fail: \"text-wf-fail\",\n warn: \"text-wf-warn\",\n run: \"text-wf-run\",\n idle: \"text-muted-foreground\",\n};\n\nexport const TONE_DOT: Record<Tone, string> = {\n ok: \"bg-wf-ok\",\n fail: \"bg-wf-fail\",\n warn: \"bg-wf-warn\",\n run: \"bg-wf-run\",\n idle: \"bg-muted-foreground/40\",\n};\n\nexport const TONE_BADGE: Record<Tone, string> = {\n ok: \"bg-wf-ok/12 text-wf-ok\",\n fail: \"bg-wf-fail/12 text-wf-fail\",\n warn: \"bg-wf-warn/12 text-wf-warn\",\n run: \"bg-wf-run/12 text-wf-run\",\n idle: \"bg-muted text-muted-foreground\",\n};\n\nexport const RUN_TONE: Record<string, Tone> = {\n SUCCEEDED: \"ok\",\n FAILED: \"fail\",\n RUNNING: \"run\",\n WAITING: \"run\",\n PENDING: \"idle\",\n PARKED: \"warn\",\n CANCELLED: \"idle\",\n};\n\nexport const STEP_TONE: Record<string, Tone> = {\n ...RUN_TONE,\n SKIPPED: \"idle\",\n REPLAYED: \"run\",\n // Neither a success nor a failure: a host call the step made timed out, so\n // a write it asked for may well have been committed. Its own tone, because\n // reading it as either of the other two is the mistake.\n INDETERMINATE: \"warn\",\n};\n\nexport const WORKFLOW_TONE: Record<string, Tone> = {\n ENABLED: \"ok\",\n DRAFT: \"idle\",\n DISABLED: \"warn\",\n ARCHIVED: \"idle\",\n};\n\n// A workflow's dot: hollow until it is first published, then coloured by its\n// last run, and a plain filled dot while it has none.\n// A succeeded run with warnings reads as a warning, never as a plain success.\nexport function runTone(run: {\n status: string;\n warningNotes?: readonly string[];\n}): Tone {\n if (run.status === \"SUCCEEDED\" && (run.warningNotes?.length ?? 0) > 0) {\n return \"warn\";\n }\n return toneOf(RUN_TONE, run.status);\n}\n\nexport function runStatusLabel(run: {\n status: string;\n warningNotes?: readonly string[];\n}): string {\n const count = run.warningNotes?.length ?? 0;\n const label = statusLabel(run.status);\n if (run.status !== \"SUCCEEDED\" || count === 0) return label;\n return `${label}, ${count} ${count === 1 ? \"warning\" : \"warnings\"}`;\n}\n\nexport function workflowHealth(\n status: string | undefined,\n lastRunStatus: string | undefined,\n published: boolean,\n): { tone: Tone; hollow: boolean; label: string } {\n if (!published) {\n return { tone: \"idle\", hollow: true, label: \"Not published yet\" };\n }\n const prefix =\n status === \"ENABLED\" ? \"\" : `${statusLabel(status ?? \"DISABLED\")}, `;\n const run = lastRunStatus\n ? `last run ${statusLabel(lastRunStatus).toLowerCase()}`\n : \"not run yet\";\n const label = prefix + run;\n return {\n tone: toneOf(RUN_TONE, lastRunStatus),\n hollow: false,\n label: label.charAt(0).toUpperCase() + label.slice(1),\n };\n}\n\nexport const CONNECTION_TONE: Record<string, Tone> = {\n OK: \"ok\",\n ERROR: \"fail\",\n REVOKED: \"fail\",\n UNCONFIGURED: \"warn\",\n};\n\nexport function toneOf(map: Record<string, Tone>, status?: string): Tone {\n const tone = status ? (map[status] as Tone | undefined) : undefined;\n return tone ?? \"idle\";\n}\n\n// FAILED → Failed; stored enums read as words, not tokens.\nexport function statusLabel(status: string): string {\n return status.charAt(0) + status.slice(1).toLowerCase();\n}\n\nexport function formatDuration(\n startedAt: string,\n endedAt: string | null,\n): string {\n if (!endedAt) return \"…\";\n return formatMs(new Date(endedAt).getTime() - new Date(startedAt).getTime());\n}\n\nexport interface TimelineSpan {\n // Fractions of the run's length, for positioning a bar.\n offset: number;\n width: number;\n ms: number;\n}\n\n// Where each timed step sat within its run; untimed steps (skipped, replayed,\n// journaled before timings) get no span.\nexport function runTimeline(run: {\n startedAt: string;\n endedAt: string | null;\n steps: { stepId: string; startedAt: string | null; endedAt: string | null }[];\n}): Map<string, TimelineSpan> {\n const start = new Date(run.startedAt).getTime();\n const ends = run.steps\n .map((step) => (step.endedAt ? new Date(step.endedAt).getTime() : 0))\n .concat(run.endedAt ? new Date(run.endedAt).getTime() : 0);\n const total = Math.max(...ends) - start;\n const spans = new Map<string, TimelineSpan>();\n if (total <= 0) return spans;\n for (const step of run.steps) {\n if (!step.startedAt || !step.endedAt) continue;\n const from = new Date(step.startedAt).getTime() - start;\n const ms =\n new Date(step.endedAt).getTime() - new Date(step.startedAt).getTime();\n spans.set(step.stepId, {\n offset: Math.min(Math.max(from / total, 0), 1),\n width: Math.min(Math.max(ms / total, 0), 1),\n ms,\n });\n }\n return spans;\n}\n\n// Rounds before splitting units, so 59.96s reads \"1m 0s\" rather than \"60.0s\".\nexport function formatMs(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n const tenths = Math.round(ms / 100);\n if (tenths < 600) return `${(tenths / 10).toFixed(1)}s`;\n const seconds = Math.round(ms / 1000);\n return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;\n}\n\nexport function durationMs(\n startedAt: string,\n endedAt: string | null,\n): number | null {\n if (!endedAt) return null;\n return new Date(endedAt).getTime() - new Date(startedAt).getTime();\n}\n\nexport function formatWhen(startedAt: string): string {\n const diff = Date.now() - new Date(startedAt).getTime();\n if (diff < 60_000) return \"just now\";\n if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;\n if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;\n return new Date(startedAt).toLocaleDateString();\n}\n\nexport function formatAbsolute(iso: string): string {\n return new Date(iso).toLocaleString();\n}\n\n// A trigger kind reads better as a verb phrase than as its stored token.\nexport function formatTrigger(kind: string): string {\n return kind.replace(/[-_]/g, \" \").toLowerCase();\n}\n\nexport interface RunStats {\n total: number;\n succeeded: number;\n failed: number;\n running: number;\n lastRun?: RunRecord;\n // Null until at least one run has finished.\n successRate: number | null;\n}\n\nexport function runStats(runs: RunRecord[]): RunStats {\n const succeeded = runs.filter((run) => run.status === \"SUCCEEDED\").length;\n const failed = runs.filter((run) => run.status === \"FAILED\").length;\n const finished = succeeded + failed;\n return {\n total: runs.length,\n succeeded,\n failed,\n running: runs.filter((run) => run.status === \"RUNNING\").length,\n // Runs arrive newest first.\n lastRun: runs[0],\n successRate:\n finished === 0 ? null : Math.round((succeeded / finished) * 100),\n };\n}\n\n// The error name of a run its deadline cancelled (the runtime's\n// RUN_DEADLINE_ERROR_NAME); a refused firing is CANCELLED without one.\nconst RUN_DEADLINE_ERROR_NAME = \"RunDeadlineExceeded\";\n\n// Whether the runtime will resume this run.\nexport function canRerun(run: { status: string; errorName?: string | null }) {\n return (\n run.status === \"FAILED\" ||\n (run.status === \"CANCELLED\" && run.errorName === RUN_DEADLINE_ERROR_NAME)\n );\n}\n","// Display metadata per block type: label + logo, Activepieces logos for\n// pieces, glyph badges for core blocks.\n//\n// Piece logo URLs are NOT derivable from the package name: Activepieces\n// serves ~10% of pieces from a different filename, folder or extension than\n// `<piece>.png` (e.g. @activepieces/piece-date-helper lives at\n// /pieces/new-core/date-helper.svg). So logos come from the piece catalog\n// metadata, registered here as it loads; unknown pieces render a glyph.\nimport {\n blockKey,\n type BlockIdentity,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n ASSERT_BLOCK,\n BRANCH_BLOCK,\n isCoreBlock,\n MANUAL_TRIGGER,\n SCHEDULE_TRIGGER,\n WEBHOOK_TRIGGER,\n} from \"./blocks.js\";\nimport { useEffect, useSyncExternalStore } from \"react\";\nimport { usePieceSource, type PieceCatalogSource } from \"./piece-source.js\";\n\nexport interface BlockMeta {\n displayName: string;\n subtitle: string;\n logoUrl?: string;\n glyph?: string;\n}\n\n// Keyed by blockKey, so every version of a core block reads the same.\nconst CORE_META: Record<string, BlockMeta> = {\n [blockKey(MANUAL_TRIGGER)]: {\n displayName: \"Manual\",\n subtitle: \"Trigger\",\n glyph: \"▶\",\n },\n [blockKey(SCHEDULE_TRIGGER)]: {\n displayName: \"Schedule\",\n subtitle: \"Trigger\",\n glyph: \"◷\",\n },\n [blockKey(WEBHOOK_TRIGGER)]: {\n displayName: \"Webhook\",\n subtitle: \"Trigger\",\n glyph: \"⇲\",\n },\n [blockKey(BRANCH_BLOCK)]: {\n displayName: \"Branch\",\n subtitle: \"Core\",\n glyph: \"⑂\",\n },\n [blockKey(ASSERT_BLOCK)]: {\n displayName: \"Assert\",\n subtitle: \"Core\",\n glyph: \"!\",\n },\n};\n\n// \"@activepieces/piece-http\" -> \"http\".\nfunction shortPieceName(packageName: string): string {\n return (\n packageName\n .split(\"/\")\n .pop()\n ?.replace(/^piece-/, \"\") ?? \"\"\n );\n}\n\n// Logos keyed by package name (\"@activepieces/piece-date-helper\"), as given\n// by the piece catalog. Module-level: display data, the same for any runtime.\nconst pieceLogos = new Map<string, string>();\n// Catalog display names (\"HTTP\", \"OpenAI\"), which the package name can't give.\nconst pieceNames = new Map<string, string>();\nconst listeners = new Set<() => void>();\n// Bumped on every registration so useSyncExternalStore re-reads.\nlet logoRevision = 0;\n\nexport function registerPieceLogos(\n entries: Iterable<{\n name: string;\n logoUrl?: string | null;\n displayName?: string | null;\n }>,\n): void {\n let changed = false;\n for (const entry of entries) {\n if (!entry.name) continue;\n if (entry.displayName && pieceNames.get(entry.name) !== entry.displayName) {\n pieceNames.set(entry.name, entry.displayName);\n changed = true;\n }\n if (!entry.logoUrl || pieceLogos.get(entry.name) === entry.logoUrl)\n continue;\n pieceLogos.set(entry.name, entry.logoUrl);\n changed = true;\n }\n if (!changed) return;\n logoRevision += 1;\n for (const listener of listeners) listener();\n}\n\nexport function pieceLogo(packageName: string): string | undefined {\n return pieceLogos.get(packageName);\n}\n\nexport function pieceDisplayName(packageName: string): string | undefined {\n return pieceNames.get(packageName);\n}\n\n// Action and trigger names (\"Ask ChatGPT\"), keyed by blockKey, loaded per\n// piece the first time one of its blocks is shown.\nconst blockNames = new Map<string, string>();\nconst namesRequested = new Set<string>();\n// Packages blockMeta() saw without names; drained by usePieceLogos.\nconst namesPending = new Set<string>();\n\nexport function registerBlockNames(\n entries: Iterable<BlockIdentity & { displayName: string }>,\n): void {\n let changed = false;\n for (const entry of entries) {\n const key = blockKey(entry);\n if (!entry.displayName || blockNames.get(key) === entry.displayName)\n continue;\n blockNames.set(key, entry.displayName);\n changed = true;\n }\n if (!changed) return;\n logoRevision += 1;\n for (const listener of listeners) listener();\n}\n\nfunction requestBlockNames(packageName: string): void {\n if (!namesRequested.has(packageName)) namesPending.add(packageName);\n}\n\n// Fire-and-forget, once per piece; a failure clears the mark so a later\n// render retries. The runtime layer caches the requests themselves.\nexport function loadPendingBlockNames(source: PieceCatalogSource): void {\n for (const packageName of namesPending) loadBlockNames(source, packageName);\n namesPending.clear();\n}\n\nfunction loadBlockNames(source: PieceCatalogSource, packageName: string) {\n if (namesRequested.has(packageName)) return;\n namesRequested.add(packageName);\n Promise.all([\n source.loadActions(packageName),\n source.loadTriggers(packageName),\n ])\n .then(([actions, triggers]) =>\n registerBlockNames([\n ...actions.map((entry) => ({ ...entry, kind: \"action\" as const })),\n ...triggers.map((entry) => ({ ...entry, kind: \"trigger\" as const })),\n ]),\n )\n .catch(() => namesRequested.delete(packageName));\n}\n\n// Test seam: drop the cache so a fresh catalog can be registered.\nexport function resetPieceLogos(): void {\n pieceLogos.clear();\n pieceNames.clear();\n blockNames.clear();\n namesRequested.clear();\n namesPending.clear();\n logoMisses.clear();\n for (const timer of retryTimers) clearTimeout(timer);\n retryTimers.clear();\n catalogLoads = new WeakMap();\n notify();\n}\n\nexport function subscribePieceLogos(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\nfunction pieceLogoRevision(): number {\n return logoRevision;\n}\n\n// Pieces a block rendered for before their logo was known.\nconst logoMisses = new Set<string>();\n\ninterface CatalogLoad {\n // Absent while a retry waits.\n load?: Promise<void>;\n attempts: number;\n}\n\nlet catalogLoads = new WeakMap<PieceCatalogSource, CatalogLoad>();\nconst retryTimers = new Set<ReturnType<typeof setTimeout>>();\n\nexport const CATALOG_RETRY_MS = 2000;\nexport const CATALOG_MAX_ATTEMPTS = 5;\n\nfunction notify(): void {\n logoRevision += 1;\n for (const listener of listeners) listener();\n}\n\n// Backs off, then wakes subscribers so their next render's effect retries.\nfunction scheduleRetry(state: CatalogLoad): void {\n if (state.attempts >= CATALOG_MAX_ATTEMPTS) return;\n const timer = setTimeout(\n () => {\n retryTimers.delete(timer);\n state.load = undefined;\n notify();\n },\n CATALOG_RETRY_MS * 2 ** (state.attempts - 1),\n );\n retryTimers.add(timer);\n}\n\n// A failed load, or one missing a piece on screen (the runtime drops the\n// published catalog when it is down), is retried with a fresh fetch.\nexport function ensurePieceLogos(source?: PieceCatalogSource): Promise<void> {\n if (!source) return Promise.resolve();\n let state = catalogLoads.get(source);\n if (!state) {\n state = { attempts: 0 };\n catalogLoads.set(source, state);\n }\n if (state.load) return state.load;\n const current = state;\n const request =\n current.attempts > 0 && source.reloadCatalog\n ? source.reloadCatalog()\n : source.loadCatalog();\n current.attempts += 1;\n current.load = request.then(\n (pieces) => {\n registerPieceLogos(pieces);\n const listed = new Set(pieces.map((piece) => piece.name));\n const unlisted = [...logoMisses].some(\n (name) => !listed.has(name) && !pieceLogos.has(name),\n );\n if (unlisted) scheduleRetry(current);\n },\n () => scheduleRetry(current),\n );\n return current.load;\n}\n\nexport function blockMeta(block: BlockIdentity): BlockMeta {\n const key = blockKey(block);\n const core = CORE_META[key] as BlockMeta | undefined;\n if (core) return core;\n if (isCoreBlock(block)) {\n return { displayName: titleCase(block.name), subtitle: \"Core\", glyph: \"?\" };\n }\n const packageName = block.pieceName;\n const short = shortPieceName(packageName);\n const pieceLabel = pieceNames.get(packageName) ?? titleCase(short);\n const known = blockNames.get(key);\n if (!known) requestBlockNames(packageName);\n const logoUrl = pieceLogo(packageName);\n if (!logoUrl) logoMisses.add(packageName);\n return {\n // The name reads as a label until the piece's own list arrives.\n displayName: known ?? titleCase(block.name),\n subtitle: block.kind === \"trigger\" ? `${pieceLabel} · Trigger` : pieceLabel,\n logoUrl,\n // Shown until the catalog arrives, and whenever the logo fails to load.\n glyph: short.slice(0, 1).toUpperCase() || \"?\",\n };\n}\n\nfunction titleCase(value: string): string {\n return value\n .replaceAll(/[-_]/g, \" \")\n .replace(/^\\w/, (char) => char.toUpperCase());\n}\n\n// Subscribes the caller to logo registrations and kicks off the catalog load.\n// Call once per component that renders many blocks, then use blockMeta().\nexport function usePieceLogos(): number {\n const source = usePieceSource();\n const revision = useSyncExternalStore(\n subscribePieceLogos,\n pieceLogoRevision,\n pieceLogoRevision,\n );\n // Every render: a retry due since the last one starts, and names this\n // render's blockMeta() calls asked for load. Both are no-ops otherwise.\n useEffect(() => {\n void ensurePieceLogos(source);\n if (source && namesPending.size > 0) loadPendingBlockNames(source);\n });\n return revision;\n}\n\nexport function useBlockMeta(block: BlockIdentity): BlockMeta {\n // Re-reads on every logo registration; blockMeta is a cheap lookup.\n usePieceLogos();\n return blockMeta(block);\n}\n","// Which piece version each block runs: the canvas badge, the header summary\n// and the step panel's update offer all read one resolution list.\nimport {\n compareVersions,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport { createContext, useContext, type ReactNode } from \"react\";\nimport type { BlockResolutionView } from \"./forms.js\";\n\nexport type VersionTone = \"neutral\" | \"warn\" | \"fail\";\n\nexport interface VersionBadgeView {\n tone: VersionTone;\n label: string;\n title: string;\n}\n\n// The runtime's note, else what was configured against what runs.\nexport function resolutionText(resolution: BlockResolutionView): string {\n if (resolution.note) return resolution.note;\n if (!resolution.resolvedVersion)\n return `Nothing resolves ${resolution.pieceName} ${resolution.kind} \"${resolution.name}\"`;\n const from = resolution.source ? ` from ${resolution.source}` : \"\";\n return `Configured with v${resolution.pieceVersion}, runs v${resolution.resolvedVersion}${from}`;\n}\n\n// True when the block does not run the version it is configured with.\nexport function runsDifferentVersion(resolution: BlockResolutionView): boolean {\n switch (resolution.match) {\n case \"exact\":\n return false;\n case \"installed\":\n return resolution.resolvedVersion !== resolution.pieceVersion;\n default:\n return true;\n }\n}\n\nexport function versionBadge(\n resolution: BlockResolutionView | undefined,\n): VersionBadgeView | null {\n if (!resolution || !runsDifferentVersion(resolution)) return null;\n const title = resolutionText(resolution);\n if (resolution.match === \"missing\") {\n return { tone: \"fail\", label: \"Missing\", title };\n }\n return {\n tone: resolution.match === \"fallback\" ? \"warn\" : \"neutral\",\n label: `v${resolution.resolvedVersion}`,\n title,\n };\n}\n\n/** The newer version to offer, when a source has one above the pin. */\nexport function updateVersion(\n resolution: BlockResolutionView | undefined,\n): string | null {\n const { pieceVersion, latestVersion } = resolution ?? {};\n if (!pieceVersion || !latestVersion) return null;\n try {\n return compareVersions(latestVersion, pieceVersion) > 0\n ? latestVersion\n : null;\n } catch {\n return null;\n }\n}\n\nconst ResolutionsContext = createContext<readonly BlockResolutionView[]>([]);\nconst DraftBlocksContext = createContext<readonly BlockRef[]>([]);\n\nexport function BlockResolutionsProvider(props: {\n resolutions: readonly BlockResolutionView[];\n // Every block the draft holds, for the picker's version hints.\n blocks: readonly BlockRef[];\n children: ReactNode;\n}) {\n return (\n <DraftBlocksContext.Provider value={props.blocks}>\n <ResolutionsContext.Provider value={props.resolutions}>\n {props.children}\n </ResolutionsContext.Provider>\n </DraftBlocksContext.Provider>\n );\n}\n\nexport function useDraftBlocks(): readonly BlockRef[] {\n return useContext(DraftBlocksContext);\n}\n\n// Only an answer for the block, at the version, the draft holds now.\nexport function useResolution(\n id: string,\n block: BlockRef,\n): BlockResolutionView | undefined {\n const resolutions = useContext(ResolutionsContext);\n return resolutions.find(\n (entry) =>\n entry.stepId === id &&\n entry.pieceName === block.pieceName &&\n entry.pieceVersion === block.pieceVersion &&\n entry.kind === block.kind &&\n entry.name === block.name,\n );\n}\n\nconst SUMMARY_TONE: Record<\"neutral\" | \"warn\", string> = {\n neutral: \"text-muted-foreground hover:text-foreground\",\n warn: \"text-wf-warn\",\n};\n\nexport interface VersionSummaryView {\n text: string;\n // Amber only when a step runs another major or nothing at all.\n tone: \"neutral\" | \"warn\";\n title: string;\n firstStepId: string;\n}\n\nexport function versionSummary(\n resolutions: readonly BlockResolutionView[],\n): VersionSummaryView | null {\n const differing = resolutions.filter(runsDifferentVersion);\n if (differing.length === 0) return null;\n const missing = differing.filter((entry) => entry.match === \"missing\");\n const count = missing.length > 0 ? missing.length : differing.length;\n const noun = count === 1 ? \"step\" : \"steps\";\n const text =\n missing.length > 0\n ? `${count} ${noun} can't find ${count === 1 ? \"its\" : \"their\"} piece`\n : `${count} ${noun} ${count === 1 ? \"runs\" : \"run\"} a different piece version`;\n const warn = differing.some(\n (entry) => entry.match === \"fallback\" || entry.match === \"missing\",\n );\n return {\n text,\n tone: warn ? \"warn\" : \"neutral\",\n title: differing.map(resolutionText).join(\"\\n\"),\n firstStepId: (missing.length > 0 ? missing : differing)[0].stepId,\n };\n}\n\n// \"2 steps run a different piece version\"; selects the first on click.\nexport function VersionSummary(props: {\n resolutions: readonly BlockResolutionView[];\n onSelect: (id: string) => void;\n}) {\n const summary = versionSummary(props.resolutions);\n if (!summary) return null;\n return (\n <button\n type=\"button\"\n data-tone={summary.tone}\n className={`truncate text-xs underline-offset-2 hover:underline ${SUMMARY_TONE[summary.tone]}`}\n title={summary.title}\n onClick={() => props.onSelect(summary.firstStepId)}\n >\n {summary.text}\n </button>\n );\n}\n","// Where the block picker opens beside the button that opened it, kept on\n// screen: below when it fits, otherwise on the roomier side, shrunk to fit.\n\nexport interface PickerRect {\n left: number;\n right: number;\n top: number;\n bottom: number;\n}\n\nexport interface PickerSize {\n width: number;\n height: number;\n}\n\nexport interface PickerPlacement {\n left: number;\n top: number;\n width: number;\n height: number;\n // Opened above the button: a picker shorter than `height` keeps to it.\n above: boolean;\n}\n\nconst MARGIN = 8;\nconst GAP = 6;\n// Below this the list shows too little to be worth opening on that side.\nconst MIN_HEIGHT = 240;\n\nexport function pickerPlacement(\n anchor: PickerRect,\n size: PickerSize,\n viewport: PickerSize,\n): PickerPlacement {\n const width = Math.min(size.width, viewport.width - 2 * MARGIN);\n const below = viewport.height - anchor.bottom - GAP - MARGIN;\n const above = anchor.top - GAP - MARGIN;\n const downward = below >= Math.min(size.height, MIN_HEIGHT) || below >= above;\n const height = Math.max(\n Math.min(size.height, downward ? below : above),\n Math.min(size.height, MIN_HEIGHT),\n );\n const centre = (anchor.left + anchor.right) / 2;\n const left = Math.min(\n Math.max(centre - width / 2, MARGIN),\n viewport.width - width - MARGIN,\n );\n const top = downward\n ? Math.min(anchor.bottom + GAP, viewport.height - height - MARGIN)\n : Math.max(anchor.top - GAP - height, MARGIN);\n return { left, top: Math.max(top, MARGIN), width, height, above: !downward };\n}\n","// Hosts the block picker beside the button that opened it, outside the\n// canvas transform so zoom never scales it and placement sees the screen.\nimport { useLayoutEffect, useState, type RefObject } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { pickerPlacement, type PickerPlacement } from \"./picker-placement.js\";\n\nexport const PICKER_SIZE = { width: 640, height: 480 };\n\nexport function PickerPopover(props: {\n anchor: RefObject<HTMLElement | null>;\n onClose: () => void;\n children: (placement: PickerPlacement) => React.ReactNode;\n}) {\n const [placement, setPlacement] = useState<PickerPlacement | null>(null);\n const { anchor, onClose } = props;\n\n useLayoutEffect(() => {\n const place = () => {\n const rect = anchor.current?.getBoundingClientRect();\n if (!rect) return;\n setPlacement(\n pickerPlacement(rect, PICKER_SIZE, {\n width: window.innerWidth,\n height: window.innerHeight,\n }),\n );\n };\n place();\n // The canvas moving under it would leave it pointing at nothing.\n const onWheel = (event: WheelEvent) => {\n const target = event.target;\n const inside =\n target instanceof Element && target.closest(\"[data-selector-open]\");\n if (!inside) onClose();\n };\n window.addEventListener(\"resize\", onClose);\n window.addEventListener(\"wheel\", onWheel, { capture: true, passive: true });\n return () => {\n window.removeEventListener(\"resize\", onClose);\n window.removeEventListener(\"wheel\", onWheel, { capture: true });\n };\n }, [anchor, onClose]);\n\n const host =\n anchor.current?.closest(\".react-flow\")?.parentElement ?? document.body;\n if (!placement) return null;\n return createPortal(\n <div\n data-selector-open=\"true\"\n className=\"nodrag nopan nowheel fixed z-50 motion-safe:animate-[wf-picker-in_120ms_ease-out]\"\n style={\n placement.above\n ? {\n left: placement.left,\n bottom: window.innerHeight - placement.top - placement.height,\n transformOrigin: \"bottom center\",\n }\n : {\n left: placement.left,\n top: placement.top,\n transformOrigin: \"top center\",\n }\n }\n >\n {props.children(placement)}\n </div>,\n host,\n );\n}\n","// The blocks this browser picked last, per kind. Stored without a version,\n// so a pick from the list pins whatever the catalog offers now.\nimport type { BlockKind, BlockPick, BlockPreset } from \"./blocks.js\";\n\nconst STORAGE_KEY = \"ph-workflow-picker-recent:v1\";\nconst MAX_RECENT = 6;\n\ninterface StoredPick {\n label: string;\n description?: string;\n block: { pieceName: string; kind: BlockKind; name: string };\n}\n\n// Storage is another tab's or an older build's writing; every field is checked.\nfunction isStoredPick(value: unknown): value is StoredPick {\n const entry = value as Partial<StoredPick> | null;\n const block = entry?.block as Partial<StoredPick[\"block\"]> | undefined;\n return (\n typeof entry?.label === \"string\" &&\n typeof block?.pieceName === \"string\" &&\n typeof block.name === \"string\" &&\n (block.kind === \"action\" || block.kind === \"trigger\")\n );\n}\n\nfunction readAll(): StoredPick[] {\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n const parsed: unknown = raw ? JSON.parse(raw) : [];\n return Array.isArray(parsed) ? parsed.filter(isStoredPick) : [];\n } catch {\n return [];\n }\n}\n\nexport function recentPicks(kind: BlockKind): BlockPreset[] {\n return readAll()\n .filter((entry) => entry.block.kind === kind)\n .map((entry) => ({\n label: entry.label,\n description: entry.description ?? \"\",\n block: entry.block satisfies BlockPick,\n defaultConfig: {},\n }));\n}\n\nexport function rememberPick(preset: BlockPreset): void {\n const { pieceName, kind, name } = preset.block;\n const entry: StoredPick = {\n label: preset.label,\n description: preset.description,\n block: { pieceName, kind, name },\n };\n const same = (other: StoredPick) =>\n other.block.pieceName === pieceName &&\n other.block.kind === kind &&\n other.block.name === name;\n const all = readAll();\n const ofKind = all.filter((other) => other.block.kind === kind);\n const others = all.filter((other) => other.block.kind !== kind);\n const next = [entry, ...ofKind.filter((other) => !same(other))].slice(\n 0,\n MAX_RECENT,\n );\n try {\n window.localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify([...next, ...others]),\n );\n } catch {\n // Storage off or full: the list is a convenience.\n }\n}\n","// A scrolling list that mounts only the rows in view. Rows have known heights,\n// so offsets are a running sum rather than a measurement.\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\nconst OVERSCAN = 6;\n\nexport function rowOffsets(heights: readonly number[]): number[] {\n const offsets = [0];\n for (const height of heights) offsets.push(offsets.at(-1)! + height);\n return offsets;\n}\n\n// Rows [start, end) overlapping the window, plus the overscan either side.\nexport function visibleRange(\n offsets: readonly number[],\n scrollTop: number,\n height: number,\n overscan = OVERSCAN,\n): [number, number] {\n const count = offsets.length - 1;\n let start = 0;\n while (start < count && offsets[start + 1] <= scrollTop) start++;\n let end = start;\n while (end < count && offsets[end] < scrollTop + height) end++;\n return [Math.max(0, start - overscan), Math.min(count, end + overscan)];\n}\n\nexport function VirtualList<T>(props: {\n items: readonly T[];\n heightOf: (item: T) => number;\n keyOf: (item: T, index: number) => string;\n render: (item: T, index: number) => React.ReactNode;\n // Kept in view as it moves.\n activeIndex?: number;\n className?: string;\n label?: string;\n // The listbox the search box's aria-controls names.\n id?: string;\n // A new value is a new list, which starts from its top.\n resetKey?: string;\n}) {\n const ref = useRef<HTMLDivElement>(null);\n const [scrollTop, setScrollTop] = useState(0);\n const [height, setHeight] = useState(400);\n const offsets = useMemo(\n () => rowOffsets(props.items.map(props.heightOf)),\n [props.items, props.heightOf],\n );\n\n useLayoutEffect(() => {\n const element = ref.current;\n if (!element) return;\n const observer = new ResizeObserver(() => setHeight(element.clientHeight));\n observer.observe(element);\n setHeight(element.clientHeight);\n return () => observer.disconnect();\n }, []);\n\n // The scroll event syncs the state.\n useEffect(() => {\n if (ref.current) ref.current.scrollTop = 0;\n }, [props.resetKey]);\n\n useEffect(() => {\n const element = ref.current;\n const index = props.activeIndex;\n if (!element || index === undefined || index < 0) return;\n const top = offsets.at(index);\n const bottom = offsets.at(index + 1);\n if (top === undefined || bottom === undefined) return;\n if (top < element.scrollTop) element.scrollTop = top;\n else if (bottom > element.scrollTop + element.clientHeight) {\n element.scrollTop = bottom - element.clientHeight;\n }\n }, [props.activeIndex, offsets]);\n\n const [start, end] = visibleRange(offsets, scrollTop, height);\n return (\n <div\n ref={ref}\n id={props.id}\n role=\"listbox\"\n aria-label={props.label}\n className={`min-h-0 overflow-y-auto ${props.className ?? \"\"}`}\n onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}\n >\n <div\n role=\"presentation\"\n style={{ height: offsets.at(-1), position: \"relative\" }}\n >\n {props.items.slice(start, end).map((item, i) => {\n const index = start + i;\n return (\n <div\n key={props.keyOf(item, index)}\n role=\"presentation\"\n style={{\n position: \"absolute\",\n top: offsets[index],\n left: 0,\n right: 0,\n height: offsets[index + 1] - offsets[index],\n }}\n >\n {props.render(item, index)}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n","// Two-pane block picker: sources on the left, the selected one's blocks on the\n// right, and a grouped search list. Shaped after the Activepieces selector.\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type RefObject,\n useId,\n useLayoutEffect,\n} from \"react\";\nimport { Icon, type IconName } from \"../../shared/icons.js\";\nimport { blockKey } from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n CATALOG_MAX_ATTEMPTS,\n CATALOG_RETRY_MS,\n registerPieceLogos,\n useBlockMeta,\n} from \"./block-meta.js\";\nimport {\n ASSERT_BLOCK,\n BRANCH_BLOCK,\n isCoreBlock,\n MANUAL_TRIGGER,\n pinBlock,\n REACTOR_PIECE,\n SCHEDULE_TRIGGER,\n stepBlock,\n WEBHOOK_TRIGGER,\n type BlockIdentity,\n type BlockPreset,\n type BlockRef,\n type PickedPreset,\n} from \"./blocks.js\";\nimport { useBlockFormPrefetch } from \"./design-time.js\";\nimport type { StepModel } from \"./model.js\";\nimport { useDraftBlocks } from \"./version-badge.js\";\nimport { PICKER_SIZE } from \"./PickerPopover.js\";\nimport { recentPicks, rememberPick } from \"./picker-recent.js\";\nimport { VirtualList } from \"./VirtualList.js\";\nimport {\n blockUnavailable,\n type PieceActionUi,\n type PieceSearchFilterUi,\n type PieceSearchMatchUi,\n type PieceSearchResultUi,\n type PieceSourceKind,\n type PieceSummaryUi,\n type PieceTriggerUi,\n usePieceSource,\n} from \"./piece-source.js\";\n\nexport type PieceMode = \"actions\" | \"triggers\";\n\n// Logo size for the picker's rows: presets, pieces, search hits and attach.\nconst ROW_LOGO = 24;\n\n// Built-in blocks have no artwork of their own; each gets a coloured tile.\nconst CORE_TILE: Record<string, { icon: IconName; color: string }> = {\n [blockKey(MANUAL_TRIGGER)]: { icon: \"play\", color: \"#2563eb\" },\n [blockKey(SCHEDULE_TRIGGER)]: { icon: \"clock\", color: \"#7c3aed\" },\n [blockKey(WEBHOOK_TRIGGER)]: { icon: \"bolt\", color: \"#0891b2\" },\n [blockKey(BRANCH_BLOCK)]: { icon: \"branch\", color: \"#d97706\" },\n [blockKey(ASSERT_BLOCK)]: { icon: \"alert\", color: \"#dc2626\" },\n};\n\nfunction CoreTile(props: {\n tile: { icon: IconName; color: string };\n size: number;\n bare?: boolean;\n}) {\n const tile = props.tile;\n const glyph = Math.round(props.size * (props.bare ? 0.9 : 0.55));\n // Bare: the caller's badge is the tile, so only the icon is drawn.\n if (props.bare) {\n return (\n <span\n className=\"flex shrink-0 items-center justify-center\"\n style={{ width: props.size, height: props.size, color: tile.color }}\n >\n <Icon name={tile.icon} size={glyph} />\n </span>\n );\n }\n return (\n <span\n className=\"flex shrink-0 items-center justify-center rounded-[22%] text-white\"\n style={{\n width: props.size,\n height: props.size,\n backgroundColor: tile.color,\n }}\n >\n <Icon name={tile.icon} size={glyph} />\n </span>\n );\n}\n\nexport function BlockLogo(props: {\n block: BlockIdentity;\n size?: number;\n // Set where the caller already draws a light badge behind the logo.\n bare?: boolean;\n}) {\n const meta = useBlockMeta(props.block);\n const tile = CORE_TILE[blockKey(props.block)] as\n | { icon: IconName; color: string }\n | undefined;\n if (tile) {\n return <CoreTile tile={tile} size={props.size ?? 36} bare={props.bare} />;\n }\n return (\n <LogoFrame\n src={meta.logoUrl}\n alt={meta.displayName}\n size={props.size ?? 36}\n glyph={meta.glyph}\n bare={props.bare}\n />\n );\n}\n\nfunction GlyphBadge(props: { glyph?: string; size: number }) {\n return (\n <div\n className=\"flex shrink-0 items-center justify-center rounded-sm border border-solid border-foreground/10 bg-muted/50 text-muted-foreground\"\n style={{\n width: props.size,\n height: props.size,\n fontSize: props.size / 2,\n }}\n >\n {props.glyph ?? \"?\"}\n </div>\n );\n}\n\n// Falls back to the glyph badge when the piece metadata carries no logo, or\n// when the CDN image fails to load (Activepieces retires logo files).\nfunction LogoFrame(props: {\n src?: string;\n alt: string;\n size: number;\n glyph?: string;\n bare?: boolean;\n}) {\n const [broken, setBroken] = useState(false);\n useEffect(() => {\n // eslint-disable-next-line react-hooks-extra/set-state-in-effect -- a new src gets a fresh chance to load\n setBroken(false);\n }, [props.src]);\n if (!props.src || broken) {\n return <GlyphBadge glyph={props.glyph} size={props.size} />;\n }\n // No frame and no padding around a logo: a piece's artwork is its own tile,\n // with its own corner radius and its own margin.\n\n // Framing it drew our border through corners that were already rounded —\n // and no single radius matches every piece, so the frame is left to the\n // glyph badge, which is the only case where we draw the tile ourselves.\n return (\n // Piece logos are drawn for light backgrounds, so dark mode backs them\n // with a small white tile rather than losing black artwork to the page.\n <div\n className={`flex shrink-0 items-center justify-center ${\n props.bare\n ? \"\"\n : \"dark:rounded-[22%] dark:bg-white dark:p-[var(--logo-pad)]\"\n }`}\n // Pixels, not %: percentage padding follows the container's width.\n style={\n {\n width: props.size,\n height: props.size,\n \"--logo-pad\": `${Math.round(props.size * 0.12)}px`,\n } as CSSProperties\n }\n >\n <img\n src={props.src}\n alt={props.alt}\n // drop-shadow, not a border or a ring: it follows the image's alpha,\n // so it traces the artwork's own silhouette — rounded corners and all\n // — and gives a white-on-transparent logo an edge on a white row.\n className=\"h-full w-full object-contain drop-shadow-sm\"\n onError={() => setBroken(true)}\n />\n </div>\n );\n}\n\nfunction Row(props: {\n logo: React.ReactNode;\n label: React.ReactNode;\n description: React.ReactNode;\n // Full text for truncated labels.\n title?: string;\n onClick: () => void;\n // Warms what a pick will need, while the row is hovered or focused.\n onHover?: () => void;\n disabled?: boolean;\n // The keyboard's row: tinted and marked.\n active?: boolean;\n // The piece the other pane shows, while the keyboard is elsewhere.\n selected?: boolean;\n // Two lines of description, for blocks; the list sizes the row.\n tall?: boolean;\n // Where it sits in its listbox; only the rows in view are mounted.\n option?: OptionPlace;\n // The piece version a pick pins to; shown on hover unless `versionNote`\n // says why it matters here.\n version?: string;\n versionNote?: string;\n}) {\n // An option, not a button: focus stays in the search box, which drives the\n // keyboard and points assistive tech at this row.\n return (\n <div\n {...optionAttributes(props.option)}\n role=\"option\"\n aria-selected={(props.active ?? false) || (props.selected ?? false)}\n aria-disabled={props.disabled}\n className={`group mx-1.5 my-px flex h-[calc(100%-2px)] cursor-pointer items-center gap-2.5 rounded-md px-2 text-left ${rowTone(\n props.active,\n props.selected,\n )} ${props.disabled ? \"cursor-not-allowed opacity-50\" : \"\"}`}\n title={props.title}\n onClick={props.disabled ? undefined : props.onClick}\n onMouseDown={(event) => event.preventDefault()}\n onMouseEnter={props.onHover}\n >\n {/* Decorative: the label names the row. */}\n <span aria-hidden=\"true\" className=\"contents\">\n {props.logo}\n </span>\n <span className=\"min-w-0\">\n <span className=\"block truncate text-[13px] font-medium leading-[18px] text-foreground\">\n {props.label}\n </span>\n <span\n // line-clamp sets its own display; `block` would undo it.\n className={`text-xs leading-4 text-muted-foreground ${\n props.tall ? \"line-clamp-2\" : \"block truncate\"\n }`}\n >\n {props.description}\n </span>\n </span>\n {props.version ? (\n <span\n className={`ml-auto shrink-0 pl-2 text-[11px] tabular-nums text-muted-foreground ${\n props.versionNote\n ? \"\"\n : props.active\n ? \"\"\n : \"hidden group-hover:inline\"\n }`}\n title={props.versionNote ?? `Pinned to version ${props.version}`}\n >\n v{props.version}\n </span>\n ) : null}\n </div>\n );\n}\n\n// The keyboard's row is tinted with the accent; the piece open beside the\n// list sits raised on the rail, joined to the pane that shows it.\nfunction rowTone(active?: boolean, selected?: boolean): string {\n if (active) return \"bg-wf-run/10 ring-1 ring-inset ring-wf-run/25\";\n if (selected) return \"bg-card shadow-sm ring-1 ring-foreground/10\";\n return \"hover:bg-foreground/[0.05]\";\n}\n\n// A row's id and position, named by the search box's aria-activedescendant.\ninterface OptionPlace {\n list: string;\n index: number;\n size: number;\n}\n\nexport function optionId(list: string, index: number): string {\n return `${list}-${index}`;\n}\n\nfunction optionAttributes(place: OptionPlace | undefined) {\n return place\n ? {\n id: optionId(place.list, place.index),\n \"aria-posinset\": place.index + 1,\n \"aria-setsize\": place.size,\n }\n : {};\n}\n\n// The core piece is the runtime's own, so its rows carry no version.\nfunction shownVersion(\n pieceName: string,\n version: string | undefined,\n): string | undefined {\n return isCoreBlock({ pieceName }) ? undefined : version;\n}\n\ntype VersionNote = (\n piece: string | undefined,\n version: string | undefined,\n) => string | undefined;\n\n// Why a row's version is worth showing: a local build shadowing the published\n// piece, or other steps of the workflow on another version of it.\nfunction useVersionNote(\n catalog: readonly PieceSummaryUi[] | undefined,\n): VersionNote {\n const draft = useDraftBlocks();\n return (piece, version) => {\n if (!piece || !version) return undefined;\n const others = [\n ...new Set(\n draft\n .filter(\n (block) =>\n block.pieceName === piece && block.pieceVersion !== version,\n )\n .map((block) => `v${block.pieceVersion}`),\n ),\n ];\n if (others.length > 0) {\n return `Other steps of this workflow use ${others.join(\", \")}`;\n }\n // The reactor piece ships with the runtime, so its copy is the one meant.\n if (piece === REACTOR_PIECE) return undefined;\n const published = catalog?.find(\n (entry) => entry.name === piece,\n )?.publishedVersion;\n return published && published !== version\n ? `A local build; v${published} is published`\n : undefined;\n };\n}\n\n// null while loading.\ninterface CatalogState {\n pieces: PieceSummaryUi[];\n error?: string;\n}\n\n// Activepieces category ids → chip labels; AI variants share one chip.\nconst CATEGORY_LABELS: Record<string, string> = {\n ARTIFICIAL_INTELLIGENCE: \"AI\",\n UNIVERSAL_AI: \"AI\",\n PRODUCTIVITY: \"Productivity\",\n MARKETING: \"Marketing\",\n COMMUNICATION: \"Communication\",\n SALES_AND_CRM: \"Sales & CRM\",\n DEVELOPER_TOOLS: \"Developer tools\",\n CONTENT_AND_FILES: \"Content & files\",\n BUSINESS_INTELLIGENCE: \"Business intelligence\",\n CORE: \"Utilities\",\n FLOW_CONTROL: \"Utilities\",\n COMMERCE: \"Commerce\",\n FORMS_AND_SURVEYS: \"Forms & surveys\",\n ACCOUNTING: \"Accounting\",\n CUSTOMER_SUPPORT: \"Customer support\",\n PAYMENT_PROCESSING: \"Payments\",\n HUMAN_RESOURCES: \"HR\",\n};\n\nconst AI_CHIP = \"AI\";\n\nfunction categoryLabel(id: string): string {\n return (\n CATEGORY_LABELS[id] ??\n id\n .toLowerCase()\n .replaceAll(\"_\", \" \")\n .replace(/^\\w/, (char) => char.toUpperCase())\n );\n}\n\nexport function chipsOf(piece: { categories: string[] }): Set<string> {\n return new Set(piece.categories.map(categoryLabel));\n}\n\n// The category ids a chip stands for, among those the pieces carry.\nexport function categoriesOfChip(\n chip: string,\n pieces: { categories: string[] }[],\n): string[] {\n const ids = new Set(pieces.flatMap((piece) => piece.categories));\n return [...ids].filter((id) => categoryLabel(id) === chip);\n}\n\n// Chip order: AI first, then by piece count.\nexport function orderChips(pieces: { categories: string[] }[]): string[] {\n const counts = new Map<string, number>();\n for (const piece of pieces) {\n for (const chip of chipsOf(piece)) {\n counts.set(chip, (counts.get(chip) ?? 0) + 1);\n }\n }\n const rest = [...counts.entries()]\n .filter(([chip]) => chip !== AI_CHIP)\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([chip]) => chip);\n return [...(counts.has(AI_CHIP) ? [AI_CHIP] : []), ...rest];\n}\n\nexport type SourceTab = \"all\" | \"core\" | \"powerhouse\" | \"activepieces\";\n\nconst TAB_LABELS: Record<SourceTab, string> = {\n all: \"All\",\n core: \"Core\",\n powerhouse: \"Powerhouse\",\n activepieces: \"Integrations\",\n};\n\n// Pieces each tab lists; Core lists the engine's presets only.\nconst TAB_SOURCES: Record<SourceTab, readonly PieceSourceKind[] | undefined> = {\n all: undefined,\n core: [],\n powerhouse: [\"local\", \"registry\"],\n activepieces: [\"activepieces\"],\n};\n\nexport function inTab(tab: SourceTab, piece: { source?: PieceSourceKind }) {\n const sources = TAB_SOURCES[tab];\n return (\n sources === undefined || sources.includes(piece.source ?? \"activepieces\")\n );\n}\n\n// Accents dropped, as the runtime's search drops them.\nfunction folded(text: string): string {\n return text.normalize(\"NFKD\").replace(/\\p{M}/gu, \"\").toLowerCase();\n}\n\nexport function queryTokens(query: string): string[] {\n return folded(query)\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean);\n}\n\n// Every token somewhere in the text, in any order.\nexport function matchesQuery(text: string, tokens: string[]): boolean {\n const lowered = folded(text);\n return tokens.every((token) => lowered.includes(token));\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// Bolds the words the query's tokens start.\nfunction Highlight(props: { text: string; tokens: string[] }) {\n if (props.tokens.length === 0) return <>{props.text}</>;\n const pattern = new RegExp(\n `(?<![\\\\p{L}\\\\p{N}])(${props.tokens.map(escapeRegExp).join(\"|\")})`,\n \"giu\",\n );\n const parts = props.text.split(pattern);\n return (\n <>\n {parts.map((part, i) =>\n i % 2 === 1 ? (\n <mark key={i} className=\"bg-transparent font-semibold text-inherit\">\n {part}\n </mark>\n ) : (\n part\n ),\n )}\n </>\n );\n}\n\nconst SEARCH_MIN_CHARS = 2;\nconst SEARCH_DEBOUNCE_MS = 250;\nconst INDEXING_RETRY_MS = 2000;\n\ntype SearchState =\n | { kind: \"idle\" }\n | { kind: \"loading\" }\n // Stale: answered for an earlier query or filter, while the current one runs.\n | { kind: \"done\"; result: PieceSearchResultUi; stale: boolean }\n | { kind: \"error\"; message: string };\n\ntype SearchAnswer =\n | { kind: \"idle\" }\n | { kind: \"done\"; key: string; result: PieceSearchResultUi }\n | { kind: \"error\"; key: string; message: string };\n\n// Debounced catalog-wide search; keeps polling while the runtime indexes.\nfunction usePieceSearch(\n query: string,\n filter: PieceSearchFilterUi | null,\n): SearchState {\n const [state, setState] = useState<SearchAnswer>({ kind: \"idle\" });\n const [attempt, setAttempt] = useState(0);\n const trimmed = query.trim();\n const search = usePieceSource()?.searchPieces;\n const active =\n filter !== null &&\n search !== undefined &&\n trimmed.length >= SEARCH_MIN_CHARS;\n // A key, so a filter rebuilt with the same fields does not search again.\n const filterKey = JSON.stringify(filter);\n const key = `${trimmed}\\n${filterKey}`;\n\n useEffect(() => {\n if (!active) {\n // eslint-disable-next-line react-hooks-extra/set-state-in-effect -- drops a finished search when the query goes inactive\n setState({ kind: \"idle\" });\n return;\n }\n let alive = true;\n let retry: ReturnType<typeof setTimeout> | undefined;\n const timer = setTimeout(() => {\n search(trimmed, JSON.parse(filterKey) as PieceSearchFilterUi).then(\n (result) => {\n if (!alive) return;\n setState({ kind: \"done\", key, result });\n if (result.status === \"indexing\") {\n retry = setTimeout(\n () => setAttempt((value) => value + 1),\n INDEXING_RETRY_MS,\n );\n }\n },\n (error: unknown) => {\n if (alive) {\n setState({\n kind: \"error\",\n key,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n },\n );\n }, SEARCH_DEBOUNCE_MS);\n return () => {\n alive = false;\n clearTimeout(timer);\n if (retry) clearTimeout(retry);\n };\n }, [active, trimmed, filterKey, key, attempt, search]);\n\n if (!active) return { kind: \"idle\" };\n // Loading through the debounce, so the browse list does not flash first.\n if (state.kind === \"idle\") return { kind: \"loading\" };\n if (state.kind === \"error\") {\n return state.key === key\n ? { kind: \"error\", message: state.message }\n : { kind: \"loading\" };\n }\n // The last answer stays on screen while the next one runs, marked stale.\n return { kind: \"done\", result: state.result, stale: state.key !== key };\n}\n\n// Arrow keys move focus along a row of buttons, wrapping at the ends.\nfunction rovingFocus(event: React.KeyboardEvent<HTMLElement>): void {\n const delta =\n event.key === \"ArrowRight\" ? 1 : event.key === \"ArrowLeft\" ? -1 : 0;\n if (delta === 0) return;\n event.preventDefault();\n const buttons = [\n ...event.currentTarget.querySelectorAll<HTMLButtonElement>(\"button\"),\n ];\n const at = buttons.indexOf(document.activeElement as HTMLButtonElement);\n buttons.at((at + delta) % buttons.length)?.focus();\n}\n\nfunction Chip(props: {\n label: string;\n active: boolean;\n // The one chip Tab lands on.\n tabStop: boolean;\n onClick: (fromKeyboard: boolean) => void;\n}) {\n return (\n <button\n type=\"button\"\n aria-pressed={props.active}\n tabIndex={props.tabStop ? 0 : -1}\n className={`shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium focus-visible:outline-2 focus-visible:outline-wf-run ${\n props.active\n ? \"border-wf-run/40 bg-wf-run/10 text-wf-run\"\n : \"border-foreground/10 text-muted-foreground hover:border-foreground/25 hover:text-foreground\"\n }`}\n // A keyboard click reports no pointer clicks.\n onClick={(event) => props.onClick(event.detail === 0)}\n >\n {props.label}\n </button>\n );\n}\n\n// A scrolling row of chips that fades at an edge with more beyond it.\nfunction ChipBar(props: { children: React.ReactNode }) {\n const ref = useRef<HTMLDivElement>(null);\n const [more, setMore] = useState({ left: false, right: false });\n const measure = () => {\n const element = ref.current;\n if (!element) return;\n const left = element.scrollLeft > 1;\n const right =\n element.scrollLeft + element.clientWidth < element.scrollWidth - 1;\n setMore((previous) =>\n previous.left === left && previous.right === right\n ? previous\n : { left, right },\n );\n };\n useLayoutEffect(() => {\n const element = ref.current;\n if (!element) return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n const fade = (side: \"left\" | \"right\") => (\n <span\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-0 w-14\"\n style={{\n [side]: 0,\n background: `linear-gradient(to ${side === \"left\" ? \"right\" : \"left\"}, var(--card), transparent)`,\n }}\n />\n );\n return (\n <div className=\"relative shrink-0 border-b border-foreground/10\">\n <div\n ref={ref}\n role=\"toolbar\"\n aria-label=\"Categories\"\n className=\"flex gap-1.5 overflow-x-auto whitespace-nowrap px-3 py-2 [scrollbar-width:none]\"\n onKeyDown={rovingFocus}\n onScroll={measure}\n >\n {props.children}\n </div>\n {more.left ? fade(\"left\") : null}\n {more.right ? fade(\"right\") : null}\n </div>\n );\n}\n\nfunction Tabs(props: {\n tabs: SourceTab[];\n active: SourceTab;\n onSelect: (tab: SourceTab, fromKeyboard: boolean) => void;\n}) {\n return (\n <div\n role=\"tablist\"\n aria-label=\"Piece sources\"\n className=\"inline-flex gap-0.5 rounded-md bg-foreground/[0.05] p-0.5\"\n onKeyDown={(event) => {\n rovingFocus(event);\n // Following focus, as a tab list does.\n const focused = document.activeElement as HTMLElement | null;\n const tab = focused?.dataset.tab as SourceTab | undefined;\n if (tab && tab !== props.active) props.onSelect(tab, true);\n }}\n >\n {props.tabs.map((tab) => (\n <button\n key={tab}\n type=\"button\"\n role=\"tab\"\n data-tab={tab}\n aria-selected={props.active === tab}\n tabIndex={props.active === tab ? 0 : -1}\n className={`rounded px-2.5 py-1 text-xs font-medium focus-visible:outline-2 focus-visible:outline-wf-run ${\n props.active === tab\n ? \"bg-card text-foreground shadow-sm\"\n : \"text-muted-foreground hover:text-foreground\"\n }`}\n onClick={(event) => props.onSelect(tab, event.detail === 0)}\n >\n {TAB_LABELS[tab]}\n </button>\n ))}\n </div>\n );\n}\n\nfunction Status(props: { children: React.ReactNode; error?: boolean }) {\n return (\n <div\n role=\"status\"\n className={`px-4 py-2.5 text-xs ${props.error ? \"text-wf-fail\" : \"text-muted-foreground\"}`}\n >\n {props.children}\n </div>\n );\n}\n\n// One pickable row, in either pane or the search list.\ninterface Entry {\n key: string;\n logo: React.ReactNode;\n label: string;\n description: string;\n // Why it cannot be picked; listed anyway, so the reason shows.\n unavailable?: string;\n version?: string;\n versionNote?: string;\n pick: () => void;\n // Warms what a pick needs.\n warm?: () => void;\n}\n\ntype ListId = \"recent\" | \"attach\" | \"core\" | \"powerhouse\";\n\n// A left-pane item: one of our own lists, or a catalog piece.\ntype Source =\n | {\n kind: \"list\";\n id: ListId;\n title: string;\n subtitle: string;\n // Drawn small in the list and large over its blocks.\n logo: (size: number) => React.ReactNode;\n entries: Entry[];\n }\n | { kind: \"piece\"; id: string; piece: PieceSummaryUi };\n\ntype SearchRow =\n | { type: \"list\"; source: Extract<Source, { kind: \"list\" }> }\n | { type: \"piece\"; match: PieceSearchMatchUi }\n | { type: \"entry\"; entry: Entry }\n | { type: \"more\"; pieceName: string; hidden: number };\n\nconst ROW_HEIGHT = 46;\nconst BLOCK_HEIGHT = 60;\n// The open piece's logo, over its blocks.\nconst HEADER_LOGO = 36;\nconst HEADER_HEIGHT = 38;\nconst MORE_HEIGHT = 28;\n// Blocks a search group shows before \"more\"; all of them for one or two groups.\nconst GROUP_BLOCKS = 4;\n// Hovering a piece previews it once the pointer settles.\nconst HOVER_PREVIEW_MS = 120;\n\nconst searchRowHeight = (row: SearchRow) =>\n row.type === \"entry\"\n ? BLOCK_HEIGHT\n : row.type === \"more\"\n ? MORE_HEIGHT\n : HEADER_HEIGHT;\nconst sourceHeight = () => ROW_HEIGHT;\nconst entryHeight = () => BLOCK_HEIGHT;\n\nfunction listTile(icon: IconName, color: string) {\n return (size: number) => <CoreTile tile={{ icon, color }} size={size} />;\n}\n\nfunction EntryRow(props: {\n entry: Entry;\n tokens: string[];\n active: boolean;\n option: OptionPlace;\n indent?: boolean;\n onActivate: () => void;\n}) {\n const { entry } = props;\n return (\n <Row\n logo={\n props.indent ? (\n // An empty slot keeps the block indented under its piece.\n <span className=\"shrink-0\" style={{ width: ROW_LOGO }} />\n ) : (\n entry.logo\n )\n }\n label={<Highlight text={entry.label} tokens={props.tokens} />}\n title={entry.description || entry.label}\n description={\n entry.unavailable ?? (\n <Highlight text={entry.description} tokens={props.tokens} />\n )\n }\n disabled={entry.unavailable !== undefined}\n active={props.active}\n tall\n option={props.option}\n version={entry.version}\n versionNote={entry.versionNote}\n onHover={() => {\n props.onActivate();\n if (entry.unavailable === undefined) entry.warm?.();\n }}\n onClick={entry.pick}\n />\n );\n}\n\nfunction SourceRow(props: {\n source: Source;\n tokens: string[];\n mode: PieceMode;\n active: boolean;\n selected: boolean;\n option: OptionPlace;\n onActivate: () => void;\n onOpen: () => void;\n}) {\n const { source } = props;\n if (source.kind === \"list\") {\n return (\n <Row\n logo={source.logo(ROW_LOGO)}\n label={source.title}\n description={source.subtitle}\n active={props.active}\n selected={props.selected}\n option={props.option}\n onHover={props.onActivate}\n onClick={props.onOpen}\n />\n );\n }\n const { piece } = source;\n const count =\n props.mode === \"triggers\" ? piece.triggerCount : piece.actionCount;\n const noun = props.mode === \"triggers\" ? \"trigger\" : \"action\";\n return (\n <Row\n logo={\n <LogoFrame\n src={piece.logoUrl}\n alt={piece.displayName}\n size={ROW_LOGO}\n />\n }\n label={\n <>\n <Highlight text={piece.displayName} tokens={props.tokens} />\n {piece.deprecated ? \" (deprecated)\" : \"\"}\n </>\n }\n title={piece.description || piece.displayName}\n description={\n piece.unsupported ?? `${count} ${noun}${count === 1 ? \"\" : \"s\"}`\n }\n active={props.active}\n selected={props.selected}\n option={props.option}\n onHover={props.onActivate}\n onClick={props.onOpen}\n />\n );\n}\n\n// The actions or triggers of one piece, once loaded.\nfunction usePieceEntries(\n piece: PieceSummaryUi | undefined,\n mode: PieceMode,\n): {\n entries: (PieceActionUi & Partial<PieceTriggerUi>)[] | null;\n error: string | null;\n} {\n const pieceSource = usePieceSource();\n const [state, setState] = useState<{\n name: string;\n entries: (PieceActionUi & Partial<PieceTriggerUi>)[] | null;\n error: string | null;\n } | null>(null);\n const name = piece?.name;\n\n useEffect(() => {\n if (!name || !pieceSource) return;\n let cancelled = false;\n const load =\n mode === \"triggers\"\n ? pieceSource.loadTriggers(name)\n : pieceSource.loadActions(name);\n load.then(\n (entries) => {\n if (!cancelled) setState({ name, entries, error: null });\n },\n (error: unknown) => {\n if (!cancelled) {\n setState({\n name,\n entries: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n );\n return () => {\n cancelled = true;\n };\n }, [name, mode, pieceSource]);\n\n return state && state.name === name\n ? { entries: state.entries, error: state.error }\n : { entries: null, error: null };\n}\n\nfunction EntriesPane(props: {\n source: Source | undefined;\n mode: PieceMode;\n pieceEntries: Entry[] | null;\n pieceError: string | null;\n tokens: string[];\n activeIndex: number;\n listId: string;\n // Off where the source is the whole picker, as a tab already names it.\n showHeader: boolean;\n onActivate: (index: number) => void;\n}) {\n const { source } = props;\n const entries = source?.kind === \"list\" ? source.entries : props.pieceEntries;\n const kind = props.mode === \"triggers\" ? \"trigger\" : \"action\";\n const title =\n source?.kind === \"list\" ? source.title : source?.piece.displayName;\n const about =\n source?.kind === \"list\" ? source.subtitle : source?.piece.description;\n return (\n <div className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {source && props.showHeader ? (\n <div className=\"flex shrink-0 items-start gap-3 border-b border-foreground/10 px-4 py-3\">\n <span aria-hidden=\"true\" className=\"contents\">\n {source.kind === \"list\" ? (\n source.logo(HEADER_LOGO)\n ) : (\n <LogoFrame src={source.piece.logoUrl} alt=\"\" size={HEADER_LOGO} />\n )}\n </span>\n <div className=\"min-w-0\">\n <div className=\"truncate text-sm font-semibold leading-5 text-foreground\">\n {title}\n </div>\n {about ? (\n <div\n className=\"line-clamp-2 text-xs leading-4 text-muted-foreground\"\n title={about}\n >\n {about}\n </div>\n ) : null}\n </div>\n </div>\n ) : null}\n {!source ? (\n <Status>Pick a piece to see its {kind}s</Status>\n ) : props.pieceError ? (\n <Status error>{props.pieceError}</Status>\n ) : entries === null ? (\n <Status>Loading…</Status>\n ) : entries.length === 0 ? (\n <Status>No {kind}s</Status>\n ) : (\n <VirtualList\n id={props.listId}\n resetKey={source.id}\n label={`${title ?? \"\"} ${kind}s`}\n className=\"flex-1 py-1\"\n items={entries}\n heightOf={entryHeight}\n keyOf={(entry) => entry.key}\n activeIndex={props.activeIndex}\n render={(entry, index) => (\n <EntryRow\n entry={entry}\n tokens={props.tokens}\n active={index === props.activeIndex}\n option={{ list: props.listId, index, size: entries.length }}\n onActivate={() => props.onActivate(index)}\n />\n )}\n />\n )}\n </div>\n );\n}\n\nfunction SearchList(props: {\n rows: SearchRow[];\n tokens: string[];\n activeIndex: number;\n onActivate: (index: number) => void;\n onOpenPiece: (pieceName: string) => void;\n onOpenList: (id: ListId) => void;\n onExpand: (pieceName: string) => void;\n status: React.ReactNode;\n // \"action\" or \"trigger\", for the heading's link.\n kind: string;\n listId: string;\n resetKey: string;\n stale: boolean;\n}) {\n const size = props.rows.length;\n return (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n {props.status}\n <VirtualList\n id={props.listId}\n label=\"Search results\"\n resetKey={props.resetKey}\n className={`flex-1 py-1 ${props.stale ? \"opacity-60\" : \"\"}`}\n items={props.rows}\n heightOf={searchRowHeight}\n keyOf={(row, index) =>\n row.type === \"entry\"\n ? `e:${row.entry.key}`\n : row.type === \"piece\"\n ? `p:${row.match.pieceName}`\n : row.type === \"list\"\n ? `l:${row.source.id}`\n : `m:${row.pieceName}:${index}`\n }\n activeIndex={props.activeIndex}\n render={(row, index) => {\n const active = index === props.activeIndex;\n const activate = () => props.onActivate(index);\n const option = { list: props.listId, index, size };\n if (row.type === \"entry\") {\n return (\n <EntryRow\n entry={row.entry}\n tokens={props.tokens}\n active={active}\n option={option}\n indent\n onActivate={activate}\n />\n );\n }\n if (row.type === \"more\") {\n return (\n <div\n {...optionAttributes(option)}\n role=\"option\"\n aria-selected={active}\n className={`mx-1.5 my-px flex h-[calc(100%-2px)] cursor-pointer items-center rounded-md pl-[42px] text-xs text-muted-foreground hover:text-foreground ${rowTone(active)}`}\n onMouseDown={(event) => event.preventDefault()}\n onMouseEnter={activate}\n onClick={() => props.onExpand(row.pieceName)}\n >\n {row.hidden} more…\n </div>\n );\n }\n const header =\n row.type === \"piece\"\n ? {\n logo: (\n <LogoFrame\n src={row.match.logoUrl}\n alt={row.match.displayName}\n size={20}\n />\n ),\n label: row.match.displayName,\n note: row.match.deprecated\n ? \"Deprecated\"\n : (row.match.unsupported ?? undefined),\n kind: props.kind,\n open: () => props.onOpenPiece(row.match.pieceName),\n }\n : {\n logo: row.source.logo(20),\n label: row.source.title,\n note: undefined,\n kind: props.kind,\n open: () => props.onOpenList(row.source.id),\n };\n return (\n <div\n {...optionAttributes(option)}\n role=\"option\"\n aria-selected={active}\n title={`Open ${header.label}`}\n className={`group mx-1.5 mt-1 flex h-[calc(100%-4px)] cursor-pointer items-center gap-2.5 rounded-md px-2 text-left ${rowTone(active)}`}\n onMouseDown={(event) => event.preventDefault()}\n onMouseEnter={activate}\n onClick={header.open}\n >\n <span aria-hidden=\"true\" className=\"contents\">\n {header.logo}\n </span>\n <span className=\"truncate text-[13px] font-semibold text-foreground\">\n <Highlight text={header.label} tokens={props.tokens} />\n </span>\n {header.note ? (\n <span className=\"truncate text-[11px] text-muted-foreground\">\n {header.note}\n </span>\n ) : null}\n <span\n className={`ml-auto flex shrink-0 items-center gap-0.5 text-[11px] text-muted-foreground ${\n active ? \"\" : \"opacity-0 group-hover:opacity-100\"\n }`}\n >\n All {header.kind}s\n <Icon name=\"chevron\" size={12} />\n </span>\n </div>\n );\n }}\n />\n </div>\n );\n}\n\nexport function BlockSelector(props: {\n title: string;\n presets: BlockPreset[];\n onPick: (preset: PickedPreset) => void;\n onClose: () => void;\n // Show the piece catalog beside the presets.\n showPieces?: boolean;\n // Which piece entries the picker offers; defaults to actions.\n pieceMode?: PieceMode;\n // Detached steps offered for re-attachment at this insertion point.\n attachSteps?: StepModel[];\n onAttach?: (stepId: string) => void;\n // The button that opened it: clicks there are its own to handle.\n anchor?: RefObject<HTMLElement | null>;\n width?: number;\n height?: number;\n}) {\n const [query, setQuery] = useState(\"\");\n const [tab, setTab] = useState<SourceTab>(\"all\");\n const [chip, setChip] = useState<string | null>(null);\n const [catalog, setCatalog] = useState<CatalogState | null>(null);\n const [selectedId, setSelectedId] = useState<string | null>(null);\n const [paneState, setPane] = useState<\"sources\" | \"entries\">(\"sources\");\n const [entryIndex, setEntryIndex] = useState(-1);\n const [rowIndex, setRowIndex] = useState(-1);\n const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const baseId = useId();\n const listIds = {\n sources: `${baseId}-sources`,\n entries: `${baseId}-entries`,\n results: `${baseId}-results`,\n };\n // Hover only counts once the pointer has moved, so a list scrolling under\n // a still pointer does not steal the selection.\n const pointerMoved = useRef(false);\n const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n const { anchor, onClose } = props;\n\n useEffect(() => {\n const handler = (event: PointerEvent) => {\n const target = event.target as globalThis.Node;\n if (containerRef.current?.contains(target)) return;\n // The opener toggles the picker itself.\n if (anchor?.current?.contains(target)) return;\n onClose();\n };\n // Capture: the canvas pan handler stops the event before it bubbles.\n window.addEventListener(\"pointerdown\", handler, true);\n return () => window.removeEventListener(\"pointerdown\", handler, true);\n }, [anchor, onClose]);\n\n useEffect(() => () => clearTimeout(hoverTimer.current), []);\n\n const anySource = usePieceSource();\n const pieceSource = props.showPieces ? anySource : undefined;\n const [catalogRound, setCatalogRound] = useState(0);\n // Loaded even without the piece list: presets are pinned to its versions.\n // A failed load retries with a fresh fetch, backing off, before it shows.\n useEffect(() => {\n if (!anySource) return;\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const load = (attempt: number) => {\n const request =\n attempt > 0 && anySource.reloadCatalog\n ? anySource.reloadCatalog()\n : anySource.loadCatalog();\n request\n .then((pieces) => {\n // Canvas nodes read logos from the registry, not from this list.\n registerPieceLogos(pieces);\n if (!cancelled) setCatalog({ pieces });\n })\n .catch((error: unknown) => {\n if (cancelled) return;\n if (attempt + 1 < CATALOG_MAX_ATTEMPTS) {\n timer = setTimeout(\n () => load(attempt + 1),\n CATALOG_RETRY_MS * 2 ** attempt,\n );\n return;\n }\n setCatalog({\n pieces: [],\n error: error instanceof Error ? error.message : String(error),\n });\n });\n };\n load(catalogRound > 0 ? 1 : 0);\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [anySource, catalogRound]);\n\n const installed = (name: string) =>\n catalog?.pieces.find((entry) => entry.name === name)?.version;\n const versionNote = useVersionNote(catalog?.pieces);\n const pinned = (preset: BlockPreset) => pinBlock(preset.block, installed);\n const pick = (preset: BlockPreset) => {\n const block = pinned(preset);\n if (!block) return;\n rememberPick(preset);\n props.onPick({ ...preset, block });\n };\n const prefetch = useBlockFormPrefetch();\n\n const mode: PieceMode = props.pieceMode ?? \"actions\";\n const kind = mode === \"triggers\" ? \"trigger\" : \"action\";\n const tokens = queryTokens(query);\n const searching = query.trim().length >= SEARCH_MIN_CHARS;\n const showCatalog = pieceSource !== undefined && tab !== \"core\";\n const tabs: SourceTab[] = pieceSource\n ? [\"all\", \"core\", \"powerhouse\", \"activepieces\"]\n : [\"all\", \"core\", \"powerhouse\"];\n\n // A piece whose every block is a preset is listed as those presets.\n const modePieces = useMemo(() => {\n const presetCounts = new Map<string, number>();\n for (const preset of props.presets) {\n const name = preset.block.pieceName;\n presetCounts.set(name, (presetCounts.get(name) ?? 0) + 1);\n }\n return (catalog?.pieces ?? []).filter((entry) => {\n const count =\n mode === \"triggers\" ? entry.triggerCount : entry.actionCount;\n return count > (presetCounts.get(entry.name) ?? 0);\n });\n }, [catalog, mode, props.presets]);\n const tabPieces = useMemo(\n () => modePieces.filter((entry) => inTab(tab, entry)),\n [modePieces, tab],\n );\n const chips = useMemo(() => orderChips(tabPieces), [tabPieces]);\n // Categories narrow catalogs; All and Core lead with our own lists. One\n // chip has nothing to narrow.\n const showChips =\n showCatalog &&\n (tab === \"activepieces\" || tab === \"powerhouse\") &&\n chips.length > 1;\n const activeChip =\n showChips && chip !== null && chips.includes(chip) ? chip : null;\n\n const searchFilter = useMemo<PieceSearchFilterUi | null>(\n () =>\n showCatalog\n ? {\n kind,\n ...(TAB_SOURCES[tab] ? { sources: TAB_SOURCES[tab] } : {}),\n ...(activeChip\n ? { categories: categoriesOfChip(activeChip, tabPieces) }\n : {}),\n }\n : null,\n [showCatalog, kind, tab, activeChip, tabPieces],\n );\n const search = usePieceSearch(query, searchFilter);\n\n const presetEntry = (preset: BlockPreset): Entry => {\n const block = pinned(preset);\n return {\n key: `${blockKey(preset.block)} ${preset.label}`,\n logo: <BlockLogo block={preset.block} size={ROW_LOGO} />,\n label: preset.label,\n description: preset.description,\n unavailable: block\n ? undefined\n : catalog === null\n ? \"Loading…\"\n : \"Not installed on this runtime\",\n version: shownVersion(preset.block.pieceName, block?.pieceVersion),\n versionNote: versionNote(preset.block.pieceName, block?.pieceVersion),\n pick: () => pick(preset),\n warm: block ? () => prefetch(block) : undefined,\n };\n };\n\n const blockEntry = (\n entry: {\n pieceName: string;\n pieceVersion: string;\n name: string;\n displayName: string;\n description: string;\n unsupported?: string | null;\n strategy?: string | null;\n },\n logo: React.ReactNode,\n ): Entry => {\n const block: BlockRef = {\n pieceName: entry.pieceName,\n pieceVersion: entry.pieceVersion,\n kind,\n name: entry.name,\n };\n return {\n key: blockKey(block),\n logo,\n label: entry.displayName,\n description: entry.description,\n // Visible but inert: picking one would build a step that never runs.\n unavailable: blockUnavailable({ ...entry, kind }),\n version: shownVersion(entry.pieceName, entry.pieceVersion),\n versionNote: versionNote(entry.pieceName, entry.pieceVersion),\n pick: () =>\n pick({\n label: entry.displayName,\n block,\n description: entry.description,\n defaultConfig: {},\n }),\n warm: () => prefetch(block),\n };\n };\n\n // Our own lists, each a source in the left pane. A chip narrows to pieces.\n const lists = (() => {\n if (activeChip !== null) return [];\n const result: Extract<Source, { kind: \"list\" }>[] = [];\n const add = (\n id: ListId,\n title: string,\n subtitle: string,\n logo: (size: number) => React.ReactNode,\n entries: Entry[],\n ) => {\n if (entries.length > 0) {\n result.push({ kind: \"list\", id, title, subtitle, logo, entries });\n }\n };\n // Detached steps first: re-attaching is why the picker opened there.\n if (tab === \"all\") {\n if (props.onAttach) {\n add(\n \"attach\",\n \"Detached steps\",\n \"Re-attach a step at this point\",\n listTile(\"branch\", \"#64748b\"),\n (props.attachSteps ?? []).map((step) => ({\n key: `attach ${step.id}`,\n logo: <BlockLogo block={stepBlock(step)} size={ROW_LOGO} />,\n label: step.name,\n description: `{{steps.${step.key}}} · detached`,\n pick: () => props.onAttach?.(step.id),\n })),\n );\n }\n }\n if (tab === \"all\" || tab === \"core\") {\n add(\n \"core\",\n \"Core\",\n \"Built into the workflow engine\",\n listTile(\"bolt\", \"#2563eb\"),\n props.presets\n .filter((preset) => preset.group !== \"powerhouse\")\n .map(presetEntry),\n );\n }\n if (tab === \"all\" || tab === \"powerhouse\") {\n const reactorPreset = props.presets.find(\n (preset) => preset.group === \"powerhouse\",\n );\n add(\n \"powerhouse\",\n \"Documents\",\n \"Read and change documents on this reactor\",\n (size) =>\n reactorPreset ? (\n <BlockLogo block={reactorPreset.block} size={size} />\n ) : null,\n props.presets\n .filter((preset) => preset.group === \"powerhouse\")\n .map(presetEntry),\n );\n }\n if (tab === \"all\") {\n const recent = recentPicks(kind).filter(\n (preset) =>\n isCoreBlock(preset.block) || installed(preset.block.pieceName),\n );\n add(\n \"recent\",\n \"Recently used\",\n `Your last ${kind}s`,\n listTile(\"clock\", \"#64748b\"),\n recent.map((preset) => {\n const entry = presetEntry(preset);\n // A piece this runtime has since stopped running stays inert.\n const reason = catalog?.pieces.find(\n (piece) => piece.name === preset.block.pieceName,\n )?.unsupported;\n return reason ? { ...entry, unavailable: reason } : entry;\n }),\n );\n }\n return result;\n })();\n\n // Browse: lists then pieces, narrowed by a short query on the client.\n const sources = ((): Source[] => {\n const listSources = lists\n .map((list) => ({\n ...list,\n entries: list.entries.filter((entry) =>\n matchesQuery(`${entry.label} ${entry.description}`, tokens),\n ),\n }))\n .filter((list) => list.entries.length > 0);\n const pieceSources: Source[] = showCatalog\n ? tabPieces\n .filter(\n (entry) =>\n (activeChip === null || chipsOf(entry).has(activeChip)) &&\n matchesQuery(\n `${entry.displayName} ${entry.name} ${entry.description}`,\n tokens,\n ),\n )\n .map((piece) => ({ kind: \"piece\", id: piece.name, piece }))\n : [];\n return [...listSources, ...pieceSources];\n })();\n\n const selected: Source | undefined =\n sources.find((source) => source.id === selectedId) ?? sources.at(0);\n const sourceIndex = selected ? sources.indexOf(selected) : -1;\n const selectedPiece = selected?.kind === \"piece\" ? selected.piece : undefined;\n const loaded = usePieceEntries(selectedPiece, mode);\n const pieceEntries =\n selectedPiece && loaded.entries\n ? loaded.entries.map((entry) =>\n blockEntry(\n entry,\n <LogoFrame\n src={selectedPiece.logoUrl}\n alt={selectedPiece.displayName}\n size={ROW_LOGO}\n />,\n ),\n )\n : null;\n const entries =\n selected?.kind === \"list\" ? selected.entries : (pieceEntries ?? []);\n // The keyboard's block, once the list it points into has loaded.\n const entryAt =\n entries.length === 0 ? -1 : Math.min(entryIndex, entries.length - 1);\n\n // Search: our lists that match, then the server's groups.\n const presetKeys = new Set(\n props.presets.map(\n (preset) => `${preset.block.pieceName} ${preset.block.name}`,\n ),\n );\n const rows: SearchRow[] = [];\n if (searching) {\n for (const source of sources) {\n if (source.kind !== \"list\" || source.id === \"recent\") continue;\n rows.push({ type: \"list\", source });\n for (const entry of source.entries) rows.push({ type: \"entry\", entry });\n }\n const groups =\n search.kind === \"done\"\n ? search.result.pieces\n .map((match) => ({\n ...match,\n // A block a preset offers is listed once, as the preset.\n blocks: match.blocks.filter(\n (hit) => !presetKeys.has(`${hit.pieceName} ${hit.name}`),\n ),\n }))\n .filter((match) => match.blocks.length > 0)\n : [];\n for (const match of groups) {\n rows.push({ type: \"piece\", match });\n const all = groups.length <= 2 || expanded.has(match.pieceName);\n const shown = all ? match.blocks : match.blocks.slice(0, GROUP_BLOCKS);\n const logo = (\n <LogoFrame\n src={match.logoUrl}\n alt={match.displayName}\n size={ROW_LOGO}\n />\n );\n for (const hit of shown) {\n rows.push({ type: \"entry\", entry: blockEntry(hit, logo) });\n }\n if (shown.length < match.blocks.length) {\n rows.push({\n type: \"more\",\n pieceName: match.pieceName,\n hidden: match.blocks.length - shown.length,\n });\n }\n }\n // A source that cannot search, or an index still building, falls back to\n // matching the catalog's piece names.\n const partial =\n !pieceSource?.searchPieces ||\n (search.kind === \"done\" && search.result.status !== \"ready\");\n if (showCatalog && partial) {\n const grouped = new Set(groups.map((match) => match.pieceName));\n // Names that match ahead of descriptions that mention them.\n const named = (source: Source) =>\n source.kind === \"piece\" &&\n matchesQuery(source.piece.displayName, tokens)\n ? 0\n : 1;\n for (const source of [...sources].sort((a, b) => named(a) - named(b))) {\n if (source.kind !== \"piece\" || grouped.has(source.id)) continue;\n rows.push({\n type: \"piece\",\n match: {\n pieceName: source.piece.name,\n pieceVersion: source.piece.version ?? \"\",\n displayName: source.piece.displayName,\n description: source.piece.description,\n logoUrl: source.piece.logoUrl,\n categories: source.piece.categories,\n source: source.piece.source ?? \"activepieces\",\n namedPiece: true,\n blocks: [],\n },\n });\n }\n }\n }\n\n // Until the keyboard moves, the best block: Enter picks it.\n const activeRow =\n rowIndex < 0\n ? rows.findIndex((row) => row.type === \"entry\")\n : Math.min(rowIndex, rows.length - 1);\n\n // One source needs no list to choose from; its blocks fill the picker.\n const twoPane = showCatalog || sources.length > 1;\n const pane = twoPane ? paneState : \"entries\";\n\n const selectSource = (id: string) => {\n setSelectedId(id);\n setPane(\"sources\");\n setEntryIndex(-1);\n };\n const openSource = (id: string) => {\n setSelectedId(id);\n setPane(\"entries\");\n setEntryIndex(0);\n };\n // From a search group to the piece itself, in the browse panes.\n const openPiece = (pieceName: string) => {\n // Not in the browse list (the catalog lacks it): show its blocks here.\n if (!modePieces.some((piece) => piece.name === pieceName)) {\n setExpanded(new Set([...expanded, pieceName]));\n return;\n }\n setQuery(\"\");\n setChip(null);\n if (tab !== \"all\") setTab(\"all\");\n openSource(pieceName);\n inputRef.current?.focus();\n };\n const hoverSource = (id: string) => {\n if (!pointerMoved.current) return;\n clearTimeout(hoverTimer.current);\n hoverTimer.current = setTimeout(() => selectSource(id), HOVER_PREVIEW_MS);\n };\n\n // An empty list (a piece's blocks still loading) keeps the position.\n const step = (index: number, delta: number, count: number) =>\n count === 0 ? index : Math.min(Math.max(index + delta, 0), count - 1);\n\n const onKeyDown = (event: React.KeyboardEvent) => {\n const key = event.key;\n // Tabs and chips handle their own keys; the lists answer the search box.\n if (key !== \"Escape\" && event.target !== inputRef.current) return;\n if (key === \"Escape\") {\n event.stopPropagation();\n if (query !== \"\") setQuery(\"\");\n else if (twoPane && pane === \"entries\" && !searching) setPane(\"sources\");\n else onClose();\n return;\n }\n const delta = key === \"ArrowDown\" ? 1 : key === \"ArrowUp\" ? -1 : 0;\n if (searching) {\n if (delta !== 0) {\n event.preventDefault();\n setRowIndex(Math.max(step(activeRow, delta, rows.length), 0));\n return;\n }\n if (key === \"Enter\") {\n event.preventDefault();\n // Rows answered for an earlier query are not what Enter means.\n if (search.kind === \"done\" && search.stale) return;\n const row = rows.at(activeRow);\n if (!row) return;\n if (row.type === \"entry\") {\n if (row.entry.unavailable === undefined) row.entry.pick();\n } else if (row.type === \"piece\") openPiece(row.match.pieceName);\n else if (row.type === \"list\") openSource(row.source.id);\n else setExpanded(new Set([...expanded, row.pieceName]));\n }\n return;\n }\n // Left and right move the caret while there is text to move it in.\n const sideways = query === \"\";\n if (pane === \"sources\") {\n if (delta !== 0) {\n event.preventDefault();\n const next = sources.at(step(sourceIndex, delta, sources.length));\n if (next) selectSource(next.id);\n } else if (key === \"Enter\" || (sideways && key === \"ArrowRight\")) {\n event.preventDefault();\n if (selected) openSource(selected.id);\n }\n return;\n }\n if (delta !== 0) {\n event.preventDefault();\n setEntryIndex(step(entryIndex, delta, entries.length));\n } else if (sideways && key === \"ArrowLeft\") {\n event.preventDefault();\n setPane(\"sources\");\n } else if (key === \"Enter\") {\n event.preventDefault();\n const entry = entryAt < 0 ? undefined : entries.at(entryAt);\n if (entry && entry.unavailable === undefined) entry.pick();\n }\n };\n\n const width = props.width ?? (pieceSource ? PICKER_SIZE.width : 360);\n const activeList = searching\n ? listIds.results\n : pane === \"entries\"\n ? listIds.entries\n : listIds.sources;\n const activeIndex = searching\n ? activeRow\n : pane === \"entries\"\n ? entryAt\n : sourceIndex;\n const activeOption =\n activeIndex >= 0 ? optionId(activeList, activeIndex) : undefined;\n const searchStatus =\n search.kind === \"loading\" || (search.kind === \"done\" && search.stale) ? (\n <Status>Searching…</Status>\n ) : search.kind === \"error\" ? (\n <Status error>{search.message}</Status>\n ) : search.kind === \"done\" && search.result.status === \"indexing\" ? (\n // Status covers the published catalog only; local pieces are listed.\n <Status>\n Still indexing the catalog: pieces are matched by name until it is\n ready.\n </Status>\n ) : search.kind === \"done\" && search.result.status === \"error\" ? (\n <Status error>\n {search.result.error ?? \"Search failed\"}; pieces are matched by name.\n </Status>\n ) : rows.length === 0 ? (\n <Status>No matching {kind}s</Status>\n ) : null;\n // Fitted to its content where one short list is all there is to show.\n const compact = !twoPane && !searching;\n const height = props.height ?? PICKER_SIZE.height;\n\n return (\n <div\n ref={containerRef}\n className=\"nodrag nopan nowheel flex flex-col overflow-hidden rounded-lg border border-solid border-foreground/10 bg-card shadow-xl\"\n style={compact ? { width, maxHeight: height } : { width, height }}\n onClick={(event) => event.stopPropagation()}\n onKeyDown={onKeyDown}\n onMouseMove={() => {\n pointerMoved.current = true;\n }}\n >\n <div className=\"shrink-0 border-b border-foreground/10\">\n <div className=\"flex items-center gap-2 px-3.5 pt-3 text-muted-foreground\">\n <Icon name=\"search\" size={15} />\n <input\n ref={inputRef}\n autoFocus\n role=\"combobox\"\n aria-expanded\n aria-autocomplete=\"list\"\n aria-label={`Search ${props.title.toLowerCase()}`}\n aria-controls={activeList}\n aria-activedescendant={activeOption}\n // Always focused while open; the caret is its focus indicator.\n className=\"min-w-0 flex-1 bg-transparent py-1 text-sm text-foreground outline-none placeholder:text-muted-foreground\"\n placeholder={\n pieceSource ? `Search pieces and ${kind}s…` : \"Search…\"\n }\n value={query}\n onChange={(event) => {\n setQuery(event.target.value);\n setRowIndex(-1);\n setExpanded(new Set());\n }}\n />\n <span className=\"shrink-0 truncate text-xs\">{props.title}</span>\n </div>\n <div className=\"px-3 pb-2.5 pt-2\">\n <Tabs\n tabs={tabs}\n active={tab}\n onSelect={(next, fromKeyboard) => {\n setTab(next);\n setChip(null);\n setSelectedId(null);\n setPane(\"sources\");\n if (!fromKeyboard) inputRef.current?.focus();\n }}\n />\n </div>\n </div>\n {showChips && catalog && !catalog.error ? (\n <ChipBar>\n {chips.map((label, index) => (\n <Chip\n key={label}\n label={label}\n active={activeChip === label}\n tabStop={activeChip === null ? index === 0 : activeChip === label}\n onClick={(fromKeyboard) => {\n setChip(activeChip === label ? null : label);\n setSelectedId(null);\n if (!fromKeyboard) inputRef.current?.focus();\n }}\n />\n ))}\n </ChipBar>\n ) : null}\n {searching ? (\n <SearchList\n rows={rows}\n tokens={tokens}\n activeIndex={activeRow}\n onActivate={(index) => {\n if (pointerMoved.current) setRowIndex(index);\n }}\n onOpenPiece={openPiece}\n onOpenList={(id) => {\n setQuery(\"\");\n openSource(id);\n }}\n onExpand={(name) => setExpanded(new Set([...expanded, name]))}\n status={searchStatus}\n kind={kind}\n listId={listIds.results}\n resetKey={`${query} ${JSON.stringify(searchFilter)}`}\n stale={search.kind === \"done\" && search.stale}\n />\n ) : (\n <div className=\"flex min-h-0 flex-1\">\n {twoPane ? (\n // A tinted rail, so the open piece can sit raised on it.\n <div className=\"flex w-56 shrink-0 flex-col border-r border-foreground/10 bg-foreground/[0.025]\">\n {catalog?.error ? (\n <div className=\"flex items-center gap-2 px-3 py-2 text-xs text-wf-fail\">\n <span className=\"min-w-0 flex-1\">{catalog.error}</span>\n <button\n type=\"button\"\n className=\"shrink-0 cursor-pointer rounded border border-solid border-foreground/15 bg-card px-1.5 py-0.5 text-foreground hover:border-foreground/25\"\n onClick={() => {\n setCatalog(null);\n setCatalogRound((round) => round + 1);\n }}\n >\n Retry\n </button>\n </div>\n ) : null}\n <VirtualList\n id={listIds.sources}\n label=\"Pieces\"\n resetKey={`${tab} ${activeChip ?? \"\"} ${query}`}\n className=\"flex-1 py-1\"\n items={sources}\n heightOf={sourceHeight}\n keyOf={(source) => `${source.kind}:${source.id}`}\n activeIndex={sourceIndex}\n render={(source, index) => (\n <SourceRow\n source={source}\n tokens={tokens}\n mode={mode}\n active={pane === \"sources\" && index === sourceIndex}\n selected={index === sourceIndex}\n option={{\n list: listIds.sources,\n index,\n size: sources.length,\n }}\n onActivate={() => hoverSource(source.id)}\n onOpen={() => {\n clearTimeout(hoverTimer.current);\n openSource(source.id);\n inputRef.current?.focus();\n }}\n />\n )}\n />\n {showCatalog && catalog === null ? (\n <Status>Loading catalog…</Status>\n ) : sources.length === 0 ? (\n <Status>\n {tab === \"powerhouse\" && tokens.length === 0\n ? \"No registry pieces on this runtime\"\n : \"No matching pieces\"}\n </Status>\n ) : null}\n </div>\n ) : null}\n <EntriesPane\n source={selected}\n mode={mode}\n pieceEntries={pieceEntries}\n pieceError={selected?.kind === \"piece\" ? loaded.error : null}\n tokens={tokens}\n activeIndex={pane === \"entries\" ? entryAt : -1}\n listId={listIds.entries}\n showHeader={twoPane}\n onActivate={(index) => {\n if (!pointerMoved.current) return;\n setPane(\"entries\");\n setEntryIndex(index);\n }}\n />\n </div>\n )}\n </div>\n );\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115],"mappings":";;;;;;;;;AAiBA,IAAI,gBAAgB,cAAc,aAAa;CAC7C,YAAY,QAAQ,SAAS;EAC3B,MAAM;EACN,KAAK,UAAU;EACf,KAAK,UAAU;EACf,KAAK,eAAe;EACpB,KAAK,mBAAmB,gBAAgB;EACxC,KAAK,YAAY;EACjB,KAAK,WAAW,OAAO;CACzB;CACA;CACA,gBAAgB,KAAK;CACrB,4BAA4B,KAAK;CACjC,iBAAiB,KAAK;CACtB;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA,gCAAgC,IAAI,IAAI;CACxC,cAAc;EACZ,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;CACvC;CACA,cAAc;EACZ,IAAI,KAAK,UAAU,SAAS,GAAG;GAC7B,KAAK,cAAc,YAAY,IAAI;GACnC,IAAI,mBAAmB,KAAK,eAAe,KAAK,OAAO,GACrD,KAAK,cAAc;QAEnB,KAAK,aAAa;GAEpB,KAAK,cAAc;EACrB;CACF;CACA,gBAAgB;EACd,IAAI,CAAC,KAAK,aAAa,GACrB,KAAK,QAAQ;CAEjB;CACA,yBAAyB;EACvB,OAAO,cACL,KAAK,eACL,KAAK,SACL,KAAK,QAAQ,kBACf;CACF;CACA,2BAA2B;EACzB,OAAO,cACL,KAAK,eACL,KAAK,SACL,KAAK,QAAQ,oBACf;CACF;CACA,UAAU;EACR,KAAK,4BAA4B,IAAI,IAAI;EACzC,KAAK,mBAAmB;EACxB,KAAK,sBAAsB;EAC3B,KAAK,cAAc,eAAe,IAAI;CACxC;CACA,WAAW,SAAS;EAClB,MAAM,cAAc,KAA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