@usine/server 0.2.1 → 0.4.0
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.
- package/LICENSE +661 -21
- package/README.md +54 -20
- package/dist/backend.d.ts +26 -5
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js +41 -16
- package/dist/backend.js.map +1 -1
- package/dist/backup.d.ts +6 -3
- package/dist/backup.d.ts.map +1 -1
- package/dist/backup.js +26 -8
- package/dist/backup.js.map +1 -1
- package/dist/cli.d.ts +77 -11
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +280 -31
- package/dist/cli.js.map +1 -1
- package/dist/command.d.ts +22 -0
- package/dist/command.d.ts.map +1 -0
- package/dist/command.js +51 -0
- package/dist/command.js.map +1 -0
- package/dist/detach.d.ts +83 -0
- package/dist/detach.d.ts.map +1 -0
- package/dist/detach.js +320 -0
- package/dist/detach.js.map +1 -0
- package/dist/export-run.d.ts +1 -1
- package/dist/export-run.d.ts.map +1 -1
- package/dist/export-run.js +3 -3
- package/dist/export-run.js.map +1 -1
- package/dist/failure-message.d.ts +19 -0
- package/dist/failure-message.d.ts.map +1 -0
- package/dist/failure-message.js +127 -0
- package/dist/failure-message.js.map +1 -0
- package/dist/http.d.ts +14 -5
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +86 -33
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/instance/environment.d.ts +17 -0
- package/dist/instance/environment.d.ts.map +1 -0
- package/dist/instance/environment.js +51 -0
- package/dist/instance/environment.js.map +1 -0
- package/dist/instance/id.d.ts +17 -0
- package/dist/instance/id.d.ts.map +1 -0
- package/dist/instance/id.js +35 -0
- package/dist/instance/id.js.map +1 -0
- package/dist/instance/lock.d.ts +27 -0
- package/dist/instance/lock.d.ts.map +1 -0
- package/dist/instance/lock.js +127 -0
- package/dist/instance/lock.js.map +1 -0
- package/dist/instance/manifest.d.ts +52 -0
- package/dist/instance/manifest.d.ts.map +1 -0
- package/dist/instance/manifest.js +131 -0
- package/dist/instance/manifest.js.map +1 -0
- package/dist/instance/operator-api.d.ts +30 -0
- package/dist/instance/operator-api.d.ts.map +1 -0
- package/dist/instance/operator-api.js +47 -0
- package/dist/instance/operator-api.js.map +1 -0
- package/dist/instance/ports.d.ts +23 -0
- package/dist/instance/ports.d.ts.map +1 -0
- package/dist/instance/ports.js +81 -0
- package/dist/instance/ports.js.map +1 -0
- package/dist/instance/record.d.ts +82 -0
- package/dist/instance/record.d.ts.map +1 -0
- package/dist/instance/record.js +116 -0
- package/dist/instance/record.js.map +1 -0
- package/dist/instance/state.d.ts +45 -0
- package/dist/instance/state.d.ts.map +1 -0
- package/dist/instance/state.js +79 -0
- package/dist/instance/state.js.map +1 -0
- package/dist/instance/systemd.d.ts +36 -0
- package/dist/instance/systemd.d.ts.map +1 -0
- package/dist/instance/systemd.js +61 -0
- package/dist/instance/systemd.js.map +1 -0
- package/dist/logger.d.ts +3 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +27 -0
- package/dist/logger.js.map +1 -0
- package/dist/main.js +38 -18
- package/dist/main.js.map +1 -1
- package/dist/registry.d.ts +20 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +37 -0
- package/dist/registry.js.map +1 -0
- package/dist/reload-signal.d.ts +8 -0
- package/dist/reload-signal.d.ts.map +1 -0
- package/dist/reload-signal.js +21 -0
- package/dist/reload-signal.js.map +1 -0
- package/dist/restart.d.ts +19 -0
- package/dist/restart.d.ts.map +1 -0
- package/dist/restart.js +105 -0
- package/dist/restart.js.map +1 -0
- package/dist/shutdown.d.ts +5 -2
- package/dist/shutdown.d.ts.map +1 -1
- package/dist/shutdown.js +11 -5
- package/dist/shutdown.js.map +1 -1
- package/dist/status.d.ts +12 -0
- package/dist/status.d.ts.map +1 -0
- package/dist/status.js +99 -0
- package/dist/status.js.map +1 -0
- package/dist/stop.d.ts +81 -0
- package/dist/stop.d.ts.map +1 -0
- package/dist/stop.js +195 -0
- package/dist/stop.js.map +1 -0
- package/dist/system-sleep.d.ts +9 -0
- package/dist/system-sleep.d.ts.map +1 -0
- package/dist/system-sleep.js +42 -0
- package/dist/system-sleep.js.map +1 -0
- package/dist/tracing.d.ts +22 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +61 -0
- package/dist/tracing.js.map +1 -0
- package/dist/up.d.ts +2 -2
- package/dist/up.d.ts.map +1 -1
- package/dist/up.js +62 -24
- package/dist/up.js.map +1 -1
- package/dist/upgrade.d.ts +58 -0
- package/dist/upgrade.d.ts.map +1 -0
- package/dist/upgrade.js +237 -0
- package/dist/upgrade.js.map +1 -0
- package/dist/web/assets/CompositeItem-DU6IyNMY.js +1 -0
- package/dist/web/assets/ToolbarRootContext-Cytu6o2e.js +1 -0
- package/dist/web/assets/X.es-B7iqdxa_.js +1 -0
- package/dist/web/assets/_agent-BVKD5odk.js +1 -0
- package/dist/web/assets/_loop-BFLzamuo.js +1 -0
- package/dist/web/assets/_name-Bh4AQ9sR.js +6 -0
- package/dist/web/assets/_name-CMVsmWzq.js +1 -0
- package/dist/web/assets/_name-DCkgEma_.js +1 -0
- package/dist/web/assets/_name-Ds_pWi15.js +1 -0
- package/dist/web/assets/_number-B9aYwvcQ.js +1 -0
- package/dist/web/assets/_run-BZWt47QS.js +8 -0
- package/dist/web/assets/_worker-Dgfufm5p.js +1 -0
- package/dist/web/assets/action-rCd1FeAz.js +1 -0
- package/dist/web/assets/agents-Drbg6qpH.js +1 -0
- package/dist/web/assets/agents-_6-dEjrY.js +1 -0
- package/dist/web/assets/button-DVWXde__.js +1 -0
- package/dist/web/assets/collapsible-IOhZV1qg.js +1 -0
- package/dist/web/assets/core-wi-Hu_JV.js +12 -0
- package/dist/web/assets/drawer-BiqnR_8i.js +1 -0
- package/dist/web/assets/dropdown-menu-C9D1kRkO.js +1 -0
- package/dist/web/assets/edit-and-retry-BgOR6mvP.js +1 -0
- package/dist/web/assets/engine-javascript-D-6se_EF.js +141 -0
- package/dist/web/assets/error-alert-9tKpTE3v.js +1 -0
- package/dist/web/assets/file-error-SjG2jLJ9.js +1 -0
- package/dist/web/assets/fill-cell-ClM88KFD.js +1 -0
- package/dist/web/assets/heading-lX1a1LNN.js +1 -0
- package/dist/web/assets/index-BymNZU1Q.js +10 -0
- package/dist/web/assets/index-Dyjfp3ET.css +2 -0
- package/dist/web/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
- package/dist/web/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
- package/dist/web/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
- package/dist/web/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
- package/dist/web/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
- package/dist/web/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/assets/label-badge-aIGT1Bry.js +1 -0
- package/dist/web/assets/list-v8WJp2Eq.js +1 -0
- package/dist/web/assets/loops-BFoFf_og.js +1 -0
- package/dist/web/assets/mark-CC3RwMy_.js +1 -0
- package/dist/web/assets/markdown-BnyfnuCL.js +29 -0
- package/dist/web/assets/matchContext-BquevSJS.js +2 -0
- package/dist/web/assets/model-BerBT6R0.js +1 -0
- package/dist/web/assets/moves-Dg9sshX5.js +1 -0
- package/dist/web/assets/overview-C_tFKGZ8.js +1 -0
- package/dist/web/assets/page-DWnGi6wA.js +301 -0
- package/dist/web/assets/project-not-found-CodaBVdu.js +1 -0
- package/dist/web/assets/pull-request-marks-DE00nqGW.js +1 -0
- package/dist/web/assets/queries-B1SHA_r4.js +1 -0
- package/dist/web/assets/reload-Dsl0zjJ7.js +1 -0
- package/dist/web/assets/repositories-BdxmD192.js +1 -0
- package/dist/web/assets/repositories-D4wYJfa_.js +1 -0
- package/dist/web/assets/route-B_gphTYG.js +1 -0
- package/dist/web/assets/route-Cc7dKnn5.js +1 -0
- package/dist/web/assets/routes-BLy5TGH_.js +65 -0
- package/dist/web/assets/run-again-BTKagSXR.js +1 -0
- package/dist/web/assets/section-B3pWIIBa.js +1 -0
- package/dist/web/assets/section-CD-MB5r3.js +1 -0
- package/dist/web/assets/section-Id99HktI.js +1 -0
- package/dist/web/assets/settings-YrDysQXW.js +1 -0
- package/dist/web/assets/slots-BraHmbNr.js +1 -0
- package/dist/web/assets/status-badge-DnvNo1tG.js +1 -0
- package/dist/web/assets/strings-CW2XaR5f.js +1 -0
- package/dist/web/assets/table-BjyI4fVI.js +1 -0
- package/dist/web/assets/tasks-DCL8kLmD.js +1 -0
- package/dist/web/assets/transcript-sxRJzx6t.js +5 -0
- package/dist/web/assets/usage-CLQJdX9-.js +1 -0
- package/dist/web/assets/use-now-0P8TUXeg.js +1 -0
- package/dist/web/assets/useAnchoredPopupScrollLock-CQ83Wy-r.js +1 -0
- package/dist/web/assets/useNavigate-BW1WdocJ.js +1 -0
- package/dist/web/assets/usePositioner-rNCxnHO-.js +1 -0
- package/dist/web/assets/useTimeout-_TcdZXP6.js +1 -0
- package/dist/web/assets/with-selector-DoElmmtd.js +1 -0
- package/dist/web/assets/workers-BH5CBOR3.js +1 -0
- package/dist/web/index.html +16 -10
- package/package.json +17 -12
- package/dist/web/assets/_name-DdyMEUN6.js +0 -6
- package/dist/web/assets/_name-eoobiMh0.js +0 -1
- package/dist/web/assets/_name-pUxlKZt5.js +0 -1
- package/dist/web/assets/badge-t7m0Vk1K.js +0 -146
- package/dist/web/assets/button-BoOukj77.js +0 -1
- package/dist/web/assets/core-CLXRiB63.js +0 -12
- package/dist/web/assets/empty-DbVYU7bi.js +0 -1
- package/dist/web/assets/engine-javascript-h-x4hGa4.js +0 -141
- package/dist/web/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/dist/web/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/dist/web/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/dist/web/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/dist/web/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/dist/web/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/dist/web/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/dist/web/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/dist/web/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/dist/web/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/dist/web/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/dist/web/assets/index-CVBBoW6r.css +0 -2
- package/dist/web/assets/index-CsW8KcJW.js +0 -10
- package/dist/web/assets/loops-DghpuoiG.js +0 -1
- package/dist/web/assets/operator-copy-DIsVXn17.js +0 -1
- package/dist/web/assets/overview-DmCIVPwN.js +0 -1
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +0 -1
- package/dist/web/assets/routes-BDyP7vCr.js +0 -1
- package/dist/web/assets/run-drawer-B-xhTXe4.js +0 -157
- package/dist/web/assets/status-badge-yblcElE0.js +0 -1
- package/dist/web/assets/table-B8cLYNvq.js +0 -1
- package/dist/web/assets/useCompositeItem-HmBmWxUW.js +0 -1
- package/dist/web/assets/with-selector-N6m4X0X_.js +0 -1
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import{A as e,D as t,E as n}from"./matchContext-BquevSJS.js";import{D as r}from"./button-DVWXde__.js";var i=e(t(),1),a=n(),o=i.createContext(void 0),s=e=>{let t=i.useContext(o);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},c=({client:e,children:t})=>(i.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,a.jsx)(o.Provider,{value:e,children:t})),l={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},u=new class{#e=l;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function d(e){setTimeout(e,0)}var f=typeof window>`u`||`Deno`in globalThis;function p(){}function m(e,t){return typeof e==`function`?e(t):e}function h(e){return typeof e==`number`&&e>=0&&e!==1/0}function g(e,t){return Math.max(e+(t||0)-Date.now(),0)}function _(e,t){return typeof e==`function`?e(t):e}function v(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==te(o,t.options))return!1}else if(!re(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function ee(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(ne(t.options.mutationKey)!==ne(a))return!1}else if(!re(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function te(e,t){return(t?.queryKeyHashFn||ne)(e)}function ne(e){return JSON.stringify(e,(e,t)=>ce(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function re(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!re(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!re(e[r],t[r]))return!1;return!0}return!1}var ie=Object.prototype.hasOwnProperty;function ae(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=se(e)&&se(t);if(!r&&!(ce(e)&&ce(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:ie.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=ae(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function oe(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function se(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ce(e){if(!le(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!le(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function le(e){return Object.prototype.toString.call(e)===`[object Object]`}function ue(e){return new Promise(t=>{u.setTimeout(t,e)})}function de(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:ae(e,t)}function fe(e){return e}function pe(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function me(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var he=Symbol();function ge(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===he?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function _e(e,t){return typeof e==`function`?e(...t):!!e}function ve(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var ye=()=>f,be=()=>ye(),xe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Se=new class extends xe{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Ce=d;function we(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Ce,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Te=we(),Ee=new class extends xe{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function De(e){return Math.min(1e3*2**e,3e4)}function Oe(e){return(e??`online`)!==`online`||Ee.isOnline()}var ke=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Ae(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(p);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ke(t);g(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Se.isFocused()&&(e.networkMode===`always`||Ee.isOnline())&&e.canRun(),m=()=>Oe(e.networkMode)&&e.canRun(),h=e=>{c()||(r?.(),i=`resolved`,a(e))},g=e=>{c()||(r?.(),i=`rejected`,o(e))},_=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),v=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(h).catch(r=>{if(c())return;let i=e.retry??(be()?0:3),a=e.retryDelay??De,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?g(r):(n++,e.onFail?.(n,r),ue(o).then(()=>f()?void 0:_(f)).then(()=>{t?g(r):v()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:m,start:()=>(m()?v():_(m).then(v),s)}}var je=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),h(this.gcTime)&&(this.#e=u.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(be()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(u.clearTimeout(this.#e),this.#e=void 0)}};function Me(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{ve(e,()=>t.signal,()=>n=!0)},u=ge(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?me:pe;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Pe:Ne,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:Ne(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Ne(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Pe(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Fe=class extends je{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Re(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Re(this.options);e.data!==void 0&&(this.setState(Le(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=de(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(p).catch(p):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>_(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===he||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>_(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!g(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=ge(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Me(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Ae({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ke&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ke){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Ie(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Le(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Te.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Ie(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Oe(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Le(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Re(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var ze=class extends xe{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ve(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return He(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return He(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof _(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!oe(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Ue(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||_(this.options.enabled,this.#t)!==_(t.enabled,this.#t)||_(this.options.staleTime,this.#t)!==_(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||_(this.options.enabled,this.#t)!==_(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return oe(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(p)),t}#h(e){return!be()&&_(this.options.enabled,this.#t)!==!1&&h(e)}#g(){this.#b();let e=_(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=g(this.#r.dataUpdatedAt,e)+1;this.#u=u.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return _(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=u.setInterval(()=>{(this.options.refetchIntervalInBackground||Se.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(u.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(u.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Ve(e,t),o=i&&Ue(e,n,t,r);(a||o)&&(l={...l,...Ie(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=de(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=de(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,v=m===`pending`,ee=m===`error`,te=v&&g,ne=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:v,isSuccess:m===`success`,isError:ee,isInitialLoading:te,isLoading:te,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!v,isLoadingError:ee&&!ne,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:ee&&ne,isStale:We(e,t),refetch:this.refetch,isEnabled:_(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),oe(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Te.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function Be(e,t){return _(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||_(t.retryOnMount,e)!==!1)}function Ve(e,t){return Be(e,t)||e.state.data!==void 0&&He(e,t,t.refetchOnMount)}function He(e,t,n){if(_(t.enabled,e)!==!1&&_(t.staleTime,e)!==`static`){let r=_(n,e);return r===`always`||r!==!1&&We(e,t)}return!1}function Ue(e,t,n,r){return(e!==t||_(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&We(e,n)}function We(e,t){return _(t.enabled,e)!==!1&&e.isStaleByTime(_(t.staleTime,e))}var Ge=i.createContext(!1),Ke=()=>i.useContext(Ge);Ge.Provider;function qe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Je=i.createContext(qe()),Ye=()=>i.useContext(Je),Xe=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?_e(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ze=e=>{i.useEffect(()=>{e.clearReset()},[e])},Qe=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||_e(n,[e.error,r])),$e=(e,t)=>t.state.data===void 0,et=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},tt=(e,t)=>e?.suspense&&t.isPending,nt=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function rt(e,t,n){let r=Ke(),a=Ye(),o=s(n),c=o.defaultQueryOptions(e),l=o.getQueryCache().get(c.queryHash),u=e.subscribed!==!1;c._optimisticResults=r?`isRestoring`:u?`optimistic`:void 0,et(c),Xe(c,a,l),Ze(a);let[d]=i.useState(()=>new t(o,c)),f=d.getOptimisticResult(c),m=!r&&u;if(i.useSyncExternalStore(i.useCallback(e=>{let t=m?d.subscribe(Te.batchCalls(e)):p;return d.updateResult(),t},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),i.useEffect(()=>{d.setOptions(c)},[c,d]),tt(c,f))throw nt(c,d,a);if(Qe({result:f,errorResetBoundary:a,throwOnError:c.throwOnError,query:l,suspense:c.suspense}))throw f.error;return c.notifyOnChangeProps?f:d.trackResult(f)}function it(e,t){return rt({...e,enabled:!0,suspense:!0,throwOnError:$e,placeholderData:void 0},ze,t)}var at=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}},ot={pipe(){return at(this,arguments)}},st=function(){function e(){}return e.prototype=ot,e}(),y=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},ct=e=>e,lt=e=>()=>e,ut=lt(!0),dt=lt(!1),ft=lt(null),pt=lt(void 0),mt=pt;function ht(e,...t){return at(e,t)}function gt(e){let t=new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function _t(e){let t=new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i!==n&&t.set(i,i),i}}var vt=e=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;e instanceof Error&&t.delete(`stack`);let n=Object.getPrototypeOf(e),r=n;for(;r!==null&&r!==Object.prototype;){let e=Reflect.ownKeys(r);for(let n=0;n<e.length;n++)t.add(e[n]);r=Object.getPrototypeOf(r)}return t.has(`constructor`)&&typeof e.constructor==`function`&&n===e.constructor.prototype&&t.delete(`constructor`),t},yt=new WeakSet,bt=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),xt=0,St=()=>{xt++};function Ct(e){return typeof e==`string`}function wt(e){return typeof e==`number`}function Tt(e){return typeof e==`boolean`}function Et(e){return typeof e==`bigint`}function Dt(e){return typeof e==`symbol`}function Ot(e){return Ct(e)||wt(e)||Dt(e)}function kt(e){return typeof e==`function`}function At(e){return e!==void 0}function jt(e){return e!=null}function Mt(e){return!1}function Nt(e){return!0}function Pt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ft(e){return typeof e==`object`&&!!e||kt(e)}var It=y(2,(e,t)=>Ft(e)&&t in e),Lt=y(2,(e,t)=>It(e,`_tag`)&&e._tag===t);function Rt(e){return e instanceof Error}function zt(e){return It(e,Symbol.iterator)||Ct(e)}var Bt=`~effect/Hash`,Vt=e=>{switch(typeof e){case`number`:return qt(e);case`bigint`:return Jt(e.toString(10));case`string`:return Jt(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?Jt(`Invalid Date`):Jt(e.toISOString());if(e instanceof RegExp)return Jt(e.toString());{if(yt.has(e))return Ht(e);let t=rn.get(e);if(t!==void 0)return t;if(an.has(e))return St(),Jt(`[Circular]`);an.add(e);let n=xt,r;try{r=`~effect/Hash`in e?e[Bt]():typeof e==`function`?Ht(e):e instanceof DataView?Qt(bt(e)):Array.isArray(e)||ArrayBuffer.isView(e)?Qt(e):e instanceof Map?$t(e):e instanceof Set?tn(e):Xt(e)}finally{an.delete(e)}return n===xt&&rn.set(e,r),r}}return Gt(Ut(Jt(String(e))))},Ht=e=>(nn.has(e)||nn.set(e,Gt(Math.random()*4294967296|0)),nn.get(e)),Ut=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),Wt=y(2,(e,t)=>Ut(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Gt=e=>e&3221225471|e>>>1&1073741824,Kt=new DataView(new ArrayBuffer(8)),qt=e=>{let t=e|0;return t===e?Gt(t):(Kt.setFloat64(0,e===e?e:NaN),Gt(Wt(Kt.getInt32(0),Kt.getInt32(4))))},Jt=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return Gt(t)},Yt=(e,t)=>{let n=12289;for(let r of t)n^=Wt(Vt(r),Vt(e[r]));return Gt(n)},Xt=e=>Yt(e,vt(e)),Zt=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return Gt(r)},Qt=e=>{let t=6151;for(let n of e)t=Wt(t,Vt(n));return Gt(t)},$t=Zt(Jt(`Map`),([e,t])=>Wt(Vt(e),Vt(t))),en=Jt(`Set`),tn=Zt(en,e=>Wt(en,Vt(e))),nn=new WeakMap,rn=new WeakMap,an=new WeakSet,on=`~effect/Equal`;function sn(){return arguments.length===1?e=>cn(e,arguments[0]):cn(arguments[0],arguments[1])}function cn(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||yt.has(e)||yt.has(t)?!1:ln(e,t):!1}function ln(e,t){let n=dn.length;for(let r=n;r-->0;)if(dn[r]===e&&fn[r]===t)return!0;if(n)return un(e,t);let r=pn.get(e);r||pn.set(e,r=new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=un(e,t)),i}function un(e,t){dn.push(e),fn.push(t);try{return mn(e,t)}finally{dn.pop(),fn.pop()}}var dn=[],fn=[],pn=new WeakMap;function mn(e,t){if(Vt(e)!==Vt(t))return!1;if(e instanceof Date){if(!(t instanceof Date))return!1;let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=xn(e);if(n!==xn(t)||typeof e==`function`&&!n)return!1;if(n)return e[on](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:hn(e,t);if(ArrayBuffer.isView(e)){let n=e instanceof DataView;return!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||n!==t instanceof DataView?!1:n?gn(bt(e),bt(t)):gn(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:vn(e,t,yn,bn):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:vn(e,t,Vt,cn):_n(e,t)}function hn(e,t){for(let n=0;n<e.length;n++)if(!cn(e[n],t[n]))return!1;return!0}function gn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function _n(e,t){let n=vt(e),r=vt(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!cn(e[i],t[i]))return!1;return!0}function vn(e,t,n,r){let i=new Map,a=0;for(let e of t){let t=n(e),r=i.get(t);r?r.push(e):i.set(t,[e]),a++}outer:for(let t of e){let e=i.get(n(t));if(e){for(let n=0;n<e.length;n++)if(r(t,e[n])){e[n]=e[e.length-1],e.pop(),a--;continue outer}}return!1}return a===0}var yn=e=>Vt(e[0]),bn=(e,t)=>cn(e[0],t[0])&&cn(e[1],t[1]),xn=e=>It(e,on),Sn=()=>sn,Cn=Symbol.for(`~effect/Redactable`),wn=e=>It(e,Cn);function Tn(e){return wn(e)?En(e):e}function En(e){return e[Cn](globalThis[`~effect/Fiber/currentFiber`]?.context??kn)}var Dn=`~effect/Fiber/currentFiber`,On=new Map,kn={"~effect/Context":{},base:On,depth:0,mapUnsafe:On,pipe(){return at(this,arguments)}};function An(e,t){let n=t?.space??0,r=new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,t=0){try{return l(e,t)}catch{return(typeof e==`object`&&e||typeof e==`function`)&&r.delete(e),`[inspection threw]`}}function l(e,n=0){if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return jn;r.add(e);let l;if(Cn in e)l=c(En(e),n);else if(Array.isArray(e))l=!i||e.length<=1?`[${e.map(e=>c(e,n)).join(`,`)}]`:`[\n${a(n+1)}${e.map(e=>c(e,n+1)).join(`,
|
|
2
|
+
`+a(n+1))}\n${a(n)}]`;else if(e instanceof Date)l=Pn(e);else if(!t?.ignoreToString&&It(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Fn(e);l=e instanceof Error&&e.cause!==void 0?`${t} (cause: ${c(e.cause,n)})`:t}else if(Symbol.iterator in e)l=`${e.constructor.name}(${c(Array.from(e),n)})`;else{let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${Mn(t)}:${c(In(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Mn(t)}: ${c(In(e,t),n+1)}`).join(`,
|
|
3
|
+
`)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}var jn=`[Circular]`;function Mn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function Nn(e){return e.map(e=>`[${Mn(e)}]`).join(``)}function Pn(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Fn(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function In(e,t){try{return e[t]}catch{return`[property access threw]`}}function Ln(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=It(r,Cn)?Tn(r):Tn(t);if(typeof i==`bigint`)return An(i);if(typeof i!=`object`||!i)return i;let a=i instanceof Error&&!It(i,`toJSON`)?{...i,name:i.name,message:i.message}:i;for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return;if(n.push(i),a!==i&&n.push(a),!Rn(a)||zn(a))return a;let o=new Proxy(a,{get(e,t){let n=Reflect.get(e,t,e);return Object.getOwnPropertyDescriptor(e,t)?.get===void 0?n:Tn(n)}});return n.push(o),o},t?.space)??`null`}function Rn(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function zn(e){for(let t of[Number.prototype.valueOf,Boolean.prototype.valueOf,String.prototype.valueOf])try{return Reflect.apply(t,e,[]),!0}catch{}return!1}var Bn=Symbol.for(`nodejs.util.inspect.custom`),Vn=e=>{try{return e=Tn(e),It(e,`toJSON`)&&kt(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(Vn):e}catch{return`[toJSON threw]`}},Hn=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Ln(e,{space:t}):An(e,{space:t})}catch{return String(e)}},Un={toJSON(){return Vn(this)},[Bn](){return this.toJSON()},toString(){return An(this.toJSON())}},Wn=class{[Bn](){return this.toJSON()}toString(){return An(this.toJSON())}},Gn=(()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),Kn=()=>Error.stackTraceLimit,qn=e=>{Gn&&(Error.stackTraceLimit=e)},Jn=class{constructor(e){this.value=e,this.done=!1}next(e){return this.done?(this.value=e,this):(this.done=!0,{value:this.value,done:!1})}},Yn=(()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=Kn();if(r===0)return n[e];qn(2);let i=t[e](()=>Error());return qn(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function Xn(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function Zn(e,t){if(!Object.hasOwn(t,`__proto__`))Object.assign(e,t);else for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&Xn(e,n,t[n])}var Qn=`~effect/Effect`,$n=`~effect/Exit`,er={_A:ct,_E:ct,_R:ct},tr=`${Qn}/identifier`,nr=`${Qn}/args`,rr=`${Qn}/evaluate`,ir=`${Qn}/successCont`,ar=`${Qn}/failureCont`,or=`${Qn}/ensureCont`,sr=Symbol.for(`effect/Effect/Yield`),cr={pipe(){return at(this,arguments)},toJSON(){return{...this}},toString(){return An(this.toJSON(),{ignoreToString:!0,space:2})},[Bn](){return this.toJSON()}},lr={[Qn]:er,...cr,[Symbol.iterator](){return new Jn(this)},toJSON(){return{_id:`Effect`,op:this[tr],...`~effect/Effect/args`in this?{args:this[nr]}:void 0}}},ur=e=>It(e,Qn),dr=e=>It(e,$n),fr=`~effect/Cause`,pr=`~effect/Cause/Reason`,mr=e=>It(e,fr),hr=e=>It(e,pr),gr=class{constructor(e){this[fr]=fr,this.reasons=e}pipe(){return at(this,arguments)}toJSON(){return{_id:`Cause`,reasons:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${An(this.reasons)})`}[Bn](){return this.toJSON()}[on](e){return mr(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>sn(t,e.reasons[n]))}[Bt](){return Qt(this.reasons)}},_r=new WeakMap,vr=class{[pr];annotations;_tag;constructor(e,t,n){if(this[pr]=pr,this._tag=e,t!==yr&&typeof n==`object`&&n&&t.size>0){let e=_r.get(n);e&&(t=new Map([...e,...t])),_r.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return at(this,arguments)}toString(){return An(this)}[Bn](){return this.toString()}},yr=new Map,br=class extends vr{constructor(e,t=yr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${An(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[on](e){return Ar(e)&&sn(this.error,e.error)&&sn(this.annotations,e.annotations)}[Bt](){return Wt(Jt(this._tag))(Wt(Vt(this.error))(Vt(this.annotations)))}},xr=e=>new gr(e),Sr=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let e=Vt(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>sn(e,i)))continue;else t.push(i);r.push(i)}return r},Cr=y(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new gr(Sr(e.reasons,t.reasons));return sn(e,n)?e:n}),wr=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)Mr(e)&&!n.some(t=>Mr(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new gr(n)},Tr=new gr([]),Er=e=>new gr([new br(e)]),Dr=class extends vr{constructor(e,t=yr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${An(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[on](e){return jr(e)&&sn(this.defect,e.defect)&&sn(this.annotations,e.annotations)}[Bt](){return Wt(Jt(this._tag))(Wt(Vt(this.defect))(Vt(this.annotations)))}},Or=e=>new gr([new Dr(e)]),kr=y(e=>mr(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new gr(e.reasons.map(e=>e.annotate(t,n)))),Ar=e=>e._tag===`Fail`,jr=e=>e._tag===`Die`,Mr=e=>e._tag===`Interrupt`;function Nr(e){return Hr(`Effect.evaluate: Not implemented`)}var Pr=e=>({...lr,[tr]:e.op,[rr]:e[`~effect/Effect/evaluate`]??Nr,[ir]:e[ir],[ar]:e[ar],[or]:e[or]}),Fr=e=>{let t=Pr(e),n=function(e){this[nr]=e};return n.prototype=t,function(e){return new n(e)}},Ir=e=>{let t={[$n]:$n,_tag:e.op,get[e.prop](){return this[nr]},...Pr(e),toString(){return`${e.op}(${An(this[nr])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[nr]}},[on](e){return dr(e)&&e._tag===this._tag&&sn(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[Bt](){return Wt(Jt(e.op),Vt(this[nr]))}},n=function(e){this[nr]=e};return n.prototype=t,function(e){return new n(e)}},Lr=Ir({op:`Success`,prop:`value`,[rr](e){let t=e.getCont(ir);return t?t[ir](this[nr],e,this):e.yieldWith(this)}}),Rr={key:`effect/Cause/StackTrace`},zr={key:`effect/Cause/InterruptorStackTrace`},Br=Ir({op:`Failure`,prop:`cause`,[rr](e){let t=this[nr],n=!1;e.cache.stackFrame&&(t=kr(t,{mapUnsafe:new Map([[Rr.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(ar),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=tr in r,r=e.getCont(ar);a&&(t=xr(t.reasons.filter(e=>e._tag!==`Fail`))),t=wr(t,i),n=!0}return r?r[ar](t,e,n?void 0:this):e.yieldWith(n?Br(t):this)}}),Vr=e=>Br(Er(e)),Hr=e=>Br(Or(e)),Ur=Fr({op:`WithFiber`,[rr](e){return this[nr](e)}}),Wr=function(){class e extends globalThis.Error{}let t=Pr({op:`YieldableError`,[rr](){return Vr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Gr=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends Wr{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(Zn(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),Kr=e=>{class t extends Gr{_tag=e}return t.prototype.name=e,t},qr=`~effect/Cause/NoSuchElementError`,Jr=class extends Kr(`NoSuchElementError`){[qr]=qr;constructor(e){super({message:e})}},Yr=`~effect/Cause/Done`,Xr=e=>It(e,Yr),Zr={[Yr]:Yr,_tag:`Done`,value:void 0},Qr=e=>e===void 0?Zr:{[Yr]:Yr,_tag:`Done`,value:e},$r=Vr(Zr),ei=e=>e===void 0?$r:Vr(Qr(e)),ti=e=>Pr({op:e.label,[rr]:e.evaluate}),ni=e=>(t,n)=>t===n||e(t,n),ri=(e,t)=>e===t,ii=()=>ri;function ai(e){return ni((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e[r](t[r],n[r]))return!1;return!0})}function oi(e){return ni((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0})}var si=`~effect/Option`,ci={[si]:{_A:e=>e},...cr,[Symbol.iterator](){return new Jn(this)}},li=Object.defineProperty(Object.assign(Object.create(ci),{_tag:`Some`,_op:`Some`,[on](e){return fi(e)&&mi(e)&&sn(this.value,e.value)},[Bt](){return Wt(Vt(this._tag))(Vt(this.value))},toString(){return`some(${An(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:Vn(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),ui=Vt(`None`),di=Object.assign(Object.create(ci),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[on](e){return fi(e)&&pi(e)},[Bt](){return ui},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),fi=e=>It(e,si),pi=e=>e._tag===`None`,mi=e=>e._tag===`Some`,hi=Object.create(di),gi=function(e){this.value=e};gi.prototype=li;var _i=e=>new gi(e),vi=`~effect/Result`,yi={[vi]:{_A:e=>e,_E:e=>e},...cr,[Symbol.iterator](){return new Jn(this)}},bi=Object.assign(Object.create(yi),{_tag:`Success`,_op:`Success`,[on](e){return Si(e)&&wi(e)&&sn(this.success,e.success)},[Bt](){return Wt(Vt(this._tag))(Vt(this.success))},toString(){return`success(${An(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:Vn(this.success)}}}),xi=Object.assign(Object.create(yi),{_tag:`Failure`,_op:`Failure`,[on](e){return Si(e)&&Ci(e)&&sn(this.failure,e.failure)},[Bt](){return Wt(Vt(this._tag))(Vt(this.failure))},toString(){return`failure(${An(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:Vn(this.failure)}}}),Si=e=>It(e,vi),Ci=e=>e._tag===`Failure`,wi=e=>e._tag===`Success`,Ti=function(e){this.failure=e};Ti.prototype=xi;var Ei=e=>new Ti(e),Di=function(e){this.success=e};Di.prototype=bi;var Oi=e=>new Di(e),ki=y(2,(e,t)=>pi(e)?Ei(t()):Oi(e.value));function Ai(e){return(t,n)=>t===n?0:e(t,n)}var ji=Ai((e,t)=>e<t?-1:1),Mi=Ai((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e<t?-1:1);function Ni(e){return Ai((t,n)=>e(n,t))}function Pi(e){let t=Array.from(e);return Ai((e,n)=>{let r=0;for(let i of t)if(r=i(e,n),r!==0)return r;return r})}var Fi=y(2,(e,t)=>Ai((n,r)=>e(t(n),t(r)))),Ii=e=>y(2,(t,n)=>e(t,n)===-1),Li=e=>y(2,(t,n)=>e(t,n)===1),Ri=e=>y(2,(t,n)=>e(t,n)!==1),zi=e=>y(2,(t,n)=>e(t,n)!==-1),b=()=>hi,x=_i,Bi=fi,S=pi,C=mi,Vi=y(2,(e,{onNone:t,onSome:n})=>S(e)?t():n(e.value)),Hi=y(2,(e,t)=>S(e)?t():e.value),Ui=y(2,(e,t)=>S(e)?t():e),Wi=e=>{let t=b();for(t of e)if(C(t))return t;return t},Gi=e=>e==null?b():x(e),Ki=e=>e===void 0?b():x(e),qi=e=>e===null?b():x(e),w=Hi(ft),Ji=Hi(pt),Yi=e=>(...t)=>{try{return x(e(...t))}catch{return b()}},Xi=y(2,(e,t)=>{if(C(e))return e.value;throw t()}),Zi=y(2,(e,t)=>S(e)?b():x(t(e.value))),Qi=y(2,(e,t)=>S(e)?b():t(e.value)),$i=Qi(ct),ea=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(S(n))return b();t.push(n.value)}return x(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(S(r))return b();Xn(t,n,r.value)}return x(t)},ta=e=>S(e)?[]:[e.value],na=y(2,(e,t)=>S(e)?b():t(e.value)?x(e.value):b()),ra=y(2,(e,t)=>t(e)?x(e):b()),ia=(e=>y(2,(t,n)=>!S(t)&&e(t.value,n)))(Sn()),aa=y(2,(e,t)=>!S(e)&&t(e.value)),oa=`~effect/Context/Service`,sa=function(){function e(){}let t=e;Object.setPrototypeOf(t,ca);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[ua]=ua,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&la.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},ca={[oa]:oa,...ti({label:`Service`,evaluate(e){return Lr(Na(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return Da(this,e)},use(e){return Ur(t=>e(Na(t.context,this)))},useSync(e){return Ur(t=>Lr(e(Na(t.context,this))))}},la=new Set,ua=`~effect/Context/Reference`,da=`~effect/Context`,fa=8,pa=8,ma=(e,t,n,r)=>{let i=Object.create(xa);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},ha=(e,t)=>{t&&(ha(e,t.parent),e.set(t.key,t.value))},ga=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return ha(t,e.overlay),e._flat=t},_a=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),ba(n)},va=Symbol(),ya=(e,t)=>{let n=e;for(let e=n.overlay;e;e=e.parent)if(e.key===t)return e.value;let r=n.base.get(t);return r===void 0&&!n.base.has(t)?va:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=pa&&(n.base=ga(n),n.overlay=void 0,n.depth=0),r)},ba=e=>ma(void 0,e,void 0,0),xa={get mapUnsafe(){return ga(this)},...cr,[da]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[on](e){if(!Ca(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!sn(r,n.get(e)))return!1;return!0},[Bt](){return qt(this.mapUnsafe.size)}},Sa=(e,t)=>e.cacheRoot===t.cacheRoot,Ca=e=>It(e,da),wa=e=>!!e[ua],Ta=()=>Ea,Ea=ba(new Map),Da=(e,t)=>ba(new Map([[e.key,t]])),Oa=y(3,(e,t,n)=>ka(e,t.key,n)),ka=(e,t,n)=>{let r=e,i=la.has(t)?void 0:r.cacheRoot;if(r.depth>=fa){let e=new Map(r._flat??r.base);return r._flat||ha(e,r.overlay),e.set(t,n),ma(i,e,void 0,0)}return ma(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},Aa=y(2,(e,t)=>ja(e,t.key)),ja=(e,t)=>{let n=ya(e,t);return n===va?void 0:n},Ma=y(2,(e,t)=>{let n=ya(e,t.key);if(n===va){if(wa(t))return Fa(t);throw Ia(t)}return n}),Na=Ma,Pa=`~effect/Context/defaultValue`,Fa=e=>Pa in e?e[Pa]:e[Pa]=e.defaultValue(),Ia=e=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
|
|
4
|
+
`);e.splice(1,3),t.stack=e.join(`
|
|
5
|
+
`)}return t},La=y(2,(e,t)=>{let n=ya(e,t.key);return n===va?wa(t)?x(Fa(t)):b():x(n)}),Ra=y(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:_a(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),za=(...e)=>{let t=new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return ba(t)},Ba=(...e)=>t=>{if(e.length<=1){let n=new Map;if(e.length===1){let r=e[0].key,i=ya(t,r);i!==va&&n.set(r,i)}return ba(n)}let n=new Set(e.map(e=>e.key));return _a(t,e=>e.forEach((t,r)=>{n.has(r)||e.delete(r)}))},Va=sa,Ha=e=>e.length>0,Ua=e=>e>0?Math.floor(e):0,Wa=e=>Math.max(1,Ua(e)),Ga=Oi,Ka=Ei,qa=ki,Ja=e=>{if(kt(e))try{return Ga(e())}catch(e){return Ka(e)}try{return Ga(e.try())}catch(t){return Ka(e.catch(t))}},Ya=Si,Xa=Ci,Za=wi,Qa=y(2,(e,t)=>Za(e)?Ga(t(e.success)):e),$a=y(2,(e,{onFailure:t,onSuccess:n})=>Xa(e)?t(e.failure):n(e.success)),eo=y(2,(e,t)=>{if(Za(e))return e.success;throw t(e.failure)})(ct),to=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(Xa(n))return n;t.push(n.success)}return Ga(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(Xa(r))return r;Xn(t,n,r.success)}return Ga(t)},no=(...e)=>e,ro=ai,io={[Symbol.iterator](){return ao}},ao={next(){return{done:!0,value:void 0}}},oo=()=>io,so=y(2,(e,t)=>Object.hasOwn(e,t)),co=y(2,(e,t)=>{let n={...e};for(let r of lo(e))Xn(n,r,t(e[r],r));return n}),lo=e=>Object.keys(e),uo=e=>y(2,(t,n)=>{for(let r of lo(t))if(!so(n,r)||!e(t[r],n[r]))return!1;return!0}),fo=e=>{let t=uo(e);return(e,n)=>t(e,n)&&t(n,e)},po=globalThis.Array,mo=e=>po.isArray(e)?e:po.from(e),ho=e=>po.isArray(e)?e:[e],go=y(2,(e,t)=>[t,...e]),_o=y(2,(e,t)=>[...e,t]),vo=y(2,(e,t)=>mo(e).concat(mo(t)));po.isArray;var yo=Ha,bo=Ha;function xo(e,t){return!Number.isFinite(e)||e<0||e>=t.length}var So=y(2,(e,t)=>{let n=Math.floor(t);return xo(n,e)?b():x(e[n])}),Co=y(2,(e,t)=>{let n=Math.floor(t);if(xo(n,e))throw Error(`Index out of bounds: ${n}`);return e[n]}),wo=So(0),To=Co(0),Eo=e=>e[e.length-1],Do=y(2,(e,t)=>{let n=mo(e);for(let e=n.length-1;e>=0;e--){let r=n[e],i=t(r,e);if(typeof i==`boolean`){if(i)return x(r)}else if(C(i))return i}return b()}),Oo=y(2,(e,t)=>{let n=po.from(e);return n.sort(t),n}),ko=y(2,(e,t)=>Ao(e,t,no)),Ao=y(3,(e,t,n)=>{let r=mo(e),i=mo(t);if(bo(r)&&bo(i)){let e=[n(To(r),To(i))],t=Math.min(r.length,i.length);for(let a=1;a<t;a++)e[a]=n(r[a],i[a]);return e}return[]}),jo=y(2,(e,t)=>{let n=mo(e);if(bo(n)){let[e,r]=t(n),i=[e],a=r;for(;Ha(a);){let[e,n]=t(a);i.push(e),a=n}return i}return[]}),Mo=y(2,(e,t)=>{let n=Wa(t);return n>=e.length?[No(e),[]]:[go(e.slice(1,n),To(e)),e.slice(n)]}),No=e=>e.slice(),Po=y(2,(e,t)=>{let n=mo(e);return bo(n)?jo(n,Mo(t)):[]}),Fo=y(2,(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e].push(r):Xn(n,e,[r])}return n}),Io=(e,t)=>{let n=Vt(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(sn(e,t))return!1;return r.push(t),!0},Lo=()=>[],Ro=e=>[e],zo=y(2,(e,t)=>e.map(t)),Bo=e=>{let t=[];for(let n of e)C(n)&&t.push(n.value);return t},Vo=oi,Ho=y(2,(e,t)=>{let n=[];next:for(let r of mo(e)){for(let e=0;e<n.length;e++)if(t(r,n[e]))continue next;n.push(r)}return n}),Uo=e=>{let t=mo(e);if(t.length<2)return[...t];let n=new Map,r=[];for(let e of t)Io(n,e)&&r.push(e);return r},Wo=`~effect/Duration`,Go=BigInt(0),Ko=BigInt(1),qo=BigInt(2),Jo=BigInt(10),Yo=BigInt(1e3),Xo=BigInt(1e6),Zo=BigInt(1e9),Qo=BigInt(6e10),$o=BigInt(36e11),es=BigInt(864e11),ts=BigInt(6048e11),ns=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),rs=e=>Number.isInteger(e)?BigInt(e)*Xo:ns(e*1e6),is=e=>vs(Number.isFinite(e)?ns(e):e),as=(e,t)=>{let n=Number(e);if(Number.isFinite(n))return n/t;let r=BigInt(t);return Number(e/r)+Number(e%r)/t},os=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=Jo**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return ss(r?-o:o,a)},ss=(e,t)=>{let n=e<Go?-e:e,r=n/t+(n%t*qo>=t?Ko:Go);return e<Go?-r:r},cs=(e,t)=>{let n=Number(e)*t;if(!Number.isFinite(n))return vs(n);let r=os(e,BigInt(t)*Xo);return vs(Number.isInteger(n)&&BigInt(n)*Xo===r?n:r)},ls=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,us=e=>{switch(typeof e){case`number`:return ws(e);case`bigint`:return Cs(e);case`string`:{if(e===`Infinity`)return xs;if(e===`-Infinity`)return Ss;let t=ls.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return Cs(os(r,Ko));if(i===`micro`||i===`micros`)return Cs(os(r,Yo));switch(i){case`milli`:case`millis`:return cs(r,1);case`second`:case`seconds`:return cs(r,1e3);case`minute`:case`minutes`:return cs(r,6e4);case`hour`:case`hours`:return cs(r,36e5);case`day`:case`days`:return cs(r,864e5);case`week`:case`weeks`:return cs(r,6048e5)}break}case`object`:{if(e===null)break;if(Wo in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(wt))return ps(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return bs;if(e[0]===-1/0||e[1]===-1/0)return Ss;if(e[0]===1/0||e[1]===1/0)return xs;let t=e[0]*1e9+e[1];return Number.isFinite(t)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?vs(BigInt(e[0])*Zo+BigInt(e[1])):is(t)}let t=e,n=0;if(t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds){if(!Number.isFinite(n))return vs(n);let e=fs(t);return e===void 0||BigInt(n)*Xo===e?vs(n):vs(e)}let r=n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0),i=Number.isFinite(r)?fs(t):void 0;return i===void 0?is(r):vs(i)}}return ps(e)},ds=e=>!e||Number.isInteger(e),fs=e=>{if(!ds(e.weeks)||!ds(e.days)||!ds(e.hours)||!ds(e.minutes)||!ds(e.seconds)||!ds(e.milliseconds)||!ds(e.microseconds)||!ds(e.nanoseconds))return;let t=Go;return e.weeks&&(t+=BigInt(e.weeks)*ts),e.days&&(t+=BigInt(e.days)*es),e.hours&&(t+=BigInt(e.hours)*$o),e.minutes&&(t+=BigInt(e.minutes)*Qo),e.seconds&&(t+=BigInt(e.seconds)*Zo),e.milliseconds&&(t+=BigInt(e.milliseconds)*Xo),e.microseconds&&(t+=BigInt(e.microseconds)*Yo),e.nanoseconds&&(t+=BigInt(e.nanoseconds)),t},ps=e=>{throw Error(`Invalid Input: ${e}`)},ms={_tag:`Millis`,millis:0},hs={_tag:`Infinity`},gs={_tag:`NegativeInfinity`},_s={[Wo]:Wo,[Bt](){switch(this.value._tag){case`Millis`:return Vt(rs(this.value.millis));case`Nanos`:return Vt(this.value.nanos);default:return Xt(this.value)}},[on](e){return ys(e)&&Ms(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[Bn](){return this.toJSON()},pipe(){return at(this,arguments)}},vs=e=>{let t=Object.create(_s);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?ms:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:rs(e)}:e>0?hs:gs:e===Go?ms:{_tag:`Nanos`,nanos:e},t},ys=e=>It(e,Wo),bs=vs(0),xs=vs(1/0),Ss=vs(-1/0),Cs=e=>vs(e),ws=e=>vs(e),Ts=e=>vs(e*1e3),Es=e=>vs(e*6e4),Ds=e=>ks(us(e),{onMillis:ct,onNanos:e=>as(e,1e6),onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),Os=e=>{let t=us(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return rs(t.value.millis)}},ks=y(2,(e,t)=>{switch(e.value._tag){case`Millis`:return t.onMillis(e.value.millis);case`Nanos`:return t.onNanos(e.value.nanos);case`Infinity`:return t.onInfinity();case`NegativeInfinity`:return(t.onNegativeInfinity??t.onInfinity)()}}),As=y(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(Os(e),t.value.nanos):n.onNanos(e.value.nanos,Os(t))),js=(e,t)=>As(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Ms=y(2,(e,t)=>js(e,t)),Ns=e=>t=>!Xa(e(t)),Ps=e=>t=>t.has(e)?Ga(t):Ka(t),Fs=y(2,(e,t)=>n=>{let r=e(n);return Xa(r)?r:t(r.success)}),Is=Va(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new Vs}),Ls=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Rs=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},zs=e=>{try{return Rs(e)}catch{return Ls(e)}},Bs=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},Vs=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?Ls:zs)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new Hs(this.setImmediate)}},Hs=class{tasks=new Bs;running=void 0;setImmediate;constructor(e=zs){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}},Us=Va(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Ws=Va(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),Gs=class extends st{constructor(e){super(),e&&Zn(this,e)}},Ks=e=>class extends Gs{_tag=e},qs=Kr,Js=`~effect/encoding/EncodingError`,Ys=class extends qs(`EncodingError`){[Js]=Js},Xs=e=>ac(typeof e==`string`?rc.encode(e):e),Zs=e=>{switch(e){case 16:return tc();case 32:return nc();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=ec();return t}}},Qs=Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),$s=()=>Math.random()*4294967296>>>0,ec=()=>{let e=$s();return String.fromCharCode(Qs[e>>>28],Qs[e>>>24&15],Qs[e>>>20&15],Qs[e>>>16&15],Qs[e>>>12&15],Qs[e>>>8&15],Qs[e>>>4&15],Qs[e&15])},tc=()=>{let e=$s(),t=$s();return String.fromCharCode(Qs[e>>>28],Qs[e>>>24&15],Qs[e>>>20&15],Qs[e>>>16&15],Qs[e>>>12&15],Qs[e>>>8&15],Qs[e>>>4&15],Qs[e&15],Qs[t>>>28],Qs[t>>>24&15],Qs[t>>>20&15],Qs[t>>>16&15],Qs[t>>>12&15],Qs[t>>>8&15],Qs[t>>>4&15],Qs[t&15])},nc=()=>{let e=$s(),t=$s(),n=$s(),r=$s();return String.fromCharCode(Qs[e>>>28],Qs[e>>>24&15],Qs[e>>>20&15],Qs[e>>>16&15],Qs[e>>>12&15],Qs[e>>>8&15],Qs[e>>>4&15],Qs[e&15],Qs[t>>>28],Qs[t>>>24&15],Qs[t>>>20&15],Qs[t>>>16&15],Qs[t>>>12&15],Qs[t>>>8&15],Qs[t>>>4&15],Qs[t&15],Qs[n>>>28],Qs[n>>>24&15],Qs[n>>>20&15],Qs[n>>>16&15],Qs[n>>>12&15],Qs[n>>>8&15],Qs[n>>>4&15],Qs[n&15],Qs[r>>>28],Qs[r>>>24&15],Qs[r>>>20&15],Qs[r>>>16&15],Qs[r>>>12&15],Qs[r>>>8&15],Qs[r>>>4&15],Qs[r&15])},rc=new TextEncoder,ic=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),ac=e=>{let t=``;for(let n=0;n<e.length;n++)t+=ic[e[n]];return t},oc=`effect/Tracer/ParentSpan`,sc=class extends sa()(oc,{fiberCached:!0}){},cc=e=>e,lc=Va(`effect/Tracer/DisablePropagation`,{defaultValue:dt}),uc=Va(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),dc=Va(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),fc=`effect/Tracer`,pc=cc({span:e=>new mc(e)}),mc=class{_tag=`Span`;sampled;name;parent;annotations;links;startTime;kind;status;_traceId=void 0;_spanId=void 0;_attributes=void 0;_events=void 0;constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime}}get traceId(){return this._traceId??=Ji(this.parent)?.traceId??Zs(32)}get spanId(){return this._spanId??=Zs(16)}get attributes(){return this._attributes??=new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}},hc=`effect/Metric/FiberRuntimeMetrics`,gc=Va(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:pt}),_c=Va(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:ut}),vc=Va(`effect/References/TracerTimingEnabled`,{defaultValue:ut}),yc=Va(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),bc=Va(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),xc=Va(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),Sc=Va(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),Cc=Va(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),wc=Va(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),Tc=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=Kn();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};qn(3);let n=Error();return qn(t),{...e,captureStackTrace:Dc(()=>n.stack)}},Ec=e=>t=>{let n;return()=>{if(n!==void 0)return n;let r=t();if(!r)return;let i=r.split(`
|
|
6
|
+
`);if(i[e]!==void 0)return n=i[e].trim(),n}},Dc=Ec(3),Oc=class extends vr{constructor(e,t=yr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[on](e){return Mr(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[Bt](){return Jt(`${this._tag}:${this.fiberId}`)}},kc=e=>new Oc(e),Ac=e=>new gr([new Oc(e)]),jc=e=>e.reasons.some(Ar),Mc=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return Ga(n.error)}return Ka(e)},Nc=e=>e.reasons.some(jr),Pc=e=>Nc(e)&&jc(e)?xr(e.reasons.map(e=>e._tag===`Fail`&&!Xr(e.error)?new Dr(e.error,e.annotations):e)):e,Fc=e=>Nc(e)?Ka(Pc(e)):Mc(e),Ic=e=>{let t=e.reasons.find(jr);return t?Ga(t.defect):Ka(e)},Lc=e=>e.reasons.some(Mr),Rc=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?Ga(t):Ka(e)},zc=e=>e.reasons.length>0&&e.reasons.every(Mr),Bc=y(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>Ar(e)?(n=!0,new br(t(e.error),e.annotations)):e);return n?xr(r):e}),Vc=e=>{let t;for(let n of e.reasons){if(n._tag===`Fail`)return n.error;n._tag===`Die`&&(t??=n)}return t===void 0?e.reasons.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`):t.defect},Hc=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=Kn();i!==0&&qn(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(Uc(i._tag===`Die`?i.defect:i.error,i.annotations,t));if(n.length===0){let e=Error(`The fiber was interrupted by:`);e.name=`InterruptCause`,e.stack=Jc(e,r);let i=new globalThis.Error(`All fibers interrupted without error`,{cause:e});i.name=`InterruptError`,i.stack=`${i.name}: ${i.message}`,n.push(Uc(i,r[0].annotations,t))}}finally{i!==0&&qn(i)}return n},Uc=(e,t,n,r=new Set)=>{let i=typeof e,a;if(e&&i===`object`){r.add(e);let i=e.cause;if(a=new globalThis.Error(Wc(e),{cause:i!==void 0&&!r.has(i)?Uc(i,void 0,void 0,r):void 0}),typeof e.name==`string`&&(a.name=e.name),typeof e.stack==`string`)a.stack=Kc(e.stack,a,t);else{let e=`${a.name}: ${a.message}`;a.stack=t?qc(e,t):e}n?.includeCauseInStack&&(a.stack=Zc(a));for(let t of Object.keys(e))t in a||(a[t]=e[t])}else{a=new globalThis.Error(e?i===`string`?e:Ln(e):`Unknown error: ${e}`);let n=`${a.name}: ${a.message}`;a.stack=t?qc(n,t):n}return a},Wc=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return Ln(e)},Gc=/\((.*)\)/g,Kc=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
|
|
7
|
+
`),a=[r];for(let e=1;e<i.length&&!/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[e]);e++)a.push(i[e]);return n?qc(a.join(`
|
|
8
|
+
`),n):a.join(`
|
|
9
|
+
`)},qc=(e,t)=>{let n=t?.get(Rr.key);return n&&(e=`${e}\n${Yc(n)}`),e},Jc=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(zr.key);n.push(` at fiber (${t})`),r&&n.push(Yc(r))}return n.join(`
|
|
10
|
+
`)},Yc=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Gc),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
|
|
11
|
+
`)},Xc=e=>Hc(e).map(Zc).join(`
|
|
12
|
+
`),Zc=e=>e.cause?`${e.stack} {\n${Qc(e.cause,` `)}\n}`:e.stack,Qc=(e,t)=>{let n=e.stack.split(`
|
|
13
|
+
`),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${Qc(e.cause,`${t} `)}\n${t}}`),r},$c=`~effect/Fiber`,el={_A:ct,_E:ct},tl={id:0},nl=(()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),rl=()=>nl===void 0?void 0:new nl(`effect/Fiber`),il=()=>globalThis[Dn],al=class{constructor(e,t=!0){this.setContext(e),this.id=++tl.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[$c](){return el}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return Na(this.context,e)}addObserver(e){return this._exit?(e(this._exit),mt):(this._observers===void 0?this._observers=[e]:this._observers.push(e),()=>this.removeObserver(e))}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=Ac(e);this.cache.stackFrame&&(n=kr(n,Da(Rr,this.cache.stackFrame))),t&&(n=kr(n,t)),this._interruptedCause=this._interruptedCause?wr(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(vl(this._interruptedCause)))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;if(this._asyncContext!==void 0){let t=this._asyncContext;this._asyncContext=void 0;try{return t.runInAsyncScope(this.evaluate,this,e)}finally{t.emitDestroy()}}else if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===sr){this._asyncContext=rl();return}let n=ll.interruptChildren&&ll.interruptChildren(this);if(n!==void 0)return this.evaluate(su(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent&&=(this._parent._children?.delete(this),void 0),this._observers!==void 0){let e=this._observers;this._observers=void 0;for(let n=0;n<e.length;n++)e[n](t)}this._stack.length=0,this._children=void 0,this.context=Ta()}runLoop(e){let t=globalThis[Dn];globalThis[Dn]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{for(;;)try{this._deferredInterrupt&&(this._deferredInterrupt=!1,i=vl(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=su(Cl,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[rr](this),i===sr){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return sr}}catch(e){if(!It(i,`~effect/Effect/evaluate`))return Hr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=Hr(e)}}finally{this._running=n,globalThis[Dn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,sl;for(;;){let t=this._stack.pop();if(!t)return;let n=t[or];if(n!==void 0){let r=n.call(t,this);if(r)return r[e]=r,r}if(t[e])return t}}succeedWith(e){if(!(++this.currentOpCount&cl-1))return Lr(e);let t=this.getCont(ir);return t?t[ir](e,this):this.yieldWith(Lr(e))}yieldWith(e){return this._yielded=e,sr}children(){return this._children??=new Set}pipe(){return at(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Sa(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=ol(e);this.cache?.scheduler!==r.scheduler&&(this._dispatcher=void 0),this.cache=r}get currentSpanLocal(){let e=this.cache.span;return e?._tag===`Span`?e:void 0}},ol=e=>{let t=ja(e,fc);return{scheduler:Na(e,Is),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:Na(e,_c),span:ja(e,oc),logLevel:Na(e,Sc),minimumLogLevel:Na(e,Cc),stackFrame:Na(e,gc),runtimeMetrics:ja(e,hc),maxOpsBeforeYield:Na(e,Us),preventYield:Na(e,Ws)}},sl={[ir](e,t){return vl(t._interruptedCause)},[ar](e,t){return vl(t._interruptedCause)}},cl=32,ll={interruptChildren:void 0},ul=e=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(zr.key,e.cache.stackFrame),ba(t)},dl=e=>{let t=e;return t._exit?_l(t._exit):Nl(n=>t._exit?n(_l(t._exit)):bl(e.addObserver(e=>n(_l(e)))))},fl=e=>Nl(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;)if(e.value._exit)r.push(e.value._exit),e=n.next();else{i=e.value.addObserver(e=>{r.push(e),a()});return}t(_l(r))}return a(),bl(()=>i?.())}),pl=e=>{let t=e;return t._exit?t._exit:Nl(n=>t._exit?n(t._exit):bl(e.addObserver(n)))},ml=e=>Ur(t=>hl(e,t.id)),hl=y(e=>It(e[0],$c),(e,t,n)=>Ur(r=>{let i=ul(r);return i=i&&n?Ra(i,n):i??n,e.interruptUnsafe(t,i),iu(dl(e))})),gl=e=>Ur(t=>{let n=ul(t),r=Lo();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return iu(fl(r))}),_l=Lr,vl=Br,yl=Vr,bl=Fr({op:`Sync`,[rr](e){let t=this[nr](),n=e.getCont(ir);return n?n[ir](t,e):e.yieldWith(Lr(t))}}),xl=Fr({op:`Suspend`,[rr](e){return this[nr]()}}),Sl=$a({onFailure:yl,onSuccess:_l}),Cl=Fr({op:`Yield`,[rr](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(bu)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}})(0),wl=_l(b()),Tl=e=>xl(()=>vl(e())),El=e=>Hr(e),Dl=_l(void 0),Ol=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new $f(e,`An error occurred in Effect.try`):e.catch;return xl(()=>{try{return _l(t())}catch(e){return yl(n(e))}})},kl=e=>jl(function(t,n){e(n).then(e=>t(_l(e)),e=>t(El(e)))},e.length!==0),Al=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new $f(e,`An error occurred in Effect.tryPromise`):e.catch;return jl(function(e,r){let i=e=>xl(()=>{try{return yl(Yn(()=>n(e)))}catch(e){return El(e)}});try{t(r).then(t=>e(_l(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},jl=function(){let e=Pr({op:`Async`,[rr](e){let t=!1,n=!1,r=this.withSignal?new AbortController:void 0,i=this.register.call(e.cache.scheduler,r=>{t||(t=!0,n?e.evaluate(r):n=r)},r?.signal);return n===!1?(n=!0,e.yieldWith(()=>{t=!0}),r===void 0&&i===void 0||e._stack.push(Ml(()=>(t=!0,r?.abort(),i??bu))),sr):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Ml=Fr({op:`AsyncFinalizer`,[or](e){e.interruptible&&(e.interruptible=!1,e._stack.push(qd))},[ar](e,t){return Lc(e)?su(_d(Br(e),this[nr]()),()=>vl(e)):vl(e)}}),Nl=e=>jl(e,e.length>=2),Pl=Nl(mt),Fl=(...e)=>{if(e.length===1){let t=e[0];return xl(()=>Ul(t()))}let[t,n]=e;return xl(()=>Ul(n.call(t.self)))},Il=(e,...t)=>{let n=t.length===0?function(){return xl(()=>Ul(e.apply(this,arguments)))}:function(){let n=xl(()=>Ul(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return Ll(e.length,n)},Ll=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Rl=Ec(2),zl=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=Kn(),i;return r!==0&&(qn(2),i=new globalThis.Error,qn(r)),e?(r,...a)=>Bl(t,r,i,a,e,n):Bl(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},Bl=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?Rl(()=>n.stack):pt;return Ll(o.length,function(...t){let n=xl(()=>{let e=o.apply(this,arguments);return ur(e)?e:Ul(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!ur(n))return n;let l=Kn(),u;return l!==0&&(qn(2),u=new globalThis.Error,qn(l)),Ou(i?Nf(e,a,e=>Pf(n,e)):n,gc,t=>({name:e,stack:u?Rl(()=>u.stack):pt,parent:{name:s,stack:c,parent:t}}))})},Vl=(e,...t)=>Ll(e.length,t.length===0?function(){return Hl(()=>e.apply(this,arguments))}:function(){let n=Hl(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),Hl=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return _l(r.value);let i=r.value;if(i&&i._tag===`Success`)n=i.value;else{if(i&&i._tag===`Failure`)return r.value;{let n=!0;return xl(()=>n?(n=!1,su(r.value,e=>Ul(t,e))):xl(()=>Ul(e())))}}}}catch(e){return El(e)}},Ul=function(){let e=Pr({op:`Iterator`,[ir](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return _l(r.value);if(!cu(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[rr](e){return this[ir](this.initial,e)}}),t=function(e,t){this.iterator=e,this.initial=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Wl=y(2,(e,t)=>new ql(e,Jl,_l(t))),Gl=function(e){return e._stack.push(this),this[nr]},Kl=Pr({op:`OnSuccess`,[rr]:Gl}),ql=function(e,t,n){this[nr]=e,this[ir]=t,this.payload=n};ql.prototype=Kl;var Jl=function(){return this.payload},Yl=function(e,t){return t.succeedWith(this.payload)},Xl=(()=>{let e=Kn();if(e===0)return!1;let t=`~effect/Effect/stackProbe`,n={[t]:function(){return Error()}};qn(1);let r=n[t]();return qn(e),r.stack?.includes(`[as `+t+`]`)===!0})(),Zl=function(e,t){let n=this.payload;return t.succeedWith(Xl?n(e):Yn(()=>n(e)))},Ql=function(e){let t=this.payload;return t(e)},$l=function(e){let t=this.payload;return new ql(t(e),Yl,e)},eu=function(e){return new ql(this.payload,Yl,e)},tu=e=>du(e,x),nu=y(2,(e,t)=>new ql(e,ur(t)?Jl:Ql,t)),ru=y(2,(e,t)=>new ql(e,ur(t)?eu:$l,t)),iu=e=>new ql(e,Jl,bu),au=(e,t)=>Ur(n=>{let r=new Set;return Nd(n,()=>r.size===0?void 0:gl(r)),Nl(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=uf(n,s,!0,!0,!1);r.add(c),c.addObserver(o=>{r.delete(c);let s=!a;a=!0,i(o),s&&t?.onWinner&&t.onWinner({fiber:c,index:e,parentFiber:n})})}})}),ou=y(e=>ur(e[1]),(e,t,n)=>au([e,t],n)),su=y(2,(e,t)=>new ql(e,Ql,t)),cu=e=>e[$n]!==void 0,lu=y(2,(e,t)=>cu(e)?e._tag===`Success`?t(e.value):e:su(e,t)),uu=e=>su(e,ct),du=y(2,(e,t)=>new ql(e,Zl,t)),fu=y(2,(e,t)=>cu(e)?xu(e,t):du(e,t)),pu=y(2,(e,t)=>cu(e)?Su(e,t):Yu(e,t)),mu=y(2,(e,t)=>cu(e)?Cu(e,t):Xu(e,t)),hu=e=>Br(Ac(e)),gu=e=>e._tag===`Success`,_u=e=>e._tag===`Failure`,vu=e=>e._tag===`Failure`?Ga(e.cause):Ka(e),yu=e=>e._tag===`Failure`&&Lc(e.cause),bu=Lr(void 0),xu=y(2,(e,t)=>e._tag===`Success`?Lr(t(e.value)):e),Su=y(2,(e,t)=>e._tag===`Success`?e:Br(Bc(e.cause,t))),Cu=y(2,(e,t)=>e._tag===`Success`?Lr(t.onSuccess(e.value)):Br(Bc(e.cause,t.onFailure))),wu=y(2,(e,t)=>gu(e)?t:e),Tu=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?bu:Br(xr(t))},Eu=e=>Ur(t=>_l(La(t.context,e))),Du=y(2,(e,t)=>Ur(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),Nd(n,()=>{n.setContext(r)})),e})),Ou=y(3,(e,t,n)=>Du(e,e=>{let r=Ma(e,t),i=n(r);return r===i?e:Oa(e,t,i)})),ku=()=>Au,Au=Ur(e=>_l(e.context)),ju=e=>Ur(t=>e(t.context)),Mu=y(2,(e,t)=>cu(e)?e:Du(e,Ra(t))),Nu=function(){return arguments.length===1?y(2,(e,t)=>Pu(e,arguments[0],t)):y(3,(e,t,n)=>Pu(e,t,n)).apply(this,arguments)},Pu=(e,t,n)=>Du(e,Oa(t,n)),Fu=y(e=>ur(e[0]),(e,t)=>ef({while:ut,body:lt(t?.disableYield?e:su(e,e=>Cl)),step:mt})),Iu=y(2,(e,t)=>new Ru(e,t.length===1?t:e=>t(e))),Lu=Pr({op:`OnFailure`,[rr]:Gl}),Ru=function(e,t){this[nr]=e,this[ar]=t};Ru.prototype=Lu;var zu=y(3,(e,t,n)=>Iu(e,e=>{let r=t(e);return Xa(r)?vl(r.failure):n(r.success,e)})),Bu=y(2,(e,t)=>zu(e,Fc,e=>t(e))),Vu=y(2,(e,t)=>zu(e,Ic,t)),Hu=y(2,(e,t)=>Iu(e,e=>nu(t(e),vl(e)))),Uu=y(3,(e,t,n)=>Iu(e,e=>{let r=t(e);return Xa(r)?vl(e):nu(n(r.success,e),vl(e))})),Wu=y(2,(e,t)=>Uu(e,Mc,e=>t(e))),Gu=y(e=>ur(e[0]),(e,t,n,r)=>Iu(e,e=>{let i=Fc(e);return Xa(i)?vl(i.failure):t(i.success)?n(i.success):r?r(i.success):vl(e)})),Ku=y(e=>ur(e[0]),(e,t,n,r)=>Iu(e,e=>{let i=Fc(e);if(Xa(i))return vl(i.failure);let a=t(i.success);return Xa(a)?r?r(a.failure):vl(e):n(a.success)})),qu=y(e=>ur(e[0]),(e,t,n,r)=>Gu(e,Array.isArray(t)?e=>It(e,`_tag`)&&t.includes(e._tag):Lt(t),n,r)),Ju=y(e=>ur(e[0]),(e,t,n)=>{let r;return Ku(e,e=>(r??=Object.keys(t),It(e,`_tag`)&&Ct(e._tag)&&r.includes(e._tag)?Ga(e):Ka(e)),e=>t[e._tag](e),n)}),Yu=y(2,(e,t)=>Iu(e,e=>vl(Bc(e,t)))),Xu=y(2,(e,t)=>td(e,{onFailure:e=>vl(Bc(e,t.onFailure)),onSuccess:e=>bl(()=>t.onSuccess(e))})),Zu=e=>Bu(e,El),Qu=y(e=>ur(e[0]),(e,t)=>{if(!t?.log)return od(e,{onFailure:e=>Dl,onSuccess:e=>Dl});let n=cp(t.log===!0?void 0:t.log);return td(e,{onFailure(e){let r=Fc(e);return Xa(r)?vl(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>Dl})}),$u=e=>sd(e,{onFailure:b,onSuccess:x}),ed=e=>cd(e,{onFailure:Ka,onSuccess:Ga}),td=y(2,(e,t)=>new rd(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),nd=Pr({op:`OnSuccessAndFailure`,[rr]:Gl}),rd=function(e,t,n){this[nr]=e,this[ir]=t,this[ar]=n};rd.prototype=nd;var id=function(e,t){let n=this.payload;return t.succeedWith(Xl?n.onSuccess(e):Yn(()=>n.onSuccess(e)))},ad=((e,t)=>{let n=Pr({op:e,[rr]:Gl,[ir]:id,[ar]:t}),r=function(e,t){this[nr]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=Fc(e);if(Xa(n))return vl(n.failure);let r=this.payload;return t.succeedWith(Xl?r.onFailure(n.success):Yn(()=>r.onFailure(n.success)))}),od=y(2,(e,t)=>td(e,{onFailure:e=>{let n=Fc(e);return Xa(n)?vl(n.failure):t.onFailure(n.success)},onSuccess:t.onSuccess})),sd=y(2,(e,t)=>new ad(e,t)),cd=y(2,(e,t)=>{if(cu(e)){if(e._tag===`Success`)return Lr(t.onSuccess(e.value));let n=Fc(e.cause);return Xa(n)?Br(n.failure):Lr(t.onFailure(n.success))}return sd(e,t)}),ld=e=>cu(e)?Lr(e):ud(e),ud=Fr({op:`Exit`,[rr](e){return e._stack.push(this),this[nr]},[ir](e,t,n){return t.succeedWith(n??Lr(e))},[ar](e,t,n){return t.succeedWith(n??Br(e))}}),dd=`~effect/Scope`,fd=`~effect/Scope/Closeable`,pd=sa(`effect/Scope`),md=(e,t)=>Ur(n=>(Xd(n),hd(e,t)??Dl)),hd=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&Cd(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return gd(n.finalizer,t);let r=n.finalizers;return r.size===1?gd(r.values().next().value,t):vd(e,r,t)},gd=(e,t)=>{try{return e(t)}catch(e){return Hr(e)}},_d=(e,t)=>gu(e)?t:Iu(t,t=>vl(Pc(Cr(e.cause,t)))),vd=Il(function*(e,t,n){let r=[],i=[],a=Array.from(t),o=il();for(let t=a.length-1;t>=0;t--){let[s,c]=a[t];e.strategy===`sequential`?r.push(yield*ld(gd(c,n))):s!==o&&i.push(uf(o,gd(c,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*fl(i)),yield*Tu(r)}),yd=(e,t)=>{let n=Td(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Sd(e,n,e=>md(n,e)),n)},bd=(e,t)=>xl(()=>e.state._tag===`Closed`?t(e.state.exit):(Sd(e,{},t),Dl)),xd=(e,t)=>bd(e,lt(t)),Sd=(e,t,n)=>{if(e.state._tag===`Empty`)e.state={_tag:`Open`,finalizerKey:t,finalizer:n,finalizers:void 0};else if(e.state._tag===`Open`){let r=e.state;r.finalizer===void 0||(r.finalizers=new Map([[r.finalizerKey,r.finalizer]]),r.finalizerKey=void 0,r.finalizer=void 0),r.finalizers.set(t,n)}},Cd=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=Ed:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=Ed))},wd=e=>Td(e,void 0),Td=(e=`sequential`,t)=>({[fd]:fd,[dd]:dd,strategy:e,parent:t,state:Ed}),Ed={_tag:`Empty`},Dd=pd,Od=Nu(pd),kd=e=>xl(()=>{let t=wd();return Pd(e(t),e=>xl(()=>hd(t,e)??Dl))}),Ad=(e,t,n)=>ju(r=>Qd(i=>su(Dd,a=>ru(n?.interruptible?i(e):e,e=>bd(a,n=>Mu(t(e,n),r)))))),jd=function(){let e=Pr({op:`OnExit`,[rr](e){return e._stack.push(this),this.effect},[or](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(qd),e.interruptible=!1)},[ir](e,t,n){n??=Lr(e);let r;try{r=this.onExit(n)}catch(e){r=Hr(e)}return r?su(r,e=>n):n},[ar](e,t,n){n??=Br(e);let r;try{r=this.onExit(n)}catch(e){r=Hr(e)}return r?su(_d(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),Md=(e,t,n)=>new jd(e,t,n),Nd=(e,t)=>{e._stack.push(new jd(void 0,t,void 0))},Pd=y(2,Md),Fd=y(2,(e,t)=>Pd(e,e=>t)),Id=y(3,(e,t,n)=>Pd(e,e=>{let r=t(e);return Xa(r)?Dl:n(r.success,e)})),Ld=y(2,(e,t)=>Id(e,vu,t)),Rd=y(3,(e,t,n)=>Pd(e,e=>{if(e._tag!==`Failure`)return Dl;let r=t(e.cause);return Xa(r)?Dl:n(r.success,e.cause)})),zd=y(2,(e,t)=>Rd(Rc,t)(e)),Bd=(e,t,n)=>Qd(r=>su(e,e=>Md(xl(()=>r(t(e))),t=>n(e,t),!0))),Vd=lt(1/0),Hd=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,Nd(e,()=>{if(!(--t.awaiters>0||t.done))return i===t&&(i=void 0),ml(t.fiber)}),pl(t.fiber));return[Ur(o=>{if(i!==void 0)return o===i.fiber?pl(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(zf).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(zf),c={fiber:new al(o.context),awaiters:0,done:!1};i=c;let l=a(o,c);return c.fiber.evaluate(Md(e,e=>{if(c.done=!0,i!==c||(i=void 0,yu(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),bl(()=>{i=void 0,r=void 0})]},Ud=e=>bl(()=>Hd(e,Vd)[0]),Wd=Ur(e=>vl(Ac(e.id))),Gd=e=>Ur(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(qd)),e)),Kd=Fr({op:`SetInterruptible`,[or](e){if(e.interruptible=this[nr],e._interruptedCause&&e.interruptible)return()=>vl(e._interruptedCause)}}),qd=Kd(!0),Jd=Kd(!1),Yd=e=>{if(e.interruptible=!0,e._stack.push(Jd),e._interruptedCause)return vl(e._interruptedCause)},Xd=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(qd))},Zd=e=>Ur(t=>t.interruptible?e:Yd(t)??e),Qd=e=>Ur(t=>t.interruptible?(t.interruptible=!1,t._stack.push(qd),e(Zd)):e(ct)),$d=(e,t)=>zt(e)?t?.mode===`result`?tf(e,ed,t):tf(e,ct,t):t?.discard?t.mode===`result`?tf(Object.values(e),ed,t):tf(Object.values(e),ct,t):xl(()=>du(tf(Object.entries(e),([e,n])=>du(t?.mode===`result`?ed(n):n,t=>[e,t]),{concurrency:t?.concurrency}),Object.fromEntries)),ef=Fr({op:`While`,[ir](e,t){return this[nr].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[nr].body()):bu},[rr](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[nr].body()):bu}}),tf=y(e=>typeof e[1]==`function`,(e,t,n)=>xl(()=>{let r=rf(n?.concurrency);if(r===1)return nf(e,t,n);let i=mo(e),a=i.length;if(a===0)return n?.discard?Dl:_l([]);let o=n?.discard?void 0:Array(a),s=cf({f:t,out:o},i,{concurrency:r});return s?Wl(s,o):_l(o)})),nf=(e,t,n)=>xl(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return Wl(ef({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),rf=e=>e===`unbounded`?1/0:Math.max(1,e??1),af=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>su(ld(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??Dl),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!cu(c))return r(e,i,a,o,c);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return i},of=e=>{let t=e.onItem,n=e.step;return(e,r,i)=>{let a=0,o=i.end??r.length,s=i.concurrency,c=!1,l,u,d,f,p,m=e=>{let t=Hr(e);return f=t,c=!0,u&&u.size>0?su(Gd(gl(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(cu(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=uf(l,g,!0,!0,`inherit`);if(t._exit){if(f=n(e,o,t._exit,a),f)break;continue}u.add(t);let r=a;if(t.addObserver(a=>{u.delete(t);try{if(f){if(a._tag===`Failure`){let e=a.cause.reasons.filter(e=>e._tag!==`Interrupt`);if(e.length>0){let t=xr(e);f=Br(f._tag===`Failure`?Pc(Cr(f.cause,t)):t)}}}else{let t=n(e,o,a,r);t&&(f=t,h())}if(i){let e=h();e&&d(e)}else c&&u.size===0&&d(f??Dl)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return Nl(e=>{l=il(),u=new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):xl(()=>(f??=bu,su(u?gl(u):Dl,()=>f?._tag===`Failure`?f:Dl)))})}if(c=!0,f){if(u&&u.size>0){let e=ul(l);u.forEach(t=>t.interruptUnsafe(l.id,e));return}if(d||f._tag===`Failure`)return f}else if(d){if(u)u.size===0&&d(Dl);else return bu}};return h()}},sf=()=>e=>of(e),cf=of({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag===`Failure`)return n;e.out&&(e.out[r]=n.value)}}),lf=y(e=>zt(e[0])&&!ur(e[0]),(e,t,n)=>du(tf(e,(e,n)=>{let r=t(e,n);return typeof r==`boolean`?_l(r?x(e):b()):du(r,t=>t?x(e):b())},n),Bo)),uf=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new al(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=rl(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},df=e=>()=>Ur(t=>t===e?Dl:ml(e)),ff=y(e=>ur(e[0]),(e,t,n)=>Ur(r=>{let i=t.state._tag===`Closed`?new al(r.context):uf(r,e,n?.startImmediately,!0,n?.uninterruptible);return i._exit||(t.state._tag===`Closed`?i.interruptUnsafe(r.id,ul(r)):(Sd(t,i,df(i)),i.addObserver(()=>Cd(t,i)))),_l(i)})),pf=y(e=>ur(e[0]),(e,t)=>su(Dd,n=>ff(e,n,t))),mf=e=>(t,n)=>{let r=new al(n?.scheduler?Oa(e,Is,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},hf=y(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(Cd(t,e),Sd(t,e,df(e)),e.addObserver(()=>Cd(t,e)),e)),gf=mf(Ta()),_f=e=>{let t=mf(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},vf=(e=>{let t=_f(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw Vc(e.cause);return e.value})})(Ta()),yf=e=>{let t=mf(e);return e=>{if(cu(e))return e;let n=new Vs(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??Hr(new Zf(r))}},bf=yf(Ta()),xf=(e=>{let t=yf(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw Vc(n.cause);return n.value}})(Ta()),Sf=_l(!0),Cf=_l(!1),wf=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Sf;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let e=0;e<this.waiters.length;e++)this.scheduled.push(this.waiters[e]);return this.waiters=[],Sf}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](bu)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](bu)}open=Ur(e=>this._isOpen?Cf:(this._isOpen=!0,this.scheduleUnsafe(e)));release=Ur(e=>this._isOpen?Cf:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=Nl(e=>this._isOpen?e(Dl):(this.waiters.push(e),bl(()=>{let t=this.waiters.indexOf(e);t===-1?this.scheduled!==void 0&&(t=this.scheduled.indexOf(e),t!==-1&&this.scheduled.splice(t,1)):this.waiters.splice(t,1)})));closeUnsafe(){return this._isOpen?(this._isOpen=!1,!0):!1}close=bl(()=>this.closeUnsafe());whenOpen=e=>su(this.await,()=>e);isOpen(){return this._isOpen}},Tf=e=>new wf(e??!1),Ef=BigInt(0),Df={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:Ef,endTime:Ef,exit:bu},attributes:new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},Of=e=>Object.assign(Object.create(Df),e),kf=e=>e?Na(e.annotations,lc)?e._tag===`Span`?kf(Ji(e.parent)):b():x(e):b(),Af=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&Na(n.annotations,lc),i=n?.parent===void 0?n?.root?b():kf(e.cache.span):x(n.parent),a;if(r)a=Of({name:t,parent:i,annotations:Oa(n?.annotations??Ta(),lc,!0)});else{let r=e.cache.tracer??pc,o=e.getRef(zf),s=e.getRef(vc),c=e.getRef(yc),l=e.getRef(bc),u=n?.level??e.getRef(uc),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??Ta(),links:d,startTime:s?o.currentTimeNanosUnsafe():Ef,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(C(i)&&i.value.sampled===!1?!1:!tp(e.getRef(dc),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},jf=(e,t)=>(t=typeof t==`function`?t:pt,Ou(gc,n=>({name:e,stack:t,parent:n}))),Mf=(e,t,n,r)=>bl(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():Ef,t)}),Nf=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return Ur(t=>{let i=Af(t,e,n),a=t.getRef(zf),o=t.getRef(vc);return Nd(t,e=>Mf(i,e,a,o)),r(i)})},Pf=Nu(sc),Ff=function(){let e=ur(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=ct;return t._tag===`Span`&&(n=Tc(n),r=jf(t.name,n?.captureStackTrace)),e?Pf(r(arguments[0]),t):e=>Pf(r(e),t)},If=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=Tc(arguments[2]);if(e){let e=arguments[0];return Nf(t,arguments[2],t=>Ff(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>Nf(t,r?r(...a):i,t=>Ff(e,t,n))},Lf=(...e)=>Ur(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return Dl}),Rf=Ur(e=>{let t=e.currentSpanLocal;return t?_l(t):yl(new Jr)}),zf=Va(`effect/Clock`,{defaultValue:()=>new Vf}),Bf=2**31-1,Vf=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=bl(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Wf()}currentTimeNanos=bl(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return Uf()}monotonicTimeNanos=bl(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(Ds(e))}sleepMillis(e){return e<=0?Cl:Number.isFinite(e)?Nl(t=>{let n=e>Bf?this.sleepMillis(e-Bf):Dl,r=setTimeout(()=>t(n),Math.min(e,Bf));return bl(()=>clearTimeout(r))}):Pl}},Hf=BigInt(1e6),Uf=function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==`function`)return()=>e.bigint();if(typeof performance<`u`&&typeof performance.now==`function`)return()=>BigInt(Math.round(performance.now()*1e6));let t=BigInt(0);return()=>{let e=BigInt(Date.now())*Hf;return e>t&&(t=e),t}}(),Wf=function(){let e=BigInt(1e9),t;return()=>{let n=Uf(),r=BigInt(Date.now())*Hf;if(t===void 0)t=r-n;else{let i=t+n;(r>i?r-i:i-r)>e&&(t=r-n)}return t+n}}(),Gf=e=>Ur(t=>e(t.getRef(zf))),Kf=e=>Gf(t=>t.sleep(us(e))),qf=Gf(e=>e.currentTimeMillis),Jf=`~effect/Cause/IllegalArgumentError`,Yf=class extends Kr(`IllegalArgumentError`){[Jf]=Jf;constructor(e){super({message:e})}},Xf=`~effect/Cause/AsyncFiberError`,Zf=class extends Kr(`AsyncFiberError`){[Xf]=Xf;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}},Qf=`~effect/Cause/UnknownError`,$f=class extends Kr(`UnknownError`){[Qf]=Qf;constructor(e,t){super({message:t,cause:e})}},ep=Va(`effect/Console`,{defaultValue:()=>globalThis.console}),tp=Li(Fi(Mi,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}})),np=Va(`effect/Logger/CurrentLoggers`,{defaultValue:()=>new Set([dp,fp])}),rp=Va(`effect/Logger/LogToStderr`,{defaultValue:dt}),ip={"~effect/Logger":{_Message:ct,_Output:ct},pipe(){return at(this,arguments)}},ap=e=>{let t=Object.create(ip);return t.log=e,t},op=e=>e.replace(/[\s="]/g,`_`),sp=(e,t)=>`${op(e[0])}=${t-e[1]}ms`,cp=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];mr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?xr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=Tr),Ur(r=>{let i=e??r.cache.logLevel;if(tp(r.cache.minimumLogLevel,i))return Dl;let a=r.getRef(zf),o=r.getRef(np);if(o.size>0){let e=new Date(a.currentTimeMillisUnsafe());for(let a of o)a.log({cause:n,fiber:r,date:e,logLevel:i,message:t})}return Dl})},lp={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};lp.gray,lp.blue,lp.green,lp.yellow,lp.red,lp.bgBrightRed,lp.black;var up=e=>`${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}.${e.getMilliseconds().toString().padStart(3,`0`)}`,dp=ap(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Xc(e));let o=t.getTime(),s=n.getRef(wc),c=``;for(let e of s)c+=` ${sp(e,o)}`;let l=n.getRef(xc);Object.keys(l).length>0&&a.push(l);let u=n.getRef(ep);(n.getRef(rp)?u.error:u.log)(`[${up(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),fp=ap(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(zf),a=t.getRef(xc),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))Xn(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Xc(e)),o.event(Hn(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)}),pp=mr,mp=hr,hp=Ar,gp=xr,_p=Er,vp=Or,yp=e=>new br(e),bp=e=>new Dr(e),xp=kc,Sp=zc,Cp=Bc,wp=Cr,Tp=Vc,Ep=Lc,Dp=Rc,Op=Xc,kp=Xr,Ap=ei,jp=Yf,Mp=Lr,Np=Br,Pp=Vr,Fp=bu,Ip=gu,Lp=_u,Rp={"~effect/Deferred":{_A:ct,_E:ct},pipe(){return at(this,arguments)}},zp=function(){this.resumes=void 0,this.effect=void 0};zp.prototype=Rp;var Bp=()=>new zp,Vp=()=>bl(()=>Bp()),Hp=e=>Nl(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),bl(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),Up=y(2,(e,t)=>bl(()=>qp(e,t))),Wp=e=>bl(()=>Gp(e)),Gp=e=>e.effect!==void 0,Kp=y(2,(e,t)=>Up(e,Lr(t))),qp=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},Jp=y(2,(e,t)=>Qd(n=>su(ld(n(e)),e=>Up(t,e)))),Yp=vc,Xp=pd,Zp=wd,Qp=Od,$p=bd,em=xd,tm=yd,nm=md,rm=`~effect/Layer`,im=`~effect/Layer/MemoMap`,am=(e,t)=>{let n={observers:0,deferred:Bp(),scope:Zp(),finalizer:r=>xl(()=>--n.observers>0?Dl:(e.map.delete(t),nm(n.scope,r)))};return n},om=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Sd(t,{},e.finalizer),!0),sm={[rm]:{_ROut:ct,_E:ct,_RIn:ct},pipe(){return at(this,arguments)}},cm=e=>{let t=Object.create(sm);return t.build=e,t},lm=e=>cm((t,n)=>{let r=tm(n);return Pd(e(t,r),e=>e._tag===`Failure`?nm(r,e):Dl)}),um=e=>{let t=lm((n,r)=>n.getOrElseMemoize(t,r,e));return t},dm=class{get[im](){return im}parent;constructor(e){this.parent=e}map=new Map;get(e,t){let n=this.map.get(e);return n?(om(n,t),n.deferred.effect??Hp(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return xl(()=>{let r;return Md(xl(()=>{let i=this.get(e,t);if(i)return i;let a=am(this,e);return om(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&qp(r,e)})})}},fm=()=>new dm,pm=e=>new dm(e),mm=class e extends sa()(`effect/Layer/CurrentMemoMap`){static forkOrCreate(t){let n=Aa(t,e);return n?pm(n):fm()}},hm=y(3,(e,t,n)=>Nu(du(xl(()=>e.build(t,n)),Oa(mm,t)),mm,t)),gm=y(2,(e,t)=>Ur(n=>hm(e,mm.forkOrCreate(n.context),t))),_m=function(){return arguments.length===1?e=>vm(Da(arguments[0],e)):vm(Da(arguments[0],arguments[1]))},vm=e=>cm(lt(_l(e))),ym=function(){return arguments.length===1?e=>bm(arguments[0],e):bm(arguments[0],arguments[1])},bm=(e,t)=>xm(du(t,t=>Da(e,t))),xm=e=>um((t,n)=>Qp(e,n)),Sm=e=>xm(Wl(e,Ta())),Cm=(e,t,n)=>{let r=tm(n,`parallel`);return tf(e,e=>e.build(t,tm(r,`sequential`)),{concurrency:e.length}).pipe(du(e=>za(...e)))},wm=(...e)=>um((t,n)=>Cm(e,t,n)),Tm=(e,t,n)=>um((r,i)=>su(Array.isArray(t)?Cm(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(Mu(t),du(e=>n(e,t))))),Em=y(2,(e,t)=>Tm(e,t,ct)),Dm=y(2,(e,t)=>Tm(e,t,(e,t)=>Ra(t,e))),Om=zf,km=qf,Am=`~effect/DateTime`,jm=`~effect/DateTime/TimeZone`,Mm={[Am]:Am,pipe(){return at(this,arguments)},[Bn](){return this.toString()},toJSON(){return dh(this).toJSON()}},Nm={...Mm,_tag:`Utc`,[Bt](){return qt(this.epochMilliseconds)},[on](e){return zm(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${dh(this).toJSON()})`}},Pm={...Mm,_tag:`Zoned`,[Bt](){return Wt(qt(this.epochMilliseconds))(Vt(this.zone))},[on](e){return zm(e)&&e._tag===`Zoned`&&this.epochMilliseconds===e.epochMilliseconds&&sn(this.zone,e.zone)},toString(){return`DateTime.Zoned(${Fh(this)})`}},Fm={[jm]:jm,[Bn](){return this.toString()}},Im={...Fm,_tag:`Named`,[Bt](){return Jt(`Named:${this.id}`)},[on](e){return Vm(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},Lm={...Fm,_tag:`Offset`,[Bt](){return Jt(`Offset:${this.offset}`)},[on](e){return Vm(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${mh(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},Rm=(e,t,n)=>{let r=Object.create(Pm);return r.epochMilliseconds=e,r.zone=t,Object.defineProperty(r,"partsUtc",{value:n,enumerable:!1,writable:!0}),Object.defineProperty(r,"adjustedEpochMillis",{value:void 0,enumerable:!1,writable:!0}),Object.defineProperty(r,"partsAdjusted",{value:void 0,enumerable:!1,writable:!0}),r},zm=e=>It(e,Am),Bm=e=>zm(e[0]),Vm=e=>It(e,jm),Hm=e=>Vm(e)&&e._tag===`Named`,Um=e=>e._tag===`Utc`,Wm=e=>e._tag===`Zoned`,Gm=e=>{let t=Object.create(Nm);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Km=e=>{let t=e.getTime();if(Number.isNaN(t))throw new jp(`Invalid date`);return Gm(t)},qm=e=>{if(zm(e))return e;if(e instanceof Date)return Km(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Km(new Date(e.epochMilliseconds));let t=new Date(0);return bh(t,e),Km(t)}return typeof e==`string`&&!Jm(e)?Km(new Date(e+`Z`)):Km(new Date(e))},Jm=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e)||/z$|gmt$/i.test(e),Ym=-864e13+432e5,Xm=864e13-504e5,Zm=(e,t)=>{let n=t?.timeZone;if(n===void 0&&zm(e)&&Wm(e))return e;let r=qm(e);if(r.epochMilliseconds<Ym||r.epochMilliseconds>Xm)throw RangeError(`Epoch millis out of range: ${r.epochMilliseconds}`);n===void 0&&typeof e==`object`&&`timeZoneId`in e&&(n=e.timeZoneId);let i;if(n===void 0)i=oh(new Date(r.epochMilliseconds).getTimezoneOffset()*-60*1e3);else if(Vm(n))i=n;else if(typeof n==`number`)i=oh(n);else{let e=lh(n);if(S(e))throw new jp(`Invalid time zone: ${n}`);i=e.value}return t?.adjustForTimeZone===!0?Sh(r.epochMilliseconds,i,t?.disambiguation??`compatible`):Rm(r.epochMilliseconds,i,r.partsUtc)},Qm=Yi(qm),$m=du(km,Gm),eh=e=>Gm(e.epochMilliseconds),th=y(Bm,(e,t,n)=>n?.adjustForTimeZone===!0?Sh(e.epochMilliseconds,t,n?.disambiguation??`compatible`):Rm(e.epochMilliseconds,t,e.partsUtc)),nh=new Map,rh={day:`numeric`,month:`numeric`,year:`numeric`,era:`short`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},ih=e=>{let t=e.resolvedOptions().timeZone,n=nh.get(t);if(n!==void 0)return n;let r=Object.create(Im);return r.id=t,r.format=e,nh.set(t,r),r},ah=e=>{let t=nh.get(e);if(t!==void 0)return t;try{let t=ih(new Intl.DateTimeFormat(`en-US`,{...rh,timeZone:e}));return nh.set(e,t),t}catch{throw new jp(`Invalid time zone: ${e}`)}},oh=e=>{let t=Object.create(Lm);return t.offset=e,t},sh=Yi(ah),ch=/^(?:GMT)?[+-]/,lh=e=>{if(ch.test(e)){let t=wh(e);return t===null?b():x(oh(t))}return sh(e)},uh=y(Bm,(e,t,n)=>Zi(sh(t),t=>th(e,t,n))),dh=e=>new Date(e.epochMilliseconds),fh=e=>{if(e._tag===`Utc`)return new Date(e.epochMilliseconds);if(e.zone._tag===`Offset`)return new Date(e.epochMilliseconds+e.zone.offset);if(e.adjustedEpochMilliseconds!==void 0)return new Date(e.adjustedEpochMilliseconds);let t=!1,n=e.zone.format.formatToParts(e.epochMilliseconds).filter(e=>e.type===`era`?(t=e.value===`BC`,!1):e.type!==`literal`),r=Number(n[2].value),i=new Date(0);return i.setUTCFullYear(t?1-r:r,Number(n[0].value)-1,Number(n[1].value)),i.setUTCHours(Number(n[3].value),Number(n[4].value),Number(n[5].value),n[6]?.type===`fractionalSecond`?Number(n[6].value):(e.epochMilliseconds%1e3+1e3)%1e3),e.adjustedEpochMilliseconds=i.getTime(),i},ph=e=>fh(e).getTime()-gh(e),mh=e=>{let t=Math.abs(e),n=Math.floor(t/36e5),r=Math.round(t%36e5/6e4);return r===60&&(n+=1,r=0),`${e<0?`-`:`+`}${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`},hh=e=>mh(ph(e)),gh=e=>e.epochMilliseconds,_h=e=>({millisecond:e.getUTCMilliseconds(),second:e.getUTCSeconds(),minute:e.getUTCMinutes(),hour:e.getUTCHours(),day:e.getUTCDate(),weekDay:e.getUTCDay(),month:e.getUTCMonth()+1,year:e.getUTCFullYear()}),vh=e=>e._tag===`Utc`?yh(e):(e.partsAdjusted===void 0&&(e.partsAdjusted=kh(e,_h)),e.partsAdjusted),yh=e=>(e.partsUtc===void 0&&(e.partsUtc=Ah(e,_h)),e.partsUtc),bh=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},xh=864e5,Sh=(e,t,n)=>{if(t._tag===`Offset`)return Rm(e-t.offset,t);let r=Th(e-xh,e,t),i=Th(e+xh,e,t);if(r===i)return Rm(e-r,t);let a=r<i,o=r-i;if(a){if(Th(e-i,e,t)===i)return Rm(e-i,t);let a=Rm(e-r,t);if(e!==fh(a).getTime())switch(n){case`reject`:{let n=new Date(e).toISOString();throw RangeError(`Gap time: ${n} does not exist in time zone ${t.id}`)}case`earlier`:return Rm(e-i,t);case`compatible`:case`later`:return a}return a}if(Th(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||Th(e-r+o,e+o,t)===r)return Rm(e-r,t);if(n===`reject`){let n=new Date(e).toISOString();throw RangeError(`Ambiguous time: ${n} occurs twice in time zone ${t.id}`)}}return Rm(e-i,t)},Ch=/([+-])(\d{2}):?(\d{2})$/,wh=e=>{let t=Ch.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},Th=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=wh(r);return i===null?ph(Rm(t,n)):i},Eh=y(Bm,(e,t,n)=>{if(e._tag===`Utc`){let n=dh(e);return t(n),Gm(n.getTime())}let r=fh(e),i=new Date(r.getTime());return t(i),Sh(i.getTime(),e.zone,n?.disambiguation??`compatible`)}),Dh=y(2,(e,t)=>Oh(e,e=>{let n=new Date(e);return t(n),n.getTime()})),Oh=y(2,(e,t)=>{let n=t(gh(e));return e._tag===`Utc`?Gm(n):Rm(n,e.zone)}),kh=y(2,(e,t)=>t(fh(e))),Ah=y(2,(e,t)=>t(dh(e))),jh=y(2,(e,t)=>{let n=Dh(e,e=>{t.milliseconds&&e.setTime(e.getTime()+t.milliseconds),t.seconds&&e.setTime(e.getTime()+t.seconds*1e3),t.minutes&&e.setTime(e.getTime()+t.minutes*60*1e3),t.hours&&e.setTime(e.getTime()+t.hours*60*60*1e3)});return!t.days&&!t.weeks&&!t.months&&!t.years?n:Eh(n,e=>{if(t.days&&e.setUTCDate(e.getUTCDate()+t.days),t.weeks&&e.setUTCDate(e.getUTCDate()+t.weeks*7),t.months){let n=e.getUTCDate();e.setUTCMonth(e.getUTCMonth()+t.months+1,0),n<e.getUTCDate()&&e.setUTCDate(n)}if(t.years){let n=e.getUTCDate(),r=e.getUTCMonth();e.setUTCFullYear(e.getUTCFullYear()+t.years,r+1,0),n<e.getUTCDate()&&e.setUTCDate(n)}})}),Mh=y(2,(e,t)=>{let n={};for(let e in t)n[e]=-1*t[e];return jh(e,n)}),Nh=e=>dh(e).toISOString(),Ph=e=>{let t=fh(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${hh(e)}`},Fh=e=>e.zone._tag===`Offset`?Ph(e):`${Ph(e)}[${e.zone.id}]`;globalThis.Number;var Ih=Mi;globalThis.String;var Lh=e=>e.toLowerCase(),Rh=e=>e.length>0,zh=`~effect/Cron`;function Bh(e){return{tz:e.tz,and:e.and,seconds:mo(e.seconds),minutes:mo(e.minutes),hours:mo(e.hours),days:mo(e.days),months:mo(e.months),weekdays:mo(e.weekdays)}}var Vh={[zh]:zh,[on](e){return Hh(e)&&og(this,e)},[Bt](){return ht(Vt(this.tz),Wt(Vt(this.and)),Wt(Qt(mo(this.seconds))),Wt(Qt(mo(this.minutes))),Wt(Qt(mo(this.hours))),Wt(Qt(mo(this.days))),Wt(Qt(mo(this.months))),Wt(Qt(mo(this.weekdays))))},toObject(){return Bh(this)},toString(){return`Cron(${An(Bh(this))})`},toJSON(){let e=Bh(this);return e._id=`Cron`,e},[Bn](){return this.toJSON()},pipe(){return at(this,arguments)}},Hh=e=>It(e,zh),Uh=e=>{let t=Object.create(Vh);t.seconds=Gh.seconds(e.seconds??[0]),t.minutes=Gh.minutes(e.minutes),t.hours=Gh.hours(e.hours),t.days=Gh.days(e.days),t.months=Gh.months(e.months),t.weekdays=Gh.weekdays(e.weekdays),t.and=e.and===!0,t.tz=Ki(e.tz);let n=Array.from(t.seconds),r=Array.from(t.minutes),i=Array.from(t.hours),a=Array.from(t.days),o=Array.from(t.months),s=Array.from(t.weekdays);return t.first={second:n[0]??0,minute:r[0]??0,hour:i[0]??0,day:a[0]??1,month:(o[0]??1)-1,weekday:s[0]??0},t.last={second:n[n.length-1]??59,minute:r[r.length-1]??59,hour:i[i.length-1]??23,day:a[a.length-1]??31,month:(o[o.length-1]??12)-1,weekday:s[s.length-1]??6},t.next={second:qh.next.second(n),minute:qh.next.minute(r),hour:qh.next.hour(i),day:qh.next.day(a),month:qh.next.month(o),weekday:qh.next.weekday(s)},t.prev={second:qh.prev.second(n),minute:qh.prev.minute(r),hour:qh.prev.hour(i),day:qh.prev.day(a),month:qh.prev.month(o),weekday:qh.prev.weekday(s)},t},Wh=(e,t,n,r=e=>e)=>i=>{let a=[];for(let o of i){if(!Number.isInteger(o)||o<t||o>n)throw RangeError(`${e} must contain only integers between ${t} and ${n}`);a.push(r(o))}return new Set(Oo(a,Ih))},Gh={seconds:Wh(`seconds`,0,59),minutes:Wh(`minutes`,0,59),hours:Wh(`hours`,0,23),days:Wh(`days`,1,31),months:Wh(`months`,1,12),weekdays:Wh(`weekdays`,0,7,e=>e===7?0:e)},Kh=(e,t)=>n=>{let r=Array(e).fill(void 0);if(n.length===0)return r;let i;if(t===`next`){let t=n.length-1;for(let a=e-1;a>=0;a--){for(;t>=0&&n[t]>=a;)i=n[t--];r[a]=i}}else{let t=0;for(let a=0;a<e;a++){for(;t<n.length&&n[t]<=a;)i=n[t++];r[a]=i}}return r},qh={prev:{second:Kh(60,`prev`),minute:Kh(60,`prev`),hour:Kh(24,`prev`),day:Kh(32,`prev`),month:Kh(13,`prev`),weekday:Kh(7,`prev`)},next:{second:Kh(60,`next`),minute:Kh(60,`next`),hour:Kh(24,`next`),day:Kh(32,`next`),month:Kh(13,`next`),weekday:Kh(7,`next`)}},Jh=`~effect/Cron/CronParseError`,Yh=class extends qs(`CronParseError`){[Jh]=Jh},Xh=(e,t)=>{let n=e.trim().split(/\s+/).filter(Rh);if(n.length!==5&&n.length!==6)return Ka(new Yh({message:`Invalid number of segments in cron expression`,input:e}));n.length===5&&n.unshift(`0`);let[r,i,a,o,s,c]=n;return to({tz:t===void 0||Vm(t)?Ga(t):qa(lh(t),()=>new Yh({message:`Invalid time zone in cron expression`,input:t})),seconds:pg(r,sg),minutes:pg(i,cg),hours:pg(a,lg),days:pg(o,ug),months:pg(s,dg),weekdays:pg(c,fg)}).pipe(Qa(({tz:e,seconds:t,minutes:n,hours:r,days:i,months:a,weekdays:o})=>Uh({tz:e,seconds:t.values,minutes:n.values,hours:r.values,days:i.values,months:a.values,weekdays:o.values,and:(i.wildcard||o.wildcard)&&i.values.size!==0&&o.values.size!==0})))},Zh=(e,t)=>eo(Xh(e,t)),Qh=(e,t)=>{let n=Zm(t,{timeZone:Ji(e.tz)}).pipe(vh);return e.seconds.size!==0&&!e.seconds.has(n.second)||e.minutes.size!==0&&!e.minutes.has(n.minute)||e.hours.size!==0&&!e.hours.has(n.hour)||e.months.size!==0&&!e.months.has(n.month)?!1:e.days.size===0&&e.weekdays.size===0?!0:e.and?(e.days.size===0||e.days.has(n.day))&&(e.weekdays.size===0||e.weekdays.has(n.weekDay)):e.weekdays.size===0?e.days.has(n.day):e.days.size===0?e.weekdays.has(n.weekDay):e.days.has(n.day)||e.weekdays.has(n.weekDay)},$h=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0)).getUTCDate(),eg=(e,t)=>ng(e,t,`next`),tg=(e,t)=>ng(e,t,`prev`),ng=(e,t,n)=>{let r=Ji(e.tz),i=Zm(t??new Date,{timeZone:r}),a=n===`prev`,o=a?-1:1,s=e[n],c=a?e.last:e.first,l=a?(e,t)=>e<t:(e,t)=>e>t,u=r!==void 0&&Hm(r)&&r.id===`UTC`,d=u?mt:e=>{let t=Zm(e,{timeZone:i.zone,adjustForTimeZone:!0,disambiguation:a?`later`:void 0}).pipe(fh),n=e.getTime()-t.getTime();(a?n!==0:n>0)&&e.setTime(a?t.getTime():e.getTime()+n)},f=a||u?dt:e=>Zm(e,{timeZone:i.zone,adjustForTimeZone:!0}).epochMilliseconds<=i.epochMilliseconds;return dh(Eh(i,t=>{let n=a&&t.getUTCMilliseconds()>0?0:o;t.setUTCSeconds(t.getUTCSeconds()+n,0);for(let n=0;n<1e4;n++){if(e.seconds.size!==0){let e=t.getUTCSeconds(),n=s.second[e];if(n===void 0){t.setUTCMinutes(t.getUTCMinutes()+o,c.second),d(t);continue}if(l(n,e)){t.setUTCSeconds(n),d(t);continue}}if(e.minutes.size!==0){let e=t.getUTCMinutes(),n=s.minute[e];if(n===void 0){t.setUTCHours(t.getUTCHours()+o,c.minute,c.second),d(t);continue}if(l(n,e)){t.setUTCMinutes(n,c.second),d(t);continue}}if(e.hours.size!==0){let e=t.getUTCHours(),n=s.hour[e];if(n===void 0){t.setUTCDate(t.getUTCDate()+o),t.setUTCHours(c.hour,c.minute,c.second),d(t);continue}if(l(n,e)){t.setUTCHours(n,c.minute,c.second),d(t);continue}}if(e.weekdays.size!==0||e.days.size!==0){if(e.and){let n=e.days.size===0||e.days.has(t.getUTCDate()),r=e.weekdays.size===0||e.weekdays.has(t.getUTCDay());if(!n||!r){t.setUTCDate(t.getUTCDate()+o),t.setUTCHours(c.hour,c.minute,c.second),d(t);continue}}else{let n=a?-1/0:1/0,r=a?-1/0:1/0;if(e.weekdays.size!==0){let e=t.getUTCDay(),r=s.weekday[e];n=r===void 0?a?c.weekday-7-e:7-e+c.weekday:r-e}if(e.days.size!==0&&n!==0){let e=t.getUTCDate(),n=s.day[e];if(n===void 0){if(a){let e=new Date(t);e.setUTCDate(0);let n=s.day[e.getUTCDate()];if(n===void 0&&(e.setUTCDate(0),n=s.day[e.getUTCDate()]),n===void 0)throw Error(`Unable to find cron date`);e.setUTCDate(n),r=(e.getTime()-t.getTime())/864e5}else r=$h(t)-e+c.day}else r=!a&&n>$h(t)?$h(t)-e+c.day:n-e}let i=a?Math.max(n,r):Math.min(n,r);if(i!==0){t.setUTCDate(t.getUTCDate()+i),t.setUTCHours(c.hour,c.minute,c.second),d(t);continue}}}if(e.months.size!==0){let n=t.getUTCMonth()+1,r=s.month[n],i=n=>{let r=$h(new Date(Date.UTC(t.getUTCFullYear(),n+1,0)));return e.days.size!==0&&e.weekdays.size===0?a?s.day[r]??r:c.day:a?r:1};if(r===void 0){t.setUTCFullYear(t.getUTCFullYear()+o),t.setUTCMonth(c.month,i(c.month)),t.setUTCHours(c.hour,c.minute,c.second),d(t);continue}if(l(r,n)){let e=r-1;t.setUTCMonth(e,i(e)),t.setUTCHours(c.hour,c.minute,c.second),d(t);continue}}if(f(t))t.setUTCSeconds(t.getUTCSeconds()+1),n=-1;else return}throw Error(`Unable to find cron date`)}))},rg=ni((e,t)=>sn(e.tz,t.tz)&&e.and===t.and&&ag(e.seconds,t.seconds)&&ag(e.minutes,t.minutes)&&ag(e.hours,t.hours)&&ag(e.days,t.days)&&ag(e.months,t.months)&&ag(e.weekdays,t.weekdays)),ig=oi(ii()),ag=(e,t)=>ig(mo(e),mo(t)),og=y(2,(e,t)=>rg(e,t)),sg={min:0,max:59},cg={min:0,max:59},lg={min:0,max:23},ug={min:1,max:31},dg={min:1,max:12,aliases:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12}},fg={min:0,max:7,normalize:e=>e===7?0:e,aliases:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}},pg=(e,t)=>{let n=new Set,r=e.split(`,`),i=mg(r[0]),a=i[0]===`*`,o=t.normalize??(e=>e),s=a&&(i[1]===void 0||i[1]===1)?mt:e=>{n.add(o(e))};for(let n=0;n<r.length;n++){let a=r[n],[o,c]=n===0?i:mg(a);if(c!==void 0){if(!Number.isInteger(c))return Ka(new Yh({message:`Expected step value to be a positive integer`,input:e}));if(c<1)return Ka(new Yh({message:`Expected step value to be greater than 0`,input:e}));if(c>t.max)return Ka(new Yh({message:`Expected step value to be less than or equal to ${t.max}`,input:e}))}if(o===`*`){if(n===0&&(c===void 0||c===1))continue;for(let e=t.min;e<=t.max;e+=c??1)s(e)}else{let[n,r]=hg(o,t.aliases);if(!Number.isInteger(n))return Ka(new Yh({message:`Expected a positive integer`,input:e}));if(n<t.min||n>t.max)return Ka(new Yh({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(r===void 0)for(let e=n;e<=(c===void 0?n:t.max);e+=c??1)s(e);else{if(!Number.isInteger(r))return Ka(new Yh({message:`Expected a positive integer`,input:e}));if(r<t.min||r>t.max)return Ka(new Yh({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(n>r)return Ka(new Yh({message:`Invalid value range`,input:e}));for(let e=n;e<=r;e+=c??1)s(e)}}}return Ga({values:n,wildcard:a})},mg=e=>{let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(t+1);return[e.slice(0,t),_g.test(n)?Number(n):NaN]}return[e,void 0]},hg=(e,t)=>{let n=e.indexOf(`-`);return n===-1?[gg(e,t),void 0]:[gg(e.slice(0,n),t),gg(e.slice(n+1),t)]};function gg(e,t){return t?.[Lh(e)]??(_g.test(e)?Number(e):NaN)}var _g=/^\d+$/,vg=y(2,(e,t)=>zu(e,Sg,e=>t(e))),yg=e=>e.reasons.some(bg),bg=e=>e._tag===`Fail`&&kp(e.error),xg=e=>{let t,n=!1;for(let r of e.reasons)bg(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Ka(e):n?Ka(gp(e.reasons.filter(e=>!bg(e)))):Ga(t)},Sg=e=>{let t=xg(e);return Xa(t)?t:Ga(t.success.value)},Cg=e=>{let t=xg(e);return Xa(t)?Np(t.failure):Mp(t.success.value)},wg=y(2,(e,t)=>td(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=xg(e);return Xa(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Tg=`~effect/Schedule`,Eg=Va(`effect/Schedule/CurrentMetadata`,{defaultValue:lt({input:void 0,output:void 0,duration:bs,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})}),Dg={[Tg]:{_Out:ct,_In:ct,_Env:ct},pipe(){return at(this,arguments)}},Og=e=>It(e,Tg),kg=e=>{let t=Object.create(Dg);return t.step=e,t},Ag=()=>{let e=0,t,n;return(r,i)=>{n===void 0&&(n=r);let a=r-n,o=t===void 0?0:r-t;return t=r,{input:i,attempt:++e,start:n,now:r,elapsed:a,elapsedSincePrevious:o}}},jg=e=>kg(du(e,e=>{let t=Ag();return(n,r)=>e(t(n,r))})),Mg=e=>Iu(e.step,e=>_l(()=>vl(e))),Ng=e=>Gf(t=>du(Mg(e),e=>{let n=Ag();return r=>xl(()=>{let i=t.currentTimeMillisUnsafe();return su(e(i,r),([e,t])=>{let a=n(i,r);return a.output=e,a.duration=t,Wl(Kf(t),a)})})})),Pg=(e,t=2)=>{let n=Ds(us(e));return jg(_l(e=>{let r=ws(n*t**(e.attempt-1));return _l([r,r])}))},Fg=e=>kg(du(Mg(e),e=>(t,n)=>wg(e(t,n),{onSuccess:e=>_l([n,e[1]]),onFailure:vl,onDone:()=>Ap(n)}))),Ig=e=>{let t=us(e);return jg(_l(e=>_l([e.attempt-1,t])))},Lg=y(2,(e,t)=>kg(du(Mg(e),e=>{let n=Ag();return(r,i)=>su(e(r,i),e=>{let[a,o]=e,s=t({...n(r,i),output:a,duration:o});return su(ur(s)?s:_l(s),t=>t?_l(e):Ap(a))})}))),Rg=Ig(bs),zg=(e,t,n)=>kd(r=>su(n?.local?hm(t,fm(),r):gm(t,r),t=>Mu(e,t))),Bg=y(e=>ur(e[0]),(e,t,n)=>Ca(t)?Mu(e,t):zg(e,Array.isArray(t)?wm(...t):t,n)),Vg=y(3,(e,t,n)=>su(Ng(t),t=>{let r=Eg.defaultValue(),i,a=zu(xl(()=>Nu(e,Eg,r)),Fc,e=>(i=e,su(t(e),e=>(r=e,a))));return vg(a,e=>Yn(()=>n(i,e)))})),Hg=y(2,(e,t)=>Vg(e,typeof t==`function`?t(ct):Og(t)?t:Wg(t),yl)),Ug=Fg(Rg),Wg=e=>{let t=e.schedule?Fg(e.schedule):Ug;return e.while&&(t=Lg(t,({input:t})=>{let n=e.while(t);return ur(n)?n:_l(n)})),e.until&&(t=Lg(t,({input:t})=>{let n=e.until(t);return ur(n)?du(n,e=>!e):_l(!n)})),e.times!==void 0&&(t=Lg(t,({attempt:t})=>_l(t<=e.times))),t},Gg=`~effect/MutableHashMap`,Kg={[Gg]:Gg,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${An(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:Vn(Array.from(this))}},[Bn](){return this.toJSON()},pipe(){return at(this,arguments)}},qg=()=>{let e=Object.create(Kg);return e.backing=new Map,e.buckets=new Map,e},Jg=y(2,(e,t)=>{if(e.backing.has(t))return x(e.backing.get(t));if(Yg(t))return b();let n=Vt(t),r=e.buckets.get(n);return r===void 0?b():Xg(e,r,t)}),Yg=e=>typeof e!=`object`&&typeof e!=`function`,Xg=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(sn(n,t[r])){let n=t[r];return x(e.backing.get(n))}return b()},Zg=y(2,(e,t)=>C(Jg(e,t))),Qg=y(3,(e,t,n)=>{if(e.backing.has(t)||Yg(t))return e.backing.set(t,n),e;let r=Vt(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=$g(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),$g=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(sn(t,e[n]))return e[n]},e_=y(2,(e,t)=>{if(Yg(t))return e.backing.delete(t),e;let n=Vt(t),r=e.buckets.get(n);if(r===void 0)return e;for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i===t||sn(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),t_=ur,n_=$d,r_=tf,i_=kl,a_=Al,T=_l,o_=wl,s_=xl,c_=bl,l_=Dl,u_=Nl,d_=Pl,E=Fl,f_=yl,p_=vl,m_=Tl,h_=El,g_=Ol,__=Ur,v_=Sl,D=su,y_=uu,b_=nu,x_=ru,S_=ed,C_=$u,w_=ld,T_=du,E_=Wl,D_=tu,O_=iu,k_=Bu,A_=qu,j_=Ju,M_=Iu,N_=Vu,P_=Yu,F_=Zu,I_=Wu,L_=Hu,R_=Hg,z_=Qu,B_=Kf,V_=au,H_=ou,U_=lf,W_=sd,G_=td,K_=ku,q_=ju,J_=Bg,Y_=Mu,X_=Eu,Z_=Du,Q_=Nu,$_=Ad,ev=Bd,tv=Fd,nv=Ld,rv=Md,iv=Pd,av=Ud,ov=Wd,sv=zd,cv=Gd,lv=Qd,uv=Fu,O=Lf,dv=Rf,fv=Nf,pv=If,mv=Ff,hv=ff,gv=pf,_v=gf,vv=mf,yv=vf,bv=xf,xv=bf,Sv=Il,k=zl,Cv=cp(`Warn`),wv=cp(`Error`),A=cp(`Info`),j=cp(`Debug`),Tv=fu,Ev=pu,Dv=mu,Ov=lu,kv=Vl,Av=`~effect/BigDecimal`,jv={[Av]:Av,[Bt](){let e=zv(this);return Wt(Jt(String(e.value)),qt(e.scale))},[on](e){return Mv(e)&&Wv(this,e)===0},toString(){return`BigDecimal(${Kv(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Bn](){return this.toJSON()},pipe(){return at(this,arguments)}},Mv=e=>It(e,Av),Nv=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(jv);return n.value=e,n.scale=t,n},Pv=(e,t)=>{let n=Nv(e,t);return n.normalized=n,n},Fv=BigInt(0),Iv=BigInt(1),Lv=BigInt(10),Rv=Pv(Fv,0),zv=e=>{if(e.normalized===void 0){if(e.value===Fv)e.normalized=Rv;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=Pv(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Bv=100,Vv=[Iv],Hv=(e,t)=>e===t?0:e<t?-1:1,Uv=(e,t)=>{let n=`${e.value<Fv?-e.value:e.value}`,r=`${t.value<Fv?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Fv)return i<Fv?-1:1;let a=Math.max(n.length,r.length);return ji(n.padEnd(a,`0`),r.padEnd(a,`0`))},Wv=(e,t)=>{if(e.scale===t.scale)return Hv(e.value,t.value);let n=Gv(e),r=Gv(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>Bv)return n===-1?Uv(t,e):Uv(e,t);let o=Vv[a]??=Lv**BigInt(a);return i>0?Hv(e.value,t.value*o):Hv(e.value*o,t.value)},Gv=e=>e.value===Fv?0:e.value<Fv?-1:1,Kv=e=>{let t=zv(e);if(Math.abs(t.scale)>=16)return qv(t);let n=t.value<Fv,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},qv=e=>{if(Jv(e))return`0e+0`;let t=zv(e),n=`${t.value}`,r=t.value<Fv?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Jv=e=>e.value===Fv,Yv=globalThis.BigInt,Xv=e=>e>Yv(2**53-1)||e<Yv(-(2**53-1))?b():x(Number(e)),Zv=BigInt(1),Qv=BigInt(1e3),$v=BigInt(1024),ey=[{symbol:`B`,factor:Zv,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:Qv,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:Qv**BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:Qv**BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:Qv**BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:Qv**BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:Qv**BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:Qv**BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:Qv**BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:Qv**BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:Qv**BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],ty=[ey[0],{symbol:`KiB`,factor:$v,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:$v**BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:$v**BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:$v**BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:$v**BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:$v**BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:$v**BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:$v**BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}];[...ey,...ty.slice(1)];var ny=Xv,ry=e=>Xi(ny(e),()=>Error(`ByteSize exceeds Number.MAX_SAFE_INTEGER: ${e}`)),iy=zm,ay=Um,oy=Km,sy=qm,cy=Qm,ly=$m,uy=eh,dy=sh,fy=uh,py=dh,my=fh,hy=gh,gy=Mh,_y=Nh,vy=Fh,yy=e=>xy(typeof e==`string`?Sy.encode(e):e),by=e=>{let t=Cy(e),n=t.length;if(n%4!=0)return Ka(new Ys({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return Ka(new Ys({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=Ey(t.charCodeAt(e))<<18|Ey(t.charCodeAt(e+1))<<12|Ey(t.charCodeAt(e+2))<<6|Ey(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return Ga(r)}catch(e){return Ka(new Ys({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},xy=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=wy[e[r-2]>>2],n+=wy[(e[r-2]&3)<<4|e[r-1]>>4],n+=wy[(e[r-1]&15)<<2|e[r]>>6],n+=wy[e[r]&63];return r===t+1&&(n+=wy[e[r-2]>>2],n+=wy[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=wy[e[r-2]>>2],n+=wy[(e[r-2]&3)<<4|e[r-1]>>4],n+=wy[(e[r-1]&15)<<2],n+=`=`),n},Sy=new TextEncoder,Cy=e=>e.replace(/[\n\r]/g,``),wy=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ty=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)Ty[wy.charCodeAt(e)]=e;Ty[61]=0;var Ey=e=>{if(e>=Ty.length||Ty[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Ty[e]},Dy=`~effect/http/Cookies`,Oy=`~effect/http/Cookies/Cookie`,ky={[Dy]:Dy,...Un,toJSON(){return{_id:`effect/Cookies`,cookies:co(this.cookies,e=>e.toJSON())}},pipe(){return at(this,arguments)}},Ay=e=>{let t=Object.create(ky);return t.cookies=e,t},jy=e=>{let t={};for(let n of e)Xn(t,n.name,n);return Ay(t)},My=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=Ny(e.trim());t&&n.push(t)}return jy(n)};function Ny(e){let t=e.split(`;`).map(e=>e.trim()).filter(e=>e!==``);if(t.length===0)return;let n=t[0].indexOf(`=`);if(n===-1)return;let r=t[0].slice(0,n);if(!Py.test(r))return;let i=t[0].slice(n+1),a=Iy(i);if(t.length===1)return Object.assign(Object.create(Fy),{name:r,value:a,valueEncoded:i});let o={};for(let e=1;e<t.length;e++){let n=t[e],r=n.indexOf(`=`),i=r===-1?n:n.slice(0,r).trim(),a=r===-1?void 0:n.slice(r+1).trim();switch(i.toLowerCase()){case`domain`:{if(a===void 0)break;let e=a.trim().replace(/^\./,``);e&&(o.domain=e);break}case`expires`:{if(a===void 0)break;let e=new Date(a);isNaN(e.getTime())||(o.expires=e);break}case`max-age`:{if(a===void 0)break;let e=parseInt(a,10);isNaN(e)||(o.maxAge=Ts(e));break}case`path`:if(a===void 0)break;a[0]===`/`&&(o.path=a);break;case`priority`:if(a===void 0)break;switch(a.toLowerCase()){case`low`:o.priority=`low`;break;case`medium`:o.priority=`medium`;break;case`high`:o.priority=`high`}break;case`httponly`:o.httpOnly=!0;break;case`secure`:o.secure=!0;break;case`partitioned`:o.partitioned=!0;break;case`samesite`:if(a===void 0)break;switch(a.toLowerCase()){case`lax`:o.sameSite=`lax`;break;case`strict`:o.sameSite=`strict`;break;case`none`:o.sameSite=`none`}}}return Object.assign(Object.create(Fy),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}var Py=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Fy={[Oy]:Oy,...Un,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}},Iy=e=>{try{return decodeURIComponent(e)}catch{return e}},Ly=new WeakMap,Ry=e=>{if(Ly.has(e))return Ly.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},zy=`~effect/Redacted`,By=e=>It(e,zy),Vy=(e,t)=>{let n=Object.create(Hy);return t?.label&&(n.label=t.label),Ly.set(n,e),n},Hy={[zy]:{_A:e=>e},label:void 0,...cr,toJSON(){return this.toString()},toString(){return`<redacted${Ct(this.label)?`:`+this.label:``}>`},[Bt](){return Vt(Ly.get(this))},[on](e){return By(e)&&sn(Ly.get(this),Ly.get(e))}},Uy=Ry,Wy=e=>ni((t,n)=>e(Uy(t),Uy(n))),Gy=Symbol.for(`~effect/http/Headers`),Ky=Object.defineProperties(Object.create(null),{[Gy]:{value:Gy},[Cn]:{value(e){return nb(this,Na(e,ib))}},toJSON:{value(){return Tn(this)}},[on]:{value(e){return Jy(this,e)}},[Bt]:{value(){return Xt(this)}},toString:{value:Un.toString},[Bn]:{value:Un[Bn]}}),qy=e=>Object.assign(Object.create(Ky),e),Jy=fo(ii()),Yy=Object.create(Ky),Xy=e=>{if(e===void 0)return Yy;if(Symbol.iterator in e){let t=Object.create(Ky);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(Ky);for(let[n,r]of Object.entries(e))Array.isArray(r)?t[n.toLowerCase()]=r.join(`, `):r!==void 0&&(t[n.toLowerCase()]=r);return t},Zy=e=>Object.setPrototypeOf(e,Ky),Qy=y(3,(e,t,n)=>{let r=qy(e);return r[t.toLowerCase()]=n,r}),$y=y(2,(e,t)=>qy({...e,...Xy(t)})),eb=y(2,(e,t)=>{let n=qy(e);return Object.assign(n,t),n}),tb=y(2,(e,t)=>{let n=qy(e);return delete n[t.toLowerCase()],n}),nb=y(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=Vy(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=Vy(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),rb=(e,t)=>{let n=e.toLowerCase();for(let r=0;r<t.length;r++){let i=t[r];if(typeof i==`string`){if(i.toLowerCase()===n)return!0}else if(e.search(i)!==-1)return!0}return!1},ib=Va(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),ab=e=>typeof e==`string`?e:Uy(e),ob=`~effect/http/UrlParams`,sb=e=>It(e,ob),cb={...cr,[ob]:ob,[Symbol.iterator](){return this.params[Symbol.iterator]()},[Cn](e){return{_id:`UrlParams`,params:Object.fromEntries(xb(this,Na(e,jb)))}},toJSON(){return Tn(this)},[on](e){return pb(this,e)},[Bt](){return Qt(this.params.flat())}},lb=e=>{let t=Object.create(cb);return t.params=e,t},ub=e=>{if(sb(e))return e;let t=db(e),n=[];for(let e=0;e<t.length;e++)if(Array.isArray(t[e][0])){let[r,i]=t[e];n.push([`${r[0]}[${r.slice(1).join(`][`)}]`,i])}else n.push(t[e]);return lb(n)},db=e=>{let t=typeof e[Symbol.iterator]==`function`?mo(e):Object.entries(e),n=[];for(let[e,r]of t)if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]!==void 0&&n.push([e,fb(r[t])]);else if(typeof r==`object`&&r&&!By(r)){let t=db(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,fb(r)]);return n},fb=e=>By(e)?e:String(e),pb=ni((e,t)=>mb(e.params,t.params)),mb=Vo(ro([ii(),Sn()])),hb=lb([]),gb=y(2,(e,t)=>lb(t(e.params))),_b=y(2,(e,t)=>{let n=ub(t).params.slice(),r=new Set;for(let e=0;e<n.length;e++)r.add(n[e][0]);for(let t=0;t<e.params.length;t++)r.has(e.params[t][0])||n.push(e.params[t]);return lb(n)}),vb=y(2,(e,t)=>gb(e,vo(ub(t).params))),yb=e=>new URLSearchParams(ub(e).params.map(([e,t])=>[e,ab(t)])).toString(),bb=e=>{let t={};for(let[n,r]of e.params){let e=ab(r);if(!Object.hasOwn(t,n))Xn(t,n,e);else{let r=t[n];typeof r==`string`?Xn(t,n,[r,e]):r.push(e)}}return t},xb=y(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Sb(e,n)?Vy(t):t])}),Sb=rb,Cb=(e,t=Ab())=>{e.includes(`@`)&&(e=Db(e));let n=e.indexOf(`?`);if(n===-1||t.length===0)return e;let r=e.indexOf(`#`);if(r!==-1&&r<n)return e;let i=r===-1?e.length:r;return e.slice(0,n+1)+Ob(e.slice(n+1,i),t)+e.slice(i)},wb=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,Tb=/[/\\?#]/,Eb=/[/?#]/,Db=e=>{let t=``,n=[];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===9||i===10||i===13||t===``&&i<=32||(t+=e[r],n.push(r))}let r=wb.exec(t);if(r===null)return e;let i=r[0].length,a=r[1]!==void 0||!r[0].includes(`:`),o=t.slice(i),s=o.search(a?Tb:Eb),c=(s===-1?o:o.slice(0,s)).lastIndexOf(`@`);return c===-1?e:e.slice(0,n[i])+`REDACTED:REDACTED`+e.slice(n[i+c])},Ob=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Sb(kb(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),kb=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},Ab=()=>Na(globalThis[`~effect/Fiber/currentFiber`]?.context??Ta(),jb),jb=Va(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function Mb(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Nb(e){return t=>Mb(t)?.[e]}var Pb=`~structural`,Fb=`~sentinels`,Ib=`~constructor`,Lb=gt(e=>{let t=Mb(e)?.identifier;return typeof t==`string`?t:e.getExpected(Lb)}),Rb=Symbol(),zb=Mp,Bb=zb(Rb),Vb=zb(Rb),Hb=e=>e===Rb?b():x(e),Ub=e=>e._tag===`None`?Bb:zb(e.value),Wb=`~effect/SchemaIssue/Issue`;function Gb(e){return It(e,Wb)&&e[Wb]===Wb}function Kb(e){return Object.hasOwn(e,`input`)}var qb=class{[Wb]=Wb;constructor(e,t){t?.reportInput===!0&&e!==Rb&&(this.input=e)}},Jb=class extends qb{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},Yb=class extends qb{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},Xb=class extends qb{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},Zb=class extends qb{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},Qb=class extends qb{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},$b=class extends qb{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ex=class extends qb{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},tx=class extends qb{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function nx(e,t,n,r,i){return new $b(e,[new Xb([t],n)],r,i)}var rx=class extends qb{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},ix=class extends qb{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ax=class extends qb{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function ox(e,t,n){if(Gb(e))return e;if(typeof e==`string`)return new tx({message:e},t,n);let r=typeof e.issue==`string`?new tx({message:e.issue},t,n):e.issue;return new Xb(e.path,r)}function sx(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new tx(void 0,t,n):ox(e,t,n)}function cx(e,t,n,r){return Array.isArray(t)?bo(t)?t.length===1?ox(t[0],n,r):new $b(e,zo(t,e=>ox(e,n,r)),n,r):void 0:sx(t,n,r)}var lx=e=>{let t=xx(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return mx(Lb(e.ast),e);case`InvalidValue`:{let t=px(e);if(t!==void 0)return mx(t,e);let n=fx(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=fx(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=fx(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},ux=e=>xx(e)??xx(e.issue);function dx(e){return t=>({issues:gx(t,[],e?.leafHook??lx,e?.checkHook??ux)})}function fx(e){return Kb(e)?An(e.input):void 0}function px(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function mx(e,t){let n=fx(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function hx(e,t){let n=t(e);if(n!==void 0||e.issue._tag!==`InvalidValue`)return n;let r=px(e.issue);return r===void 0?mx(_x(e.filter),e):mx(r,e.issue)}function gx(e,t,n,r,i){switch(e._tag){case`Filter`:return gx(e.issue,t,n,r,i??hx(e,r));case`Encoding`:return gx(e.issue,t,n,r,i);case`Pointer`:return gx(e.issue,[...t,...e.path],n,r,i);case`Composite`:case`AnyOf`:return e._tag===`Composite`||e.issues.length>0?e.issues.flatMap(e=>gx(e,t,n,r,i)):[{path:t,message:i??xx(e)??mx(Lb(e.ast),e)}];default:return[{path:t,message:i??n(e)}]}}function _x(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>_x(e)).join(` & `)}}function vx(){return e=>bx(e,``)}var yx=vx();function bx(e,t,n){let r;switch(e._tag){case`Filter`:return bx(e.issue,t,n??hx(e,ux));case`Encoding`:return bx(e.issue,t,n);case`Pointer`:return bx(e.issue,t+Nn(e.path),n);case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>bx(e,t,n)).join(`
|
|
14
|
+
`);r=n??xx(e)??mx(Lb(e.ast),e);break;default:r=n??lx(e)}return t?`${r}\n at ${t}`:r}function xx(e){if(e._tag===`Pointer`||e._tag===`Composite`)return;if(e._tag===`Encoding`)return xx(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function Sx(e){let t;for(let n of e.reasons){if(!hp(n)||!Gb(n.error))return;t??=n.error}return t}function Cx(e,t){let n=Sx(e);if(n===void 0)throw Error(t,{cause:e});return n}var wx=e=>Object.assign(Object.create(ot),e);function Tx(e){return Nx((t,n)=>f_(e(t,n)))}function Ex(e){return Tx((t,n)=>{let r={message:e(t)};return C(t)?new rx(r,t.value,n):new rx(r)})}var Dx=Ex(()=>`Encoding is not supported`),Ox=wx({_tag:`Passthrough`});function kx(){return Ox}function Ax(e){return wx({_tag:`Transform`,transform:e})}function jx(e){return wx({_tag:`TransformEffect`,transform:e})}function Mx(e){return wx({_tag:`TransformOptional`,transform:e})}function Nx(e){return wx({_tag:`TransformOptionalEffect`,transform:e})}function Px(){return Mx(()=>b())}function Fx(e){return Nx(t=>{let n=na(t,At);return C(n)?T(n):Tv(e,x)})}function Ix(){return Ax(globalThis.String)}function Lx(){return Ax(globalThis.Number)}function Rx(){return jx((e,t)=>{try{return T(globalThis.BigInt(e))}catch{return f_(new tx({expected:`a value that can be converted to a bigint`},e,t))}})}function zx(e){return jx((t,n)=>g_({try:()=>JSON.parse(t,e?.reviver),catch:()=>new tx({expected:`a valid JSON string`},t,n)}))}function Bx(e){return jx((t,n)=>g_({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new tx({expected:`a JSON-serializable value`},t,n)}))}function Vx(){return Ax(yy)}function Hx(){return jx((e,t)=>Ev(v_(by(e)),()=>new tx({expected:`a valid Base64 string`},e,t)))}var Ux=class extends st{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Ux(this.encode,this.decode)}},Wx=`~effect/SchemaTransformation/Transformation`,Gx=class extends st{[Wx]=Wx;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Gx(this.encode,this.decode)}};function Kx(e){return It(e,Wx)&&e[Wx]===Wx}var qx=e=>Kx(e)?e:new Gx(e.decode,e.encode);function Jx(e){return new Gx(jx(e.decode),jx(e.encode))}function Yx(e){return new Gx(Ax(e.decode),Ax(e.encode))}function Xx(e){return new Gx(Mx(e.decode),Mx(e.encode))}var Zx=new Gx(kx(),kx());function Qx(){return Zx}var $x=new Gx(Lx(),Ix()),eS=new Gx(Rx(),Ix()),tS=e=>Pt(e)&&typeof e.message==`string`,nS=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:oS(e.cause)}):Error(e.message);return typeof e.name==`string`&&e.name!==`Error`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t},rS=e=>{try{let t=Ln(e);return t===void 0?An(e):JSON.parse(t)}catch{return An(e)}},iS=(e,t,n)=>{let r={name:e.name,message:typeof e.message==`string`?e.message:``};return t?.includeStack&&typeof e.stack==`string`&&(r.stack=e.stack),!t?.excludeCause&&e.cause!==void 0&&(r.cause=n(e.cause)),r},aS=e=>{let t=new WeakSet,n=r=>{if(Rt(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=iS(r,e,n);return t.delete(r),i}return rS(r)};return n},oS=e=>tS(e)?nS(e):e,sS=e=>Yx({decode:oS,encode:aS(e)});function cS(){return Yx({decode:qi,encode:w})}function lS(){return Xx({decode:x,encode:$i})}var uS=Jx({decode:(e,t)=>URL.canParse(e)?T(new URL(e)):f_(new tx({expected:`a valid URL string`},e,t)),encode:e=>T(e.href)}),dS=new Gx(Hx(),Vx());function fS(e){return new Gx(zx(e??{}),Bx(e))}function pS(e){return t=>t._tag===e}var mS=pS(`Declaration`),hS=pS(`Null`),gS=pS(`Void`),_S=pS(`Never`),vS=pS(`Literal`),yS=pS(`UniqueSymbol`),bS=pS(`Arrays`),xS=pS(`Objects`),SS=pS(`Union`),CS=pS(`Suspend`),wS=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},TS={},ES=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},DS=`~effect/Schema`,OS=class{[DS]=DS;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},kS=class extends OS{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>{if(t===Rb)return Bb;e??=this.run(this.typeParameters);try{return e(t,this,n)}catch(e){return h_(e)}}}_rebuild(e,t,n,r,i){let a=ew(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new kS(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},AS=new class extends OS{_tag=`Null`;getParser(){return vw(this,null)}getExpected(){return`null`}},jS=class extends OS{_tag=`Undefined`;getParser(){return vw(this,void 0)}toCodecJson(){return HC(this,[MS])}getExpected(){return`undefined`}},MS=new wS(AS,new Gx(Ax(()=>void 0),Ax(()=>null))),NS=new jS,PS=new class extends OS{_tag=`Void`;getParser(){let e=zb(void 0);return t=>t===Rb?Bb:e}toCodecJson(){return HC(this,[MS])}getExpected(){return`void`}},FS=new class extends OS{_tag=`Never`;getParser(){return yw(this,Mt)}getExpected(){return`never`}},IS=new class extends OS{_tag=`Unknown`;getParser(){return yw(this,Nt)}getExpected(){return`unknown`}},LS=class extends OS{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${An(e)}`);this.literal=e}getParser(){return vw(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?RS(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:RS(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function RS(e){let t=globalThis.String(e.literal);return HC(e,[new wS(new LS(t),new Gx(Ax(()=>e.literal),Ax(()=>t)))])}var zS=new class extends OS{_tag=`String`;getParser(){return yw(this,Ct)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&jw(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},BS=class extends OS{_tag=`Number`;getParser(){return yw(this,wt)}matchKey(e,t){return this._match(Cw,e,t)}matchPart(e,t){return this._match(Sw,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:jw(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(VS(this.checks,`effect/schema/isFinite`)||VS(this.checks,`effect/schema/isInt`))?this:HC(this,[LC])}toCodecStringTree(){return this.toCodecJson()===this?HC(this,[Ew]):HC(this,[Dw])}getExpected(){return`number`}};function VS(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&VS(e.checks,t))}var HS=new BS,US=new class extends OS{_tag=`Boolean`;getParser(){return yw(this,Tt)}getExpected(){return`boolean`}},WS=new class extends OS{_tag=`BigInt`;getParser(){return yw(this,Et)}matchPart(e,t){if(!Ow.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:jw(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return HC(this,[Aw])}getExpected(){return`bigint`}},GS=class extends OS{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(lw(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(lw(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new Qb(n,t[o],i),a=new Xb([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return f_(new $b(n,[a],t,i))}return e.issues?f_(new $b(n,e.issues,t,i)):zb(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:[],issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:rf(t.concurrency),f=d===1?JS(i,e,0,u):YS(i,e,{concurrency:d,end:u});if(!f)return c(i);if(cu(f))return Ov(f,()=>c(i));let p=!0;return s_(()=>p?(p=!1,D(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===Rb)return Bb;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):f_(new ex(n,e,a))}catch(e){return h_(e)}}}_rebuild(e,t,n){let r=ew(this.elements,e),i=ew(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new GS(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function KS(e,t,n,r){if(n._tag===`Failure`)return XS(e,e.ast,r,n);let i=n===Vb?t:n[nr];if(i!==Rb)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(lw(t.ast))return;let n=new Xb([r],new Zb(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Pp(new $b(e.ast,[n],e.input,e.options))}}var qS={onItem(e,t,n){let r=n<e.len?t:Rb;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:KS},JS=af()(qS),YS=sf()(qS),XS=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Sx(r.cause);if(i===void 0)return Np(Cp(r.cause,r=>new $b(t,[new Xb([n],r)],e.input,e.options)));let a=new Xb([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Pp(new $b(t,[a],e.input,e.options))},ZS=`[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?`;function QS(e,t,n=TS){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(bw(mw(t)))}var $S=class{name;type;constructor(e,t){this.name=e,this.type=t}};function eC(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(eC);default:return!1}}function tC(e){let t=WC(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(tC);default:return!1}}function nC(e){return eC(e)&&tC(e)}var rC=class{parameter;type;constructor(e,t){if(!nC(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,lw(t)&&!_w(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},iC=class extends OS{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return yw(n,jt);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(bw(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return XS(t,n,i,s)??Fp;let c=s===Vb?o:s[nr];if(a!==Rb&&c!==Rb){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Fp;Xn(t.out,a,c)}return Fp},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!cu(t))return D(w_(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return XS(e,n,r,a)??Fp;let o=a===Vb?r:a[nr],s=e.input[r],l=i.parserValue(s,e.options);return cu(l)?t(e,r,o,s,l):D(w_(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return cu(a)?t(e,n,n,i,a):D(w_(a),r=>t(e,n,n,i,r))},u=i?sf()({onItem:(e,[t,n])=>n.is.parameter===zS?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return kv(function*(t,d){if(t===Rb)return Rb;if(typeof t!=`object`||!t||Array.isArray(t))return yield*f_(new ex(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},h=d.errors===`all`,g=d.onExcessProperty===`error`,_=d.concurrency===void 0?1:rf(d.concurrency),v=i&&g?n.indexSignatures.map(e=>QS(f,e.parameter,d)):void 0;if(g){let r=v?new Set(e):e;if(v)for(let e of v)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new Qb(n,f[a],d),r=new Xb([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*f_(new $b(n,[r],t,d))}}}if(r){let e=_===1?sC(m,a):cC(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===zS?l:c,r=v?.[e]??(t.is.parameter===zS?Object.keys(f):QS(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!cu(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Lo();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===zS?Object.keys(f):QS(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:_});t&&(yield*t)}return m.issues?yield*f_(new $b(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return D(w_(n),n=>{let i={...e,out:{...e.out}},o=aC(i,r,n);if(o)return o;let s=()=>zb(i.out),c=sC(i,a.slice(t+1));return c?Ov(c,s):s()})};return(e,t)=>{if(e===Rb)return Bb;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&rf(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return f_(new ex(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=xC(i,s),l=c?i[s]:Rb,d=n.parser(l,t);if(!cu(d))return u(o,e,d);if(d===Vb){c&&Xn(a,s,l);continue}let f=aC(o,n,d);if(f)return f}}catch(e){return h_(e)}return zb(a)}}_rebuild(e,t,n,r){let i=ew(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new $S(t.name,n)}),a=ew(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new rC(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new iC(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function aC(e,t,n){if(n._tag===`Failure`)return XS(e,e.ast,t.name,n);if(n===Vb)return;let r=n[nr];if(r!==Rb)Xn(e.out,t.name,r);else if(delete e.out[t.name],!lw(t.type)){let n=new Xb([t.name],new Zb(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Pp(new $b(e.ast,[n],e.input,e.options))}}var oC={onItem(e,t){if(!xC(e.input,t.name))return t.parser(Rb,e.options);let n=e.input[t.name];return Xn(e.out,t.name,n),t.parser(n,e.options)},step:aC},sC=af()(oC),cC=sf()(oC);function lC(e,t){return e?t?[...e,...t]:e:t}function uC(e,t,n){return new iC(Reflect.ownKeys(e).map(t=>new $S(t,e[t].ast)),[],n,t)}function dC(e){return e.ast}function fC(e,t=void 0){return new GS(!1,e.map(e=>e.ast),[],void 0,t)}function pC(e,t,n){return new CC(e.map(dC),t,void 0,n)}function mC(e,t){if(e.encoding||t.some(e=>e.encoding))throw Error(`StructWithRest does not support encodings`);let n=e.propertySignatures,r=e.indexSignatures,i=e.checks;for(let e of t){for(let t of e.propertySignatures)if(n.some(e=>e.name===t.name))throw Error(`Duplicate identifier: ${JSON.stringify(t.name)}. ts(2300)`);n=n.concat(e.propertySignatures),r=r.concat(e.indexSignatures),i=lC(i,e.checks)}return new iC(n,r,void 0,i)}var hC=_t(e=>{for(;;){if(CS(e))return IS;let t=e.encoding;if(!t)return e.recur?.(hC,ct)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==ct))return IS;e=t[t.length-1].to}});function gC(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(gC)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function _C(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Fb];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!lw(t)){if(vS(t))return[{key:e.name,literal:t.literal}];if(yS(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!lw(e)){if(vS(e))return[{key:t,literal:e.literal}];if(yS(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>_C(hC(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return _C(e.thunk())}}var vC=new WeakMap,yC=Object.freeze([]),bC=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,xC=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function SC(e){let t=vC.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=hC(c);if(_S(l))continue;if(vS(l)||yS(l)){a??=new Map;let e=vS(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=_C(l);if(u.length){n??=new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=gC(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??yC);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??yC;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(Ft(e)){let n=xC(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??yC;if(t)return o}return yC}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=bC(t);if(!Ft(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=xC(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=xC(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=xC(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(bC(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return vC.set(e,t),t}var CC=class extends OS{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===Rb)return Bb;let i=(o??=SC(n.types))(e,r);if(i.length===0)return f_(new ix(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:cu(r)?wC(n,r.cause,e,t):TC(n,r,e,t)}return EC(n,a,i,e,t)}}_rebuild(e,t,n){let r=ew(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new CC(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=mw(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(vS);if(t.length>0)return`${AC(n.isMutable)}[ ${t.map(t=>e(t)+jC(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>vS(e.type));if(t.length>0)return`{ ${t.map(t=>`${AC(t.type.context?.isMutable)}${Mn(t.name)}${jC(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function wC(e,t,n,r){let i=Sx(t);return i?Pp(new ix(e,[i],n,r)):Np(t)}function TC(e,t,n,r){return M_(t,t=>wC(e,t,n,r))}function EC(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=OC(a,n);if(!o)return a.out?a.out:f_(new ix(e,a.issues??[],r,i));if(cu(o))return DC(o,a);let s=!0;return s_(()=>s?(s=!1,DC(o,a)):EC(e,t,n,r,i))}function DC(e,t){return Ov(e,e=>t.out===Vb?T(t.input):t.out?t.out:f_(new ix(t.ast,t.issues??[],t.input,t.options)))}var OC=af()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Sx(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),Pp(new ax(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Fp}}}),kC=new CC([new LS(`Infinity`),new LS(`-Infinity`),new LS(`NaN`)]);function AC(e){return e?``:`readonly `}function jC(e){return e?`?`:``}var MC=class extends st{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new MC(this.run,{...this.annotations,...e},this.aborted)}abort(){return new MC(this.run,this.annotations,!0)}and(e,t){return new NC([this,e],t)}},NC=class extends st{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new NC(this.checks,{...this.annotations,...e})}and(e,t){return new NC([this,e],t)}};function PC(e,t,n=!1){return new MC((t,n,r)=>cx(n,e(t,n,r),t,r),t,n)}function FC(e){return PC(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}var IC=qC(HS,[FC()]),LC=new wS(new CC([IC,kC]),new Gx(Lx(),Ax(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function RC(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return PC(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var zC=new WeakMap;function BC(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&zC.set(n,VC(e)),n}function VC(e){let t=zC.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return zC.set(e,n),n}function HC(e,t){return e.encoding===t?e:BC(e,{encoding:t})}function UC(e,t){if(e.context===t)return e;let n=VC(e);return n.context===t&&n.encoding===e.encoding?n:BC(e,{context:t})}function WC(e){return e.encoding?WC(e.encoding[e.encoding.length-1].to):e}function GC(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return KC(e,_o(e.checks.slice(0,-1),n.annotate(t)))}return BC(e,{annotations:{...e.annotations,...t}})}function KC(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:BC(e,{checks:t})}function qC(e,t){return KC(e,lC(e.checks,t))}function JC(e,t){let n=t(e.to);return n===e.to?e:new wS(n,e.transformation)}function YC(e,t){let n=e,r=n[n.length-1],i=JC(r,t);return i===r?e:_o(e.slice(0,e.length-1),i)}function XC(e){return t=>t.encoding?HC(t,YC(t.encoding,e)):t}function ZC(e,t){return XC(e=>UC(e,t))(e)}function QC(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:HC(r,YC(r.encoding,n))}return e(r)}return _t(n)}function $C(e,t,n){let r=new wS(e,t);return HC(n,n.encoding?[...n.encoding,r]:[r])}function ew(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function tw(e,t){return UC(e,e.context?new ES(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new ES(!1,!1,void 0,t))}var nw=_t(e=>rw(UC(e,e.context?e.context.isOptional===!1?new ES(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new ES(!0,!1)))),rw=XC(nw),iw=gt(e=>nw(new CC([e,NS])));function aw(e,t){return UC(e,e.context?new ES(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new ES(!1,!1,t))}function ow(e,t,n){return $C(e,n,t)}function sw(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:Ot(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function cw(e,t){let{literals:n,parameters:r}=sw(e);return new iC(n.map(e=>new $S(e,t)),r.map(e=>new rC(e,t)))}function lw(e){return e.context?.isOptional??!1}function uw(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(uw)}function dw(e){function t(e){return uw(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return yo(n)?n:void 0}function fw(e){let t=!0;function n(e){return t=t&&!e.encoding&&!CS(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var pw=_t(e=>{let t=VC(e);if(t!==e){let n=pw(t);return n===t&&e.encoding===void 0?e:UC(n,e.context)}let n=`recur`in e?e.recur(pw):e;if(`encodingChecks`in n&&n.encodingChecks){let t=fw(e)?n.encodingChecks:bS(n)||xS(n)||mS(n)&&n.typeParameters.length>0?dw(n.encodingChecks):void 0;return BC(n,{encodingChecks:void 0,checks:lC(n.checks,t)})}return n}),mw=_t(e=>pw(gw(e)));function hw(e,t){let n=t,r=n.length,i=n[r-1],a=[new wS(gw(HC(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new wS(gw(n[e-1].to),n[e].transformation.flip()));let o=gw(i.to);return o.encoding?HC(o,[...o.encoding,...a]):HC(o,a)}var gw=gt(e=>{if(e.encoding)return hw(e,e.encoding);let t=VC(e);if(t!==e){let n=gw(t);return n===t?e:UC(n,e.context)}return`flip`in e?e.flip(gw):`recur`in e?e.recur(gw):e});function _w(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(_w);default:return!1}}function vw(e,t){let n=t===0?Vb:zb(t);return(r,i)=>r===Rb?Bb:r===t?n:f_(new ex(e,r,i))}function yw(e,t){return(n,r)=>n===Rb?Bb:t(n)?Vb:f_(new ex(e,n,r))}var bw=QC(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(bw)}}),xw=QC(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(xw)}}),Sw=new globalThis.RegExp(`^${ZS}$`),Cw=new globalThis.RegExp(`^(?:${ZS}|Infinity|-Infinity|NaN)$`);function ww(e){return RC(Sw,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:Sw.source}),...e})}var Tw=qC(zS,[ww()]),Ew=new wS(Tw,$x),Dw=new wS(new CC([Tw,kC]),$x),Ow=new globalThis.RegExp(`^-?\\d+$`);function kw(e){return RC(Ow,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Ow.source}),...e})}var Aw=new wS(qC(zS,[kw({expected:`a string representing a bigint`})]),eS);function jw(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=jw(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new Jb(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Mw(e){if(!mS(e))return;let t=e.annotations?.[Ib];return kt(t)?t(e.typeParameters):void 0}var Nw=Mb,Pw=Nb;function Fw(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function Iw(e){return e===void 0||typeof e==`string`}function Lw(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function Rw(e){return Lw(e,Fw)}var zw=new kS([],()=>(e,t,n)=>Rw(e)?Vb:f_(new ex(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>Uw}),Bw=new wS(zw,Qx()),Vw=new wS(new CC([new GS(!1,[],[zw]),new iC([],[new rC(zS,zw)])]),Qx());function Hw(e){return Lw(e,Iw)}var Uw=new wS(new kS([],()=>(e,t,n)=>Hw(e)?Vb:f_(new ex(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),Qx()),Ww=(e,t,n)=>e===Vb?n(t):Ov(e,n);function Gw(e){let t=Kw(e);return(e,n,r)=>{try{return t(e,n,r)}catch(e){return h_(e)}}}function Kw(e){if(e._tag===`Middleware`)return(t,n,r)=>qw(t===Vb?e.decode(zb(Hb(n)),r):e.decode(Tv(t,Hb),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===Vb?zb(t):e;case`Transform`:{let e=e=>e===Rb?Bb:zb(t.transform(e));return(t,n)=>Ww(t,n,e)}case`TransformOptional`:{let e=e=>Ub(t.transform(Hb(e)));return(t,n)=>Ww(t,n,e)}case`TransformEffect`:return(e,n,r)=>Ww(e,n,e=>e===Rb?Bb:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>Ww(e,n,e=>qw(t.transform(Hb(e),r)))}}var qw=e=>Ov(e,Ub),Jw=(e,t,n,r)=>M_(r,r=>m_(()=>Cp(r,r=>new Yb(e,r,t,n))));function Yw(e,t){let n=Gw(e.link.transformation),r;return(i,a)=>{if(i===Rb)return Bb;if(e.isConstructed(i))return Vb;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function Xw(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==Rb&&r!==void 0)return t(r,i);let a=n;if(cu(a)&&a._tag===`Success`){let e=t(a[nr],i);return e===Vb?a:e}return Ov(Jw(e,r,i,a),e=>{let n=t(e,i);return n===Vb?zb(e):n})}}function Zw(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:Xw(e,n)}function Qw(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Mw(e):void 0,o=a?Yw(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>Gw(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);try{if(u&&!n.disableChecks){if(cu(r)){if(r._tag===`Success`){let i=r===Vb?t:r[nr];if(t!==Rb&&i!==Rb){let i=jw(u,t,void 0,e,n);i&&(r=f_(new $b(e,i,t,n)))}}}else r=D(r,r=>{if(t!==Rb&&r!==Rb){let r=jw(u,t,void 0,e,n);if(r)return f_(new $b(e,r,t,n))}return T(r)})}if(s&&!n.disableChecks){if(cu(r)){if(r._tag===`Success`){let i=r===Vb?t:r[nr];if(i===Rb)return r;let a=jw(s,i,void 0,e,n);a&&(r=f_(new $b(e,a,i,n)))}}else r=D(r,t=>{if(t!==Rb){let r=jw(s,t,void 0,e,n);if(r)return f_(new $b(e,r,t,n))}return T(t)})}return r}catch(e){return h_(e)}},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[nr],o=t(a,r)):o=Ov(o,e=>{let n=t(e,r);return n===Vb?zb(e):n})}if(o._tag===`Success`){let e=o[nr],t=p(e,r);return t===Vb?o:t}return o=Jw(e,n,r,o),Ov(o,e=>{let t=p(e,r);return t===Vb?zb(e):t})}:p}var $w=Symbol(),eT=new WeakMap,tT=e=>aT(e).parser,nT=e=>aT(e).makeEffect,rT=e=>Zw(e,nT),iT=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=Qw(this.ast,tT)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=Qw(this.ast,nT,rT)}};function aT(e){let t=eT.get(e);if(t!==void 0)return t;let n=new iT(e);return eT.set(e,n),n}function oT(e){let t=e.ast,n;return(e,r)=>(n??=bT(ET,pw(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function sT(e){let t=oT(e);return(e,n)=>{let r=xv(t(e,n));return Ip(r)?x(r.value):(Cx(r.cause,`Option adapter can only return none for schema issues`),b())}}function cT(e){return wT(pw(e.ast))}function lT(e){return dT(e.ast)}function uT(e){{let t=xT(vT(e));return e=>{let n=t(e,TS);return Ip(n)?!0:(Cx(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function dT(e){let t=pw(e),n=e=>(n=uT(t),n(e));return e=>n(e)}function fT(e,t){let n=vT(e.ast);return t===void 0?n:(e,r)=>n(e,gT(t,r))}function pT(e,t){return ST(fT(e,t))}var mT=pT;function hT(e,t){let n=vT(gw(e.ast));return t===void 0?n:(e,r)=>n(e,gT(t,r))}var gT=(e,t)=>t?{...e,...t}:e,_T=e=>e===Rb?f_(new tx):T(e);function vT(e){return bT(TT,e)}function yT(e,t){return e===Vb?T(t):cu(e)?e[`~effect/Effect/args`]===Rb?_T(Rb):e:Ov(e,_T)}function bT(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??TS);return a===Vb?T(r):cu(a)?a[`~effect/Effect/args`]===Rb?_T(Rb):a:Ov(a,_T)}}function xT(e){return(t,n)=>xv(e(t,n))}function ST(e){let t=xT(e);return(e,n)=>{let r=t(e,n);return Ip(r)?x(r.value):(Cx(r.cause,`Option adapter can only return none for schema issues`),b())}}function CT(e,t){let n=xv(e);if(Ip(n))return n.value;let r=Cx(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function wT(e){let t,n;return(r,i)=>{t??=aT(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??TS,o=t.make;if(o!==void 0&&r!==Rb){let e;try{e=o(r,a)}catch(e){throw Cx(vp(e),`Constructor adapter can only throw schema issues`),e}if(e!==$w&&e!==Rb)return e}return CT(yT((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var TT=e=>aT(e).parser,ET=e=>aT(e).makeEffect,DT=`~effect/Schema/Schema`,OT=Symbol(),kT={[DT]:DT,get make(){let e=cT(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=oT(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=sT(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return at(this,arguments)},annotate(e){return this.rebuild(GC(this.ast,e))},annotateKey(e){return this.rebuild(tw(this.ast,e))},check(...e){return this.rebuild(qC(this.ast,e))},rebuild(e){return AT(e,this[OT])}};function AT(e,t){function n(){}let r=Object.setPrototypeOf(n,kT);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[OT]=t,r.ast=e,r}function jT(e){return AT(MT(e.ast),{schema:e})}var MT=QC(e=>{let t=VC(e);if(t!==e){let n=MT(t);if(n===t)return e;if(n.encoding===void 0)return UC(n,e.context)}let n=LT(e,MT),r=e.context;return n===e||r===void 0?n:ZC(n,NT(r))});function NT(e){return e.constructorDefault===void 0?e:new ES(e.isOptional,e.isMutable,void 0,e.annotations)}function PT(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function FT(e){return t=>{let n=[...t].sort((t,n)=>e(mw(t))-e(mw(n)));return n.some((e,n)=>e!==t[n])?n:t}}var IT=FT(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function LT(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!kt(n))return HC(e,[Bw]);let r=n(e.typeParameters.map(e=>AT(mw(e))));return r===void 0?e:HC(e,[JC(r,t)])}case`Unknown`:return HC(e,[Bw]);case`ObjectKeyword`:return HC(e,[Vw]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return PT(e),e.recur(t,xw);case`Union`:{let n=IT(e.types);return n===e.types?e.recur(t):new CC(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}function RT(e){return AT(WT(e.ast),{schema:e})}var zT=FT(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function BT(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>AT(t(mw(e)))),i=e.annotations?.toCodecStringTree;if(kt(i)){let n=i(r);return n===void 0?e:HC(e,[JC(n,t)])}let a=e.annotations?.toCodecJson,o=kt(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(kt(s)?s(r):void 0);return c===void 0?n(e):HC(e,[JC(c,t)])}case`Null`:return HC(e,[VT]);case`Boolean`:return HC(e,[HT]);case`Unknown`:case`ObjectKeyword`:return HC(e,[Uw]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return PT(e),e.recur(t,xw);case`Union`:{let n=zT(e.types);return n===e.types?e.recur(t):new CC(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}var VT=new wS(new LS(`null`),new Gx(Ax(()=>null),Ax(()=>`null`))),HT=new wS(new CC([new LS(`true`),new LS(`false`)]),new Gx(Ax(e=>e===`true`),Ix())),UT=new Gx(Ax(e=>typeof e==`string`?[e]:e),kx()),WT=QC(e=>{let t=BT(e,WT,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?ZC(t,NT(e.context)):t},{stopAt:e=>e.transformation===UT});function GT(e){return Ip(e)?e.value:{issues:[{message:Op(e.cause)}]}}function KT(e,t){let n=fT(e),r={errors:`all`,...t?.parseOptions},i=dx(t);return qT(e,{validate:e=>{let t=new Vs(`sync`),a=_v(W_(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?GT(o):new Promise(e=>{a.addObserver(t=>{e(GT(t))})})}})}function qT(e,t){let n={version:1,vendor:`effect`,...Object.hasOwn(e,`~standard`)?e[`~standard`]:void 0,...t},r=typeof e==`function`?Function.prototype.bind.call(e,void 0):Object.create(Object.getPrototypeOf(e));return Object.defineProperties(r,{...Object.getOwnPropertyDescriptors(e),ast:{value:e.ast,enumerable:!0,configurable:!0},"~standard":{value:n,writable:!0,enumerable:!0,configurable:!0}})}var JT=y(2,(e,t)=>({...e,...t})),YT=y(2,(e,t)=>ZT(e,(e,n)=>[Object.hasOwn(t,e)?t[e]:e,n])),XT=e=>e;function ZT(e,t){let n={};for(let r of Reflect.ownKeys(e)){if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;let i=t(r,e[r]);if(i){let[e,t]=i;Xn(n,e,t)}}return n}var QT=`~effect/Schema/SchemaError`;function $T(e){return It(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...Un}),{...Un},{...Un},{...Un},{...Un},{...Un},{...Un},{...Un};var eE=DT;function tE(){return(e,t,n)=>bE(new kS(e.map(dC),e=>t(e.map(e=>bE(e))),n))}function nE(e,t){return tE()([],()=>(t,n,r)=>e(t)?T(t):f_(new ex(n,t,r)),t)}var rE=class extends qs(`SchemaError`){[QT]=QT;constructor(e){let t=Kn();qn(0);try{super({issue:e})}finally{qn(t)}}get message(){return yx(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[Bn](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function iE(e){return $T(e)}function aE(e){return cu(e)?oE(e):M_(e,e=>m_(()=>Cp(e,e=>new rE(e))))}function oE(e){return Ip(e)?e:Np(Cp(e.cause,e=>new rE(e)))}function sE(e,t){let n;for(let r of e.reasons){if(!hp(r)||!iE(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function cE(e){let t=xv(e);if(Ip(t))return t.value;throw sE(t.cause,`Sync adapter can only throw schema errors`)}function lE(e,t){return KT(e,t)}var uE=lT;function dE(e,t){let n=fT(e,t);return(e,t)=>aE(n(e,t))}var fE=dE,pE=pT,mE=mT;function hE(e,t){let n=dE(e,t);return(e,t)=>cE(n(e,t))}function gE(e,t){let n=hT(e,t);return(e,t)=>aE(n(e,t))}var _E=gE;function vE(e,t){let n=gE(e,t);return(e,t)=>cE(n(e,t))}var yE=vE,bE=AT;function xE(e){return It(e,eE)&&e[eE]===eE}var SE=XT(e=>bE(nw(e.ast),{schema:e})),CE=XT(e=>{let t=GE(e);return bE(iw(e.ast),{schema:t})}),wE=XT(e=>bE(pw(e.ast),{schema:e})),TE=XT(e=>bE(mw(e.ast),{schema:e}));function EE(e){let t=bE(new LS(e),{literal:e,transform(n){return t.pipe(KE(EE(n),{decode:Ax(()=>n),encode:Ax(()=>e)}))}});return t}var DE=bE(FS),OE=bE(IS),kE=bE(AS),AE=bE(NS),M=bE(zS),jE=bE(HS),ME=bE(US),NE=bE(WS),PE=bE(PS);function FE(e,t){return bE(e,{fields:t,mapFields(e,t){let n=e(this.fields);return FE(uC(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function N(e){return FE(uC(e,void 0),e)}var IE=e=>typeof e==`symbol`?e:globalThis.String(e);function LE(e){return function(t){let n={},r=Object.create(null),i=Object.create(null),a=new Set;for(let o of Reflect.ownKeys(t.fields)){let s=TE(t.fields[o]),c=Object.hasOwn(e,o),l=c?e[o]:o,u=IE(l);if(a.has(u))throw new globalThis.Error(`Duplicate encoded keys: ${Mn(l)}`);a.add(u),Xn(n,l,s),c&&(r[o]=l,i[l]=o)}return N(n).pipe(KE(t,Yx({decode:YT(i),encode:YT(r)})))}}function RE(e,t){return bE(cw(e.ast,t.ast),{key:e,value:t})}function zE(e,t){return bE(mC(e.ast,t.map(dC)),{schema:e,records:t})}function BE(e,t){return bE(e,{elements:t,mapElements(e,t){let n=e(this.elements);return BE(fC(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function VE(e){return BE(fC(e),e)}var P=XT(e=>bE(new GS(!1,[],[e.ast]),{value:e})),HE=XT(e=>bE(new GS(!1,[e.ast],[e.ast]),{value:e}));function UE(e,t){return bE(e,{members:t,mapMembers(e,t){let n=e(this.members);return UE(pC(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function F(e,t){return UE(pC(e,t,void 0),e)}function WE(e){let t=e.map(EE);return bE(pC(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return F(e(this.members))},pick(e){return WE(e)},transform(e){return F(t.map((t,n)=>t.transform(e[n])))}})}var I=XT(e=>F([e,kE])),GE=XT(e=>F([e,AE]));function L(e){return t=>bE(t.ast,{schema:t,identifier:e})}function KE(e,t){return n=>bE(ow(n.ast,e.ast,t?qx(t):Qx()),{from:n,to:e})}function qE(){return(e,t)=>nD()(e,{decode:t,encode:Dx})}function JE(e,t){return n=>t?KE(n,t)(e):KE(n)(e)}function YE(e){return t=>bE(aw(t.ast,e),{schema:t})}function XE(e){return cu(e)&&e._tag===`Success`?e:M_(e,e=>m_(()=>Cp(e,e=>e.issue)))}function ZE(e,t){let n=t?.encodingStrategy===`omit`?Px():kx();return t=>SE(TE(t)).pipe(KE(t,{decode:Fx(XE(e)),encode:n}))}function QE(e,t){return n=>wE(n).pipe(ZE(e,t),JE(SE(n)))}function $E(e){return EE(e).pipe(YE(T(e)))}function eD(e,t){return N({_tag:$E(e),...t})}function tD(e,t){return nE(t=>t instanceof e,t)}function nD(){return(e,t)=>new wS(e.ast,qx(t))}var rD=PC;function iD(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${An(n)})`:`new RegExp(${An(n)}, ${An(r)})`;return RC(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var aD=bE(IC),oD=FC;function sD(e){let t=Li(e.order),n=e.formatter??An;return(r,i)=>rD(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function cD(e){let t=zi(e.order),n=e.formatter??An;return(r,i)=>rD(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function lD(e){let t=zi(e.order),n=Li(e.order),r=Ri(e.order),i=Ii(e.order),a=e.formatter??An;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return rD(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function uD(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${An(e)}`);return e}var dD=sD({order:Mi,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:uD(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${An(e)})`})})}),fD=cD({order:Mi,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:uD(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${An(e)})`})})}),pD=lD({order:Mi,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:uD(e.minimum),maximum:uD(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${An(e.minimum)}, maximum: ${An(e.maximum)}, exclusiveMinimum: ${An(t)}, exclusiveMaximum: ${An(n)} })`})}}});function mD(e){return rD(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>({type:`integer`,minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var R=jE.check(mD());function hD(e,t){return e=yD(e),gD(e,Math.ceil(e/2),t)}function gD(e,t,n){return rD(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Pb]:!0,arbitraryConstraint:{minLength:e},...n})}function _D(e){return gD(1,1,e)}function vD(e,t){return e=yD(e),rD(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Pb]:!0,arbitraryConstraint:{maxLength:e},...t})}function yD(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function bD(e){return rD(e=>Uo(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitraryConstraint:{uniqueBy:ct},...e})}var z=M.check(_D()),xD=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),SD=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},CD=[];function wD(e){let t=xD(e),n=CD[t];if(n!==void 0)return n;let r=oO.pipe(KE(OE,sS(SD(t))));return CD[t]=r,r}globalThis.RegExp;var TD=M.annotate({expected:`a string that will be decoded as a URL`}),ED=tD(globalThis.URL,{representation:{id:`effect/schema/URL`,payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:`URL`,toCodecJson:()=>nD()(TD,uS)}),DD=TD.pipe(KE(ED,uS)),OD=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function kD(e,t){return OD.pipe(KE(e,fS(t)))}var AD=kD(OE);globalThis.File,globalThis.URLSearchParams;var jD=M.annotate({expected:`a string that will be decoded as a finite number`}).pipe(KE(aD,$x)),MD=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),ND=tD(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>nD()(MD,dS)});function PD(e,t){return bE(tE()([e,t],([e,t])=>(n,r,i)=>{if(!mp(n))return f_(new ex(r,n,i));switch(n._tag){case`Fail`:return Dv(fT(e)(n.error,i),{onSuccess:yp,onFailure:e=>nx(r,`error`,e,n,i)});case`Die`:return Dv(fT(t)(n.defect,i),{onSuccess:bp,onFailure:e=>nx(r,`defect`,e,n,i)});case`Interrupt`:return T(n)}},{representation:{id:`effect/schema/CauseReason`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.CauseReason(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Failure<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause.Failure`,toCodec:([e,t])=>nD()(F([N({_tag:EE(`Fail`),error:e}),N({_tag:EE(`Die`),defect:t}),N({_tag:EE(`Interrupt`),fiberId:GE(aD)})]),Yx({decode:e=>{switch(e._tag){case`Fail`:return yp(e.error);case`Die`:return bp(e.defect);case`Interrupt`:return xp(e.fiberId)}},encode:e=>{switch(e._tag){case`Fail`:return{_tag:`Fail`,error:e.error};case`Die`:return{_tag:`Die`,defect:e.defect};case`Interrupt`:return{_tag:`Interrupt`,fiberId:e.fiberId}}}}))}).ast,{error:e,defect:t})}function FD(e,t){return bE(tE()([e,t],([e,t])=>{let n=P(PD(e,t));return(e,t,r)=>pp(e)?Dv(fT(n)(e.reasons,r),{onSuccess:gp,onFailure:n=>nx(t,`reasons`,n,e,r)}):f_(new ex(t,e,r))},{representation:{id:`effect/schema/Cause`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Cause(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Cause<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause`,toCodec:([e,t])=>nD()(P(PD(e,t)),Yx({decode:gp,encode:({reasons:e})=>e}))}).ast,{error:e,defect:t})}var ID=Jx({decode:(e,t)=>Vi(cy(e),{onNone:()=>f_(new tx({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>T(uy(e))}),encode:e=>T(_y(e))}),LD=-864e13,RD=864e13;function zD(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function BD(e,t){return R.check(pD({minimum:e,maximum:t}))}var VD=nE(e=>iy(e)&&ay(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=zD(e,LD,RD);return qE()(BD(t,n),Ax(sy))},toCodecJson:()=>nD()(M,ID),toFormatter:()=>e=>e.toString()}),HD=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(KE(VD,ID));function B(e){return bE(tE()([e],([e])=>(t,n,r)=>Bi(t)?S(t)?o_:Dv(fT(e)(t.value,r),{onSuccess:x,onFailure:e=>nx(n,`value`,e,t,r)}):f_(new ex(n,t,r)),{representation:{id:`effect/schema/Option`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Option(${e[0].runtime})`,Type:`Option.Option<${e[0].Type}>`,importDeclarations:[`import * as Option from "effect/Option"`]}),expected:`Option`,toCodec:([e])=>nD()(F([N({_tag:EE(`Some`),value:e}),N({_tag:EE(`None`)})]),Yx({decode:e=>e._tag===`None`?b():x(e.value),encode:e=>C(e)?{_tag:`Some`,value:e.value}:{_tag:`None`}}))}).ast,{value:e})}function UD(e){return I(e).pipe(KE(B(wE(e)),cS()))}var WD=nE(sb,{representation:{id:`effect/http/UrlParams`,payload:null},toCode:()=>({runtime:`Schema.UrlParams`,Type:`UrlParams.UrlParams`,importDeclarations:[`import * as UrlParams from "effect/http/UrlParams"`]}),expected:`UrlParams`,toEquivalence:()=>pb,toCodec:()=>nD()(P(VE([M,M])),Yx({decode:lb,encode:e=>e.params.map(([e,t])=>[e,ab(t)])}))}).pipe(KE(RE(M,F([M,HE(M)])),Yx({decode:bb,encode:ub})));function GD(e){return SE(e).pipe(KE(B(wE(e)),lS()))}function KD(e,t){let n=typeof t?.label==`string`?t.label:void 0,r=t?.disallowJsonEncode===!0,i=n===void 0?r?{disallowJsonEncode:!0}:void 0:r?{label:n,disallowJsonEncode:!0}:{label:n},a=n===void 0?void 0:fT(EE(n));return bE(tE()([e],([e])=>(t,n,r)=>By(t)?Ov(a===void 0?l_:Ev(a(t.label,r),e=>new Xb([`label`],e)),()=>Dv(fT(e)(Uy(t),r),{onSuccess:e=>Vy(e,{label:t.label}),onFailure:()=>new $b(n,[new Xb([`value`],new tx(void 0,t,r))],t,r)})):f_(new ex(n,t,r)),{representation:{id:`effect/schema/Redacted`,payload:i??null},toCode:({typeParameters:e})=>({runtime:i===void 0?`Schema.Redacted(${e[0].runtime})`:`Schema.Redacted(${e[0].runtime}, ${An(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>nD()(e,{decode:Ax(e=>Vy(e,{label:n})),encode:r?Ex(e=>`Cannot serialize Redacted`+(C(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):Ax(Uy)}),toEquivalence:([e])=>Wy(e)}).ast,{value:e})}function qD(e,t){return KE(KD(wE(e),{label:t?.label,disallowJsonEncode:t?.disallowEncode}),{decode:Ax(e=>Vy(e,{label:t?.label})),encode:t?.disallowEncode?Ex(e=>`Cannot encode Redacted`+(C(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):Ax(Uy)})(e)}var JD=globalThis.Symbol.for(`immer-draftable`),YD={};function XD(e,t,n,r,i){let a=eO(n,t,r),o=$D(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===YD?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:YD,value:i}})}static[eE]=eE;get[o](){return o}static[JD]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return at(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return cT(a(this))(e??{},t)}static makeOption(e,t){return sT(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(GC(this.ast,e))}static annotateKey(e){return this.rebuild(tw(this.ast,e))}static check(...e){return this.rebuild(qC(this.ast,e))}static extend(e){return(t,r)=>{let a=tO(t)?t:N(t),o={...n.fields,...a.fields},s=uC(o,n.ast.checks,{identifier:e});return XD(this,e,FE(qC(s,a.ast.checks),o),r,i)}}static mapFields(e,t){return n.mapFields(e,t)}};return i!==void 0&&Object.assign(s.prototype,i(t)),s}function ZD(e,t){return new e(t,{"~payload":{token:YD,value:t}})}function QD(e){return new Gx(Ax(t=>ZD(e,t)),kx())}function $D(e){return`~effect/Schema/Class/${e}`}function eO(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=$D(t),o=e=>e instanceof i||It(e,a),s=QD(i);return r=KE(bE(new kS([e.ast],()=>(e,t,n)=>o(e)?T(e):f_(new ex(t,e,n)),{identifier:t,[Ib]:([e])=>({isConstructed:o,link:new wS(e,s)}),toCodec:([e])=>new wS(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[Fb]:_C(e.ast),...n})),s)(e)}}function tO(e){return xE(e)}var V=e=>(t,n)=>XD(Gs,e,tO(t)?t:N(t),n,e=>({toString(){return`${e}(${An({...this})})`}})),H=e=>(t,n,r)=>{let i=tO(n)?n.mapFields(e=>({_tag:$E(t),...e}),{unsafePreserveChecks:!0}):eD(t,n);return V(e??t)(i,r)},nO=e=>(t,n)=>XD(Gr,e,tO(t)?t:N(t),n,e=>({name:e})),rO=e=>(t,n,r)=>{let i=tO(n)?n.mapFields(e=>({_tag:$E(t),...e}),{unsafePreserveChecks:!0}):eD(t,n);return nO(e??t)(i,r)},iO=jT,aO=RT,oO=bE(GC(zw,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),sO=RE(M,oO),cO=dl,lO=pl,uO=ml,dO=hl,fO=gl,pO=hf,mO=Tf,hO=`~effect/MutableRef`,gO={[hO]:hO,...cr,toJSON(){return{_id:`MutableRef`,current:Vn(this.current)}}},_O=e=>{let t=Object.create(gO);return t.current=e,t},vO=y(2,(e,t)=>(e.current=t,e)),yO=Symbol.for(`effect/MutableList/Empty`),bO=()=>({head:void 0,tail:void 0,length:0}),xO=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},SO=()=>({array:[],mutable:!0,offset:0,next:void 0}),CO=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=SO(),e.tail=e.tail.next):e.head=e.tail=SO(),e.tail.array.push(t),e.length++},wO=e=>{e.head=e.tail=void 0,e.length=0},TO=e=>{if(!e.head)return yO;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:wO(e):xO(e),t},EO=`~effect/Queue`,DO=`~effect/Queue/Enqueue`,OO=`~effect/Queue/Dequeue`,kO={_A:ct,_E:ct},AO={[EO]:kO,[DO]:kO,[OO]:kO,...cr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:VO(this)}}},jO=e=>Ur(t=>{let n=Object.create(AO);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=bO(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},_l(n)}),MO=e=>jO({capacity:e}),NO=y(2,(e,t)=>xl(()=>PO(e,t)?UO:e.state._tag===`Open`&&e.strategy===`suspend`?ZO(e,t):HO)),PO=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(TO(e.messages),CO(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(CO(e.messages,t),KO(e),!0):(CO(e.messages,t),qO(e),!0):!1,FO=y(2,(e,t)=>bl(()=>IO(e,t))),IO=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=wu(Br(t),WO);return e.state.offers.size===0&&e.messages.length===0?(nk(e,n),!0):(e.state={...e.state,_tag:`Closing`,exit:n},qO(e),!0)},LO=e=>bl(()=>RO(e)),RO=e=>{if(e.state._tag===`Done`)return!1;wO(e.messages);let t=e.state.offers;nk(e,e.state._tag===`Open`?GO:e.state.exit);for(let e of t)$O(e);return!0},zO=e=>JO(()=>BO(e)??nu(XO(e,()=>YO(e,1)),zO(e))),BO=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=TO(e.messages);return tk(e),Lr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=ek(e.state.offers);return tk(e),Lr(t)}},VO=e=>e.state._tag===`Done`?0:e.messages.length,HO=Lr(!1),UO=Lr(!0),WO=Vr(Qr()),GO=hu(),KO=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(bu),e.messages.length===0))break}},qO=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,KO(e)},0))},JO=Fr({op:`QueueTake`,[rr](e){let t=this[nr]();return dr(t)?t[rr](e):t}}),YO=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,XO=(e,t)=>Nl(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(bu);let r={ready:t,resume:n};return e.state.takers.add(r),bl(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),ZO=(e,t)=>Nl(n=>PO(e,t)?n(UO):QO(e,{_tag:`Single`,message:t,resume:n})),QO=(e,t)=>{if(e.state._tag!==`Open`)return $O(t);let n=e.state.offers;return n.add(t),bl(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&nk(e,e.state.exit))})},$O=e=>e._tag===`Single`?e.resume(HO):e.resume(Lr(e.remaining.slice(e.offset))),ek=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(UO),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Lr([]))),n},tk=e=>{if(e.state._tag===`Done`)return yg(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(nk(e,e.state.exit),yg(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)CO(e.messages,t.message),e.state.offers.delete(t),t.resume(UO);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;CO(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Lr([]))}let r=e.state;if(r._tag===`Done`)return yg(r.exit.cause)}return!1},nk=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},rk=e=>new ak(e),ik=(e,t,n)=>Nl(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),bl(()=>{e.waiters.delete(i)})}),ak=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=xl(()=>this.free<e?ik(this,e,t):(this.taken+=e,_l(e)));return t}takeIfAvailable(e){return xl(()=>this.free<e?_l(!1):(this.taken+=e,_l(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return Ur(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Dl))}release(e){return Ur(t=>_l(this.releaseUnsafe(t,e)))}get releaseAll(){return Ur(e=>_l(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>Qd(n=>{let r=xl(()=>this.free<e?su(n(ik(this,e,Dl)),()=>r):(this.taken+=e,Md(n(t),()=>{this.releaseUnsafe(il(),e)},!0)));return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>Qd(n=>this.free<e?wl:(this.taken+=e,Md(n(tu(t)),()=>{this.releaseUnsafe(il(),e)},!0)))}},ok=e=>bl(()=>new ak(e)),sk=`~effect/Channel`,ck=e=>It(e,sk),lk={[sk]:{_Env:ct,_InErr:ct,_InElem:ct,_OutErr:ct,_OutElem:ct},pipe(){return at(this,arguments)}},uk=e=>{let t=Object.create(lk);return t.transform=(t,n)=>M_(e(t,n),e=>T(p_(e))),t},dk=(e,t)=>uk((n,r)=>D(mk(e)(n,r),e=>t(e,r))),fk=e=>uk((t,n)=>e),pk=e=>uk(Sv(function*(t,n){let r=tm(n),i=e=>nm(r,Cg(e));return nv(yield*nv(e(t,n,r),i),i)})),mk=e=>e.transform,hk=e=>uk((t,n)=>s_(()=>mk(e())(t,n))),gk=e=>fk(T(f_(e))),_k=e=>fk(p_(e)),vk=e=>_k(vp(e)),yk=e=>uk((t,n)=>bk({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),bk=e=>{let t=e.readable.getReader(),n=e.exit??_O(void 0),r=s_(()=>n.current?n.current:G_(a_({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??p_(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Ap():T(Ro(t))}));return E_(em(e.scope,e.releaseLockOnEnd?c_(()=>t.releaseLock()):i_(()=>t.cancel().catch(e=>t.closed.then(()=>Promise.reject(e),mt))).pipe(tv(c_(()=>t.releaseLock())))),r)},xk=y(2,(e,t)=>dk(e,e=>c_(()=>{let n=0;return T_(e,e=>t(e,n++))}))),Sk=e=>e===void 0||e!==`unbounded`&&e<=1,Ck=y(e=>ck(e[0]),(e,t,n)=>Sk(n?.concurrency)?wk(e,t):Tk(e,t,n)),wk=(e,t)=>uk((n,r)=>{let i=0;return T_(mk(e)(n,r),D(e=>t(e,i++)))}),Tk=(e,t,n)=>pk(Sv(function*(r,i,a){let o=0,s=yield*mk(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:Math.min(n.concurrency,2**53-1),l=yield*MO(0);yield*em(a,LO(l));let u=vv(yield*K_()),d=pO(a);if(n.unordered){let e=rk(c),n=lt(e.release(1)),r=G_({onFailure:e=>D(FO(l,e),n),onSuccess:e=>D(NO(l,e),n)});yield*e.take(1).pipe(D(()=>s),D(e=>{let n=o++;return d(u(r(s_(()=>t(e,n))))),l_}),uv({disableYield:!0}),M_(t=>e.withPermits(c-1)(FO(l,t))),hv(a))}else{let e=yield*MO(c-2);yield*em(a,LO(e)),yield*zO(e).pipe(y_,D(e=>NO(l,e)),uv({disableYield:!0}),M_(e=>FO(l,e)),hv(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,IO(l,e.cause))};yield*s.pipe(D(i=>{if(n)return p_(n);let a=o++,s=u(s_(()=>t(i,a)));return d(s),s.addObserver(r),NO(e,lO(s))}),uv({disableYield:!0}),M_(t=>NO(e,Np(t)).pipe(b_(FO(e,t)))),hv(a))}return zO(l)})),Ek=e=>dk(e,e=>{let t,n=0;return T(s_(function r(){if(t===void 0)return D(e,e=>{switch(e.length){case 0:return r();case 1:return T(e[0]);default:return t=e,T(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),T(i)}))}),Dk=y(2,(e,t)=>dk(e,e=>T(D(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return bo(i)?T(i):D(e,n)})))),Ok=y(2,(e,t)=>uk((n,r)=>{let i=tm(r);return T_(mk(e)(n,i),e=>{let a=e.pipe(M_(e=>{if(yg(e))return p_(e);let o=i;return i=tm(r),nm(o,Np(e)).pipe(b_(mk(t(e))(n,i)),D(e=>(a=e,e)))}));return s_(()=>a)})})),kk=y(3,(e,t,n)=>Ok(e,e=>{let r=t(e);return Xa(r)?_k(r.failure):n(r.success,e)})),Ak=y(2,(e,t)=>kk(e,Fc,e=>t(e))),jk=y(e=>ck(e[0]),(e,t,n,r)=>Ak(e,e=>t(e)?n(e):r?r(e):gk(e))),Mk=y(2,(e,t)=>dk(e,e=>T(P_(e,e=>kp(e)?e:t(e))))),Nk=y(e=>ck(e[0])&&ck(e[1]),(e,t,n)=>pk(Sv(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*MO(0);yield*em(a,LO(s));let c=0;function l(e,t){if(c++,!yg(t))return FO(s,t);switch(o){case`both`:return c===2?FO(s,t):l_;case`left`:case`right`:return e===o?FO(s,t):l_;case`either`:return FO(s,t)}}let u=(e,t,n)=>mk(t)(r,n).pipe(D(e=>e.pipe(D(e=>NO(s,e)),uv)),nv(t=>rv(Cg(t),e=>nm(n,e)).pipe(G_({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),hv(a));return yield*u(`left`,e,tm(a)),yield*u(`right`,t,tm(a)),zO(s)}))),Pk=(e,t)=>uk((n,r)=>c_(()=>{let r=new TextDecoder(e,t),i={stream:!0},a=n.pipe(T_(zo(e=>r.decode(e,i))),vg(e=>{a=Ap(e);let t=r.decode();return t.length>0?T(Ro(t)):a}));return s_(()=>a)})),Fk=y(2,(e,t)=>uk((n,r)=>D(mk(e)(n,r),e=>mk(t)(e,r)))),Ik=y(2,(e,t)=>Nk(e,fk(T(D(t,Ap))),{haltStrategy:`either`})),Lk=y(2,(e,t)=>pk((n,r,i)=>$p(i,t).pipe(b_(mk(e)(n,r))))),Rk=y(2,(e,t)=>Lk(e,e=>t)),zk=(e,t,n)=>s_(()=>{let r=Zp();return vg(D(mk(e)(Ap(),r),t),n||T).pipe(iv(e=>nm(r,e)))}),Bk=y(2,(e,t)=>uk((n,r)=>T_(Y_(mk(e)(n,r),t),Y_(t)))),Vk=y(2,(e,t)=>zk(e,e=>uv(D(e,t),{disableYield:!0}))),Hk=e=>s_(()=>{let t=b();return zk(e,e=>e.pipe(D_,D(e=>(t=e,Ap()))),()=>T(t))}),Uk=(e,t)=>mk(e)(Ap(),t),Wk=(e,t)=>()=>{let n=fE(HE(e),t);return uk((e,t)=>T(D(e,e=>n(e))))},Gk=`~effect/Stream`,Kk={_R:ct,_E:ct,_A:ct},qk=function(e){this.channel=e};qk.prototype={[Gk]:Kk,pipe(){return at(this,arguments)}};var Jk=e=>new qk(e),Yk=`~effect/Stream`,Xk=e=>It(e,Yk),Zk=Jk,Qk=(e,t)=>Zk(uk((n,r)=>D(Uk(e.channel,r),e=>t(e,r)))),$k=e=>e.channel,eA=e=>{let t=Zk(hk(()=>e().channel));return tA.set(t,e),t},tA=new WeakMap,nA=e=>Zk(gk(e)),rA=e=>Zk(vk(e)),iA=e=>Zk(yk(e)),aA=y(2,(e,t)=>eA(()=>{let n=0;return Zk(xk(e.channel,zo(e=>t(e,n++))))})),oA=y(e=>Xk(e[0]),(e,t,n)=>e.channel.pipe(Ek,Ck(t,n),xk(Ro),Zk)),sA=y(2,(e,t)=>Zk(Ck(e.channel,t))),cA=y(2,(e,t)=>Zk(Dk($k(e),t))),lA=y(e=>Xk(e[0]),(e,t,n,r)=>Zk(jk($k(e),t,e=>n(e).channel,r&&(e=>r(e).channel)))),uA=y(2,(e,t)=>Zk(Mk(e.channel,t))),dA=y(2,(e,t)=>Zk(Fk(e.channel,t))),fA=y(e=>Xk(e[0]),(e,t)=>e.channel.pipe(Fk(Pk(t?.encoding)),Zk)),pA=y(2,(e,t)=>Zk(Ik(e.channel,t))),mA=y(2,(e,t)=>Zk(Rk(e.channel,t))),hA=y(2,(e,t)=>Zk(Bk(e.channel,t))),gA=e=>T_(Hk(e.channel),Zi(Co(0))),_A=y(e=>Xk(e[0]),(e,t,n)=>{let r,i,a=!1,o=mO(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=_v(Y_(Vk(dk(e.channel,e=>T(o.whenOpen(e))),e=>c_(()=>{o.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0})),t)),i.addObserver(e=>{s?.removeEventListener(`abort`,c),!a&&(e._tag===`Failure`&&s?.aborted!==!0?n.error(Tp(e.cause)):n.close())}),s!==void 0&&i.pollUnsafe()===void 0&&(s.aborted?c():s.addEventListener(`abort`,c,{once:!0}))},pull(){return new Promise(e=>{r=e,o.openUnsafe()})},cancel(){if(i)return a=!0,yv(O_(uO(i)))}},n?.strategy)}),vA=y(e=>Xk(e[0]),(e,t)=>T_(K_(),n=>_A(e,n,t))),yA=sa(`effect/Crypto`),bA=`~effect/FiberMap`,xA=e=>It(e,bA),SA={[bA]:bA,[Symbol.iterator](){return this.state._tag===`Closed`?oo():this.state.backing[Symbol.iterator]()},...cr,toJSON(){return{_id:`FiberMap`,state:this.state}}},CA=(e,t)=>{let n=Object.create(SA);return n.state={_tag:`Open`,backing:e,fibers:new Set},n.deferred=t,n},wA=()=>$_(c_(()=>CA(qg(),Bp())),e=>s_(()=>{let t=e.state;return t._tag===`Closed`?l_:(e.state={_tag:`Closed`},fO(t.fibers).pipe(Jp(e.deferred)))})),TA=-1,EA=Ns(Fs(Dp,Ps(TA))),DA=y(e=>xA(e[0]),(e,t,n,r)=>{if(e.state._tag===`Closed`){n.interruptUnsafe(TA);return}let i=Jg(e.state.backing,t);if(i._tag===`Some`){if(i.value===n)return;if(r?.onlyIfMissing===!0){n.interruptUnsafe(TA);return}}Qg(e.state.backing,t,n),e.state.fibers.add(n),i._tag===`Some`&&i.value.interruptUnsafe(TA),n.addObserver(i=>{if(e.state._tag===`Closed`)return;e.state.fibers.delete(n);let a=Jg(e.state.backing,t);C(a)&&n===a.value&&e_(e.state.backing,t),Lp(i)&&(r?.propagateInterruption===!0?!EA(i.cause):!Sp(i.cause))&&qp(e.deferred,i)})}),OA=y(2,(e,t)=>e.state._tag===`Closed`?b():Jg(e.state.backing,t)),kA=y(2,(e,t)=>s_(()=>T(OA(e,t)))),AA=y(2,(e,t)=>e.state._tag!==`Closed`&&Zg(e.state.backing,t)),jA=y(2,(e,t)=>c_(()=>AA(e,t))),MA=y(2,(e,t)=>s_(()=>{if(e.state._tag===`Closed`)return l_;let n=Jg(e.state.backing,t);return n._tag===`None`?l_:dO(n.value,TA)})),NA=function(){let e;return()=>(e===void 0&&(e=_v(ov)),e)}(),PA=function(){let e=arguments[0];if(t_(arguments[2]))return FA(e,arguments[1],arguments[2],arguments[3]);let t=arguments[1],n=arguments[2];return r=>FA(e,t,r,n)},FA=(e,t,n,r)=>__(i=>{if(e.state._tag===`Closed`)return ov;if(r?.onlyIfMissing===!0&&AA(e,t))return c_(NA);let a=uf(i,n,r?.startImmediately??!0,!0);return DA(e,t,a,r),T(a)}),IA={"~effect/Match/Matcher":{_input:ct,_filters:ct,_remaining:ct,_result:ct,_return:ct,_args:ct},_tag:`TypeMatcher`,add(e){return LA(this.select,[...this.cases,e])},pipe(){return at(this,arguments)}};function LA(e,t){let n=Object.create(IA);return n.select=e,n.cases=t,n}var RA=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),zA=y(2,(e,t)=>VA(t)(LA(ct,[]))(e)),BA=e=>t=>{let n=RA(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},VA=(e=>t=>{let n=BA(e)(t);return e=>WA(n(e))})(`_tag`),HA=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?Ga(t.evaluate(r,...n)):Ka(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return Ga(t.evaluate(r,...n))}return Ka(r)}},UA=`effect/match/Match/exhaustive: absurd`,WA=e=>{let t=HA(e);if(Ya(t)){if(Za(t))return t.success;throw Error(UA)}return(...e)=>{let n=t(...e);if(Za(n))return n.success;throw Error(UA)}},GA=zA,KA={"~effect/Ref":{_A:ct},...cr,toJSON(){return{_id:`Ref`,ref:this.ref}}},qA=e=>{let t=Object.create(KA);return t.ref=_O(e),t},JA=e=>c_(()=>qA(e)),YA=e=>c_(()=>e.ref.current),XA=y(2,(e,t)=>c_(()=>vO(e.ref,t))),ZA=y(2,(e,t)=>c_(()=>{let[n,r]=t(e.ref.current);return e.ref.current=r,n})),QA=y(2,(e,t)=>c_(()=>{e.ref.current=t(e.ref.current)})),$A=y(2,(e,t)=>c_(()=>e.ref.current=t(e.ref.current))),ej=y(2,(e,t)=>e===void 0?void 0:t(e)),tj=`~effect/SynchronizedRef`,nj={...cr,[tj]:tj,toJSON(){return{_id:`SynchronizedRef`,value:this.backing.ref.current}}},rj=e=>{let t=Object.create(nj);return t.semaphore=rk(1),t.backing=qA(e),t},ij=e=>c_(()=>rj(e)),aj=e=>e.backing.ref.current,oj=y(2,(e,t)=>e.semaphore.withPermit(s_(()=>T_(t(aj(e)),([t,n])=>(e.backing.ref.current=n,t))))),sj=M.check(iD(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,{message:`Expected a full GitHub repo name (owner/name)`})).pipe(L(`RepositoryName`)),cj=M.check(iD(/^[^\s-]\S*$/u,{message:`Expected a Git revision without whitespace or a leading dash`})).pipe(L(`RepositoryRevision`)),lj=M.check(iD(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u,{message:`Expected a 40- or 64-character lowercase Git object ID`})).pipe(L(`CommitSha`)),uj=e=>e.replaceAll(/[^A-Za-z0-9_.-]/gu,`_`),dj=e=>{let t=e.indexOf(`/`);return{owner:e.slice(0,t),name:e.slice(t+1)}},fj=e=>e.toLowerCase(),pj=z.pipe(L(`EventId`)),mj=z.pipe(L(`DedupKey`)),hj=class extends V(`Event`)({id:pj,dedupKey:mj,payload:oO,receivedAt:VD}){},gj=z.pipe(L(`LoopName`)),_j=[`none`,`required`],vj=WE(_j),yj=[`write`,`read`],bj=WE(yj),xj=class extends H(`CancelReason/OperatorCanceled`)(`OperatorCanceled`,{}){},Sj=class extends H(`CancelReason/Superseded`)(`Superseded`,{by:pj}){},Cj=class extends H(`CancelReason/Revoked`)(`Revoked`,{}){},wj=F([xj,Sj,Cj]),Tj=class extends H(`RunState/Pending`)(`Pending`,{}){},Ej=class extends H(`RunState/Waiting`)(`Waiting`,{}){},Dj=class extends H(`RunState/Queued`)(`Queued`,{}){},Oj=class extends H(`RunState/Running`)(`Running`,{}){},kj=class extends H(`RunState/Succeeded`)(`Succeeded`,{}){},Aj=class extends H(`RunState/Failed`)(`Failed`,{}){},jj=class extends H(`RunState/Canceled`)(`Canceled`,{reason:wj}){},Mj=F([Tj,Ej,Dj,Oj]),Nj=F([...Mj.members,kj,Aj,jj]),Pj=F([Tj,Ej,Dj]),Fj=F([Tj,Dj]),Ij=uE(Mj),Lj=uE(Pj),Rj=uE(Fj),zj=e=>({canApprove:e._tag===`Waiting`,canRetry:e._tag===`Failed`,canResolveFailure:e._tag===`Failed`,canCancel:Ij(e),canRunAgain:e._tag===`Succeeded`||e._tag===`Canceled`}),Bj=()=>(...e)=>e,Vj=Bj()(`Pending`,`Waiting`,`Queued`,`Running`),Hj=Bj()(`Pending`,`Waiting`,`Queued`,`Running`,`Succeeded`,`Failed`,`Canceled`),Uj=Bj()(`Pending`,`Waiting`,`Queued`),eee=e=>new Ej,Wj=e=>new Dj,Gj=e=>new Oj,Kj=e=>new kj,qj=e=>new Aj,Jj=e=>new Oj,Yj=e=>new jj({reason:new xj}),Xj=(e,t)=>new jj({reason:new Sj({by:t})}),Zj=e=>new jj({reason:new Cj}),Qj=z.pipe(L(`RunId`)),$j=class extends V(`Run`)({id:Qj,eventId:pj,loop:gj,state:Nj,openedAt:VD}){},eM=M.check(iD(/^(?:[A-Za-z_][A-Za-z0-9_.]*|list<[A-Za-z_][A-Za-z0-9_.]*>|map<[A-Za-z_][A-Za-z0-9_.]*,[A-Za-z_][A-Za-z0-9_.]*>)$/u,{message:`Expected a CEL type reference`})).pipe(L(`CelTypeReference`)),tM=M.check(iD(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),nM=M.check(iD(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),rM=e=>rD(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),iM=class extends V(`@usine/expression/ObjectField`)({name:tM,type:eM,nullable:ME.pipe(YE(T(!1)))}){},aM=class extends V(`@usine/expression/ObjectType`)({name:nM,fields:P(iM).check(rM(`Expected unique CEL object-field names`))}){},oM=class extends V(`@usine/expression/Variable`)({name:tM,type:eM}){},sM=class extends V(`@usine/expression/Environment`)({types:P(aM).check(rM(`Expected unique CEL object-type names`)),variables:P(oM).check(rM(`Expected unique CEL variable names`))}){},cM=M.check(iD(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(L(`ExpressionSource`)),lM=R.check(fD(0)),uM=WE([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]);F([class extends rO(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:cM,code:uM,message:z,position:B(lM)}){},class extends rO(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:cM,message:z}){}]),F([M,jE,NE,ME,kE]);var dM=class extends sa()(`@usine/expression/ExpressionEngine`){},fM=z.pipe(L(`InstancePath`)),pM=WE([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),mM=class extends rO(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:fM,stage:pM,expression:GD(cM),message:z}){};F([mM,class extends rO(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:fM,stage:pM,message:z}){}]);var hM=M.check(iD(/\S/u,{message:`Expected a non-blank model ID`})).pipe(L(`ModelId`)),gM=WE([`claude`,`codex`,`pi`]),_M=WE([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),vM=class extends V(`Agent/BrainSpec`)({harness:gM,model:hM,effort:_M}){},yM=M.check(iD(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case agent name`})).pipe(L(`AgentName`)),bM=M.check(iD(/\S/u,{message:`Expected a non-blank agent persona`})).pipe(L(`AgentPersona`)),xM=class extends V(`Agent`)({name:yM,brain:vM,parentModel:UD(hM),parentEffort:GD(_M),persona:bM}){},SM=(e,t)=>Wi([e.parentModel,t]),CM=(e,t)=>Hi(Wi([e.parentEffort,t]),()=>e.brain.effort),wM=e=>{let t=N(e),n=new Set(Object.keys(e)),r=RE(M.check(rD(e=>!n.has(e))),DE.annotate({message:`Unexpected key`}));return t.rebuild(zE(t,[r]).ast)},TM=M.check(iD(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,{message:`Expected a GitHub login`})).pipe(L(`OperatorLogin`)),EM=class extends H(`StepResult/Commit`)(`Commit`,{sha:lj,summary:z}){},DM=class extends H(`StepResult/PullRequest`)(`PullRequest`,{number:R.check(fD(1)),url:DD}){},OM=WE([`issue-comment`,`review`,`review-comment`]),kM=class extends H(`StepResult/Comment`)(`Comment`,{url:DD,kind:OM,at:GD(HD)}){},AM=F([EM,DM,kM]),jM=class extends V(`StepResult`)({message:z,facts:P(AM)}){},MM=z.pipe(L(`StepName`)),NM=class extends V(`Step`)({runId:Qj,name:MM,result:B(jM)}){},PM=M.check(iD(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case worker name`})).pipe(L(`WorkerName`)),FM=WE([`local`,`exe.dev`,`ssh`,`cloudflare`]),IM=M.check(iD(/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\[bot\]$/u,{message:`Expected a GitHub bot login: <slug>[bot]`})).pipe(L(`BotLogin`)),LM=R.check(fD(1)).pipe(L(`BotUserId`)),RM=class extends V(`BotAccount`)({login:IM,id:LM}){get noreplyEmail(){return`${String(this.id)}+${this.login}@users.noreply.github.com`}},zM=M.check(iD(/^(?:[A-Za-z0-9._-]+@)?(?:[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?|[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7})$/u,{message:`Expected an SSH destination: a host name or address, optionally prefixed by a user`})).pipe(L(`SshDestination`)),BM=R.check(pD({minimum:1,maximum:65535})).pipe(L(`SshPort`)),VM=M.check(iD(/^(?:\/|~\/)[!-~]+$/u,{message:`Expected an absolute or ~/ key path without spaces or control characters`})).pipe(L(`SshIdentityFile`)),HM=M.check(iD(/^(?:\/[!-.0-~]+)+$/u,{message:`Expected an absolute directory without spaces, control characters, or a trailing /`})).pipe(L(`WorkerRoot`)),UM=M.check(iD(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u,{message:`Expected a lowercase DNS domain`})).pipe(L(`GatewayDomain`)),WM=R.check(pD({minimum:1,maximum:65535})).pipe(L(`GatewayAdminPort`)),GM=WE([`anthropic`,`openai`]),KM=WE([`api-key`,`subscription`]),qM=M.check(iD(/^[a-z0-9][A-Za-z0-9._/:@-]{0,254}$/u,{message:`Expected a container image reference, such as ghcr.io/owner/image:tag, without spaces or a leading dash`})).pipe(L(`ContainerImage`)),JM=M.check(iD(/^[0-9a-f]{64}$/u,{message:`Expected a container ID of 64 lowercase hex digits`})).pipe(L(`ContainerId`)),YM=aD.check(dD(0)).pipe(L(`ContainerCpus`)),XM=R.check(fD(256)).pipe(L(`ContainerMemoryMib`)),ZM=R.check(fD(64)).pipe(L(`ContainerPids`)),QM=class extends V(`ContainerLimits`)({cpus:YM,memoryMib:XM,pids:ZM}){},$M=[`cpus`,`memoryMib`,`pids`],eN=WE([`lite`,`basic`,`standard-1`,`standard-2`,`standard-3`,`standard-4`]),tN=M.check(iD(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/u,{message:`Expected an image name of letters, digits, and underscores that doesn't start with a digit`})).pipe(L(`CloudflareImageName`)),nN=WE([`anthropic`,`openai`]),rN=WE([`hetzner`,`boat`]),iN=M.check(iD(/^[A-Za-z0-9_-]{1,64}$/u,{message:`Expected a provider machine ID`})).pipe(L(`MachineId`)),aN=M.check(iD(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner server type, such as cx33`})).pipe(L(`HetznerServerType`)),oN=M.check(iD(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner location, such as nbg1`})).pipe(L(`HetznerLocation`)),sN=M.check(iD(/^[!-~](?:[ -~]{0,253}[!-~])?$/u,{message:`Expected a Hetzner image ID, snapshot description, or image name`})).pipe(L(`HetznerImage`)),cN=M.check(iD(/^[!-~](?:[ -~]{0,126}[!-~])?$/u,{message:`Expected a Hetzner resource name without control characters`})).pipe(L(`HetznerResourceName`)),lN=/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]*[a-z0-9A-Z])?\/)?[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?$/u,uN=RE(M,M.check(iD(/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?)?$/u,{message:`Expected a Hetzner label value`}))).check(rD(e=>{let t=Object.keys(e),n=t.find(e=>!lN.test(e));if(n!==void 0)return`Expected a Hetzner label key, not "${n}"`;let r=t.find(e=>e.startsWith(`usine-`));return r===void 0||`Expected a label key that doesn't start with usine-, which usine sets itself, not "${r}"`})),dN=M.check(iD(/^[a-z_][a-z0-9_-]{0,31}$/u,{message:`Expected a Unix user name`})).pipe(L(`SshUser`)),fN=WE([`small`,`default`,`large`,`xlarge`]),pN=z.pipe(L(`AgentSessionId`)),mN=R.check(fD(0)).pipe(L(`TokenCount`)),hN=R.check(fD(1)),gN=hN.pipe(L(`ChildSessionBudget`)),_N=hN.pipe(L(`ChildSessionCount`)),vN=F([class extends H(`Agent/ParentSession`)(`ParentSession`,{id:pN,agent:yM,brain:vM}){},class extends H(`Agent/ChildSession`)(`ChildSession`,{id:pN,parentId:pN,agent:yM,brain:vM,gatewayCredential:GD(KM).pipe(YE(T(b())))}){}]),yN=z.pipe(L(`HarnessSessionId`)),bN=class extends V(`Agent/HarnessSession`)({id:yN,cwd:z,home:GD(z).pipe(YE(T(b())))}){},xN=class extends H(`Agent/SessionStarted`)(`SessionStarted`,{session:vN,harnessSession:GD(bN).pipe(YE(T(b())))}){},SN=class extends H(`Agent/TextOutput`)(`TextOutput`,{session:vN,text:z}){},CN=class extends H(`Agent/ToolStarted`)(`ToolStarted`,{session:vN,callId:z,tool:z,input:oO}){},wN=class extends H(`Agent/ToolFinished`)(`ToolFinished`,{session:vN,callId:z,tool:z,output:oO,isError:ME}){},TN=class extends H(`Agent/SessionFinished`)(`SessionFinished`,{session:vN}){},EN=class extends H(`Agent/SessionIdle`)(`SessionIdle`,{session:vN}){},DN=class extends H(`Agent/SessionResumed`)(`SessionResumed`,{session:vN}){},ON=aD.check(fD(0)).pipe(L(`UsdAmount`)),kN=R.check(fD(0)),AN=class extends V(`Agent/TokenBreakdown`)({input:kN,cachedInput:kN,cacheWrite:kN,output:kN}){},jN=class extends H(`Agent/SessionTokensUpdated`)(`SessionTokensUpdated`,{session:vN,totalTokens:mN,costUsd:GD(ON).pipe(YE(T(b()))),breakdown:GD(AN).pipe(YE(T(b())))}){},MN=WE([`apiKeys`,`claudePlan`,`chatgptPlan`]),NN=(e,t)=>{switch(e.harness){case`claude`:return ia(t,`api-key`)?`apiKeys`:`claudePlan`;case`codex`:return ia(t,`api-key`)?`apiKeys`:`chatgptPlan`;case`pi`:return e.model.startsWith(`openai-codex/`)?`chatgptPlan`:`apiKeys`}},PN=e=>GA(e,{ParentSession:({brain:e})=>NN(e,b()),ChildSession:({brain:e,gatewayCredential:t})=>NN(e,t)}),FN=class extends V(`Agent/RateLimitWindow`)({usedPercent:jE,windowDurationMinutes:UD(jE),resetsAt:UD(HD)}){},IN=class extends V(`Agent/RateLimitsSnapshot`)({limitId:UD(M),limitName:UD(M),primary:UD(FN),secondary:UD(FN)}){},LN=class extends H(`Agent/PoolRateLimitsUpdated`)(`PoolRateLimitsUpdated`,{session:vN,pool:MN,rateLimits:IN}){},RN=hN.pipe(L(`ProviderRetries`)),zN=F([xN,SN,CN,wN,LN,TN,EN,DN,jN,class extends H(`Agent/ProviderRetrying`)(`ProviderRetrying`,{session:vN,message:z,retries:RN}){},class extends H(`Agent/ProviderRecovered`)(`ProviderRecovered`,{session:vN,retries:RN}){}]),BN=class extends rO(`AttemptFailure/InfraFailure`)(`InfraFailure`,{message:M,cause:wD()}){},VN=class extends rO(`AttemptFailure/DefectFailure`)(`DefectFailure`,{message:M,cause:wD()}){},HN=class extends rO(`AttemptFailure/AgentFailure`)(`AgentFailure`,{message:M}){},UN=class extends rO(`AttemptFailure/BlockedFailure`)(`BlockedFailure`,{message:z}){},WN=class extends rO(`AttemptFailure/QuestionFailure`)(`QuestionFailure`,{question:z}){},GN=WE([`wall-clock`,`tokens`]),KN=F([BN,VN,HN,UN,WN,class extends rO(`AttemptFailure/RunawayFailure`)(`RunawayFailure`,{ceiling:GN}){},class extends rO(`AttemptFailure/ChildSessionBudgetFailure`)(`ChildSessionBudgetFailure`,{maxChildren:gN,attemptedChildren:_N}){}]),qN=uE(BN),JN=class extends H(`AttemptOutcome/Succeeded`)(`Succeeded`,{}){},YN=class extends H(`AttemptOutcome/Failed`)(`Failed`,{failure:KN}){},XN=class extends H(`AttemptOutcome/Canceled`)(`Canceled`,{}){},ZN=F([JN,YN,XN]),QN=z.pipe(L(`SalvageRef`)),$N=(e,t)=>QN.make(`usine/salvage/${uj(e)}/${t}`),eP=class extends H(`AttemptSalvage/Pushed`)(`Pushed`,{ref:QN,commit:lj}){},tP=F([eP,class extends H(`AttemptSalvage/PartlyPushed`)(`PartlyPushed`,{ref:QN,commit:lj,path:z,message:M}){},class extends H(`AttemptSalvage/Retained`)(`Retained`,{path:z,commit:UD(lj),message:M}){},class extends H(`AttemptSalvage/Rejected`)(`Rejected`,{path:z,commit:lj,message:M}){}]),nP=class extends H(`AttemptStart/Event`)(`Event`,{}){},rP=class extends H(`AttemptStart/Retry`)(`OperatorRetry`,{operator:UD(TM)}){},iP=class extends H(`AttemptStart/EditAndRetry`)(`EditAndRetry`,{operator:UD(TM)}){},aP=class extends H(`AttemptStart/InfraRetry`)(`InfraRetry`,{}){},oP=class extends H(`AttemptStart/AfterRestart`)(`AfterRestart`,{}){},sP=F([rP,iP]),cP=F([nP,rP,iP,aP,oP]),lP=z.pipe(L(`AttemptId`)),uP=R.check(fD(1)).pipe(L(`AttemptNumber`)),dP=M.check(iD(/\S/u,{message:`Expected non-blank task text`})).pipe(L(`AttemptTask`)),fP=WE([`cancel`,`failed`,`startup`]),pP=class extends V(`AttemptContext`)({task:dP,agent:xM,parentModel:UD(hM)}){},mP=class extends V(`FailureResolution`)(wM({resolvedAt:HD,operator:UD(TM)})){},hP=R.check(fD(1)),gP=class extends V(`OutOfMemoryKills`)({kills:hP,memoryMib:XM}){},_P=class extends V(`ContainerOutOfMemoryKills`)({container:JM,kills:hP,memoryMib:XM}){},vP=e=>new gP({kills:e.reduce((e,{kills:t})=>e+t,0),memoryMib:Eo(e).memoryMib}),yP=class extends V(`Attempt`)({id:lP,runId:Qj,stepName:MM,worker:PM,number:uP,brain:vM,task:dP,agent:yM,operatorIntervened:ME,parentModel:UD(hM),startedAt:VD,outcome:B(ZN),endedAt:B(VD),salvage:B(tP),failureResolution:B(mP).pipe(YE(T(b()))),start:B(cP).pipe(YE(T(b()))),reattachedAt:B(VD).pipe(YE(T(b()))),comments:P(kM).pipe(YE(T([]))),outOfMemory:B(gP).pipe(YE(T(b())))}){},bP=class extends V(`AttemptWindow`)({attemptId:lP,startedAt:VD,endedAt:B(VD)}){},xP=e=>C(e.outcome)&&S(e.endedAt)?b():x(new bP({attemptId:e.id,startedAt:e.startedAt,endedAt:e.endedAt})),SP=e=>{let t=hy(e.startedAt);return t-t%1e3},CP=(e,t)=>Vi(e.endedAt,{onNone:()=>!0,onSome:e=>t<=hy(e)}),wP=(e,t)=>{let n=hy(t);return SP(e)<=n&&CP(e,n)},TP=(e,t)=>CP(e,SP(t))&&CP(t,SP(e)),EP=class extends V(`AttemptWindows`)({own:B(bP),overlapping:P(bP)}){},DP=e=>qN(e.failure)&&e.number<e.maxAutoAttempts,OP=z.pipe(L(`ItemKey`)),kP=R.check(fD(1)).pipe(L(`ItemNumber`)),AP=R.check(fD(1)).pipe(L(`CycleLimit`)),jP=R.check(fD(0)).pipe(L(`CycleGeneration`)),MP=AP.make(3),NP=R.check(fD(0)).pipe(L(`CycleCount`)),PP=class extends V(`LoopCycleCount`)(wM({loop:gj,admitted:NP,completed:NP}).check(rD(({admitted:e,completed:t})=>t<=e,{message:`Completed runs can't exceed admitted runs`}))){},FP=pj.pipe(L(`CycleBudgetAskId`)),IP=class extends V(`CycleBudgetAsk`)(wM({id:FP,itemKey:OP,repository:sj,loop:gj,limit:AP,counts:HE(PP)}).check(rD(({loop:e,limit:t,counts:n})=>new Set(n.map(e=>e.loop)).size===n.length&&n.some(n=>n.loop===e&&n.admitted>=t),{message:`Expected unique participating loops, including the exhausted loop at its limit`}))){get completedCycles(){return NP.make(Math.max(...this.counts.map(({completed:e})=>e)))}},LP=R.check(fD(1)).pipe(L(`AttemptChannelSequence`)),RP=[`inbound`,`outbound`],zP=WE(RP),BP=class extends V(`AttemptChannel/RunSpec`)({attemptId:lP,repository:sj,revision:cj,baseCommit:lj,payload:oO,task:dP,agent:xM,parentModel:UD(hM),maxChildren:gN,parentEffort:_M,resume:UD(eP),conflictingSalvage:UD(eP).pipe(ZE(T(null)),YE(T(b()))),preparedAt:UD(HD).pipe(ZE(T(null))),botLogin:UD(IM).pipe(ZE(T(null)))}){},VP=class extends H(`AttemptChannel/Started`)(`Started`,{parentModel:hM,conflictingSalvage:UD(eP).pipe(ZE(T(null)),YE(T(b())))}){},HP=class extends H(`AttemptChannel/SessionEvent`)(`SessionEvent`,{event:zN}){},UP=class extends H(`AttemptChannel/Final`)(`Final`,{result:jM}){},WP=class extends H(`AttemptChannel/Failed`)(`Failed`,{failure:KN}){},GP=class extends H(`AttemptChannel/Interrupted`)(`Interrupted`,{}){},KP=class extends H(`AttemptChannel/Steer`)(`Steer`,{message:z}){},qP=class extends H(`AttemptChannel/Interrupt`)(`Interrupt`,{}){},JP=class extends H(`AttemptChannel/Cancel`)(`Cancel`,{}){},YP=class extends H(`AttemptChannel/OperatorMessage`)(`OperatorMessage`,{message:z}){},XP=class extends H(`AttemptChannel/Release`)(`Release`,{}){},ZP=F([KP,qP,YP,XP]),QP=F([ZP,JP]),$P=class extends H(`AttemptChannel/ParentTarget`)(`Parent`,{}){},eF=class extends H(`AttemptChannel/ChildTarget`)(`Child`,{sessionId:pN}){},tF=F([$P,eF]),nF=class extends V(`AttemptChannel/Intervention`)({operator:z,target:tF,action:ZP}){},rF=class extends V(`AttemptChannel/InterventionState`)({held:ME,paused:ME,queued:ME.pipe(ZE(T(!1)),YE(T(!1)))}){},iF=class extends H(`AttemptChannel/InterventionApplied`)(`InterventionApplied`,{inputSequence:LP,intervention:nF,state:rF}){},aF=class extends H(`AttemptChannel/InterventionRejected`)(`InterventionRejected`,{inputSequence:LP,intervention:nF,message:z}){},oF=class extends H(`AttemptChannel/WorkerUnresponsive`)(`WorkerUnresponsive`,{worker:PM,lastAnsweredAt:HD,reason:z}){},sF=class extends H(`AttemptChannel/WorkerResponsive`)(`WorkerResponsive`,{worker:PM,lastAnsweredAt:HD}){};F([oF,sF]);var cF=F([VP,HP,UP,WP,GP,iF,aF,oF,sF]),lF={version:EE(7),attemptId:lP,sequence:LP,sentAt:HD},uF=class extends H(`AttemptChannel/OutboundEnvelope`)(`OutboundEnvelope`,{...lF,payload:cF}){},dF=class extends H(`AttemptChannel/InboundEnvelope`)(`InboundEnvelope`,{...lF,target:tF.pipe(ZE(T({_tag:`Parent`}))),operator:z,payload:QP}){},fF=F([uF,dF]),pF=[`ui`,`github-ask`],mF=WE(pF),hF=class extends V(`ApprovalSource`)(wM({channel:mF,approver:UD(TM)}).check(rD(({channel:e,approver:t})=>e!==`github-ask`||C(t),{message:`Expected an approver for a GitHub ask approval`}))){},gF=class extends V(`RunApproval`)({approvedAt:VD,source:B(hF)}){},_F=class e extends sa()(`@usine/engine/internal/RunDatabase`){static layer=t=>_m(e)(t)},vF=class extends rO(`@usine/engine/RunNotFoundError`)(`RunNotFoundError`,{runId:Qj}){},yF=class extends rO(`@usine/engine/RunOperationRejectedError`)(`RunOperationRejectedError`,{runId:Qj,operation:WE([`approve`,`retry`,`resolveFailure`,`runAgain`,`cancel`]),state:M}){},bF=class extends rO(`@usine/engine/RunRetryBlockedError`)(`RunRetryBlockedError`,{runId:Qj,openRunId:Qj,message:z}){},xF=class extends rO(`@usine/engine/EnginePersistenceError`)(`EnginePersistenceError`,{operation:M,cause:wD()}){},SF=class extends rO(`@usine/engine/AttemptCancellationError`)(`AttemptCancellationError`,{attemptId:lP,cause:wD()}){},CF=F([vF,yF,bF,xF]),wF=class extends rO(`@usine/engine/RunInterventionRejectedError`)(`RunInterventionRejectedError`,{runId:Qj,attemptId:lP,message:z}){},TF=class extends rO(`@usine/engine/LeftoversDiscardRejectedError`)(`LeftoversDiscardRejectedError`,{worker:PM,running:R.check(fD(0))}){};F([vF,yF,bF,xF,SF,wF]);var EF=`~effect/encoding/Ndjson/NdjsonError`,DF=new TextEncoder,OF=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),kF=class extends qs(`NdjsonError`){[EF]=EF;get message(){return this.kind}},AF=e=>It(e,EF),jF=()=>uk((e,t)=>T(D(e,e=>{try{return T(Ro(e.map(e=>{let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Value cannot be represented as JSON`);return t}).join(`
|
|
15
|
+
`)+`
|
|
16
|
+
`))}catch(e){return f_(new kF({kind:`Pack`,cause:e}))}}))),MF=()=>xk(jF(),zo(e=>DF.encode(e))),NF=(e,t,n)=>{let r,i,a=(e,t)=>(r=t,yo(e)?T(e):t===void 0?void 0:f_(t)),o=s_(()=>r===void 0?i===void 0?wg(e,{onSuccess:e=>{let n=[];return a(n,t(e,n))??o},onFailure:p_,onDone:e=>{i={leftover:e};let t=[];return a(t,n(t))??Ap(e)}}):Ap(i.leftover):f_(r));return o},PF=(e,t,n,r)=>{if(!(n&&e.length===0))try{t.push(JSON.parse(e))}catch(e){return new kF({kind:`Unpack`,reason:`InvalidJson`,unterminated:r,cause:e})}},FF=10,IF=13,LF=new Uint8Array,RF=e=>uk((t,n)=>c_(()=>{let n=e?.ignoreEmptyLines===!0,r=e?.maxLineBytes??1/0,i=new TextDecoder(`utf-8`,{fatal:!0}),a=[],o=0,s=!1,c=(e,t,n)=>{if(o===0)return e.subarray(t,n);let r=new Uint8Array(o+n-t),i=0;for(let e of a)r.set(e,i),i+=e.length;return r.set(e.subarray(t,n),i),a=[],o=0,r},l=(e,t,r)=>{let a;try{a=i.decode(e)}catch(e){return new kF({kind:`Unpack`,reason:`InvalidUtf8`,unterminated:r,cause:e})}let o=i!==OF;if(i=OF,!(o&&r&&a.length===0))return PF(a,t,n,r)};return NF(t,(e,t)=>{for(let n of e){let e=0;for(let i=0;i<n.length;i++){let a=n[i];if(a===FF||a===IF){if(a===FF&&s)e=i+1;else{let r=l(c(n,e,i),t,!1);if(r!==void 0)return r;e=i+1}s=a===IF}else if(s=!1,o+i+1-e>r)return new kF({kind:`Unpack`,reason:`LineTooLarge`,unterminated:!1,cause:RangeError(`NDJSON line exceeds maxLineBytes of ${r}`)})}e<n.length&&(a.push(n.slice(e)),o+=n.length-e)}},e=>o===0?void 0:l(c(LF,0,0),e,!0))})),zF=`~effect/encoding/Sse/SseError`,BF=class extends qs(`EventTooLarge`){get message(){return`Pending SSE event exceeded the maximum size of ${this.maxEventSize}`}},VF=class extends qs(`SseError`){[zF]=zF;get message(){return this.reason.message}},HF=10485760,UF=e=>uk((t,n)=>c_(()=>{let n=[],r,i=GF(e=>{e._tag===`Retry`?r=e:n.push(e)},e),a=D(t,e=>{for(let t=0;t<e.length;t++){let n=i.feed(e[t]);if(n!==void 0)return f_(n)}return l_});return s_(function e(){if(yo(n)){let e=n;return n=[],T(e)}return r?f_(r):D(a,e)})})),WF=(e,t,n)=>Fk(UF(t),Wk(XF.pipe(KE(e,ZF)),n)());function GF(e,t){let n=t?.maxEventSize??HF,r=t?.dispatchEmptyNamedEvents===!0,i,a,o,s,c=0,l,u,d;return f(),{feed:p,reset:f};function f(){c++,i=!0,a=[],o=0,s=!1,l=void 0,u=void 0,d=``}function p(e){i&&e.startsWith(KF)&&(e=e.slice(KF.length)),i=!1;let t=e.length,r=c,l=0;for(;l<t;){if(s&&(s=!1,e.charCodeAt(l)===qF)){++l;continue}let n=l;for(;n<t;){let t=e.charCodeAt(n);if(t===JF||t===qF)break;++n}if(n===t){a.push(e.slice(l)),o+=t-l;break}s=e.charCodeAt(n)===JF;let i=e.slice(l,n);if(a.length>0&&(a.push(i),i=a.join(``),a=[],o=0),m(i),c!==r)return;l=n+1}if(o+d.length>n){let e=new VF({reason:new BF({maxEventSize:n})});return f(),e}}function m(t){if(t.length===0){let t=u!==void 0&&u!==``,n=u||`message`,i=d;u=void 0,d=``,(i.length>0||r&&t)&&e({_tag:`Event`,id:l,event:n,data:i.slice(0,-1)});return}let n=t.indexOf(`:`),i=t,a=``;n>=0&&(i=t.slice(0,n),a=t.slice(t.charCodeAt(n+1)===YF?n+2:n+1)),i===`data`?d+=a+`
|
|
17
|
+
`:i===`event`?u=a:i===`id`&&!a.includes(`\0`)?l=a:i===`retry`&&/^\d+$/.test(a)&&e(new $F({duration:ws(parseInt(a,10)),lastEventId:l}))}}var KF=``,qF=10,JF=13,YF=32,XF=N({_tag:$E(`Event`),id:GE(M),event:M,data:M}),ZF=Yx({decode:e=>e.id===void 0?{event:e.event,data:e.data}:{id:e.id,event:e.event,data:e.data},encode:e=>({_tag:`Event`,id:e.id,event:e.event??`message`,data:e.data})}),QF=`~effect/encoding/Sse/Retry`,$F=class e extends Ks(`Retry`){[QF]=QF;static is(e){return It(e,QF)}static filter(t){return e.is(t)?Ga(t):Ka(t)}},eI=class extends V(`@usine/engine/Submission`)({event:hj,itemKey:OP,loop:gj,step:MM,approval:vj,permissions:bj.pipe(ZE(T(`write`)),YE(T(`write`))),cycleLimit:B(AP).pipe(QE(T(x(MP))),YE(T(x(MP)))),cycleGeneration:jP.pipe(ZE(T(jP.make(0))),YE(T(jP.make(0)))),repository:sj,revision:cj,task:dP,agent:xM,parentModel:B(hM)}){},tI=`@usine/engine/DurableRun`,nI=k(`Submission.runIdFor`)(function*(e){let t=yield*(yield*yA).digest(`SHA-256`,new TextEncoder().encode(`${tI}-${e.event.dedupKey}`)).pipe(F_);return Qj.make(Xs(t.subarray(0,16)))}),rI=(e,t,n)=>{let r=mj.make(JSON.stringify([`reopened`,n,t]));return new eI({...e,event:new hj({...e.event,id:pj.make(r),dedupKey:r})})},iI=class extends H(`@usine/engine/Claimed`)(`Claimed`,{eventId:pj,runId:Qj}){},aI=class extends H(`@usine/engine/Queued`)(`Queued`,{eventId:pj}){},oI=[`superseded`,`revoked`],sI=WE(oI),cI=class extends H(`@usine/engine/Ignored`)(`Ignored`,{eventId:pj,reason:sI}){},lI=class extends H(`@usine/engine/Suppressed`)(`Suppressed`,{eventId:pj,runId:Qj}){},uI=class extends H(`@usine/engine/CycleBlocked`)(`CycleBlocked`,{eventId:pj,ask:IP}){},dI=F([iI,aI,lI,cI,uI]),fI=new class extends V(`@usine/engine/RetryRequest`)({requestedBy:B(TM),amendment:B(pP)}){}({requestedBy:b(),amendment:b()}),pI=class extends V(`RunAgain`)(wM({from:Qj,requestedBy:UD(TM)})){},mI=R.check(fD(1)).pipe(L(`TranscriptSequence`)),hI=WE([3,4]),gI=N({...uF.fields,version:hI}),_I=N({_tag:EE(`InboundEnvelope`),version:hI,attemptId:lP,sequence:LP,sentAt:HD,payload:F([KP,qP])}),vI=WE([5,6]),yI=F([fF,N({...uF.fields,version:vI}),N({...dF.fields,version:vI}),gI,_I]),bI=class extends V(`@usine/engine/TranscriptEntry`)({sequence:mI,attemptId:lP,direction:zP,envelope:yI,receivedAt:VD}){},xI=class extends H(`@usine/engine/TranscriptAllQuery`)(`TranscriptAllQuery`,{attemptId:lP}){},SI=class extends H(`@usine/engine/TranscriptSessionsQuery`)(`TranscriptSessionsQuery`,{attemptId:lP}){},CI=class extends H(`@usine/engine/TranscriptUsageQuery`)(`TranscriptUsageQuery`,{attemptId:lP}){},wI=class extends H(`@usine/engine/TranscriptTailQuery`)(`TranscriptTailQuery`,{attemptId:lP,after:mI,limit:R.check(fD(1))}){},TI=class extends H(`@usine/engine/TranscriptPageQuery`)(`TranscriptPageQuery`,{attemptId:lP,before:B(mI),limit:R.check(fD(1))}){};F([xI,SI,CI,wI,TI]);var EI=class extends V(`@usine/engine/RunSnapshot`)({event:hj,itemKey:OP,run:$j,step:NM,attempts:P(yP),resolvedFailureAttemptId:B(lP),closedAt:B(VD),approval:B(gF),runAgain:B(pI),repository:sj,revision:cj,task:dP,agent:xM,parentModel:B(hM),permissions:bj}){},DI=class extends V(`@usine/engine/RunEvent`)({runId:Qj,event:hj}){},OI=class extends V(`@usine/engine/RunEvidence`)({snapshot:EI,transcript:P(bI)}){},kI=class extends V(`@usine/engine/RunSummary`)({itemKey:OP,run:$j,step:NM,attempts:P(yP),resolvedFailureAttemptId:B(lP),closedAt:B(VD),approval:B(gF),runAgain:B(pI),repository:sj,task:dP,agent:xM}){},AI=class extends V(`@usine/engine/WorkerAttempts`)(N({worker:PM,attempts:R.check(fD(1)),running:R.check(fD(0))}).check(rD(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},jI=class extends V(`@usine/engine/LoopSighting`)({loop:gj,itemKey:OP,event:B(pj),run:B(Qj),suppressedBy:B(Qj)}){},MI=R.check(fD(0)).pipe(L(`ProjectionRevision`));V(`@usine/engine/RunAgainRequest`)({step:MM,approval:vj,cycleLimit:B(AP),permissions:bj,context:pP,requestedBy:B(TM)});var NI=F([iI,uI]),PI=(e,t,n)=>{let r=mj.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new eI({event:new hj({id:pj.make(r),dedupKey:r,payload:e.event.payload,receivedAt:n.receivedAt}),itemKey:e.itemKey,loop:e.run.loop,step:t.step,approval:t.approval,permissions:t.permissions,cycleLimit:t.cycleLimit,cycleGeneration:n.generation,repository:e.repository,revision:e.revision,task:t.context.task,agent:t.context.agent,parentModel:t.context.parentModel})},FI=class extends V(`@usine/engine/StepExecution`)({attempt:yP,event:hj,run:$j,step:NM,repository:sj,revision:cj,task:dP,agent:xM,parentModel:B(hM),permissions:bj,resume:B(eP),reattach:ME.pipe(YE(T(!1)))}){},II=class extends sa()(`@usine/engine/StepExecutor`){},U=Symbol.for(`drizzle:entityKind`),LI=new WeakMap;function RI(e){let t=new Set;for(let n=e;n;n=Object.getPrototypeOf(n))U in n&&t.add(n[U]);return LI.set(e,t),t}var zI=Function.prototype[Symbol.hasInstance];function W(e,t){if(zI.call(t,e))return!0;if(typeof e!=`object`||!e)return!1;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`&&(LI.get(n)??RI(n)).has(t[U])}function BI(e){if(typeof e!=`object`||!e)return;let t=Object.getPrototypeOf(e)?.constructor;if(typeof t==`function`)return LI.get(t)??RI(t)}var VI=class extends Error{static[U]=`DrizzleError`;static[Symbol.hasInstance](e){return W(e,this)}constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}},HI=Symbol.for(`drizzle:Name`),UI=Symbol.for(`drizzle:Schema`),WI=Symbol.for(`drizzle:Columns`),GI=Symbol.for(`drizzle:ExtraConfigColumns`),KI=Symbol.for(`drizzle:OriginalName`),qI=Symbol.for(`drizzle:BaseName`),JI=Symbol.for(`drizzle:CacheKey`),YI=Symbol.for(`drizzle:IsAlias`),XI=Symbol.for(`drizzle:Qualifier`),ZI=Symbol.for(`drizzle:ExtraConfigBuilder`),QI=Symbol.for(`drizzle:IsDrizzleTable`),$I=class{static[U]=`Table`;static[Symbol.hasInstance](e){return W(e,this)}static Symbol={Name:HI,Schema:UI,OriginalName:KI,Columns:WI,ExtraConfigColumns:GI,BaseName:qI,IsAlias:YI,ExtraConfigBuilder:ZI,CacheKey:JI};[HI];[KI];[UI];[WI];[GI];[qI];[JI];[YI]=!1;[QI]=!0;[ZI]=void 0;constructor(e,t,n){this[HI]=this[KI]=e,this[UI]=t,this[qI]=n,this[JI]=t?`${t}.${e}`:e}};function eL(e){return e[HI]}var tL=Symbol.for(`drizzle:OriginalColumn`),nL=e=>e;nL.isNoop=!0;var rL=class{static[U]=`Column`;static[Symbol.hasInstance](e){return W(e,this)}codec;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;isAlias;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.isAlias=!1,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue=nL;mapToDriverValue=nL;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}[tL](){return this}},G=class{value;static[U]=`StringChunk`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.value=e}},K={", ":new G(`, `)," ":new G(` `),"(":new G(`(`),")":new G(`)`),"((":new G(`((`),"))":new G(`))`),"), (":new G(`), (`),".":new G(`.`),default:new G(`default`),null:new G(`null`),"1 = 0":new G(`1 = 0`),"1 = 1":new G(`1 = 1`)," = ":new G(` = `)," <> ":new G(` <> `)," > ":new G(` > `)," >= ":new G(` >= `)," < ":new G(` < `)," <= ":new G(` <= `)," in ":new G(` in `)," not in ":new G(` not in `),") and (":new G(`) and (`),") or (":new G(`) or (`),"not (":new G(`not (`),"with ":new G(`with `),"select ":new G(`select `),"(select ":new G(`(select `),"values ":new G(`values `)," from ":new G(` from `),".* from ":new G(`.* from `)," as ":new G(` as `),") as ":new G(`) as `)," inner join ":new G(` inner join `)," cross join ":new G(` cross join `)," on ":new G(` on `)," where ":new G(` where `)," order by ":new G(` order by `)," asc":new G(` asc`)," desc":new G(` desc`)," limit ":new G(` limit `)," limit 1":new G(` limit 1`)," offset ":new G(` offset `),"top(1) ":new G(`top(1) `),"exists (select * from ":new G(`exists (select * from `),"not exists (select * from ":new G(`not exists (select * from `),"select count(*) as ":new G(`select count(*) as `),"(select count(*) from ":new G(`(select count(*) from `),"min(":new G(`min(`),"max(":new G(`max(`),"count(":new G(`count(`),"avg(":new G(`avg(`),"first(":new G(`first(`)},iL=Symbol.for(`drizzle:ViewBaseConfig`),aL=Symbol.for(`drizzle:IsDrizzleView`),oL=class{static[U]=`View`;static[Symbol.hasInstance](e){return W(e,this)}[iL];[aL]=!0;get[HI](){return this[iL].name}get[UI](){return this[iL].schema}get[YI](){return this[iL].isAlias}get[KI](){return this[iL].originalName}get[WI](){return this[iL].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[iL]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}},sL=class{static[U]=`Subquery`;static[Symbol.hasInstance](e){return W(e,this)}get[HI](){return this._.alias}get[UI](){}get[KI](){return this._.alias}get[YI](){return!1}get[WI](){return this._.selectedFields}constructor(e,t,n,r=!1){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r}}},cL=class extends sL{static[U]=`WithSubquery`};function lL(e){return e!=null&&typeof e.getSQL==`function`}var uL=class e{queryChunks;static[U]=`SQL`;static[Symbol.hasInstance](e){return W(e,this)}decoder=vL;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return this.buildQueryFromSourceParams(this.queryChunks,e)}buildQueryFromSourceParams(e,t){let n={sql:``},r=[],i=t.tagged?[]:void 0;this.collectSQL(e,t,t.paramStartIndex||{value:0},t.inlineParams||this.shouldInlineParams,n,r,i);let a=n.sql;if(i===void 0)return{sql:a,params:r};let o=Array(i.length);for(let e=0;e<i.length;++e)o[e]=a.slice(i[e],e+1<i.length?i[e+1]:a.length);return{sql:a,params:r,_sql:Object.assign(o,{raw:o})}}collectSQL(e,t,n,r,i,a,o){let{escapeName:s,escapeParam:c,codecs:l,invokeSource:u}=t;for(let d=0;d<e.length;++d){o!==void 0&&o.push(i.sql.length);let f=e[d],p=mL(f);if(hL(f,p,q.string))i.sql+=f.value??``;else if(hL(f,p,q.sql))this.collectSQL(f.queryChunks,t,n,r||f.shouldInlineParams,i,a,void 0);else if(hL(f,p,q.name))i.sql+=s(f.value);else if(f!==void 0){if(hL(f,p,q.column)){let e=f.name;if(u===`indexes`){i.sql+=s(e);continue}let t=u===`mssql-check`?void 0:f.table[$I.Symbol.Schema];i.sql+=f.isAlias?s(f.name):f.table[YI]||t===void 0?s(f.table[$I.Symbol.Name])+`.`+s(e):s(t)+`.`+s(f.table[$I.Symbol.Name])+`.`+s(e)}else if(hL(f,p,q.param)){let e=f.value,o=mL(e);if(hL(e,o,q.sql)){let o=e;this.collectSQL(o.queryChunks,t,n,r||o.shouldInlineParams,i,a,void 0);continue}let s=f.encoder,u=l&&mL(s)===q.column?l.codecsOf(s):void 0;if(o===q.placeholder){let e=c(n.value++,f),t=u?.normalizeParam,r=u?.castParam;f.codec=t?e=>t(e,s.dimensions):void 0,i.sql+=r?r(e,s,s.dimensions):e,a.push(f);continue}this.collectBoundValue(e,s,u,t,n,r,i,a)}else if(hL(f,p,q.placeholder))i.sql+=c(n.value++,f),a.push(f);else if(hL(f,p,q.table)){let e=f[$I.Symbol.Schema],t=f[$I.Symbol.Name];if(u===`mssql-view-with-schemabinding`){i.sql+=s(e===void 0?`dbo`:e)+`.`+s(t);continue}i.sql+=e===void 0||f[YI]?s(t):s(e)+`.`+s(t)}else if(hL(f,p,q.view)){let e=f[iL].schema,t=f[iL].name;i.sql+=e===void 0||f[iL].isAlias?s(t):s(e)+`.`+s(t)}else if(hL(f,p,q.aliased)&&f.fieldAlias!==void 0)i.sql+=(f.origin===void 0?``:s(f.origin)+`.`)+s(f.fieldAlias);else if(hL(f,p,q.valueRows)){let{cells:e,encoders:o}=f,s=o.length,c=Array(s);for(let e=0;e<s;++e){let t=o[e];c[e]=l&&mL(t)===q.column?l.codecsOf(t):void 0}i.sql+=`(`;for(let l=0,u=0;l<e.length;++l,++u){u===s?(u=0,i.sql+=`), (`):u>0&&(i.sql+=`, `);let d=e[l],f=mL(d);f===q.other?this.collectBoundValue(d,o[u],c[u],t,n,r,i,a):hL(d,f,q.string)?i.sql+=d.value??``:this.collectSQL([f===q.sql?d:new bL(d,o[u])],t,n,r,i,a,void 0)}i.sql+=`)`}else if(hL(f,p,q.subquery)){if(f._.isWith){i.sql+=s(f._.alias);continue}let e=f._.sql;i.sql+=`(`,this.collectSQL(e.queryChunks,t,n,r||e.shouldInlineParams,i,a,void 0),i.sql+=`) `+s(f._.alias)}else if(typeof f==`function`&&`enumName`in f){if(`schema`in f&&f.schema){i.sql+=s(f.schema)+`.`+s(f.enumName);continue}i.sql+=s(f.enumName)}else if(lL(f)){let e=f.getSQL(),o=r||e.shouldInlineParams;if(f.shouldOmitSQLParens?.()){this.collectSQL(e.queryChunks,t,n,o,i,a,void 0);continue}i.sql+=`(`,this.collectSQL(e.queryChunks,t,n,o,i,a,void 0),i.sql+=`)`}else if(Array.isArray(f)){i.sql+=`(`;let e=[void 0];for(let o=0;o<f.length;++o)o>0&&(i.sql+=`, `),e[0]=f[o],this.collectSQL(e,t,n,r,i,a,void 0);i.sql+=`)`}else r?i.sql+=this.mapInlineParam(f,t):(i.sql+=c(n.value++,f),a.push(f))}}}collectBoundValue(e,t,n,r,i,a,o,s){let c=e;if(e!==null){if(t.mapToDriverValue.isNoop||(c=t.mapToDriverValue(e)),mL(c)===q.sql){let e=c;this.collectSQL(e.queryChunks,r,i,a||e.shouldInlineParams,o,s,void 0);return}let l=n?.normalizeParam;!a&&l&&(c=l(c,t.dimensions))}if(a){o.sql+=this.mapInlineParam(c,r);return}let{escapeParam:l}=r,u=l(i.value++,c),d=n?.castParam;o.sql+=d?d(u,t,t.dimensions):u,s.push(c)}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}nullable(){return this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},q={other:0,string:1,sql:2,name:3,column:4,param:5,placeholder:6,table:7,view:8,aliased:9,subquery:10,valueRows:11},dL=new WeakMap,fL=Symbol(`drizzle:chunkKind`);function pL(e,t){let n=t.has(G[U])?q.string:t.has(uL[U])?q.sql:t.has(gL[U])?q.name:t.has(rL[U])?q.column:t.has(bL[U])?q.param:t.has(CL[U])?q.placeholder:t.has($I[U])?q.table:t.has(oL[U])?q.view:t.has(uL.Aliased[U])?q.aliased:t.has(sL[U])?q.subquery:t.has(xL[U])?q.valueRows:q.other;return dL.set(e,n),n!==q.other&&Object.defineProperty(e.prototype,fL,{value:n}),n}function mL(e){if(typeof e!=`object`||!e)return q.other;let t=e[fL];if(t!==void 0)return t;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`?dL.get(n)??pL(n,BI(e)):q.other}function hL(e,t,n){return t===n}var gL=class{value;static[U]=`Name`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e){this.value=e}getSQL(){return new uL([this])}};function _L(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var vL={mapFromDriverValue:e=>e};vL.mapFromDriverValue.isNoop=!0;var yL={mapToDriverValue:e=>e};yL.mapToDriverValue.isNoop=!0,{...vL,...yL};var bL=class{value;encoder;codec;static[U]=`Param`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t=yL,n){this.value=e,this.encoder=t,this.codec=n}getSQL(){return new uL([this])}},xL=class{cells;encoders;static[U]=`ValueRows`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.cells=e,this.encoders=t}getSQL(){let{cells:e,encoders:t}=this,n=t.length,r=[];for(let i=0;i<e.length;++i){let a=i%n;r.push(a===0?i===0?K[`(`]:K[`), (`]:K[`, `]);let o=e[i],s=mL(o);r.push(s===q.sql||s===q.string?o:new bL(o,t[a]))}return r.push(K[`)`]),new uL(r)}shouldOmitSQLParens(){return!0}};function J(e,...t){let n=[];e[0]&&n.push(new G(e[0]));for(let r=0;r<t.length;++r){let i=t[r];i!==void 0&&n.push(i);let a=e[r+1];a&&n.push(new G(a))}return new uL(n)}(function(e){function t(){return new uL([])}e.empty=t;function n(e){return new uL(e)}e.fromList=n;function r(e){return new uL([new G(e)])}e.raw=r;function i(e,t){let{length:n}=e;if(t===void 0||n===0)return new uL(e.slice());let r=Array(n*2-1);for(let i=0,a=0;i<n;++i)r[a++]=e[i],i<n-1&&(r[a++]=t);return new uL(r)}e.join=i;function a(e){return new gL(e)}e.identifier=a;function o(e){return new CL(e)}e.placeholder=o;function s(e,t){return new bL(e,t)}e.param=s;function c(e){let t=SL(e);if(t.length)return J.raw(t)}e.comment=c})(J||={});function SL(e){let t=SL.encodeInput(e);return t.length?`/*${t}*/`:``}(function(e){function t(e,t){let r;if(typeof e==`object`&&typeof t==`object`)r=n({...e,...t});else if(e&&t)r=[n(e),n(t)].filter(e=>e.length).join(`,`);else if(t)r=n(t);else if(e)r=n(e);else return``;return r.length?`/*${r}*/`:``}e.merge=t;function n(e){if(typeof e==`string`)return e.length?i(e):e;let t=[];for(let[n,i]of Object.entries(e)){if(i==null||i===``)continue;let e=r(n),a=r(String(i));t.push(`${e}='${a}'`)}return t.length?t.sort().join(`,`):``}e.encodeInput=n;function r(e){return encodeURIComponent(e).replace(/'/g,`\\'`)}e.sanitizeObjectElement=r;function i(e){return e.replace(/\/\*/g,`/ *`).replace(/\*\//g,`* /`)}e.sanitizeStringInput=i})(SL||={}),(function(e){class t{sql;fieldAlias;static[U]=`SQL.Aliased`;static[Symbol.hasInstance](e){return W(e,this)}isSelectionField=!1;origin;constructor(e,t){this.sql=e,this.fieldAlias=t}getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(uL||={});var CL=class{name;static[U]=`Placeholder`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}getSQL(){return new uL([this])}};function wL(e){let t=e.queryChunks,n;for(let e=0;e<t.length;++e){let r=t[e];W(r,rL)&&((n??=[...t])[e]=J.identifier(r.name))}if(!n)return e;let r=new uL(n);return r.decoder=e.decoder,r.shouldInlineParams=e.shouldInlineParams,r}function TL(e,t){for(let n=0;n<e.length;++n){let r=e[n];switch(mL(r)){case q.table:t.add(r[JI]);break;case q.sql:TL(r.queryChunks,t);break;case q.param:{let e=r.value;mL(e)===q.sql&&TL(e.queryChunks,t);break}case q.subquery:TL(r._.sql.queryChunks,t);break;case q.valueRows:TL(r.cells,t);break;case q.other:case q.aliased:Array.isArray(r)?TL(r,t):lL(r)&&TL(r.getSQL().queryChunks,t)}}}rL.prototype.getSQL=function(){return new uL([this])},G.prototype.getSQL=function(){return new uL([this])},sL.prototype.getSQL=function(){return new uL([this])};function EL(e,t){Object.defineProperty(e,XI,{get(){let e=t(this);return Object.defineProperty(this,XI,{value:e,enumerable:!1,configurable:!0,writable:!0}),e},configurable:!0})}function DL(e,t){return new uL(e===void 0?[new gL(t)]:[new gL(e),K[`.`],new gL(t)])}EL($I.prototype,e=>DL(e[UI],e[HI])),EL(oL.prototype,e=>DL(e[iL].schema,e[iL].name)),EL(sL.prototype,e=>new gL(e._.alias));function OL(e,t){let n=Array(t.length);for(let r=0;r<t.length;++r){let i=t[r],a=[];for(let t=0;t<e.length;++t){let n=e[t].path;n.length>1&&n[0]===i&&a.push(t)}n[r]={key:i,leaves:a}}return n}var kL=Object.getPrototypeOf(()=>null).constructor;function AL(e,t){let n=[],r=[];r.push(`const [ ${e.map((e,t)=>`c${t}`).join(`, `)} ] = rows[i];`);let i={},a=new Set(t??[]),o=Array(e.length);for(let t=0;t<e.length;++t){let{field:r,fieldType:a,path:s,codec:c,arrayDimensions:l}=e[t],u,d,f;switch(a){case`Column`:u=r,f=`field: decoder${t}`;break;case`SQL`:u=r.decoder,f=`field: { decoder: decoder${t} }`;break;case`Subquery`:u=r._.sql.decoder,f=`field: { _: { sql: { decoder: decoder${t} } } }`;break;default:u=r.sql.decoder,f=`field: { sql: { decoder: decoder${t} } }`}d=`decoder${t}.mapFromDriverValue`,u.mapFromDriverValue.isNoop&&(d=``),d?n.push(`const { ${f}${c?`, codec: codec${t}`:``} } = columns[${t}];`):c&&n.push(`const { codec: codec${t} } = columns[${t}];`);let p=`c${t}`,m=p;c&&(m=`codec${t}(${m}, ${l})`),d&&(m=`${d}(${m})`),o[t]=p===m?`${p}`:`${p} === null ? ${p} : ${m}`,s.length>1&&(i[s[0]]??=[]).push(p)}r.push(`mapped[i] = {`);let s=[];for(let t=0;t<e.length;++t){let{path:n}=e[t],c=n.map(e=>JSON.stringify(e)),l=o[t],u=n.slice(0,-1),d=0;for(;d<s.length&&d<u.length&&s[d]===u[d];)d++;for(let e=s.length-1;e>=d;--e)r.push(`${` `.repeat(e+1)}},`);for(let e=d;e<u.length;++e){let t=e===0&&a.has(n[0]);r.push(`${` `.repeat(e+1)}${c[e]}: ${t?`${i[n[0]].map(e=>`${e} === null`).join(` && `)} ? null : {`:`{`}`)}s=u,r.push(`${` `.repeat(n.length)}${c[n.length-1]}: ${l},`)}for(let e=s.length-1;e>=0;--e)r.push(`${` `.repeat(e+1)}},`);return r.push(`};`),`${n.length?`${n.join(`
|
|
18
|
+
`)}\n\t`:``}for (let i = 0; i < length; ++i) {
|
|
19
|
+
${r.join(`
|
|
20
|
+
`)}
|
|
21
|
+
}`}function jL(e,t){let n=`\t"use strict";
|
|
22
|
+
const { columns } = this;
|
|
23
|
+
const { length } = rows;
|
|
24
|
+
const mapped = new Array(length);
|
|
25
|
+
${AL(e,t)}
|
|
26
|
+
return mapped;
|
|
27
|
+
//# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new kL(`rows`,n).bind({columns:e}),{body:`function jitQueryMapper (rows) {\n${n}\n}`})}function ML(e,t){let n=Array(e.length);for(let t=0;t<e.length;++t){let{field:r,fieldType:i,codec:a,arrayDimensions:o}=e[t],s;switch(i){case`Column`:s=r;break;case`SQL`:s=r.decoder;break;case`Subquery`:s=r._.sql.decoder;break;default:s=r.sql.decoder}let c;c=s.mapFromDriverValue.isNoop?a?e=>a(e,o):void 0:a?e=>s.mapFromDriverValue(a(e,o)):e=>s.mapFromDriverValue(e),n[t]=c}let r=t?.length?OL(e,t):void 0;return(t=>{let{length:i}=t,a=Array(i);for(let o=0;o<i;++o){let i=t[o],s={};for(let t=0;t<e.length;++t){let{path:r}=e[t],a=s;for(let e=0;e<r.length;++e){let o=r[e];if(e<r.length-1)o in a||(a[o]={}),a=a[o];else{let e=n[t],r=i[t];a[o]=r===null?null:e?e(r):r}}}if(r)for(let e=0;e<r.length;++e){let{key:t,leaves:n}=r[e],a=!0;for(let e=0;e<n.length;++e)if(i[n[e]]!==null){a=!1;break}a&&(s[t]=null)}a[o]=s}return a})}function NL(e,t,n,r=[]){let i=Object.entries(e);for(let e=0;e<i.length;++e){let[a,o]=i[e];if(typeof a!=`string`)return r;let s=t?[...t,a]:[a];if(W(o,rL))r.push({path:s,field:o,fieldType:`Column`,codec:n?.get(o,`normalize`),arrayDimensions:o.dimensions,column:o});else if(W(o,uL)){let e=PL(o);r.push(e?{path:s,field:o,fieldType:`SQL`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`SQL`})}else if(W(o,uL.Aliased)){let e=PL(o);r.push(e?{path:s,field:o,fieldType:`SQL.Aliased`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`SQL.Aliased`})}else if(W(o,sL)){let e,t=Object.values(o._.selectedFields)[0],i;W(t,rL)?(e=t,i=t):W(t,uL)?(e=PL(t),i=t.decoder):(e=PL(t),i=t.sql.decoder),i&&(o._.sql.decoder=i),r.push(e?{path:s,field:o,fieldType:`Subquery`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`Subquery`})}else W(o,$I)?NL(o[$I.Symbol.Columns],s,n,r):NL(o,s,n,r)}return r}function PL(e){let{decoder:t}=e.getSQL();return hL(t,mL(t),q.column)?t:void 0}function FL(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function IL(e){return e[$I.Symbol.Columns]}function LL(e){let t=mL(e);return hL(e,t,q.subquery)?e._.alias:hL(e,t,q.view)?e[iL].name:hL(e,t,q.sql)?void 0:e[$I.Symbol.IsAlias]?e[$I.Symbol.Name]:e[$I.Symbol.BaseName]}function RL(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;function zL(e,t=4096){let n=new Map;return r=>{let i=n.get(r);return i===void 0&&(n.size>=t&&n.clear(),i=e(r),n.set(r,i)),i}}var BL=class{table;ignoreColumnAlias;static[U]=`ColumnTableAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.table=e,this.ignoreColumnAlias=t}get(e,t){return t===`table`?this.table:t===`isAlias`&&this.ignoreColumnAlias?!1:t===tL&&!this.ignoreColumnAlias?()=>e:e[t]}},VL=class{view;selection;ignoreColumnAlias;static[U]=`ViewSelectionAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t,n){this.view=e,this.selection=t,this.ignoreColumnAlias=n}memo;columnHandler;get(e,t){let n=e[t];if(typeof n!=`object`||!n)return n;let r=this.memo??=new WeakMap,i=r.get(n);return i===void 0&&(i=hL(n,mL(n),q.column)?new Proxy(n,this.columnHandler??=new BL(this.view,this.ignoreColumnAlias)):lL(n)?n:new Proxy(n,this),r.set(n,i)),i}},HL=class{alias;replaceOriginalName;ignoreColumnAlias;static[U]=`TableAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t,n){this.alias=e,this.replaceOriginalName=t,this.ignoreColumnAlias=n}qualifier;proxiedColumns;memo;columnHandler;get(e,t,n){if(t===XI)return this.qualifier??=J.identifier(this.alias);if(t===$I.Symbol.IsAlias)return!0;if(t===$I.Symbol.Name||this.replaceOriginalName&&t===$I.Symbol.OriginalName)return this.alias;if(t===$I.Symbol.Columns){let t=e[$I.Symbol.Columns];return t&&(hL(e,mL(e),q.view)?this.aliasSelection(t,n):this.getProxiedColumns(t,n))}if(t===iL){let t=e[iL],r=this.memo??=new WeakMap,i=r.get(t);return i===void 0&&r.set(t,i={...t,name:this.alias,isAlias:!0,selectedFields:this.aliasSelection(t.selectedFields,n)}),i}let r=e[t];if(hL(r,mL(r),q.column)){let i=e[$I.Symbol.Columns];if(typeof t==`string`&&i?.[t]===r)return this.getProxiedColumns(i,n)[t];let a=this.memo??=new WeakMap,o=a.get(r);return o===void 0&&a.set(r,o=this.aliasColumn(r,n)),o}return r}aliasColumn(e,t){return new Proxy(e,this.columnHandler??=new BL(t,this.ignoreColumnAlias))}aliasSelection(e,t){let n=this.memo??=new WeakMap,r=n.get(e);return r===void 0&&n.set(e,r=new Proxy(e,new VL(t,e,this.ignoreColumnAlias))),r}getProxiedColumns(e,t){if(this.proxiedColumns)return this.proxiedColumns;let n={};for(let r of Object.keys(e))n[r]=this.aliasColumn(e[r],t);return this.proxiedColumns=n}},UL=class{subquery;alias;static[U]=`SubquerySelectionAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.subquery=e,this.alias=t}memo;columnHandler;get(e,t){let n=e[t];if(typeof n!=`object`||!n)return n;let r=this.memo??=new WeakMap,i=r.get(n);if(i!==void 0)return i;let a=mL(n);return hL(n,a,q.column)?i=new Proxy(n,this.columnHandler??=new BL(this.subquery,!0)):hL(n,a,q.aliased)?(i=n.clone(),i.isSelectionField=!0,i.origin=this.alias):i=n,r.set(n,i),i}},WL=class{alias;static[U]=`SubqueryAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.alias=e}qualifier;config;selection;get(e,t,n){if(t===XI)return this.qualifier??=J.identifier(this.alias);if(t===$I.Symbol.IsAlias)return!0;if(t===$I.Symbol.Name)return this.alias;if(t===$I.Symbol.OriginalName)return e._.alias;if(t!==$I.Symbol.Schema)return t===`_`?this.config??={...e._,alias:this.alias,isWith:!0,selectedFields:this.aliasSelection(e,n)}:t===$I.Symbol.Columns?this.aliasSelection(e,n):e[t]}aliasSelection(e,t){return this.selection??=new Proxy(e._.selectedFields,new UL(t,this.alias))}},GL=class{alias;static[U]=`ColumnAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.alias=e}get(e,t){return t===`isAlias`?!0:t===`name`?this.alias:t===`keyAsName`?!1:t===tL?()=>e:e[t]}};function KL(e,t){return hL(e,mL(e),q.subquery)?new Proxy(e,new WL(t)):new Proxy(e,new HL(t,!1,!1))}function qL(e){let t=e[$I.Symbol.Schema],n=J.identifier(e[$I.Symbol.OriginalName]);return t?J`${J.identifier(t)}.${n} ${e}`:J`${n} ${e}`}function JL(e,t){return new Proxy(e,new GL(t))}rL.prototype.as=function(e){return JL(this,e)};function YL(e){return e[tL]()}var XL=class{static[U]=`ColumnBuilder`;static[Symbol.hasInstance](e){return W(e,this)}config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default(e){return this.$defaultFn(e)}$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate(e){return this.$onUpdateFn(e)}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e,t){this.config.name===``&&(this.config.name=t(e))}};function ZL(e,t){if(_L(t)&&!lL(e)){let n=mL(e);if(n!==q.param&&n!==q.placeholder&&n!==q.column&&n!==q.table&&n!==q.view)return new bL(e,t)}return e}var QL=(e,t,n)=>new uL([e,t,ZL(n,e)]),Y=(e,t)=>QL(e,K[` = `],t),$L=(e,t)=>QL(e,K[` <> `],t),eR=(e,t)=>{let n=Array(e.length*2+1),r=e.length-1;n[0]=K[`((`];for(let i=0;i<r;i++)n[i*2+1]=e[i],n[i*2+2]=t;return n[r*2+1]=e[r],n[r*2+2]=K[`))`],new uL(n)};function tR(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new uL(t):eR(t,K[`) and (`])}function nR(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new uL(t):eR(t,K[`) or (`])}function rR(e){if(e)return W(e,uL)?J`not (${e})`:J`not ${e}`}var iR=(e,t)=>QL(e,K[` > `],t),aR=(e,t)=>QL(e,K[` >= `],t),oR=(e,t)=>QL(e,K[` < `],t),sR=(e,t)=>QL(e,K[` <= `],t);function cR(e,t){return Array.isArray(t)?t.length===0?new uL([K[`1 = 0`]]):new uL([e,K[` in `],t.map(t=>ZL(t,e))]):QL(e,K[` in `],t)}function lR(e,t){return Array.isArray(t)?t.length===0?new uL([K[`1 = 1`]]):new uL([e,K[` not in `],t.map(t=>ZL(t,e))]):QL(e,K[` not in `],t)}function uR(e){return J`(${e} is null)`}function dR(e){return J`(${e} is not null)`}function fR(e){return J`exists ${e}`}function pR(e){return J`not exists ${e}`}function mR(e,t,n){return J`${e} between ${ZL(t,e)} and ${ZL(n,e)}`}function hR(e,t,n){return J`${e} not between ${ZL(t,e)} and ${ZL(n,e)}`}function gR(e,t){return J`${e} like ${t}`}function _R(e,t){return J`${e} not like ${t}`}function vR(e,t){return J`${e} ilike ${t}`}function yR(e,t){return J`${e} not ilike ${t}`}function bR(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);let n=ZL(t,e),r=J`${Array.isArray(n)?new bL(n):n}`;return J`${e} @> ${r}`}return J`${e} @> ${ZL(t,e)}`}function xR(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);let n=ZL(t,e),r=J`${Array.isArray(n)?new bL(n):n}`;return J`${e} <@ ${r}`}return J`${e} <@ ${ZL(t,e)}`}function SR(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);let n=ZL(t,e),r=J`${Array.isArray(n)?new bL(n):n}`;return J`${e} && ${r}`}return J`${e} && ${ZL(t,e)}`}function CR(e){return J`${e} asc`}function wR(e){return J`${e} desc`}var TR={and:tR,between:mR,eq:Y,exists:fR,gt:iR,gte:aR,ilike:vR,inArray:cR,arrayContains:bR,arrayContained:xR,arrayOverlaps:SR,isNull:uR,isNotNull:dR,like:gR,lt:oR,lte:sR,ne:$L,not:rR,notBetween:hR,notExists:pR,notLike:_R,notIlike:yR,notInArray:lR,or:nR,sql:J},ER={sql:J,asc:CR,desc:wR};function DR(e,t,n,r=!1,i=!1,a=!0){let o=t?1:e.length,s=n.map(({field:e,fieldType:t,codec:n,arrayDimensions:r,subqueryDecoder:i})=>{let o;switch(t){case`Column`:o=e;break;case`SQL`:o=e.decoder;break;case`SQL.Aliased`:o=e.sql.decoder;break;case`Subquery`:o=i??vL;break;case`Nested`:o=vL;break;default:o=e.getSQL().decoder}return a&&e.mapFromJsonValue?t=>e.mapFromJsonValue(t):o.mapFromDriverValue.isNoop?n?e=>n(e,r):void 0:n?e=>o.mapFromDriverValue(n(e,r)):e=>o.mapFromDriverValue(e)});for(let a=0;a<o;++a){let o=t?e:e[a];for(let e=0;e<n.length;++e){let t=n[e];if(t.selection){if(o[t.key]===null)continue;if(r){if(o[t.key]=JSON.parse(o[t.key]),o[t.key]===null)continue}else i&&typeof o[t.key]==`string`&&(o[t.key]=JSON.parse(o[t.key]));if(t.isArray){DR(o[t.key],!1,t.selection,!1,i);continue}DR(o[t.key],!0,t.selection,!1,i);continue}if(o[t.key]===null)continue;let a=s[e];a&&(o[t.key]=a(o[t.key]))}}return e}function OR(e,t,n,r=!1,i=!1){let a=t?1:e.length,o=n.map(({field:e,fieldType:t,codec:n,arrayDimensions:r,subqueryDecoder:i})=>{let a;switch(t){case`Column`:a=e;break;case`SQL`:a=e.decoder;break;case`SQL.Aliased`:a=e.sql.decoder;break;case`Subquery`:a=i??vL;break;case`Nested`:a=vL;break;default:a=e.getSQL().decoder}return a.mapFromDriverValue.isNoop?n?e=>n(e,r):void 0:n?e=>a.mapFromDriverValue(n(e,r)):e=>a.mapFromDriverValue(e)}),s=Array(a);for(let c=0;c<a;++c){let a=t?e:e[c],l={};for(let e=0;e<n.length;++e){let t=n[e],s=a[e];if(t.selection){if(s===null){l[t.key]=null;continue}if(r){if(s=JSON.parse(s),s===null){l[t.key]=null;continue}}else i&&typeof s==`string`&&(s=JSON.parse(s));t.isArray?DR(s,!1,t.selection,!1,i):DR(s,!0,t.selection,!1,i),l[t.key]=s;continue}if(s===null){l[t.key]=null;continue}let c=o[e];l[t.key]=c?c(s):s}s[c]=l}return t?s[0]:s}function kR({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){return(o=>t&&!o[0]?o[0]:a?OR(t?o[0]:o,t,e,n,r):DR(t?o[0]:o,t,e,n,r,i))}function AR(e,t,n,r,i,a,o,s,c){let l=[],u=[],d=!1,f=e.map(()=>`c${s.n++}`),p=e.map((e,t)=>c?f[t]:`${JSON.stringify(e.key)}: ${f[t]}`);l.push(c?`let [ ${p.join(`, `)} ] = ${t};`:`let { ${p.join(`, `)} } = ${t};`);for(let[t,{field:c,fieldType:p,key:m,codec:h,isArray:g,selection:_,arrayDimensions:v,subqueryDecoder:ee}]of e.entries()){let e=`${n}[${t}]`,te=JSON.stringify(m),ne=f[t];if(_){r?(l.push(`if (${ne} !== null) ${ne} = JSON.parse(${ne});`),d=!0):i&&(l.push(`if (typeof ${ne} === 'string') ${ne} = JSON.parse(${ne});`),d=!0);let t=`s${s.n++}`,n=o.length;if(o.push(`const { selection: ${t} } = ${e};`),g){let e=`j${s.n++}`,r=AR(_,`${ne}[${e}]`,t,!1,i,!0,o,s,!1);if(r.hasWork){d=!0,l.push(`if (${ne} !== null) {`),l.push(`\tfor (let ${e} = 0; ${e} < ${ne}.length; ++${e}) {`);for(let e of r.bodyStmts)l.push(`\t\t${e}`);l.push(`\t\t${ne}[${e}] = ${r.literal};`),l.push(` }`),l.push(`}`)}else o.splice(n,1)}else{let e=AR(_,ne,t,!1,i,!0,o,s,!1);if(e.hasWork){d=!0,l.push(`if (${ne} !== null) {`);for(let t of e.bodyStmts)l.push(`\t${t}`);l.push(`\t${ne} = ${e.literal};`),l.push(`}`)}else o.splice(n,1)}u.push(`${te}: ${ne}`);continue}let re=``,ie=``,ae=!1;switch(p){case`Column`:if(a&&c.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: dec${e}`,re=`dec${e}.mapFromJsonValue`}else if(!c.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: dec${e}`,re=`dec${e}.mapFromDriverValue`}break;case`SQL`:if(a&&c.decoder.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: { decoder: dec${e} }`,re=`dec${e}.mapFromJsonValue`}else if(!c.decoder.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: { decoder: dec${e} }`,re=`dec${e}.mapFromDriverValue`}break;case`SQL.Aliased`:if(a&&c.sql.decoder.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: { sql: { decoder: dec${e} } }`,re=`dec${e}.mapFromJsonValue`}else if(!c.sql.decoder.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: { sql: { decoder: dec${e} } }`,re=`dec${e}.mapFromDriverValue`}break;case`Subquery`:if(a&&ee?.mapFromJsonValue){ae=!0;let e=s.n++;ie=`subqueryDecoder: dec${e}`,re=`dec${e}.mapFromJsonValue`}else if(ee&&!ee.mapFromDriverValue.isNoop){let e=s.n++;ie=`subqueryDecoder: dec${e}`,re=`dec${e}.mapFromDriverValue`}break;case`Nested`:break;default:{let t=c.getSQL();if(a&&t.decoder.mapFromJsonValue){ae=!0;let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),re=`dec${t}.mapFromJsonValue`}else if(!t.decoder.mapFromDriverValue.isNoop){let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),re=`dec${t}.mapFromDriverValue`}}}let oe=``;if(!ae&&h&&(oe=`codec${s.n++}`),ie||oe){let t=[];ie&&t.push(ie),oe&&t.push(`codec: ${oe}`),o.push(`const { ${t.join(`, `)} } = ${e};`)}if(re||oe){d=!0;let e=ne;oe&&(e=`${oe}(${e}, ${v})`),re&&(e=`${re}(${e})`),u.push(`${te}: ${ne} === null ? null : ${e}`)}else u.push(`${te}: ${ne}`)}return{bodyStmts:l,literal:`{ ${u.join(`, `)} }`,hasWork:d}}function jR({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){let o=[],s=AR(e,`row`,`selection`,n,r,!a&&i,o,{n:0},!!a),c=[];c.push(` "use strict";
|
|
28
|
+
const { selection } = this;`);for(let e of o)c.push(`\t${e}`);if(a){if(t){c.push(` const row = rows[0];`),c.push(` if (!row) return undefined;`);for(let e of s.bodyStmts)c.push(`\t${e}`);c.push(`\treturn ${s.literal};`)}else{c.push(` const { length } = rows;`),c.push(` const mapped = new Array(length);`),c.push(` for (let i = 0; i < length; ++i) {`),c.push(` const row = rows[i];`);for(let e of s.bodyStmts)c.push(`\t\t${e}`);c.push(`\t\tmapped[i] = ${s.literal};`),c.push(` }`),c.push(` return mapped;`)}}else if(!s.hasWork)c.push(t?` return rows[0];`:` return rows;`);else if(t){c.push(` const row = rows[0];`),c.push(` if (!row) return undefined;`);for(let e of s.bodyStmts)c.push(`\t${e}`);c.push(`\trows[0] = ${s.literal};`),c.push(` return rows[0];`)}else{c.push(` for (let i = 0; i < rows.length; ++i) {`),c.push(` const row = rows[i];`);for(let e of s.bodyStmts)c.push(`\t\t${e}`);c.push(`\t\trows[i] = ${s.literal};`),c.push(` }`),c.push(` return rows;`)}c.push(` //# sourceURL=drizzle:jit-relational-query-mapper`);let l=c.join(`
|
|
29
|
+
`);return Object.assign(new kL(`rows`,l).bind({selection:e}),{body:`function jitRqbMapper (rows) {\n${l}\n}`})}function MR(e,t){let n=e[WI][t],r=mL(n);return hL(n,r,q.column)?n:new uL([e,K[`.`],J.identifier(hL(n,r,q.aliased)?n.fieldAlias:t)])}var NR=class{chunks;separator;static[U]=`ConditionsCollector`;static[Symbol.hasInstance](e){return W(e,this)}start;count=0;mark=0;conditionStart=0;constructor(e,t){this.chunks=e,this.separator=t,this.start=e.length,e.push(void 0)}open(){this.mark=this.chunks.length,this.count&&this.chunks.push(this.separator),this.conditionStart=this.chunks.length}close(){this.chunks.length===this.conditionStart?this.chunks.length=this.mark:++this.count}push(e){e!==void 0&&(this.count&&this.chunks.push(this.separator),this.chunks.push(e),++this.count)}pushChunks(e){if(e?.length){this.count&&this.chunks.push(this.separator);for(let t=0;t<e.length;++t)this.chunks.push(e[t]);++this.count}}finish(){return this.count?(this.count>1&&(this.chunks[this.start]=K[`((`],this.chunks.push(K[`))`])),!0):(this.chunks.length=this.start,!1)}};function PR(e,t,n=[]){if(t===XR)return;if(t===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);if(typeof t!=`object`||W(t,CL))return n.push(Y(e,t)),n;let r=Object.entries(t);if(!r.length)return;let i=new NR(n,K[`) and (`]);for(let[t,a]of r)if(a!==XR){if(a===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);switch(t){case`NOT`:{i.open();let t=n.length;n.push(K[`not (`]),PR(e,a,n),n.length===t+1?n.length=t:n.push(K[`)`]),i.close();continue}case`OR`:case`AND`:{let r=a;if(!r.length)throw Error(`Unexpected empty array in filters' '${t}' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);i.open();let o=new NR(n,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of r)o.open(),PR(e,t,n),o.close();o.finish(),i.close();continue}case`isNotNull`:case`isNull`:if(!a)continue;i.push(TR[t](e));continue;case`in`:i.push(TR.inArray(e,a));continue;case`notIn`:i.push(TR.notInArray(e,a));continue;default:i.push(TR[t](e,a));continue}}return i.finish()?n:void 0}function FR(e,t,n={},r={},i,a=0,o=[]){if(t===XR)return{sql:void 0,hasRelationFilters:!1};if(t===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);let s=Object.entries(t);if(!s.length)return{sql:void 0,hasRelationFilters:!1};let c=new NR(o,K[`) and (`]),l=!1,u=t=>{FR(e,t,n,r,i,a,o).hasRelationFilters&&(l=!0)};for(let[t,d]of s)if(d!==XR){if(d===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);switch(t){case`RAW`:{let t=typeof d==`function`?d(e,TR):d.getSQL();if(t===XR)continue;c.push(t),l=!0;continue}case`OR`:case`AND`:{let e=d;if(!e.length)throw Error(`Unexpected empty array in filters' '${t}' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);c.open();let n=new NR(o,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of e)n.open(),u(t),n.close();n.finish(),c.close();continue}case`NOT`:{c.open();let e=o.length;o.push(K[`not (`]),u(d),o.length===e+1?o.length=e:o.push(K[`)`]),c.close();continue}default:{if(Object.prototype.hasOwnProperty.call(e[WI],t)&&e[WI][t]){c.open(),PR(MR(e,t),d,o),c.close();continue}let s=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!s)throw new VI({message:`Unknown relational filter field: "${t}"`});i&&(JR(i,s.targetTable),JR(i,s.throughTable));let u=KL(s.targetTable,`f${a}`),f=s.throughTable?KL(s.throughTable,`ft${a}`):void 0,p=r[s.targetTableName],m=typeof d==`boolean`;c.open();let h=o.length;o.push(d?K[`exists (select * from `]:K[`not exists (select * from `]),YR(u,o),f&&(o.push(K[` inner join `]),YR(f,o),o.push(K[` on `]));let{filter:g}=UR(s,e,u,f,[],o);o.push(K[` where `]);let _=new NR(o,K[`) and (`]);if(_.pushChunks(g),!m){_.open();let e=FR(u,d,p.relations,r,i,a+1,o);if(_.close(),!e.sql){o.length=h,c.close();continue}}_.finish(),o.push(K[`)`]),c.close(),l=!0}}}return{sql:c.finish()?o:void 0,hasRelationFilters:l}}var IR=new Set([`min`,`max`,`count`,`avg`,`first`]);function LR(e,t){if(typeof e!=`string`)throw new VI({message:`Invalid order "${t}": expected a string, got ${e===null?`null`:typeof e}`});let n=e.split(`(`),r=n[0];if(r!==`asc`&&r!==`desc`)throw new VI({message:`Invalid order "${t}": unknown direction "${r}" in "${e}", expected "asc" or "desc"`});if(n.length===1)return{direction:r};if(n.length>2||!n[1].endsWith(`)`))throw new VI({message:`Invalid order "${t}": malformed value "${e}", expected "${r}" or "${r}(<aggregate>)"`});let i=n[1].slice(0,-1);if(!IR.has(i))throw new VI({message:`Invalid order "${t}": unknown aggregate "${i}" in "${e}", expected one of: ${[...IR].join(`, `)}`});return{direction:r,aggregate:i}}function RR(e,t,n,r,i,a,o,s,c=s.length){for(let[l,u]of Object.entries(t)){if(!u)continue;let t=o?`${o.path}.${l}`:l;if(Object.prototype.hasOwnProperty.call(e[WI],l)&&e[WI][l]){let{direction:n,aggregate:r}=LR(u,t);if(!!r!=!!o?.isAggregated)throw new VI({message:`Invalid order "${t}": expected ${o?.isAggregated?`"asc(<aggregate>)" or "desc(<aggregate>)", with aggregate being one of: min, max, count, avg, first`:`"asc" or "desc"`}, got "${u}"`});let i=MR(e,l);if(s.length>c&&s.push(K[`, `]),!o){s.push(i,n===`asc`?K[` asc`]:K[` desc`]);continue}let d=!r||r===`first`;s.push(K[`(select `]),d?(a===`top`&&s.push(K[`top(1) `]),s.push(i)):s.push(K[`${r}(`],i,K[`)`]),s.push(K[` from `]);for(let e=0;e<o.from.length;++e)s.push(o.from[e]);let f=s.length;s.push(K[` where `]);let p=new NR(s,K[`) and (`]);for(let e=0;e<o.filters.length;++e)p.pushChunks(o.filters[e]);p.finish()||(s.length=f),d&&a===`limit`&&s.push(K[` limit 1`]),s.push(K[`)`],n===`asc`?K[` asc`]:K[` desc`]);continue}let d=Object.prototype.hasOwnProperty.call(n,l)?n[l]:void 0;if(!d)throw new VI({message:`Unknown relational order field: "${t}"`});let f=d.relationType===`many`&&typeof u==`string`?LR(u,t):void 0,p=f?.aggregate===`count`?f.direction:void 0;if(typeof u!=`object`&&!p)throw new VI({message:`Invalid order "${t}": expected an object with fields of relation to order by${d.relationType===`many`?`, "asc(count)" or "desc(count)"`:``}, got "${u}"`});i&&(JR(i,d.targetTable),JR(i,d.throughTable));let m=o?.depth??0,h=KL(d.targetTable,`o${m}`),g=d.throughTable?KL(d.throughTable,`ot${m}`):void 0,_=o?[...o.from,K[` cross join `]]:[];YR(h,_),g&&(_.push(K[` inner join `]),YR(g,_),_.push(K[` on `]));let{filter:v}=UR(d,e,h,g,[],_),ee=o?[...o.filters,v]:[v];if(typeof u!=`object`){s.length>c&&s.push(K[`, `]),s.push(K[`(select count(*) from `]);for(let e=0;e<_.length;++e)s.push(_[e]);let e=s.length;s.push(K[` where `]);let t=new NR(s,K[`) and (`]);for(let e=0;e<ee.length;++e)t.pushChunks(ee[e]);t.finish()||(s.length=e),s.push(K[`)`],p===`asc`?K[` asc`]:K[` desc`])}else RR(h,u,r[d.targetTableName]?.relations??{},r,i,a,{from:_,filters:ee,isAggregated:!!o?.isAggregated||d.relationType===`many`,depth:m+1,path:t},s,c)}return s}function zR(e,t,n={},r={},i,a=`limit`,o=[]){let s=o.length;if(typeof t==`function`){let n=t(e,ER);if(!n)return;let r=mL(n);if(hL(n,r,q.sql))o.push(n);else if(Array.isArray(n))for(let e=0;e<n.length;++e){e&&o.push(K[`, `]);let t=n[e];o.push(t),mL(t)!==q.sql&&o.push(K[` asc`])}else hL(n,r,q.column)&&o.push(n,K[` asc`]);return o.length>s?o:void 0}return RR(e,t,n,r,i,a,void 0,o,s),o.length>s?o:void 0}function BR(e,t,n,r,i=[]){let a=i.length,o=[];for(let[s,c]of Object.entries(t)){let t=typeof c==`function`?c(e,{sql:TR.sql}):c;if(!t)continue;let l=t.getSQL(),u=n?PL(l):void 0,d=u&&(!r||!u.jsonSelectIdentifier)?new uL([n.apply(u,r?`castInJson`:`cast`,new uL([K[`(`],l,K[`)`]])),K[` as `],J.identifier(s)]):new uL([K[`(`],l,K[`) as `],J.identifier(s)]);d.decoder=l.decoder,i.length>a&&i.push(K[`, `]),i.push(d),o.push(u&&(!r||!u.mapFromJsonValue)?{key:s,field:d,fieldType:`SQL`,codec:n.get(u,r?`normalizeInJson`:`normalize`),arrayDimensions:u.dimensions}:{key:s,field:d,fieldType:`SQL`})}return{sql:i.length>a?i:void 0,selection:o}}function VR({_:{column:e,key:t}}){let n=mL(e);return J.identifier(hL(e,n,q.column)?e.name:hL(e,n,q.aliased)?e.fieldAlias:t)}function HR(e,t,n,r,i,a){e.open(),t.push(n,K[`.`],VR(r),K[` = `],i,K[`.`],VR(a)),e.close()}function UR(e,t,n,r,i=[],a=[]){let o=e.isFilterReversed?t:n,s=t[XI],c=n[XI],l=r?.[XI],u=new NR(i,K[`) and (`]);if(e.through){let{sourceColumns:t,targetColumns:n,through:{source:r,target:d}}=e;u.open(),FR(o,e.where,{},{},void 0,0,i),u.close();for(let e=0;e<t.length;++e)HR(u,i,s,t[e],l,r[e]);u.finish();let f=new NR(a,K[`) and (`]);for(let e=0;e<n.length;++e)HR(f,a,l,d[e],c,n[e]);return f.finish(),{filter:i,joinCondition:a}}let{sourceColumns:d,targetColumns:f}=e;for(let e=0;e<d.length;++e)HR(u,i,s,d[e],c,f[e]);return u.open(),FR(o,e.where,{},{},void 0,0,i),u.close(),u.finish(),{filter:i}}function WR(e,t,n,r,i,a,o=[]){let s=new NR(o,K[`) and (`]),c=!1;return t&&`where`in t&&(s.open(),c=FR(e,t.where,n,r,i,0,o).hasRelationFilters,s.close()),s.pushChunks(a),{sql:s.finish()?o:void 0,hasRelationFilters:c}}function GR(e,t,n,r,i,a,o){a?e.push(i.apply(a,o?`castInJson`:`cast`,new uL([t,K[`.`],J.identifier(n)]))):e.push(t,K[`.`],J.identifier(n)),e.push(K[` as `],J.identifier(r))}function KR(e,t,n,r,i,a,o,s){let c,l,u,d=mL(t);if(hL(t,d,q.column)){c=t,u=`Column`;let{jsonSelectIdentifier:i,dimensions:a}=t,l=r&&i?void 0:o.codecsOf(t)[r?`castInJson`:`cast`];if(l||r&&i){let r=new uL([e,K[`.`],J.identifier(t.name)]),o=l?l(r,a):i.call(t,r,J,a);s.push(o,K[` as `],J.identifier(n))}else s.push(e,K[`.`],J.identifier(t.name),K[` as `],J.identifier(n))}else if(hL(t,d,q.sql))c=PL(t),u=`SQL`,GR(s,e,n,n,o,c,r);else if(hL(t,d,q.aliased))c=PL(t),u=`SQL.Aliased`,GR(s,e,t.fieldAlias,n,o,c,r);else if(hL(t,d,q.subquery)){let i=Object.values(t._.selectedFields)[0],a=mL(i);hL(i,a,q.column)?(c=i,l=i):hL(i,a,q.aliased)?(c=PL(i),l=i.sql.decoder):hL(i,a,q.sql)&&(c=PL(i),l=i.decoder),u=`Subquery`,GR(s,e,t._.alias,n,o,c,r)}else if(lL(t))c=PL(t),u=`SQLWrapper`,GR(s,e,n,n,o,c,r);else throw new VI({message:t===void 0?`Unknown column: "${a}"."${n}"`:`Views and subqueries with nested selections are not supported by the relational query builder`});i.push(c?{key:n,field:t,fieldType:u,subqueryDecoder:l,codec:!r||!c.mapFromJsonValue?o.get(c,r?`normalizeInJson`:`normalize`):void 0,arrayDimensions:c.dimensions}:{key:n,field:t,fieldType:u,subqueryDecoder:l})}function qR(e,t,n,r,i,a,o,s){let c=o.length;if(!s){for(let s of Object.keys(t))o.length>c&&o.push(K[`, `]),KR(e,t[s],s,r,n,i,a,o);return!0}let l;for(let u of Object.keys(s)){let d=s[u];d!==void 0&&(l||=d,d&&(o.length>c&&o.push(K[`, `]),KR(e,t[u],u,r,n,i,a,o)))}if(l===!1)for(let l of Object.keys(t))s[l]!==!1&&(o.length>c&&o.push(K[`, `]),KR(e,t[l],l,r,n,i,a,o));return o.length>c}function JR(e,t){let n=mL(t);if(e.usedTables!==void 0&&hL(t,n,q.table)){e.usedTables.add(t[JI]);return}if(!hL(t,n,q.subquery))return;let r=t._.alias,i=e.subqueries.get(r);if(i&&i._.sql!==t._.sql)throw new VI({message:`Different subqueries with the same alias "${r}" are used in a single relational query - make sure every subquery in schema has a unique alias`});e.subqueries.set(r,t)}function YR(e,t=[]){if(!e[YI])return t.push(e),t;let n=e[UI];return n&&t.push(J.identifier(n),K[`.`]),t.push(J.identifier(e[KI]),K[` as `],e[XI]),t}var XR=Symbol.for(`drizzle:EmptyFilter`),ZR=class{static[U]=`SQLiteForeignKeyBuilder`;static[Symbol.hasInstance](e){return W(e,this)}reference;_onUpdate;_onDelete;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new QR(e,this)}},QR=class{table;static[U]=`SQLiteForeignKey`;static[Symbol.hasInstance](e){return W(e,this)}reference;onUpdate;onDelete;constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[HI],...r,n[0].table[HI],...i];return e??`${a.join(`_`)}_fk`}isNameExplicit(){return!!this.reference().name}};function $R(e){function t(){if(typeof e==`function`){let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignColumns:r}}return e}return new ZR(t)}var ez=class extends XL{static[U]=`SQLiteColumnBuilder`;foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:`always`,mode:t?.mode??`virtual`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>((n,r)=>{let i=new ZR(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)})(n,r))}},tz=class extends rL{static[U]=`SQLiteColumn`;table;constructor(e,t){super(e,t),this.table=e}},nz={},rz={cast:void 0,castInJson:void 0,castParam:void 0,normalize:void 0,normalizeInJson:void 0,normalizeParam:void 0},iz={cast:`cast`,castArray:`cast`,castInJson:`castInJson`,castArrayInJson:`castInJson`,castParam:`castParam`,castArrayParam:`castParam`,normalize:`normalize`,normalizeArray:`normalize`,normalizeInJson:`normalizeInJson`,normalizeArrayInJson:`normalizeInJson`,normalizeParam:`normalizeParam`,normalizeParamArray:`normalizeParam`},az=class{resolveTypes;codecs;static[U]=`CodecsCollection`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t=nz){this.resolveTypes=e,this.codecs=t}itemCodecsCache=new Map;arrayCodecsCache=new Map;codecsOf(e,t){let n=t??e.codec;if(!n)return rz;let r=!!e.dimensions,i=r?this.arrayCodecsCache:this.itemCodecsCache,a=i.get(n);if(a===void 0){let e=this.codecs[n];a=e?r?{cast:e.castArray,castInJson:e.castArrayInJson,castParam:e.castArrayParam,normalize:e.normalizeArray,normalizeInJson:e.normalizeArrayInJson,normalizeParam:e.normalizeParamArray}:{cast:e.cast,castInJson:e.castInJson,castParam:e.castParam,normalize:e.normalize,normalizeInJson:e.normalizeInJson,normalizeParam:e.normalizeParam}:rz,i.set(n,a)}return a}get(e,t,n){return this.codecsOf(e,n)[iz[t]]}apply(e,t,n,r){let i=iz[t],a=this.codecsOf(e,r)[i];return a?i===`castParam`?a(n,e,e.dimensions):a(n,e.dimensions):n}},oz={int:`integer`,int2:`integer`,int8:`integer`,tinyint:`integer`,smallint:`integer`,mediumint:`integer`,bool:`integer:boolean`,boolean:`integer:boolean`,float:`real`,double:`real`,"double precision":`real`,decimal:`numeric`,character:`text`,varchar:`text`,"varying character":`text`,nchar:`text`,"native character":`text`,nvarchar:`text`,clob:`text`,json:`text:json`};function sz(e){return oz[e]??e}var cz=typeof Buffer>`u`?new TextEncoder:void 0,lz=cz?e=>cz.encode(e):e=>Buffer.from(e),uz={integer:{integer:`integer`,"integer:boolean":`integer`,"integer:timestamp":`integer`,"integer:timestamp_ms":`integer`,real:`integer`,text:`integer`,"text:json":`integer`,blob:`integer`,"blob:json":`integer`,"blob:bigint":`integer`,numeric:`integer`,"numeric:number":`integer`,"numeric:bigint":`integer`},"integer:boolean":{integer:`integer:boolean`,"integer:boolean":`integer:boolean`,"integer:timestamp":`integer:boolean`,"integer:timestamp_ms":`integer:boolean`,real:`integer:boolean`,text:`integer:boolean`,"text:json":`integer:boolean`,blob:`integer:boolean`,"blob:json":`integer:boolean`,"blob:bigint":`integer:boolean`,numeric:`integer:boolean`,"numeric:number":`integer:boolean`,"numeric:bigint":`integer:boolean`},"integer:timestamp":{integer:`integer:timestamp`,"integer:boolean":`integer:timestamp`,"integer:timestamp":`integer:timestamp`,"integer:timestamp_ms":`integer:timestamp`,real:`integer:timestamp`,text:`integer:timestamp`,"text:json":`integer:timestamp`,blob:`integer:timestamp`,"blob:json":`integer:timestamp`,"blob:bigint":`integer:timestamp`,numeric:`integer:timestamp`,"numeric:number":`integer:timestamp`,"numeric:bigint":`integer:timestamp`},"integer:timestamp_ms":{integer:`integer:timestamp_ms`,"integer:boolean":`integer:timestamp_ms`,"integer:timestamp":`integer:timestamp_ms`,"integer:timestamp_ms":`integer:timestamp_ms`,real:`integer:timestamp_ms`,text:`integer:timestamp_ms`,"text:json":`integer:timestamp_ms`,blob:`integer:timestamp_ms`,"blob:json":`integer:timestamp_ms`,"blob:bigint":`integer:timestamp_ms`,numeric:`integer:timestamp_ms`,"numeric:number":`integer:timestamp_ms`,"numeric:bigint":`integer:timestamp_ms`},real:{integer:`real`,"integer:boolean":`real`,"integer:timestamp":`real`,"integer:timestamp_ms":`real`,real:`real`,text:`real`,"text:json":`real`,blob:`real`,"blob:json":`real`,"blob:bigint":`real`,numeric:`real`,"numeric:number":`real`,"numeric:bigint":`real`},text:{integer:`text`,"integer:boolean":`text`,"integer:timestamp":`text`,"integer:timestamp_ms":`text`,real:`text`,text:`text`,"text:json":`text`,blob:`text`,"blob:json":`text`,"blob:bigint":`text`,numeric:`numeric`,"numeric:number":`text`,"numeric:bigint":`text`},"text:json":{integer:`text:json`,"integer:boolean":`text:json`,"integer:timestamp":`text:json`,"integer:timestamp_ms":`text:json`,real:`text:json`,text:`text:json`,"text:json":`text:json`,blob:`text:json`,"blob:json":`blob:json`,"blob:bigint":`text:json`,numeric:`text:json`,"numeric:number":`text:json`,"numeric:bigint":`text:json`},blob:{integer:`blob`,"integer:boolean":`blob`,"integer:timestamp":`blob`,"integer:timestamp_ms":`blob`,real:`blob`,text:`blob`,"text:json":`blob`,blob:`blob`,"blob:json":`blob`,"blob:bigint":`blob`,numeric:`blob`,"numeric:number":`blob`,"numeric:bigint":`blob`},"blob:json":{integer:`blob:json`,"integer:boolean":`blob:json`,"integer:timestamp":`blob:json`,"integer:timestamp_ms":`blob:json`,real:`blob:json`,text:`blob:json`,"text:json":`blob:json`,blob:`blob:json`,"blob:json":`blob:json`,"blob:bigint":`blob:json`,numeric:`blob:json`,"numeric:number":`blob:json`,"numeric:bigint":`blob:json`},"blob:bigint":{integer:`blob:bigint`,"integer:boolean":`blob:bigint`,"integer:timestamp":`blob:bigint`,"integer:timestamp_ms":`blob:bigint`,real:`blob:bigint`,text:`blob:bigint`,"text:json":`blob:bigint`,blob:`blob:bigint`,"blob:json":`blob:bigint`,"blob:bigint":`blob:bigint`,numeric:`blob:bigint`,"numeric:number":`blob:bigint`,"numeric:bigint":`blob:bigint`},numeric:{integer:`numeric`,"integer:boolean":`numeric`,"integer:timestamp":`numeric`,"integer:timestamp_ms":`numeric`,real:`numeric`,text:`numeric`,"text:json":`numeric`,blob:`numeric`,"blob:json":`numeric`,"blob:bigint":`numeric`,numeric:`numeric`,"numeric:number":`numeric`,"numeric:bigint":`numeric`},"numeric:number":{integer:`numeric:number`,"integer:boolean":`numeric:number`,"integer:timestamp":`numeric:number`,"integer:timestamp_ms":`numeric:number`,real:`numeric:number`,text:`numeric:number`,"text:json":`numeric:number`,blob:`numeric:number`,"blob:json":`numeric:number`,"blob:bigint":`numeric:number`,numeric:`numeric:number`,"numeric:number":`numeric:number`,"numeric:bigint":`numeric:number`},"numeric:bigint":{integer:`numeric:bigint`,"integer:boolean":`numeric:bigint`,"integer:timestamp":`numeric:bigint`,"integer:timestamp_ms":`numeric:bigint`,real:`numeric:bigint`,text:`numeric:bigint`,"text:json":`numeric:bigint`,blob:`numeric:bigint`,"blob:json":`numeric:bigint`,"blob:bigint":`numeric:bigint`,numeric:`numeric:bigint`,"numeric:number":`numeric:bigint`,"numeric:bigint":`numeric:bigint`}};function dz(e,t){return uz[e]?.[t]}var fz=class extends ez{static[U]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteBigInt`)}build(e){return new pz(e,this.config)}},pz=class extends tz{static[U]=`SQLiteBigInt`;codec=`blob:bigint`;getSQLType(){return`blob`}mapToDriverValue=e=>lz(e.toString())},mz=class extends ez{static[U]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteBlobJson`)}build(e){return new hz(e,this.config)}},hz=class extends tz{static[U]=`SQLiteBlobJson`;codec=`blob:json`;getSQLType(){return`blob`}mapToDriverValue=e=>lz(JSON.stringify(e))},gz=class extends ez{static[U]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`object buffer`,`SQLiteBlobBuffer`)}build(e){return new _z(e,this.config)}},_z=class extends tz{static[U]=`SQLiteBlobBuffer`;codec=`blob`;getSQLType(){return`blob`}};function vz(e,t){let{name:n,config:r}=RL(e,t);return r?.mode===`bigint`?new fz(n):r?.mode===`buffer`?new gz(n):new mz(n)}var yz=class extends ez{static[U]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new bz(e,this.config)}},bz=class extends tz{static[U]=`SQLiteCustomColumn`;codec;sqlName;mapFromJsonValue;jsonSelectIdentifier;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapToDriverValue=t.customTypeParams.toDriver??this.mapToDriverValue,this.mapFromDriverValue=t.customTypeParams.fromDriver??this.mapFromDriverValue,this.mapFromJsonValue=t.customTypeParams.fromJson,this.jsonSelectIdentifier=t.customTypeParams.forJsonSelect;let n=typeof t.customTypeParams.codec==`string`||t.customTypeParams.codec===void 0?t.customTypeParams.codec:t.customTypeParams.codec(t.fieldConfig);this.codec=typeof n==`string`?sz(n):void 0}getSQLType(){return this.sqlName}};function xz(e){return(t,n)=>{let{name:r,config:i}=RL(t,n);return new yz(r,i,e)}}var Sz=class extends ez{static[U]=`SQLiteBaseIntegerBuilder`;constructor(e,t,n){super(e,t,n),this.config.autoIncrement=!1}primaryKey(e){return e?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}},Cz=class extends tz{static[U]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},wz=class extends Sz{static[U]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number int53`,`SQLiteInteger`)}build(e){return new Tz(e,this.config)}},Tz=class extends Cz{static[U]=`SQLiteInteger`;codec=`integer`},Ez=class extends Sz{static[U]=`SQLiteTimestampBuilder`;constructor(e,t){super(e,`object date`,`SQLiteTimestamp`),this.config.mode=t}defaultNow(){return this.default(J`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Dz(e,this.config)}},Dz=class extends Cz{static[U]=`SQLiteTimestamp`;codec=`integer:${this.config.mode}`;mode=this.config.mode;mapToDriverValue=e=>{if(typeof e==`number`)return e;let t=e.getTime();return this.config.mode===`timestamp`?Math.floor(t/1e3):t}},Oz=class extends Sz{static[U]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new kz(e,this.config)}},kz=class extends Cz{static[U]=`SQLiteBoolean`;codec=`integer:boolean`;mode=this.config.mode;mapToDriverValue=e=>+!!e};function Az(e,t){let{name:n,config:r}=RL(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new Ez(n,r.mode):r?.mode===`boolean`?new Oz(n,r.mode):new wz(n)}var jz=class extends ez{static[U]=`SQLiteNumericBuilder`;constructor(e){super(e,`string numeric`,`SQLiteNumeric`)}build(e){return new Mz(e,this.config)}},Mz=class extends tz{static[U]=`SQLiteNumeric`;codec=`numeric`;getSQLType(){return`numeric`}},Nz=class extends ez{static[U]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new Pz(e,this.config)}},Pz=class extends tz{static[U]=`SQLiteNumericNumber`;codec=`numeric:number`;mapToDriverValue=String;getSQLType(){return`numeric`}},Fz=class extends ez{static[U]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteNumericBigInt`)}build(e){return new Iz(e,this.config)}},Iz=class extends tz{static[U]=`SQLiteNumericBigInt`;codec=`numeric:bigint`;mapToDriverValue=String;getSQLType(){return`numeric`}};function Lz(e,t){let{name:n,config:r}=RL(e,t),i=r?.mode;return i===`number`?new Nz(n):i===`bigint`?new Fz(n):new jz(n)}var Rz=class extends ez{static[U]=`SQLiteRealBuilder`;constructor(e){super(e,`number double`,`SQLiteReal`)}build(e){return new zz(e,this.config)}},zz=class extends tz{static[U]=`SQLiteReal`;codec=`real`;getSQLType(){return`real`}};function Bz(e){return new Rz(e??``)}var Vz=class extends ez{static[U]=`SQLiteTextBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`SQLiteText`),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new Hz(e,this.config)}},Hz=class extends tz{static[U]=`SQLiteText`;codec=`text`;enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},Uz=class extends ez{static[U]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteTextJson`)}build(e){return new Wz(e,this.config)}},Wz=class extends tz{static[U]=`SQLiteTextJson`;codec=`text:json`;getSQLType(){return`text`}mapToDriverValue=e=>JSON.stringify(e)};function X(e,t={}){let{name:n,config:r}=RL(e,t);return r.mode===`json`?new Uz(n):new Vz(n,r)}function Gz(){return{blob:vz,customType:xz,integer:Az,numeric:Lz,real:Bz,text:X}}function Kz(e){return(e.replace(/['\u2019]/g,``).match(/[\d\p{Ll}\p{Lo}]+|[\p{Lu}]+(?![\p{Ll}\p{Lo}])|[\p{Lu}][\d\p{Ll}\p{Lo}]+/gu)??[]).map(e=>e.toLowerCase()).join(`_`)}function qz(e){return(e.replace(/['\u2019]/g,``).match(/[\d\p{Ll}\p{Lo}]+|[\p{Lu}]+(?![\p{Ll}\p{Lo}])|[\p{Lu}][\d\p{Ll}\p{Lo}]+/gu)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function Jz(e){return e===`snake_case`?Kz:e===`camelCase`?qz:e=>e}var Yz=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),Xz=class extends $I{static[U]=`SQLiteTable`;static Symbol=Object.assign({},$I.Symbol,{InlineForeignKeys:Yz});[$I.Symbol.Columns];[Yz]=[];[$I.Symbol.ExtraConfigBuilder]=void 0};function Zz(e,t,n,r,i,a=e){let o=Jz(i),s=new Xz(e,r,a),c=typeof t==`function`?t(Gz()):t,l=Object.fromEntries(Object.entries(c).map(([e,t])=>{let n=t;n.setName(e,o);let r=n.build(s).postBuild();return s[Yz].push(...n.buildForeignKeys(r,s)),[e,r]})),u=Object.assign(s,l);return u[$I.Symbol.Columns]=l,u[$I.Symbol.ExtraConfigColumns]=l,n&&(u[Xz.Symbol.ExtraConfigBuilder]=n),u}function Qz(e){return(t,n,r)=>Zz(t,n,r,void 0,e)}var $z=class{name;value;static[U]=`SQLiteCheckBuilder`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t){this.name=e,this.value=t}build(e){return new eB(e,this)}},eB=class{table;static[U]=`SQLiteCheck`;static[Symbol.hasInstance](e){return W(e,this)}name;value;constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}};function tB(e,t){return new $z(e,t)}var nB=class{name;unique;static[U]=`SQLiteIndexBuilderOn`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.name=e,this.unique=t}on(...e){return new rB(this.name,e,this.unique)}},rB=class{static[U]=`SQLiteIndexBuilder`;static[Symbol.hasInstance](e){return W(e,this)}config;constructor(e,t,n){this.config={name:e,columns:t,unique:n,where:void 0}}where(e){return this.config.where=e,this}build(e){return new iB(this.config,e)}},iB=class{static[U]=`SQLiteIndex`;static[Symbol.hasInstance](e){return W(e,this)}config;isNameExplicit;constructor(e,t){this.config={...e,table:t},this.isNameExplicit=!!e.name}};function aB(e){return new nB(e,!1)}function oB(e){return new nB(e,!0)}function sB(...e){return e[0].columns?new cB(e[0].columns,e[0].name):new cB(e)}var cB=class{static[U]=`SQLitePrimaryKeyBuilder`;static[Symbol.hasInstance](e){return W(e,this)}columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new lB(e,this.columns,this.name)}},lB=class{table;static[U]=`SQLitePrimaryKey`;static[Symbol.hasInstance](e){return W(e,this)}columns;name;isNameExplicit;constructor(e,t,n){this.table=e,this.columns=t,this.name=n,this.isNameExplicit=!!n}getName(){return this.name??`${this.table[Xz.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}},uB=zL(e=>`"${e.replace(/"/g,`""`)}"`),dB={json:new G(`json`),object:new G(`_object(`),groupArray:new G(`_group_array(json_object(`),groupArrayClose:new G(`))`),relationFrom:new G(` as "r" from (`),relationClose:new G(`) as "t") as `)},fB=class{static[U]=`SQLiteDialect`;static[Symbol.hasInstance](e){return W(e,this)}codecs;mapperGenerators;constructor(e){this.codecs=new az(sz,e?.codecs),this.mapperGenerators=e?.useJitMappers?{rows:jL,relationalRows:jR}:{rows:ML,relationalRows:kR}}escapeName(e){return uB(e)}escapeParam(e){return`?`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=e.length,n=Array(t+1),r=0;n[r++]=K[`with `];for(let i=0;i<t;++i){let a=e[i];n[r++]=i<t-1?J`${J.identifier(a._.alias)} as (${a._.sql}), `:J`${J.identifier(a._.alias)} as (${a._.sql}) `}return new uL(n)}buildDeleteQuery({table:e,where:t,returning:n,withList:r,limit:i,orderBy:a,useSelectionCastCodecs:o}){let s=this.buildWithCTE(r),c=n?J` returning ${this.buildSelection(n,{isSingleTable:!0,ignoreCastCodecs:!o,table:e})}`:void 0,l=t?J` where ${t}`:void 0,u=this.buildOrderBy(a),d=this.buildLimit(i);return J`${s}delete from ${e}${l}${c}${u}${d}`}buildUpdateSet(e,t){let n=e[$I.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length,a=Array(i);for(let e=0;e<r.length;++e){let o=r[e],s=n[o],c;if(t[o]!==void 0)c=t[o];else{let e=s.onUpdateFn?.();c=W(e,uL)?e:J.param(e,s)}a[e]=e<i-1?J`${J.identifier(s.name)} = ${c}, `:J`${J.identifier(s.name)} = ${c}`}return new uL(a)}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,joins:a,from:o,limit:s,orderBy:c,useSelectionCastCodecs:l}){let u=this.buildWithCTE(i),d=this.buildUpdateSet(e,t),f=o&&new uL([K[` from `],this.buildFromTable(o)]),p=this.buildJoins(a),m=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:!l,table:e})}`:void 0,h=n?J` where ${n}`:void 0,g=this.buildOrderBy(c),_=this.buildLimit(s);return J`${u}update ${e} set ${d}${f}${p}${h}${m}${g}${_}`}buildSelection(e,{isSingleTable:t=!1,ignoreCastCodecs:n=!1,table:r}={}){let{length:i}=e,a=[],o=mL(r),s=r?hL(r,o,q.sql)||hL(r,o,q.subquery)?void 0:r[$I.Symbol.IsAlias]||r[$I.Symbol.Schema]===void 0?r[$I.Symbol.Name]:`${r[$I.Symbol.Schema]}.${r[$I.Symbol.Name]}`:void 0;for(let r=0;r<i;++r){let{field:o,codecOverride:c,column:l,fieldType:u}=e[r],d=c;switch(u){case`Column`:{let e;e=t?o.isAlias?J.identifier(YL(o).name):J.identifier(o.name):o.isAlias?YL(o):o;let r=n?e:this.codecs.apply(o,`cast`,e,d);a.push(o.isAlias?J`${r} as ${o}`:r);break}case`SQL.Aliased`:if(o.isSelectionField){let e=!t&&o.origin!==void 0?J`${J.identifier(o.origin)}.${J.identifier(o.fieldAlias)}`:J.identifier(o.fieldAlias);l&&!n?a.push(this.codecs.apply(l,`cast`,e,d)):a.push(e)}else{if(t&&s!==void 0){let{queryChunks:e}=o.sql,t=Array(e.length),r=!1;for(let n=0;n<e.length;++n){let i=e[n];if(W(i,rL)){let{table:e}=i;if((e[$I.Symbol.IsAlias]||e[$I.Symbol.Schema]===void 0?e[$I.Symbol.Name]:`${e[$I.Symbol.Schema]}.${e[$I.Symbol.Name]}`)!==s){r=!0;break}t[n]=J.identifier(i.name)}else t[n]=i}if(r)a.push(l&&!n?this.codecs.apply(l,`cast`,o.sql,d):o.sql);else{let e=new uL(t);o.sql.shouldInlineParams&&e.inlineParams(),a.push(l&&!n?this.codecs.apply(l,`cast`,e,d):e)}}else a.push(l&&!n?this.codecs.apply(l,`cast`,o.sql,d):o.sql);a.push(J` as ${J.identifier(o.fieldAlias)}`)}break;case`SQL`:if(t&&s!==void 0){let{queryChunks:e}=o,t=Array(e.length),r=!1;for(let n=0;n<e.length;++n){let i=e[n];if(W(i,rL)){let{table:e}=i;if((e[$I.Symbol.IsAlias]||e[$I.Symbol.Schema]===void 0?e[$I.Symbol.Name]:`${e[$I.Symbol.Schema]}.${e[$I.Symbol.Name]}`)!==s){r=!0;break}t[n]=J.identifier(i.name)}else t[n]=i}if(r)a.push(l&&!n?this.codecs.apply(l,`cast`,o,d):o);else{let e=new uL(t);o.shouldInlineParams&&e.inlineParams(),a.push(l&&!n?this.codecs.apply(l,`cast`,e,d):e)}}else a.push(l&&!n?this.codecs.apply(l,`cast`,o,d):o);break;case`Subquery`:if(o._.isWith)a.push(l&&!n?this.codecs.apply(l,`cast`,o,d):o);else{let e=J`(${o._.sql})`;a.push(J`${l&&!n?this.codecs.apply(l,`cast`,e,d):e} ${J.identifier(o._.alias)}`)}}r<i-1&&a.push(K[`, `])}return new uL(a)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[n,r]of e.entries()){n===0&&t.push(K[` `]);let i=r.table,a=r.on?J` on ${r.on}`:void 0;W(i,Xz)?t.push(J`${new G(r.joinType)} join ${i[$I.Symbol.IsAlias]?qL(i):i}${a}`):t.push(J`${new G(r.joinType)} join ${i}${a}`),n<e.length-1&&t.push(K[` `])}return new uL(t)}buildLimit(e){return typeof e==`object`||typeof e==`number`?J` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e)for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(K[`, `]);return t.length>0?J` order by ${J.join(t)}`:void 0}buildFromTable(e){if(W(e,$I)&&e[$I.Symbol.IsAlias])return qL(e);if(W(e,oL)&&e[iL].isAlias){let t=J`${J.identifier(e[iL].originalName)}`;return e[iL].schema&&(t=J`${J.identifier(e[iL].schema)}.${t}`),J`${t} ${J.identifier(e[iL].name)}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,distinct:d,setOperators:f,useSelectionCastCodecs:p}){let m=n??NL(t,void 0,this.codecs),h=mL(a),g=hL(a,h,q.subquery)?a._.alias:hL(a,h,q.view)?a[iL].name:hL(a,h,q.sql)?void 0:eL(a);for(let e of m)if(W(e.field,rL)&&eL(e.field.table)!==g&&!(e=>o?.some(({alias:t})=>t===(e[$I.Symbol.IsAlias]?eL(e):e[$I.Symbol.BaseName])))(e.field.table)){let t=eL(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let _=!o||o.length===0,v=this.buildWithCTE(e),ee=d?J` distinct`:void 0,te=this.buildSelection(m,{isSingleTable:_,table:a,ignoreCastCodecs:!p||f.length>0}),ne=this.buildFromTable(a),re=this.buildJoins(o),ie=r?J` where ${r}`:void 0,ae=i?J` having ${i}`:void 0,oe=[];if(c)for(let[e,t]of c.entries())oe.push(t),e<c.length-1&&oe.push(K[`, `]);let se=oe.length>0?J` group by ${J.join(oe)}`:void 0,ce=this.buildOrderBy(s),le=this.buildLimit(l),ue=u?J` offset ${u}`:void 0,de=J`${v}select${ee} ${te} from ${ne}${re}${ie}${se}${ae}${ce}${le}${ue}`;return f.length>0?this.buildSetOperations(de,m,p,f):de}buildSetOperations(e,t,n,r){for(let n=0;n<r.length;++n){let i=r[n];e=this.buildSetOperationQuery({leftSelect:e,setOperator:i});let a=NL(i.rightSelect.getSelectedFields());for(let e=0;e<t.length;++e){let n=t[e],r=n.path.join(`.`),i=a.find(e=>e.path.join(`.`)===r),o=n.codecOverride??n.column?.codec,s=i.codecOverride??i.column?.codec;n.codecOverride=o&&s?dz(o,s):o}}for(let e=0;e<t.length;++e){let n=t[e];n.codec=n.codecOverride?this.codecs.get(n.column,`normalize`,n.codecOverride):n.codec}return n?J`select ${this.buildSelection(t.map(e=>{if(e.fieldType===`SQL.Aliased`){let t=e.field.clone();return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}if(e.fieldType===`Column`&&e.field.isAlias){let t=new uL.Aliased(J`${J.identifier(e.field.name)}`,e.field.name);return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}if(e.fieldType===`Subquery`){let t=new uL.Aliased(J`${e.field.getSQL()}`,e.field._.alias);return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}return e}),{isSingleTable:!0,ignoreCastCodecs:!n})} from (${e}) ${J.identifier(`drizzle_union`)}`:e}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=J`${e.getSQL()} `,c=J`${r.getSQL()}`,l;if(a&&a.length>0){let e=[];for(let t of a)W(t,tz)?e.push(J.identifier(t.name)):W(t,uL)?e.push(J`${wL(t)}`):e.push(J`${t}`);l=J` order by ${J.join(e,K[`, `])}`}let u=typeof i==`object`||typeof i==`number`&&i>=0?J` limit ${i}`:void 0,d=new G(`${t} ${n?`all `:``}`),f=o?J` offset ${o}`:void 0;return J`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a,columnList:o,useSelectionCastCodecs:s}){let c=e[$I.Symbol.Columns],l=o?o.map(e=>[e,c[e]]):Object.entries(c),u=a&&!W(t,uL)?Object.keys(t.getSelectedFields()).map(e=>[e,c[e]]):l.filter(([e,t])=>!t.shouldDisableInsert()),d=Array(u.length*2+1),f=0;d[f++]=K[`(`];for(let e=0;e<u.length;++e){let[,{name:t}]=u[e];d[f++]=J.identifier(t),e<u.length-1&&(d[f++]=K[`, `])}d[f++]=K[`)`];let p=new uL(d),m;if(a)m=[t.getSQL()];else{let e=t,n=Array(e.length*u.length),r=0;for(let t=0;t<e.length;++t){let i=e[t];for(let e=0;e<u.length;++e){let[t,a]=u[e],o=i[t];o===void 0?a.defaultFn===void 0?a.default!==null&&a.default!==void 0?n[r++]=a.default:a.onUpdateFn===void 0?n[r++]=K.null:n[r++]=a.onUpdateFn():n[r++]=a.defaultFn():n[r++]=o}}m=[K[`values `],new xL(n,u.map(([,e])=>e))]}let h=this.buildWithCTE(i),g=new uL(m),_=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:!s,table:e})}`:void 0,v=n?.length?J.join(n):void 0;return J`${h}insert into ${e} ${p} ${g}${v}${_}`}sqlToQuery(e,t){return e.toQuery({escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,codecs:this.codecs,invokeSource:t})}buildRelationalQuery(e){let t=[],n=this.collectRelationalQuery(e,t);return{sql:new uL(t),selection:n}}collectRelationalQuery({schema:e,table:t,tableConfig:n,queryConfig:r,relationWhere:i,mode:a,nested:o,errorPath:s,depth:c,through:l,jsonb:u,withSubqueries:d,usedTables:f},p){let m=[],h=a===`first`,g=r===!0?void 0:r,_=s??``,v=c??0,ee=d??{subqueries:new Map,usedTables:f};v||(JR(ee,t),t=KL(t,`d${v}`));let te=t[XI],ne=h?1:g?.limit,re=g?.offset,{sql:ie}=WR(t,g,n.relations,e,ee,i),ae=g?.orderBy?zR(t,g.orderBy,n.relations,e,ee):void 0,oe=g?g.with:void 0,se=[];if(oe)for(let e of Object.keys(oe))oe[e]&&se.push(e);let ce=v?-1:p.length;v||p.push(void 0),p.push(K[`select `]);let le=+!!qR(te,n.table[WI],m,!!o,n.name,this.codecs,p,g?.columns);if(g?.extras){let e=p.length;le&&p.push(K[`, `]);let n=BR(t,g.extras,this.codecs,!!o,p);m.push(...n.selection),n.sql?++le:p.length=e}if(!le&&!se.length)throw new VI({message:`No fields selected for table "${n.name}"${_?` ("${_}")`:``}`});for(let r of se){let i=oe[r],a=n.relations[r];if(!a)throw new VI({message:`Unknown relation "${n.name}" -> "${r}"`});let s=a.relationType===`one`;JR(ee,a.targetTable),JR(ee,a.throughTable);let c=KL(a.targetTable,`d${v+1}`),l=a.throughTable?KL(a.throughTable,`tr${v}`):void 0,{filter:d,joinCondition:f}=UR(a,t,c,l);le++&&p.push(K[`, `]);let h=p.length;p.push(void 0,dB.relationFrom);let g=this.collectRelationalQuery({table:c,mode:s?`first`:`many`,schema:e,queryConfig:i,tableConfig:e[a.targetTableName],relationWhere:d,nested:!0,errorPath:`${_.length?`${_}.`:``}${r}`,depth:v+1,withSubqueries:ee,through:l?{table:l,condition:f}:void 0,jsonb:u},p);p.push(dB.relationClose,J.identifier(r));let te=[K[`(select `],o?u:dB.json,s?dB.object:dB.groupArray];for(let e=0;e<g.length;++e){let t=g[e];e&&te.push(K[`, `]),te.push(new G(this.escapeString(t.key)),K[`, `]),t.selection?te.push(u,K[`(`],J.identifier(t.key),K[`)`]):te.push(J.identifier(t.key))}te.push(s?K[`)`]:dB.groupArrayClose),p[h]=new uL(te),m.push({field:c,fieldType:`Nested`,key:r,selection:g,isArray:!s,isOptional:(a.optional??!1)||i!==!0&&!!i.where})}return p.push(K[` from `]),YR(t,p),l&&(p.push(K[` inner join `]),YR(l.table,p),p.push(K[` on `],...l.condition)),ie&&p.push(K[` where `],...ie),ae&&p.push(K[` order by `],...ae),ne!==void 0&&p.push(K[` limit `],ne),re!==void 0&&p.push(K[` offset `],re),ce!==-1&&(p[ce]=this.buildWithCTE([...ee.subqueries.values()])),m}},pB=class extends oL{static[U]=`SQLiteViewBase`},mB=class e{static[U]=`SelectionProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}config;constructor(e){this.config={...e}}get(t,n,r){if(n===`_`)return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(n===iL)return{...t[iL],selectedFields:new Proxy(t[iL].selectedFields,this)};if(typeof n==`symbol`)return t[n];let i=mL(t),a=(hL(t,i,q.subquery)?t._.selectedFields:hL(t,i,q.view)?t[iL].selectedFields:t)[n];if(a===void 0&&n===`getSQL`){let e=t[n];return typeof e==`function`?e.bind(r??t):e}let o=mL(a);if(hL(a,o,q.aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!a.isSelectionField)return a.sql;let e=a.clone();return e.isSelectionField=!0,e.origin=this.config.alias,e}if(hL(a,o,q.sql)){if(this.config.sqlBehavior===`sql`)return a;throw Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return hL(a,o,q.column)?this.config.alias?new Proxy(a,new BL(new Proxy(a.table,new HL(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0)):a:typeof a!=`object`||!a?a:new Proxy(a,new e(this.config))}};function hB(e){if(W(e,$I))return[e[JI]];let t=new Set;return TL(e.queryChunks,t),[...t]}var gB=class{static[U]=`TypedQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}getSelectedFields(){return this._.selectedFields}},_B=class{builder;static[U]=`SQLiteSelectBuilder`;static[Symbol.hasInstance](e){return W(e,this)}fields;session;dialect;withList;distinct;constructor(e,t=vB){this.builder=t,this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,n;return n=this.fields?this.fields:W(e,sL)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):W(e,pB)?e[iL].selectedFields:W(e,uL)?{}:IL(e),new this.builder({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList??[],distinct:this.distinct})}},vB=class extends gB{static[U]=`SQLiteSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=LL(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}getUsedTables(e=this.getSQL()){return hB(e)}createJoin(e){return(t,n)=>{let r=this.tableName,i=LL(t);if(typeof i==`string`&&this.config.joins?.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(this.config.fieldsFlat=void 0,this.config.mapper=void 0,!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof r==`string`&&(this.config.fields={[r]:this.config.fields}),typeof i==`string`&&!W(t,uL))){let e=W(t,sL)?t._.selectedFields:W(t,oL)?t[iL].selectedFields:t[$I.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new mB({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);crossJoin=this.createJoin(`cross`);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(bB()):n;if(!FL(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);except=this.createSetOperator(`except`,!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new mB({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new mB({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new mB({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new mB({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enabled:!0,autoInvalidate:!0}:e===!1?{enabled:!1}:{enabled:!0,autoInvalidate:!0,...e},this}getSQL(e=!1){return this.config.fieldsFlat??=NL(this.config.fields,void 0,this.dialect.codecs),this.dialect.buildSelectQuery(e?{...this.config,useSelectionCastCodecs:!0}:this.config)}toSQL(e=!0){return this.dialect.sqlToQuery(this.getSQL(e))}as(e){return new Proxy(new sL(this.getSQL(),this.config.fields,e),new mB({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new mB({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}};function yB(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!FL(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var bB=()=>({union:xB,unionAll:SB,intersect:CB,except:wB}),xB=yB(`union`,!1),SB=yB(`union`,!0),CB=yB(`intersect`,!1),wB=yB(`except`,!1),TB=class{static[U]=`SQLiteQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}dialect;dialectConfig;constructor(e){this.dialect=W(e,fB)?e:void 0,this.dialectConfig=W(e,fB)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>{typeof r==`function`&&(r=r(n));let i=r.getSQL();return new Proxy(new cL(i,t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new mB({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}}};with(...e){let t=this;function n(n){return new _B({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new _B({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new _B({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new _B({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new fB(this.dialectConfig),this.dialect}},EB=class{name;static[U]=`SQLiteViewBuilderCore`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}config={}},DB=class extends EB{static[U]=`SQLiteViewBuilder`;as(e){typeof e==`function`&&(e=e(new TB));let t=new mB({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=e.getSelectedFields();return new Proxy(new kB({config:{name:this.name,schema:void 0,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},OB=class extends EB{static[U]=`SQLiteManualViewBuilder`;columns;constructor(e,t,n){super(e),this.columns=IL(Zz(e,t,void 0,void 0,n))}existing(){return new Proxy(new kB({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new mB({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new kB({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new mB({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},kB=class extends pB{static[U]=`SQLiteView`;constructor({config:e}){super(e)}};function AB(e){return((t,n)=>n?new OB(t,n,e):new DB(t))}function jB(e,t){return new Proxy(e,new HL(t,!1))}var MB={table:Qz(`snake_case`),view:AB(`snake_case`)},NB=class extends V(`CycleBudgetReset`)({itemKey:OP,repository:sj,generation:jP}){},PB=class extends rO(`CycleBudgetResetRejectedError`)(`CycleBudgetResetRejectedError`,{askId:FP}){},FB=[`ItemClosed`];WE(FB);var IB=N({...NB.fields,ask:UD(IP),resetPending:ME}),LB=MB.table(`usine_events`,{eventId:X().$type().primaryKey(),dedupKey:X().$type().notNull().unique(),payloadJson:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[tB(`usine_events_payload_json_valid`,J`json_valid(${e.payloadJson})`)]),Z=MB.table(`usine_trigger_events`,{eventId:X().$type().primaryKey().references(()=>LB.eventId),itemKey:X().$type().notNull(),loopName:X().$type().notNull(),stepName:X().$type().notNull(),approval:X({enum:_j}).$type().notNull(),permissions:X({enum:yj}).$type().notNull().default(`write`),cycleLimit:Az().$type(),cycleGeneration:Az().notNull().default(0),repository:X().$type().notNull(),revision:X().$type().notNull(),task:X().$type().notNull(),agentJson:X({mode:`json`}).$type().notNull(),parentModel:X().$type(),reopensEventId:X().$type().references(()=>LB.eventId),reopening:Az().notNull().default(0)},e=>[tB(`usine_trigger_events_approval`,J`${e.approval} in ('none', 'required')`),tB(`usine_trigger_events_cycle_limit`,J`${e.cycleLimit} is null or ${e.cycleLimit} >= 1`),tB(`usine_trigger_events_agent_json_valid`,J`json_valid(${e.agentJson})`),aB(`usine_trigger_events_item`).on(e.loopName,e.itemKey),aB(`usine_trigger_events_item_history`).on(e.itemKey),oB(`usine_trigger_event_reopening`).on(e.reopensEventId,e.reopening)]),RB=MB.table(`usine_loop_items`,{loopName:X().$type().notNull(),itemKey:X().$type().notNull(),observedEventId:X().$type().references(()=>LB.eventId),suppressedByRunId:X().$type().references(()=>Q.runId),suppressedEventId:X().$type().references(()=>LB.eventId)},e=>[sB({columns:[e.loopName,e.itemKey]})]),zB=MB.table(`usine_item_cycle_budgets`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),generation:Az().notNull().default(0),askJson:X({mode:`json`}).$type(),resetPending:Az({mode:`boolean`}).notNull().default(!1)},e=>[tB(`usine_item_cycle_generation`,J`${e.generation} >= 0`),tB(`usine_item_cycle_ask_json`,J`${e.askJson} is null or json_valid(${e.askJson})`)]),BB=MB.table(`usine_cycle_reservations`,{runId:X().$type().primaryKey().references(()=>Q.runId),itemKey:X().$type().notNull().references(()=>zB.itemKey),generation:Az().notNull(),loop:X().$type().notNull()},e=>[aB(`usine_cycle_reservations_item`).on(e.itemKey,e.generation,e.loop),tB(`usine_cycle_reservations_generation`,J`${e.generation} >= 0`)]),VB=MB.table(`usine_cycle_resets`,{askId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>LB.eventId),itemKey:X().$type().notNull().references(()=>zB.itemKey)}),HB=MB.table(`usine_cycle_ask_closures`,{askId:X().$type().primaryKey(),itemKey:X().$type().notNull().references(()=>zB.itemKey),reason:X({enum:FB}).$type().notNull(),askJson:X({mode:`json`}).$type().notNull(),closedAt:X().notNull()},e=>[tB(`usine_cycle_ask_closures_reason`,J`${e.reason} in ('ItemClosed')`),tB(`usine_cycle_ask_closures_ask_json`,J`json_valid(${e.askJson})`)]),Q=MB.table(`usine_runs`,{runId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>Z.eventId),loopName:X().$type().notNull(),stateJson:X({mode:`json`}).$type().notNull(),resolvedFailureAttemptId:X().$type(),openedAt:X().notNull(),closedAt:X(),repository:X().$type().notNull(),revision:X().$type().notNull(),task:X().$type().notNull(),agentJson:X({mode:`json`}).$type().notNull(),parentModel:X().$type(),nextStartJson:X({mode:`json`}).$type()},e=>[tB(`usine_runs_state_json_valid`,J`json_valid(${e.stateJson})`),tB(`usine_runs_agent_json_valid`,J`json_valid(${e.agentJson})`)]),UB=MB.table(`usine_steps`,{runId:X().$type().notNull().references(()=>Q.runId),stepName:X().$type().notNull(),result:X({mode:`json`}).$type()},e=>[sB({columns:[e.runId,e.stepName]}),tB(`usine_steps_result_json_valid`,J`${e.result} is null or json_valid(${e.result})`)]),$=MB.table(`usine_attempts`,{attemptId:X().$type().primaryKey(),runId:X().$type().notNull(),stepName:X().$type().notNull(),workerName:X().$type().notNull(),attemptNumber:Az({mode:`number`}).$type().notNull(),brainJson:X({mode:`json`}).$type().notNull(),task:X().$type().notNull(),agent:X().$type().notNull(),operatorIntervened:Az({mode:`boolean`}).notNull().default(!1),parentModel:X().$type(),startedAt:X().notNull(),outcomeJson:X({mode:`json`}).$type(),endedAt:X(),salvageJson:X({mode:`json`}).$type(),leftoversDiscardedAt:X(),startJson:X({mode:`json`}).$type(),failureResolutionJson:X({mode:`json`}).$type(),reattachedAt:X(),commentsJson:X({mode:`json`}).$type(),outOfMemoryJson:X({mode:`json`}).$type()},e=>[tB(`usine_attempts_number`,J`${e.attemptNumber} >= 1`),tB(`usine_attempts_brain_json_valid`,J`json_valid(${e.brainJson})`),tB(`usine_attempts_outcome_json_valid`,J`${e.outcomeJson} is null or json_valid(${e.outcomeJson})`),tB(`usine_attempts_salvage_json_valid`,J`${e.salvageJson} is null or json_valid(${e.salvageJson})`),oB(`usine_attempt_number`).on(e.runId,e.stepName,e.attemptNumber),oB(`usine_one_in_flight_attempt`).on(e.runId).where(J`${e.outcomeJson} is null`),$R({columns:[e.runId,e.stepName],foreignColumns:[UB.runId,UB.stepName]})]),WB=MB.table(`usine_attempt_transcripts`,{sequence:Az({mode:`number`}).primaryKey({autoIncrement:!0}),attemptId:X().$type().notNull().references(()=>$.attemptId),direction:X({enum:RP}).notNull(),channelSequence:Az({mode:`number`}).$type().notNull(),envelope:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[tB(`usine_attempt_transcripts_direction`,J`${e.direction} in ('inbound', 'outbound')`),tB(`usine_attempt_transcripts_sequence`,J`${e.channelSequence} >= 1`),tB(`usine_attempt_transcripts_envelope_json_valid`,J`json_valid(${e.envelope})`),oB(`usine_attempt_transcript_envelope`).on(e.attemptId,e.direction,e.channelSequence),aB(`usine_attempt_transcript_tail`).on(e.attemptId,e.sequence)]),GB=MB.table(`usine_approvals`,{runId:X().$type().primaryKey().references(()=>Q.runId),eventId:X().$type().notNull().unique().references(()=>LB.eventId),channel:X({enum:pF}).$type(),approver:X().$type()},e=>[tB(`usine_approvals_source`,J`(${e.channel} is null and ${e.approver} is null) or ${e.channel} = 'ui' or (${e.channel} = 'github-ask' and ${e.approver} is not null)`)]),KB=MB.table(`usine_run_again_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),fromRunId:X().$type().notNull().references(()=>Q.runId),requestedBy:X().$type()}),qB=MB.table(`usine_ignored_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),reason:X({enum:oI}).$type().notNull()},e=>[tB(`usine_ignored_events_reason`,J`${e.reason} in ('superseded', 'revoked')`)]),JB=MB.table(`usine_cursors`,{cursorKey:X().primaryKey(),valueJson:X({mode:`json`}).$type().notNull()},e=>[tB(`usine_cursors_value_json_valid`,J`json_valid(${e.valueJson})`)]),YB=MB.table(`usine_item_projections`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),source:X().notNull(),itemNumber:Az({mode:`number`}).notNull(),contentHash:X().notNull(),payloadJson:X({mode:`json`}).$type().notNull(),goneAt:X()},e=>[tB(`usine_item_projections_number`,J`${e.itemNumber} >= 1`),tB(`usine_item_projections_payload_json_valid`,J`json_valid(${e.payloadJson})`),oB(`usine_item_projection_number`).on(e.repository,e.itemNumber)]),XB=MB.table(`usine_repository_label_projections`,{repository:X().$type().primaryKey(),labelsJson:X({mode:`json`}).$type().notNull()},e=>[tB(`usine_repository_label_projections_labels_json_valid`,J`json_valid(${e.labelsJson})`)]),ZB=MB.table(`usine_board_moves`,{moveId:Az({mode:`number`}).primaryKey({autoIncrement:!0}),repository:X().$type().notNull(),itemKey:X().$type().notNull(),movedAt:X().notNull(),fromLane:X().notNull(),toLane:X().notNull(),addedJson:X({mode:`json`}).$type().notNull(),removedJson:X({mode:`json`}).$type().notNull()},e=>[tB(`usine_board_moves_added_json_valid`,J`json_valid(${e.addedJson})`),tB(`usine_board_moves_removed_json_valid`,J`json_valid(${e.removedJson})`),aB(`usine_board_moves_item`).on(e.itemKey,e.movedAt)]),QB=MB.table(`usine_loop_runtime`,{loopName:X().$type().primaryKey(),paused:Az({mode:`boolean`}).notNull()}),$B=MB.table(`usine_projection_revision`,{singleton:Az({mode:`number`}).primaryKey().default(1),revision:Az({mode:`number`}).notNull().default(0)},e=>[tB(`usine_projection_revision_singleton`,J`${e.singleton} = 1`)]),eV=N({eventId:pj,dedupKey:mj,payload:oO,receivedAt:HD,itemKey:OP,loop:gj,step:MM,approval:vj,permissions:bj,cycleLimit:I(AP),cycleGeneration:jP,repository:sj,revision:cj,task:dP,agent:xM,parentModel:I(hM)}),tV=N({itemKey:OP,repository:sj,revision:cj,task:dP,agent:xM,parentModel:I(hM),runId:Qj,eventId:pj,loop:gj,state:Nj,resolvedFailureAttemptId:I(lP),openedAt:HD,closedAt:I(HD),stepName:MM,result:I(jM),approvedAt:I(HD),approvalChannel:I(mF),approver:I(TM),againFrom:I(Qj),againRequestedBy:I(TM)}),nV=N({attemptId:lP,runId:Qj,stepName:MM,worker:PM,number:uP,brain:vM,task:dP,agent:yM,operatorIntervened:ME,parentModel:I(hM),startedAt:HD,outcome:I(ZN),endedAt:I(HD),salvage:I(tP),start:I(cP),failureResolution:I(mP),reattachedAt:I(HD),comments:I(P(kM)),outOfMemory:I(P(_P))}),rV=N({sequence:mI,attemptId:lP,direction:zP,envelope:bI.fields.envelope,receivedAt:HD}),iV=N({runId:Qj}),aV=N({reason:sI}),oV=N({revision:MI}),sV=N({runId:Qj,eventId:pj,dedupKey:mj,payload:oO,receivedAt:HD}),cV=N({...eV.fields,reopening:R}),lV=N({eventId:pj,dedupKey:mj}),uV=dE(P(eV)),dV=dE(P(cV)),fV=dE(P(lV)),pV=dE(P(tV)),mV=dE(P(sV)),hV=dE(P(nV)),gV=dE(P(iV)),_V=dE(P(aV)),vV=dE(P(oV)),yV=dE(P(rV)),bV=yE(oO),xV=yE(HD),SV=yE(Nj),CV=yE(ZN),wV=yE(tP),TV=yE(P(kM)),EV=yE(P(_P)),DV=dE(P(N({outOfMemory:I(P(_P))}))),OV=yE(mP),kV=yE(cP),AV=dE(P(N({nextStart:I(sP)}))),jV=yE(jM),MV=yE(fF),NV=yE(xM),PV=yE(vM),FV=uE(CF),IV=e=>t=>P_(t,t=>FV(t)?t:new xF({operation:e,cause:t})),LV=e=>new hj({id:e.eventId,dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),RV=e=>new DI({runId:e.runId,event:LV(e)}),zV=e=>new eI({event:LV(e),itemKey:e.itemKey,loop:e.loop,step:e.step,approval:e.approval,permissions:e.permissions,cycleLimit:Gi(e.cycleLimit),cycleGeneration:e.cycleGeneration,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:Gi(e.parentModel)}),BV=e=>new $j({id:e.runId,eventId:e.eventId,loop:e.loop,state:e.state,openedAt:e.openedAt}),VV=e=>Zi(Gi(e.approvedAt),t=>new gF({approvedAt:t,source:Zi(Gi(e.approvalChannel),t=>new hF({channel:t,approver:Gi(e.approver)}))})),HV=e=>Zi(Gi(e.againFrom),t=>new pI({from:t,requestedBy:Gi(e.againRequestedBy)})),UV=e=>new NM({runId:e.runId,name:e.stepName,result:Gi(e.result)}),WV=e=>new yP({id:e.attemptId,runId:e.runId,stepName:e.stepName,worker:e.worker,number:e.number,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,parentModel:Gi(e.parentModel),startedAt:e.startedAt,outcome:Gi(e.outcome),endedAt:Gi(e.endedAt),salvage:Gi(e.salvage),start:Gi(e.start),failureResolution:Gi(e.failureResolution),reattachedAt:Gi(e.reattachedAt),comments:e.comments??[],outOfMemory:ra(e.outOfMemory??[],bo).pipe(Zi(vP))}),GV=(e,t)=>new kI({itemKey:e.itemKey,run:BV(e),step:UV(e),attempts:t.map(WV),resolvedFailureAttemptId:Gi(e.resolvedFailureAttemptId),closedAt:Gi(e.closedAt),approval:VV(e),runAgain:HV(e),repository:e.repository,task:e.task,agent:e.agent}),KV=e=>new bI({sequence:e.sequence,attemptId:e.attemptId,direction:e.direction,envelope:e.envelope,receivedAt:e.receivedAt}),qV={itemKey:zB.itemKey,repository:zB.repository,generation:zB.generation,ask:zB.askJson,resetPending:zB.resetPending},JV=dE(P(IB),{onExcessProperty:`error`}),YV=e=>{let t=Y(Z.cycleGeneration,J`coalesce((
|
|
30
|
+
select ${zB.generation} from ${zB}
|
|
31
|
+
where ${zB.itemKey} = ${Z.itemKey}
|
|
32
|
+
), 0)`),n=k(`CycleBudget.get`)(function*(t){return yield*O({itemKey:t}),Gi((yield*e.select(qV).from(zB).where(Y(zB.itemKey,t)).execute().pipe(D(JV)))[0])}),r=k(`CycleBudget.counts`)(function*(t){yield*O({itemKey:t.itemKey,generation:t.generation});let n=fR(e.select({id:$.attemptId}).from($).where(Y($.runId,Q.runId))),r=J`json_extract(${Q.stateJson}, '$._tag')`,i=yield*e.select({loop:BB.loop,admitted:J`count(*)`,completed:J`sum(case when ${lR(r,[...Vj])} and ${n} then 1 else 0 end)`}).from(BB).innerJoin(Q,Y(Q.runId,BB.runId)).where(tR(Y(BB.itemKey,t.itemKey),Y(BB.generation,t.generation),nR($L(r,`Canceled`),n))).groupBy(BB.loop).orderBy(CR(BB.loop)).execute();return yield*dE(P(PP))(i,{onExcessProperty:`error`})});return{admit:k(`CycleBudget.admit`)(function*(t){yield*O({itemKey:t.itemKey,loop:t.loop});let i=yield*n(t.itemKey);if(C(i)&&C(i.value.ask))return yield*A(`Item cycle budget remains exhausted`,{itemKey:t.itemKey,askId:i.value.ask.value.id,loop:t.loop}),i.value.ask;if(S(t.cycleLimit))return b();yield*e.insert(zB).values({itemKey:t.itemKey,repository:t.repository}).onConflictDoNothing().execute();let a=yield*n(t.itemKey);if(S(a))return yield*h_(Error(`Cycle budget missing after insertion`));let o=yield*r(a.value),s=o.find(({loop:e})=>e===t.loop);if(s===void 0||s.admitted<t.cycleLimit.value)return b();let c=new IP({id:FP.make(pj.make(JSON.stringify([t.event.id,a.value.generation]))),itemKey:t.itemKey,repository:t.repository,loop:t.loop,limit:t.cycleLimit.value,counts:[s,...o.filter(({loop:e})=>e!==t.loop)]});return yield*e.update(zB).set({askJson:yE(IP)(c)}).where(Y(zB.itemKey,t.itemKey)).execute(),yield*Cv(`Item cycle budget exhausted; operator reset required`,{itemKey:t.itemKey,repository:t.repository,askId:c.id,loop:c.loop,limit:c.limit,completedCycles:c.completedCycles,counts:c.counts}),x(c)}),reserve:k(`CycleBudget.reserve`)(function*(t,i){if(S(t.cycleLimit))return;yield*O({runId:i,itemKey:t.itemKey,loop:t.loop});let a=yield*n(t.itemKey);if(S(a))return yield*h_(Error(`Run admitted without its cycle budget`));yield*e.insert(BB).values({runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation}).onConflictDoNothing().execute(),yield*A(`Item cycle reserved`,{runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation,counts:yield*r(a.value)})}),get:n,asks:k(`CycleBudget.asks`)(function*(){return(yield*e.select(qV).from(zB).where(dR(zB.askJson)).execute().pipe(D(JV))).flatMap(({ask:e})=>ta(e))}),pendingResets:k(`CycleBudget.pendingResets`)(function*(){return yield*e.select(qV).from(zB).where(Y(zB.resetPending,!0)).execute().pipe(D(JV))}),isCurrentEvent:k(`CycleBudget.isCurrentEvent`)(function*(e){yield*O({eventId:e.event.id,itemKey:e.itemKey});let t=Vi(yield*n(e.itemKey),{onNone:()=>0,onSome:e=>e.generation}),r=e.cycleGeneration===t;return r||(yield*A(`Event observation was superseded by a cycle reset`,{eventId:e.event.id,itemKey:e.itemKey,observedGeneration:e.cycleGeneration,generation:t})),r}),currentEvent:t}},XV=dE(P(N({observedEventId:I(pj),suppressedByRunId:I(Qj),suppressedEventId:I(pj)}))),ZV=dE(P(N({loop:gj,itemKey:OP,observedEventId:I(pj),suppressedByRunId:I(Qj)}))),QV=dE(P(N({eventId:pj,reopensEventId:pj}))),$V=dE(P(N({eventId:pj,runId:Qj}))),eH=e=>{let t=(e,t)=>tR(Y(RB.loopName,e),Y(RB.itemKey,t)),n=k(`LoopItems.row`)(function*(n,r){return Gi((yield*XV(yield*e.select({observedEventId:RB.observedEventId,suppressedByRunId:RB.suppressedByRunId,suppressedEventId:RB.suppressedEventId}).from(RB).where(t(n,r)).execute()))[0])});return{sighted:k(`LoopItems.sighted`)(function*(t,r,i){let a=Zi(yield*n(t,r),({observedEventId:e})=>Gi(e));return yield*e.insert(RB).values({loopName:t,itemKey:r,observedEventId:i}).onConflictDoUpdate({target:[RB.loopName,RB.itemKey],set:{observedEventId:i}}).execute(),a}),unmatched:k(`LoopItems.unmatched`)(function*(n,r){yield*e.update(RB).set({observedEventId:null,suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),suppression:k(`LoopItems.suppression`)(function*(e,t){return Qi(yield*n(e,t),({suppressedByRunId:e,suppressedEventId:t})=>e===null?b():x({runId:e,suppressedEventId:Gi(t)}))}),startSuppression:k(`LoopItems.startSuppression`)(function*(t,r,i,a,o){if(aa(yield*n(t,r),({observedEventId:e})=>e===null))return!1;let s=w(o);return yield*e.insert(RB).values({loopName:t,itemKey:r,observedEventId:a,suppressedByRunId:i,suppressedEventId:s}).onConflictDoUpdate({target:[RB.loopName,RB.itemKey],set:{suppressedByRunId:i,suppressedEventId:s}}).execute(),!0}),suppressFrom:k(`LoopItems.suppressFrom`)(function*(n,r,i){yield*e.update(RB).set({suppressedEventId:i}).where(tR(t(n,r),dR(RB.suppressedByRunId))).execute()}),lift:k(`LoopItems.lift`)(function*(n,r){yield*e.update(RB).set({suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),liftRun:k(`LoopItems.liftRun`)(function*(t){return(yield*e.update(RB).set({suppressedByRunId:null,suppressedEventId:null}).where(Y(RB.suppressedByRunId,t)).returning({loopName:RB.loopName}).execute()).length>0}),sightings:k(`LoopItems.sightings`)(function*(t){let n=[...new Set(t)];if(n.length===0)return[];let r=(yield*r_(Po(n,100),t=>e.select({loop:RB.loopName,itemKey:RB.itemKey,observedEventId:RB.observedEventId,suppressedByRunId:RB.suppressedByRunId}).from(RB).where(cR(RB.itemKey,t)).execute().pipe(D(ZV)))).flat(),i=[...new Set(r.flatMap(({observedEventId:e})=>e===null?[]:[e]))],a=(yield*r_(Po(i,100),t=>e.select({eventId:Z.eventId,reopensEventId:Z.reopensEventId}).from(Z).where(cR(Z.reopensEventId,t)).orderBy(wR(Z.reopening)).execute().pipe(D(QV)))).flat(),o=new Map;for(let{eventId:e,reopensEventId:t}of a)o.has(t)||o.set(t,e);let s=e=>o.get(e)??e,c=new Map((yield*r_(Po(i.map(s),100),t=>e.select({eventId:Q.eventId,runId:Q.runId}).from(Q).where(cR(Q.eventId,t)).execute().pipe(D($V)))).flat().map(({eventId:e,runId:t})=>[e,t]));return r.map(({loop:e,itemKey:t,observedEventId:n,suppressedByRunId:r})=>{let i=Zi(Gi(n),s);return new jI({loop:e,itemKey:t,event:i,run:Qi(i,e=>Gi(c.get(e))),suppressedBy:Gi(r)})})})}},tH=e=>({appendTranscript:k(`RunStoreQueries.appendTranscript`)(function*(t,n,r){return(yield*e.insert(WB).values({attemptId:n.attemptId,direction:t,channelSequence:n.sequence,envelope:MV(n),receivedAt:xV(r)}).onConflictDoNothing().returning({sequence:WB.sequence}).execute()).length>0}),transcript:k(`RunStoreQueries.transcript`)(function*(t){yield*O({attemptId:t.attemptId,query:t._tag});let n=GA(t,{TranscriptSessionsQuery:({attemptId:t})=>cR(WB.sequence,e.select({sequence:J`max(${WB.sequence})`}).from(WB).where(tR(Y(WB.attemptId,t),J`(
|
|
33
|
+
json_extract(${WB.envelope}, '$.payload._tag') = 'InterventionApplied'
|
|
34
|
+
OR (json_extract(${WB.envelope}, '$.payload._tag') = 'SessionEvent'
|
|
35
|
+
AND json_extract(${WB.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
|
|
36
|
+
)`)).groupBy(J`coalesce(json_extract(${WB.envelope}, '$.payload.event.session.id'), json_extract(${WB.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${WB.envelope}, '$.payload._tag')`,J`json_extract(${WB.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:WB.sequence,tokens:J`max(json_extract(${WB.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(WB).where(tR(Y(WB.attemptId,t),J`json_extract(${WB.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${WB.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${WB.envelope}, '$.payload.event.session.id')`).as(`highest`);return cR(WB.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(WB.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>tR(Y(WB.attemptId,e),iR(WB.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>Vi(t,{onNone:()=>Y(WB.attemptId,e),onSome:t=>tR(Y(WB.attemptId,e),oR(WB.sequence,t))})}),r=e.select({sequence:WB.sequence,attemptId:WB.attemptId,direction:WB.direction,envelope:WB.envelope,receivedAt:WB.receivedAt}).from(WB).where(n);return(yield*yV(yield*GA(t,{TranscriptSessionsQuery:()=>r.orderBy(CR(WB.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(CR(WB.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(CR(WB.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(CR(WB.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(wR(WB.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(KV).sort((e,t)=>e.sequence-t.sequence)})}),nH=(e,t)=>hy(t.openedAt)-hy(e.openedAt)||t.runId.localeCompare(e.runId),rH={eventId:LB.eventId,dedupKey:LB.dedupKey,payload:LB.payloadJson,receivedAt:LB.receivedAt,itemKey:Z.itemKey,loop:Z.loopName,step:Z.stepName,approval:Z.approval,permissions:Z.permissions,cycleLimit:Z.cycleLimit,cycleGeneration:Z.cycleGeneration,repository:Z.repository,revision:Z.revision,task:Z.task,agent:Z.agentJson,parentModel:Z.parentModel},iH=jB(LB,`approval_event`),aH={itemKey:Z.itemKey,runId:Q.runId,eventId:Q.eventId,loop:Q.loopName,state:Q.stateJson,resolvedFailureAttemptId:Q.resolvedFailureAttemptId,openedAt:Q.openedAt,closedAt:Q.closedAt,repository:Q.repository,revision:Q.revision,task:Q.task,agent:Q.agentJson,parentModel:Q.parentModel,stepName:UB.stepName,result:UB.result,approvedAt:iH.receivedAt,approvalChannel:GB.channel,approver:GB.approver,againFrom:KB.fromRunId,againRequestedBy:KB.requestedBy},oH={attemptId:$.attemptId,runId:$.runId,stepName:$.stepName,worker:$.workerName,number:$.attemptNumber,brain:$.brainJson,task:$.task,agent:$.agent,operatorIntervened:$.operatorIntervened,parentModel:$.parentModel,startedAt:$.startedAt,outcome:$.outcomeJson,endedAt:$.endedAt,salvage:$.salvageJson,start:$.startJson,failureResolution:$.failureResolutionJson,reattachedAt:$.reattachedAt,comments:$.commentsJson,outOfMemory:$.outOfMemoryJson},sH=J`json_extract(${Q.stateJson}, '$._tag')`,cH=cR(sH,[...Vj]),lH=cR(sH,[...Uj]),uH=e=>hE(oO)(NV(e)),dH=e=>{let t=k(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*uV(yield*e.select(rH).from(LB).innerJoin(Z,Y(Z.eventId,LB.eventId)).where(Y(LB.dedupKey,t)).execute())}),n=k(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*uV(yield*e.select(rH).from(Q).innerJoin(LB,Y(LB.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,LB.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(aH).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(UB,Y(UB.runId,Q.runId)).leftJoin(GB,Y(GB.runId,Q.runId)).leftJoin(iH,Y(iH.eventId,GB.eventId)).leftJoin(KB,Y(KB.eventId,Q.eventId)),i=k(`RunStoreQueries.runRows`)(function*(e){return yield*pV(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>E(function*(){let n=yield*e.select({attemptId:$.attemptId,worker:$.workerName,repository:Q.repository,runId:$.runId,loop:Z.loopName,itemKey:Z.itemKey,number:$.attemptNumber,permissions:Z.permissions,outcome:J`coalesce(json_extract(${$.outcomeJson}, '$._tag'), '')`,salvage:$.salvageJson}).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tR(uR($.leftoversDiscardedAt),...t)).execute();return(yield*dE(P(N({attemptId:lP,worker:PM,repository:sj,runId:Qj,loop:gj,itemKey:OP,number:uP,permissions:bj,outcome:M,salvage:I(tP)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:$N(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?x(n):b()}))}),o=k(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=k(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*O({attemptId:e}),wo(yield*a(Y($.attemptId,e)))}),c=k(`RunStoreQueries.attemptRows`)(function*(t){return yield*hV(yield*e.select(oH).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=k(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*n_([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new vF({runId:e}):new EI({event:LV(s),itemKey:s.itemKey,run:BV(o),step:UV(o),attempts:r.map(WV),resolvedFailureAttemptId:Gi(o.resolvedFailureAttemptId),closedAt:Gi(o.closedAt),approval:VV(o),runAgain:HV(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:Gi(o.parentModel),permissions:s.permissions})}),u=k(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=Fo((yield*r_(Po(t.map(({runId:e})=>e),100),t=>e.select(oH).from($).where(cR($.runId,t)).orderBy(CR($.runId),CR($.attemptNumber)).execute().pipe(D(hV)))).flat(),({runId:e})=>e);return t.map(e=>GV(e,n[e.runId]??[]))}),d=k(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*r_(Po([...new Set(e)],100),e=>r().where(cR(Z.itemKey,e)).execute().pipe(D(pV)))).flat().sort(nH);return yield*u(t)}),f=k(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*n_([r().where(cH).orderBy(wR(Q.openedAt),wR(Q.runId)).execute().pipe(D(pV)),r().where(lR(sH,[...Vj])).orderBy(wR(Q.openedAt),wR(Q.runId)).limit(e).execute().pipe(D(pV))]),i=[...t,...n].sort(nH);return yield*u(i)}),p=k(`RunStoreQueries.runEvents`)(function*(t){return(yield*r_(Po([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:LB.eventId,dedupKey:LB.dedupKey,payload:LB.payloadJson,receivedAt:LB.receivedAt}).from(Q).innerJoin(LB,Y(LB.eventId,Q.eventId)).where(cR(Q.runId,t)).execute().pipe(D(mV)))).flat().map(RV)}),m=k(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(lR(sH,[...Vj])).orderBy(wR(Q.closedAt),wR(Q.runId)).limit(e).execute().pipe(D(pV));return yield*u(t)}),h=k(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=lR(sH,[...Vj]),n=yield*r().where(Vi(e,{onNone:()=>t,onSome:e=>tR(t,aR(Q.closedAt,xV(e)))})).orderBy(wR(Q.closedAt),wR(Q.runId)).execute().pipe(D(pV));return yield*u(n)}),g=k(`RunStoreQueries.projectionRevision`)(function*(){return Gi((yield*vV(yield*e.select({revision:$B.revision}).from($B).where(Y($B.singleton,1)).limit(1).execute()))[0]?.revision)}),_=k(`RunStoreQueries.updateState`)(function*(t,n,r){let i=Ij(n)?null:xV(r??(yield*ly));if((yield*e.update(Q).set({stateJson:SV(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new vF({runId:t})}),v=k(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*O({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:OV(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),ee=k(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:PV(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:w(t.parentModel),startedAt:xV(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:Vi(t.start,{onNone:()=>null,onSome:kV})}).execute()}),te=k(`RunStoreQueries.recordReattach`)(function*(t,n){yield*O({attemptId:t}),yield*e.update($).set({reattachedAt:xV(n)}).where(Y($.attemptId,t)).execute()}),ne=k(`RunStoreQueries.nextStart`)(function*(t){return Gi((yield*AV(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),re=k(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:Vi(n,{onNone:()=>null,onSome:kV})}).where(Y(Q.runId,t)).execute()}),ie=k(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*O({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:wV(n)}).where(Y($.attemptId,t)).execute()}),ae=k(`RunStoreQueries.recordComments`)(function*(t,n){yield*O({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:TV(n)}).where(Y($.attemptId,t)).execute()}),oe=k(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*O({attemptId:t,container:n.container,kills:n.kills});let r=_o(((yield*DV(yield*e.select({outOfMemory:$.outOfMemoryJson}).from($).where(Y($.attemptId,t)).execute()))[0]?.outOfMemory??[]).filter(({container:e})=>e!==n.container),n);return yield*e.update($).set({outOfMemoryJson:EV(r)}).where(Y($.attemptId,t)).execute(),vP(r)}),se=k(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:CV(n),endedAt:xV(r)}).where(tR(Y($.attemptId,t),uR($.outcomeJson))).execute()}),ce=k(`RunStoreQueries.amend`)(function*(t,n){yield*O({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:uH(n.agent),parentModel:w(n.parentModel)}).where(Y(Q.runId,t)).execute()}),le=k(`RunStoreQueries.markIntervened`)(function*(t){yield*O({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),ue=k(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),de=k(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(UB).set({result:jV(r)}).where(tR(Y(UB.runId,t),Y(UB.stepName,n))).execute()}),fe=k(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(GB,Y(GB.runId,t)).execute())>0}),pe=k(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(LB).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:bV(n.payload),receivedAt:xV(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(GB).values({runId:t,eventId:n.id,channel:r.channel,approver:w(r.approver)}).execute()}),me=k(`RunStoreQueries.createRun`)(function*(t,n,r){let i=jB(Z,`candidate`),a=jB(Q,`candidate_run`),o=jB(qB,`ignored`);yield*e.insert(qB).select(e.select({eventId:i.eventId,reason:J`'superseded'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).leftJoin(o,Y(o.eventId,i.eventId)).where(tR(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),$L(i.eventId,n),uR(a.runId),uR(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:SV(new Tj),openedAt:xV(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:uH(t.agent),parentModel:w(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(UB).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),he=k(`RunStoreQueries.runForEvent`)(function*(t){return yield*gV(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),ge=k(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*_V(yield*e.select({reason:qB.reason}).from(qB).where(Y(qB.eventId,t)).execute())}),_e=k(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*gV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tR(Y(Z.loopName,t),Y(Z.itemKey,n),cH)).orderBy(wR(Q.openedAt)).limit(1).execute())}),ve=k(`RunStoreQueries.newestReopening`)(function*(t){return Zi(Gi((yield*dV(yield*e.select({...rH,reopening:Z.reopening}).from(LB).innerJoin(Z,Y(Z.eventId,LB.eventId)).where(Y(Z.reopensEventId,t)).orderBy(wR(Z.reopening)).limit(1).execute()))[0]),e=>({submission:zV(e),reopening:e.reopening}))}),ye=k(`RunStoreQueries.reopenedEvent`)(function*(t){let n=jB(LB,`reopened_event`);return Gi((yield*fV(yield*e.select({eventId:n.eventId,dedupKey:n.dedupKey}).from(Z).innerJoin(n,Y(n.eventId,Z.reopensEventId)).where(Y(Z.eventId,t)).execute()))[0])}),be=k(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(KB).values({eventId:t,fromRunId:n.from,requestedBy:w(n.requestedBy)}).execute()}),xe=k(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=b()){yield*e.insert(LB).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:bV(n.event.payload),receivedAt:xV(n.event.receivedAt)}).onConflictDoNothing().execute();let i=(yield*t(n.event.dedupKey))[0];return i===void 0?(yield*e.insert(Z).values({eventId:n.event.id,itemKey:n.itemKey,loopName:n.loop,stepName:n.step,approval:n.approval,permissions:n.permissions,cycleLimit:w(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:uH(n.agent),parentModel:w(n.parentModel),reopensEventId:w(Zi(r,({eventId:e})=>e)),reopening:Vi(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):zV(i)}),Se=k(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return b();let i=yield*eH(e).suppression(r.loop,r.itemKey);if(C(i))return yield*A(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),b();let a=yield*uV(yield*e.select(rH).from(LB).innerJoin(Z,Y(Z.eventId,LB.eventId)).leftJoin(Q,Y(Q.eventId,LB.eventId)).leftJoin(qB,Y(qB.eventId,LB.eventId)).where(tR(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),YV(e).currentEvent,uR(Q.runId),uR(qB.eventId))).orderBy(wR(LB.receivedAt)).execute());return Gi(a[0]).pipe(Zi(e=>({submission:zV(e),eventIds:a.map(e=>e.eventId)})))}),Ce=k(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*gV(yield*e.select({runId:Q.runId}).from(Q).where(tR(cH,$L(sH,`Waiting`))).execute())).map(({runId:e})=>e)}),we=k(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(qB,Y(qB.eventId,Z.eventId)).leftJoin(zB,Y(zB.itemKey,Z.itemKey)).leftJoin(RB,tR(Y(RB.loopName,Z.loopName),Y(RB.itemKey,Z.itemKey))).where(tR(uR(Q.runId),uR(qB.eventId),uR(zB.askJson),uR(RB.suppressedByRunId),YV(e).currentEvent)).execute();return(yield*r_(yield*dE(P(N({loop:gj,itemKey:OP})))(t),({loop:t,itemKey:n})=>E(function*(){return(yield*_e(t,n)).length>0?[]:yield*gV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tR(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(wR(Q.openedAt),wR(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Te=k(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=jB(Z,`candidate`),a=jB(Q,`candidate_run`);return(yield*e.insert(qB).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(tR(Y(i.loopName,t),Y(i.itemKey,n),cR(i.eventId,r),uR(a.runId)))).onConflictDoNothing().returning({eventId:qB.eventId}).execute()).length}),Ee=k(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*gV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tR(Y(Z.loopName,t),Y(Z.itemKey,n),lH)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(tR(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Te(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:YV(e),loopItems:eH(e),...tH(e),addAttempt:ee,recordReattach:te,nextStart:ne,setNextStart:re,recordSalvage:ie,recordComments:ae,recordOutOfMemory:oe,amend:ce,markIntervened:le,approvalExists:fe,blockingRun:_e,closeAttempt:se,createRun:me,eventRouteByRun:n,ignoredEvent:ge,newestReopening:ve,nextQueued:Se,reopenedEvent:ye,recordRunAgain:be,pendingContinuations:we,recordTriggerEvent:xe,runIdsToDrive:Ce,recordApproval:pe,revision:g,revokeQueued:Te,revokeUnstarted:Ee,runSummaries:f,closedRunSummaries:m,closedRunSummariesSince:h,itemRunSummaries:d,runEvents:p,runForEvent:he,snapshot:l,updateStepResult:de,updateAttemptParentModel:ue,updateState:_,resolveFailure:v}},fH=e=>({attemptWindows:k(`RunStoreQueries.attemptWindows`)(function*(t){yield*O({attemptId:t});let[n]=yield*e.select(oH).from($).where(Y($.attemptId,t)).execute().pipe(D(hV));if(n===void 0)return yield*h_(Error(`No attempt ${t} recorded`));let r=xP(WV(n));if(S(r))return yield*j(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new EP({own:r,overlapping:[]});let i=e.select({itemKey:Z.itemKey}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Y(Q.runId,n.runId));return new EP({own:r,overlapping:(yield*e.select(oH).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tR(cR(Z.itemKey,i),Y($.agent,n.agent),$L($.attemptId,t))).orderBy($.startedAt).execute().pipe(D(hV))).flatMap(e=>ta(xP(WV(e)))).filter(e=>TP(r.value,e))})})}),pH=uR($.leftoversDiscardedAt),mH=uR($.outcomeJson),hH=e=>{let t=k(`RunStoreQueries.attemptCountsByWorker`)(function*(){let t=yield*e.select({worker:$.workerName,attempts:J`count(*)`,running:J`sum(case when ${mH} then 1 else 0 end)`}).from($).where(pH).groupBy($.workerName).orderBy(CR($.workerName)).execute();return yield*dE(P(AI))(t)});return{attemptCountsByWorker:t,openAttempts:k(`RunStoreQueries.openAttempts`)(function*(e){return(yield*t()).find(t=>t.worker===e)?.running??0}),discardLeftovers:k(`RunStoreQueries.discardLeftovers`)(function*(t,n){return(yield*e.update($).set({leftoversDiscardedAt:xV(n)}).where(tR(Y($.workerName,t),pH)).returning({attemptId:$.attemptId}).execute()).map(({attemptId:e})=>e)})}},gH=uP.make(3),_H=e=>Gi(e.attempts.at(-1)).pipe(na(e=>S(e.outcome))),vH=(e,t,n)=>{let r=new YN({failure:n});return DP({failure:n,number:t.number,maxAutoAttempts:gH})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:qj(e)}},yH=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=_H(e);return S(r)?{_tag:`Unchanged`,reason:`NoOpenAttempt`}:r.value.id===t?Xa(n)?vH(e.run.state,r.value,n.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new JN,state:Kj(e.run.state),result:n.success}:{_tag:`Unchanged`,reason:`AttemptReplaced`}},bH=e=>GA(e,{Pushed:e=>x(e),PartlyPushed:({ref:e,commit:t})=>x(new eP({ref:e,commit:t})),Retained:()=>b(),Rejected:()=>b()}),xH=e=>Do(e,e=>Qi(e.salvage,bH)),SH=(e,t,n,r)=>{let i=e.run.state;if(!Rj(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=b(),o=_H(e);if(i._tag===`Running`&&C(o)){if(ia(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:xH(e.attempts)};let r=vH(i,o.value,t);if(r._tag===`RunFailed`)return r;a=x(r)}let s=C(a)?new oP:Hi(r,()=>e.attempts.length===0?new nP:new aP);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:Gj(i),number:uP.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:xH(e.attempts)}},CH=e=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:Ij(e.run.state)?{_tag:`Canceled`,state:Yj(e.run.state),attempt:e.run.state._tag===`Running`?Zi(_H(e),e=>({id:e.id,outcome:new XN})):b()}:{_tag:`CancelRejected`},wH=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:Jj(t)}:t._tag===`Running`&&S(_H(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},TH=(e,t)=>Vi(e,{onNone:()=>!1,onSome:e=>!ia(e,t)}),EH=(e,t)=>e._tag===`Owned`?e.run.state._tag===`Canceled`&&t?{_tag:`ReopenEvent`}:{_tag:`JoinRun`,run:e.run}:e.reason===`revoked`&&t?{_tag:`ReopenEvent`}:{_tag:`StayIgnored`,reason:e.reason},DH=e=>{if(e._tag!==`RunFailed`)return b();switch(e.outcome.failure._tag){case`QuestionFailure`:return x(`question`);case`BlockedFailure`:return x(`blocker`);default:return b()}},OH=(e,t)=>Vi(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),kH=(e,t)=>{if(S(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:Lj(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:Xj(n.state,t)}:{_tag:`OpenRun`}},AH=B(Qj).pipe(YE(T(b()))),jH=class extends V(`@usine/engine/internal/Claim`)({result:dI,openedRun:AH,supersededRun:AH}){},MH=class extends H(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:FI}){},NH=class extends H(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},PH=class extends H(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},FH=E(function*(){let e=yield*_F,t=yield*yA,n=dH(e),r=k(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return C(r)?new uI({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new iI({eventId:t.event.id,runId:n}))}),i=k(`RunStore.openRun`)(function*(e,t,n,i=b()){let a=yield*r(e,t,n);return new jH({result:a,openedRun:a._tag===`Claimed`?x(n):b(),supersededRun:i})}),a=e=>nI(e).pipe(Q_(yA,t)),o=k(`RunStore.settlementOf`)(function*(e,t){let n=(yield*e.runForEvent(t))[0];if(n!==void 0){let t=(yield*e.snapshot(n.runId)).run;return x({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?b():x({_tag:`Ignored`,reason:r.reason})}),s=k(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new jH({result:new cI({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(C(r)){let n=OH(r.value,t.event.id),i={eventId:t.event.id,suppressedBy:r.value.runId,loop:t.loop,itemKey:t.itemKey};switch(n._tag){case`SuppressFrom`:return yield*e.loopItems.suppressFrom(t.loop,t.itemKey,t.event.id),yield*A(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new jH({result:new lI({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*A(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new jH({result:new lI({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*A(`Item changed after the Agent stopped for the operator; the Loop acts on its new state`,i)}}let a=(yield*e.blockingRun(t.loop,t.itemKey))[0],o=kH(a===void 0?b():x((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*A(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new jH({result:new aI({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,x(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=k(`RunStore.recordAndClaim`)(function*(t,n){return yield*O({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>E(function*(){let r=dH(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=Hi(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(S(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=EH(d.value,TH(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*A(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new jH({result:new iI({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*A(`Event remains ignored`,{eventId:u,reason:f.reason}),new jH({result:new cI({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(rI(t,i.event.dedupKey,e),x({eventId:i.event.id,reopening:e}));return yield*A(`The Item came back to the state of an Event no Attempt worked on; it opens again`,{eventId:u,settled:d.value._tag,reopenedEventId:n.event.id,reopening:e}),yield*s(r,n,yield*a(n))}}}))},IV(`submit event`)),l=k(`RunStore.parkForApproval`)(function*(t){return yield*O({runId:t}),yield*e.transaction(e=>E(function*(){let n=dH(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=eee(r.run.state);return yield*n.updateState(t,i),i}))},IV(`park run for approval`)),u=k(`RunStore.applyFinish`)(function*(e,t,n){if(yield*O({runId:t}),n._tag===`Unchanged`){yield*A(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*O({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*A(`Attempt completion decided`,GA(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*ly;yield*e.closeAttempt(r.id,i,o),n._tag!==`RetryAttempt`&&(n._tag===`RunSucceeded`&&(yield*e.updateStepResult(t,r.stepName,n.result)),yield*e.updateState(t,n.state,o))}),d=k(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Zi(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*A(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:Hi(i,()=>`none yet`)}):yield*A(`Agent stopped for the operator, but nothing is suppressed; the Loop last saw the Item not matching`,a)}),f=(e,{attempt:t,state:n,resume:r,reattach:i})=>new FI({attempt:t,event:e.event,run:new $j({id:e.run.id,eventId:e.run.eventId,loop:e.run.loop,state:n,openedAt:e.run.openedAt}),step:e.step,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel,permissions:e.permissions,resume:r,reattach:i}),p=k(`RunStore.beginAttempt`)(function*(t,n,r){return yield*O({runId:t,worker:n}),yield*e.transaction(e=>E(function*(){let i=dH(e),a=yield*i.snapshot(t),o=new BN({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=SH(a,o,r,s);if(c._tag===`RunClosed`)return yield*A(`Attempt start skipped`,{runId:t,state:c.state._tag}),new PH;if(c._tag===`RunFailed`)return yield*u(i,t,c),new NH;if(c._tag===`ReattachAttempt`){let e=yield*ly,r=new yP({...c.attempt,reattachedAt:x(e)});return yield*i.recordReattach(r.id,e),yield*O({attemptId:r.id}),yield*A(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*wv(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new MH({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}C(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=lP.make(`${t}/${a.step.name}/${c.number}`),d=yield*ly,p=new yP({id:l,runId:t,stepName:a.step.name,worker:n,number:c.number,brain:a.agent.brain,task:a.task,agent:a.agent.name,operatorIntervened:!1,parentModel:a.parentModel,startedAt:d,outcome:b(),endedAt:b(),salvage:b(),start:x(c.start),reattachedAt:b()});return yield*i.addAttempt(p),C(s)&&(yield*i.setNextStart(t,b())),yield*A(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Zi(c.resume,({ref:e})=>e)}),new MH({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},IV(`begin attempt`)),m=k(`RunStore.recordSalvage`)(function*(t,n){yield*O({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>dH(e).recordSalvage(t,n)),yield*A(`Attempt salvage recorded`,GA(n,{Pushed:({ref:e,commit:n})=>({attemptId:t,ref:e,commit:n}),PartlyPushed:({ref:e,commit:n,path:r})=>({attemptId:t,ref:e,commit:n,path:r}),Retained:({path:e,commit:n})=>({attemptId:t,path:e,commit:n}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},IV(`record attempt salvage`)),h=k(`RunStore.recordComments`)(function*(t,n){yield*O({attemptId:t,comments:n.length}),yield*e.transaction(e=>dH(e).recordComments(t,n)),yield*A(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},IV(`record attempt comments`)),g=k(`RunStore.recordOutOfMemory`)(function*(t,n){yield*O({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>dH(e).recordOutOfMemory(t,n));yield*A(`Recorded the processes the kernel killed in the Attempt's container`,{attemptId:t,container:n.container,kills:n.kills,memoryMib:n.memoryMib,attemptKills:r.kills})},IV(`record attempt out-of-memory kills`)),_=k(`RunStore.attemptWindows`)(function*(t){yield*O({attemptId:t});let n=yield*fH(e).attemptWindows(t);return yield*j(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:C(n.own),ended:aa(n.own,({endedAt:e})=>C(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},IV(`read attempt windows`)),v=k(`RunStore.discardLeftovers`)(function*(t){yield*O({worker:t});let n=yield*ly;return yield*e.transaction(e=>hH(e).discardLeftovers(t,n))},IV(`discard attempt leftovers`)),ee=k(`RunStore.openAttempts`)(function*(t){return yield*O({worker:t}),yield*hH(e).openAttempts(t)},IV(`count open attempts`)),te=k(`RunStore.finishAttempt`)(function*(t,n){return yield*O({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>E(function*(){let r=dH(e),i=yield*r.snapshot(t.runId),a=yH(i,t.id,n);yield*u(r,t.runId,a);let o=DH(a);return C(o)&&(yield*d(r,i,o.value)),a}))},IV(`finish attempt`)),ne=k(`RunStore.resolveFailure`)(function*(t,n,r){return yield*O({runId:t,attemptId:n}),yield*e.transaction(e=>E(function*(){let i=dH(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!zj(a.run.state).canResolveFailure||o?.id!==n)return yield*A(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new yF({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(ia(a.resolvedFailureAttemptId,n))return yield*A(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new mP({resolvedAt:yield*ly,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*A(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:_y(s.resolvedAt),operator:w(r)}),c}))},IV(`resolve run failure`)),re=k(`RunStore.approve`)(function*(t,n,r){return yield*O({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>E(function*(){let i=dH(e);if(yield*i.approvalExists(t))return!1;let a=yield*i.snapshot(t);return a.run.state._tag===`Waiting`?(yield*i.recordApproval(t,n,r),yield*i.updateState(t,Wj(a.run.state)),!0):yield*new yF({runId:t,operation:`approve`,state:a.run.state._tag})}))},IV(`approve run`)),ie=k(`RunStore.retry`)(function*(t,n=fI){let{amendment:r,requestedBy:i}=n;return yield*O({runId:t}),yield*e.transaction(e=>E(function*(){let n=dH(e),a=yield*n.snapshot(t),o=wH(a);if(yield*A(`Operator retry decided`,{runId:t,state:a.run.state._tag,decision:o._tag}),o._tag===`Resume`){let e=(yield*n.blockingRun(a.run.loop,a.itemKey))[0];return e===void 0?(C(r)&&(yield*n.amend(t,r.value),yield*A(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*A(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,x(C(r)?new iP({operator:i}):new rP({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*A(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new bF({runId:t,openRunId:e.runId,message:`Cannot retry run ${t}: run ${e.runId} of loop "${a.run.loop}" is open on the same item. Cancel run ${e.runId}, or try again after it closes.`}))}return o._tag===`ResumePending`&&S(r)?!1:yield*new yF({runId:t,operation:`retry`,state:a.run.state._tag})}))},IV(`retry run`)),ae=k(`RunStore.runAgain`)(function*(t,n){yield*O({runId:t,agent:n.context.agent.name});let i=yield*ly;return yield*e.transaction(e=>E(function*(){let o=dH(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!zj(s.run.state).canRunAgain)return yield*A(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new yF({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*A(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new bF({runId:t,openRunId:u.runId,message:`Run ${t} cannot run again: run ${u.runId} of loop "${c}" is open on the same item. Cancel run ${u.runId}, or try again after it closes.`});let d=Hi(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=Vi(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=Vi(yield*o.cycles.get(l),{onNone:()=>jP.make(0),onSome:e=>e.generation}),m=PI(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,x({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new pI({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*A(`Run again decided`,GA(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:Hi(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:Hi(n.requestedBy,()=>`none`)})})),g}))},IV(`run again`)),oe=k(`RunStore.cancel`)(function*(t){return yield*O({runId:t}),yield*e.transaction(e=>E(function*(){let n=dH(e),r=yield*n.snapshot(t),i=CH(r);if(yield*A(`Operator cancellation decided`,{runId:t,state:r.run.state._tag,decision:i._tag}),i._tag===`AlreadyClosed`)return i;if(i._tag===`CancelRejected`)return yield*new yF({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*ly;if(C(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Zi(i.attempt,({id:e})=>e),loop:r.run.loop,itemKey:r.itemKey}}))},IV(`cancel run`)),se=k(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>E(function*(){let r=dH(e);yield*r.loopItems.unmatched(t,n);let i=yield*r.revokeUnstarted(t,n);for(let e of i){let t=yield*r.snapshot(e.runId);Lj(t.run.state)&&(yield*r.updateState(e.runId,Zj(t.run.state)))}return i.map(e=>e.runId)}))},IV(`revoke run`)),ce=k(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*O({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},IV(`revoke queued events`)),le=k(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>E(function*(){let r=dH(e),a=yield*r.runForEvent(t.event.id);return a[0]===void 0?(yield*r.ignoredEvent(t.event.id)).length>0||(yield*r.blockingRun(t.loop,t.itemKey)).length>0||C(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?b():(yield*i(r,t,n)).openedRun:(yield*A(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),b())}))},IV(`claim queued event`)),ue=k(`RunStore.appendTranscript`)(function*(t,n){let r=yield*ly;yield*e.transaction(e=>E(function*(){let i=dH(e);t===`outbound`&&n.payload._tag===`Started`&&(yield*i.updateAttemptParentModel(n.attemptId,n.payload.parentModel)),t===`outbound`&&n.payload._tag===`InterventionApplied`&&(yield*i.markIntervened(n.attemptId)),(yield*i.appendTranscript(t,n,r))||(yield*j(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},IV(`append attempt transcript`)),de=k(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},IV(`read attempt transcript`));return{approve:re,appendTranscript:ue,beginAttempt:p,cancel:oe,claimQueued:le,finishAttempt:te,nextQueued:e=>n.nextQueued(e).pipe(IV(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(IV(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(IV(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(IV(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(IV(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:v,openAttempts:ee,submission:e=>n.eventRouteByRun(e).pipe(D(t=>t[0]===void 0?f_(new vF({runId:e})):T(zV(t[0]))),IV(`read run submission`)),resolveFailure:ne,retry:ie,revoke:se,revokeQueued:ce,runAgain:ae,snapshot:e=>n.snapshot(e).pipe(IV(`read run`)),transcript:de}}),IH=class e extends sa()(`@usine/engine/internal/RunStore`){static layer=ym(e,FH)},LH=E(function*(){let e=yield*_F,t=dH(e),n=k(`RunReader.inspect`)(e=>t.snapshot(e).pipe(IV(`read run`))),r=k(`RunReader.evidence`)(function*(t){yield*O({runId:t});let n=yield*e.transaction(e=>E(function*(){let n=dH(e),r=yield*n.snapshot(t);return new OI({snapshot:r,transcript:(yield*r_(r.attempts,({id:e})=>n.transcript(new xI({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(IV(`read run evidence`));return yield*j(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=k(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(IV(`list runs`))),a=k(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(IV(`list closed runs`))),o=k(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(IV(`list runs closed since a time`))),s=k(`RunReader.revision`)(()=>t.revision().pipe(IV(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:k(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(IV(`read item run histories`))),events:k(`RunReader.events`)(e=>t.runEvents(e).pipe(IV(`read the events of runs`))),revision:s,transcript:k(`RunReader.transcript`)(e=>t.transcript(e).pipe(IV(`read attempt transcript`))),attemptsByWorker:k(`RunReader.attemptsByWorker`)(()=>hH(e).attemptCountsByWorker().pipe(IV(`count attempts by worker`))),sightings:k(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(IV(`read loop sightings`)))}}),RH=class e extends sa()(`@usine/engine/RunReader`){static layer=ym(e,LH)},zH=z.pipe(L(`ItemProjectionSource`)),BH=z.pipe(L(`ItemContentHash`)),VH=class extends V(`@usine/engine/ItemProjection`)({itemKey:OP,repository:sj,source:zH,number:kP,contentHash:BH,payload:sO,goneAt:UD(HD).pipe(ZE(T(null)),YE(T(b())))}){},HH=N({itemKey:VH.fields.itemKey,repository:sj,source:zH,number:kP,contentHash:BH,payload:sO,goneAt:VH.fields.goneAt}),UH=dE(P(HH)),WH=dE(P(kP)),GH=yE(sO),KH=yE(HH.fields.goneAt),qH=e=>t=>P_(t,t=>new xF({operation:e,cause:t})),JH={itemKey:YB.itemKey,repository:YB.repository,source:YB.source,number:YB.itemNumber,contentHash:YB.contentHash,payload:YB.payloadJson,goneAt:YB.goneAt},YH=E(function*(){let e=yield*_F;return{get:k(`ItemProjectionReader.get`)(function*(t){yield*O({itemKey:t});let[n]=yield*UH(yield*e.select(JH).from(YB).where(Y(YB.itemKey,t)).execute(),{onExcessProperty:`error`});return Zi(Gi(n),e=>new VH(e))},qH(`read item projection`)),list:k(`ItemProjectionReader.list`)(function*(t,n){return yield*O({repository:t,limit:n.limit}),(yield*UH(yield*e.select(JH).from(YB).where(Y(YB.repository,t)).orderBy(wR(YB.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new VH(e))},qH(`list item projections`)),openIssues:k(`ItemProjectionReader.openIssues`)(function*(t){return yield*O({repository:t}),yield*WH((yield*e.select({number:YB.itemNumber}).from(YB).where(tR(Y(YB.repository,t),Y(YB.source,`issue`),uR(YB.goneAt),J`json_extract(${YB.payloadJson}, '$.state') = 'OPEN'`)).orderBy(CR(YB.itemNumber)).execute()).map(({number:e})=>e))},qH(`list open issue projections`))}}),XH=E(function*(){let e=yield*_F;return{upsert:k(`ItemProjectionWriter.upsert`)(function*(t){yield*O({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=KH(t.goneAt);return(yield*e.insert(YB).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:GH(t.payload),goneAt:n}).onConflictDoUpdate({target:YB.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:GH(t.payload),goneAt:n},setWhere:J`${YB.contentHash} != ${t.contentHash} OR ${YB.goneAt} IS NOT ${n}`}).returning({itemKey:YB.itemKey}).execute()).length===0?(yield*j(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*j(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},qH(`write item projection`)),markGone:k(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*O({itemKey:t}),(yield*e.update(YB).set({goneAt:KH(x(n))}).where(tR(Y(YB.itemKey,t),uR(YB.goneAt))).returning({itemKey:YB.itemKey}).execute()).length===0?(yield*j(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*A(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:_y(n)}),!0)},qH(`mark item projection gone`))}}),ZH=class e extends sa()(`@usine/engine/ItemProjectionReader`){static layer=ym(e,YH)},QH=class e extends sa()(`@usine/engine/ItemProjectionWriter`){static layer=ym(e,XH)},$H=M.check(iD(/\S/u,{message:`Expected a non-blank repository label`})),eU=M.check(iD(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),tU=class extends V(`@usine/engine/RepositoryLabel`)({name:$H,color:UD(eU),description:UD(M)}){},nU=rD(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),rU=P(tU).check(nU),iU=class extends V(`@usine/engine/RepositoryLabelProjection`)({repository:sj,labels:rU}){},aU=P(M),oU=uE(aU),sU=N({repository:sj,labels:F([iU.fields.labels,aU])}),cU=e=>oU(e)?e.map(e=>new tU({name:e,color:b(),description:b()})):e,lU=dE(P(sU)),uU=yE(iU.fields.labels),dU=e=>t=>P_(t,t=>new xF({operation:e,cause:t})),fU=E(function*(){let e=yield*_F;return{get:k(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*lU(yield*e.select({repository:XB.repository,labels:XB.labelsJson}).from(XB).where(Y(XB.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?b():x(new iU({repository:n.repository,labels:cU(n.labels)}))},dU(`read repository label projection`))}}),pU=E(function*(){let e=yield*_F;return{replace:k(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*O({repository:t.repository});let n=uU(t.labels);return(yield*e.insert(XB).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:XB.repository,set:{labelsJson:n},setWhere:$L(XB.labelsJson,n)}).returning({repository:XB.repository}).execute()).length===0?(yield*j(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*j(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},dU(`write repository label projection`))}}),mU=class e extends sa()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=ym(e,fU)},hU=class e extends sa()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=ym(e,pU)},gU=class extends sa()(`@usine/engine/TriggerCondition`){},_U=z.pipe(L(`CursorKey`)),vU=dE(P(N({value:oO}))),yU=e=>t=>P_(t,t=>new xF({operation:e,cause:t})),bU=class e extends sa()(`@usine/engine/CursorStore`){static layer=ym(e,E(function*(){let e=yield*_F;return{read:k(`CursorStore.read`)(function*(t,n){let r=Gi((yield*E(function*(){return yield*vU(yield*e.select({value:JB.valueJson}).from(JB).where(Y(JB.cursorKey,t)).limit(1).execute())}).pipe(yU(`read runtime cursor`)))[0]);return S(r)?b():yield*dE(n)(r.value.value,{onExcessProperty:`error`}).pipe(T_(x),k_(e=>Cv(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(E_(b()))))}),write:k(`CursorStore.write`)(function*(t,n,r){let i=yield*_E(n)(r).pipe(yU(`encode runtime cursor`));yield*e.insert(JB).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:JB.cursorKey,set:{valueJson:i}}).execute().pipe(O_,yU(`write runtime cursor`))})}}))},xU=class extends V(`@usine/engine/LoopRuntimeState`)({loop:gj,paused:ME}){},SU=e=>t=>t.pipe(P_(t=>new xF({operation:e,cause:t}))),CU=E(function*(){let e=yield*_F,t=k(`LoopControl.stateFor`)(function*(t){yield*O({loop:t});let n=(yield*e.select({loop:QB.loopName,paused:QB.paused}).from(QB).where(Y(QB.loopName,t)).limit(1).execute())[0];return n===void 0?new xU({loop:t,paused:!1}):new xU(n)},SU(`read loop runtime state`)),n=k(`LoopControl.states`)(function*(){return(yield*e.select({loop:QB.loopName,paused:QB.paused}).from(QB).orderBy(CR(QB.loopName)).execute()).map(e=>new xU(e))},SU(`list loop runtime states`)),r=k(`LoopControl.write`)(function*(n){yield*O({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*j(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(QB).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:QB.loopName,set:{paused:n.paused}}).execute().pipe(SU(`write loop runtime state`)),yield*A(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:k(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:k(`LoopControl.pause`)(e=>r(new xU({loop:e,paused:!0}))),states:n(),unpause:k(`LoopControl.unpause`)(e=>r(new xU({loop:e,paused:!1})))}}),wU=class e extends sa()(`@usine/engine/LoopControl`){static layer=ym(e,CU)},TU=e=>e.pipe(P_(e=>e instanceof PB?e:new xF({operation:`update cycle budget`,cause:e}))),EU=class e extends sa()(`@usine/engine/CycleBudgets`){static layer=ym(e,E(function*(){let e=yield*_F,t=YV(e);return{generation:k(`CycleBudgets.generation`)(function*(e){return yield*O({itemKey:e}),Vi(yield*t.get(e).pipe(P_(e=>new xF({operation:`read cycle generation`,cause:e}))),{onNone:()=>jP.make(0),onSome:e=>e.generation})}),asks:k(`CycleBudgets.asks`)(()=>t.asks().pipe(P_(e=>new xF({operation:`read cycle asks`,cause:e})))),reset:k(`CycleBudgets.reset`)(function*(t,n){yield*O({askId:t,eventId:n.id}),yield*e.transaction(e=>E(function*(){if((yield*e.select().from(VB).where(Y(VB.askId,t)).execute())[0]?.eventId===n.id){yield*A(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*YV(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new PB({askId:t});let i=yield*YV(e).get(r.itemKey);if(S(i))return yield*h_(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(LB).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:bV(n.payload),receivedAt:xV(n.receivedAt)}).execute(),yield*e.insert(VB).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(zB).set({generation:a,askJson:null,resetPending:!0}).where(Y(zB.itemKey,r.itemKey)).execute(),yield*e.update(BB).set({generation:a}).where(tR(Y(BB.itemKey,r.itemKey),cR(BB.runId,e.select({runId:Q.runId}).from(Q).where(cR(J`json_extract(${Q.stateJson}, '$._tag')`,[...Uj]))))).execute(),yield*A(`Operator reset Item cycle budget`,{askId:t,eventId:n.id,itemKey:r.itemKey,repository:r.repository,generation:a,completedCycles:r.completedCycles,counts:r.counts})})).pipe(TU)}),close:k(`CycleBudgets.close`)(function*(t,n){yield*O({askId:t,reason:n});let r=xV(yield*ly);return yield*e.transaction(e=>E(function*(){let i=(yield*YV(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*A(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=yE(IP)(i);return yield*e.insert(HB).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:HB.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(zB).set({askJson:null}).where(Y(zB.itemKey,i.itemKey)).execute(),yield*A(`Closed cycle-budget Ask without a reset`,{askId:t,reason:n,itemKey:i.itemKey,repository:i.repository,loop:i.loop,completedCycles:i.completedCycles,counts:i.counts}),!0})).pipe(P_(e=>new xF({operation:`close cycle ask`,cause:e})))}),pendingResets:k(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(T_(e=>e.map(e=>new NB(e))),P_(e=>new xF({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:k(`CycleBudgets.acknowledgeReset`)(function*(t){yield*O({itemKey:t.itemKey,generation:t.generation}),yield*e.update(zB).set({resetPending:!1}).where(tR(Y(zB.itemKey,t.itemKey),Y(zB.generation,t.generation))).execute().pipe(P_(e=>new xF({operation:`acknowledge cycle reset`,cause:e}))),yield*A(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},DU=P(z),OU=class extends V(`@usine/engine/BoardMoveRecord`)({repository:sj,itemKey:OP,at:VD,fromLane:z,toLane:z,added:DU.check(_D()),removed:DU}){},kU=dE(P(N({repository:OU.fields.repository,itemKey:OU.fields.itemKey,at:HD,fromLane:OU.fields.fromLane,toLane:OU.fields.toLane,added:OU.fields.added,removed:OU.fields.removed}))),AU=yE(OU.fields.added),jU=yE(OU.fields.removed),MU=e=>t=>P_(t,t=>new xF({operation:e,cause:t})),NU=E(function*(){let e=yield*_F;return{record:k(`BoardMoves.record`)(function*(t){yield*O({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(ZB).values({repository:t.repository,itemKey:t.itemKey,movedAt:xV(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:AU(t.added),removedJson:jU(t.removed)}).execute(),yield*j(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:xV(t.at),fromLane:t.fromLane,toLane:t.toLane})},MU(`record board move`)),onItem:k(`BoardMoves.onItem`)(function*(t,n){return yield*O({itemKey:t}),(yield*kU(yield*e.select({repository:ZB.repository,itemKey:ZB.itemKey,at:ZB.movedAt,fromLane:ZB.fromLane,toLane:ZB.toLane,added:ZB.addedJson,removed:ZB.removedJson}).from(ZB).where(tR(Y(ZB.itemKey,t),aR(ZB.movedAt,xV(n)))).orderBy(CR(ZB.movedAt),CR(ZB.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new OU(e))},MU(`read board moves`))}}),PU=class e extends sa()(`@usine/engine/BoardMoves`){static layer=ym(e,NU)},FU=class extends sa()(`@usine/engine/RunEngineShutdown`){},IU=class e extends sa()(`@usine/engine/AttemptAdmission`){static layer=ym(e,E(function*(){let e=yield*X_(FU),t=C(e)?e.value:yield*Vp(),n=yield*JA(new Set),r=yield*Vp(),i=k(`AttemptAdmission.enter`)(function*(e){yield*O({runId:e});let r=yield*ZA(n,n=>Gp(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*A(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=k(`AttemptAdmission.leave`)(function*(e){yield*O({runId:e});let i=yield*$A(n,t=>new Set([...t].filter(t=>t!==e)));(yield*Wp(t))&&(yield*A(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*Kp(r,void 0)))});return{withAttempt:k(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*O({runId:e}),yield*ev(i(e),e=>e?t:d_,t=>t?a(e):l_)}),drain:k(`AttemptAdmission.drain`)(function*(){yield*Kp(t,void 0);let e=yield*YA(n);yield*A(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*Kp(r,void 0)),yield*Hp(r),yield*A(`Engine drain completed; all admitted Attempts settled`)})}}))},LU=class extends rO(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:lP,worker:PM,cause:wD()}){},RU=(e,t)=>{let n=new Map(e);return n.delete(t),n},zU=k(`CheckoutRecovery.for`)(function*(e,t){let n=yield*JA(new Map),r=n=>t.recover(n,{salvage:t=>e.recordSalvage(n.attemptId,t),comments:t=>e.recordComments(n.attemptId,t),windows:e.attemptWindows(n.attemptId)}).pipe(I_(e=>wv(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),z_),i=k(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(D(e=>av(e.release).pipe(T_(t=>({worker:e.worker,release:t,checkoutKept:!0})))),D(t=>QA(n,n=>new Map(n).set(e.attemptId,t))),cv)}),a=k(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*O(n);let a=yield*t.isLive(e.attemptId).pipe(S_);if(Za(a)&&!a.success)return yield*r(e);Xa(a)?yield*Cv(`Could not read whether an open Attempt's parent task is live; its checkout stays for its Run to decide`,{...n,errorTag:a.failure._tag,message:a.failure.message}):yield*A(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*A(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=k(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*O(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe(S_);return Za(a)?(yield*r(e),b()):(yield*Cv(`Could not confirm that the parent task of a closed Attempt stopped; its checkout and a slot of its Worker stay kept, and no Attempt starts on its Loop's Item, until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),x(e))}),s=k(`CheckoutRecovery.atStartup`)(function*(){let n=new Set(yield*t.workers),r=yield*e.salvageCandidates,i=r.filter(({worker:e})=>n.has(e)),s=r.filter(({worker:e})=>!n.has(e));return s.length>0&&(yield*Cv(`Attempts recorded on Workers that are not configured were not reconciled; their checkouts stay until those Workers are configured again or their leftovers are discarded`,{attempts:s.length,workers:[...new Set(s.map(({worker:e})=>e))].sort().join(`,`)})),Bo(yield*r_(i,e=>e.open?a(e).pipe(E_(b())):o(e)))}),c=k(`CheckoutRecovery.reattachSlot`)(function*(e){return Zi(na(Ki((yield*YA(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:YA(n).pipe(D(n=>n.get(e)===t?A(`The slot startup occupied stays kept with the checkout no execution acquired, until the Attempt's parent task is confirmed stopped`,{attemptId:e,worker:t.worker}):t.release))}))}),l=k(`CheckoutRecovery.acquired`)(function*(e){(yield*ZA(n,t=>t.get(e)?.checkoutKept===!0?[!0,RU(t,e)]:[!1,t]))&&(yield*A(`The reattached Attempt's execution acquired the checkout startup kept; its executor releases the checkout from here, and its Run the slot once the Attempt ends`,{attemptId:e}))}),u=k(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*O(r);let i=yield*av(t.release);(yield*ZA(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*A(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*j(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},cv),d=k(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*O(i);let a=yield*t.interrupt(e,r).pipe(S_);if(Za(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?Cv(`Could not confirm that the parent task of an Attempt its Run does not reattach stopped; its checkout and its Worker's slot stay, and the Run starts no next Attempt until the stop is confirmed`,o):Cv(`Could not confirm that the parent task of a closed Attempt stopped; its Worker's slot stays taken, and no Attempt starts on its Loop's Item, until a reconcile confirms the stop`,o),yield*new LU({attemptId:e,worker:n.worker,cause:a.failure})}),f=k(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe(S_);if(Xa(i)){yield*wv(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:i.failure._tag});return}if(S(i.success)){yield*Cv(`The leftovers of the Attempt whose checkout startup kept were discarded; the checkout stays`,{attemptId:n});return}let a=i.success.value,o={attemptId:n,worker:a.worker,open:a.open};yield*O(o),(yield*t.workers).includes(a.worker)?(yield*A(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*Cv(`The Worker of the Attempt whose checkout startup kept is no longer configured; the checkout stays until it is configured again or its leftovers are discarded`,o)});return{atStartup:s,reattachSlot:c,acquired:l,hold:u,reconcile:k(`CheckoutRecovery.reconcile`)(function*(e,t){yield*O({attemptId:e,reason:t});let r=(yield*YA(n)).get(e);r===void 0?yield*j(`No slot kept for the Attempt awaits its parent task's stop`,{attemptId:e}):(yield*d(e,r,t),r.checkoutKept&&(yield*f(e)),yield*QA(n,t=>RU(t,e)).pipe(b_(r.release),cv),yield*A(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),BU=class extends V(`@usine/engine/UnconfirmedStop`)({attemptId:lP,runId:Qj,loop:gj,itemKey:OP,worker:PM,reason:fP}){},VU=class e extends sa()(`@usine/engine/UnconfirmedStops`){static empty=_m(e)({list:T([])})},HU=e=>j_(e,{EnginePersistenceError:e=>new BN({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>h_(e),RunOperationRejectedError:e=>h_(e),RunRetryBlockedError:e=>h_(e)}),UU=4,WU=`100 millis`,GU=(e,t)=>n=>n.pipe(I_(n=>n._tag===`EnginePersistenceError`?Cv(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):l_),R_({schedule:Pg(WU),times:UU,while:e=>e._tag===`EnginePersistenceError`})),KU=e=>Qi(e,e=>e._tag===`Live`?x(e.attempt):b()),qU=class e extends sa()(`@usine/engine/internal/RunDriver`){static layer=ym(e,E(function*(){let e=yield*IH,t=yield*II,n=yield*IU,r=yield*gU,i=yield*QH,a=yield*yA,o=yield*wA(),s=yield*zU(e,t),c=yield*JA(new Map),l=yield*JA(new Map),u=(e,t)=>ZA(l,n=>n.get(e)===t?[!0,RU(n,e)]:[!1,n]).pipe(D(n=>n?t.release:j(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=k(`RunDriver.launch`)(function*(e){if(yield*O({runId:e}),yield*jA(o,e)){yield*j(`The Run's fiber already runs in this process`,{runId:e});return}yield*j(`Starting the Run's fiber`,{runId:e});let t=yield*C_(dv);yield*PA(o,e,ee(e).pipe(L_(t=>Sp(t)?l_:wv(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),pv(`RunDriver.drive`,{root:!0,links:ta(Zi(t,e=>({span:e,attributes:{}})))}),M_(e=>Sp(e)?p_(e):l_)),{onlyIfMissing:!0})}),f=k(`RunDriver.resume`)(function*(e){yield*O({runId:e});let t=yield*kA(o,e);C(t)&&(yield*j(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*cO(t.value)),yield*d(e)}),p=k(`RunDriver.stop`)(function*(e){yield*O({runId:e}),(yield*jA(o,e))?(yield*MA(o,e),yield*A(`The closed Run's fiber stopped`,{runId:e})):yield*j(`The closed Run has no fiber in this process`,{runId:e})}),m=k(`RunDriver.markItemGone`)(function*(e,t){return yield*O({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*ly).pipe(GU(e,`mark the item's projection gone`),k_(n=>Cv(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(E_(!1))))}),h=k(`RunDriver.continueWithNewest`)(function*(t){yield*O({runId:t});let n=yield*e.nextQueued(t).pipe(GU(t,`read the queued events`));if(S(n))return;let i=n.value.submission,o={completedRunId:t,eventId:i.event.id,loop:i.loop,itemKey:i.itemKey},s=yield*r.recheck(i);if(s!==`matches`){let r=yield*e.revokeQueued(n.value).pipe(GU(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*A(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*A(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*nI(i).pipe(Q_(yA,a)),l=yield*e.claimQueued(i,c).pipe(GU(t,`claim the queued event`));S(l)?yield*A(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*A(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=k(`RunDriver.openAttempt`)(function*(n){yield*O({runId:n});let r=yield*e.snapshot(n).pipe(GU(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||C(i.outcome))return b();let a={runId:n,attemptId:i.id,worker:i.worker};yield*O({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe(S_);if(Xa(o))return yield*Cv(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),x({_tag:`Interrupted`,attempt:i});if(o.success)return yield*A(`The open Attempt's parent task is live; reattaching it`,a),x({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe(S_);if(Xa(s))return yield*Cv(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),x({_tag:`Interrupted`,attempt:i});if(S(s.success))return yield*A(`The open Attempt's parent task is gone; the Run does not reattach it`,a),x({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*A(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:$a(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),x({_tag:`Finished`,attempt:i,result:c})}),_=k(`RunDriver.slot`)(function*(e,n,r,i){yield*O({runId:e});let a=T(r),o=KU(r);if(C(o)){let t=yield*s.reattachSlot(o.value.id);if(C(t))return yield*A(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(e,n,Zi(o,({worker:e})=>e))),open:C(o)?g(e):a}}),v=k(`RunDriver.attempt`)(function*(n,r,i,a){yield*O({runId:n,worker:i});let o=yield*a;if(C(o)&&o.value._tag===`Finished`){let t=yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(GU(n,`finish the attempt`));if(t._tag!==`RetryAttempt`)return t._tag}let c=yield*e.beginAttempt(n,i,Zi(KU(o),({id:e})=>e)).pipe(GU(n,`begin the attempt`));if(c._tag===`AttemptRecoveryFailed`)return`RunFailed`;if(c._tag===`RunClosed`)return`Unchanged`;let l=yield*t.execute(c.execution,{append:(t,n)=>e.appendTranscript(t,n).pipe(HU),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(HU),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(HU),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(HU),windows:e.attemptWindows(c.execution.attempt.id).pipe(GU(n,`read the attempt windows`),HU),transcript:e.transcript(new xI({attemptId:c.execution.attempt.id})).pipe(GU(n,`read the attempt transcript`),HU,T_(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(N_(e=>wv(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(b_(new VN({message:`The step executor crashed with an unexpected error`,cause:e})))),S_);return c.execution.reattach&&Xa(l)&&(yield*s.reconcile(c.execution.attempt.id,`failed`)),Xa(l)&&(yield*re({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,reason:`failed`},i)),(yield*e.finishAttempt(c.execution.attempt,l).pipe(GU(n,`finish the attempt`)))._tag}),ee=Sv(function*(t){let r=yield*e.submission(t).pipe(GU(t,`read the run's submission`));if(yield*O({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(GU(t,`park the run for approval`)))._tag===`Waiting`){yield*A(`Run waits for its approval`,{runId:t});return}let i;do{let e=yield*g(t);if(C(e)&&e.value._tag!==`Live`&&(yield*s.reconcile(e.value.attempt.id,`startup`)),S(KU(e))){let e=yield*ie(r);if(C(e)){yield*A(`The Run starts no Attempt while the parent task of an earlier Attempt on its Loop's Item is not confirmed stopped; each reconcile tries that stop again, then drives the Run`,{runId:t,loop:r.loop,itemKey:r.itemKey,unstoppedAttemptId:e.value.attemptId,unstoppedRunId:e.value.runId,worker:e.value.worker,reason:e.value.reason});return}}i=yield*lv(i=>_(t,r,e,i).pipe(x_(({lease:e})=>QA(l,n=>new Map(n).set(t,e))),D(({lease:e,open:a})=>i(n.withAttempt(t,v(t,r,e.worker,a))).pipe(tv(u(t,e))))))}while(i===`RetryAttempt`);i===`Unchanged`?yield*A(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t)}),te=k(`RunDriver.holdSlot`)(function*(e,t){yield*O({runId:e,attemptId:t});let n=yield*ZA(l,t=>[Ki(t.get(e)),RU(t,e)]);S(n)?yield*j(`The Run's fiber holds no slot in this process; no slot moves to its Attempt`,{runId:e,attemptId:t}):yield*s.hold(t,n.value)},cv),ne=e=>QA(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),re=k(`RunDriver.confirmStopAfterFailure`)(function*(e,n){let{attemptId:r,runId:i}=e,a={runId:i,attemptId:r,worker:n,reason:e.reason};yield*O(a);let o=yield*t.interrupt(r,e.reason).pipe(S_);Za(o)?yield*j(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a):(yield*Cv(`Could not confirm that the parent task of the failed Attempt stopped; the Attempt keeps its Run's slot, no Attempt starts on its Loop's Item, and each reconcile tries the stop again`,{...a,errorTag:o.failure._tag,message:o.failure.message}),yield*te(i,r).pipe(b_(ne(new BU({...e,worker:n}))),cv))}),ie=e=>YA(c).pipe(T_(t=>Ki([...t.values()].find(({loop:t,itemKey:n})=>t===e.loop&&n===e.itemKey)))),ae=k(`RunDriver.releaseKept`)(function*(e){let{attemptId:t,runId:n,reason:r}=e;yield*O({runId:n,attemptId:t,reason:r});let i=yield*s.reconcile(t,r).pipe(S_);if(Za(i)){(yield*ZA(c,e=>[e.has(t),RU(e,t)]))&&(yield*A(`The parent task of a closed Attempt is confirmed stopped; Runs on its Loop's Item start Attempts again`,{runId:n,attemptId:t,loop:e.loop,itemKey:e.itemKey,reason:r}));return}let{worker:a}=i.failure;yield*O({worker:a}),yield*ne(new BU({...e,worker:a})),yield*Cv(`The parent task of a closed Attempt is not confirmed stopped; its Worker's slot, and any checkout startup kept, stay kept, no Attempt starts on its Loop's Item, and the next reconcile tries the stop again`,{runId:n,attemptId:t,worker:a,loop:e.loop,itemKey:e.itemKey,reason:r})}),oe=k(`RunDriver.recoverWorkspaces`)(function*(){yield*r_(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>ne(new BU({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:k(`RunDriver.reconcile`)(function*(){let n=[...(yield*YA(c)).values()];yield*r_(n,ae,{discard:!0});let r=yield*e.pendingContinuations;yield*r_(r,e=>h(e).pipe(I_(t=>wv(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),z_),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*U_(i,e=>T_(jA(o,e),e=>!e));yield*r_(a,d,{discard:!0}),yield*t.sweep;let s={continuedAfterRunIds:r,startedRunIds:a,drivenRunIds:i.length,retriedStopAttemptIds:n.map(({attemptId:e})=>e)};r.length===0&&a.length===0&&n.length===0?yield*j(`Every Run to drive already has its fiber`,s):yield*A(`Runs recovered from the run tables`,s)}),recoverWorkspaces:oe,holdSlot:te,releaseKept:ae,unconfirmedStops:YA(c).pipe(T_(e=>[...e.values()]))}}))},JU=Va(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});E(function*(){let e=yield*IH,t=yield*qU,n=yield*IU,r=yield*II,i=yield*yA,a=k(`RunEngine.submit`)(function*(n){let r=yield*nI(n).pipe(Q_(yA,i)),a=yield*e.recordAndClaim(n,r);return C(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),C(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},cv),o=k(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*A(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:Hi(i.approver,()=>`none`)}),yield*t.resume(n)):yield*j(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},cv),s=k(`RunEngine.retry`)(function*(n,r=fI){(yield*e.retry(n,r))?yield*t.resume(n):yield*j(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},cv),c=k(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},cv),l=k(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*j(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*A(`Run canceled`,{runId:n,openAttempt:Hi(i.openAttempt,()=>`none`)}),C(i.openAttempt)&&(yield*t.holdSlot(n,i.openAttempt.value));let a=C(i.openAttempt)?yield*r.interrupt(i.openAttempt.value,`cancel`).pipe(S_):Ga(void 0);if(yield*t.stop(n),C(i.openAttempt)&&(yield*t.releaseKept({attemptId:i.openAttempt.value,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`})),yield*t.continueWithNewest(n),C(i.openAttempt)&&Xa(a))return yield*new SF({attemptId:i.openAttempt.value,cause:a.failure})},cv),u=k(`RunEngine.intervene`)(function*(t,n,i){yield*O({runId:t,attemptId:n,action:i.action._tag});let a=yield*e.snapshot(t),o=a.attempts.at(-1);if(a.run.state._tag!==`Running`||o?.id!==n||C(o.outcome))return yield*A(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new wF({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(P_(e=>new wF({runId:t,attemptId:n,message:GA(e,{RunawayFailure:()=>`The attempt reached its runaway limit`,ChildSessionBudgetFailure:()=>`The attempt reached its child-session budget`,QuestionFailure:()=>`The attempt ended with a question for the operator`,BlockedFailure:({message:e})=>e,InfraFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),I_(e=>Cv(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=k(`RunEngine.resolveFailure`)(function*(n,r,i){yield*O({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*A(`The operator resolved the Agent's question or blocker; the Item's queued Events get their turn`,{runId:n,attemptId:r}),yield*t.continueWithNewest(n))},cv),f=k(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*r_(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},cv),p=k(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=k(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=k(`RunEngine.discardLeftovers`)(function*(t){if(yield*O({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*A(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new TF({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*A(`Discarded the leftovers of the Attempts on a Worker that is not configured; startup no longer reconciles them`,{worker:t,attempts:n.length}),yield*r.discard(t,n),n.length});return yield*t.recoverWorkspaces(),yield*t.reconcile(),yield*B_(yield*JU).pipe(b_(t.reconcile()),I_(e=>wv(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),z_,uv,gv),{approve:o,cancel:l,discardLeftovers:h,drain:n.drain,inspect:p,intervene:u,reconcile:t.reconcile,retry:s,resolveFailure:d,revoke:f,runAgain:c,submit:a,transcript:m}});var YU=class extends sa()(`@usine/engine/RunEngine`){},XU=WE([`preflight`,`prepare`,`launch`,`cancel`,`cleanup`]),ZU=WE([`machine`,`toolchain`,`memory`,`harness-login`,`credentials`,`gateway`,`container`,`provider`]),QU=class extends rO(`@usine/executor/ExecutorOperationError`)(`ExecutorOperationError`,{operation:XU,message:z,cause:wD()}){},$U=WE([`refused`,`unreachable`]),eW=class extends rO(`@usine/executor/CredentialUnavailableError`)(`CredentialUnavailableError`,{repository:sj,reason:$U,message:z,cause:wD()}){},tW=class extends rO(`@usine/executor/WorkerCapabilityError`)(`WorkerCapabilityError`,{worker:PM,capability:ZU,message:z,cause:wD()}){},nW=WE([`capacity`,`quota`,`refused`,`provider`,`unreachable`,`timeout`]);rO(`@usine/executor/MachineUnavailableError`)(`MachineUnavailableError`,{worker:PM,provider:rN,reason:nW,message:z}),F([QU,eW,tW]),V(`@usine/executor/CheckoutRequest`)({attemptId:lP,worker:PM,repository:sj,loop:gj,permissions:bj,revision:cj,payload:oO,task:dP,agent:xM,parentModel:B(hM),maxChildren:gN,maxAttemptMinutes:B(R.check(dD(0))),maxAttemptTokens:B(R.check(dD(0))),parentEffort:_M,salvageRef:QN,resume:B(eP),reattach:ME.pipe(YE(T(!1))),botLogin:B(IM).pipe(YE(T(b()))),commitAuthor:RM});var rW=z.pipe(L(`WorktreePath`));V(`@usine/executor/AttemptWorkspace`)({worker:PM,spec:BP,worktree:rW});var iW=nE(e=>By(e)&&Ct(Uy(e)),{expected:`Redacted<string>`});V(`@usine/executor/WorkerCredential`)({value:iW,expiresAt:VD}),sa()(`@usine/executor/CredentialProvider`),sa()(`@usine/executor/Executor`);var aW=z.pipe(L(`MachineHold`)),oW=class extends V(`@usine/executor/MachineCheck`)({brains:P(vM),containerLimits:B(QM)}){};V(`@usine/executor/MachineGrant`)({hold:aW,id:iN,worker:PM,provider:rN,checked:B(oW)});var sW=WE([`creating`,`ready`,`deleting`]);V(`@usine/executor/MachineStatus`)({worker:PM,provider:rN,state:sW,id:B(iN),runId:B(Qj),attemptId:B(lP),since:VD}),sa()(`@usine/executor/WorkerMachines`);var cW=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,lW=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]];function uW(e,t){let n=1;for(;t<e.length;)if(t++,e[t]===`\\`)t++;else if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t;throw TypeError(`Invalid regexp expression in "`+e+`"`)}var dW=`~effect/http/HttpBody`,fW=e=>It(e,dW),pW=class{[dW];constructor(){this[dW]=dW}[Bn](){return this.toJSON()}toString(){return An(this,{ignoreToString:!0})}},mW=new class extends pW{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},hW=class extends pW{_tag=`Uint8Array`;contentType;contentLength;text;_body;constructor(e,t,n,r){super(),this._body=e,this.text=r,this.contentType=t,this.contentLength=n}get body(){return this._body??=yW(this.text)}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}},gW=(e,t)=>new hW(e,t??`application/octet-stream`,e.length),_W=new TextEncoder,vW=globalThis.Buffer,yW=vW===void 0?e=>_W.encode(e):e=>vW.from(e,`utf8`),bW=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),vW!==void 0)return new hW(void 0,t??`text/plain`,vW.byteLength(e,`utf8`),e);let n=_W.encode(e);return new hW(n,t??`text/plain`,n.length,e)},xW=(e,t)=>bW(JSON.stringify(e),t??`application/json`),SW=(e,t)=>bW(yb(ub(e)),t??`application/x-www-form-urlencoded`),CW=class extends pW{_tag=`FormData`;contentType=void 0;contentLength=void 0;formData;constructor(e){super(),this.formData=e}toJSON(){return{_id:`effect/HttpBody`,_tag:`FormData`,formData:this.formData}}},wW=e=>new CW(e),TW=class extends pW{_tag=`Stream`;stream;contentType;contentLength;constructor(e,t,n){super(),this.stream=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Stream`,contentType:this.contentType,contentLength:this.contentLength}}},EW=(e,t,n)=>new TW(e,t??`application/octet-stream`,n),DW=`~effect/http/HttpClientError`,OW=class extends qs(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[DW]=DW;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},kW=e=>e.endsWith(`Error`)?e.slice(0,-5):e,AW=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,jW=e=>`${e.method} ${Cb(e.url)}`,MW=class extends qs(`TransportError`){get methodAndUrl(){return jW(this.request)}get message(){return AW(kW(this._tag),this.description,this.methodAndUrl)}},NW=class extends qs(`InvalidUrlError`){get methodAndUrl(){return jW(this.request)}get message(){return AW(kW(this._tag),this.description,this.methodAndUrl)}},PW=class extends qs(`StatusCodeError`){get methodAndUrl(){return jW(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return AW(kW(this._tag),this.description,e)}},FW=class extends qs(`DecodeError`){get methodAndUrl(){return jW(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return AW(kW(this._tag),this.description,e)}},IW=class extends qs(`EmptyBodyError`){get methodAndUrl(){return jW(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return AW(kW(this._tag),this.description,e)}},LW=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?tb(tb(e,`content-type`),`content-length`):(e=t.contentType===void 0?tb(e,`content-type`):Qy(e,`content-type`,t.contentType),t.contentLength===void 0?tb(e,`content-length`):Qy(e,`content-length`,t.contentLength.toString())),RW=class extends qs(`UrlError`){},zW=(e,t,n)=>Ja({try:()=>{let r=new URL(e,BW());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,ab(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new RW({cause:e})}),BW=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0){let e=location.origin+location.pathname;try{return new URL(e).href}catch{return}}},VW=`~effect/http/HttpClientRequest`,HW={[VW]:VW,...Un,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Cb(this.url),urlParams:this.urlParams,hash:this.hash,headers:Tn(this.headers),body:this.body.toJSON()}},pipe(){return at(this,arguments)}};function UW(e,t,n,r,i,a){let o=Object.create(HW);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var WW=UW(`GET`,``,hb,b(),Yy,mW),GW=e=>(t,n)=>JW(WW,{method:e,url:t,...n??void 0}),KW=GW(`GET`),qW=GW(`POST`),JW=y(2,(e,t)=>{let n=e;return t.method&&(n=YW(n,t.method)),t.url&&(n=tG(n,t.url)),t.headers&&(n=ZW(n,t.headers)),t.urlParams&&(n=iG(n,t.urlParams)),t.hash&&(n=oG(n,t.hash)),t.body&&(n=sG(n,t.body)),t.accept&&(n=QW(n,t.accept)),t.acceptJson&&(n=$W(n)),n}),YW=y(2,(e,t)=>UW(t,e.url,e.urlParams,e.hash,e.headers,e.body)),XW=y(3,(e,t,n)=>UW(e.method,e.url,e.urlParams,e.hash,Qy(e.headers,t,n),e.body)),ZW=y(2,(e,t)=>UW(e.method,e.url,e.urlParams,e.hash,$y(e.headers,t),e.body)),QW=y(2,(e,t)=>XW(e,`Accept`,t)),$W=QW(`application/json`),eG=y(2,(e,t)=>UW(e.method,e.url,e.urlParams,e.hash,Qy(Qy(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),tG=y(2,(e,t)=>{if(typeof t==`string`)return UW(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=ub(n.searchParams),i=Gi(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,UW(e.method,n.toString(),r,i,e.headers,e.body)}),nG=y(2,(e,t)=>t===``?e:UW(e.method,rG(t,e.url),e.urlParams,e.hash,e.headers,e.body)),rG=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},iG=y(2,(e,t)=>UW(e.method,e.url,_b(e.urlParams,t),e.hash,e.headers,e.body)),aG=y(2,(e,t)=>UW(e.method,e.url,vb(e.urlParams,t),e.hash,e.headers,e.body)),oG=y(2,(e,t)=>UW(e.method,e.url,e.urlParams,x(t),e.headers,e.body)),sG=y(2,(e,t)=>UW(e.method,e.url,e.urlParams,e.hash,LW(e.headers,t),t)),cG=y(2,(e,t)=>sG(e,xW(t))),lG=y(2,(e,t)=>sG(e,wW(t)));function uG(e){let t=zW(e.url,e.urlParams,Ji(e.hash));return Za(t)?x(t.success):b()}var dG=`~effect/http/HttpIncomingMessage`,fG=(e,t)=>{let n=fE(iO(e)),r=t?.reviver===void 0?void 0:fE(kD(iO(e),t));return e=>r===void 0?D(e.json,e=>n(e,t)):D(e.text,i=>i===``?D(e.json,e=>n(e,t)):r(i,t))},pG=(e,t)=>({...t,headers:Tn(e.headers),remoteAddress:e.remoteAddress}),mG=`~effect/http/HttpClientResponse/WebSource`,hG=e=>e[mG]?.(),gG=`~effect/http/HttpClientResponse`,_G=(e,t)=>new vG(e,t),vG=class extends Wn{[dG];[gG];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[dG]=dG,this[gG]=gG}toJSON(){return pG(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split(`#`)[0];let e=uG(this.request);return S(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Xy(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=My(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return b()}[mG](){return this.source}get stream(){return this.source.body?iA({evaluate:()=>this.source.body,onError:e=>new OW({reason:new FW({request:this.request,response:this,cause:e})})}):nA(new OW({reason:new IW({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return D(this.text,e=>g_({try:()=>e===``?null:JSON.parse(e),catch:e=>new OW({reason:new FW({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=T_(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return D(this.text,e=>g_({try:()=>ub(new URLSearchParams(e)),catch:e=>new OW({reason:new FW({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=a_({try:()=>this.source.formData(),catch:e=>new OW({reason:new FW({request:this.request,response:this,cause:e})})}).pipe(av,bv)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=a_({try:()=>this.source.arrayBuffer(),catch:e=>new OW({reason:new FW({request:this.request,response:this,cause:e})})}).pipe(av,bv),this.arrayBufferBody}get upgrade(){return f_(new OW({reason:new PW({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return at(this,arguments)}},yG=e=>Zy({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${Vi(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),bG=sa(`effect/http/HttpEffect/CurrentRequestState`),xG={"http:":80,"https:":443,"ws:":80,"wss:":443},SG=(e,t,n)=>{let r=Cb(t.search,n).slice(1);if(e.attribute(`url.full`,Cb(t.href,n)),e.attribute(`url.path`,t.pathname),r!==``&&e.attribute(`url.query`,r),e.attribute(`url.scheme`,t.protocol.slice(0,-1)),t.hostname!==``){e.attribute(`server.address`,t.hostname.startsWith(`[`)?t.hostname.slice(1,-1):t.hostname);let n=t.port===``?xG[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},CG=(e,t)=>{let n=e.params.filter(([,e])=>typeof e!=`string`).map(([e])=>e);return n.length===0?t:[...t,...new URLSearchParams(n.map(e=>[e,``])).keys()]},wG=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,rb(a,i)?`<redacted>`:n[a])},TG=e=>__(t=>{let n=Aa(t.context,bG);return n!==void 0&&(n.loggerDisabled=!0),e}),EG=`~effect/http/HttpClient`,DG=sa(`effect/HttpClient`),OG=y(2,(e,t)=>kG(n=>t(e.postprocess(n)),e.preprocess)),kG=(e,t)=>{let n=Object.create(AG);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},AG={[EG]:EG,pipe(){return at(this,arguments)},...Un,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(lW.map(([e,t])=>[t,function(t,n){return this.execute(GW(e)(t,n))}]))},jG=e=>kG(t=>D(t,t=>__(n=>{let r=BG.get(t),i=r??new AbortController,a=zW(t.url,t.urlParams,Ji(t.hash));if(Xa(a))return f_(new OW({reason:new NW({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(lc)||n.getRef(PG)(t)){let a=e(t,o,i.signal,n);return r?a:lv(e=>G_(e(a),{onSuccess(e){return zG.register(e,i),T(new VG(e,i))},onFailure(e){return Ep(e)&&i.abort(),p_(e)}}))}return fv(n.getRef(LG)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(ib);SG(a,o,CG(t.urlParams,n.getRef(jb)));let c=n.getRef(FG);return wG(a,`request`,t.headers,c,s),t=n.getRef(IG)?ZW(t,yG(a)):t,lv(l=>l(e(t,o,i.signal,n)).pipe(mv(a,{captureStackTrace:!1}),G_({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),wG(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),MG(n,a,t,e)),r?T(e):(zG.register(e,i),T(new VG(e,i)))),onFailure(e){return!r&&Ep(e)&&i.abort(),p_(e)}})))})})),T),MG=(e,t,n,r)=>{let i=Kn();qn(0);let a;try{a=Pp(new OW({reason:new PW({request:n,response:r})}))}finally{qn(i)}t.end(e.getRef(Yp)?e.getRef(Om).currentTimeNanosUnsafe():BigInt(0),a)},NG=y(2,(e,t)=>kG(e.postprocess,n=>T_(e.preprocess(n),t))),PG=Va(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>dt}),FG=Va(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>dt}),IG=Va(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:ut}),LG=Va(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),RG=e=>ym(DG)(q_(t=>T_(e,e=>OG(e,Z_(e=>Ra(t,e)))))),zG=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{try{e.abort()}catch{}});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new WeakMap;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),BG=new WeakMap,VG=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[gG]=gG;[dG]=dG;applyInterrupt(e){return s_(()=>(zG.unregister(this.original),sv(e,()=>c_(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[mG](){let e=hG(this.original);return e!==void 0&&zG.unregister(this.original),e}get stream(){return eA(()=>(zG.unregister(this.original),mA(this.original.stream,c_(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Bn](){return this.original[Bn]()}pipe(){return at(this,arguments)}},HG=sa(`effect/http/HttpRouter`),UG=e=>e.endsWith(`/`)?e.slice(0,-1):e,WG=y(2,(e,t)=>(t=UG(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),GG=`~effect/http/HttpRouter/Middleware`,KG=function(){return arguments.length===0?qG:qG(arguments[0],arguments[1])},qG=(e,t)=>t?.global?Sm(E(function*(){let t=yield*HG,n=t_(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new XG(t_(e)?xm(T_(e,e=>ba(new Map([[YG,e]])))):vm(ba(new Map([[YG,e]])))),JG=0,YG=`effect/http/HttpRouter/MiddlewareFn`,XG=class e{[GG]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++JG}`;this.layer=xm(E({self:this},function*(){let e=yield*K_(),t=[ja(e,YG)];if(this.dependencies){let n=yield*mm,r=Na(e,Xp),i=yield*hm(this.dependencies,n,r);t.push(...QG(i))}return ba(new Map([[n,t]]))})).pipe(Em(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?Dm(this.dependencies,t.layer):t.layer)}},ZG=new WeakMap,QG=e=>{let t=ZG.get(e);if(t)return t;let n=Lo(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=mo(e).reverse()}return ZG.set(e,t),t};KG(TG).layer;var $G={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},eK=e=>$G[e],tK=`~effect/http-api/HttpApiSchema/Stream`;function nK(e){let t=typeof e==`string`?eK(e):e;return e=>e.ast.checks!==void 0||SK(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var rK=(e=>PE.pipe(nK(e)))(204),iK=e=>xE(e)&&It(e,tK),aK=e=>iK(e)&&e._tag===`StreamSse`,oK=e=>iK(e)&&e._tag===`StreamUint8Array`,sK=e=>iK(e)&&e._tag===`StreamNdjson`,cK=`~effect/http-api/HttpApiSchema/Upgrade`,lK=e=>xE(e)&&It(e,cK),uK=`~effect/http-api/HttpApiSchema/WithHeaders`,dK=`~effect/http-api/HttpApiSchema/WithHeadersValue`,fK=e=>({[dK]:dK,body:e.body,headers:e.headers}),pK=e=>xE(e)&&It(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function mK(e,t,n){return bE(e.ast,{[uK]:uK,schema:t,headers:n})}function hK(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??gK(t._tag)}})}function gK(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function _K(e){return t=>hK(t,{_tag:`FormUrlEncoded`,...e})}var vK=e=>{if(gS(e)||gS(mw(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&gS(t)},yK=Pw(`~httpApiEncoding`),bK=Pw(`~httpApiWithHeaders`),xK=Pw(`httpApiStatus`);function SK(e){let t=Nw(e);return t!==void 0&&`httpApiStatus`in t}function CK(e){return SK(e)?xK(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var wK={_tag:`Json`,contentType:`application/json`},TK={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function EK(e){return yK(e)??wK}function DK(e,t){return yK(e)||(cW(t)?wK:TK)}function OK(e){let t=EK(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function kK(e){return CK(e)??200}function AK(e){return pK(e)?CK(e.ast)??kK(e.schema.ast):kK(e.ast)}function jK(e){return pK(e)&&yK(e.ast)===void 0?OK(e.schema.ast):OK(e.ast)}function MK(e){return CK(e)??500}function NK(e){return pK(e)?CK(e.ast)??MK(e.schema.ast):MK(e.ast)}function PK(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var FK=`~effect/http-api/HttpApiEndpoint`;function IK(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function LK(e){let t=Array.from(e.success);return yo(t)?t:[rK]}function RK(e){let t=new Set(e.error),n=e.disableCodecs?ct:qK;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var zK={[FK]:FK,pipe(){return at(this,arguments)},prefix(e){return VK({...BK(this),path:WG(this.path,e)})},middleware(e){return VK({...BK(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return VK({...BK(this),annotations:Oa(this.annotations,e,t)})},annotateMerge(e){return VK({...BK(this),annotations:Ra(this.annotations,e)})}},BK=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function VK(e){function t(){}return Object.setPrototypeOf(t,zK),Object.assign(t,e)}var HK=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?ct:aO;return VK({identifier:t,path:n,method:e,params:UK(r?.params,a),query:UK(r?.query,a),headers:UK(r?.headers,a),payload:WK(r?.payload,e,i),success:KK(r?.success,e,r?.payload!==void 0,i),error:JK(r?.error,i),annotations:Ta(),middlewares:new Set,disableCodecs:i})};function UK(e,t){if(e!==void 0)return xE(e)?t(e):t(N(e))}function WK(e,t,n){let r=new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:xE(e)?[e]:[N(e).pipe(_K())],a=n?ct:iq,o=!1;for(let e of i){if(iK(e)){if(aK(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!cW(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(o)throw Error(`Multiple streaming payloads are not supported`);o=!0;let n=PK(e.contentType);if(r.has(n))throw Error(`Cannot combine buffered and streaming payloads for content-type: ${e.contentType}`);r.set(n,{encoding:{_tag:`Stream`,contentType:e.contentType},schemas:[e]});continue}let n=DK(e.ast,t),i=PK(n.contentType),s=r.get(i);if(s){if(s.encoding._tag===`Stream`)throw Error(`Cannot combine buffered and streaming payloads for content-type: ${n.contentType}`);if(s.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(s.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);s.schemas.push(a(e,t))}else r.set(i,{encoding:n,schemas:[a(e,t)]})}return r}var GK=`effect/http-api/stream/failure`;function KK(e,t,n,r){if(e===void 0)return new Set;let i=ho(e);return YK(i,t,n),new Set(r?i:i.map(qK))}var qK=gt(e=>iK(e)||lK(e)?e:pK(e)?mK(e,iK(e.schema)?e.schema:rq(e.schema,jK(e)),aO(e.headers)):nq(e));function JK(e,t){if(e===void 0)return new Set;let n=ho(e);for(let e of n){let t=pK(e)?e.schema:e;if(iK(t))throw Error(`Streaming schemas are not supported in error responses`);if(lK(t))throw Error(`Upgrade schemas are not supported in error responses`)}return ZK(n,NK),new Set(t?n:n.map(qK))}function YK(e,t,n){if(e.some(lK)){if(e.length>1)throw Error(`Cannot combine an upgrade with other success responses`);if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare an upgrade`);if(n)throw Error(`Upgrade endpoints cannot declare a payload`);return}let r=!1,i=new Map;for(let n of e){let e=pK(n)?n.schema:n,a=AK(n);if(iK(e)){if(QK(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=XK(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(PK(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);i.set(a,{...n,stream:e})}else{let t=XK(i,a),r=vK(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=jK(n);if(PK(e.contentType)===PK(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(PK(jK(n).contentType)),t.noContent=t.noContent||r}}ZK(e,AK)}function XK(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function ZK(e,t){let n=new Map;for(let r of e){let e=t(r),i=bK(r.ast),a=pK(r)?r.schema:i?.body??r,o=vK(a.ast)?``:PK(iK(a)?a.contentType:jK(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:new Set},n.set(e,s));let c=()=>Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(pK(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function QK(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(aK(e)&&$K(e.events.ast))throw Error(`SSE event name is reserved: ${GK}`)}function $K(e){return eq(mw(e),new Set)}function eq(e,t){if(t.has(e))return!1;if(t.add(e),SS(e))return e.types.some(e=>eq(e,t));if(CS(e))return eq(e.thunk(),t);if(!xS(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&tq(n.type,t)}function tq(e,t){if(t.has(e))return!1;t.add(e);let n=mw(e);return n===e?vS(e)?e.literal===GK:SS(e)?e.types.some(e=>tq(e,t)):CS(e)?tq(e.thunk(),t):!1:tq(n,t)}function nq(e){let t=OK(e.ast),n=bK(e.ast);return n===void 0?rq(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:rq(n.body,t),headersCodec:aO(n.headers)}})}function rq(e,t){switch(t._tag){case`Json`:return iO(e);case`FormUrlEncoded`:return aO(e);case`Text`:case`Uint8Array`:return e}}function iq(e,t){switch(DK(e.ast,t)._tag){case`Json`:return iO(e);case`FormUrlEncoded`:return aO(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var aq=HK(`GET`),oq=HK(`POST`),sq=`~effect/http-api/HttpApi`,cq={[sq]:sq,pipe(){return at(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Xn(t,n.identifier,n);return uq({...lq(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];Xn(t,n,r.annotateMerge(Ra(e.annotations,r.annotations)))}return uq({...lq(this),groups:t})},prefix(e){return uq({...lq(this),groups:co(this.groups,t=>t.prefix(e))})},middleware(e){return uq({...lq(this),groups:co(this.groups,t=>t.middleware(e))})},annotate(e,t){return uq({...lq(this),annotations:Oa(this.annotations,e,t)})},annotateMerge(e){return uq({...lq(this),annotations:Ra(this.annotations,e)})}},lq=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),uq=e=>{function t(){}return Object.setPrototypeOf(t,cq),Object.assign(t,e)},dq=e=>uq({identifier:e,groups:{},annotations:Ta()}),fq=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=Ra(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:Ra(n,e.annotations),successes:pq(LK(e),AK),errors:pq(RK(e),NK)})}},pq=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=pK(e)?e.schema:e;if(iK(r)||lK(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},mq=class extends sa()(`effect/http-api/HttpApi/ParseOptions`){},hq=class extends sa()(`effect/http-api/HttpApi/ParamsParseOptions`){},gq=class extends sa()(`effect/http-api/HttpApi/QueryParseOptions`){},_q=class extends sa()(`effect/http-api/HttpApi/HeadersParseOptions`){},vq=class extends sa()(`effect/http-api/HttpApi/PayloadParseOptions`){},yq=class extends sa()(`effect/http-api/HttpApi/SuccessParseOptions`){},bq=class extends sa()(`effect/http-api/HttpApi/ErrorParseOptions`){},xq=e=>{let t=Aa(e,mq);return{params:Aa(e,hq)??t,query:Aa(e,gq)??t,headers:Aa(e,_q)??t,payload:Aa(e,vq)??t,success:Aa(e,yq)??t,error:Aa(e,bq)??t}},Sq=`~effect/http-api/HttpApiMiddleware`,Cq=`~effect/http-api/HttpApiMiddleware/Security`,wq=()=>(e,t)=>{let n=Kn(),r;n!==0&&(qn(2),r=new globalThis.Error,qn(n));class i extends sa()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[Sq]=Sq,a.error=Tq(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[Cq]=Cq,a.security=t.security}return a};function Tq(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var Eq=new Set;function Dq(e){if(e===void 0)return Eq;let t=WC(e.ast);return xS(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function Oq(e,t,n){let r=/::|:(\w+)/g,i=``,a=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let s=o[1];if(s===void 0||t!==void 0&&!t.has(s))continue;let c=r.lastIndex;e[c]===`(`&&(c=uW(e,c)+1);let l=e[c]===`?`;l&&c++;let u=n(s,l),d=o.index;u===void 0&&e[d-1]===`/`&&d--,i+=e.slice(a,d)+(u??``),r.lastIndex=c,a=c}return i+e.slice(a)}var kq=(e,t)=>E(function*(){let n=yield*K_(),r=t.httpClient.pipe(t?.baseUrl===void 0?ct:NG(nG(t.baseUrl.toString())));function i(e,t,a,o,s){if(s===-1)return r.execute(a);let c=n.mapUnsafe.get(o[s]);return c===void 0?i(e,t,a,o,s-1):c({endpoint:t,group:e,request:a,next(n){return i(e,t,n,o,s-1)}})}fq(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:a,successes:o,mergedAnnotations:s}=e,c=xq(s),l=Mq(r.path,r.params),u={orElse:nJ},d=new Map;for(let[e,t]of a.entries()){let n=Rq(t);for(let[t,r]of n.entries())Iq(d,e,t,Nq(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=Lq(t);u[e]=e=>D(M_(n(e),t=>p_(wp(_p(new OW({reason:new PW({request:e.request,response:e})})),t))),f_)}let f=new Map;for(let[e,t]of o.entries()){let n=Rq(t);for(let[t,r]of n.entries())Iq(f,e,t,Nq(r,c.success,c.headers))}for(let e of Uq(r)){let t=Vq(e)?e.schema:e;Iq(f,AK(e),t.contentType,Wq(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=Lq(t);let p=Hq(r);p!==void 0&&(u[101]=e=>T_(e.upgrade,t=>({headers:e.headers,socket:t})));let m=ej(r.params,e=>gE(e,c.params)),h=[],g;for(let e of IK(r))oK(e)||sK(e)?g=e:h.push(e);let _=ej(g,e=>({contentType:e.contentType,encode:iJ(e,c.payload)})),v=yo(h)?gE(cW(r.method)?aJ(h,r.method):F(h),c.payload):void 0,ee=ej(r.headers,e=>gE(e,c.headers)),te=ej(r.query,e=>gE(e,c.query)),ne=Array.from(e.middleware,e=>`${e.key}/Client`),re=Sv(function*(e){let a=GW(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);a=tG(a,l(t))}if(_!==void 0&&Xk(e.payload)){let t=yield*K_();a=sG(a,EW(hA(_.encode(e.payload),t),_.contentType))}else if(v!==void 0){if(cW(r.method)){if(e.payload instanceof FormData)a=lG(a,e.payload);else{let t=yield*v(e.payload);a=sG(a,t)}}else{let t=yield*v(e.payload);a=aG(a,t)}}else if(_!==void 0)return yield*new rE(new tx({message:`Expected a Stream payload`},e.payload));if(ee!==void 0){let t=yield*ee(e.headers);a=ZW(a,t)}if(te!==void 0){let t=yield*te(e.query);a=aG(a,t)}}p!==void 0&&(a=eG(a,p.protocol));let o=yield*i(n,r,a,ne,ne.length-1);if(e?.responseMode===`response-only`)return o;let s=(u[o.status]??u.orElse)(o,e?.sseOptions),c=yield*t.transformResponse===void 0?s:t.transformResponse(s);return e?.responseMode===`decoded-and-response`?[c,o]:c});t.onEndpoint({...e,endpointFn:re})}})}),Aq=(e,t)=>D(DG,n=>jq(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),jq=(e,t)=>{let n={};return kq(e,{...t,onGroup({group:e}){e.topLevel||Xn(n,e.identifier,{})},onEndpoint({endpoint:e,endpointFn:t,group:r}){Xn(r.topLevel?n:n[r.identifier],e.identifier,t)}}).pipe(E_(n))},Mq=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=Dq(t);return t=>Oq(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function Nq(e,t,n){let r=e.some(e=>pK(e)||bK(e.ast)!==void 0),i=dE(r?F(e.map(e=>Fq(e,t,n))):eJ(e),t);return e=>D(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var Pq=N({body:OE,headers:OE});function Fq(e,t,n){let r=bK(e.ast),i=r===void 0?pK(e)?{body:e.schema,headers:e.headers,toValue:fK}:{body:e,headers:OE,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=dE(tJ(i.body).pipe(KE(i.body)),t),o=dE(i.headers,n);return Pq.pipe(KE(pK(e)?e:wE(e),Jx({decode:e=>n_({body:a(e.body),headers:o(e.headers)}).pipe(T_(i.toValue),P_(e=>e.issue)),encode:(e,t)=>f_(new rx({message:`Decode only schema`},e,t))})))}function Iq(e,t,n,r){let i=PK(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function Lq(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:(t,n)=>{let r=PK(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?zq(t,r,e):i.decode(t,n)}}function Rq(e){let t=new Map;for(let n of e){let e=vK((pK(n)?n.schema:n).ast)?``:PK(jK(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function zq(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return f_(new OW({reason:new FW({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var Bq=`effect/http-api/stream/failure`,Vq=e=>pK(e);function Hq(e){for(let t of e.success)if(lK(t))return t}function Uq(e){let t=[];for(let n of e.success)iK(pK(n)?n.schema:n)&&t.push(n);return t}function Wq(e,t,n){let r=Vq(e),i=Gq(r?e.schema:e,t),a=(e,t)=>T_(K_(),n=>hA(i(e,t),n));if(!r)return a;let o=dE(e.headers,n);return(e,t)=>D(o(e.headers),n=>T_(a(e,t),e=>fK({body:e,headers:n})))}function Gq(e,t){if(oK(e))return e=>e.stream;if(sK(e)){let n=dE(iO(e.schema),t),r=ry(e.maxElementBytes);return e=>e.stream.pipe(dA(RF({ignoreEmptyLines:!0,maxLineBytes:r})),uA(t=>AF(t)?t.reason===`LineTooLarge`?new OW({reason:new FW({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):qq(t):t),oA(e=>n(e)))}let n=Jq(e,t);return(t,r)=>Yq(t.stream,e,n(r))}var Kq=e=>AF(e)&&e.kind===`Pack`,qq=e=>new rE(new tx({message:e.reason===`InvalidUtf8`?`Expected valid UTF-8`:e.unterminated?`Expected a valid JSON line, got an unterminated final line`:`Expected a valid JSON line`}));function Jq(e,t){let n=F([N({id:CE(M),event:EE(Bq),data:kD(iO(FD(e.error,wD())))}),e.events]),r=WF(n,void 0,t);return e=>e===void 0?r:WF(n,e,t)}function Yq(e,t,n){let r=Qk(e.pipe(fA,dA(n)),e=>c_(()=>{let t;return s_(()=>t===void 0?D(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===Bq&&pp(r.data)){if(n===0)return p_(r.data);t=r.data,e=e.slice(0,n);break}}return T(e)}):p_(t))}));return t.sseMode===`data`?aA(r,e=>e.data):r}var Xq=tD(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),Zq=Xq.pipe(KE(ND,Yx({decode(e){return new Uint8Array(e)},encode(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}))),Qq=Xq.pipe(KE(M,Yx({decode(e){return new TextDecoder().decode(e)},encode(e){let t=new TextEncoder().encode(e);return t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}))),$q=Qq.pipe(KE(F([EE(``).pipe(KE(AE,Yx({decode:()=>void 0,encode:()=>``}))),AD])));function eJ(e){return F(e.map(t));function t(e){return tJ(e).pipe(KE(e))}}function tJ(e){switch(OK(e.ast)._tag){case`Json`:return hS(mw(e.ast))?$q.pipe(KE(OE,Yx({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):$q;case`FormUrlEncoded`:return Qq.pipe(KE(WD,Yx({decode:e=>ub(new URLSearchParams(e)),encode:yb})));case`Uint8Array`:return Zq;case`Text`:return Qq}}var nJ=e=>f_(new OW({reason:new FW({request:e.request,response:e})})),rJ=nE(fW);function iJ(e,t){if(oK(e))return e=>e;let n=gE(HE(iO(e.schema)),t);return e=>e.pipe(sA(e=>n(e)),dA(MF()),lA(Kq,rA))}function aJ(e,t){return F(e.map(e=>sJ(e,t)))}var oJ=new WeakMap;function sJ(e,t){let n=e.ast,r=oJ.get(n);if(r!==void 0)return r;let i=DK(n,t),a=rJ.pipe(KE(e,Jx({decode(e,t){return f_(new rx({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return f_(new rx({message:`Payload must be a FormData`},e,t));case`Json`:try{return T(bW(JSON.stringify(e),i.contentType))}catch{return f_(new tx({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?T(bW(e,i.contentType)):f_(new tx({message:`Expected a string`},e,t));case`FormUrlEncoded`:return Pt(e)?T(SW(ub(e),i.contentType)):f_(new tx({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?T(gW(e,i.contentType)):f_(new tx({message:`Expected a Uint8Array`},e,t))}}})));return oJ.set(n,a),a}var cJ=`~effect/http-api/HttpApiGroup`,lJ={[cJ]:cJ,add(...e){let t={...this.endpoints};for(let n of e)Xn(t,n.identifier,n);return dJ({...uJ(this),endpoints:t})},prefix(e){return dJ({...uJ(this),endpoints:co(this.endpoints,t=>t.prefix(e))})},middleware(e){return dJ({...uJ(this),endpoints:co(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return dJ({...uJ(this),annotations:Ra(this.annotations,e)})},annotate(e,t){return dJ({...uJ(this),annotations:Oa(this.annotations,e,t)})},annotateEndpointsMerge(e){return dJ({...uJ(this),endpoints:co(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return dJ({...uJ(this),endpoints:co(this.endpoints,n=>n.annotate(e,t))})},pipe(){return at(this,arguments)}},uJ=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),dJ=e=>{function t(){}return Object.setPrototypeOf(t,lJ),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},fJ=(e,t)=>dJ({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:Ta()}),pJ=class extends V(`@usine/config/AgentFile`)({name:yM,harness:gM,model:hM,effort:_M,parentModel:B(hM),parentEffort:B(_M),persona:bM}){get agent(){return new xM({name:this.name,persona:this.persona,brain:new vM({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},mJ=class extends V(`@usine/config/InvalidAgent`)({file:fM,error:mM}){},hJ=M.check(iD(/^\S(?:.*\S)?$/u,{message:`Expected a GitHub label name without surrounding whitespace`}),vD(50,{message:`Expected a GitHub label name of at most 50 characters`})).pipe(L(`GitHubLabelName`)),gJ=e=>e.toLowerCase(),_J=M.check(iD(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex GitHub label color without #`})).pipe(L(`GitHubLabelColor`)),vJ=M.check(vD(100,{message:`Expected a GitHub label description of at most 100 characters`})),yJ=class extends V(`@usine/config/DeclaredLabel`)({name:hJ,color:GD(_J),description:GD(vJ)}){},bJ=e=>M.check(iD(/\S/u,{message:e})),xJ=e=>rD(t=>new Set(t.map(t=>fj(e(t)))).size===t.length,{message:`Expected unique repository names, ignoring case`}),SJ=bJ(`Expected a non-blank lane name`).pipe(L(`LaneName`)),CJ=WE([`issue-open`,`issue-closed`,`pr-open`,`pr-closed`,`pr-merged`]),wJ=WE([`issue-closed`,`pr-closed`,`pr-merged`]),TJ=uE(wJ),EJ=e=>TJ(e),DJ=class extends V(`@usine/config/LabelLaneSource`)({label:hJ}){},OJ=F([DJ,class extends V(`@usine/config/StateLaneSource`)({state:CJ}){}]),kJ=class extends V(`@usine/config/Lane`)({name:SJ,sources:P(OJ).check(_D())}){},AJ=bJ(`Expected a non-blank registry tag`).pipe(L(`RegistryTag`)),jJ=R.check(fD(1)),MJ=rD(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),NJ=e=>`label`in e?`label:${gJ(e.label)}`:`state:${e.state}`,PJ=rD(e=>{let t=e.flatMap(({sources:e})=>e.map(NJ));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),FJ=P(kJ).check(MJ,PJ),IJ=rD(e=>new Set(e.map(({name:e})=>gJ(e))).size===e.length,{message:`Expected unique GitHub label names`}),LJ=P(yJ).check(IJ),RJ=class extends V(`@usine/config/ManagedRepo`)({name:sj,tags:P(AJ).check(bD()).pipe(ZE(T([]))),lanes:FJ.pipe(ZE(T([])))}){},zJ=jJ.pipe(ZE(T(1))),BJ=class extends V(`@usine/config/LocalWorker`)({name:PM,kind:EE(`local`),maxConcurrentAttempts:zJ}){},VJ=class extends V(`@usine/config/ExeDevWorker`)({name:PM,kind:EE(`exe.dev`),maxConcurrentAttempts:zJ}){},HJ=M.check(iD(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(L(`EnvironmentVariableName`)),UJ=class extends V(`@usine/config/WorkerGateway`)({domain:UM,destination:zM,adminPort:WM.pipe(ZE(T(7070))),adminTokenEnv:HJ,llmProviders:P(GM).check(bD()).pipe(ZE(T([])))}){},WJ=class extends V(`@usine/config/WorkerContainer`)({image:GD(qM),cpus:GD(YM),memoryMib:GD(XM),pids:GD(ZM)}){},GJ=class extends V(`@usine/config/ProviderApiKeys`)({anthropic:GD(HJ),openai:GD(HJ)}){}.pipe(ZE(T({}))),KJ=class extends V(`@usine/config/HetznerProvisioner`)({provider:EE(`hetzner`),tokenEnv:HJ,serverType:aN,location:oN,image:sN,network:GD(cN),firewall:GD(cN),sshKey:cN,sshUser:dN.pipe(ZE(T(`usine`))),labels:uN.pipe(ZE(T({}))),apiKeys:GJ}){},qJ=class extends V(`@usine/config/BoatProvisioner`)({provider:EE(`boat`),tokenEnv:HJ,size:fN.pipe(ZE(T(`default`))),apiKeys:GJ}){};F([KJ,qJ]);var JJ=F([KJ.pipe(LE({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),qJ.pipe(LE({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),YJ=class extends V(`@usine/config/SshWorker`)({name:PM,kind:EE(`ssh`),maxConcurrentAttempts:zJ,destination:GD(zM),provisioner:GD(JJ),identityFile:GD(VM),port:GD(BM),root:HM,gateway:GD(UJ.pipe(LE({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:WJ.pipe(LE({memoryMib:`memory_mib`}),ZE(T({})))}){},XJ=e=>{let t=Ji(e.provisioner);if(t===void 0)return S(e.destination)?`SSH worker "${e.name}" needs a destination or a provisioner`:void 0;if(C(e.destination))return`SSH worker "${e.name}" sets both destination and provisioner; a provisioned worker creates its machines, so remove destination`;if(C(e.port))return`SSH worker "${e.name}" sets port, which a provisioned worker takes from its provider`;switch(t.provider){case`hetzner`:return C(e.gateway)&&S(t.network)?`SSH worker "${e.name}" has a gateway, so its provisioner needs the gateway's private network in network`:void 0;case`boat`:return C(e.gateway)?`SSH worker "${e.name}" has a Boat provisioner and a gateway; Boat has no network rules, so no gateway can be its machines' only way out. Remove gateway.`:S(e.identityFile)?`SSH worker "${e.name}" has a Boat provisioner and needs identity_file, whose .pub file usine adds to each sandbox`:void 0}},ZJ=DD.check(rD(e=>e.protocol===`https:`,{message:`Expected an https URL`}),rD(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),QJ=class extends V(`@usine/config/CloudflareLlmProviderKey`)({provider:nN,apiKeyEnv:HJ}){},$J=rD(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),eY=class extends V(`@usine/config/CloudflareWorker`)({name:PM,kind:EE(`cloudflare`),maxConcurrentAttempts:zJ,workerUrl:ZJ,accessClientIdEnv:HJ,accessClientSecretEnv:HJ,image:tN,instanceType:eN.pipe(ZE(T(`standard-4`))),llmProviders:P(QJ.pipe(LE({apiKeyEnv:`api_key_env`}))).check($J).pipe(ZE(T([])))}){};F([BJ,VJ,YJ,eY]);var tY=class extends V(`@usine/config/Settings`)({pollInterval:jJ.pipe(ZE(T(60))),maxChildren:gN.pipe(ZE(T(4))),maxAttemptMinutes:GD(jJ),maxAttemptTokens:GD(jJ),parentModel:GD(hM),parentEffort:GD(_M)}){},nY=F([N({mode:EE(`off`)}),N({mode:EE(`deliveries`)}),N({mode:EE(`endpoint`),publicUrl:DD}).pipe(LE({publicUrl:`public_url`}))]),rY=DD.check(rD(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),rD(e=>e.username===``&&e.password===``&&e.search===``,{message:`Expected a URL without a username, password, or query string; authenticate in a collector next to usine up`})),iY=class extends V(`@usine/config/Tracing`)({otlpUrl:rY,serviceName:bJ(`Expected a non-blank service name`).pipe(ZE(T(`usine`)))}){},aY=tY.pipe(LE({pollInterval:`poll_interval`,maxChildren:`max_children`,maxAttemptMinutes:`max_attempt_minutes`,maxAttemptTokens:`max_attempt_tokens`,parentModel:`parent_model`,parentEffort:`parent_effort`})),oY=F([BJ.pipe(LE({maxConcurrentAttempts:`max_concurrent_attempts`})),VJ.pipe(LE({maxConcurrentAttempts:`max_concurrent_attempts`})),YJ.pipe(LE({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(rD(e=>XJ(e)??!0)),eY.pipe(LE({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),sY=P(RJ).check(xJ(e=>e.name)),cY=P(oY).check(_D(),MJ),lY=class extends V(`@usine/config/UsineConfig`)({version:EE(1),labels:LJ.pipe(ZE(T([]))),repos:sY,settings:aY.pipe(ZE(T({}))),workers:cY.pipe(ZE(T([{name:`local`,kind:`local`}]))),webhooks:nY.pipe(ZE(T({mode:`off`}))),operator:GD(TM),tracing:GD(iY.pipe(LE({otlpUrl:`otlp_url`,serviceName:`service_name`})))}){},uY=class extends V(`@usine/config/Selector`)({repos:GD(P(sj).check(_D(),xJ(e=>e))),tags:GD(P(AJ).check(_D(),bD()))}){}.check(rD(e=>C(e.repos)||C(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),dY=(e,t)=>Vi(e,{onNone:()=>!0,onSome:e=>{let n=Vi(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>fj(e)===fj(t.name))}),r=Vi(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),fY=M.check(rD(e=>e.trim().split(/\s+/u).length===5&&Za(Xh(e)),{message:`Expected a valid five-field cron expression`})).pipe(L(`Cron`)),pY=M.check(rD(e=>C(dy(e)),{message:`Expected an IANA time-zone name`})).pipe(L(`TimeZone`)),mY=class extends V(`@usine/config/IssueTrigger`)({on:EE(`issue`),if:cM}){},hY=class extends V(`@usine/config/PullRequestTrigger`)({on:EE(`pr`),if:cM}){},gY=class extends V(`@usine/config/ScheduleTrigger`)({on:EE(`schedule`),if:cM,cron:fY,tz:pY.pipe(ZE(T(`UTC`)))}){},_Y=F([mY,hY,gY]),vY=iD(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case file name`}),yY=gj.check(vY),bY=bJ(`Expected a non-blank Markdown prompt`).pipe(L(`PromptTemplate`)),xY=R.check(fD(1,{message:`Expected a priority of at least 1`})).pipe(L(`LoopPriority`)),SY=class extends V(`@usine/config/LoopFile`)({name:yY,trigger:_Y,selector:B(uY),approval:vj,maxCycles:AP.pipe(ZE(T(MP)),YE(T(MP))),permissions:bj.pipe(ZE(T(`write`)),YE(T(`write`))),priority:B(xY).pipe(YE(T(b()))),step:MM,agent:yM,body:bY}){},CY=class extends V(`@usine/config/QuarantinedLoop`)({file:fM,error:mM}){},wY=e=>fM.make(`loops/${e}.md`),TY=WE([`workers`,`webhooks`,`tracing`]),EY=e=>N({added:P(e),removed:P(e),changed:P(e)}),DY=class extends V(`@usine/orchestrator/InstanceReload`)({loops:EY(gj),agents:EY(yM),labels:EY(hJ),repos:EY(sj),workers:EY(PM),settingsChanged:ME,operatorChanged:ME,quarantinedLoops:P(CY),invalidAgents:P(mJ)}){},OY=class extends H(`@usine/orchestrator/InfraFailureView`)(`InfraFailure`,{message:M}){},kY=class extends H(`@usine/orchestrator/DefectFailureView`)(`DefectFailure`,{message:M}){},AY=class extends H(`@usine/orchestrator/AgentFailureView`)(`AgentFailure`,{message:M}){},jY=class extends H(`@usine/orchestrator/BlockedFailureView`)(`BlockedFailure`,{message:M}){},MY=class extends H(`@usine/orchestrator/QuestionFailureView`)(`QuestionFailure`,{question:M}){},NY=class extends H(`@usine/orchestrator/RunawayFailureView`)(`RunawayFailure`,{ceiling:GN}){},PY=class extends H(`@usine/orchestrator/ChildSessionBudgetFailureView`)(`ChildSessionBudgetFailure`,{maxChildren:gN,attemptedChildren:_N}){},FY=F([OY,kY,AY,jY,MY,NY,PY]),IY=class extends H(`@usine/orchestrator/SucceededAttemptView`)(`Succeeded`,{}){},LY=class extends H(`@usine/orchestrator/FailedAttemptView`)(`Failed`,{failure:FY}){},RY=class extends H(`@usine/orchestrator/CanceledAttemptView`)(`Canceled`,{}){},zY=F([IY,LY,RY]),BY=class extends H(`@usine/orchestrator/LocalWorkerAccess`)(`Local`,{}){},VY=class extends H(`@usine/orchestrator/SshWorkerAccess`)(`Ssh`,{destination:zM,port:I(BM)}){},HY=class extends H(`@usine/orchestrator/ProvisionedWorkerAccess`)(`Provisioned`,{provider:rN}){},UY=class extends H(`@usine/orchestrator/SandboxWorkerAccess`)(`Sandbox`,{}){},WY=F([BY,VY,HY,UY]),GY=class extends V(`@usine/orchestrator/AttemptView`)({id:lP,number:uP,worker:PM,workerAccess:I(WY),brain:vM,task:dP,agent:yM,operatorIntervened:ME,startedAt:M,outcome:I(zY),endedAt:I(M),salvage:I(tP),start:I(cP).pipe(YE(T(null))),reattachedAt:I(M).pipe(YE(T(null))),outOfMemory:I(gP).pipe(YE(T(null)))}){},KY=class extends V(`@usine/orchestrator/MachineView`)({worker:PM,provider:rN,state:sW,id:I(iN),runId:I(Qj),attemptId:I(lP),since:M}){},qY=class extends V(`@usine/orchestrator/ProvisioningPauseView`)({reason:F([nW,EE(`check`)]),message:M,failures:R,failedAt:M,retryAt:M,blocked:ME}){},JY=class extends H(`@usine/orchestrator/HetznerProvisionerView`)(`hetzner`,{tokenEnv:M,serverType:aN,location:oN,image:sN,network:I(cN),firewall:I(cN).pipe(YE(T(null))),sshKey:cN,sshUser:dN,labels:RE(M,M),anthropicKeyEnv:I(M),openaiKeyEnv:I(M)}){},YY=class extends H(`@usine/orchestrator/BoatProvisionerView`)(`boat`,{tokenEnv:M,size:fN,anthropicKeyEnv:I(M),openaiKeyEnv:I(M)}){},XY=F([JY,YY]),ZY=e=>new KY({worker:e.worker,provider:e.provider,state:e.state,id:w(e.id),runId:w(e.runId),attemptId:w(e.attemptId),since:_y(e.since)}),QY=e=>new qY({reason:e.reason,message:e.message,failures:e.failures,failedAt:_y(e.failedAt),retryAt:_y(e.retryAt),blocked:e.blocked}),$Y=e=>Vi(e.provisioner,{onNone:()=>null,onSome:e=>e.provider===`hetzner`?new JY({tokenEnv:e.tokenEnv,serverType:e.serverType,location:e.location,image:e.image,network:w(e.network),firewall:w(e.firewall),sshKey:e.sshKey,sshUser:e.sshUser,labels:e.labels,anthropicKeyEnv:w(e.apiKeys.anthropic),openaiKeyEnv:w(e.apiKeys.openai)}):new YY({tokenEnv:e.tokenEnv,size:e.size,anthropicKeyEnv:w(e.apiKeys.anthropic),openaiKeyEnv:w(e.apiKeys.openai)})}),eX=class extends H(`@usine/orchestrator/FailedTranscriptView`)(`Failed`,{failure:FY}){},tX=F([VP,HP,UP,eX,GP,KP,qP,YP,XP,JP,iF,aF,oF,sF]),nX=class extends V(`@usine/orchestrator/TranscriptEventView`)({sequence:mI,attemptId:lP,receivedAt:M,direction:zP,target:SE(tF),operator:SE(z),payload:tX}){},rX=class extends V(`@usine/orchestrator/TranscriptPageCursor`)({attemptId:lP,before:mI}){},iX=class extends H(`@usine/orchestrator/ColdTranscriptRequest`)(`ColdTranscriptRequest`,{}){},aX=class extends H(`@usine/orchestrator/TailTranscriptRequest`)(`TailTranscriptRequest`,{after:mI}){},oX=class extends H(`@usine/orchestrator/EarlierTranscriptRequest`)(`EarlierTranscriptRequest`,{attemptId:lP,before:mI}){};F([iX,aX,oX]);var sX=class extends rO(`@usine/orchestrator/TranscriptAttemptNotFoundError`)(`TranscriptAttemptNotFoundError`,{runId:Qj,attemptId:lP}){},cX=new Map([[`gpt-6-astra`,{input:10,cachedInput:1,cacheWrite:12.5,output:50}],[`gpt-6.1-sol`,{input:2,cachedInput:.1,cacheWrite:2.5,output:10}],[`gpt-6-sol`,{input:2,cachedInput:.2,cacheWrite:2.5,output:10}],[`gpt-6-luna`,{input:.1,cachedInput:.01,cacheWrite:.125,output:.5}],[`gpt-5.6-sol`,{input:4,cachedInput:.4,cacheWrite:5,output:20}],[`gpt-5.6-terra`,{input:2,cachedInput:.2,cacheWrite:2.5,output:12}],[`gpt-5.6-luna`,{input:.2,cachedInput:.02,cacheWrite:.25,output:1.2}],[`gpt-5.5`,{input:5,cachedInput:.5,output:30}],[`gpt-5.4`,{input:2.5,cachedInput:.25,output:15}],[`gpt-5.4-mini`,{input:.75,cachedInput:.075,output:4.5}],[`gpt-5.2`,{input:1.75,cachedInput:.175,output:14}]]),lX=(e,t)=>Zi(Gi(cX.get(e)),e=>ON.make((t.input*e.input+t.cachedInput*e.cachedInput+t.cacheWrite*(e.cacheWrite??e.input)+t.output*e.output)/1e6)),uX=class extends V(`@usine/orchestrator/UsageCostView`)({usd:ON,estimate:ME}){},dX=class extends V(`@usine/orchestrator/SessionUsageView`)({attemptId:lP,session:vN,pool:MN,tokens:mN,cost:I(uX)}){},fX=class extends V(`@usine/orchestrator/PoolUsageView`)({pool:MN,tokens:mN,cost:I(uX)}){},pX=class extends V(`@usine/orchestrator/RunUsageView`)({tokens:mN,pools:P(fX),sessions:P(dX)}){},mX=class extends V(`@usine/orchestrator/TaskPoolUsageView`)({pool:MN,tokens:mN,cost:I(uX),unpriced:ME}){},hX=class extends V(`@usine/orchestrator/TaskUsageView`)({durationMillis:R.check(fD(0)),runningSince:P(M),unmeasured:R.check(fD(0)),tokens:mN,pools:P(mX),cost:I(uX)}){},gX=[`apiKeys`,`claudePlan`,`chatgptPlan`],_X=(e,t)=>Vi(t,{onNone:()=>null,onSome:t=>new uX({usd:t,estimate:e!==`apiKeys`})}),vX=({session:e,costUsd:t,breakdown:n})=>C(t)||e.brain.harness!==`codex`?t:Qi(n,t=>lX(e.brain.model,t)),yX=e=>{let t=new Map;for(let{attemptId:n,envelope:r}of e){let e=r.payload;if(e._tag!==`SessionEvent`||e.event._tag!==`SessionTokensUpdated`)continue;let i=`${n} ${e.event.session.id}`,a=t.get(i);a!==void 0&&a.report.totalTokens>=e.event.totalTokens||t.set(i,{attemptId:n,report:e.event})}let n=[...t.values()].map(e=>({...e,price:vX(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=PN(t.session);return new dX({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:_X(r,n)})}),i=new Set(n.flatMap(({report:e,price:t})=>S(t)&&e.session.brain.harness===`codex`&&C(e.breakdown)?[e.session.brain.model]:[])),a=gX.flatMap(e=>{let t=r.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new fX({pool:e,tokens:mN.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:_X(e,n.length===t.length?x(ON.make(n.reduce((e,t)=>e+t,0))):b())})]});return{view:new pX({tokens:mN.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},bX=(e,t)=>{let n=0,r=0,i=[];for(let{attempts:t}of e)for(let{startedAt:e,endedAt:a,outcome:o}of t)o===null?i.push(e):a===null?r+=1:n+=Math.max(0,Date.parse(a)-Date.parse(e));let a=e.flatMap(({id:e})=>t.get(e)?.sessions??[]),o=gX.flatMap(e=>{let t=a.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new mX({pool:e,tokens:mN.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:_X(e,n.length===0?b():x(ON.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new hX({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:mN.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new uX({usd:ON.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},xX=E(function*(){let e=yield*RH,t=yield*c_(()=>new Map),n=yield*c_(()=>new Set),r=k(`RunUsageReader.attemptReports`)(function*(n){let r=t.get(n.id);if(r!==void 0)return{reports:r,read:!1};let i=yield*e.transcript(new CI({attemptId:n.id}));return C(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:k(`RunUsageReader.read`)(function*(e){yield*O({runId:e.run.id});let t=yield*r_(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=yX(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*Cv(`The OpenAI price table has no rates for a Codex model, so its sessions have no cost`,{model:t,runId:e.run.id}));return yield*j(`Read Run usage`,{runId:e.run.id,sessions:i.sessions.length,tokens:i.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),i})}});(class e extends sa()(`@usine/orchestrator/RunUsageReader`){static layer=ym(e,xX)});var SX=WE(Hj),CX=I(M),wX=class extends V(`@usine/orchestrator/EditAndRetry`)({task:dP,agent:yM}){},TX=class extends V(`@usine/orchestrator/SessionIntervention`)({attemptId:lP,target:tF.pipe(ZE(T({_tag:`Parent`}))),action:ZP}){};rO(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:yM,message:M}),rO(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:gj,message:M});var EX=class extends V(`@usine/orchestrator/ApprovalView`)({approvedAt:M,source:I(hF)}){},DX=class extends V(`@usine/orchestrator/RunView`)({id:Qj,itemKey:OP,loop:gj,repository:sj,agent:yM,agentBrain:vM,state:SX,loopPaused:ME,openedAt:M,closedAt:I(M),task:M,attempts:P(GY),approval:I(EX),runAgain:I(pI),resultMessage:CX,pullRequestUrl:CX,canApprove:ME,canRetry:ME,canResolveFailure:ME,canCancel:ME,canRunAgain:ME}){},OX=R.check(fD(0)),kX=R.check(fD(0)),AX=class extends V(`@usine/orchestrator/RunDurationView`)({endedMillis:OX,runningSince:I(M),unmeasured:kX}){},jX=class extends V(`@usine/orchestrator/UnconfirmedStopView`)({runId:Qj,attemptNumber:uP,worker:PM}){},MX=class extends V(`@usine/orchestrator/RunDetailView`)({run:DX,agentDefinitionChanged:ME,eventDedupKey:M,eventPayload:oO,transcript:P(nX),sessionState:P(nX),earlierTranscript:P(rX),worker:I(PM).pipe(YE(T(null))),settledItemState:I(wJ).pipe(YE(T(null))),duration:AX.pipe(YE(T(new AX({endedMillis:0,runningSince:null,unmeasured:0})))),usage:pX.pipe(YE(T(new pX({tokens:mN.make(0),pools:[],sessions:[]})))),unconfirmedStop:I(jX).pipe(YE(T(null))),machine:I(KY).pipe(YE(T(null)))}){},NX=z.pipe(L(`BoardLaneId`)),PX=WE([`authored`,`proposed`,`fallback`]),FX=class extends V(`@usine/orchestrator/BoardItemLink`)({itemKey:OP,kind:WE([`issue`,`pr`]),number:kP,title:M,url:z,state:CJ}){},IX=class extends V(`@usine/orchestrator/BoardPullRequestView`)({number:kP,url:z,state:WE([`pr-open`,`pr-merged`])}){},LX=class extends V(`@usine/orchestrator/BoardTaskView`)({...FX.fields,labels:P(hJ),items:P(FX).check(_D()),pullRequest:I(IX),runs:P(DX),run:I(DX),needsYou:ME,conflicting:ME,loops:P(gj),usage:hX}){},RX={id:NX,name:SJ,sources:P(OJ),origin:PX,items:P(LX)},zX=class extends H(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...RX,origin:EE(`authored`),labels:P(hJ).check(_D())}){},BX=class extends H(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,RX){},VX=F([zX,BX]),HX=class extends rO(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:sj,itemKey:OP,message:z}){},UX=class extends V(`@usine/orchestrator/BoardView`)({lanes:P(VX),failures:P(HX)}){},WX=class extends V(`@usine/orchestrator/LabelView`)({name:hJ,color:I(M),description:I(M)}){};V(`@usine/orchestrator/BoardMove`)({repository:sj,item:kP,toLane:NX});var GX=class extends rO(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:sj}){},KX=class extends rO(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:sj,item:kP}){};rO(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:sj,lane:NX}),rO(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:sj,lane:NX});var qX=Va(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),JX=class extends sa()(`effect/http/FetchHttpClient/RequestInit`){},YX=RG(T(jG((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return f_(new OW({reason:new MW({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(qX),a=Aa(r.context,JX)??{},o=a.headers?eb(Xy(a.headers),e.headers):e.headers;o[`content-length`]&&(o=tb(o,`content-length`));let s,c=c_(()=>s?.abort()),l=r=>T_(a_({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:typeof ReadableStream<`u`&&r instanceof ReadableStream?`half`:void 0,signal:s?AbortSignal.any([n,s.signal]):n}),catch:t=>new OW({reason:new MW({request:e,cause:t})})}),t=>{let n=_G(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>tv(n[e],c)}])),stream:{get:()=>mA(n.stream,c)}})):n}).pipe(nv(()=>c));switch(e.body._tag){case`Raw`:case`Uint8Array`:return l(e.body.body);case`FormData`:return l(e.body.formData);case`Stream`:{s=new AbortController;let t=AbortSignal.any([n,s.signal]),r=u_(e=>{let n=()=>e(ov);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),c_(()=>t.removeEventListener(`abort`,n))});return D(vA(pA(e.body.stream,r)),l)}}return l(void 0)}))),XX=R.check(fD(1)).pipe(L(`GitHubAppId`)),ZX=qD(z.check(iD(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(L(`GitHubAppPrivateKey`)),{disallowEncode:!0});V(`@usine/github/AppCredentials`)({appId:XX,privateKey:ZX});var QX=class extends sa()(`@usine/github/GitHubCredentials`){},$X=class extends rO(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:z}){},eZ=new TextEncoder,tZ=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),nZ=(...e)=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},rZ=e=>{if(e<128)return new Uint8Array([e]);let t=[];for(let n=e;n>0;n>>>=8)t.unshift(n&255);return new Uint8Array([128|t.length,...t])},iZ=(e,t)=>nZ(new Uint8Array([e]),rZ(t.length),t),aZ=e=>iZ(48,nZ(new Uint8Array([2,1,0]),tZ,iZ(4,e))),oZ=e=>{let t=e.includes(`-----BEGIN RSA PRIVATE KEY-----`),n=e.replace(/-----BEGIN (?:RSA )?PRIVATE KEY-----/gu,``).replace(/-----END (?:RSA )?PRIVATE KEY-----/gu,``).replace(/\s/gu,``),r=atob(n),i=Uint8Array.from(r,e=>e.charCodeAt(0));return t?aZ(i):i},sZ=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},cZ=e=>sZ(eZ.encode(JSON.stringify(e))),lZ=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},uZ=k(`AppJwt.import`)(function*(e){let t=yield*a_({try:async()=>crypto.subtle.importKey(`pkcs8`,lZ(oZ(Uy(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new $X({message:`Could not import the GitHub App private key as an RSA private key`})});return k(`AppJwt.sign`)(function*(){let n=Math.floor((yield*km)/1e3),r=`${cZ({alg:`RS256`,typ:`JWT`})}.${cZ({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*i_(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,lZ(eZ.encode(r))));return Vy(`${r}.${sZ(new Uint8Array(i))}`)})}),dZ=R.check(fD(1)),fZ=dZ.pipe(L(`GitHubInstallationId`)),pZ=dZ.pipe(L(`GitHubRepositoryId`)),mZ=z.pipe(L(`GitHubAppSlug`)),hZ=class extends V(`@usine/github/Installation`)({id:fZ,accountLogin:z,appSlug:mZ}){},gZ=class extends H(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},_Z=class extends H(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:sj,repositoryId:pZ,permissions:bj}){},vZ=F([gZ,_Z]),yZ=class extends V(`@usine/github/InstallationToken`)({value:KD(z,{disallowJsonEncode:!0}),expiresAt:VD,scope:vZ}){},bZ=WE([`missing`,`multiple`,`suspended`]),xZ=class extends rO(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:bZ,message:z}){},SZ={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},CZ={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},wZ=(e,t)=>e===t||t===`read`&&e===`write`,TZ=e=>Object.entries(SZ).flatMap(([t,n])=>wZ(e[t],n)?[]:[`${t}:${n}`]),EZ=class extends H(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:fZ,repository:sj,repositoryId:pZ}){},DZ=class extends rO(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:sj,message:z}){};F([EZ,DZ]);var OZ=(e,t,n)=>{let r=new Map(n.map(e=>[e.name.toLowerCase(),e]));return t.map(t=>{let n=r.get(t.toLowerCase());return n===void 0?new DZ({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new EZ({installationId:e.id,repository:t,repositoryId:n.id})})},kZ=class extends rO(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:P(z).check(_D()),message:z}){},AZ=WE([`create-repository-label`,`discover-installation`,`fetch-base-ref-head`,`fetch-item-labels`,`fetch-issue-snapshot`,`fetch-item-timeline`,`fetch-pull-request-snapshot`,`find-missing-issues`,`list-installation-repositories`,`list-repository-labels`,`mint-installation-token`,`mint-worker-token`,`poll-repository-changes`,`read-bot-account`,`update-item-labels`]),jZ=class extends rO(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:AZ,status:B(R),message:z}){},MZ=class extends rO(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:AZ,retryAt:VD,message:z}){},NZ=class extends rO(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:AZ,message:z,detail:z}){},PZ=class extends rO(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:AZ,item:R.check(fD(1)),message:z}){};F([xZ,kZ,jZ,MZ,NZ]);var FZ=`https://api.github.com`,IZ=`2026-03-10`,LZ=e=>ZW({accept:`application/vnd.github+json`,authorization:`Bearer ${Uy(e)}`,"user-agent":`usine`,"x-github-api-version":IZ}),RZ=(e,t)=>new jZ({operation:e,status:t.response===void 0?b():x(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),zZ=pE(N({message:z})),BZ=(e,t)=>t.json.pipe(T_(t=>Vi(zZ(t),{onNone:()=>e,onSome:({message:t})=>new jZ({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),k_(t=>j(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(E_(e)))),VZ=(e,t)=>new NZ({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),HZ=e=>{if(e===void 0||!/^\d+$/u.test(e))return b();let t=Number(e);return Number.isSafeInteger(t)?x(t):b()},UZ=(e,t)=>{let n=HZ(e);if(C(n))return x(t+n.value*1e3);if(e===void 0)return b();let r=Date.parse(e);return Number.isFinite(r)?x(r):b()},WZ=(e,t)=>{let n=HZ(e[`x-ratelimit-remaining`]),r=HZ(e[`x-ratelimit-reset`]);return C(n)&&n.value<=t&&C(r)?x(r.value*1e3):b()},GZ=(e,t)=>Zi(HZ(e[`x-poll-interval`]),e=>t+e*1e3),KZ=e=>{let t=e.flatMap(e=>Vi(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?b():x(Math.max(...t))},qZ=(e,t)=>KZ([UZ(e[`retry-after`],t),WZ(e,0)]),JZ=(e,t,n)=>{let r=Qi(qZ(t.headers,n),cy);return(t.status===403||t.status===429)&&C(r)?new MZ({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new jZ({operation:e,status:x(t.status),message:`GitHub returned HTTP status ${t.status}`})},YZ=36e5,XZ=3e5,ZZ=P(N({id:fZ,appSlug:mZ,account:N({login:z}),permissions:RE(M,M),suspendedAt:I(M)}).pipe(LE({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),QZ=N({login:IM,id:LM}),$Z=N({id:pZ,name:sj}).pipe(LE({name:`full_name`})),eQ=N({totalCount:R.check(fD(0)),repositories:P($Z)}).pipe(LE({totalCount:`total_count`})),tQ=N({token:z,expiresAt:HD,repositories:GD(P($Z))}).pipe(LE({expiresAt:`expires_at`})),nQ=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:SZ}}:{operation:`mint-worker-token`,body:{permissions:CZ[e.permissions],repository_ids:[e.repositoryId]}},rQ=class e extends sa()(`@usine/github/GitHubApp`){static layer=ym(e,E(function*(){let e=yield*uZ(yield*QX),t=yield*DG,n=(e,n,r)=>E(function*(){let i=yield*t.execute(n).pipe(P_(t=>RZ(e,t)));if(i.status<200||i.status>=300){let t=JZ(e,i,yield*km);return t._tag===`GitHubRateLimitError`?yield*t:yield*yield*BZ(t,i)}return yield*fG(r)(i).pipe(P_(t=>VZ(e,t.message)))}),r=k(`GitHubApp.discoverInstallation`)(function*(){let t=yield*e(),[r,...i]=yield*n(`discover-installation`,KW(`${FZ}/app/installations?per_page=2`).pipe(LZ(t)),ZZ);if(r===void 0)return yield*new xZ({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(i.length>0)return yield*new xZ({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(r.suspendedAt!==null)return yield*new xZ({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=TZ(r.permissions);return a.length>0?yield*new kZ({missing:a,message:`The GitHub App installation is missing permissions: ${a.join(`, `)}. Grant them in the GitHub App settings, then approve the change on the installation.`}):new hZ({id:r.id,accountLogin:r.account.login,appSlug:r.appSlug})}),i=k(`GitHubApp.mintToken`)(function*(t,r){let{operation:i,body:a}=nQ(r);yield*O({installationId:t,operation:i,scope:r._tag,permissions:r._tag===`SingleRepository`?r.permissions:`installation`});let o=yield*e(),s=yield*n(i,qW(`${FZ}/app/installations/${t}/access_tokens`).pipe(cG(a),LZ(o)),tQ),c=yield*km,l=hy(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new NZ({operation:i,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${_y(s.expiresAt)} is ${l}ms from now`});l>YZ&&(yield*A(`Accepted GitHub token clock skew; capped the local lease`,{installationId:t,operation:i,skewMillis:l-YZ}));let u=Hi(s.repositories,()=>[]);return r._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===r.repositoryId))?yield*new NZ({operation:i,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${r.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new yZ({value:Vy(s.token),expiresAt:sy(c+Math.min(l,YZ)),scope:r})}),a=k(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let r=1;;r+=1){let i=yield*n(`list-installation-repositories`,KW(`${FZ}/installation/repositories?per_page=100&page=${r}`).pipe(LZ(e.value)),eQ);if(t.push(...i.repositories),t.length>=i.totalCount)return t;if(i.repositories.length===0)return yield*new NZ({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${r} was empty after ${t.length} of ${i.totalCount} repositories`})}}),o=yield*ij(b()),s=k(`GitHubApp.lease`)(()=>oj(o,e=>E(function*(){let t=yield*km;if(C(e)&&hy(e.value.token.expiresAt)-t>XZ)return[e.value,e];let n=yield*r(),a={installation:n,token:yield*i(n.id,new gZ)};return[a,x(a)]}))),c=yield*ij(b()),l=k(`GitHubApp.botAccount`)(()=>oj(c,e=>E(function*(){let{installation:t,token:r}=yield*s(),{appSlug:i}=t;if(yield*O({appSlug:i}),C(e)&&e.value.appSlug===i)return[e.value.account,e];let a=new RM(yield*n(`read-bot-account`,KW(`${FZ}/users/${encodeURIComponent(`${i}[bot]`)}`).pipe(LZ(r.value)),QZ));return yield*A(`Read the App's bot account`,{appSlug:i,login:a.login,id:a.id}),[a,x({appSlug:i,account:a})]})));return{installation:k(`GitHubApp.installation`)(()=>T_(s(),e=>e.installation)),botAccount:l,installationToken:k(`GitHubApp.installationToken`)(()=>T_(s(),e=>e.token)),projectAccess:k(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*s();return OZ(t,e,yield*a(n))}),workerToken:k(`GitHubApp.workerToken`)((e,t)=>i(e.installationId,new _Z({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},iQ=z.pipe(L(`GitHubEntityTag`)),aQ=z.pipe(L(`GitHubBaseRefName`)),oQ=class extends V(`@usine/github/BaseRefHead`)({baseRefName:aQ,sha:lj,entityTag:UD(iQ)}){},sQ=class e extends V(`@usine/github/PollCursor`)({entityTag:UD(iQ),watermark:UD(HD)}){static empty=new e({entityTag:b(),watermark:b()})},cQ=class extends H(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:R.check(fD(1)),updatedAt:VD}){},lQ=class extends H(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:R.check(fD(1)),updatedAt:VD}){},uQ=F([cQ,lQ]),dQ=class extends H(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:sQ,nextPollAt:B(VD),backoffUntil:B(VD).pipe(YE(T(b())))}){},fQ=class extends H(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:sQ,items:P(uQ),backlog:ME,nextPollAt:B(VD),backoffUntil:B(VD).pipe(YE(T(b())))}){};F([dQ,fQ]);var pQ=z.pipe(L(`GitHubRepositoryLabelName`)),mQ=M.check(iD(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(L(`GitHubRepositoryLabelColor`)),hQ=class extends V(`@usine/github/RepositoryLabel`)({name:pQ,color:mQ,description:UD(M)}){},gQ=rD(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),_Q=class extends V(`@usine/github/RepositoryLabelCatalog`)({entityTag:UD(iQ),labels:P(hQ).check(gQ)}){},vQ=class extends H(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};F([_Q,vQ]);var yQ=class extends V(`@usine/github/NewRepositoryLabel`)({name:pQ,color:B(mQ),description:B(M)}){},bQ=N({name:pQ,color:mQ,description:I(M)}),xQ=e=>{let{name:t,owner:n}=dj(e);return`${FZ}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},SQ=class e extends sa()(`@usine/github/GitHubLabelWriter`){static layer=ym(e,E(function*(){let e=yield*rQ,t=yield*DG;return{create:k(`GitHubLabelWriter.create`)(function*(n,r){yield*O({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};C(r.color)&&(a.color=r.color.value),C(r.description)&&(a.description=r.description.value);let o=qW(xQ(n)).pipe(cG(a),LZ(i.value)),s=yield*t.execute(o).pipe(P_(e=>RZ(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*JZ(`create-repository-label`,s,yield*km);let c=yield*fG(bQ)(s).pipe(P_(e=>VZ(`create-repository-label`,e.message)));return new hQ({name:c.name,color:c.color,description:Gi(c.description)})})}}))},CQ=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),wQ=e=>Array.isArray(e)?e.map(wQ):uE(sO)(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!CQ.has(e)).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,wQ(t)])):e,TQ=6e4,EQ=N({data:SE(OE),errors:SE(P(N({message:M,type:SE(M)})))}),DQ=k(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=qW(`${FZ}/graphql`).pipe(cG({query:r,variables:i}),LZ(t.value)),s=yield*e.execute(o).pipe(P_(e=>RZ(n,e))),c=yield*km;if(s.status!==200)return yield*JZ(n,s,c);let l=yield*fG(EQ)(s).pipe(P_(e=>VZ(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new MZ({operation:n,retryAt:sy(Hi(qZ(s.headers,c),()=>c+TQ)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*VZ(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*dE(a)(l.data).pipe(P_(e=>VZ(n,e.message)))}),OQ=R.check(fD(1)),kQ=R.check(fD(0)),AQ=M.check(iD(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),jQ=(e,t)=>I(e).pipe(KE(e,{decode:Ax(e=>e??t),encode:Ax(e=>e)})),MQ={totalCount:0,nodes:[]},NQ=N({login:z}),PQ=I(NQ),FQ=N({totalCount:kQ,nodes:P(N({name:z}))}),IQ=N({totalCount:kQ,nodes:P(N({author:PQ,body:M,createdAt:AQ}))}),LQ=N({number:OQ,title:M,body:M,url:z,state:M,stateReason:I(M),createdAt:AQ,updatedAt:AQ,closedAt:I(AQ),author:PQ,issueType:I(N({name:M})),milestone:I(N({title:M})),labels:jQ(FQ,MQ),assignees:N({totalCount:kQ,nodes:P(NQ)}),comments:IQ,closedByPullRequestsReferences:jQ(N({totalCount:kQ,nodes:P(N({number:OQ,state:M,isDraft:ME,url:z}))}),MQ)}),RQ=I(N({login:SE(z)})),zQ=N({author:PQ,state:M,body:M,submittedAt:I(AQ),commit:I(N({oid:z}))}),BQ=N({author:PQ,body:M}),VQ=N({number:OQ,title:M,body:M,url:z,state:M,isDraft:ME,merged:ME,createdAt:AQ,updatedAt:AQ,mergedAt:I(AQ),author:PQ,baseRefName:aQ,headRefName:M,headRefOid:z,additions:kQ,deletions:kQ,changedFiles:kQ,reviewDecision:I(M),mergeable:M.pipe(ZE(T(`UNKNOWN`))),mergeStateStatus:M.pipe(ZE(T(`UNKNOWN`))),statusCheckRollup:I(N({state:M})),labels:jQ(FQ,MQ),reviewRequests:jQ(N({totalCount:kQ,nodes:P(N({requestedReviewer:RQ}))}),MQ),reviews:jQ(N({totalCount:kQ,nodes:P(zQ)}),MQ),reviewThreads:N({totalCount:kQ,nodes:P(N({isResolved:ME,isOutdated:ME,path:M,comments:N({totalCount:kQ,nodes:P(BQ)})}))}),comments:IQ,closingIssuesReferences:jQ(N({totalCount:kQ,nodes:P(N({number:OQ,state:M}))}),MQ)}),HQ=M.check(iD(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(L(`GitHubContentHash`)),UQ=class extends H(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:LQ,contentHash:HQ}){},WQ=class extends H(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:VQ,contentHash:HQ}){};F([UQ,WQ]);var GQ=`
|
|
37
|
+
query UsineIssuePayload($owner: String!, $name: String!, $number: Int!) {
|
|
38
|
+
repository(owner: $owner, name: $name) {
|
|
39
|
+
issue(number: $number) {
|
|
40
|
+
number
|
|
41
|
+
title
|
|
42
|
+
body
|
|
43
|
+
url
|
|
44
|
+
state
|
|
45
|
+
stateReason
|
|
46
|
+
createdAt
|
|
47
|
+
updatedAt
|
|
48
|
+
closedAt
|
|
49
|
+
author { login }
|
|
50
|
+
issueType { name }
|
|
51
|
+
milestone { title }
|
|
52
|
+
labels(first: 50) {
|
|
53
|
+
totalCount
|
|
54
|
+
nodes { name }
|
|
55
|
+
}
|
|
56
|
+
assignees(first: 10) {
|
|
57
|
+
totalCount
|
|
58
|
+
nodes { login }
|
|
59
|
+
}
|
|
60
|
+
comments(last: 20) {
|
|
61
|
+
totalCount
|
|
62
|
+
nodes {
|
|
63
|
+
author { login }
|
|
64
|
+
body
|
|
65
|
+
createdAt
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
closedByPullRequestsReferences(first: 10, includeClosedPrs: true) {
|
|
69
|
+
totalCount
|
|
70
|
+
nodes {
|
|
71
|
+
number
|
|
72
|
+
state
|
|
73
|
+
isDraft
|
|
74
|
+
url
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
`,KQ=`
|
|
81
|
+
query UsinePullRequestPayload($owner: String!, $name: String!, $number: Int!) {
|
|
82
|
+
repository(owner: $owner, name: $name) {
|
|
83
|
+
pullRequest(number: $number) {
|
|
84
|
+
number
|
|
85
|
+
title
|
|
86
|
+
body
|
|
87
|
+
url
|
|
88
|
+
state
|
|
89
|
+
isDraft
|
|
90
|
+
merged
|
|
91
|
+
createdAt
|
|
92
|
+
updatedAt
|
|
93
|
+
mergedAt
|
|
94
|
+
author { login }
|
|
95
|
+
baseRefName
|
|
96
|
+
headRefName
|
|
97
|
+
headRefOid
|
|
98
|
+
additions
|
|
99
|
+
deletions
|
|
100
|
+
changedFiles
|
|
101
|
+
reviewDecision
|
|
102
|
+
mergeable
|
|
103
|
+
mergeStateStatus
|
|
104
|
+
statusCheckRollup { state }
|
|
105
|
+
labels(first: 50) {
|
|
106
|
+
totalCount
|
|
107
|
+
nodes { name }
|
|
108
|
+
}
|
|
109
|
+
reviewRequests(first: 10) {
|
|
110
|
+
totalCount
|
|
111
|
+
nodes {
|
|
112
|
+
requestedReviewer {
|
|
113
|
+
... on User { login }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
reviews(last: 20) {
|
|
118
|
+
totalCount
|
|
119
|
+
nodes {
|
|
120
|
+
author { login }
|
|
121
|
+
state
|
|
122
|
+
body
|
|
123
|
+
submittedAt
|
|
124
|
+
commit { oid }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
reviewThreads(first: 50) {
|
|
128
|
+
totalCount
|
|
129
|
+
nodes {
|
|
130
|
+
isResolved
|
|
131
|
+
isOutdated
|
|
132
|
+
path
|
|
133
|
+
comments(first: 10) {
|
|
134
|
+
totalCount
|
|
135
|
+
nodes {
|
|
136
|
+
author { login }
|
|
137
|
+
body
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
comments(last: 20) {
|
|
143
|
+
totalCount
|
|
144
|
+
nodes {
|
|
145
|
+
author { login }
|
|
146
|
+
body
|
|
147
|
+
createdAt
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
closingIssuesReferences(first: 10) {
|
|
151
|
+
totalCount
|
|
152
|
+
nodes {
|
|
153
|
+
number
|
|
154
|
+
state
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
`,qQ=e=>{let t=Array.from({length:e},(e,t)=>t);return`
|
|
161
|
+
query UsineIssuesPresent($owner: String!, $name: String!, ${t.map(e=>`$n${e}: Int!`).join(`, `)}) {
|
|
162
|
+
repository(owner: $owner, name: $name) {
|
|
163
|
+
${t.map(e=>`i${e}: issue(number: $n${e}) { number }`).join(`
|
|
164
|
+
`)}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
`},JQ=5e3,YQ=100,XQ=10,ZQ=100,QQ=50,$Q=P(N({number:R.check(fD(1)),updatedAt:HD,pullRequest:SE(OE)}).pipe(LE({updatedAt:`updated_at`,pullRequest:`pull_request`}))),e$=N({object:N({sha:lj})}),t$=P(N({name:pQ,color:mQ,description:I(M)})),n$=({name:e,color:t,description:n})=>new hQ({name:e,color:t,description:Gi(n)}),r$=N({repository:UD(N({issue:UD(LQ)}))}),i$=N({repository:UD(N({pullRequest:UD(VQ)}))}),a$=I(N({number:R})),o$=e=>N({repository:UD(N(Object.fromEntries(Array.from({length:e},(e,t)=>[`i${t}`,a$]))))}),s$=e=>cy(e),c$=e=>e.map(e=>e.pullRequest===void 0?new cQ({number:e.number,updatedAt:e.updatedAt}):new lQ({number:e.number,updatedAt:e.updatedAt})),l$=e=>{let t=e.flatMap(e=>Vi(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?b():s$(Math.max(...t))},u$=(e,t)=>l$([UZ(e[`retry-after`],t),WZ(e,YQ)]),d$=(e,t)=>l$([GZ(e,t),UZ(e[`retry-after`],t),WZ(e,YQ)]),f$=e=>e===void 0?b():Gi(/<(?<url>[^>]+)>;\s*rel="next"/u.exec(e)?.groups?.url),p$=e=>{let t=hy(e)-JQ;return`${new Date(t-t%1e3).toISOString().slice(0,19)}Z`},m$=(e,t)=>{let{name:n,owner:r}=dj(e),i=new URL(`${FZ}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues`);return i.searchParams.set(`state`,`all`),i.searchParams.set(`sort`,`updated`),i.searchParams.set(`direction`,`asc`),i.searchParams.set(`per_page`,`100`),C(t.watermark)&&i.searchParams.set(`since`,p$(t.watermark.value)),i.toString()},h$=e=>{let{name:t,owner:n}=dj(e),r=new URL(`${FZ}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`);return r.searchParams.set(`per_page`,`100`),r.toString()},g$=(e,t)=>{let{name:n,owner:r}=dj(e),i=t.split(`/`).map(encodeURIComponent).join(`/`);return`${FZ}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/git/ref/heads/${i}`},_$=(e,t)=>{let{name:n,owner:r}=dj(e),i=new URL(`${FZ}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues/${t}/labels`);return i.searchParams.set(`per_page`,`100`),i.toString()},v$=(e,t)=>{let n=t.map(({updatedAt:e})=>hy(e));return C(e.watermark)&&n.push(hy(e.watermark.value)),n.length===0?b():s$(Math.max(...n))},y$=class e extends sa()(`@usine/github/GitHubPolling`){static layer=ym(e,E(function*(){let e=yield*rQ,t=yield*yA,n=yield*DG,r=b$(t),i=k(`GitHubPolling.execute`)(function*(e,t){return yield*n.execute(t).pipe(P_(t=>RZ(e,t)))}),a=k(`GitHubPolling.changesPage`)(function*(t){let n=yield*e.installationToken(),r=KW(t).pipe(LZ(n.value)),a=yield*i(`poll-repository-changes`,r),o=yield*km;return a.status===200?{items:c$(yield*fG($Q)(a).pipe(P_(e=>VZ(`poll-repository-changes`,e.message)))),next:f$(a.headers.link)}:yield*JZ(`poll-repository-changes`,a,o)}),o=k(`GitHubPolling.labelsPage`)(function*(t,n){let r=yield*e.installationToken(),a=KW(n).pipe(LZ(r.value)),o=yield*i(t,a),s=yield*km;return o.status===200?{labels:(yield*fG(t$)(o).pipe(P_(e=>VZ(t,e.message)))).map(n$),next:f$(o.headers.link)}:yield*JZ(t,o,s)}),s=k(`GitHubPolling.remainingLabelPages`)(function*(e,t){let n=[...t.labels],r=t.next,i=1;for(;C(r)&&i<ZQ;){let t=yield*o(e,r.value);n.push(...t.labels),r=t.next,i+=1}return C(r)?yield*VZ(e,`the GitHub label list has more than ${ZQ} pages`):n.sort((e,t)=>e.name.localeCompare(t.name))}),c=k(`GitHubPolling.allLabels`)(function*(e,t){return yield*s(e,yield*o(e,t))}),l=k(`GitHubPolling.labels`)(function*(t,n){yield*O({repository:t});let r=yield*e.installationToken(),a=KW(h$(t)).pipe(LZ(r.value));C(n)&&(a=XW(a,`if-none-match`,n.value));let o=yield*i(`list-repository-labels`,a),c=yield*km;if(o.status===304)return new vQ;if(o.status!==200)return yield*JZ(`list-repository-labels`,o,c);let l=yield*fG(t$)(o).pipe(P_(e=>VZ(`list-repository-labels`,e.message))),u=yield*s(`list-repository-labels`,{labels:l.map(n$),next:f$(o.headers.link)}),d=pE(iQ)(o.headers.etag);return S(d)&&(yield*Cv(`GitHub omitted the label catalog ETag; next poll is unconditional`,{repository:t})),new _Q({entityTag:d,labels:u})}),u=k(`GitHubPolling.changes`)(function*(t,n){let r=yield*e.installationToken(),o=KW(m$(t,n)).pipe(LZ(r.value));C(n.entityTag)&&(o=XW(o,`if-none-match`,n.entityTag.value));let s=yield*i(`poll-repository-changes`,o),c=yield*km,l=d$(s.headers,c);if(s.status===304)return new dQ({cursor:n,nextPollAt:l,backoffUntil:u$(s.headers,c)});if(s.status!==200)return yield*JZ(`poll-repository-changes`,s,c);let u=c$(yield*fG($Q)(s).pipe(P_(e=>VZ(`poll-repository-changes`,e.message)))),d=pE(iQ)(s.headers.etag);S(d)&&(yield*Cv(`GitHub omitted the changes ETag; next poll is unconditional`,{repository:t}));let f=[...u],p=f$(s.headers.link),m=1;for(;C(p)&&m<XQ;){let e=yield*a(p.value);f.push(...e.items),p=e.next,m+=1}let h=C(p);return h&&(yield*A(`GitHub changes walk hit the page cap; backlog remains`,{repository:t,pages:m,items:f.length})),new fQ({cursor:new sQ({entityTag:d,watermark:v$(n,f)}),items:f,backlog:h,nextPollAt:l,backoffUntil:u$(s.headers,c)})}),d=k(`GitHubPolling.baseRefHead`)(function*(t,n,r){yield*O({repository:t,baseRefName:n});let a=yield*e.installationToken(),o=KW(g$(t,n)).pipe(LZ(a.value)),s=Qi(r,({entityTag:e})=>e);C(s)&&(o=XW(o,`if-none-match`,s.value));let c=yield*i(`fetch-base-ref-head`,o),l=yield*km;if(c.status===304&&C(r))return r.value;if(c.status!==200)return yield*JZ(`fetch-base-ref-head`,c,l);let u=yield*fG(e$)(c).pipe(P_(e=>VZ(`fetch-base-ref-head`,e.message))),d=pE(iQ)(c.headers.etag);return S(d)&&(yield*Cv(`GitHub omitted the base branch ETag; next read is unconditional`,{repository:t,baseRefName:n})),new oQ({baseRefName:n,sha:u.object.sha,entityTag:d})}),f=k(`GitHubPolling.graphql`)(function*(t,r,i,a,o){let s=yield*e.installationToken(),{name:c,owner:l}=dj(r);return yield*DQ(n,s,t,a,{owner:l,name:c,number:i},o)});return{changes:u,labels:l,baseRefHead:d,snapshot:k(`GitHubPolling.snapshot`)((e,t)=>E(function*(){let n=t=>VZ(t,`repository "${e}" is null: deleted, renamed, or no longer accessible`),i=(n,r)=>new PZ({operation:n,item:t.number,message:`GitHub ${r} ${e}#${t.number} was not found. It was deleted or transferred, or the GitHub App can no longer read it.`}),a=k(`GitHubPolling.completeItemLabels`)(function*(n){if(n.labels.nodes.length>=n.labels.totalCount)return n.labels;yield*j(`Completing truncated Item label connection for Board matching`,{repository:e,item:t.number,listedLabels:n.labels.nodes.length,totalLabels:n.labels.totalCount});let r=yield*c(`fetch-item-labels`,_$(e,t.number));return{totalCount:r.length,nodes:r.map(({name:e})=>({name:e}))}});if(t._tag===`ChangedIssue`){let o=yield*f(`fetch-issue-snapshot`,e,t.number,GQ,r$);if(S(o.repository))return yield*n(`fetch-issue-snapshot`);let s=o.repository.value.issue;if(S(s))return yield*i(`fetch-issue-snapshot`,`issue`);let c={...s.value,labels:yield*a(s.value)};return new UQ({payload:c,contentHash:yield*r(c)})}let o=yield*f(`fetch-pull-request-snapshot`,e,t.number,KQ,i$);if(S(o.repository))return yield*n(`fetch-pull-request-snapshot`);let s=o.repository.value.pullRequest;if(S(s))return yield*i(`fetch-pull-request-snapshot`,`pull request`);let l={...s.value,labels:yield*a(s.value)};return new WQ({payload:l,contentHash:yield*r(l)})})),missingIssues:k(`GitHubPolling.missingIssues`)(function*(t,r){yield*O({repository:t,issues:r.length});let{name:i,owner:a}=dj(t);return(yield*r_(Po(r,QQ),r=>E(function*(){let o=yield*e.installationToken(),s=yield*DQ(n,o,`find-missing-issues`,qQ(r.length),{owner:a,name:i,...Object.fromEntries(r.map((e,t)=>[`n${t}`,e]))},o$(r.length));if(S(s.repository))return yield*VZ(`find-missing-issues`,`repository "${t}" is null: deleted, renamed, or no longer accessible`);let c=s.repository.value;return r.filter((e,t)=>c[`i${t}`]===null)}))).flat()})}}))},b$=e=>k(`GitHubPolling.contentHash`)(function*(t){let n=new TextEncoder().encode(JSON.stringify(wQ(t))),r=yield*e.digest(`SHA-256`,n).pipe(F_);return HQ.make(Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``))}),x$=class extends V(`@usine/orchestrator/LabelPreflightFinding`)({repository:sj,label:hJ,errorTag:z,message:z}){},S$=(e,t)=>{let n=[];if(C(e.color)){let r=e.color.value.toLowerCase();Vi(t.color,{onNone:()=>!0,onSome:e=>e.toLowerCase()!==r})&&n.push(`color`)}if(C(e.description)){let r=e.description.value;Vi(t.description,{onNone:()=>!0,onSome:e=>e!==r})&&n.push(`description`)}return n},C$=e=>new yQ({name:pQ.make(e.name),color:Zi(e.color,mQ.make),description:e.description}),w$=class e extends sa()(`@usine/orchestrator/LabelReconciler`){static layer=ym(e,E(function*(){let e=yield*SQ;return{reconcile:k(`LabelReconciler.reconcile`)(function*(t,n,r){yield*O({repository:t});let i=[...r],a=new Map(r.map(e=>[gJ(e.name),e])),o=[],s=!1,c=b();for(let r of n){let n=a.get(gJ(r.name));if(n!==void 0){let e=S$(r,n);e.length>0?yield*Cv(`Declared GitHub label differs from the existing repository label; left unchanged`,{repository:t,label:r.name,drift:e.join(`, `)}):yield*j(`Declared GitHub label already exists`,{repository:t,label:r.name});continue}let l=yield*S_(e.create(t,C$(r)));if(Xa(l)){let e=l.failure;if(o.push(new x$({repository:t,label:r.name,errorTag:e._tag,message:e.message})),e._tag===`GitHubRateLimitError`){c=x(e.retryAt),yield*Cv(`Label creation rate-limited; remaining declarations deferred and trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message,retryAt:_y(e.retryAt)});break}yield*wv(`Declared GitHub label could not be created; trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message});continue}let u=new tU({name:l.success.name,color:x(l.success.color),description:l.success.description});i.push(u),a.set(gJ(u.name),u),s=!0,yield*A(`Created declared GitHub label`,{repository:t,label:u.name})}return i.sort((e,t)=>e.name.localeCompare(t.name)),{labels:i,findings:o,catalogChanged:s,nextPollAt:c}})}}))},T$=(e,t,n)=>{let r=`${t}---`,i=e.indexOf(r,n);for(;i>=0;){let n=i+r.length;if(n===e.length||e.startsWith(t,n))return i;i=e.indexOf(r,n)}return-1},E$=(e,t)=>{let n=t.startsWith(`---\r
|
|
168
|
+
`)?`\r
|
|
169
|
+
`:t.startsWith(`---
|
|
170
|
+
`)?`
|
|
171
|
+
`:void 0;if(n===void 0)return new mM({file:e,stage:`frontmatter`,expression:b(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=T$(t,n,r);if(a<0)return new mM({file:e,stage:`frontmatter`,expression:b(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return T({yaml:t.slice(r,a),body:t.slice(s),newline:n})},D$=class extends H(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:sj,lane:SJ,label:hJ}){},O$=class extends H(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:SY.fields.name,label:hJ}){};F([D$,O$]);var k$=hE(eM),A$=(e,t)=>new aM({name:e,fields:t.map(([e,t,n])=>new iM({name:e,type:k$(t),nullable:n===`nullable`}))}),j$=A$(`Actor`,[[`login`,`string`]]),M$=A$(`Label`,[[`name`,`string`]]),N$=A$(`Milestone`,[[`title`,`string`]]),P$=A$(`IssueType`,[[`name`,`string`]]),F$=A$(`Commit`,[[`oid`,`string`]]),I$=A$(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),L$=A$(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),R$=A$(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),z$=A$(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),B$=A$(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),V$=A$(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),H$=A$(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),U$=A$(`IssuePayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`stateReason`,`string`,`nullable`],[`createdAt`,`string`],[`updatedAt`,`string`],[`closedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`issueType`,`IssueType`,`nullable`],[`milestone`,`Milestone`,`nullable`],[`labels`,`Labels`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),W$=A$(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),G$=A$(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),K$=A$(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),q$=A$(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),J$=A$(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),Y$=A$(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),X$=A$(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),Z$=A$(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),Q$=A$(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),$$=A$(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),e1=A$(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),t1=A$(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),n1=A$(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),r1=A$(`StatusCheckRollup`,[[`state`,`string`]]),i1=A$(`PullRequestPayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`isDraft`,`bool`],[`merged`,`bool`],[`createdAt`,`string`],[`updatedAt`,`string`],[`mergedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`baseRefName`,`string`],[`headRefName`,`string`],[`headRefOid`,`string`],[`additions`,`int`],[`deletions`,`int`],[`changedFiles`,`int`],[`reviewDecision`,`string`,`nullable`],[`mergeable`,`string`],[`mergeStateStatus`,`string`],[`statusCheckRollup`,`StatusCheckRollup`,`nullable`],[`labels`,`Labels`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),a1=A$(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),o1=A$(`SchedulePayload`,[[`tick`,`Tick`]]),s1=(e,t)=>new sM({types:[I$,...e],variables:[new oM({name:`repo`,type:k$(`RepoContext`)}),new oM({name:`item`,type:k$(t)})]}),c1=s1([j$,M$,N$,P$,L$,R$,z$,B$,V$,H$,U$],`IssuePayload`),l1=s1([j$,M$,F$,L$,W$,G$,K$,q$,J$,Y$,X$,Z$,Q$,$$,e1,t1,n1,r1,i1],`PullRequestPayload`),u1=s1([a1,o1],`SchedulePayload`),d1=e=>{switch(e){case`issue`:return c1;case`pr`:return l1;case`schedule`:return u1}},f1=e=>{let{owner:t}=dj(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},p1=Symbol.for(`yaml.alias`),m1=Symbol.for(`yaml.document`),h1=Symbol.for(`yaml.map`),g1=Symbol.for(`yaml.pair`),_1=Symbol.for(`yaml.scalar`),v1=Symbol.for(`yaml.seq`),y1=Symbol.for(`yaml.node.type`),b1=e=>!!e&&typeof e==`object`&&e[y1]===p1,x1=e=>!!e&&typeof e==`object`&&e[y1]===m1,S1=e=>!!e&&typeof e==`object`&&e[y1]===h1,C1=e=>!!e&&typeof e==`object`&&e[y1]===g1,w1=e=>!!e&&typeof e==`object`&&e[y1]===_1,T1=e=>!!e&&typeof e==`object`&&e[y1]===v1;function E1(e){if(e&&typeof e==`object`)switch(e[y1]){case h1:case v1:return!0}return!1}function D1(e){if(e&&typeof e==`object`)switch(e[y1]){case p1:case h1:case _1:case v1:return!0}return!1}var O1=e=>(w1(e)||E1(e))&&!!e.anchor,k1=Symbol(`break visit`),A1=Symbol(`skip children`),j1=Symbol(`remove node`);function M1(e,t){let n=P1(t);x1(e)?N1(null,e.contents,n,Object.freeze([e]))===j1&&(e.contents=null):N1(null,e,n,Object.freeze([]))}M1.BREAK=k1,M1.SKIP=A1,M1.REMOVE=j1;function N1(e,t,n,r){let i=F1(e,t,n,r);if(D1(i)||C1(i))return I1(e,r,i),N1(e,i,n,r);if(typeof i!=`symbol`){if(E1(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=N1(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===k1)return k1;else i===j1&&(t.items.splice(e,1),--e)}}else if(C1(t)){r=Object.freeze(r.concat(t));let e=N1(`key`,t.key,n,r);if(e===k1)return k1;e===j1&&(t.key=null);let i=N1(`value`,t.value,n,r);if(i===k1)return k1;i===j1&&(t.value=null)}}return i}function P1(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function F1(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(S1(t))return n.Map?.(e,t,r);if(T1(t))return n.Seq?.(e,t,r);if(C1(t))return n.Pair?.(e,t,r);if(w1(t))return n.Scalar?.(e,t,r);if(b1(t))return n.Alias?.(e,t,r)}function I1(e,t,n){let r=t[t.length-1];if(E1(r))r.items[e]=n;else if(C1(r))e===`key`?r.key=n:r.value=n;else if(x1(r))r.contents=n;else{let e=b1(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var L1={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},R1=e=>e.replace(/[!,[\]{}]/g,e=>L1[e]),z1=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+R1(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&D1(e.contents)){let t={};M1(e.contents,(e,n)=>{D1(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
|
|
172
|
+
`)}};z1.defaultYaml={explicit:!1,version:`1.2`},z1.defaultTags={"!!":`tag:yaml.org,2002:`};function B1(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function V1(e){let t=new Set;return M1(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function H1(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function U1(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=V1(e);let a=H1(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(w1(t.node)||E1(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function W1(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=W1(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=W1(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=W1(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=W1(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function G1(e,t,n){if(Array.isArray(e))return e.map((e,t)=>G1(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!O1(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var K1=class{constructor(e){Object.defineProperty(this,y1,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!x1(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=G1(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?W1(i,{"":o},``,o):o}},q1=class extends K1{constructor(e){super(p1),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],M1(e,{Node:(e,t)=>{(b1(t)||O1(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(G1(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=J1(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(B1(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function J1(e,t,n){if(b1(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(E1(t)){let r=0;for(let i of t.items){let t=J1(e,i,n);t>r&&(r=t)}return r}if(C1(t)){let r=J1(e,t.key,n),i=J1(e,t.value,n);return Math.max(r,i)}return 1}var Y1=e=>!e||typeof e!=`function`&&typeof e!=`object`,X1=class extends K1{constructor(e){super(_1),this.value=e}toJSON(e,t){return t?.keep?this.value:G1(this.value,e,t)}toString(){return String(this.value)}};X1.BLOCK_FOLDED=`BLOCK_FOLDED`,X1.BLOCK_LITERAL=`BLOCK_LITERAL`,X1.PLAIN=`PLAIN`,X1.QUOTE_DOUBLE=`QUOTE_DOUBLE`,X1.QUOTE_SINGLE=`QUOTE_SINGLE`;var Z1=`tag:yaml.org,2002:`;function Q1(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function $1(e,t,n){if(x1(e)&&(e=e.contents),D1(e))return e;if(C1(e)){let t=n.schema[h1].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new q1(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Z1+t.slice(2));let l=Q1(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new X1(e);return c&&(c.node=t),t}l=e instanceof Map?o[h1]:Symbol.iterator in Object(e)?o[v1]:o[h1]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new X1(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function e0(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return $1(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var t0=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,n0=class extends K1{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>D1(t)||C1(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(t0(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(E1(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,e0(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(E1(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&w1(i)?i.value:i:E1(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!C1(t))return!1;let n=t.value;return n==null||e&&w1(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return E1(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(E1(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,e0(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},r0=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function i0(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var a0=(e,t,n)=>e.endsWith(`
|
|
173
|
+
`)?i0(n,t):n.includes(`
|
|
174
|
+
`)?`
|
|
175
|
+
`+i0(n,t):(e.endsWith(` `)?``:` `)+n,o0=`flow`,s0=`block`,c0=`quoted`;function l0(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=u0(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
|
|
176
|
+
`)n===`block`&&(h=u0(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
|
|
177
|
+
`&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
|
|
178
|
+
`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function u0(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
179
|
+
`);r=t,i=t+1,a=e[i]}return r}var d0=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),f0=e=>/^(%|---|\.\.\.)/m.test(e);function p0(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
|
|
180
|
+
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function m0(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(f0(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
|
|
181
|
+
|
|
182
|
+
`;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
|
|
183
|
+
`,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:l0(o,a,c0,d0(t,!1))}function h0(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
184
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return m0(e,t);let n=t.indent||(f0(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:l0(r,n,o0,d0(t,!1))}function g0(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=m0;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?h0:i&&!t?m0:n?h0:m0}return r(e,t)}var _0;try{_0=RegExp(`(^|(?<!
|
|
185
|
+
))
|
|
186
|
+
+(?!
|
|
187
|
+
|$)`,`g`)}catch{_0=/\n+(?!\n|$)/g}function v0({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return g0(n,r);let l=r.indent||(r.forceBlockIndent||f0(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===X1.BLOCK_FOLDED?!1:t===X1.BLOCK_LITERAL||!p0(n,c,l.length);if(!n)return u?`|
|
|
188
|
+
`:`>
|
|
189
|
+
`;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
|
|
190
|
+
`&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
|
|
191
|
+
`);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
|
|
192
|
+
`&&(p=p.slice(0,-1)),p.replace(_0,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
|
|
193
|
+
`)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let ee=(h?l?`2`:`1`:``)+d;if(e&&(ee+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
|
|
194
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=d0(r,!0);o!==`folded`&&t!==X1.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=l0(`${v}${e}${p}`,l,s0,a);if(!i)return`>${ee}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${ee}\n${l}${v}${n}${p}`}function y0(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
195
|
+
`)||u&&/[[\]{},]/.test(a))return g0(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
196
|
+
`)?g0(a,t):v0(e,t,n,r);if(!s&&!u&&i!==X1.PLAIN&&a.includes(`
|
|
197
|
+
`))return v0(e,t,n,r);if(f0(a)){if(c===``)return t.forceBlockIndent=!0,v0(e,t,n,r);if(s&&c===l)return g0(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return g0(a,t)}return s?d:l0(d,c,o0,d0(t,!1))}function b0(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==X1.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=X1.QUOTE_DOUBLE);let c=e=>{switch(e){case X1.BLOCK_FOLDED:case X1.BLOCK_LITERAL:return i||a?g0(o.value,t):v0(o,t,n,r);case X1.QUOTE_DOUBLE:return m0(o.value,t);case X1.QUOTE_SINGLE:return h0(o.value,t);case X1.PLAIN:return y0(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function x0(e,t){let n=Object.assign({blockQuote:!0,commentString:r0,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function S0(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(w1(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function C0(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(w1(e)||E1(e))&&e.anchor;a&&B1(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function w0(e,t,n,r){if(C1(e))return e.toString(t,n,r);if(b1(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=D1(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=S0(t.doc.schema.tags,a);let o=C0(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):w1(a)?b0(a,t,n,r):a.toString(t,n,r);return o?w1(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function T0({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=D1(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(E1(e)||!D1(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||E1(e)||(w1(e)?e.type===X1.BLOCK_FOLDED||e.type===X1.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=w0(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=a0(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=a0(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=a0(g,n.indent,l(f))));let _,v,ee;D1(t)?(_=!!t.spaceBefore,v=t.commentBefore,ee=t.comment):(_=!1,v=null,ee=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&w1(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&T1(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let te=!1,ne=w0(t,n,()=>te=!0,()=>h=!0),re=` `;if(f||_||v){if(re=_?`
|
|
198
|
+
`:``,v){let e=l(v);re+=`\n${i0(e,n.indent)}`}ne===``&&!n.inFlow?re===`
|
|
199
|
+
`&&ee&&(re=`
|
|
200
|
+
|
|
201
|
+
`):re+=`\n${n.indent}`}else if(!p&&E1(t)){let e=ne[0],r=ne.indexOf(`
|
|
202
|
+
`),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=ne.indexOf(` `);e===`&`&&n!==-1&&n<r&&ne[n+1]===`!`&&(n=ne.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(re=`\n${n.indent}`)}}else(ne===``||ne[0]===`
|
|
203
|
+
`)&&(re=``);return g+=re+ne,n.inFlow?te&&r&&r():ee&&!te?g+=a0(g,n.indent,l(ee)):h&&i&&i(),g}function E0(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var D0=`<<`,O0={identify:e=>e===D0||typeof e==`symbol`&&e.description===D0,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new X1(Symbol(D0)),{addToJSMap:A0}),stringify:()=>D0},k0=(e,t)=>(O0.identify(t)||w1(t)&&(!t.type||t.type===X1.PLAIN)&&O0.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===O0.tag&&e.default);function A0(e,t,n){let r=M0(e,n);if(T1(r))for(let n of r.items)j0(e,t,n);else if(Array.isArray(r))for(let n of r)j0(e,t,n);else j0(e,t,r)}function j0(e,t,n){let r=M0(e,n);if(!S1(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function M0(e,t){return e&&b1(t)?t.resolve(e.doc,e):t}function N0(e,t,{key:n,value:r}){if(D1(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(k0(e,n))A0(e,t,r);else{let i=G1(n,``,e);if(t instanceof Map)t.set(i,G1(r,i,e));else if(t instanceof Set)t.add(i);else{let a=P0(n,i,e),o=G1(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function P0(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(D1(e)&&n?.doc){let t=x0(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),E0(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function F0(e,t,n){return new I0($1(e,void 0,n),$1(t,void 0,n))}var I0=class e{constructor(e,t=null){Object.defineProperty(this,y1,{value:g1}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return D1(n)&&(n=n.clone(t)),D1(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return N0(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?T0(this,e,t,n):JSON.stringify(this)}};function L0(e,t,n){return(t.inFlow??e.flow?z0:R0)(e,t,n)}function R0({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(D1(i))!d&&i.spaceBefore&&f.push(``),B0(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(C1(i)){let e=D1(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),B0(n,f,e.commentBefore,d))}d=!1;let s=w0(i,u,()=>o=null,()=>d=!0);o&&(s+=a0(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
|
|
204
|
+
`}}return e?(p+=`
|
|
205
|
+
`+i0(l(e),c),s&&s()):d&&o&&o(),p}function z0({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(D1(i))i.spaceBefore&&d.push(``),B0(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(C1(i)){let e=D1(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),B0(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=D1(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=w0(i,c,()=>a=null);l||=d.length>u||o.includes(`
|
|
206
|
+
`),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=a0(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
|
|
207
|
+
`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function B0({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=i0(t(r),e);n.push(i.trimStart())}}function V0(e,t){let n=w1(t)?t.value:t;for(let r of e)if(C1(r)&&(r.key===t||r.key===n||w1(r.key)&&r.key.value===n))return r}var H0=class extends n0{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(h1,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(F0(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=C1(e)?e:!e||typeof e!=`object`||!(`key`in e)?new I0(e,e?.value):new I0(e.key,e.value);let r=V0(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);w1(r.value)&&Y1(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=V0(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=V0(this.items,e)?.value;return(!t&&w1(n)?n.value:n)??void 0}has(e){return!!V0(this.items,e)}set(e,t){this.add(new I0(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)N0(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!C1(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),L0(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},U0={collection:`map`,default:!0,nodeClass:H0,tag:`tag:yaml.org,2002:map`,resolve(e,t){return S1(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>H0.from(e,t,n)},W0=class extends n0{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(v1,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=G0(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=G0(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&w1(r)?r.value:r}has(e){let t=G0(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=G0(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];w1(r)&&Y1(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(G1(e,String(r++),t));return n}toString(e,t,n){return e?L0(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push($1(a,void 0,n))}}return i}};function G0(e){let t=w1(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var K0={collection:`seq`,default:!0,nodeClass:W0,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return T1(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>W0.from(e,t,n)},q0={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),b0(e,t,n,r)}},J0={identify:e=>e==null,createNode:()=>new X1(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new X1(null),stringify:({source:e},t)=>typeof e==`string`&&J0.test.test(e)?e:t.options.nullStr},Y0={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new X1(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&Y0.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function X0({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var Z0={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:X0},Q0={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():X0(e)}},$0={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new X1(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:X0},e2=e=>typeof e==`bigint`||Number.isInteger(e),t2=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function n2(e,t,n){let{value:r}=e;return e2(r)&&r>=0?n+r.toString(t):X0(e)}var r2={identify:e=>e2(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>t2(e,2,8,n),stringify:e=>n2(e,8,`0o`)},i2={identify:e2,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>t2(e,0,10,n),stringify:X0},a2={identify:e=>e2(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>t2(e,2,16,n),stringify:e=>n2(e,16,`0x`)},o2=[U0,K0,q0,J0,Y0,r2,i2,a2,Z0,Q0,$0];function s2(e){return typeof e==`bigint`||Number.isInteger(e)}var c2=({value:e})=>JSON.stringify(e),l2=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:c2},{identify:e=>e==null,createNode:()=>new X1(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:c2},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:c2},{identify:s2,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>s2(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:c2}],u2=[U0,K0].concat(l2,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),d2={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=X1.BLOCK_LITERAL,t!==X1.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===X1.BLOCK_LITERAL?`
|
|
208
|
+
`:` `)}return b0({comment:e,type:t,value:s},r,i,a)}};function f2(e,t){if(T1(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!C1(r)){if(S1(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new I0(new X1(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=C1(r)?r:new I0(r)}}else t(`Expected a sequence for this tag`);return e}function p2(e,t,n){let{replacer:r}=n,i=new W0(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(F0(o,s,n))}return i}var m2={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:f2,createNode:p2},h2=class e extends W0{constructor(){super(),this.add=H0.prototype.add.bind(this),this.delete=H0.prototype.delete.bind(this),this.get=H0.prototype.get.bind(this),this.has=H0.prototype.has.bind(this),this.set=H0.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(C1(e)?(r=G1(e.key,``,t),i=G1(e.value,r,t)):r=G1(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=p2(e,t,n),i=new this;return i.items=r.items,i}};h2.tag=`tag:yaml.org,2002:omap`;var g2={collection:`seq`,identify:e=>e instanceof Map,nodeClass:h2,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=f2(e,t),r=[];for(let{key:e}of n.items)w1(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new h2,n)},createNode:(e,t,n)=>h2.from(e,t,n)};function _2({value:e,source:t},n){return t&&(e?v2:y2).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var v2={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new X1(!0),stringify:_2},y2={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new X1(!1),stringify:_2},b2={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:X0},x2={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():X0(e)}},S2={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new X1(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:X0},C2=e=>typeof e==`bigint`||Number.isInteger(e);function w2(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function T2(e,t,n){let{value:r}=e;if(C2(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return X0(e)}var E2={identify:C2,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>w2(e,2,2,n),stringify:e=>T2(e,2,`0b`)},D2={identify:C2,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>w2(e,1,8,n),stringify:e=>T2(e,8,`0`)},O2={identify:C2,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>w2(e,0,10,n),stringify:X0},k2={identify:C2,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>w2(e,2,16,n),stringify:e=>T2(e,16,`0x`)},A2=class e extends H0{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=C1(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new I0(e.key,null):new I0(e,null),V0(this.items,t.key)||this.items.push(t)}get(e,t){let n=V0(this.items,e);return!t&&C1(n)?w1(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=V0(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new I0(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(F0(e,null,n));return i}};A2.tag=`tag:yaml.org,2002:set`;var j2={collection:`map`,identify:e=>e instanceof Set,nodeClass:A2,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>A2.from(e,t,n),resolve(e,t){if(S1(e)){if(e.hasAllNullValues(!0))return Object.assign(new A2,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function M2(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function N2(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return X0(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var P2={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>M2(e,n),stringify:N2},F2={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>M2(e,!1),stringify:N2},I2={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(I2.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=M2(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``},L2=[U0,K0,q0,J0,v2,y2,E2,D2,O2,k2,b2,x2,S2,d2,O0,g2,m2,j2,P2,F2,I2],R2=new Map([[`core`,o2],[`failsafe`,[U0,K0,q0]],[`json`,u2],[`yaml11`,L2],[`yaml-1.1`,L2]]),z2={binary:d2,bool:Y0,float:$0,floatExp:Q0,floatNaN:Z0,floatTime:F2,int:i2,intHex:a2,intOct:r2,intTime:P2,map:U0,merge:O0,null:J0,omap:g2,pairs:m2,seq:K0,set:j2,timestamp:I2},B2={"tag:yaml.org,2002:binary":d2,"tag:yaml.org,2002:merge":O0,"tag:yaml.org,2002:omap":g2,"tag:yaml.org,2002:pairs":m2,"tag:yaml.org,2002:set":j2,"tag:yaml.org,2002:timestamp":I2};function V2(e,t,n){let r=R2.get(t);if(r&&!e)return n&&!r.includes(O0)?r.concat(O0):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(R2.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(O0)),i.reduce((e,t)=>{let n=typeof t==`string`?z2[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(z2).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var H2=(e,t)=>e.key<t.key?-1:+(e.key>t.key),U2=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?V2(e,`compat`):e?V2(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?B2:{},this.tags=V2(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,h1,{value:U0}),Object.defineProperty(this,_1,{value:q0}),Object.defineProperty(this,v1,{value:K0}),this.sortMapEntries=typeof a==`function`?a:a===!0?H2:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function W2(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=x0(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(i0(t,``))}let o=!1,s=null;if(e.contents){if(D1(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(i0(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=w0(e.contents,i,()=>s=null,t);s&&(c+=a0(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(w0(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
|
|
209
|
+
`)?(n.push(`...`),n.push(i0(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(i0(a(t),``)))}return n.join(`
|
|
210
|
+
`)+`
|
|
211
|
+
`}var G2=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,y1,{value:m1});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new z1({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[y1]:{value:m1}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=D1(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){K2(this.contents)&&this.contents.add(e)}addIn(e,t){K2(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=V1(this);e.anchor=!t||n.has(t)?H1(t||`a`,n):t}return new q1(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=U1(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=$1(e,l,p);return o&&E1(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new I0(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return K2(this.contents)?this.contents.delete(e):!1}deleteIn(e){return t0(e)?this.contents!=null&&(this.contents=null,!0):K2(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return E1(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return t0(e)?!t&&w1(this.contents)?this.contents.value:this.contents:E1(this.contents)?this.contents.getIn(e,t):void 0}has(e){return E1(this.contents)?this.contents.has(e):!1}hasIn(e){return t0(e)?this.contents!==void 0:E1(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=e0(this.schema,[e],t):K2(this.contents)&&this.contents.set(e,t)}setIn(e,t){t0(e)?this.contents=t:this.contents==null?this.contents=e0(this.schema,Array.from(e),t):K2(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new z1({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new z1({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new U2(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=G1(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?W1(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return W2(this,e)}};function K2(e){if(E1(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var q2=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},J2=class extends q2{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},Y2=class extends q2{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},X2=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
|
|
212
|
+
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function Z2(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,ee=null,te=null,ne=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!te||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),te&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),te=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){ee&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),ee=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let re=e[e.length-1],ie=re?re.offset+re.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:ee,found:te,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:ie,start:ne??ie}}function Q2(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
|
|
213
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(Q2(t.key)||Q2(t.value))return!0}return!1;default:return!0}}function $2(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&Q2(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function e4(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||w1(e)&&w1(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var t4=`All mapping items must start at the same column`;function n4({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??H0)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=Z2(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,t4)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
|
|
214
|
+
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||Q2(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,t4);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&$2(r.indent,u,i),n.atKey=!1,e4(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=Z2(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&$2(r.indent,f,i),s=c.range[2];let l=new I0(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
|
|
215
|
+
`+_.comment:g.comment=_.comment);let e=new I0(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function r4({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??W0)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=Z2(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&$2(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function i4(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var a4=`Block collections are not allowed within flow collections`,o4=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function s4({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?H0:W0))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=Z2(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
|
|
216
|
+
`+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&Q2(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];C1(t)&&(t=t.value??t.key),t.comment?t.comment+=`
|
|
217
|
+
`+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],o4(m)&&i(r.range,`BLOCK_IN_FLOW`,a4)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);o4(f)&&i(g.range,`BLOCK_IN_FLOW`,a4),n.atKey=!1;let _=Z2(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?o4(m)&&i(v.range,`BLOCK_IN_FLOW`,a4):_.comment&&(g.comment?g.comment+=`
|
|
218
|
+
`+_.comment:g.comment=_.comment);let ee=new I0(g,v);if(n.options.keepSourceTokens&&(ee.srcToken=l),o){let e=c;e4(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(ee)}else{let e=new H0(n.schema);e.flow=!0,e.items.push(ee);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=i4(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
|
|
219
|
+
`+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function c4(e,t,n,r,i,a){let o=n.type===`block-map`?n4(e,t,n,r,a):n.type===`block-seq`?r4(e,t,n,r,a):s4(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function l4(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===H0.tagName&&s===`map`||o===W0.tagName&&s===`seq`)return c4(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),c4(e,t,n,i,o)}let l=c4(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=D1(u)?u:new X1(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function u4(e,t,n){let r=t.offset,i=d4(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?X1.BLOCK_FOLDED:X1.BLOCK_LITERAL,o=t.source?f4(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
|
|
220
|
+
`.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
|
|
221
|
+
`;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===X1.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
|
|
222
|
+
`):t.length>c||r[0]===` `?(f===` `?f=`
|
|
223
|
+
`:!p&&f===`
|
|
224
|
+
`&&(f=`
|
|
225
|
+
|
|
226
|
+
`),d+=f+t.slice(c)+r,f=`
|
|
227
|
+
`,p=!0):r===``?f===`
|
|
228
|
+
`?d+=`
|
|
229
|
+
`:f=`
|
|
230
|
+
`:(d+=f+r,f=` `,p=!1)}switch(i.chomp){case`-`:break;case`+`:for(let e=s;e<o.length;++e)d+=`
|
|
231
|
+
`+o[e][0].slice(c);d[d.length-1]!==`
|
|
232
|
+
`&&(d+=`
|
|
233
|
+
`);break;default:d+=`
|
|
234
|
+
`}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function d4({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function f4(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function p4(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=X1.PLAIN,c=m4(a,l);break;case`single-quoted-scalar`:s=X1.QUOTE_SINGLE,c=h4(a,l);break;case`double-quoted-scalar`:s=X1.QUOTE_DOUBLE,c=_4(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=i4(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function m4(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),g4(e)}function h4(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),g4(e.slice(1,-1)).replace(/''/g,`'`)}function g4(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
|
|
235
|
+
`?a+=o:o=`
|
|
236
|
+
`:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function _4(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
|
|
237
|
+
`){if(i===`
|
|
238
|
+
`){let{fold:t,offset:i}=v4(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=y4[i];if(a)n+=a;else if(i===`
|
|
239
|
+
`)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
|
|
240
|
+
`)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=b4(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
|
|
241
|
+
`&&(a!==`\r`||e[r+2]!==`
|
|
242
|
+
`)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function v4(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
|
|
243
|
+
`||r===`\r`)&&(r!==`\r`||e[t+2]===`
|
|
244
|
+
`);)r===`
|
|
245
|
+
`&&(n+=`
|
|
246
|
+
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var y4={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
|
|
247
|
+
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function b4(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function x4(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?u4(e,t,r):p4(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[_1]:c?S4(e.schema,i,c,n,r):t.type===`scalar`?C4(e,i,t,r):e.schema[_1];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=w1(a)?a:new X1(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new X1(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function S4(e,t,n,r,i){if(n===`!`)return e[_1];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[_1])}function C4({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[_1];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[_1];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function w4(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var T4={composeNode:E4,composeEmptyNode:D4};function E4(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=O4(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=x4(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=l4(T4,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=D4(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!w1(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function D4(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=x4(e,{type:`scalar`,offset:w4(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function O4({options:e},{offset:t,source:n,end:r},i){let a=new q1(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=i4(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function k4(e,t,{offset:n,start:r,value:i,end:a},o){let s=new G2(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=Z2(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?E4(c,i,l,o):D4(c,l.end,r,null,l,o);let u=s.contents.range[2],d=i4(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function A4(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function j4(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
|
|
248
|
+
|
|
249
|
+
`:`
|
|
250
|
+
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var M4=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=A4(e);r?this.warnings.push(new Y2(i,t,n)):this.errors.push(new J2(i,t,n))},this.directives=new z1({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=j4(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(E1(i)&&!i.flow&&i.items.length>0){let e=i.items[0];C1(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:j4(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=A4(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=k4(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new J2(A4(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new J2(A4(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=i4(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new J2(A4(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new G2(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},N4=Symbol(`break visit`),P4=Symbol(`skip children`),F4=Symbol(`remove item`);function I4(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),L4(Object.freeze([]),e,t)}I4.BREAK=N4,I4.SKIP=P4,I4.REMOVE=F4,I4.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},I4.parentCollection=(e,t)=>{let n=I4.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function L4(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=L4(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===N4)return N4;else r===F4&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function R4(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
|
|
251
|
+
`:case`\r
|
|
252
|
+
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function z4(e){switch(e){case void 0:case` `:case`
|
|
253
|
+
`:case`\r`:case` `:return!0;default:return!1}}var B4=new Set(`0123456789ABCDEFabcdef`),V4=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),H4=new Set(`,[]{}`),U4=new Set(` ,[]{}
|
|
254
|
+
\r `),W4=e=>!e||U4.has(e),G4=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
|
|
255
|
+
`||t===`\r`&&this.buffer[e+1]===`
|
|
256
|
+
`}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
|
|
257
|
+
`||!t&&!this.atEnd)return e+n+1}return t===`
|
|
258
|
+
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&z4(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
259
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&z4(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!z4(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&z4(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(W4),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&z4(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(W4),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||z4(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
|
|
260
|
+
`,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
|
|
261
|
+
`,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>z4(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
|
|
262
|
+
`:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
|
|
263
|
+
`)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
|
|
264
|
+
`,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
|
|
265
|
+
`;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
|
|
266
|
+
`&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(z4(r)||e&&H4.has(r))break;t=n}else if(z4(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
|
|
267
|
+
`?(n+=1,r=`
|
|
268
|
+
`,i=this.buffer[n+1]):t=n),i===`#`||e&&H4.has(i))break;if(r===`
|
|
269
|
+
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&H4.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(W4),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(z4(n)||t&&H4.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!z4(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(V4.has(t))t=this.buffer[++e];else if(t===`%`&&B4.has(this.buffer[e+1])&&B4.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
270
|
+
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
271
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},K4=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function q4(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function J4(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function Y4(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function X4(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function Z4(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function Q4(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function $4(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!q4(t.start,`explicit-key-ind`)&&!q4(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,Y4(t.value)?t.value.end?Q4(t.value.end,t.sep):t.value.end=t.sep:Q4(t.start,t.sep),delete t.sep)}var e3=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new G4,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=R4(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&$4(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&J4(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:J4(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=Z4(X4(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
|
|
272
|
+
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
273
|
+
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Q4(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(q4(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=Z4(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(q4(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Y4(t.key)&&!q4(t.sep,`newline`)){let e=Z4(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):q4(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!q4(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Q4(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||q4(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=Z4(X4(t));$4(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
274
|
+
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
275
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=Z4(X4(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=Z4(X4(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function t3(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new K4||null,prettyErrors:t}}function n3(e,t={}){let{lineCounter:n,prettyErrors:r}=t3(t),i=new e3(n?.addNewLine),a=new M4(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new J2(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(X2(e,n)),o.warnings.forEach(X2(e,n))),o}var r3=e=>Vi(pE(N({message:z}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),i3=(e,t)=>E(function*(){let n=yield*g_({try:()=>n3(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new mM({file:e,stage:`yaml`,expression:b(),message:r3(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new mM({file:e,stage:`yaml`,expression:b(),message:r.message})}),a3=vx(),o3=F([M,ME]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(KE(cM,{decode:Ax(e=>String(e)),encode:Ax(e=>e)})),s3=F([mY.mapFields(JT({if:o3})).pipe(KE(mY)),hY.mapFields(JT({if:o3})).pipe(KE(hY)),gY.mapFields(JT({if:o3})).pipe(KE(gY))]),c3=class extends V(`@usine/config/LoopFrontmatter`)({trigger:s3,selector:GD(uY),approval:vj.pipe(ZE(T(`none`))),step:MM.pipe(ZE(T(`run`))),agent:yM,maxCycles:SY.fields.maxCycles,permissions:SY.fields.permissions,priority:GD(xY)}){}.pipe(LE({maxCycles:`max_cycles`})),l3=class extends V(`@usine/config/AgentFrontmatter`)({harness:gM,model:hM,effort:_M,parentModel:GD(hM),parentEffort:GD(_M)}){}.pipe(LE({parentModel:`parent_model`,parentEffort:`parent_effort`})),u3=(e,t)=>new mM({file:e,stage:`schema`,expression:b(),message:a3(t.issue)}),d3=dE(oO),f3=(e,t)=>E(function*(){return yield*d3((yield*i3(e,t)).toJS()).pipe(P_(t=>new mM({file:e,stage:`yaml`,expression:b(),message:a3(t.issue)})))}),p3=(e,t)=>new mM({file:e,stage:`expression`,expression:x(t.source),message:t.message}),m3=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?T(t.slice(0,-3)):new mM({file:e,stage:`schema`,expression:b(),message:`Expected a .md filename`})},h3=e=>m3(e).pipe(D(t=>dE(SY.fields.name)(t).pipe(P_(t=>u3(e,t))))),g3=e=>m3(e).pipe(D(t=>dE(yM)(t).pipe(P_(t=>u3(e,t))))),_3=(e,t)=>E(function*(){let n=[],r=0;for(;r<t.length;){let i=t.indexOf(`{{`,r);if(i<0)break;let a=t.indexOf(`}}`,i+2);if(a<0)return yield*new mM({file:e,stage:`expression`,expression:b(),message:`The prompt has an unclosed {{ at character ${i}. Close it with }}.`});let o=t.slice(i+2,a).trim(),s=yield*dE(cM)(o).pipe(P_(t=>u3(e,t)));n.push({source:s,start:i,end:a+2}),r=a+2}return n}),v3=(e,t,n)=>{let r=wY(t.name),i=d1(t.trigger.on);return E(function*(){let a=yield*r_(yield*_3(r,t.body),t=>e.evaluateScalar(t.source,i,n).pipe(P_(e=>p3(r,e)),T_(e=>({expression:t,value:e})))),o=``,s=0;for(let{expression:e,value:n}of a)o+=t.body.slice(s,e.start),o+=String(n),s=e.end;return o+t.body.slice(s)})},y3=k(`ConfigParser.parseUsineYaml`)((e,t)=>E(function*(){let n=yield*f3(e,t);return yield*dE(lY)(n,{onExcessProperty:`error`}).pipe(P_(t=>u3(e,t)))})),b3=k(`ConfigParser.parseAgentFile`)((e,t)=>E(function*(){let n=yield*g3(e),r=yield*E$(e,t),i=yield*f3(e,r.yaml),a=yield*dE(l3)(i,{onExcessProperty:`error`}).pipe(P_(t=>u3(e,t))),o=yield*dE(bM)(r.body).pipe(P_(t=>u3(e,t)));return new pJ({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),x3=e=>k(`ConfigParser.parseLoopFile`)((t,n)=>E(function*(){let r=yield*h3(t),i=yield*E$(t,n),a=yield*f3(t,i.yaml),o=yield*dE(c3)(a,{onExcessProperty:`error`}).pipe(P_(e=>u3(t,e))),s=yield*dE(bY)(i.body).pipe(P_(e=>u3(t,e))),c=d1(o.trigger.on);return yield*e.checkBoolean(o.trigger.if,c).pipe(P_(e=>p3(t,e))),yield*r_(yield*_3(t,s),({source:n})=>e.checkScalar(n,c).pipe(P_(e=>p3(t,e))),{discard:!0}),new SY({name:r,trigger:o.trigger,selector:o.selector,approval:o.approval,maxCycles:o.maxCycles,permissions:o.permissions,priority:o.priority,step:o.step,agent:o.agent,body:s})})),S3=pE(hJ),C3=e=>k(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>gJ(e))),i=[];for(let e of t.repos)for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(gJ(n.label))&&i.push(new D$({repository:e.name,lane:t.name,label:n.label}));for(let t of n){let n=yield*e.relatedStringLiterals(t.trigger.if,[`item`,`labels`]);for(let e of n){let n=S3(e);C(n)&&!r.has(gJ(n.value))&&i.push(new O$({loop:t.name,label:n.value}))}}return i}),w3=class e extends sa()(`@usine/config/ConfigParser`){static layer=ym(e,E(function*(){let e=yield*dM;return{configWarnings:C3(e),parseUsineYaml:y3,parseAgentFile:b3,parseLoopFile:x3(e),renderPrompt:k(`ConfigParser.renderPrompt`)((t,n)=>v3(e,t,n))}}))},T3=(e,t)=>e.changes.pipe(cA(e=>e!==t),gA,D(Vi({onNone:()=>d_,onSome:e=>T(e)}))),E3=cj.make(`HEAD`),D3=class extends rO(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:gj,agent:yM,message:z}){},O3=k(`TriggerRouting.resolveLoop`)(function*(e,t){yield*O({loop:t.name,agent:t.agent});let n=new Map(e.agents.map(e=>[e.name,e])).get(t.agent);if(n===void 0)return yield*new D3({loop:t.name,agent:t.agent,message:`Loop "${t.name}" references agent "${t.agent}", which is not in the roster`});let r=n.agent;return{agent:r,loop:t,parentModel:SM(r,e.config.settings.parentModel)}}),k3=k(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*S_(O3(e,n));Za(r)?t.push(r.success):yield*wv(`Loaded loop lost its rostered Agent; skipping the loop`,{loop:r.failure.loop,agent:r.failure.agent,errorTag:r.failure._tag,message:r.failure.message})}return t}),A3=e=>e.trigger.on===`schedule`?b():x(e.maxCycles),j3=e=>new eI({event:new hj({id:pj.make(e.dedupKey),dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),itemKey:e.itemKey,cycleGeneration:e.cycleGeneration,loop:e.loop.name,step:e.loop.step,approval:e.loop.approval,permissions:e.loop.permissions,cycleLimit:A3(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),M3=e=>GA(e,{Claimed:({runId:e})=>({runId:e}),Queued:()=>({}),Suppressed:({runId:e})=>({suppressedBy:e}),Ignored:({reason:e})=>({reason:e}),CycleBlocked:({ask:e})=>({askId:e.id,reason:`cycle-budget-exhausted`})}),N3=e=>Vi(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),P3=class extends V(`@usine/orchestrator/RepositoryPollFailure`)({repository:sj,errorTag:z,message:M}){},F3=class extends V(`@usine/orchestrator/RepositoryPoll`)({repository:sj,completedAt:VD}){},I3=class extends V(`@usine/orchestrator/PollCycle`)({repositoryPolls:P(F3).pipe(YE(T([]))),repositories:R.check(fD(0)),changedItems:R.check(fD(0)),submissions:P(dI),revokedRuns:R.check(fD(0)),failures:P(P3),preflightFindings:P(x$),nextPollAt:B(VD)}){},L3=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...N3(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},R3=e=>{let t=e.flatMap(e=>Vi(e,{onNone:()=>[],onSome:e=>[hy(e)]}));return t.length===0?b():cy(Math.max(...t))},z3=class extends V(`@usine/orchestrator/LoopEvaluationFailure`)({loop:gj,stage:WE([`if`,`prompt`]),expression:UD(cM),errorTag:z,message:M}){},B3=class extends V(`@usine/orchestrator/FailingItem`)({stream:WE([`issue`,`pr`]),number:kP,updatedAt:HD,contentHash:BH,failures:HE(z3)}){},V3=e=>e.stream===`issue`?new cQ({number:e.number,updatedAt:e.updatedAt}):new lQ({number:e.number,updatedAt:e.updatedAt}),H3=(e,t,n)=>{let[r,...i]=n;return r===void 0?b():x(new B3({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:kP.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},U3=e=>e.stage===`if`?`if:`:Vi(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),W3=(e,t)=>t.failures.map(n=>new P3({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${U3(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),G3=e=>Vi(e,{onNone:()=>[],onSome:({failures:e})=>e}),K3=(e,t)=>e.loop===t.loop&&e.stage===t.stage,q3=k(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*O({repository:e,item:t});for(let i of ta(r)){let r=Vi(n,{onNone:()=>[],onSome:e=>e.contentHash===i.contentHash?e.failures:[]});for(let n of i.failures){let a={repository:e,item:t,contentHash:i.contentHash,loop:n.loop,stage:n.stage,expression:w(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>K3(e,n))?yield*j(`Loop evaluation still fails on unchanged Item content`,a):yield*wv(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=G3(r);for(let r of G3(n))i.some(e=>K3(e,r))||(yield*A(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),J3=dE(P(hJ)),Y3=N({labels:LQ.fields.labels}),X3=N({labels:VQ.fields.labels}),Z3=(e,t)=>dE(e===`issue`?Y3:X3)(t).pipe(D(({labels:e})=>J3(e.nodes.map(({name:e})=>e)))),Q3=(e,t)=>new HX({repository:e.repository,itemKey:e.itemKey,message:t}),$3=e=>E(function*(){let t=C(e.goneAt);if(e.source===`issue`){let n=yield*dE(LQ)(e.payload).pipe(P_(t=>Q3(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:kP.make(e.number),title:n.title,url:n.url,state:n.state===`OPEN`&&!t?`issue-open`:`issue-closed`,linkedPullRequests:n.closedByPullRequestsReferences.nodes.map(({url:e})=>e),labels:yield*J3(n.labels.nodes.map(({name:e})=>e)).pipe(P_(t=>Q3(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*dE(VQ)(e.payload).pipe(P_(t=>Q3(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:kP.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*J3(n.labels.nodes.map(({name:e})=>e)).pipe(P_(t=>Q3(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*Q3(e,`Unsupported item projection source: ${e.source}`)}),e6=k(`settledItemState`)(function*(e){yield*O({itemKey:e});let t=yield*(yield*ZH).get(e);if(S(t))return b();let n=yield*S_($3(t.value));if(Xa(n))return yield*j(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),b();let{state:r}=n.success;return EJ(r)?x(r):b()}),t6=(e,t)=>e.canApprove||e.canResolveFailure&&!t,n6=k(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*O({repository:e});let t=yield*EU,n=(yield*t.asks()).filter(t=>fj(t.repository)===fj(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*e6(e.itemKey);S(r)?yield*j(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*A(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),r6=wE(OP).pipe(KE(kD(VE([EE(`github`),sj,kP])))),i6=yE(r6),a6=(e,t)=>i6([`github`,sj.make(fj(e)),kP.make(t)]),o6={labels:[],findings:[],catalogChanged:!1,nextPollAt:b()},s6=k(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*O({repository:e});let r=yield*mU,i=yield*hU,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:b(),failures:[],nextPollAt:b()};if(Xa(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*Cv(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:_y(t.retryAt)}),{...a,nextPollAt:x(t.retryAt)}):(yield*wv(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...L3(t)}),{...a,failures:[new P3({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof _Q)){let t=yield*r.get(e);return S(t)?(yield*Cv(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:b(),entityTagChanged:!0}):(yield*j(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:x(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new tU({name:e,color:x(t),description:n}));return yield*i.replace(new iU({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:x(s)}}),c6=k(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*O({repository:e});let r=yield*y$,i=yield*w$,a=yield*hU,o=yield*s6(e,n,yield*S_(r.labels(e,n))),s=yield*Vi(o.confirmedLabels,{onNone:()=>T(o6),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?b():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:R3([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new iU({repository:e,labels:s.labels})).pipe(P_(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),l6=k(`PollingTriggers.observeItem`)(function*(e,t){yield*O({repository:e,item:t.number});let n=yield*y$,r=yield*QH,i=yield*EU,a=a6(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new VH({itemKey:a,repository:e,source:zH.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:kP.make(t.number),contentHash:BH.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*j(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),u6=k(`PollingTriggers.markItemGone`)(function*(e,t){return yield*O({repository:e,item:t}),yield*(yield*QH).markGone(a6(e,t),yield*ly)}),d6=(e,t,{projection:n,cycleGeneration:r})=>mj.make(JSON.stringify([e.name,fj(t.name),n.number,n.contentHash,...r===0?[]:[r]])),f6=(e,t,n)=>E(function*(){return yield*(yield*dM).evaluateBoolean(e.trigger.if,d1(e.trigger.on),{repo:f1(t),item:n})}),p6=(e,t,n)=>E(function*(){let r=yield*dM,i=f1(t);return yield*r.evaluateBooleanEach(e.trigger.if,d1(e.trigger.on),n.map(e=>({repo:i,item:e})))}),m6=k(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*O({repository:e.name,item:r.number});let a=yield*w3,o=yield*YU,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:f1(e),item:c};if(s.length===0)return yield*j(`Item projected without any matching repository Loop`,{repository:e.name,item:r.number,stream:r.source}),{submissions:[],revokedRuns:0,failures:[]};let u=[],d=r.source===`pr`?cj.make(yield*dE(lj)(c.headRefOid).pipe(P_(()=>new NZ({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):E3,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*O({loop:m.name,agent:t.name});let s=yield*S_(f6(m,e,c));if(Xa(s)){f.push(new z3({loop:m.name,stage:`if`,expression:x(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*j(`Item did not match its loop expression`,{repository:e.name,loop:m.name,agent:t.name,item:r.number});let n=yield*o.revoke(m.name,r.itemKey);p+=n.length,n.length>0&&(yield*A(`Item stopped matching; revoked its unstarted runs`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,runIds:n.join(`, `)}));continue}let g=d6(m,e,n),_=yield*ly,v=yield*S_(a.renderPrompt(m,l));if(Xa(v)){f.push(new z3({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let ee=yield*o.submit(j3({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:dP.make(v.success),agent:t,parentModel:h}));yield*A(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:ee._tag,...M3(ee)}),u.push(ee)}return{submissions:u,revokedRuns:p,failures:f}}),h6=k(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*O({repository:e.name,item:r});let i=yield*YU,a=a6(e.name,r),o=0;for(let{agent:s,loop:c}of t.filter(({loop:e})=>e.trigger.on===n)){let t=yield*i.revoke(c.name,a);o+=t.length,t.length>0&&(yield*A(`Item is gone from GitHub; revoked its unstarted runs`,{repository:e.name,loop:c.name,agent:s.name,item:r,runIds:t.join(`, `)}))}return o}),g6=E(function*(){let e=new Set,t=yield*jO({capacity:128,strategy:`dropping`}),n=yield*JA(0),r=({repository:e,item:t})=>`${fj(e)}:${t.number}`,i=e=>Vi(e,{onNone:()=>l_,onSome:e=>QA(n,t=>Math.max(t,hy(e)))});return{offer:k(`PollingTriggers.hint`)(function*(n,a,o=b()){yield*O({repository:n,item:a.number}),yield*i(o);let s={repository:n,item:a},c=r(s);e.has(c)?yield*j(`Self-write Hint coalesced with a pending Item fetch`,{repository:n,item:a.number}):(e.add(c),(yield*NO(t,s))?yield*j(`Self-write Hint queued`,{repository:n,item:a.number}):(e.delete(c),yield*Cv(`Self-write Hint queue full; the normal poll will refresh the Item`,{repository:n,item:a.number})))},cv),take:lv(n=>n(zO(t)).pipe(x_(t=>c_(()=>e.delete(r(t)))))),defer:i,awaitBackoff:E(function*(){for(;;){let e=yield*YA(n),t=yield*km;if(e<=t)return;yield*A(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*B_(ws(e-t))}})}}),_6=class e extends sa()(`@usine/orchestrator/ItemHints`){static layer=ym(e,g6)},v6=Es(10),y6={revokedRuns:0,failures:[],nextPollAt:b()},b6=k(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*O({repository:e.name});let n=yield*ZH,r=yield*y$,i=yield*n.openIssues(e.name);if(i.length===0)return yield*j(`No open issues to check against GitHub`,{repository:e.name}),y6;let a=yield*S_(r.missingIssues(e.name,i));if(Xa(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*Cv(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:_y(t.retryAt)}),{...y6,nextPollAt:x(t.retryAt)}):(yield*wv(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...L3(t)}),{...y6,failures:[new P3({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*h6(e,t,`issue`,n),i=yield*u6(e.name,n);o+=r,yield*A(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*j(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...y6,revokedRuns:o}}),x6=4,S6=class extends V(`@usine/orchestrator/OpenPullRequest`)({number:lQ.fields.number,updatedAt:HD,baseRefName:GD(aQ),mergeable:M.pipe(ZE(T(`UNKNOWN`))),checksUnsettled:ME.pipe(ZE(T(!0)))}){},C6=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?x(new S6({number:e.number,updatedAt:e.updatedAt,baseRefName:x(t.payload.baseRefName),mergeable:t.payload.mergeable,checksUnsettled:t.payload.statusCheckRollup?.state===`PENDING`||t.payload.statusCheckRollup?.state===`EXPECTED`||t.payload.statusCheckRollup===null&&t.payload.mergeStateStatus===`BLOCKED`})):b(),w6=k(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*O({repository:e,baseRefName:t});let i=yield*S_((yield*y$).baseRefHead(e,t,n));if(Xa(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*Cv(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...L3(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return S(n)?(yield*A(`Base branch head recorded; refreshing its open pull requests once`,{repository:e,baseRefName:t,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a}):n.value.sha===a.sha?{_tag:`Unchanged`,head:a}:(yield*A(`Base branch head moved; refreshing its open pull requests`,{repository:e,baseRefName:t,previousHead:n.value.sha,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a})}),T6=(e,t)=>{if(S(e.baseRefName))return x(`baseUnrecorded`);let n=t.get(e.baseRefName.value);return n?._tag===`Moved`?x(`baseMoved`):n?._tag===`Unreadable`?x(`baseUnreadable`):e.mergeable===`UNKNOWN`?x(`mergeableUnknown`):e.checksUnsettled?x(`checksUnsettled`):b()},E6=k(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*O({repository:e}),t.length===0)return{refreshed:[],baseRefHeads:[]};let i=new Map;for(let{number:e,baseRefName:n}of t){if(S(n))continue;let t=i.get(n.value)??[];t.push(e),i.set(n.value,t)}let a=new Map(yield*r_(i,([t,r])=>w6(e,t,Gi(n.find(e=>e.baseRefName===t)),r).pipe(T_(e=>[t,e])),{concurrency:x6})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>ta(Zi(T6(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*j(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=Fo(s,({reason:e})=>e);yield*A(`Refreshing open pull requests`,{repository:e,baseRefReads:a.size,refreshed:s.length,skipped:o.length-s.length,...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.map(({pullRequest:e})=>e.number).join(`, `)]))})}return{refreshed:s.map(({pullRequest:e})=>e),baseRefHeads:[...a.values()].flatMap(e=>e._tag===`Unreadable`?ta(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),D6=4,O6=4,k6=z.pipe(L(`GitHubPollWatchKey`)),A6=class extends V(`@usine/orchestrator/StoredPollCursor`)({boardVersion:EE(5),openPullRequests:P(S6),baseRefHeads:P(oQ).pipe(ZE(T([]))),cursor:sQ,labelEntityTag:UD(iQ),watches:P(k6).check(bD()),failingItems:P(B3).pipe(ZE(T([])))}){},j6=e=>_U.make(`github-poll:${fj(e.name)}`),M6=({loop:e})=>k6.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),N6=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:e})=>e.trigger.on!==`schedule`&&dY(e.selector,n));return{repository:n,declaredLabels:e.config.labels,loops:r,watches:r.map(M6).sort()}}),P6=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),F6=class e extends sa()(`@usine/orchestrator/PollingTriggers`){static layer=ym(e,E(function*(){let e=yield*bU,t=yield*EU,n=yield*y$,r=yield*wU,i=yield*JA(b()),a=yield*JA(new Map),o=yield*_6,s=yield*ok(1),c=yield*JA({instance:b(),repositories:new Set}),l=yield*JA(new Map),u=e=>new A6({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:sQ.empty,labelEntityTag:b(),watches:e,failingItems:[]}),d=k(`PollingTriggers.readCursor`)(function*(t){yield*O({repository:t.repository.name});let n=yield*e.read(j6(t.repository),A6);return S(n)?u(t.watches):P6(n.value.watches,t.watches)?n.value:(yield*A(`Watched loops changed; re-polling the repository from scratch`,{repository:t.repository.name,previousWatches:n.value.watches.length,currentWatches:t.watches.length}),u(t.watches))}),f=k(`PollingTriggers.writeCursor`)(function*(t,n){yield*O({repository:t.repository.name}),yield*e.write(j6(t.repository),A6,n)}),p=k(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*O({repository:e.repository.name});let t=j6(e.repository),n=yield*km,r=(yield*YA(l)).get(t);return r!==void 0&&n-r<Ds(v6)?(yield*j(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:_y(sy(r))}),y6):(yield*QA(l,e=>new Map(e).set(t,n)),yield*b6(e.repository,e.loops))}),m=k(`PollingTriggers.pollRepository`)(function*(e){yield*O({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>fj(t)===fj(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*A(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*c6(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*E(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*YA(c)).repositories.has(j6(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*E6(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,V3(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new lQ({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*A(`Repository changed`,{repository:e.repository.name,changedItems:s.items.length,backlog:s.backlog}));let g=new Set([...m.refreshed,...l].map(({number:e})=>e).filter(e=>!d.has(e)));l.length>0&&(yield*A(`Evaluating Items whose Loops failed before this process started or the instance was reloaded`,{repository:e.repository.name,items:l.map(({number:e})=>e).join(`, `)}));let _=R3([s.nextPollAt,a.nextPollAt]);yield*j(`Refreshing detected Items and open pull requests`,{repository:e.repository.name,detection:s._tag,openPullRequests:i.openPullRequests.length,refreshedPullRequests:m.refreshed.length,items:h.size});let v=new Map(i.failingItems.map(e=>[e.number,e])),ee=yield*r_(h.values(),t=>E(function*(){let n=yield*l6(e.repository.name,t),r=yield*m6(e.repository,e.loops,n),i=H3(t,n.projection.contentHash,r.failures);return yield*q3(e.repository.name,t.number,Gi(v.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(A_(`GitHubItemNotFoundError`,n=>E(function*(){if(!g.has(t.number))return yield*n;let r=yield*h6(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*u6(e.repository.name,t.number);return yield*Cv(`GitHub no longer has an Item the poll cursor kept; it is dropped from the cursor`,{repository:e.repository.name,item:t.number,openPullRequest:i.openPullRequests.some(({number:e})=>e===t.number),revokedRuns:r,projectionMarkedGone:a,errorTag:n._tag,message:n.message}),{_tag:`Missing`,revokedRuns:r}}))),{concurrency:O6}),te=ee.flatMap(e=>e._tag===`Evaluated`?[e]:[]),ne=ee.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),re=te.map(({cycle:e})=>e),ie=yield*p(e);yield*o.defer(ie.nextPollAt),yield*n6(e.repository.name);let ae=[...i.failingItems.filter(({number:e})=>!h.has(e)),...te.flatMap(({failing:e})=>ta(e))].sort((e,t)=>e.number-t.number),oe=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...te.flatMap(({item:e,observation:t})=>ta(C6(e,t.snapshot)))],se=m.baseRefHeads.filter(({baseRefName:e})=>oe.some(t=>ia(t.baseRefName,e))),ce=new A6({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:oe,baseRefHeads:se,failingItems:ae});return(s._tag===`RepositoryChanges`||h.size>0||a.entityTagChanged||!sn(se,i.baseRefHeads))&&(yield*f(e,ce)),yield*QA(c,t=>({...t,repositories:new Set([...t.repositories,j6(e.repository)])})),yield*r_(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:re.flatMap(({submissions:e})=>e),revokedRuns:re.reduce((e,t)=>e+t.revokedRuns,ne+ie.revokedRuns),failures:[...a.failures,...ie.failures,...ae.flatMap(t=>W3(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:R3([_,ie.nextPollAt])}}).pipe(P_(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>W3(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*K_()).pipe(Ba(w3,EU,dM,y$,ZH,QH,w$,mU,hU,YU)),g=k(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*QA(c,t=>ia(t.instance,e)?t:{instance:x(e),repositories:new Set});let t=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let n of e.loops)n.trigger.on!==`schedule`&&t.has(n.name)&&(yield*j(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=N6(e,(yield*k3(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*r_(n,e=>S_(m(e)).pipe(T_(t=>({repository:e,result:t}))),{concurrency:D6}),l=[],u=[],d=[],f=[],p=yield*ly;for(let{repository:e,result:t}of s){if(Za(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*QA(a,t=>new Map(t).set(fj(e.repository.name),new F3({repository:e.repository.name,completedAt:p})));continue}let n=t.failure._tag===`InterruptedRepositoryCycle`,r=n?t.failure.error:t.failure;n&&(u.push(...t.failure.failures),f.push(...t.failure.preflightFindings),d.push(t.failure.nextPollAt),yield*o.defer(t.failure.nextPollAt)),r._tag===`GitHubRateLimitError`?(yield*Cv(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:_y(r.retryAt)}),d.push(x(r.retryAt)),yield*o.defer(x(r.retryAt))):(yield*wv(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...L3(r)}),u.push(new P3({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*YA(a),g=new I3({repositoryPolls:n.flatMap(({repository:e})=>ta(Gi(h.get(fj(e.name))))),repositories:n.length,changedItems:l.reduce((e,t)=>e+t.changedItems,0),submissions:l.flatMap(({submissions:e})=>e),revokedRuns:l.reduce((e,t)=>e+t.revokedRuns,0),failures:[...l.flatMap(({failures:e})=>e),...u],preflightFindings:f,nextPollAt:R3([...l.map(({nextPollAt:e})=>e),...d])});return yield*XA(i,x(g)),g},Y_(h),s.withPermits(1)),_=k(`PollingTriggers.refreshHint`)(function*(e,t){yield*O({repository:t.repository,item:t.item.number}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=N6(e,(yield*k3(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>fj(e.name)===fj(t.repository));if(i===void 0){yield*A(`Self-write Hint ignored for an unmanaged repository`,{repository:t.repository,item:t.item.number});return}let a=yield*l6(i.repository.name,t.item),s=yield*m6(i.repository,i.loops,a);for(let e of s.failures)yield*Cv(`Self-write Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:t.item.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*A(`Self-write Hint refreshed the Item`,{repository:t.repository,item:t.item.number,submissions:s.submissions.length,revokedRuns:s.revokedRuns,failures:s.failures.length})},Y_(h),(e,t,n)=>e.pipe(k_(e=>E(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(x(e.retryAt))),yield*Cv(`Self-write Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:n.item.number,...L3(e)})})),s.withPermits(1))),v=(e,t,n,r)=>E(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*km);if(t<=0)return;let n=yield*V_([B_(ws(t)).pipe(T_(()=>({_tag:`Due`}))),o.take.pipe(T_(e=>({_tag:`Hint`,hint:e}))),T3(e,a).pipe(T_(e=>({_tag:`Reloaded`,instance:e})))]);if(n._tag===`Due`)return;if(n._tag===`Hint`){yield*_(yield*e.get,n.hint);continue}a=n.instance,i=r;let s=r-(yield*km);s>0?yield*A(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*A(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:YA(i),poll:g,run:e=>E(function*(){let t=yield*e.get,n=yield*km,r=yield*S_(g(t));if(Xa(r)){let e=t.config.settings.pollInterval*1e3;yield*wv(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*B_(ws(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=Vi(i.nextPollAt,{onNone:()=>0,onSome:hy}),s=yield*km,c=Math.max(0,Math.max(a,o)-s);yield*A(`Poll cycle complete`,{repositories:i.repositories,changedItems:i.changedItems,submissions:i.submissions.length,revokedRuns:i.revokedRuns,failures:i.failures.length,preflightFindings:i.preflightFindings.length,sleepMs:c}),yield*v(e,t,a,o)}).pipe(uv),hint:o.offer}})).pipe(Em(_6.layer))},I6=4,L6=6e4,R6=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...N3(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},z6=class extends H(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:gj,agent:yM,message:M}){},B6=class extends H(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:gj,repository:sj,scheduledAt:VD,errorTag:z,message:M}){},V6=class extends H(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:gj,cron:M,tz:M,message:M}){},H6=F([z6,V6,B6]),U6=class extends V(`@usine/orchestrator/ScheduleCycle`)({loops:R.check(fD(0)),fanout:R.check(fD(0)),submissions:P(dI),skipped:R.check(fD(0)),alreadyFired:R.check(fD(0)),failures:P(H6),nextTickAt:B(VD)}){},W6=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(e=>dY(t.selector,e)),trigger:n}]:[]}),G6=(e,t)=>{let n=py(t);return n.setUTCSeconds(0,0),oy(Qh(e,n)?n:tg(e,n))},K6=(e,t)=>oy(eg(e,py(t))),q6=(e,t)=>Vi(fy(e,t),{onNone:()=>_y(e),onSome:vy}),J6=e=>e.length===0?b():cy(Math.min(...e.map(hy))),Y6=e=>OP.make(JSON.stringify([`github`,fj(e.name)])),X6=(e,t,n)=>mj.make(JSON.stringify([e.name,fj(t.name),_y(n)])),Z6=e=>({tick:{scheduledAt:_y(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends sa()(`@usine/orchestrator/ScheduleTriggers`){static layer=ym(e,E(function*(){let e=yield*w3,t=yield*dM,n=yield*YU,r=yield*wU,i=yield*JA(b()),a=yield*JA({instance:b(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=Zh(e.cron,e.tz);return o.set(e,n),n},c=k(`ScheduleTriggers.submitTick`)(function*(r,i){yield*O({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:_y(r.scheduledAt)});let a=Z6(r),o={repo:f1(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,d1(`schedule`),o)))return yield*j(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:_y(r.scheduledAt)}),b();let s=X6(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(j3({cycleGeneration:jP.make(0),agent:r.agent,dedupKey:s,itemKey:Y6(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:E3,task:dP.make(c),parentModel:r.parentModel}));return yield*A(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:_y(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...M3(l)}),x(l)}),l=k(`ScheduleTriggers.tick`)(function*(e){let t=yield*ly,n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let t of e.loops)t.trigger.on===`schedule`&&n.has(t.name)&&(yield*j(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=W6(e).filter(({loop:e})=>!n.has(e.name)),l=yield*ZA(a,t=>{let n=ia(t.instance,e)?t:{instance:x(e),ticks:new Map};return[n.ticks,n]}),u=[],d=[],f=[],p=new Map,m=[],h=0;for(let n of o){n.repositories.length===0&&(yield*Cv(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*g_({try:()=>{let e=s(n.trigger),r=G6(e,t);return{latest:r,latestLocal:q6(r,n.trigger.tz),next:K6(e,t)}},catch:e=>e}).pipe(S_);if(Xa(r)){yield*wv(`Schedule cron boundaries could not be computed`,{loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}),f.push(new V6({loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}));continue}let i=r.success;m.push(i.next);let a=hy(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*j(`Tick already fired`,{loop:n.loop.name,scheduledAt:_y(i.latest)});continue}let c=yield*S_(O3(e,n.loop));if(Xa(c)){let e=c.failure;yield*wv(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new z6({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*A(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:_y(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:_y(i.next)});for(let e of n.repositories)u.push({agent:c.success.agent,loop:n.loop,parentModel:c.success.parentModel,repository:e,scheduledAt:i.latest,scheduledAtLocal:i.latestLocal,trigger:n.trigger})}}yield*O({schedules:o.length,fanout:u.length});let g=yield*r_(u,e=>S_(c(e,t)).pipe(T_(t=>({candidate:e,result:t}))),{concurrency:I6}),_=[],v=[],ee=new Set,te=new Set,ne=0;for(let{candidate:e,result:t}of g){if(Za(t)){C(t.success)?(_.push(t.success.value),ee.add(e.loop.name)):ne+=1;continue}let n=t.failure;te.add(e.loop.name),yield*wv(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:_y(e.scheduledAt),...R6(n)}),v.push(new B6({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*QA(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)ee.has(e)&&!te.has(e)&&t.set(e,n);return{...e,ticks:t}});let re=new U6({loops:o.length,fanout:u.length,submissions:_,skipped:ne,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:J6(m)});return yield*XA(i,x(re)),re}),u=(e,t,n)=>H_(B_(ws(n)),T3(e,t).pipe(b_(A(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:YA(i),run:e=>E(function*(){let t=yield*e.get,n=yield*S_(l(t));if(Xa(n)){yield*wv(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:L6}),yield*u(e,t,L6);return}let r=n.success,i=yield*km,a=Vi(r.nextTickAt,{onNone:()=>i+L6,onSome:hy}),o=Math.min(L6,Math.max(0,a-i)),s={loops:r.loops,fanout:r.fanout,submissions:r.submissions.length,skipped:r.skipped,alreadyFired:r.alreadyFired,failures:r.failures.length,nextTickAt:Vi(r.nextTickAt,{onNone:()=>`none`,onSome:_y}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*j(`Schedule cycle complete`,s):yield*A(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(uv),tick:l}}))});var Q6=class extends H(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:M,repository:sj,runId:Qj,loop:gj,item:I(FX)}){},$6=class extends H(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:M,repository:sj,runId:Qj,loop:gj,failure:FY}){},e8=class extends H(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:M,failure:P3}){},t8=class extends H(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:M,finding:x$}){},n8=class extends H(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:M,failure:HX}){},r8=class extends H(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:M,failure:H6}){},i8=class extends H(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:M,kind:WE([`loop`,`agent`]),error:mM}){},a8=class extends H(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,N({id:M,worker:PM,attempts:R.check(fD(1)),running:R.check(fD(0))}).check(rD(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},o8=class extends H(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:M,repository:sj,runId:Qj,loop:gj,attemptNumber:uP,worker:PM}){},s8=F([class extends H(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:M,ask:IP,itemLabel:M,itemUrl:I(M)}){},Q6,n8,$6,e8,t8,r8,i8,a8,o8]),c8=WE([`clear`,`active`,`needs-you`]),l8=class extends V(`@usine/orchestrator/ProjectView`)({repository:sj,status:c8,runs:P(DX),board:UX,labels:P(WX),preflightFindings:P(x$)}){},u8=class extends V(`@usine/orchestrator/LoopView`)({name:gj,trigger:M,agent:yM,paused:ME}){},d8=class extends H(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:P(l8),loops:P(u8),needsYou:P(s8)}){},f8=class extends H(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:z,projects:P(l8),loops:P(u8),needsYou:P(s8)}){},p8=F([d8,f8]),m8=10,h8=class extends H(`@usine/github/LabelAdded`)(`LabelAdded`,{at:VD,label:hQ}){},g8=class extends H(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:VD,label:hQ}){},_8=class extends H(`@usine/github/Commented`)(`Commented`,{at:VD,url:z}){},v8=WE([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),y8=class extends H(`@usine/github/Reviewed`)(`Reviewed`,{at:VD,url:z,state:v8}){};F([h8,g8,_8,y8]);var b8=`
|
|
276
|
+
__typename
|
|
277
|
+
... on LabeledEvent { createdAt actor { __typename login } label { name color description } }
|
|
278
|
+
... on UnlabeledEvent { createdAt actor { __typename login } label { name color description } }
|
|
279
|
+
... on IssueComment { createdAt url author { __typename login } }`,x8=`
|
|
280
|
+
query UsineItemTimeline($owner: String!, $name: String!, $number: Int!, $since: DateTime!, $after: String) {
|
|
281
|
+
repository(owner: $owner, name: $name) {
|
|
282
|
+
issueOrPullRequest(number: $number) {
|
|
283
|
+
... on Issue {
|
|
284
|
+
timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT]) {
|
|
285
|
+
pageInfo { hasNextPage endCursor }
|
|
286
|
+
nodes {${b8}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
... on PullRequest {
|
|
291
|
+
timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT, PULL_REQUEST_REVIEW]) {
|
|
292
|
+
pageInfo { hasNextPage endCursor }
|
|
293
|
+
nodes {${b8}
|
|
294
|
+
... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
`,S8=I(N({__typename:M,login:M})),C8=N({name:pQ,color:mQ,description:I(M)}),w8=e=>N({__typename:EE(e),createdAt:HD,actor:S8,label:C8}),T8=F([w8(`LabeledEvent`),w8(`UnlabeledEvent`),N({__typename:EE(`IssueComment`),createdAt:HD,url:z,author:S8}),N({__typename:EE(`PullRequestReview`),createdAt:HD,submittedAt:I(HD),url:z,state:WE([...v8.literals,`PENDING`]),author:S8})]),E8=N({repository:UD(N({issueOrPullRequest:UD(N({timelineItems:N({pageInfo:N({hasNextPage:ME,endCursor:I(M)}),nodes:P(I(T8))})}))}))}),D8=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e,r=e=>new hQ({name:e.name,color:e.color,description:Gi(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new h8({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new g8({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new _8({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new y8({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},O8=class e extends sa()(`@usine/github/GitHubItemHistory`){static layer=ym(e,E(function*(){let e=yield*rQ,t=yield*DG,n=k(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){let o=yield*e.installationToken(),{name:s,owner:c}=dj(n),l=yield*DQ(t,o,`fetch-item-timeline`,x8,{owner:c,name:s,number:r,since:i,after:a},E8);if(S(l.repository))return yield*VZ(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(S(u))return yield*new PZ({operation:`fetch-item-timeline`,item:r,message:`Issue or pull request ${n}#${r} was not found on GitHub. It was deleted or transferred, or the GitHub App can no longer read it.`});let{pageInfo:d,nodes:f}=u.value.timelineItems;return d.hasNextPage?d.endCursor===null?yield*VZ(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:x(d.endCursor)}:{nodes:f,next:b()}});return{appChanges:k(`GitHubItemHistory.appChanges`)(function*(t,r,i){yield*O({repository:t,item:r});let{appSlug:a}=yield*e.installation(),o=_y(i),s=[],c=b(),l=0;do{let e=yield*n(t,r,o,w(c));s.push(...e.nodes),c=e.next,l+=1}while(C(c)&&l<m8);if(C(c))return yield*VZ(`fetch-item-timeline`,`the timeline of ${t}#${r} since ${o} has more than ${m8} pages`);let u=s.flatMap(e=>e===null?[]:D8(a,e));return yield*j(`Read the App's changes from an Item timeline`,{repository:t,item:r,since:o,pages:l,timelineItems:s.length,appChanges:u.length}),u})}}))},k8=class extends H(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:M,label:WX}){},A8=class extends H(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:M,label:WX}){},j8=class extends H(`@usine/orchestrator/CommentedView`)(`Commented`,{at:M,url:M}){},M8=class extends H(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:M,url:M,state:v8}){},N8=class extends H(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:M,fromLane:SJ,toLane:SJ}){},P8=F([k8,A8,j8,M8,N8]),F8=class extends V(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:lP,changes:P(P8)}){},I8=class extends V(`@usine/orchestrator/RunGitHubChangesView`)({attempts:P(F8)}){},L8=1e3,R8=6e4,z8=1e3,B8=1e4,V8=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>wP(e,i.at));t!==void 0&&(a.length>0?r.push(i):n.set(t.attemptId,[...n.get(t.attemptId)??[],i]))}return{attributed:n,ambiguous:r}},H8=e=>t=>{let n=hy(t.at),r=n-z8,i=hy(e.at),a=gJ(e.label.name);return r-r%1e3<=i&&i<=n+B8&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>gJ(e)===a)},U8=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(H8(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},W8=e=>new WX({name:hJ.make(e.name),color:e.color,description:w(e.description)}),G8=e=>GA(e,{LabelAdded:({at:e,label:t})=>new k8({at:_y(e),label:W8(t)}),LabelRemoved:({at:e,label:t})=>new A8({at:_y(e),label:W8(t)}),Commented:({at:e,url:t})=>new j8({at:_y(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new M8({at:_y(e),url:t,state:n})}),K8=e=>new N8({at:_y(e.at),fromLane:SJ.make(e.fromLane),toLane:SJ.make(e.toLane)}),q8=E(function*(){let e=yield*RH,t=yield*O8,n=yield*PU,r=yield*JA(new Map),i=k(`RunGitHubChanges.windowFor`)(function*(t){let n=xP(t);if(C(n))return n;let[r]=yield*e.transcript(new TI({attemptId:t.id,before:b(),limit:1}));return r===void 0?(yield*A(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),b()):x(new bP({attemptId:t.id,startedAt:t.startedAt,endedAt:x(r.receivedAt)}))});return{read:k(`RunGitHubChanges.read`)(function*(a){yield*O({runId:a});let o=yield*e.inspect(a),s=mE(r6)(o.itemKey);if(S(s))return yield*j(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:a}),new I8({attempts:[]});let[,,c]=s.value,l=o.repository;yield*O({repository:l,item:c});let u=e=>new I8({attempts:o.attempts.map(({id:t})=>new F8({attemptId:t,changes:e.get(t)??[]}))}),d=yield*YA(r),f=o.attempts.filter(({id:e})=>!d.has(e));if(f.length===0)return yield*j(`Served the Run's GitHub changes from the Attempt cache`,{runId:a,attempts:o.attempts.length}),u(d);let p=yield*e.forItems([o.itemKey]),m=(yield*r_([...new Map([...p.flatMap(({attempts:e})=>e),...o.attempts].map(e=>[e.id,e])).values()],i)).flatMap(ta),h=yield*km,g=new Map,_=[],v=f.flatMap(e=>{let t=m.find(({attemptId:t})=>t===e.id);return t===void 0?(g.set(e.id,[]),_.push(e.id),[]):[t]});if(v.length>0){let e=Math.min(...v.map(({startedAt:e})=>hy(e))),r=sy(e-e%1e3),[i,s]=yield*n_([t.appChanges(l,c,r),n.onItem(o.itemKey,gy(r,{milliseconds:B8}))],{concurrency:`unbounded`}),{moves:u,rest:d}=U8(s,i),{attributed:f,ambiguous:p}=V8(m,d);p.length>0&&(yield*A(`Left out GitHub changes that overlapping Attempts on the Item could each have made`,{runId:a,repository:l,item:c,changes:p.length,at:p.map(({at:e})=>_y(e)).join(`, `)}));for(let e of v){let t=[...(f.get(e.attemptId)??[]).map(e=>({at:hy(e.at),view:G8(e)})),...u.flatMap(t=>{let n=hy(t.at);return hy(e.startedAt)<=n&&Vi(e.endedAt,{onNone:()=>!0,onSome:e=>n<=hy(e)})?[{at:n,view:K8(t)}]:[]})];g.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),C(e.endedAt)&&h-hy(e.endedAt.value)>=R8&&_.push(e.attemptId)}yield*A(`Read the App's GitHub changes on a Run's Item`,{runId:a,repository:l,item:c,since:_y(r),appChanges:i.length,boardMoves:s.length,boardMoveChanges:i.length-d.length,placed:v.reduce((e,{attemptId:t})=>e+(f.get(t)?.length??0),0),cachedAttempts:_.length})}let ee=yield*$A(r,e=>{let t=new Map(e);for(let e of _)t.set(e,g.get(e)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-L8)))t.delete(e);return t});return u(new Map([...ee,...g]))})}});(class e extends sa()(`@usine/orchestrator/RunGitHubChanges`){static layer=ym(e,q8)});var J8=pE(DD),Y8=e=>new FX({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),X8=(e,t,n,r,i,a)=>{let o=Fo(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${fj(e)}/pull/`,l=new Map(s.filter(({item:e})=>e.kind===`pr`).map(e=>[`${c}${e.item.number}`,e])),u=new Set(r);for(let e of s){if(e.item.kind!==`issue`)continue;let t=[...e.item.linkedPullRequests,...e.runs.flatMap(({pullRequestUrl:e})=>e===null?[]:[e])];for(let n of t){let t=J8(n);if(S(t)||t.value.protocol!==`https:`||t.value.host!==`github.com`)continue;let r=l.get(t.value.pathname.toLowerCase());r!==void 0&&(e.related.add(r),r.related.add(e))}}let d=new Set,f=[];for(let e of s){if(d.has(e))continue;d.add(e);let t=[e];for(let e of t)for(let n of e.related)d.has(n)||(d.add(n),t.push(n));let n=Oo(t,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||Mi(e.number,t.number)),r=n[0],o=t.flatMap(({item:e,runs:t})=>t.map(t=>({item:e,run:t}))).sort(({run:e},{run:t})=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),s=o.find(({run:e})=>e.canCancel),c=t.filter(({item:e})=>e.kind===`pr`).sort(({item:e},{item:t})=>Number(t.state===`pr-open`)-Number(e.state===`pr-open`)||t.number-e.number),l=s?.item??c[0]?.item??r.item,[p=null]=c.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new IX({number:e,url:t,state:n})]:[]),m=o.find(({item:e,run:t})=>t6(t,EJ(e.state)))??s??o[0],h=o.map(({run:e})=>e).reverse(),g=new LX({...Y8(l),title:r.item.title,labels:l.labels,items:n.map(({item:e})=>Y8(e)),pullRequest:p,runs:h,run:m?.run??null,needsYou:o.some(({item:e,run:t})=>t6(t,EJ(e.state)))||t.some(({item:e})=>u.has(e.itemKey)),conflicting:l.conflicting,loops:[...new Set(n.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:bX(h,a)});f.push({view:g,running:s?.run.state===`Running`?s.run:void 0})}return f},Z8=e=>e.flatMap(e=>`label`in e?[e.label]:[]),Q8=e=>e.flatMap(e=>`state`in e?[e.state]:[]),$8=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>hJ.make(e)).map(e=>({lane:new kJ({name:SJ.make(e),sources:[new DJ({label:e})]}),origin:`proposed`})),e5=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):$8(t),t5=e=>NX.make(`${e.origin}:${e.lane.name}`),n5=(e,t)=>{let n=new Set(e.labels.map(gJ));return t.find(({lane:e})=>Z8(e.sources).some(e=>n.has(gJ(e))))},r5=(e,t)=>t.find(({lane:t})=>Q8(t.sources).includes(e.state)),i5=(e,t)=>EJ(e.state)?r5(e,t):n5(e,t)??r5(e,t),a5=k(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*O(a),EJ(t.state))return;let o=n5(t,r);if(o!==void 0)return yield*j(`Placing the running card in the lane its Item's labels match`,{...a,lane:o.lane.name}),o;let s=i.get(n.id);if(s===void 0){yield*j(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*Z3(t.kind,s.payload).pipe(T_(x),k_(e=>Cv(`The running Run's Event has no labels to read; placing its card by its Item's state`,{...a,eventId:s.id,errorTag:e._tag,message:e.message}).pipe(E_(b()))));if(S(c))return;let l=n5({labels:c.value},r);return yield*j(l===void 0?`No lane label when the card's running Run was triggered; placing it by its Item's state`:`Keeping the card in the lane its running Run was triggered from`,{...a,lane:l?.lane.name??`none`}),l}),o5=k(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>E(function*(){yield*O({repository:e.name});let c=yield*r_(n,e=>$3(e).pipe(S_)),l=[],u=[];for(let e of c)Za(e)?l.push(e.success):(u.push(e.failure),yield*wv(`Item projection quarantined from Board; siblings continue`,{repository:e.failure.repository,itemKey:e.failure.itemKey,errorTag:e.failure._tag,message:e.failure.message}));let d=e5(e,t),f=X8(e.name,l,r,i,a,o);yield*j(`Projected Task cards from linked Items`,{repository:e.name,items:l.length,tasks:f.length,runs:r.length,watchedTasks:f.filter(({view:e})=>e.loops.length>0).length,runningTasks:f.filter(({running:e})=>e!==void 0).length});let p=new Map;for(let e of d)p.set(t5(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*a5(e,t,n,d,s))??i5(t,d);r===void 0?m.push(t):p.get(t5(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new UX({failures:u,lanes:[...d.map(e=>{let t=Z8(e.lane.sources),n={id:t5(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(t5(e))??[])};return e.origin===`authored`&&t.length>0?new zX({...n,origin:e.origin,labels:t}):new BX(n)}),new BX({id:NX.make(`fallback:unmapped`),name:SJ.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),s5=500,c5=500,l5=e=>GA(e,{InfraFailure:({message:e})=>new OY({message:e}),DefectFailure:({message:e})=>new kY({message:e}),AgentFailure:({message:e})=>new AY({message:e}),BlockedFailure:({message:e})=>new jY({message:e}),QuestionFailure:({question:e})=>new MY({question:e}),RunawayFailure:({ceiling:e})=>new NY({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new PY({attemptedChildren:e,maxChildren:t})}),u5=e=>GA(e,{Succeeded:()=>new IY,Failed:({failure:e})=>new LY({failure:l5(e)}),Canceled:()=>new RY}),d5=e=>{switch(e.kind){case`local`:return new BY;case`ssh`:return Vi(e.provisioner,{onSome:({provider:e})=>new HY({provider:e}),onNone:()=>new VY({destination:Hi(e.destination,()=>zM.make(e.name)),port:w(e.port)})});case`exe.dev`:return new VY({destination:zM.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new UY}},f5=e=>new Map(e.map(e=>[e.name,d5(e)])),p5=(e,t)=>new GY({id:e.id,number:e.number,worker:e.worker,workerAccess:t.get(e.worker)??null,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,startedAt:_y(e.startedAt),outcome:Vi(e.outcome,{onNone:()=>null,onSome:u5}),endedAt:Vi(e.endedAt,{onNone:()=>null,onSome:_y}),salvage:w(e.salvage),start:w(e.start),reattachedAt:Vi(e.reattachedAt,{onNone:()=>null,onSome:_y}),outOfMemory:w(e.outOfMemory)});k(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*r_(t.attempts.filter(e=>C(e.outcome)&&S(e.endedAt)),t=>e.transcript(new TI({attemptId:t.id,before:b(),limit:1})).pipe(T_(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var m5=k(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*j(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),h5=(e,t,n)=>{let r=zj(e.run.state),i=w(e.step.result),a=i?.facts.find(e=>e._tag===`PullRequest`);return new DX({id:e.run.id,itemKey:e.itemKey,loop:e.run.loop,repository:e.repository,agent:e.agent.name,agentBrain:e.agent.brain,state:e.run.state._tag,loopPaused:t.has(e.run.loop),openedAt:_y(e.run.openedAt),closedAt:Vi(e.closedAt,{onNone:()=>null,onSome:_y}),task:e.task,attempts:e.attempts.map(e=>p5(e,n)),approval:Vi(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new EX({approvedAt:_y(e),source:w(t)})}),runAgain:w(e.runAgain),resultMessage:i?.message??null,pullRequestUrl:a?.url.toString()??null,...r,canResolveFailure:r.canResolveFailure&&!ia(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},g5=e=>GA(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new eX({failure:l5(e)}),Interrupted:e=>e,Steer:e=>e,Interrupt:e=>e,OperatorMessage:e=>e,Release:e=>e,Cancel:e=>e,InterventionApplied:e=>e,InterventionRejected:e=>e,WorkerUnresponsive:e=>e,WorkerResponsive:e=>e}),_5=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:_y(e.receivedAt),direction:e.direction,payload:g5(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new nX({...t,target:e.envelope.target,operator:e.envelope.operator}):new nX(t)},v5=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(_5),y5=k(`Operator.readTranscriptPage`)(function*(e,t,n){yield*O({attemptId:t,before:w(n)});let r=yield*e.transcript(new TI({attemptId:t,before:n,limit:501})),i=r.length>s5,a=i?r.slice(1):r,o=a[0];return yield*j(`Read operator transcript page`,{attemptId:t,before:w(n),returned:a.length,hasEarlier:i}),{events:v5(a),earlier:i&&o!==void 0?[new rX({attemptId:t,before:o.sequence})]:[]}});k(`Operator.readTranscript`)(function*(e,t,n){yield*O({runId:t.run.id,request:n._tag});let r=yield*GA(n,{ColdTranscriptRequest:()=>r_(t.attempts,t=>y5(e,t.id,b()),{concurrency:4}).pipe(T_(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>r_(t.attempts,t=>e.transcript(new wI({attemptId:t.id,after:n,limit:c5})),{concurrency:4}).pipe(T_(e=>({events:v5(e.flat()).slice(0,c5),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?y5(e,n,x(r)):new sX({runId:t.run.id,attemptId:n})});return yield*j(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var b5=500,x5=class extends V(`@usine/orchestrator/TaskItemView`)({...FX.fields,labels:P(hJ),conflicting:ME}){},S5=class extends V(`@usine/orchestrator/TaskLaneView`)({id:NX,name:SJ}){},C5=class extends V(`@usine/orchestrator/TaskCommentView`)({runId:Qj,kind:OM,url:M,postedAt:I(M),attemptEndedAt:I(M)}){},w5=class extends V(`@usine/orchestrator/TaskView`)({repository:sj,number:kP,title:M,current:OP,lane:S5,needsYou:ME,items:HE(x5),runs:P(DX),comments:P(C5)}){},T5=Vi({onNone:()=>null,onSome:_y}),E5=e=>{let t=(t,n)=>new C5({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:T5(t.at),attemptEndedAt:T5(n)}),n=Do(e.attempts,e=>aa(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(Qi(({endedAt:e})=>e)),r=Vi(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return Ho([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},D5=E(function*(){let e=yield*RH,t=yield*wU,n=yield*ZH,r=yield*mU,i=yield*EU;return{read:k(`TaskReader.read`)(function*(a,o,s){yield*O({repository:o,item:s});let c=a.config.repos.find(({name:e})=>fj(e)===fj(o));if(c===void 0)return yield*A(`Task read refused; the repository is not a registered Project`,{repository:o,item:s}),yield*new GX({repository:o});let[l,u,d,f]=yield*n_([n.list(c.name,{limit:b5}),r.get(c.name),t.states,i.asks()],{concurrency:`unbounded`}),p=yield*e.forItems(l.map(({itemKey:e})=>e)),m=yield*m5(e,p),h=new Set(d.filter(e=>e.paused).map(e=>e.loop)),g=f5(a.config.workers),_=(yield*o5(c,Vi(u,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),l,p.map(e=>h5(e,h,g)),f.map(({itemKey:e})=>e),new Map,new Map,m)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===s));if(_===void 0)return yield*A(`Task read found no Task; the Item is not among the Project's newest Board Items`,{repository:c.name,item:s,window:b5}),yield*new KX({repository:c.name,item:s});let{lane:v,task:ee}=_,te=new Set(ee.items.map(({itemKey:e})=>e)),ne=yield*r_(l.filter(({itemKey:e})=>te.has(e)),e=>$3(e).pipe(S_)),re=new Map;for(let e of ne){if(Xa(e)){yield*wv(`Task Item could not be projected; the other Items are shown`,{repository:c.name,itemKey:e.failure.itemKey,message:e.failure.message});continue}let{itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}=e.success;re.set(t,new x5({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}))}let[ie,...ae]=ee.items.flatMap(({itemKey:e})=>{let t=re.get(e);return t===void 0?[]:[t]});if(ie===void 0)return yield*new KX({repository:c.name,item:s});let oe=new Set(ee.runs.map(({id:e})=>e)),se=p.filter(({run:e})=>oe.has(e.id)).sort((e,t)=>hy(t.run.openedAt)-hy(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(E5),ce=new w5({repository:c.name,number:ie.number,title:ee.title,current:ee.itemKey,lane:new S5({id:v.id,name:v.name}),needsYou:ee.needsYou,items:[ie,...ae],runs:[...ee.runs].reverse(),comments:se});return yield*j(`Read a Task`,{repository:c.name,item:s,origin:ce.number,lane:v.name,items:ce.items.length,runs:ce.runs.length,comments:se.length}),ce})}});(class e extends sa()(`@usine/orchestrator/TaskReader`){static layer=ym(e,D5)});var O5=WE([`binary`,`version`,`login`]),k5=class extends rO(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:gM,capability:O5,message:z}){};F([class extends H(`HarnessReady`)(`HarnessReady`,{harness:gM}){},k5]),uE(k5),Fi(ji,({harness:e})=>e);var A5=class e extends sa()(`@usine/orchestrator/WorkerStatus`){static idle=_m(e)({slots:T([]),queue:T([]),preflights:T([]),machines:T([]),provisioning:T([])})},j5=class extends V(`@usine/orchestrator/LoopSelectorView`)({repos:I(P(sj)),tags:I(P(AJ))}){},M5=class extends V(`@usine/orchestrator/LoopFileView`)({name:gj,file:fM,stream:WE([`issue`,`pr`,`schedule`]),condition:cM,cron:I(fY),timeZone:I(pY),selector:I(j5),repositories:P(sj),approval:vj,maxCycles:AP,permissions:bj,priority:I(xY),step:MM,agent:yM,prompt:bY,paused:ME,undeclaredLabels:P(hJ)}){},N5=class extends V(`@usine/orchestrator/QuarantinedLoopView`)({name:z,file:fM,error:mM}){},P5=class extends V(`@usine/orchestrator/AgentFileView`)({name:yM,file:fM,harness:gM,model:hM,effort:_M,parentModel:I(hM),parentEffort:I(_M),resolvedParentModel:I(hM),resolvedParentEffort:_M,persona:bM,loops:P(gj)}){},F5=class extends V(`@usine/orchestrator/InvalidAgentView`)({name:z,file:fM,error:mM}){},I5=class extends V(`@usine/orchestrator/GatewayView`)({domain:UM,destination:zM,adminPort:WM,adminTokenEnv:z,llmProviders:P(GM)}){},L5=class extends V(`@usine/orchestrator/WorkerSlotsView`)({capacity:R,leased:R}){},R5=class extends H(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:M}){},z5=class extends H(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:M,message:M}){},B5=class extends H(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:M,message:M}){},V5=class extends H(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:M,capability:I(ZU),message:M}){},H5=F([R5,z5,B5,V5]),U5=class extends V(`@usine/orchestrator/HarnessPreflightView`)({harness:gM,check:H5}){},W5=class extends V(`@usine/orchestrator/ContainerView`)({image:I(qM),cpus:I(YM),memoryMib:I(XM),pids:I(ZM)}){},G5=class extends V(`@usine/orchestrator/WorkerConfigurationView`)({name:PM,kind:FM,maxConcurrentAttempts:R,destination:I(zM),port:I(BM),identityFile:I(VM),root:I(HM),gateway:I(I5),container:I(W5),containerLimits:I(QM).pipe(YE(T(null))),provisioner:I(XY).pipe(YE(T(null))),machines:P(KY).pipe(YE(T([]))),provisioning:I(qY).pipe(YE(T(null))),slots:I(L5),prerequisites:I(H5),harnesses:P(U5)}){},K5=class extends V(`@usine/orchestrator/RemovedWorkerView`)({name:PM,running:R}){},q5=class extends V(`@usine/orchestrator/LabelStateView`)({name:hJ,onGitHub:I(ME),color:I(M),description:I(M),declared:ME,failure:I(x$)}){},J5=class extends H(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:q5}){},Y5=class extends H(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:CJ}){},X5=F([J5,Y5]),Z5=class extends V(`@usine/orchestrator/LaneConfigurationView`)({name:SJ,sources:P(X5)}){},Q5=class extends V(`@usine/orchestrator/RepositoryConfigurationView`)({name:sj,tags:P(AJ),lanes:P(Z5),declaredLabels:P(q5),loops:P(gj)}){},$5=class extends V(`@usine/orchestrator/SettingsView`)({pollInterval:R,maxChildren:R,maxAttemptMinutes:I(R),maxAttemptTokens:I(R),parentModel:I(hM),parentEffort:I(_M),operator:I(TM),webhooks:WE([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:I(M),tracing:I(N({otlpUrl:M,serviceName:M}))}){},e7=class extends V(`@usine/orchestrator/ConfigurationView`)({loops:P(M5),quarantinedLoops:P(N5),agents:P(P5),invalidAgents:P(F5),workers:P(G5),removedWorkers:P(K5),repositories:P(Q5),settings:$5}){},t7=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},n7=e=>GA(e,{Passed:({checkedAt:e})=>new R5({checkedAt:_y(e)}),Degraded:({checkedAt:e,message:t})=>new z5({checkedAt:_y(e),message:t}),Deferred:({checkedAt:e,message:t})=>new B5({checkedAt:_y(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new V5({checkedAt:_y(e),capability:w(t),message:n})}),r7=e=>e.kind===`ssh`?{destination:w(e.destination),provisioner:$Y(e),port:w(e.port),identityFile:w(e.identityFile),root:e.root,gateway:Vi(e.gateway,{onNone:()=>null,onSome:e=>new I5({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new W5({image:w(e.container.image),cpus:w(e.container.cpus),memoryMib:w(e.container.memoryMib),pids:w(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},i7=E(function*(){let e=yield*wU,t=yield*mU,n=yield*F6,r=yield*A5,i=k(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Zi(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[gJ(e.name),e]))),a=new Map(e.config.labels.map(e=>[gJ(e.name),e])),o=e=>{let t=gJ(e),o=Qi(i,e=>Gi(e.get(t))),s=a.get(t);return new q5({name:e,onGitHub:Vi(i,{onNone:()=>null,onSome:()=>C(o)}),color:w(Ui(Qi(o,({color:e})=>e),()=>Qi(Gi(s),({color:e})=>e))),description:w(Ui(Qi(o,({description:e})=>e),()=>Qi(Gi(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&gJ(e.label)===t)??null})};return new Q5({name:n.name,tags:n.tags,lanes:n.lanes.map(e=>new Z5({name:e.name,sources:e.sources.map(e=>`label`in e?new J5({label:o(e.label)}):new Y5({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(e=>dY(e.selector,n)).map(({name:e})=>e)})});return{view:k(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*n_([e.states,n.latest,r.slots,r.preflights,r.machines,r.provisioning],{concurrency:`unbounded`}),f=new Set(o.filter(e=>e.paused).map(e=>e.loop)),p=Vi(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*r_(a.repos,e=>i(t,e,p),{concurrency:4}),h=e=>t.warnings.flatMap(t=>t._tag===`UndeclaredTriggerLabelWarning`&&t.loop===e?[t.label]:[]),g=t.loops.map(e=>new M5({name:e.name,file:fM.make(`loops/${e.name}.md`),stream:e.trigger.on,condition:e.trigger.if,cron:e.trigger.on===`schedule`?e.trigger.cron:null,timeZone:e.trigger.on===`schedule`?e.trigger.tz:null,selector:Vi(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new j5({repos:w(e),tags:w(t)})}),repositories:a.repos.filter(t=>dY(e.selector,t)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:w(e.priority),step:e.step,agent:e.agent,prompt:e.body,paused:f.has(e.name),undeclaredLabels:h(e.name)})),_=t.agents.map(e=>new P5({name:e.name,file:fM.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:w(e.parentModel),parentEffort:w(e.parentEffort),resolvedParentModel:w(SM(e.agent,a.settings.parentModel)),resolvedParentEffort:CM(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),v=new Map(c.map(e=>[e.worker,e])),ee=new Map(l.map(e=>[e.worker,e])),te=new Set(a.workers.map(({name:e})=>e)),ne=a.workers.map(e=>{let t=v.get(e.name),n=ee.get(e.name);return new G5({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...r7(e),slots:t===void 0?null:new L5({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:w(Zi(n.prerequisites,n7)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new U5({harness:e,check:n7(t)})),containerLimits:n===void 0?null:w(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(ZY),provisioning:w(Zi(Gi(d.find(t=>t.worker===e.name)),QY))})}),{settings:re,webhooks:ie,tracing:ae}=a,oe=new e7({loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new N5({name:t7(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new F5({name:t7(e),file:e,error:t})),workers:ne,removedWorkers:c.filter(({worker:e,leased:t})=>!te.has(e)&&t>0).map(({worker:e,leased:t})=>new K5({name:e,running:t})),repositories:m,settings:new $5({pollInterval:re.pollInterval,maxChildren:re.maxChildren,maxAttemptMinutes:w(re.maxAttemptMinutes),maxAttemptTokens:w(re.maxAttemptTokens),parentModel:w(re.parentModel),parentEffort:w(re.parentEffort),operator:w(a.operator),webhooks:ie.mode,webhooksPublicUrl:ie.mode===`endpoint`?ie.publicUrl.href:null,tracing:Vi(ae,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*j(`Read the configuration view`,{loops:g.length,quarantinedLoops:oe.quarantinedLoops.length,agents:_.length,invalidAgents:oe.invalidAgents.length,workers:ne.length,runningWorkers:c.length,repositories:m.length}),oe})}});(class e extends sa()(`@usine/orchestrator/OperatorConfiguration`){static layer=ym(e,i7)});var a7=class e extends sa()(`@usine/orchestrator/LoopMatches`){static layer=ym(e,E(function*(){let e=yield*dM;return{matching:k(`LoopMatches.matching`)(function*(e,t,n){yield*O({repository:t.name,items:n.length});let r=e.loops.filter(e=>e.trigger.on!==`schedule`&&dY(e.selector,t)),i=n.filter(({goneAt:e})=>S(e)),a=new Map,o=0;for(let e of r){let n=i.filter(({source:t})=>t===e.trigger.on);if(n.length===0)continue;let r=yield*S_(p6(e,t,n.map(({payload:e})=>e)));if(Xa(r)){o+=n.length,yield*j(`Loop trigger could not be checked; it matches no stored Item`,{repository:t.name,loop:e.name,items:n.length,errorTag:r.failure._tag,message:r.failure.message});continue}let s=new Set;for(let[i,a]of ko(n,r.success))Za(a)?a.success&&s.add(i):(o+=1,yield*j(`Loop trigger could not be evaluated on a stored Item`,{repository:t.name,loop:e.name,item:i.number,errorTag:a.failure._tag,message:a.failure.message}));a.set(e,s)}let s=[];for(let e of i)for(let t of r)a.get(t)?.has(e)===!0&&s.push({loop:t,item:e});return yield*j(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},Q_(dM,e))}}))},o7=200,s7=10,c7=100,l7=500,u7=class extends H(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:PM,lastAnsweredAt:M}){},d7=class extends H(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:yM,message:z,retries:RN,since:M}){},f7=F([u7,d7]),p7=class extends V(`@usine/orchestrator/RunningAttemptView`)({run:DX,attempt:GY,item:I(FX),lastActivityAt:I(M),warnings:P(f7)}){},m7=class extends H(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:DX}){},h7=class extends H(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:DX}){},g7=class extends H(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:DX}){},_7=class extends H(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},v7=class extends H(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:IP}){},y7=class extends H(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:DX}){},b7=class extends H(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:DX,ahead:I(R.check(fD(0))),creating:I(KY).pipe(YE(T(null)))}){},x7=class extends H(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:DX,stop:jX}){},S7=class extends H(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},C7=F([y7,m7,v7,g7,h7,_7,x7,b7,S7]),w7=class extends V(`@usine/orchestrator/StalledItemView`)({repository:sj,loop:gj,item:FX,reason:C7}){},T7=class extends V(`@usine/orchestrator/ClosedRunView`)({run:DX,item:I(FX),closedAt:M}){},E7=class extends V(`@usine/orchestrator/WorkerView`)({name:PM,slots:L5,preflight:I(H5),machines:P(KY).pipe(YE(T([]))),provisioning:I(qY).pipe(YE(T(null)))}){},D7=class extends V(`@usine/orchestrator/RepositoryPollView`)({repository:sj,polledAt:I(M)}){},O7=class extends V(`@usine/orchestrator/DeskView`)({running:P(p7),notMoving:P(w7),lastOutcomes:P(T7),workers:P(E7),polls:P(D7)}){},k7=({runs:e,sighting:t,paused:n,ask:r,ahead:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>Vj.some(t=>t===e));if(s!==void 0){let e=s.attempts.at(-1)?.outcome===null;if(C(o)&&s.state!==`Waiting`&&!e)return x(new x7({run:s,stop:o.value}));switch(s.state){case`Running`:return b();case`Waiting`:return x(new y7({run:s}));default:return x(new b7({run:s,ahead:i.get(s.id)??null,creating:a.get(s.id)??null}))}}if(n)return x(new _7);let c=t=>Gi(e.find(({id:e})=>e===t)),l=Qi(Qi(t,({suppressedBy:e})=>e),c);if(C(l))return x(new m7({run:l.value}));if(C(r))return x(new v7({ask:r.value}));let u=Qi(Qi(t,({run:e})=>e),c);return C(u)?x(u.value.state===`Failed`?new g7({run:u.value}):new h7({run:u.value})):x(new S7)},A7=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],j7=Pi([Fi(Mi,({reason:e})=>A7.indexOf(e._tag)),Fi(ji,({repository:e})=>e),Fi(Ni(Mi),({item:e})=>e.number),Fi(ji,({loop:e})=>e)]),M7=({direction:e,envelope:t})=>{let n=t.payload;return e===`outbound`&&n._tag!==`WorkerUnresponsive`&&n._tag!==`WorkerResponsive`&&(n._tag!==`SessionEvent`||n.event._tag!==`PoolRateLimitsUpdated`&&n.event._tag!==`ProviderRetrying`)},N7=e=>{let t=null,n=new Map,r=null;for(let i of e){M7(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new u7({worker:e.worker,lastAnsweredAt:_y(e.lastAnsweredAt)});else if(e._tag===`WorkerResponsive`)t=null;else if(e._tag===`SessionEvent`){let t=e.event;t._tag===`ProviderRetrying`?n.set(t.session.id,new d7({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??_y(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:_y(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},P7=e=>hy(e.checkedAt),F7=e=>{let t=[...ta(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return Gi((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||P7(t)>P7(e)?t:e,void 0))},I7=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},L7=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,R7=E(function*(){let e=yield*RH,t=yield*wU,n=yield*EU,r=yield*ZH,i=yield*F6,a=yield*a7,o=yield*A5,s=yield*VU,c=k(`Operator.desk.recentActivity`)(function*(t){return yield*O({attemptId:t.id}),N7(yield*e.transcript(new TI({attemptId:t.id,before:b(),limit:o7})))});return{desk:k(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,v,ee,te]=yield*n_([e.list({closedLimit:0}),e.closed({limit:c7}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),ne=ee.map(ZY),re=new Map(ne.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),ie=new Map(h.map(({runId:e,ahead:t})=>[e,t])),ae=new Set(f.filter(e=>e.paused).map(e=>e.loop)),oe=f5(l.config.workers),se=yield*r_(l.config.repos,e=>E(function*(){let t=yield*r.list(e.name,{limit:l7});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),ce=new Map;for(let{items:e}of se)for(let t of e){let e=yield*S_($3(t));if(Xa(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;ce.set(n,new FX({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let le=se.flatMap(({matches:e})=>e),ue=[...new Set(le.map(({item:e})=>e.itemKey))],[de,fe]=yield*n_([e.forItems(ue),e.sightings(ue)],{concurrency:`unbounded`}),pe=new Map([...u,...de].map(e=>[e.run.id,h5(e,ae,oe)])),me=[...pe.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),he=(e,t)=>Qi(Gi(v.find(n=>n.loop===e&&n.itemKey===t)),e=>Zi(Gi(pe.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new jX({runId:e.runId,attemptNumber:t,worker:e.worker}))),ge=[];for(let{loop:e,item:t}of le){let n=ce.get(t.itemKey);if(n===void 0)continue;let r=k7({runs:me.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:Gi(fe.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:ae.has(e.name),ask:Gi(p.find(({itemKey:e})=>e===t.itemKey)),ahead:ie,creating:re,stop:he(e.name,t.itemKey)});S(r)||(yield*j(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...GA(r.value,{AwaitingApproval:({run:e})=>({runId:e.id}),SuppressedForOperator:({run:e})=>({runId:e.id}),CycleBudgetUsedUp:({ask:e})=>({askId:e.id}),RunFailed:({run:e})=>({runId:e.id}),ClosedUnchanged:({run:e})=>({runId:e.id,state:e.state}),LoopPaused:()=>({}),WaitingForStop:({run:e,stop:t})=>({runId:e.id,unstoppedRunId:t.runId,attemptNumber:t.attemptNumber,worker:t.worker}),QueuedForWorker:({run:e,ahead:t})=>({runId:e.id,ahead:t}),AwaitingPoll:()=>({})})}),ge.push(new w7({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let _e=yield*r_(me.flatMap(e=>{let t=e.attempts.at(-1);return e.state===`Running`&&t!==void 0&&t.outcome===null?[{run:e,attempt:t}]:[]}),({run:e,attempt:t})=>T_(c(t),n=>new p7({run:e,attempt:t,item:ce.get(e.itemKey)??null,...n})),{concurrency:4}),ve=d.filter(e=>!L7(e)).map(e=>{let t=h5(e,ae,oe);return new T7({run:t,item:ce.get(t.itemKey)??null,closedAt:I7(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,s7),ye=new Map(m.map(e=>[e.worker,e])),be=new Map(g.map(e=>[e.worker,e])),xe=new Set(l.config.workers.map(({name:e})=>e)),Se=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!xe.has(e))].map(e=>{let t=ye.get(e),n=be.get(e);return new E7({name:e,slots:new L5({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:w(Zi(Qi(Gi(n),F7),n7)),machines:ne.filter(t=>t.worker===e),provisioning:w(Zi(Gi(te.find(t=>t.worker===e)),QY))})}),Ce=Vi(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),we=l.config.repos.map(({name:e})=>{let t=Ce.find(({repository:t})=>fj(t)===fj(e));return new D7({repository:e,polledAt:t===void 0?null:_y(t.completedAt)})});return yield*j(`Built the operator desk`,{running:_e.length,matches:le.length,notMoving:ge.length,lastOutcomes:ve.length,workers:Se.length}),new O7({running:_e,notMoving:[...ge].sort(j7),lastOutcomes:ve,workers:Se,polls:we})})}});(class e extends sa()(`@usine/orchestrator/OperatorDesk`){static layer=ym(e,R7).pipe(Em(a7.layer))});var z7=R.check(fD(0)),B7=R.check(fD(1)),V7=R.check(fD(0)),H7=aD.check(pD({minimum:0,maximum:1})),U7=M.check(iD(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),W7=WE([`7d`,`30d`,`all`]),G7=WE([`day`,`week`]),K7=class extends V(`@usine/orchestrator/TaskDoneView`)({repository:sj,number:kP,mergedAt:M,durationMillis:V7}){},q7=class extends V(`@usine/orchestrator/TaskPeriodView`)({start:U7,tasks:z7,medianMillis:I(V7),firstTimeRight:z7,operatorActions:z7}){},J7=class extends V(`@usine/orchestrator/LoopShareView`)({loop:gj,share:H7}){},Y7=class extends V(`@usine/orchestrator/LoopRunTimeView`)({loop:gj,runs:B7,medianMillis:V7}){},X7=class extends V(`@usine/orchestrator/TaskTimeView`)({tasks:B7,loops:P(J7),waiting:H7,runs:P(Y7)}){},Z7=class extends V(`@usine/orchestrator/TaskCostView`)({tasks:B7,medianUsd:ON,estimate:ME}){},Q7=class extends V(`@usine/orchestrator/TaskTokensView`)({tasks:B7,medianTokens:mN,loops:P(J7),cost:I(Z7)}){},$7=class extends V(`@usine/orchestrator/UntimedTasksView`)({tasks:B7,before:U7}){},e9=class extends V(`@usine/orchestrator/StatisticsView`)({window:W7,from:M,to:M,bucket:G7,loops:P(gj),tasks:P(K7),medianMillis:I(V7),periods:P(q7),firstTimeRight:z7,operatorActions:z7,time:I(X7),tokens:I(Q7),untimed:I($7),unmetered:z7}){},t9=class extends V(`@usine/orchestrator/DurationSummaryView`)({count:B7,medianMillis:V7}){},n9=class extends V(`@usine/orchestrator/OutcomeCountsView`)({succeeded:z7,failed:z7,canceled:z7}){},r9=class extends V(`@usine/orchestrator/PoolTokensView`)({pool:MN,tokens:mN}){},i9=class extends V(`@usine/orchestrator/CostSummaryView`)({usd:ON,meanUsd:ON,estimate:ME,priced:B7}){},a9=class extends V(`@usine/orchestrator/UsageSummaryView`)({measured:z7,tokens:mN,meanTokens:I(mN),pools:P(r9),cost:I(i9)}){},o9={outcomes:n9,time:I(t9),usage:a9},s9=class extends V(`@usine/orchestrator/LoopStatisticsView`)({loop:gj,...o9}){},c9=class extends V(`@usine/orchestrator/AgentStatisticsView`)({agent:yM,...o9}){},l9=class extends V(`@usine/orchestrator/BrainStatisticsView`)({brain:vM,...o9}){},u9=class extends V(`@usine/orchestrator/ThroughputPeriodView`)({start:U7,...n9.fields}){},d9=class extends V(`@usine/orchestrator/WorkerQueueWaitView`)({worker:PM,wait:t9}){},f9=class extends V(`@usine/orchestrator/AttemptCountView`)({attempts:B7,runs:z7}){},p9=class extends V(`@usine/orchestrator/WorkerUtilizationView`)({worker:PM,slots:B7,occupiedMillis:V7,share:H7}){},m9=class extends V(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:U7,approvals:z7,failures:z7}){},h9=class extends V(`@usine/orchestrator/NeedsAttentionView`)({approvals:z7,failures:z7,periods:P(m9),approvalWait:I(t9),retryWait:I(t9),resolutionWait:I(t9),failureWait:I(t9)}){},g9=class extends V(`@usine/orchestrator/RunStatisticsView`)({window:W7,from:M,to:M,bucket:G7,runs:n9,runTime:I(t9),attemptTime:I(t9),unmeasuredAttempts:z7,throughput:P(u9),loops:P(s9),agents:P(c9),brains:P(l9),queueWait:P(d9),attemptsPerRun:P(f9),utilization:P(p9),needsAttention:h9}){},_9={SchemaError:400,InvalidRequestError:400,CrossSiteRequestError:403,RunNotFoundError:404,TranscriptAttemptNotFoundError:404,BoardProjectNotFoundError:404,BoardItemNotFoundError:404,BoardLaneNotFoundError:404,GitHubItemNotFoundError:404,RunOperationRejectedError:409,RunRetryBlockedError:409,RunInterventionRejectedError:409,LeftoversDiscardRejectedError:409,RosterAgentNotFoundError:404,LoopNotFoundError:404,CycleBudgetResetRejectedError:409,BoardLaneReadOnlyError:409,RestartRequiredError:409,ReloadPreflightError:409,FactoryConfigError:422,EnginePersistenceError:500,AttemptCancellationError:500,HttpBodyError:500,GitHubApiError:502,InvalidGitHubResponseError:502,BackendUnavailableError:503,InstallationDiscoveryError:503,AppPermissionError:503,GitHubRateLimitError:503},v9=class extends nO(`@usine/orchestrator/OperatorHttpError`)({error:WE(lo(_9)),message:M}){get status(){return _9[this.error]}},y9=[...new Set(Object.values(_9))].map(e=>v9.check(rD(t=>t.status===e)).annotate({httpApiStatus:e})),b9=class extends wq()(`@usine/orchestrator/OperatorHttpPolicy`,{error:y9}){},x9=F([eD(`WorkerCapabilityError`,{worker:PM,capability:ZU,message:M}),eD(`ExecutorOperationError`,{operation:XU,message:M}),eD(`CredentialUnavailableError`,{repository:sj,message:M})]),S9=class extends nO(`@usine/orchestrator/RestartRequiredRefusal`)({error:EE(`RestartRequiredError`),message:M,blocks:HE(TY),fields:HE(z)},{httpApiStatus:409}){},C9=class extends nO(`@usine/orchestrator/ReloadPreflightRefusal`)({error:EE(`ReloadPreflightError`),message:M,agents:P(yM),workers:P(PM),cause:x9},{httpApiStatus:409}){},w9=class extends nO(`@usine/orchestrator/FactoryConfigRefusal`)({error:EE(`FactoryConfigError`),message:M,file:fM,stage:pM},{httpApiStatus:422}){},T9=SE(DE),E9=F([M,HE(M).pipe(KE(M,Yx({decode:e=>e[0],encode:e=>[e]})))]),D9=E9.pipe(KE(jD),KE(mI)),O9=F([N({after:T9,before:T9,attempt:T9}).pipe(KE(wE(iX),Yx({decode:()=>new iX,encode:()=>({})}))),N({after:D9,before:T9,attempt:T9}).pipe(KE(wE(aX),Yx({decode:({after:e})=>new aX({after:e}),encode:({after:e})=>({after:e})}))),N({after:T9,before:D9,attempt:E9.pipe(KE(lP))}).pipe(KE(wE(oX),Yx({decode:({before:e,attempt:t})=>new oX({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),k9=M.check(iD(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),A9=N({ok:EE(!0)}),j9={runId:Qj},M9={loop:gj},N9=N({window:E9.pipe(KE(W7),ZE(T(`30d`)))}),P9=dq(`OperatorApi`).add(fJ(`operator`).add(aq(`overview`,`/api/overview`,{success:p8}),aq(`agents`,`/api/agents`,{success:P(yM)}),oq(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:j9,payload:wX,success:A9}),oq(`runAgain`,`/api/runs/:runId/run-again`,{params:j9,payload:wX,success:NI}),oq(`intervene`,`/api/runs/:runId/intervene`,{params:j9,payload:TX,success:A9}),oq(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:N({askId:FP}),success:A9}),aq(`detail`,`/api/runs/:runId`,{params:j9,query:O9,success:MX}),aq(`githubChanges`,`/api/runs/:runId/github-changes`,{params:j9,success:I8}),oq(`approve`,`/api/runs/:runId/approve`,{params:j9,success:A9}),oq(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:j9,payload:N({attemptId:lP}),success:A9}),oq(`retry`,`/api/runs/:runId/retry`,{params:j9,success:A9}),oq(`cancel`,`/api/runs/:runId/cancel`,{params:j9,success:A9}),oq(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:k9,repository:k9,item:jD.pipe(KE(kP))},payload:N({toLane:NX}),success:A9}),oq(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:PM},success:A9}),oq(`pause`,`/api/loops/:loop/pause`,{params:M9,success:A9}),oq(`unpause`,`/api/loops/:loop/unpause`,{params:M9,success:A9}),oq(`reload`,`/api/instance/reload`,{success:DY,error:[S9,C9,w9]})).add(aq(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:k9,repository:k9,item:jD.pipe(KE(kP))},success:w5})).add(aq(`configuration`,`/api/configuration`,{success:e7})).add(aq(`desk`,`/api/desk`,{success:O7})).add(aq(`statistics`,`/api/statistics`,{query:N9,success:e9}),aq(`runStatistics`,`/api/statistics/runs`,{query:N9,success:g9})).annotate(vq,{onExcessProperty:`error`}).middleware(b9)),F9=()=>Aq(P9,{baseUrl:globalThis.location.origin}),I9=e=>yv(D(F9(),t=>e(t.operator)).pipe(Q_(IG,!1),J_(YX))),L9=e=>e instanceof Error?e.message:String(e),R9=e=>`${e.harness} · ${e.model} · ${e.effort}`,z9=e=>{switch(e){case`issue`:return`Issue`;case`pr`:return`PR`;case`schedule`:return`Schedule`;default:return e}},B9=(e,t=Date.now())=>{let n=Math.max(0,t-Date.parse(e));return n<6e4?`now`:n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:`${Math.floor(n/864e5)}d`},V9=(e,t)=>{let n=B9(e,t);return n===`now`?`just now`:`${n} ago`},H9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`},U9=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],W9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getDate()} ${U9[t.getMonth()]} ${n(t.getHours())}:${n(t.getMinutes())}`},G9=e=>`${e.getDate()} ${U9[e.getMonth()]}`,K9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},q9=e=>{let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.round(t/60);return n<60?`${n} min`:n%60==0?`${Math.floor(n/60)} h`:`${Math.floor(n/60)} h ${n%60} min`},J9=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}).format(e),Y9=e=>e>0&&e<.005?`under $0.01`:`$${e.toFixed(2)}`,X9=e=>({claude:`Claude Code`,codex:`Codex`,pi:`Pi`})[e],Z9=e=>({apiKeys:`API keys`,claudePlan:`Claude plan`,chatgptPlan:`ChatGPT plan`})[e],Q9=e=>e%1440==0?`${e/1440}-day`:e%60==0?`${e/60}-hour`:`${e}-minute`,$9=({title:e,leading:t,counts:n,children:i,actions:o,className:s})=>(0,a.jsxs)(`header`,{className:r(`flex flex-wrap items-baseline gap-x-3 gap-y-1`,s),children:[(0,a.jsxs)(`h1`,{className:`flex items-baseline gap-2 text-xl font-semibold wrap-anywhere`,children:[t!==void 0&&(0,a.jsx)(`span`,{className:`flex h-7 shrink-0 items-center self-start`,children:t}),(0,a.jsx)(`span`,{className:`min-w-0`,children:e})]}),n!==void 0&&(0,a.jsx)(`p`,{className:`text-sm text-muted-foreground tabular-nums`,children:n}),i,o!==void 0&&(0,a.jsx)(`div`,{className:`ml-auto flex items-center gap-2 self-center`,children:o})]}),tee=({children:e,width:t=`prose`})=>(0,a.jsx)(`main`,{className:`px-4 pt-5 pb-6 md:px-5`,children:(0,a.jsx)(`div`,{className:r(`flex flex-col gap-4`,t===`prose`&&`max-w-3xl`),children:e})}),nee={lg:`lg:flex-row lg:items-start lg:justify-between lg:gap-6`,sm:`sm:flex-row sm:items-start sm:justify-between sm:gap-6`,never:``},ree=({eyebrow:e,heading:t,facts:n,actions:i,actionsBeside:o,className:s})=>(0,a.jsxs)(`header`,{className:r(`flex flex-col gap-3`,nee[o],s),children:[(0,a.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[e!==void 0&&(0,a.jsx)(`p`,{className:`flex flex-wrap items-center gap-x-3.5 gap-y-1 text-xs text-muted-foreground`,children:e}),t,n!==void 0&&(0,a.jsx)(`div`,{className:`flex flex-wrap items-center gap-x-5 gap-y-1.5 pt-0.5 text-sm text-muted-foreground`,children:n})]}),i!==void 0&&(0,a.jsx)(`div`,{className:`shrink-0`,children:i})]}),iee=({icon:e,title:t,children:n})=>(0,a.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,title:t,children:[(0,a.jsx)(e,{"aria-hidden":`true`,className:`size-[1em] shrink-0 text-faint`}),n]});export{R as $,Fe as $t,TX as A,g_ as At,XP as B,w as Bt,C9 as C,_y as Ct,r6 as D,k_ as Dt,d8 as E,E_ as Et,mI as F,aa as Ft,Qj as G,Vi as Gt,dP as H,S as Ht,eF as I,na as It,dj as J,x as Jt,Vj as K,b as Kt,qP as L,Qi as Lt,oX as M,Bo as Mt,aX as N,bo as Nt,wX as O,Cv as Ot,EJ as P,ea as Pt,jD as Q,ze as Qt,YP as R,Gi as Rt,v9 as S,lE as St,f8 as T,hy as Tt,$M as U,C as Ut,kP as V,Ji as Vt,yM as W,Zi as Wt,P as X,it as Xt,GA as Y,ta as Yt,ME as Z,rt as Zt,Y9 as _,_e as _n,fD as _t,V9 as a,xe as an,RE as at,L9 as b,s as bn,CE as bt,G9 as c,te as cn,F as ct,B9 as d,v as dn,pE as dt,je as en,oO as et,X9 as f,p as fn,yE as ft,z9 as g,oe as gn,oD as gt,J9 as h,_ as hn,pD as ht,$9 as i,Se as in,jE as it,iX as j,pv as jt,MX as k,bv as kt,W9 as l,fe as ln,mE as lt,H9 as m,ae as mn,uE as mt,iee as n,Ee as nn,WE as nt,R9 as o,m as on,M as ot,Z9 as p,re as pn,kD as pt,sj as q,Ui as qt,ree as r,Te as rn,I as rt,K9 as s,ne as sn,N as st,tee as t,Ae as tn,EE as tt,q9 as u,ee as un,KE as ut,Q9 as v,he as vn,vD as vt,S9 as w,my as wt,w9 as x,SE as xt,I9 as y,c as yn,hD as yt,$P as z,Hi as zt};
|