@tomato414941/foundation 12.1.0 → 12.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.mjs +3 -3
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -125,10 +125,10 @@ ${c}`:c:"",l=Function,d=`return (input) => {
125
125
  ${c}
126
126
  }`,f;try{f=new l(...s,d)(...a)}catch(p){throw new Ke(`this schema (generated code failed to evaluate: ${p.message})`)}return e?.debug&&(f.code=u),f.definite=o.definite,f}function ye(t,e){for(let[o,n]of t.constants)if(n===e)return o;let r=`c${t.constantCounter++}`;return t.constants.set(r,e),r}function Ll(t,e){return t.definite=!1,ye(t,e)}function pe(t){return`v${t.varCounter++}`}function tTe(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return Fn;let o=r;return o.issues.length===0?o.value:Fn}function _n(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return rr(t,e,r,o,n)}catch(u){if(!(u instanceof Ke)||!u.islandable)throw u;if(t.content.length=i,e.constants.size>s){let l=Array.from(e.constants.keys()).slice(s);for(let d of l)e.constants.delete(d)}return e.constantCounter=a,e.varCounter=c,rTe(t,e,r,o)}}function rTe(t,e,r,o){e.definite=!1;let n=ye(e,r),i=ye(e,tTe),s=pe(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var nTe=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function oTe(t,e,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let s of n){let a=s._zod.def;if(a.when&&!nTe.has(a.check))throw new Ke('check with a custom "when" condition');switch(a.check){case"greater_than":iTe(t,e,a,i);break;case"less_than":sTe(t,e,a,i);break;case"multiple_of":aTe(t,e,a,i);break;case"number_format":Z9(t,a,i);break;case"min_length":{let c=Ml(a.minimum,"min_length"),u=Lz(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Ml(a.maximum,"max_length"),u=Lz(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Ml(a.length,"length_equals"),u=Lz(t,e,i,`${i}.length >= ${c} && ${i}.length <= ${a.length*2}`);t.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":t.write(`if (${i}.size < ${Ml(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${Ml(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${Ml(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=W9(t,e,a,i);break;case"custom":i=fTe(t,e,s,i);break;case"bigint_format":cTe(t,a,i);break;case"mime_type":uTe(t,e,a,i);break;case"property":dTe(t,e,a,i);break;case"properties":lTe(t,e,a,i);break;case"overwrite":{let c=pe(e);pTe(t,e,s,i,c),i=c;break}default:throw new Ke(`check type ${a.check}`)}}return i}function Lz(t,e,r,o){let n=ye(e,Cl),i=pe(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function Ml(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Ke(`${e} bound of type ${typeof t}`);return`${t}`}function K9(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Ke("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Ke("comparison check with Invalid Date bound");return ye(t,e)}throw new Ke(`comparison check bound of type ${typeof e}`)}function iTe(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${K9(e,r.value)}) return INVALID;`)}function sTe(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${K9(e,r.value)}) return INVALID;`)}function aTe(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Ke("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ye(e,ng);t.write(`if (${n}(${o}, ${Ml(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Z9(t,e,r){let o=e.format;switch(o){case"safeint":t.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":t.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":t.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":t.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":t.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Ke(`number format ${o}`)}}function cTe(t,e,r){let o=e.format;if(o)switch(o){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Ke(`bigint format ${o}`)}}function uTe(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=ye(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function lTe(t,e,r,o){if(r.when)throw new Ke('check with a custom "when" condition');t.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?ye(e,i):Ln(i),a=pe(e);t.write(`const ${a} = ${o}[${s}];`),_n(t,e,n[i],a,!1)}}function dTe(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;rr(t,e,r.schema,n)}function pTe(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Ke("overwrite check without a transform function");if(jl(i))throw new Oi("z.compile: async overwrite transforms are not supported");let s=ye(e,i);t.write(`const ${n} = ${s}(${o});`)}function jz(){throw new so}function Vz(t){this.issues.push(t)}function fTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(jl(n.fn))throw new Oi("z.compile: async .refine() predicates are not supported");let i=Ll(e,n.fn),s=ye(e,jz),a=pe(e);return t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`),o}if(r._zod.check){if(jl(r._zod.check))throw new Oi("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=Ll(e,u=>{let l={value:u,issues:[],addIssue:Vz};return i(l)instanceof Promise&&jz(),l.issues.length===0?l.value:Fn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Ke("custom check without a predicate or check function")}var mTe=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function W9(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ye(e,wg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ye(e,KS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ye(e,ex),l=ye(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ye(e,vg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ye(e,VS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ye(e,JS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ye(e,YS);return t.write(`if (!${u}(${o})) return INVALID;`),o}let s=r;if(i==="url"||i==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=ye(e,AS),l=ye(e,r),d=pe(e),f=pe(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${f} = ${u}(${d}, ${l});`),t.write(`if (typeof ${f} === "number") return INVALID;`),s.hostname!==void 0){let y=ye(e,PS);t.write(`if (!${y}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let y=ye(e,kS);t.write(`if (!${y}(${f}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=pe(e),m=s.normalize?`${f}.href`:`${ye(e,yg)}(${d})`;return t.write(`const ${p} = ${m};`),p}let a=r.fn;if(a){if(jl(a))throw new Ke(`async string format ${i}`);let u=ye(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(mTe.has(i)&&r.pattern){let u=ye(e,r.pattern);return t.write(`${u}.lastIndex = 0;`),t.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new Ke("regex format without a pattern");case"lowercase":t.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":t.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":t.write(`if (!${o}.includes(${Ln(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${Ln(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${Ln(u)}) return INVALID;`);break}default:throw new Ke(`string format ${c}`)}return o}function rr(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Ke(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=hTe(t,e,r,o,a);break;case"number":c=gTe(t,r,o);break;case"boolean":c=yTe(t,o);break;case"bigint":c=vTe(t,r,o);break;case"symbol":c=wTe(t,o);break;case"undefined":c=_Te(t,o);break;case"null":c=bTe(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=STe(t,o);break;case"nan":c=xTe(t,o);break;case"date":c=ETe(t,o);break;case"object":c=$Te(t,e,r,o,a);break;case"optional":c=RTe(t,e,r,o,a);break;case"nullable":c=PTe(t,e,r,o,a);break;case"array":c=kTe(t,e,r,o,a);break;case"literal":c=TTe(t,e,r,o);break;case"enum":c=CTe(t,e,r,o);break;case"readonly":{let u=G9(t,e,r,o),l=pe(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":G9(t,e,r,o),c="true";break;case"default":case"prefault":c=OTe(t,e,r,o);break;case"nonoptional":c=DTe(t,e,r,o);break;case"tuple":c=NTe(t,e,r,o);break;case"union":c=zTe(t,e,r,o);break;case"intersection":c=LTe(t,e,r,o);break;case"record":c=jTe(t,e,r,o);break;case"map":c=qTe(t,e,r,o);break;case"set":c=VTe(t,e,r,o);break;case"file":c=GTe(t,o);break;case"template_literal":c=HTe(t,e,r,o);break;case"lazy":c=BTe(t,e,r,o);break;case"pipe":c=KTe(t,e,r,o);break;case"custom":c=ZTe(t,e,r,o);break;case"transform":c=XTe(t,e,r,o);break;case"catch":c=JTe(t,e,r,o);break;default:throw new Ke(`schema type ${s}`)}return c===null?null:oTe(t,e,r,c)}function hTe(t,e,r,o,n=!0){t.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:W9(t,e,i,o,n)}function gTe(t,e,r){t.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=e._zod.def;return o.check==="number_format"&&o.format&&Z9(t,{format:o.format},r),r}function yTe(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function vTe(t,e,r){t.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=e._zod.def;if(o.format)switch(o.format){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function wTe(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function _Te(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function bTe(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function STe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function xTe(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function ETe(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function $Te(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let s=i.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=S=>typeof S=="symbol"?ye(e,S):Ln(S),d=S=>typeof S=="symbol"?`[${l(S)}]`:Ln(S),f=s;if(a.includes("__proto__"))throw new Ke('object shape key "__proto__"');let p=new Map;for(let S of u){let x=f[S],R=l(S),T=pe(e);if(t.write(`const ${T} = ${o}[${R}];`),x._zod.optin!==void 0){let M=pe(e);t.write(`let ${M} = (() => {`),t.indented(K=>{let te=_n(K,e,x,T);K.write(`return ${te};`)}),t.write("})();"),x._zod.optout==="optional"?(t.write(`if (${M} === INVALID) {`),t.indented(K=>{K.write(`if (${R} in ${o}) return INVALID;`),K.write(`${M} = undefined;`)}),t.write("}")):t.write(`if (${M} === INVALID) return INVALID;`),p.set(S,M)}else{ATe(x)&&t.write(`if (!(${R} in ${o})) return INVALID;`);let M=_n(t,e,x,T,n);M!==null&&p.set(S,M)}}let m=i.catchall,y="none";if(m){let S=m._zod.def.type;if(S==="never"){let x=a.map(R=>`k !== ${Ln(R)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(R=>{R.write(`if (${x}) return INVALID;`)}),t.write("}")}else(S==="unknown"||S==="any")&&!m._zod.def.checks?.length?y="passthrough":y="schema"}let w=pe(e),b=u.some(S=>V9(f[S])||Fz(f[S]));if(!n){if(y==="schema"){let S=a.length>0?ye(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`);let R=pe(e);x.write(`const ${R} = ${o}[k];`),_n(x,e,m,R,!1)}),t.write("}")}return null}if(b){t.write(`const ${w} = {};`);for(let S of u){let x=l(S),R=p.get(S);Fz(f[S])?t.write(`if (${x} in ${o}) ${w}[${x}] = ${R};`):V9(f[S])?t.write(`if (${R} !== undefined || ${x} in ${o}) ${w}[${x}] = ${R};`):t.write(`${w}[${x}] = ${R};`)}}else{let S=u.map(x=>`${d(x)}: ${p.get(x)}`).join(", ");t.write(`const ${w} = { ${S} };`)}if(y!=="none"){let S=a.length>0?ye(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{if(x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`),y==="passthrough")x.write(`${w}[k] = ${o}[k];`);else{let R=pe(e);x.write(`const ${R} = ${o}[k];`);let T=_n(x,e,m,R);x.write(`${w}[k] = ${T};`)}}),t.write("}")}return w}function RTe(t,e,r,o,n=!0){let i=r._zod.def;if(ITe(r))return rr(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=pe(e),c=pe(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=rr(l,e,i.innerType,o);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),t.write("} else {"),t.indented(u=>{let l=rr(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?pe(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=rr(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function ITe(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function ATe(t){return t._zod.optin===void 0&&Ul(t)}function Ul(t){if(t._zod.def.coerce)return!0;let e=t._zod.def;switch(e.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return e.innerType?Ul(e.innerType):!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return e.innerType?Ul(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(Ul):!0;case"intersection":return!e.left||!e.right?!0:Ul(e.left)&&Ul(e.right);case"pipe":return e.in?Ul(e.in):!0;default:return!0}}function Fz(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function V9(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&Lp(t)}function Lp(t){let e=t._zod.def;switch(e.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return e.innerType?Lp(e.innerType):!0;case"union":return e.options?e.options.some(Lp):!0;case"intersection":return!e.left||!e.right||Lp(e.left)||Lp(e.right);case"pipe":return e.out?Lp(e.out):!0;default:return!0}}function PTe(t,e,r,o,n=!0){let i=r._zod.def,s=n?pe(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=rr(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function kTe(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?pe(e):null,a=pe(e),c=pe(e);return s&&t.write(`const ${s} = new Array(${o}.length);`),t.write(`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`),t.indented(u=>{u.write(`const ${c} = ${o}[${a}];`);let l=_n(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function TTe(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=ye(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=ye(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${Ln(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")t.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)t.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)t.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")t.write(`if (${o} !== ${s}n) return INVALID;`);else throw new Ke(`literal type ${typeof s}`);return o}function CTe(t,e,r,o){let n=r._zod.values;if(!n)throw new Ke("enum schema without enumerated values");let i=ye(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function G9(t,e,r,o){let n=r._zod.def;return rr(t,e,n.innerType,o)}function OTe(t,e,r,o){let n=r._zod.def,s=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!s)return rr(t,e,n.innerType,o);let c=ye(e,s),u=pe(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),rr(t,e,n.innerType,u)}let a=pe(e);if(s){let c=ye(e,s),u=ye(e,_p);t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),t.write("} else {"),t.indented(l=>{let d=rr(l,e,n.innerType,o);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),t.write("}")}else t.write(`let ${a};`),t.write(`if (${o} !== undefined) {`),t.indented(c=>{let u=rr(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function DTe(t,e,r,o){let n=r._zod.def,i=rr(t,e,n.innerType,o),s=pe(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function NTe(t,e,r,o){let n=r._zod.def,i=n.items,s=n.rest;t.write(`if (!Array.isArray(${o})) return INVALID;`);let a=H9(i,"optin"),c=H9(i,"optout");s?t.write(`if (${o}.length < ${a}) return INVALID;`):t.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=pe(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(f=>{f.write(`if (${l} < ${o}.length) {`),f.indented(p=>{let m=pe(e);p.write(`const ${m} = ${o}[${l}];`);let y=_n(p,e,d,m);p.write(`${u}[${l}] = ${y};`)}),f.write("} else {"),f.indented(p=>{if(Fz(d)){p.write(`${u}.length = ${l};`);return}let m=pe(e),y=pe(e);p.write(`const ${m} = undefined;`),p.write(`const ${y} = (() => {`),p.indented(w=>{let b=_n(w,e,d,m);w.write(`return ${b};`)}),p.write("})();"),p.write(`if (${y} === INVALID || ${y} === undefined) ${u}.length = ${l};`),p.write(`else ${u}[${l}] = ${y};`)}),f.write("}")}),t.write("}");else{let f=pe(e);t.write(`const ${f} = ${o}[${l}];`);let p=_n(t,e,d,f);t.write(`${u}[${l}] = ${p};`)}}if(s){let l=pe(e),d=pe(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(f=>{f.write(`const ${d} = ${o}[${l}];`);let p=_n(f,e,s,d);f.write(`${u}[${l}] = ${p};`)}),t.write("}")}return u}function H9(t,e){for(let r=t.length-1;r>=0;r--)if(!(e==="optin"?t[r]._zod.optin!==void 0:t[r]._zod.optout==="optional"))return r+1;return 0}function zTe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return MTe(t,e,n,o);if(n.inclusive===!1)throw new Ke("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return rr(t,e,i[0],o);if(i.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(i.flatMap(l=>l._zod.def.values)),u=ye(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=pe(e);t.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?t.write(`${a} = (() => {`):t.write(`if (${a} === INVALID) ${a} = (() => {`),t.indented(l=>{let d=rr(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function MTe(t,e,r,o){if(r.unionFallback)throw new Ke("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=pe(e),i=pe(e);t.write(`const ${n} = ${o}?.[${Ln(r.discriminator)}];`),t.write(`let ${i};`);let s=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Ke("discriminated union option without static discriminator values");for(let f of u){if(a.has(f))throw new Ke(`duplicate discriminator value ${String(f)}`);a.add(f)}let l=Array.from(u,f=>UTe(e,n,f)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(f=>{let p=rr(f,e,c,o);f.write(`${i} = ${p};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function UTe(t,e,r){if(typeof r=="string")return`${e} === ${Ln(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${e})`:`${e} === ${r}`;if(typeof r=="boolean")return`${e} === ${r}`;if(r===null)return`${e} === null`;if(r===void 0)return`${e} === undefined`;if(typeof r=="bigint")return`${e} === ${r}n`;if(typeof r=="symbol"){let o=ye(t,r);return`${e} === ${o}`}throw new Ke(`literal discriminator value ${String(r)}`)}function LTe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=_n(t,e,n.left,o),s=_n(t,e,n.right,o),a=ye(e,Tp),c=pe(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function jTe(t,e,r,o){let n=r._zod.def,i=ye(e,Wo);t.write(`if (!${i}(${o})) return INVALID;`);let s=pe(e),a=pe(e),c=pe(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let y of l){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new Ke(`record key value ${String(y)}`);let w=typeof y=="number"?y.toString():y;if(w==="__proto__")throw new Ke('record key "__proto__"');p.push(w);let b=ye(e,y),S=rr(t,e,n.keyType,b),x=pe(e);t.write(`const ${x} = ${o}[${FTe(e,w)}];`);let R=_n(t,e,n.valueType,x);t.write(`${s}[${S}] = ${R};`)}let m=ye(e,new Set(p));return t.write(`for (const ${a} in ${o}) {`),t.indented(y=>{y.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?y.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):y.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let p=n.mode==="loose",m=Jx(n.keyType);m.definite===!1&&(e.definite=!1);let y=ye(e,m),w=ye(e,Ua),b=pe(e);return B9(t,e,o,a,S=>{S.write(`let ${b} = ${y}(${a});`),S.write(`if (${b} === INVALID && typeof ${a} === "string" && ${w}.test(${a})) ${b} = ${y}(Number(${a}));`),p?S.write(`if (${b} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):S.write(`if (${b} === INVALID) return INVALID;`),S.write(`if (${b} === "__proto__") continue;`);let x=pe(e);S.write(`const ${x} = ${o}[${a}];`);let R=_n(S,e,n.valueType,x);S.write(`${s}[${b}] = ${R};`)}),s}return B9(t,e,o,a,p=>{p.write(`const ${c} = ${o}[${a}];`);let m=_n(p,e,n.valueType,c);p.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function B9(t,e,r,o,n,i){let s=ye(e,Object.prototype.propertyIsEnumerable),a=pe(e),c=pe(e),u=pe(e);t.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),t.write(`const ${c} = Object.getOwnPropertyNames(${r});`),t.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),t.write("}"),t.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),t.write("}")}function FTe(t,e){return typeof e=="string"?Ln(e):ye(t,e)}function qTe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=pe(e),s=pe(e),a=pe(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=rr(c,e,n.keyType,s),l=rr(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function VTe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=pe(e),s=pe(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=rr(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function GTe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function HTe(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=ye(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function BTe(t,e,r,o){let n=r._zod.def,i=Ll(e,n.getter),s=ye(e,{parser:null});t.write(`if (!${s}.parser) {`),t.indented(c=>{c.write(`const inner = ${i}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),t.write("}");let a=pe(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function KTe(t,e,r,o){let n=r._zod.def,i=rr(t,e,n.in,o);if(n.transform){if(jl(n.transform))throw new Oi("z.compile: async transforms in pipes are not supported");let s=n.transform,c=Ll(e,l=>{let d={value:l,issues:[],addIssue:Vz},f=s(l,d);return f instanceof Promise?Fn:d.issues.length===0?f:Fn}),u=pe(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),rr(t,e,n.out,u)}else return rr(t,e,n.out,i)}function jl(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function ZTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(jl(n.fn))throw new Oi("z.compile: async custom predicates are not supported");let i=Ll(e,n.fn),s=ye(e,jz),a=pe(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Ke("custom schema without a predicate function");return o}function WTe(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return Fn;let n=o;return n.issues.length===0?n.value:e()}function JTe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[oS])throw new Ke("catch with a callback (only a constant catch value compiles)",!1);let i=pe(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=_n(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ye(e,n.innerType),a=Ll(e,n.catchValue),c=ye(e,WTe);return t.write(`if (${i} === INVALID) {`),t.indented(u=>{u.write(`${i} = ${c}(${s}, ${a}, ${o});`),u.write(`if (${i} === INVALID) return INVALID;`)}),t.write("}"),i}function XTe(t,e,r,o){let n=r._zod.def;if(n.transform){if(jl(n.transform))throw new Oi("z.compile: async transforms are not supported");let i=n.transform,a=Ll(e,u=>{let l={value:u,issues:[],addIssue:Vz},d=i(u,l);return d instanceof Promise?Fn:l.issues.length===0?d:Fn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function Xx(t){return t.checks&&(t.checks=[...t.checks]),t}function Yx(t,e){return new t(Xx({type:"string",...j(e)}))}function Gz(t,e){return new t(Xx({type:"string",coerce:!0,...j(e)}))}function kg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Tg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function Cg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Og(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Dg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Ng(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function jp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function zg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Mg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function Ug(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function Lg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function jg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function Fg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function qg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function Vg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function Gg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function Qx(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...j(e)})}function Hg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function Bg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function Kg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Zg(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function Wg(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function e0(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...j(e)})}function t0(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...j(e)})}function Jg(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}var Hz={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Xg(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function Yg(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function Qg(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function ey(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function r0(t,e){return new t(Xx({type:"number",checks:[],...j(e)}))}function Bz(t,e){return new t(Xx({type:"number",coerce:!0,checks:[],...j(e)}))}function n0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function o0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...j(e)})}function i0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...j(e)})}function s0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...j(e)})}function a0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...j(e)})}function c0(t,e){return new t({type:"boolean",...j(e)})}function Kz(t,e){return new t({type:"boolean",coerce:!0,...j(e)})}function u0(t,e){return new t({type:"bigint",...j(e)})}function Zz(t,e){return new t({type:"bigint",coerce:!0,...j(e)})}function l0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...j(e)})}function d0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...j(e)})}function p0(t,e){return new t({type:"symbol",...j(e)})}function f0(t,e){return new t({type:"undefined",...j(e)})}function m0(t,e){return new t({type:"null",...j(e)})}function h0(t){return new t({type:"any"})}function g0(t){return new t({type:"unknown"})}function y0(t,e){return new t({type:"never",...j(e)})}function v0(t,e){return new t({type:"void",...j(e)})}function w0(t,e){return new t({type:"date",...j(e)})}function Wz(t,e){return new t({type:"date",coerce:!0,...j(e)})}function _0(t,e){return new t({type:"nan",...j(e)})}function As(t,e){return new vS({check:"less_than",...j(e),value:t,inclusive:!1})}function Eo(t,e){return new vS({check:"less_than",...j(e),value:t,inclusive:!0})}function Ps(t,e){return new wS({check:"greater_than",...j(e),value:t,inclusive:!1})}function $o(t,e){return new wS({check:"greater_than",...j(e),value:t,inclusive:!0})}function b0(t){return Ps(0,t)}function S0(t){return As(0,t)}function x0(t){return Eo(0,t)}function E0(t){return $o(0,t)}function Nc(t,e){return new iz({check:"multiple_of",...j(e),value:t})}function zc(t,e){return new cz({check:"max_size",...j(e),maximum:t})}function ks(t,e){return new uz({check:"min_size",...j(e),minimum:t})}function Fl(t,e){return new lz({check:"size_equals",...j(e),size:t})}function ql(t,e){return new dz({check:"max_length",...j(e),maximum:t})}function La(t,e){return new pz({check:"min_length",...j(e),minimum:t})}function Vl(t,e){return new fz({check:"length_equals",...j(e),length:t})}function Fp(t,e){return new mz({check:"string_format",format:"regex",...j(e),pattern:t})}function qp(t){return new hz({check:"string_format",format:"lowercase",...j(t)})}function Vp(t){return new gz({check:"string_format",format:"uppercase",...j(t)})}function Gp(t,e){return new yz({check:"string_format",format:"includes",...j(e),includes:t})}function Hp(t,e){return new vz({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Bp(t,e){return new wz({check:"string_format",format:"ends_with",...j(e),suffix:t})}function $0(t,e,r){return new _z({check:"property",property:t,schema:e,...j(r)})}function Kp(t,e){return new bz({check:"properties",shape:t,...j(e)})}function Zp(t,e){return new Sz({check:"mime_type",mime:t,...j(e)})}function Di(t){return new xz({check:"overwrite",tx:t})}function Wp(t){return Di(e=>e.normalize(t))}function Jp(){return Di(t=>t.trim())}function Xp(){return Di(t=>t.toLowerCase())}function Yp(){return Di(t=>t.toUpperCase())}function Qp(){return Di(t=>s1(t))}function Jz(t,e,r){return new t({type:"array",element:e,...j(r)})}function YTe(t,e,r){return new t({type:"union",options:e,...j(r)})}function QTe(t,e,r){return new t({type:"union",options:e,inclusive:!1,...j(r)})}function eCe(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...j(o)})}function tCe(t,e,r){return new t({type:"intersection",left:e,right:r})}function rCe(t,e,r,o){let n=r instanceof be,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...j(i)})}function nCe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...j(o)})}function oCe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...j(o)})}function iCe(t,e,r){return new t({type:"set",valueType:e,...j(r)})}function sCe(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...j(r)})}function aCe(t,e,r){return new t({type:"enum",entries:e,...j(r)})}function cCe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...j(r)})}function R0(t,e){return new t({type:"file",...j(e)})}function uCe(t,e){return new t({type:"transform",transform:e})}function lCe(t,e){return new t({type:"optional",innerType:e})}function dCe(t,e){return new t({type:"nullable",innerType:e})}function pCe(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():_p(r)}})}function fCe(t,e,r){return new t({type:"nonoptional",innerType:e,...j(r)})}function mCe(t,e){return new t({type:"success",innerType:e})}function hCe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:f1(r)})}function gCe(t,e,r){return new t({type:"pipe",in:e,out:r})}function yCe(t,e){return new t({type:"readonly",innerType:e})}function vCe(t,e,r){return new t({type:"template_literal",parts:e,...j(r)})}function wCe(t,e){return new t({type:"lazy",getter:e})}function _Ce(t,e){return new t({type:"promise",innerType:e})}function I0(t,e,r){let o=j(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function A0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function P0(t,e){let r=J9(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(bp(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(bp(i))}},t(o.value,o)),e);return r}function J9(t,e){let r=new Pt({check:"custom",...j(e)});return r._zod.check=t,r}function k0(t){let e=new Pt({check:"describe"});return e._zod.onattach=[r=>{let o=Wr.get(r)??{};Wr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function T0(t){let e=new Pt({check:"meta"});return e._zod.onattach=[r=>{let o=Wr.get(r)??{};Wr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function C0(t,e){let r=j(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));let i=new Set(o),s=new Set(n),a=t.Codec??Dp,c=t.Boolean??Cp,u=t.String??Dc,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),f=new a({type:"pipe",in:l,out:d,transform:((p,m)=>{let y=p;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:s.has(y)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:f,continue:!1}),{})}),reverseTransform:((p,m)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function Mc(t,e,r,o={}){let n=j(o),i={check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(i.pattern=r),new t(i)}function ty(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&Zr(t,o,r[o]);return t}function Uc(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Wr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function Pr(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function Rt(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let f=s.schema,p=e.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(t,e,f,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),Rt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&ty(s.schema,c),e.io==="input"&&qn(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function X9(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Lc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(m=>m);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${X9(p)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+X9(l)}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
127
127
 
128
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function eZ(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;eZ(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var tZ=new Set(["type","properties","required","additionalProperties"]),Y9=["oneOf","anyOf"];function Q9(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function Xz(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!tZ.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??Q9(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:Xz(a)??{allOf:a};Zr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=Q9(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function bCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of tZ)if(n in t)return;let r=e.filter(n=>Y9.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Xz(e);else{let n=r[0],i=Y9.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>Xz([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,ty(t,o))}function jc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):ty(u,m),ty(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&p.def)for(let w in u)w==="$ref"||w==="allOf"||w in p.def&&JSON.stringify(u[w])===JSON.stringify(p.def[w])&&delete u[w]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())eZ(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])bCe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}ty(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Zr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:ef(e,"input",t.processors),output:ef(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function qn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return qn(o.element,r);if(o.type==="set")return qn(o.valueType,r);if(o.type==="lazy")return qn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return qn(o.innerType,r);if(o.type==="intersection")return qn(o.left,r)||qn(o.right,r);if(o.type==="record"||o.type==="map")return qn(o.keyType,r)||qn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:qn(o.in,r)||qn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(qn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(qn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(qn(n,r))return!0;return!!(o.rest&&qn(o.rest,r))}return!1}var Yz=(t,e={})=>r=>{let o=Uc({...r,processors:e});return Rt(t,o),Lc(o,t),jc(o,t)},ef=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Uc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Lc(s,t),jc(s,t)};var tf=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},rf=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},rZ=(t,e)=>{tf(t,"minimum",e),rf(t,"maximum",e)},sZ=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},aZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},cZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},uZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},nZ=(t,e)=>tf(t,"minimum",e.minimum),oZ=(t,e)=>rf(t,"maximum",e.maximum),iZ=t=>(e,r)=>{uZ(e,r.format);let[o,n]=t[r.format];tf(e,"minimum",o),rf(e,"maximum",n)},SCe={greater_than:(t,e)=>tf(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>rf(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>sZ(t,e.value),number_format:iZ(ig),bigint_format:iZ(sg),min_length:nZ,max_length:oZ,length_equals:(t,e)=>rZ(t,e.length),min_size:nZ,max_size:oZ,size_equals:(t,e)=>rZ(t,e.size),string_format:(t,e)=>{uZ(t,e.format),e.pattern&&aZ(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>cZ(t,e.mime)};function kr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)SCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&tf(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&tf(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&rf(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&rf(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&sZ(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&cZ(e,n.mime);for(let i of n.patterns??[])aZ(e,i);return e}var xCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ECe=new Map([[HS,L1],[_g,j1]]),lZ=t=>ECe.get(t)??t,tM=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=kr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=xCe[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(lZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},rM=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=kr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let b of a)Number.isFinite(b)&&b!==0?m.add(Math.abs(b)):Pr(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=m;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},nM=(t,e,r,o)=>{r.type="boolean"},oM=(t,e,r,o)=>{Pr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},iM=(t,e,r,o)=>{Pr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},sM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},aM=(t,e,r,o)=>{Pr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},cM=(t,e,r,o)=>{Pr(t,e,r,o,"Void cannot be represented in JSON Schema")},uM=(t,e,r,o)=>{r.not={}},lM=(t,e,r,o)=>{},dM=(t,e,r,o)=>{},pM=(t,e,r,o)=>{Pr(t,e,r,o,"Date cannot be represented in JSON Schema")},fM=(t,e,r,o)=>{let n=t._zod.def,i=gp(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},mM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Pr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Pr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},hM=(t,e,r,o)=>{Pr(t,e,r,o,"NaN cannot be represented in JSON Schema")},gM=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},yM=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=kr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},vM=(t,e,r,o)=>{r.type="boolean"},wM=(t,e,r,o)=>{Pr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},_M=(t,e,r,o)=>{Pr(t,e,r,o,"Function types cannot be represented in JSON Schema")},bM=(t,e,r,o)=>{Pr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},SM=(t,e,r,o)=>{Pr(t,e,r,o,"Map cannot be represented in JSON Schema")},xM=(t,e,r,o)=>{Pr(t,e,r,o,"Set cannot be represented in JSON Schema")},EM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=kr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function ry(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?ry(e.out):e.type==="catch"?ry(e.innerType):t._zod.optin}var $M=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Pr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Zr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?ry(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},D0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},RM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},IM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?ry(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:m}=kr(t);typeof p=="number"&&(n.minItems=p),typeof m=="number"&&(n.maxItems=m)};function Qz(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let y=Qz(t,m,r);return y===m?e:y}for(let m of["anyOf","oneOf"]){let y=e[m];if(!Array.isArray(y))continue;let w=y.map(b=>Qz(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[m]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Ua:fg).source)),p}var eM=new WeakMap;function $Ce(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of eM.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=Qz(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var AM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=kr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Zr(n.patternProperties,lZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=eM.get(e);l||(l=[],eM.set(e,l),e.deferred.push(()=>$Ce(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&ry(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},PM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},kM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},TM=Symbol();function dZ(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Pr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),TM):JSON.parse(s)}var CM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=dZ(n.defaultValue,t,e,r,o);s!==TM&&(r.default=s)},OM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=dZ(n.defaultValue,t,e,r,o);s!==TM&&(r._prefault=s)},DM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Pr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},NM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},zM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},MM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},N0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},UM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},O0={string:tM,number:rM,boolean:nM,bigint:oM,symbol:iM,null:sM,undefined:aM,void:cM,never:uM,any:lM,unknown:dM,date:pM,enum:fM,literal:mM,nan:hM,template_literal:gM,file:yM,success:vM,custom:wM,function:_M,transform:bM,map:SM,set:xM,array:EM,object:$M,union:D0,intersection:RM,tuple:IM,record:AM,nullable:PM,nonoptional:kM,default:CM,prefault:OM,catch:DM,pipe:NM,readonly:zM,promise:MM,optional:N0,lazy:UM};function Gl(t,e){if("_idmap"in t){let o=t,n=Uc({...e,processors:O0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Lc(n,l),Zr(s,u,jc(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Uc({...e,processors:O0});return Rt(t,r),Lc(r,t),jc(r,t)}var z0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Uc({processors:O0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Lc(this.ctx,e);let o=jc(this.ctx,e),{"~standard":n,...i}=o;return i}};var pZ={};var df={};Ht(df,{ZodAny:()=>nU,ZodArray:()=>aU,ZodBase64:()=>tE,ZodBase64URL:()=>rE,ZodBigInt:()=>uf,ZodBigIntFormat:()=>iE,ZodBoolean:()=>cf,ZodCIDRv4:()=>Q0,ZodCIDRv6:()=>eE,ZodCUID:()=>B0,ZodCUID2:()=>K0,ZodCatch:()=>RU,ZodCodec:()=>dy,ZodCreditCard:()=>YM,ZodCustom:()=>py,ZodCustomStringFormat:()=>Bl,ZodDate:()=>sy,ZodDefault:()=>_U,ZodDiscriminatedUnion:()=>uU,ZodE164:()=>nE,ZodEmail:()=>q0,ZodEmoji:()=>G0,ZodEnum:()=>of,ZodExactOptional:()=>cE,ZodFile:()=>gU,ZodFunction:()=>zU,ZodGUID:()=>V0,ZodIBAN:()=>QM,ZodIPv4:()=>X0,ZodIPv6:()=>Y0,ZodISODate:()=>qc,ZodISODateTime:()=>Fc,ZodISODuration:()=>Gc,ZodISOTime:()=>Vc,ZodInstanceOf:()=>LU,ZodIntersection:()=>lU,ZodJWT:()=>oE,ZodKSUID:()=>J0,ZodLazy:()=>OU,ZodLiteral:()=>hU,ZodMAC:()=>XM,ZodMap:()=>fU,ZodNaN:()=>AU,ZodNanoID:()=>H0,ZodNever:()=>iU,ZodNonOptional:()=>uE,ZodNull:()=>rU,ZodNullable:()=>wU,ZodNumber:()=>af,ZodNumberFormat:()=>Kl,ZodObject:()=>ay,ZodOptional:()=>Zl,ZodPipe:()=>ly,ZodPrefault:()=>SU,ZodPreprocess:()=>PU,ZodPromise:()=>NU,ZodReadonly:()=>kU,ZodRecord:()=>nf,ZodSet:()=>mU,ZodString:()=>sf,ZodStringFormat:()=>Tt,ZodSuccess:()=>$U,ZodSymbol:()=>eU,ZodTemplateLiteral:()=>CU,ZodTransform:()=>yU,ZodTuple:()=>dU,ZodType:()=>Ce,ZodULID:()=>Z0,ZodURL:()=>oy,ZodUUID:()=>Ts,ZodUndefined:()=>tU,ZodUnion:()=>cy,ZodUnknown:()=>oU,ZodVoid:()=>sU,ZodXID:()=>W0,ZodXor:()=>cU,_ZodString:()=>F0,_default:()=>bU,_function:()=>_W,any:()=>tW,array:()=>qe,base64:()=>NZ,base64url:()=>zZ,bigint:()=>JZ,boolean:()=>hr,catch:()=>IU,check:()=>bW,cidrv4:()=>OZ,cidrv6:()=>DZ,codec:()=>gW,creditCard:()=>UZ,cuid:()=>$Z,cuid2:()=>RZ,currencyCode:()=>GZ,custom:()=>lE,date:()=>nW,describe:()=>SW,discriminatedUnion:()=>uy,e164:()=>MZ,email:()=>hZ,emoji:()=>xZ,enum:()=>Xr,exactOptional:()=>vU,file:()=>pW,float32:()=>BZ,float64:()=>KZ,function:()=>_W,guid:()=>gZ,hash:()=>HZ,hex:()=>VZ,hostname:()=>qZ,httpUrl:()=>SZ,iban:()=>LZ,instanceof:()=>EW,int:()=>L0,int32:()=>ZZ,int64:()=>XZ,intersection:()=>lf,invertCodec:()=>yW,ipv4:()=>kZ,ipv6:()=>CZ,json:()=>RW,jwt:()=>jZ,keyof:()=>oW,ksuid:()=>PZ,lazy:()=>DU,literal:()=>ae,looseObject:()=>Jr,looseRecord:()=>cW,mac:()=>TZ,map:()=>uW,meta:()=>xW,nan:()=>hW,nanoid:()=>EZ,nativeEnum:()=>dW,never:()=>sE,nonoptional:()=>EU,null:()=>iy,nullable:()=>ny,nullish:()=>fW,number:()=>yt,object:()=>X,optional:()=>kt,partialRecord:()=>aW,pipe:()=>j0,prefault:()=>xU,preprocess:()=>fy,promise:()=>wW,readonly:()=>TU,record:()=>Ct,refine:()=>MU,set:()=>lW,strictObject:()=>iW,string:()=>O,stringFormat:()=>FZ,stringbool:()=>$W,success:()=>mW,superRefine:()=>UU,symbol:()=>QZ,templateLiteral:()=>vW,transform:()=>aE,tuple:()=>pU,uint32:()=>WZ,uint64:()=>YZ,ulid:()=>IZ,undefined:()=>eW,union:()=>It,unknown:()=>Ut,url:()=>bZ,uuid:()=>yZ,uuidv4:()=>vZ,uuidv6:()=>wZ,uuidv7:()=>_Z,void:()=>rW,xid:()=>AZ,xor:()=>sW});var M0={};Ht(M0,{endsWith:()=>Bp,gt:()=>Ps,gte:()=>$o,includes:()=>Gp,length:()=>Vl,lowercase:()=>qp,lt:()=>As,lte:()=>Eo,maxLength:()=>ql,maxSize:()=>zc,mime:()=>Zp,minLength:()=>La,minSize:()=>ks,multipleOf:()=>Nc,negative:()=>S0,nonnegative:()=>E0,nonpositive:()=>x0,normalize:()=>Wp,overwrite:()=>Di,positive:()=>b0,properties:()=>Kp,property:()=>$0,regex:()=>Fp,size:()=>Fl,slugify:()=>Qp,startsWith:()=>Hp,toLowerCase:()=>Xp,toUpperCase:()=>Yp,trim:()=>Jp,uppercase:()=>Vp});var fZ=new WeakSet([Object.prototype,Error.prototype]);function U0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var mZ=(t,e)=>{w1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);fZ.has(r)||(fZ.add(r),U0(r,"format",o=>n=>dg(o,n)),U0(r,"flatten",o=>n=>lg(o,n)),U0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,yp,2)}),U0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,yp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ICe=$("ZodError",mZ),co=$("ZodError",mZ,void 0,{Parent:Error});var LM=Sp(co),jM=xp(co),FM=Ep(co),qM=Rp(co),VM=sS(co),GM=aS(co),HM=cS(co),BM=uS(co),KM=lS(co),ZM=dS(co),WM=pS(co),JM=fS(co);function PCe(){zr.localeError||cr(Gx())}function Hl(){zr.memoizer||cr({memoizer:Ag()})}var Ce=$("ZodType",(t,e)=>(PCe(),be.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(MU(t,e))},superRefine(t,e){return this.check(UU(t,e))},overwrite(t){return this.check(Di(t))},optional(){return kt(this)},exactOptional(){return vU(this)},nullable(){return ny(this)},nullish(){return kt(ny(this))},nonoptional(t){return EU(this,t)},array(){return qe(this)},or(t){return It([this,t])},and(t){return lf(this,t)},transform(t){return j0(this,aE(t))},default(t){return bU(this,t)},prefault(t){return xU(this,t)},catch(t){return IU(this,t)},pipe(t){return j0(this,t)},readonly(){return TU(this)},describe(t){let e=this.clone();return Wr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Wr.get(this);let e=this.clone();return Wr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return D.hide(this,"~standard",{...ES(this),jsonSchema:{input:ef(this,"input"),output:ef(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return LM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await jM(this,e,r,{callee:t})},safeParse(t,e){return FM(this,t,e)},async safeParseAsync(t,e){return qM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Ap(this,t,e)},validateAsync(t,e){return Pp(this,t,e)},encode:function t(e,r){return VM(this,e,r,{callee:t})},decode:function t(e,r){return GM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await HM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await BM(this,e,r,{callee:t})},safeEncode(t,e){return KM(this,t,e)},safeDecode(t,e){return ZM(this,t,e)},async safeEncodeAsync(t,e){return WM(this,t,e)},async safeDecodeAsync(t,e){return JM(this,t,e)},toJSONSchema(t){return Yz(this,{})(t)},get description(){return Wr.get(this)?.description},get _def(){return this._zod.def}}),F0=$("_ZodString",(t,e)=>{Dc.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tM(t,r,o,n)},D.derived({format:t=>kr(t).format??null,minLength:t=>kr(t).minimum??null,maxLength:t=>kr(t).maximum??null},{regex(...t){return this.check(Fp(...t))},includes(...t){return this.check(Gp(...t))},startsWith(...t){return this.check(Hp(...t))},endsWith(...t){return this.check(Bp(...t))},min(...t){return this.check(La(...t))},max(...t){return this.check(ql(...t))},length(...t){return this.check(Vl(...t))},nonempty(...t){return this.check(La(1,...t))},lowercase(t){return this.check(qp(t))},uppercase(t){return this.check(Vp(t))},trim(){return this.check(Jp())},normalize(...t){return this.check(Wp(...t))},toLowerCase(){return this.check(Xp())},toUpperCase(){return this.check(Yp())},slugify(){return this.check(Qp())}})),sf=$("ZodString",(t,e)=>{Dc.init(t,e),F0.init(t,e)},{email(t){return this.check(kg(q0,t))},url(t){return this.check(jp(oy,t))},jwt(t){return this.check(Jg(oE,t))},emoji(t){return this.check(zg(G0,t))},guid(t){return this.check(Tg(V0,t))},uuid(t){return this.check(Cg(Ts,t))},uuidv4(t){return this.check(Og(Ts,t))},uuidv6(t){return this.check(Dg(Ts,t))},uuidv7(t){return this.check(Ng(Ts,t))},nanoid(t){return this.check(Mg(H0,t))},cuid(t){return this.check(Ug(B0,t))},cuid2(t){return this.check(Lg(K0,t))},ulid(t){return this.check(jg(Z0,t))},base64(t){return this.check(Kg(tE,t))},base64url(t){return this.check(Zg(rE,t))},xid(t){return this.check(Fg(W0,t))},ksuid(t){return this.check(qg(J0,t))},ipv4(t){return this.check(Vg(X0,t))},ipv6(t){return this.check(Gg(Y0,t))},cidrv4(t){return this.check(Hg(Q0,t))},cidrv6(t){return this.check(Bg(eE,t))},e164(t){return this.check(Wg(nE,t))},datetime(t){return this.check(Xg(Fc,t))},date(t){return this.check(Yg(qc,t))},time(t){return this.check(Qg(Vc,t))},duration(t){return this.check(ey(Gc,t))}});function O(t){return Yx(sf,t)}var Tt=$("ZodStringFormat",(t,e)=>{St.init(t,e),F0.init(t,e)}),Fc=$("ZodISODateTime",(t,e)=>{Az.init(t,e),Tt.init(t,e)}),qc=$("ZodISODate",(t,e)=>{Pz.init(t,e),Tt.init(t,e)}),Vc=$("ZodISOTime",(t,e)=>{kz.init(t,e),Tt.init(t,e)}),Gc=$("ZodISODuration",(t,e)=>{Tz.init(t,e),Tt.init(t,e)}),q0=$("ZodEmail",(t,e)=>{IS.init(t,e),Tt.init(t,e)});function hZ(t){return kg(q0,t)}var V0=$("ZodGUID",(t,e)=>{$S.init(t,e),Tt.init(t,e)});function gZ(t){return Tg(V0,t)}var Ts=$("ZodUUID",(t,e)=>{RS.init(t,e),Tt.init(t,e)});function yZ(t){return Cg(Ts,t)}function vZ(t){return Og(Ts,t)}function wZ(t){return Dg(Ts,t)}function _Z(t){return Ng(Ts,t)}var oy=$("ZodURL",(t,e)=>{TS.init(t,e),Tt.init(t,e)});function bZ(t){return jp(oy,t)}function SZ(t){return jp(oy,{protocol:pg,hostname:q1,...D.normalizeParams(t)})}var G0=$("ZodEmoji",(t,e)=>{CS.init(t,e),Tt.init(t,e)});function xZ(t){return zg(G0,t)}var H0=$("ZodNanoID",(t,e)=>{OS.init(t,e),Tt.init(t,e)});function EZ(t){return Mg(H0,t)}var B0=$("ZodCUID",(t,e)=>{DS.init(t,e),Tt.init(t,e)});function $Z(t){return Ug(B0,t)}var K0=$("ZodCUID2",(t,e)=>{NS.init(t,e),Tt.init(t,e)});function RZ(t){return Lg(K0,t)}var Z0=$("ZodULID",(t,e)=>{zS.init(t,e),Tt.init(t,e)});function IZ(t){return jg(Z0,t)}var W0=$("ZodXID",(t,e)=>{MS.init(t,e),Tt.init(t,e)});function AZ(t){return Fg(W0,t)}var J0=$("ZodKSUID",(t,e)=>{US.init(t,e),Tt.init(t,e)});function PZ(t){return qg(J0,t)}var X0=$("ZodIPv4",(t,e)=>{LS.init(t,e),Tt.init(t,e)});function kZ(t){return Vg(X0,t)}var XM=$("ZodMAC",(t,e)=>{FS.init(t,e),Tt.init(t,e)});function TZ(t){return Qx(XM,t)}var Y0=$("ZodIPv6",(t,e)=>{jS.init(t,e),Tt.init(t,e)});function CZ(t){return Gg(Y0,t)}var Q0=$("ZodCIDRv4",(t,e)=>{qS.init(t,e),Tt.init(t,e)});function OZ(t){return Hg(Q0,t)}var eE=$("ZodCIDRv6",(t,e)=>{GS.init(t,e),Tt.init(t,e)});function DZ(t){return Bg(eE,t)}var tE=$("ZodBase64",(t,e)=>{BS.init(t,e),Tt.init(t,e)});function NZ(t){return Kg(tE,t)}var rE=$("ZodBase64URL",(t,e)=>{ZS.init(t,e),Tt.init(t,e)});function zZ(t){return Zg(rE,t)}var nE=$("ZodE164",(t,e)=>{WS.init(t,e),Tt.init(t,e)});function MZ(t){return Wg(nE,t)}var YM=$("ZodCreditCard",(t,e)=>{XS.init(t,e),Tt.init(t,e)});function UZ(t){return e0(YM,t)}var QM=$("ZodIBAN",(t,e)=>{QS.init(t,e),Tt.init(t,e)});function LZ(t){return t0(QM,t)}var oE=$("ZodJWT",(t,e)=>{tx.init(t,e),Tt.init(t,e)});function jZ(t){return Jg(oE,t)}var Bl=$("ZodCustomStringFormat",(t,e)=>{rx.init(t,e),Tt.init(t,e)});function FZ(t,e,r={}){return Mc(Bl,t,e,r)}function qZ(t){return Mc(Bl,"hostname",F1,t)}function VZ(t){return Mc(Bl,"hex",rz,t)}function GZ(t){return Mc(Bl,"currency_code",G1,t)}function HZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=xo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Mc(Bl,o,n,e)}var af=$("ZodNumber",(t,e)=>{bg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rM(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=kr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=kr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=kr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>kr(t).format??null},{gt(t,e){return this.check(Ps(t,e))},gte(t,e){return this.check($o(t,e))},min(t,e){return this.check($o(t,e))},lt(t,e){return this.check(As(t,e))},lte(t,e){return this.check(Eo(t,e))},max(t,e){return this.check(Eo(t,e))},int(t){return this.check(L0(t))},safe(t){return this.check(L0(t))},positive(t){return this.check(Ps(0,t))},nonnegative(t){return this.check($o(0,t))},negative(t){return this.check(As(0,t))},nonpositive(t){return this.check(Eo(0,t))},multipleOf(t,e){return this.check(Nc(t,e))},step(t,e){return this.check(Nc(t,e))},finite(){return this}}));function yt(t){return r0(af,t)}var Kl=$("ZodNumberFormat",(t,e)=>{nx.init(t,e),af.init(t,e)});function L0(t){return n0(Kl,t)}function BZ(t){return o0(Kl,t)}function KZ(t){return i0(Kl,t)}function ZZ(t){return s0(Kl,t)}function WZ(t){return a0(Kl,t)}var cf=$("ZodBoolean",(t,e)=>{Cp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nM(t,r,o,n)});function hr(t){return c0(cf,t)}var uf=$("ZodBigInt",(t,e)=>{Sg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oM(t,r,o,n)},D.derived({minValue:t=>kr(t).minimum??null,maxValue:t=>kr(t).maximum??null,format:t=>kr(t).format??null},{gte(t,e){return this.check($o(t,e))},min(t,e){return this.check($o(t,e))},gt(t,e){return this.check(Ps(t,e))},lt(t,e){return this.check(As(t,e))},lte(t,e){return this.check(Eo(t,e))},max(t,e){return this.check(Eo(t,e))},positive(t){return this.check(Ps(BigInt(0),t))},negative(t){return this.check(As(BigInt(0),t))},nonpositive(t){return this.check(Eo(BigInt(0),t))},nonnegative(t){return this.check($o(BigInt(0),t))},multipleOf(t,e){return this.check(Nc(t,e))}}));function JZ(t){return u0(uf,t)}var iE=$("ZodBigIntFormat",(t,e)=>{ox.init(t,e),uf.init(t,e)});function XZ(t){return l0(iE,t)}function YZ(t){return d0(iE,t)}var eU=$("ZodSymbol",(t,e)=>{ix.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iM(t,r,o,n)});function QZ(t){return p0(eU,t)}var tU=$("ZodUndefined",(t,e)=>{sx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aM(t,r,o,n)});function eW(t){return f0(tU,t)}var rU=$("ZodNull",(t,e)=>{ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sM(t,r,o,n)});function iy(t){return m0(rU,t)}var nU=$("ZodAny",(t,e)=>{cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n)});function tW(){return h0(nU)}var oU=$("ZodUnknown",(t,e)=>{ux.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n)});function Ut(){return g0(oU)}var iU=$("ZodNever",(t,e)=>{lx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n)});function sE(t){return y0(iU,t)}var sU=$("ZodVoid",(t,e)=>{dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cM(t,r,o,n)});function rW(t){return v0(sU,t)}var sy=$("ZodDate",(t,e)=>{px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pM(t,r,o,n),t.min=(r,o)=>t.check($o(r,o)),t.max=(r,o)=>t.check(Eo(r,o))},D.derived({minDate:t=>{let{minimum:e}=kr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=kr(t);return e?new Date(e):null}},{}));function nW(t){return w0(sy,t)}var aU=$("ZodArray",(t,e)=>{Hl(),fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(La(t,e))},nonempty(t){return this.check(La(1,t))},max(t,e){return this.check(ql(t,e))},length(t,e){return this.check(Vl(t,e))},unwrap(){return this.element}});function qe(t,e){return Jz(aU,t,e)}function oW(t){let e=t._zod.def.shape;return Xr(Object.keys(e))}var ay=$("ZodObject",(t,e)=>{Hl(),Cz.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$M(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Xr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:sE()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return D.extend(this,t)},safeExtend(t){return D.safeExtend(this,t)},merge(t){return D.merge(this,t)},pick(t){return D.pick(this,t)},omit(t){return D.omit(this,t)},partial(...t){return D.partial(Zl,this,t[0])},exactPartial(...t){return D.partial(cE,this,t[0],"exactPartial")},required(...t){return D.required(uE,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new ay(r)}function iW(t,e){return new ay({type:"object",shape:t,catchall:sE(),...D.normalizeParams(e)})}function Jr(t,e){return new ay({type:"object",shape:t,catchall:Ut(),...D.normalizeParams(e)})}var cy=$("ZodUnion",(t,e)=>{Op.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>D0(t,r,o,n),t.options=e.options});function It(t,e){return new cy({type:"union",options:t,...D.normalizeParams(e)})}var cU=$("ZodXor",(t,e)=>{cy.init(t,e),hx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>D0(t,r,o,n),t.options=e.options});function sW(t,e){return new cU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var uU=$("ZodDiscriminatedUnion",(t,e)=>{cy.init(t,e),gx.init(t,e)});function uy(t,e,r){return new uU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var lU=$("ZodIntersection",(t,e)=>{yx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RM(t,r,o,n)});function lf(t,e){return new lU({type:"intersection",left:t,right:e})}var dU=$("ZodTuple",(t,e)=>{Hl(),xg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Zl({type:"optional",innerType:e}))})}});function pU(t,e,r){let o=e instanceof be,n=o?r:e,i=o?e:null;return new dU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var nf=$("ZodRecord",(t,e)=>{Hl(),vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Ct(t,e,r){return!e||!e._zod?new nf({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new nf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function aW(t,e,r){return new nf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function cW(t,e,r){return new nf({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var fU=$("ZodMap",(t,e)=>{Hl(),wx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(ks(...r)),t.nonempty=r=>t.check(ks(1,r)),t.max=(...r)=>t.check(zc(...r)),t.size=(...r)=>t.check(Fl(...r))});function uW(t,e,r){return new fU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var mU=$("ZodSet",(t,e)=>{Hl(),_x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n),t.min=(...r)=>t.check(ks(...r)),t.nonempty=r=>t.check(ks(1,r)),t.max=(...r)=>t.check(zc(...r)),t.size=(...r)=>t.check(Fl(...r))});function lW(t,e){return new mU({type:"set",valueType:t,...D.normalizeParams(e)})}var of=$("ZodEnum",(t,e)=>{bx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(o,n,i)=>fM(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new of({...e,checks:[],...D.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new of({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Xr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new of({type:"enum",entries:r,...D.normalizeParams(e)})}function dW(t,e){return new of({type:"enum",entries:t,...D.normalizeParams(e)})}var hU=$("ZodLiteral",(t,e)=>{Sx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ae(t,e){return new hU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var gU=$("ZodFile",(t,e)=>{xx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n),t.min=(r,o)=>t.check(ks(r,o)),t.max=(r,o)=>t.check(zc(r,o)),t.mime=(r,o)=>t.check(Zp(Array.isArray(r)?r:[r],o))});function pW(t){return R0(gU,t)}var yU=$("ZodTransform",(t,e)=>{Hl(),Ex.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Oc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(D.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(D.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function aE(t){return new yU({type:"transform",transform:t})}var Zl=$("ZodOptional",(t,e)=>{Eg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function kt(t){return new Zl({type:"optional",innerType:t})}var cE=$("ZodExactOptional",(t,e)=>{$x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function vU(t){return new cE({type:"optional",innerType:t})}var wU=$("ZodNullable",(t,e)=>{Rx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ny(t){return new wU({type:"nullable",innerType:t})}function fW(t){return kt(ny(t))}var _U=$("ZodDefault",(t,e)=>{Ix.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function bU(t,e){return new _U({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var SU=$("ZodPrefault",(t,e)=>{Ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function xU(t,e){return new SU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var uE=$("ZodNonOptional",(t,e)=>{Px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function EU(t,e){return new uE({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var $U=$("ZodSuccess",(t,e)=>{kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function mW(t){return new $U({type:"success",innerType:t})}var RU=$("ZodCatch",(t,e)=>{Tx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>DM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function IU(t,e){return new RU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var AU=$("ZodNaN",(t,e)=>{Cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n)});function hW(t){return _0(AU,t)}var ly=$("ZodPipe",(t,e)=>{$g.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>NM(t,r,o,n),t.in=e.in,t.out=e.out});function j0(t,e){return new ly({type:"pipe",in:t,out:e})}var dy=$("ZodCodec",(t,e)=>{ly.init(t,e),Dp.init(t,e)});function gW(t,e,r){return new dy({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function yW(t){let e=t._zod.def;return new dy({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var PU=$("ZodPreprocess",(t,e)=>{ly.init(t,e),Dz.init(t,e)}),kU=$("ZodReadonly",(t,e)=>{Ox.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function TU(t){return new kU({type:"readonly",innerType:t})}var CU=$("ZodTemplateLiteral",(t,e)=>{Dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n)});function vW(t,e){return new CU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var OU=$("ZodLazy",(t,e)=>{Np.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>UM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function DU(t){return new OU({type:"lazy",getter:t})}var NU=$("ZodPromise",(t,e)=>{zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>MM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wW(t){return new NU({type:"promise",innerType:t})}var zU=$("ZodFunction",(t,e)=>{Nx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n)});function _W(t){return new zU({type:"function",input:Array.isArray(t?.input)?pU(t?.input):t?.input??qe(Ut()),output:t?.output??Ut()})}var py=$("ZodCustom",(t,e)=>{Mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n)});function bW(t){let e=new Pt({check:"custom"});return e._zod.check=t,e}function lE(t,e){return I0(py,t??(()=>!0),e)}function MU(t,e={}){return A0(py,t,e)}function UU(t,e){return P0(t,e)}var SW=k0,xW=T0,LU=$("ZodInstanceOf",(t,e)=>{py.init(t,e)},{properties(t,e){return this.check(Kp(t,e))}});function EW(t,e={}){let r=new LU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...D.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var $W=(...t)=>C0({Codec:dy,Boolean:cf,String:sf},...t);function RW(t){let e=DU(()=>It([O(t),yt(),hr(),iy(),qe(e),Ct(O(),e)]));return e}function fy(t,e){return new PU({type:"pipe",in:aE(t),out:e})}var kCe={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function TCe(t){cr({customError:t})}function CCe(){return cr().customError}var jU;jU||(jU={});var Wl={};Ht(Wl,{ZodISODate:()=>qc,ZodISODateTime:()=>Fc,ZodISODuration:()=>Gc,ZodISOTime:()=>Vc,date:()=>DCe,datetime:()=>OCe,duration:()=>zCe,time:()=>NCe});function OCe(t){return Xg(Fc,t)}function DCe(t){return Yg(qc,t)}function NCe(t){return Qg(Vc,t)}function zCe(t){return ey(Gc,t)}var W={...df,...M0,iso:Wl},MCe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function UCe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function IW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function LCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jCe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:LCe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function FCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function FU(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=FU(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=FU(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var qCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),VCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function my(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(my):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>qCe.has(e)?my(r):!VCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(my))}function AW(t){return t===1?"element":"elements"}function GCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=FU(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${AW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${AW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function PW(t,e){if(t!==!1)return t===void 0||t===!0?W.any():Vn(t,e)}var HCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function kW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return W.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=jCe(n,e),s=Vn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return W.null();if(n.length===0)return W.never();if(n.length===1)return W.literal(n[0]);if(n.every(s=>typeof s=="string"))return W.enum(n);let i=n.map(s=>W.literal(s));return i.length<2?i[0]:W.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return W.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return kW(s,e)});return n.length===0?W.never():n.length===1?n[0]:W.union(n)}if(!r)return W.any();let o;switch(r){case"string":{let n=W.string();if(t.format){let i=t.format;i==="email"?n=n.check(W.email()):i==="uri"||i==="uri-reference"?n=n.check(W.url()):i==="uuid"||i==="guid"?n=n.check(W.uuid()):i==="date-time"?n=n.check(W.iso.datetime({offset:!0})):i==="date"?n=n.check(W.iso.date()):i==="time"?n=n.check(W.regex(HCe)):i==="duration"?n=n.check(W.iso.duration()):i==="hostname"?n=n.check(W.hostname()):i==="ipv4"?n=n.check(W.ipv4()):i==="ipv6"?n=n.check(W.ipv6()):i==="mac"?n=n.check(W.mac()):i==="cidr"?n=n.check(W.cidrv4()):i==="cidr-v6"?n=n.check(W.cidrv6()):i==="base64"?n=n.check(W.base64()):i==="base64url"?n=n.check(W.base64url()):i==="e164"?n=n.check(W.e164()):i==="credit_card"?n=n.check(W.creditCard()):i==="iban"?n=n.check(W.iban()):i==="jwt"?n=n.check(W.jwt()):i==="emoji"?n=n.check(W.emoji()):i==="nanoid"?n=n.check(W.nanoid()):i==="cuid"?n=n.check(W.cuid()):i==="cuid2"?n=n.check(W.cuid2()):i==="ulid"?n=n.check(W.ulid()):i==="xid"?n=n.check(W.xid()):i==="ksuid"&&(n=n.check(W.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?W.number().int():W.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=W.boolean();break}case"null":{o=W.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Vn(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=Vn(f,e);Zr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let y of f){let w=Vn(d[y],e),b=W.string().regex(new RegExp(y));p.push(W.looseRecord(b,w))}let m=[];if(Object.keys(n).length>0&&m.push(W.object(n).passthrough()),m.push(...p),m.length===0)o=W.object({}).passthrough();else if(m.length===1)o=m[0];else{let y=W.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)y=W.intersection(y,m[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=f.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Wo(S.value))return;let x=[];for(let R of Object.keys(S.value))y.includes(R)||w.some(T=>T.test(R))||x.push(R);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=W.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=Vn(f,e)}o=FCe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>Vn(d,e)),c=IW(a,s),u=Array.isArray(i)?void 0:PW(i,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Vn(d,e)),c=IW(a,s),u=PW(t.additionalItems,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(i!==void 0){let s=Vn(i,e),a=W.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=W.array(W.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=GCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Vn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Vn(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r=kW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>Vn(u,e)),c=W.union(a);r=o?W.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Vn(u,e)),c=W.xor(a);r=o?W.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:W.any();else{let a=o?r:Vn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=W.intersection(a,Vn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=W.nullable(r)),t.readOnly===!0&&(r=W.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!my(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!my(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))MCe.has(a)||Zr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function TW(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=UCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Wr};return Vn(r,i)}var CW=Symbol("z.visit/resolving");function hy(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===CW)return new Np({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,CW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let m of l){let y=n(u[m]);y!==u[m]&&(d=!0),f[m]=y}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let m=n(p);m!==p&&(l=!0),d.push(m)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function OW(t){return hy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function BCe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Zo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function DW(t){return BCe(t.out,t.checks)}function KCe(t){return t.in._zod.traits.has("$ZodTransform")?DW(t):t.in}function NW(t){return hy(t,{pipe:e=>KCe(e._zod.def),default:(e,r)=>r?kt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function zW(t){return hy(t,{pipe:e=>DW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var qU={};Ht(qU,{bigint:()=>XCe,boolean:()=>JCe,date:()=>YCe,number:()=>WCe,string:()=>ZCe});function ZCe(t){return Gz(sf,t)}function WCe(t){return Bz(af,t)}function JCe(t){return Kz(cf,t)}function XCe(t){return Zz(uf,t)}function YCe(t){return Wz(sy,t)}var gy={name:"@tomato414941/foundation",version:"12.1.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&h.config({jitless:!0});function eOe(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var yy=h.string().trim().max(8192).refine(t=>eOe(t)!==null,"Use an OpenSSH public key from a .pub file."),vy=h.object({authorizedKeys:h.array(yy).max(32)}).strict(),Ugt=vy.extend({revision:h.number().int().positive().optional()}),VU=vy.extend({host:h.string().min(1).max(253).nullable(),port:h.number().int().min(1).max(65535),username:h.literal("root"),workingDirectory:h.literal("/workspace"),hostKey:yy.nullable(),fingerprint:h.string().nullable(),revision:h.number().int().positive(),appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),Lgt=VU.extend({state:h.enum(["starting","configuring","ready","disabled","stopped"])}),jgt=h.object({hostKey:yy,appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),tOe=vy.extend({port:h.number().int().min(1).max(65535),revision:h.number().int().positive()}).strict(),dE=h.object({configuration:tOe.nullable()}).strict();var pf=new TextEncoder,ff=new TextDecoder,MW=new TextDecoder("utf-8",{fatal:!0}),pE=2**32;function Gn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function GU(t,e,r){if(e<0||e>=pE)throw new RangeError(`value must be >= 0 and <= ${pE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function HU(t){let e=Math.floor(t/pE),r=t%pE,o=new Uint8Array(8);return GU(o,e,0),GU(o,r,4),o}function fE(t){let e=new Uint8Array(4);return GU(e,t),e}var rOe=/[^\x00-\x7f]/;function Yr(t){if(typeof t=="string"&&t.length>=128){if(rOe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return pf.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function UW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function LW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function mE(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var ja=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Jl=class extends ja{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ot=class extends ja{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Hc=class extends ja{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},G=class extends ja{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Xt=class extends ja{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var wy=class extends ja{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var hE=class extends ja{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var nOe="The input to be decoded is not correctly encoded.";function Xl(t){try{return LW(typeof t=="string"?t:ff.decode(t),!0)}catch(e){throw new TypeError(nOe,{cause:e})}}function nr(t){return UW(typeof t=="string"?pf.encode(t):t,!0)}function Ro(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function vr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Bc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Xo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function uo(t,e,r){try{return Xl(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function gE(t,e,r){try{return Yr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function mf(t,e,r){let o;try{o=JSON.parse(MW.decode(Xl(t)))}catch{throw new e(r)}if(!vr(o))throw new e(r);return o}var yE={__proto__:null,b64:!0},vE={__proto__:null};function _y(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function wE(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Kc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ot(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function _E(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Yl(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!vr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var oOe=t=>t[Symbol.toStringTag],iOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function zi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(vr(e)){if(s=XU(e),typeof s.kty!="string")throw jW(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(iOe(t,s,r),s.kty==="oct")return Xl(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!ZU(e))throw jW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${oOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Zc(e))return e;if(a=e,a.type==="secret")return a.export()}BU||=new WeakMap;let c=e,u=BU.get(c);if(u?.[o])return u[o];if(u||BU.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=sOe[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await gf(t,s)}var BU,sOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function SE(t){if(!Zc(t))throw new Error("CryptoKey instance expected")}var Zc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},KU=t=>t?.[Symbol.toStringTag]==="KeyObject",ZU=t=>Zc(t)||KU(t);function FW(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Fa=(t,...e)=>FW("Key must be ",t,...e);function jW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(FW(`Key for the ${t} algorithm must be `,e,...o))}var bE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function WU(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function hf(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function JU(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw bE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw bE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw bE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw bE(e.length,"algorithm.length");WU(t,r)}function xE(t){return{__proto__:null,...t}}function XU(t){let e=xE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function EE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function gf(t,e,r){if(!t.kty.includes(e.kty))throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Mi(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),JU(t,e,r),t}var Ql=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function $E(t,e){let r=t.byteLength<<3;if(r!==e)throw new G(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var aOe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function qW(t,e){if(e.length<<3!==t.ivBits)throw new G("Invalid Initialization Vector length")}async function VW(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Fa(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function GW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function cOe(t,e,r,o,n){let[i,s,a]=await VW(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Gn(n,o,c,HU(n.length*8)),l=await GW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function uOe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function lOe(t,e,r,o,n,i){let[s,a,c]=await VW(t,e,"decrypt"),u=Gn(i,o,r,HU(i.length*8)),l=await GW(a,u,c);try{if(await uOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Hc}async function RE(t,e,r,o,n){if(!Zc(r)&&!(r instanceof Uint8Array))throw new TypeError(Fa(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?qW(t,o):o=aOe(t),r instanceof Uint8Array&&$E(r,t.cekBits),t.cbc)return cOe(t,e,r,o,n);let i=await Mi(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function IE(t,e,r,o,n,i){if(!Zc(e)&&!(e instanceof Uint8Array))throw new TypeError(Fa(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new G("JWE Initialization Vector missing");if(!n)throw new G("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new G("Invalid Authentication Tag length");if(qW(t,o),e instanceof Uint8Array&&$E(e,t.cekBits),t.cbc)return lOe(t,e,r,o,n,i);let s=await Mi(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Gn(r,n)))}catch{throw new Hc}}function by(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var dOe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],pOe=[[],["deriveBits"]],kE=[[],[]];function AE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:dOe,ops:["wrapKey","unwrapKey"]}}function PE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:pOe,ops:[void 0,"deriveBits"]}}function yf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:kE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function YU(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:kE,ops:["deriveBits","deriveBits"]}}var qa=by({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:kE,ops:["encrypt","decrypt"]},"RSA-OAEP":AE(1),"RSA-OAEP-256":AE(256),"RSA-OAEP-384":AE(384),"RSA-OAEP-512":AE(512),"ECDH-ES":PE("direct-key-agreement"),"ECDH-ES+A128KW":PE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":PE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":PE("key-agreement-with-key-wrapping"),A128KW:yf(128),A192KW:yf(192),A256KW:yf(256),A128GCMKW:yf(128,!0),A192GCMKW:yf(192,!0),A256GCMKW:yf(256,!0),"PBES2-HS256+A128KW":YU(),"PBES2-HS384+A192KW":YU(),"PBES2-HS512+A256KW":YU()}),fOe=["encrypt","decrypt"];function vf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:kE,ops:fOe,cekBits:t,ivBits:e?128:96,cbc:e}}var mOe=by({A128GCM:vf(128),A192GCM:vf(192),A256GCM:vf(256),"A128CBC-HS256":vf(256,!0),"A192CBC-HS384":vf(384,!0),"A256CBC-HS512":vf(512,!0)});function HW(t,e){throw new Ot(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Ui(t){return(typeof t=="string"?qa[t]:void 0)??HW("alg","Algorithm")}function Li(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function ed(t){return(typeof t=="string"?mOe[t]:void 0)??HW("enc","Encryption Algorithm")}function BW(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");WU(t,e)}async function hOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function gOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function ZW(t,e,r){JU(e,Ui(t).subtle,r),hf(t,e)}async function WW(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new G("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new G("PBES2 Count Input must be a positive integer");let n=Gn(Yr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Mi(o,Ui(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function QU(t){return Gn(fE(t.length),t)}async function yOe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await mE("sha256",Gn(fE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function JW(t,e,r,o,n=new Uint8Array,i=new Uint8Array){BW(t),BW(e,"deriveBits");let s=Gn(QU(Yr(r)),QU(n),QU(i),fE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return yOe(a,o,s)}function XW(t){SE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ot("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function TE(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new G(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return uo(r,e,G)}}function YW(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new G('JOSE Header "apu" and "apv" values must be distinct')}}function vOe(t){if(t===void 0)throw new G("JWE Encrypted Key missing")}function KW(t){if(t!==void 0)throw new G("Encountered unexpected JWE Encrypted Key")}function wOe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function QW(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return KW(o),r;let c=a==="direct-key-agreement";switch(c?KW(o):vOe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!vr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new G('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');XW(r);let l=await gf(t,u),d=TE(n,"apu"),f=TE(n,"apv");YW(d,f);let p=await JW(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return SE(r),ZW(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new G('JOSE Header "p2c" (PBES2 Count) missing or invalid');wOe(i);let u=i??1e4;if(n.p2c>u)throw new G('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new G('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=uo(n.p2s,"p2s",G);r=await WW(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new G('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new G('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=uo(n.iv,"iv",G),l=uo(n.tag,"tag",G);if(u.byteLength!==12)throw new G("Invalid Initialization Vector length");if(l.byteLength!==16)throw new G("Invalid Authentication Tag length");return IE(ed(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return gOe(s.slice(-6),r,o)}async function CE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Li(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await zi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Ql(e):void 0;l&&$E(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{XW(u);let{apu:p,apv:m}=i;p!==void 0&&Ro(p,'"apu"'),m!==void 0&&Ro(m,'"apv"');let y=p??TE(o,"apu"),w=m??TE(o,"apv");YW(y,w);let b;i.epk!==void 0?b=await zi(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:R,y:T,crv:M,kty:K}=await S.exportKey("jwk",x),te=a==="direct-key-agreement",Ie=await JW(u,b,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),Te={x:R,crv:M,kty:K};if(K==="EC"&&(Te.y=T),f={epk:Te},p!==void 0&&(f.apu=nr(p)),m!==void 0&&(f.apv=nr(m)),te)return[Ie,void 0,f];u=Ie;break}case"RSA-OAEP":{SE(u),ZW(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await WW(m,s,p,u),f={p2c:p,p2s:nr(m)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await RE(ed(s.slice(0,-2)),l,u,p,new Uint8Array);d=m.ciphertext,f={iv:nr(m.iv),tag:nr(m.tag)}}}if(d??=await hOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,f]}function OE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ot('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new G('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function e5(t){if(typeof globalThis[t]>"u")throw new Ot(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function t5(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new G("Decompressed plaintext exceeded the configured limit")}return Gn(...n)}async function r5(t){return e5("CompressionStream"),t5(new CompressionStream("deflate-raw"),t)}async function n5(t,e){return e5("DecompressionStream"),t5(new DecompressionStream("deflate-raw"),t,e)}function o5(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new G("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new G("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new G("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new G("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new G("JWE AAD incorrect type");if(s!==void 0&&!vr(s))throw new G("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function i5(t){let e,r;try{let{header:o}=t;if(vr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function s5(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new G("JWE Encrypted Key incorrect type");if(r!==void 0&&!vr(r))throw new G("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new G("JOSE Header missing")}function eL(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=mf(e,G,"JWE Protected Header is invalid")),[s,uo(r,"ciphertext",G),o!==void 0?uo(o,"iv",G):void 0,n!==void 0?uo(n,"tag",G):void 0,gE((e??"")+(i!==void 0?`.${i}`:""),"aad",G)]}function DE(t){return[t&&_y("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&_y("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function tL(t,e,r,o=eL(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Bc(n,u,l))throw new G("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,m,y,w,b]=e,{encrypted_key:S}=t;Kc(G,vE,y,n,f),OE(f,n);let{alg:x,enc:R}=f;if(typeof x!="string"||!x)throw new G("missing JWE Algorithm (alg) in JWE Header");let T=qa[x];if(S===""&&(!T||!Li(T)))throw new G("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof R!="string"||!R))throw new G("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new Jl('"alg" (Algorithm) Header Parameter value not allowed');let K;if(M){if(R!==void 0)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new G("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new G("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(R))throw new Jl('"enc" (Encryption Algorithm) Header Parameter value not allowed');K=ed(R)}let te;if(S!==void 0)try{te=uo(S,"encrypted_key",G)}catch(Fe){if(!T||!Li(T))throw Fe;te=new Uint8Array}let Ie=!1;typeof r=="function"&&(r=await r(n,t),Ie=!0);let Te=T??Ui(x);Li(Te)&&te===void 0&&(te=new Uint8Array);let bt=await zi(Te.mode==="direct-encryption"?K:Te,r,"decrypt"),fe;if(Te.mode==="integrated-encryption")fe=await Te.decrypt(bt,te,i,c,n,f);else{let Fe=K,se;try{se=await QW(Te,Fe,bt,te,f,w),Li(Te)&&se instanceof Uint8Array&&se.byteLength<<3!==Fe.cekBits&&(se=Ql(Fe))}catch(tr){if(tr instanceof TypeError||tr instanceof G||tr instanceof Ot)throw tr;se=Ql(Fe)}fe=await IE(Fe,se,i,s,a,c)}if(f.zip==="DEF"){let Fe=b??25e4;if(Fe===0)throw new Ot('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Fe!==1/0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");fe=await n5(fe,Fe).catch(se=>{throw se instanceof G?se:new G("Failed to decompress plaintext",{cause:se})})}return{plaintext:fe,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:uo(d,"aad",G)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ie&&{key:bt}}}async function a5(t,e,r){if(t instanceof Uint8Array&&(t=ff.decode(t)),typeof t!="string")throw new G("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new G("Invalid Compact JWE");return tL({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Sy(t,e,r){return a5(t,DE(r),e)}async function rL(t,e,r){if(!vr(t))throw new G("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new G("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(vr))throw new G("JWE Recipients missing or incorrect type");if(!n.length)throw new G("JWE Recipients has no members");let i,s,a;try{i=DE(r),s=o5(t),a=eL(s)}catch{throw new Hc}let c=n.map(u=>i5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?qa[l]:void 0;if(d&&!Li(d))throw new G(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return s5(l),await tL(l,i,e,a)}catch{}throw new Hc}function NE(t,e,r){if(!Bc(t,e,r))throw new G("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function nL(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new G("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Ro(s,"JWE Additional Authenticated Data"),a!==void 0&&Ro(a,"JWE Content Encryption Key"),c!==void 0&&Ro(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Yl(G,o)[0],t[1]=o),n!==void 0&&(n=Yl(G,n)[0],t[2]=n),!r&&i!==void 0&&(i=Yl(G,i)[0],t[3]=i),u!==void 0&&!vr(u))throw new TypeError("JWE Key Management Parameters must be an object");NE(o,n,i);let d={...o,...n,...i};wE(G,o),Kc(G,vE,l,o,d),OE(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new G('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=qa[f];if(m?.mode==="integrated-encryption"){if(p!==void 0)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!="string"||!p)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,ed(p),m]}async function oL(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,m]=t,y=a,w=c,b=i??Ui(o.alg),S,x,R;b.mode==="integrated-encryption"?R=await zi(b,r,"encrypt"):[R,S,x]=await CE(b,n,r,o,d,p),x&&(m?w=w?{...w,...x}:x:y=y?{...y,...x}:x,NE(y,w,u));let T=y?nr(JSON.stringify(y)):"",M=l?.byteLength?nr(l):void 0,K=Yr(M?`${T}.${M}`:T),te=s;o.zip==="DEF"&&(te=await r5(te).catch(Fe=>{throw new G("Failed to compress plaintext",{cause:Fe})}));let Ie,Te,bt;b.mode==="integrated-encryption"?[S,Ie]=await b.encrypt(R,te,K,y,o,p):{ciphertext:Ie,tag:Te,iv:bt}=await RE(n,te,R,f,K);let fe={ciphertext:nr(Ie)};return bt&&(fe.iv=nr(bt)),Te&&(fe.tag=nr(Te)),S?.byteLength&&(fe.encrypted_key=nr(S)),M&&(fe.aad=M),y&&(fe.protected=T),u&&(fe.unprotected=u),w&&(fe.header=w),fe}async function c5(t,e,r){return oL(t,nL(t,r),e)}function u5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var iL=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Xo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Xo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},xy=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new iL(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Xo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Xo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new G("at least one recipient must be added");Ro(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[y,w,b,S]=m.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],R=nL(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,R,b]);let[{alg:T,enc:M},,K]=R;if(e&&K&&!Li(K))throw new G(`"${T}" alg may only have a single recipient`);if(!r)r=M;else if(r!==M)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Ui(m[0].alg);let[s,a,c]=i[0],u=e?Ql(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await oL(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let m=1;m<i.length;m++){let[y,[w,b,S],x]=i[m],R=y[2],[,T,M]=await CE(S,b,x,w,u,y[7]),K={encrypted_key:nr(T)};if(R||M){let te={...R,...M};M&&NE(y[1],te,y[3]),K.header=te}p.recipients.push(K)}return p}};var Ey=[["verify"],["sign"]];function sL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Ey}}function wf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:Ey,minRsaBits:2048}}function aL(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Ey}}function l5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Ey}}function cL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Ey}}var uL=by({HS256:sL(256),HS384:sL(384),HS512:sL(512),RS256:wf(256),RS384:wf(384),RS512:wf(512),PS256:wf(256,32),PS384:wf(384,48),PS512:wf(512,64),ES256:aL("P-256",256),ES384:aL("P-384",384),ES512:aL("P-521",512),EdDSA:l5(),Ed25519:l5(),"ML-DSA-44":cL(44),"ML-DSA-65":cL(65),"ML-DSA-87":cL(87)});function zE(t){let e=typeof t=="string"?uL[t]:void 0;if(!e)throw new Ot(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function d5(t){return[t&&_y("algorithms",t.algorithms),t?.crit]}function _Oe(t){return t===void 0?{}:mf(t,Xt,"JWS Protected Header is invalid")}function bOe(t){try{return Yr(t)}catch{throw new Xt("JWS Compact Serialization payload must use only ASCII characters")}}async function SOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??_Oe(i);if(!Bc(c,s))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=_E(c,Kc(Xt,yE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new Jl('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Xt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let m=zE(d),y=Gn(i!==void 0?Yr(i):new Uint8Array,Yr("."),typeof f=="string"?e[2]??=gE(f,"payload",Xt):f),w=uo(t.signature,"signature",Xt),b=await zi(m,r,"verify"),S=await Mi(b,m.subtle,"verify");m.minRsaBits&&hf(m.alg,S);let x=!1;try{x=await crypto.subtle.verify(m.signing,S,w,y)}catch{}if(!x)throw new hE;let R={payload:typeof f=="string"?uo(f,"payload",Xt):f};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),p?[{...R,key:b},l]:[R,l]}async function p5(t,e,r){if(t instanceof Uint8Array&&(t=ff.decode(t)),typeof t!="string")throw new Xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Xt("Invalid Compact JWS");return SOe({payload:n,protected:o,signature:i},e,r,bOe)}async function lL(t,e,r){let[o]=await p5(t,d5(r),e);return o}var _f=class{#e;constructor(e){Ro(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Xo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Xo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Xo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Xo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return u5(await c5([...this.#e],e,r))}};async function xOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=Yl(Xt,n);n=b[0],a=nr(b[1])}if(i!==void 0&&(i=Yl(Xt,i)[0]),!n&&!i)throw new Xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Bc(n,i))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};wE(Xt,n);let u=_E(n,Kc(Xt,yE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=zE(l),f="",p=o,m;if(u){let b=t[4];b?(f=b[0]??=nr(o),p=b[1]??=Yr(f)):(f=nr(o),m=pf.encode(`${a}.${f}`))}m??=Gn(Yr(a),Yr("."),p);let y=await Mi(await zi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&hf(d.alg,y);let w={signature:nr(new Uint8Array(await crypto.subtle.sign(d.signing,y,m))),payload:f};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function f5(t,e,r,o,n){let[i]=await xOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var $y=class{#e;#t;constructor(e){Ro(e,"payload"),this.#e=e}setProtectedHeader(e){return Xo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return f5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var dL='"alg" (Algorithm)';function pL(t='JWK "alg" (Algorithm) Parameter'){throw new Ot(`Invalid or unsupported ${t} value`)}function Ry(t,e){return(typeof t=="string"?uL[t]??qa[t]:void 0)??pL(e)}async function Wc(t){if(KU(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:nr(t)};if(!Zc(t))throw new TypeError(Fa(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var Va=(t,e)=>{if(typeof t!="string"||!t)throw new wy(`${e} missing or invalid`)};async function fL(t,e){let r;if(vr(t)){if(r=xE(t),typeof r.kty!="string")throw new TypeError(Fa(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(ZU(t))r=xE(await Wc(t));else throw new TypeError(Fa(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":Va(r.alg,'"alg" (Algorithm) Parameter'),Va(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Va(r.crv,'"crv" (Curve) Parameter'),Va(r.x,'"x" (X Coordinate) Parameter'),Va(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Va(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Va(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Va(r.e,'"e" (Exponent) Parameter'),Va(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new wy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ot('"kty" (Key Type) Parameter missing or unsupported')}let n=Yr(JSON.stringify(o));return nr(await mE(e,n))}async function Yo(t,e,r){if(!vr(t))throw new TypeError("JWK must be an object");let o=XU(t),n=EE(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return Xl(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return gf(Ry(e),o,n)}case"RSA":case"EC":case"OKP":return gf(Ry(e),o,n);default:throw new Ot('Unsupported "kty" (Key Type) Parameter value')}}function mL(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return mf(e,TypeError,r)}function EOe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ot("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Iy(t,e){let r=EE(e?.extractable),o=Ry(t,dL);o.secret&&pL(dL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ot("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ot(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:EOe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var y5=h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),v5=h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),m5=h.string().min(1).max(128),h5=h.string().min(1).max(16384),$Oe=h.discriminatedUnion("kind",[h.object({kind:h.literal("access_key"),accessKeyId:m5,secretAccessKey:h5}).strict(),h.object({kind:h.literal("session"),accessKeyId:m5,secretAccessKey:h5,sessionToken:h.string().min(1).max(16384),expiresAt:h.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),h.object({kind:h.literal("environment")}).strict()]),ROe=h.object({arn:v5,externalId:h.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Ga=h.object({authentication:$Oe,region:y5,role:ROe.optional()}).strict(),ME=h.object({accountId:h.string().regex(/^\d{12}$/),principalId:h.string().min(1).max(256),arn:h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),UE=Ga.extend({sourceIdentity:ME.optional(),identity:ME.optional()}).strict();function bf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function g5(t){return{...t,arn:bf(t.arn)}}function w5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:g5(t.sourceIdentity)}:{},...t.identity?{identity:g5(t.identity)}:{}}}var LE=h.object({authentication:h.enum(["access_key","session","environment"]),region:y5,sourceAccountId:h.string().regex(/^\d{12}$/).optional(),sourceArn:h.string().max(2e3).optional(),roleArn:v5.optional(),expiresAt:h.number().int().positive().optional()}).strict();function _5(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var b5=h.object({method:h.enum(["GET","POST","PUT","DELETE","PATCH"]),path:h.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),Ay=h.object({account:h.string().min(1),identities:h.array(h.string()),user:h.string().nullable(),description:h.string().nullable(),roles:h.array(h.string()).nullable(),credentialId:h.number().int().positive(),rules:h.array(b5),allowedIPs:h.array(h.string()).nullable(),expiresAt:h.number().nullable()}).strict();function S5(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return b5.parse({method:r[1],path:r[2]})})}typeof window<"u"&&h.config({jitless:!0});var E=h.uuid(),me=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Ae=h.iso.datetime(),wr=h.json(),Lt=h.record(h.string(),wr),x5=h.enum(["ja","en"]),E5=h.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var $5=h.enum(["variable","connection","service","method","app","object","environment","function"]),bn=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),IOe=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:E}).strict(),GE=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return IOe.safeParse(mL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Io=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:E,epk:bn.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Swt=h.object({id:E,name:me,publicKey:bn}),Jc=h.object({id:E,name:me,owner:h.object({id:E,name:me}).nullable(),createdAt:Ae,permissions:h.array(E5),createKinds:h.array($5),publicKey:bn.nullable()}),R5=h.object({id:E,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:Ae,lastUsedAt:Ae.nullable(),expiresAt:Ae.nullable(),canOpen:h.boolean()}),I5=h.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),AOe=h.object({subjectId:E,relation:I5,objectId:E}).strict(),xwt=AOe.extend({objectType:h.enum(["principal",...$5.options]),subjectName:me,objectName:me,createdAt:Ae}),Ewt=h.object({error:h.object({code:h.string(),message:h.string(),details:wr.optional()})}),$wt=h.object({ok:h.literal(!0)}),POe=h.object({value:h.string().min(1).max(200),label:h.string().min(1).max(200),values:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).default({})}).strict(),hL=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional(),choices:h.array(POe).min(1).max(100).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),gL=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),A5=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),required:h.array(h.string()).optional(),separator:h.string().default(" "),docs:h.url().optional()}),td=h.string().min(1).max(4096),qE=h.union([h.string(),h.array(h.string()).min(1)]),kOe=h.object({application:h.enum(["required","implicit"]).default("required"),grantType:h.enum(["authorization_code","client_credentials"]).optional(),issuer:h.url().optional(),authorizeUrl:td.optional(),tokenUrl:td,identity:h.object({url:td.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:qE.default("/id"),name:qE.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),revoke:h.object({url:td,style:h.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:h.enum(["body","basic","none"]).optional()}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:A5.default({default:[],separator:" "}),fields:h.array(hL).default([]),outputs:gL.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),TOe=h.object({fields:h.array(hL).min(1),outputs:gL,identity:h.object({url:td,headers:h.record(h.string(),h.string()),id:qE,name:qE}).strict().optional(),console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}),yL=h.enum(["oauth","token","aws","ovh"]),COe=h.object({hint:h.string().optional()}).strict(),OOe=h.object({authorization:h.enum(["api_key","consumer_key"]),apiBaseUrl:td,fields:h.array(hL).min(1),scopes:A5.default({default:[],separator:`
128
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function eZ(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;eZ(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var tZ=new Set(["type","properties","required","additionalProperties"]),Y9=["oneOf","anyOf"];function Q9(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function Xz(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!tZ.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??Q9(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:Xz(a)??{allOf:a};Zr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=Q9(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function bCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of tZ)if(n in t)return;let r=e.filter(n=>Y9.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Xz(e);else{let n=r[0],i=Y9.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>Xz([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,ty(t,o))}function jc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):ty(u,m),ty(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&p.def)for(let w in u)w==="$ref"||w==="allOf"||w in p.def&&JSON.stringify(u[w])===JSON.stringify(p.def[w])&&delete u[w]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())eZ(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])bCe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}ty(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Zr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:ef(e,"input",t.processors),output:ef(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function qn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return qn(o.element,r);if(o.type==="set")return qn(o.valueType,r);if(o.type==="lazy")return qn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return qn(o.innerType,r);if(o.type==="intersection")return qn(o.left,r)||qn(o.right,r);if(o.type==="record"||o.type==="map")return qn(o.keyType,r)||qn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:qn(o.in,r)||qn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(qn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(qn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(qn(n,r))return!0;return!!(o.rest&&qn(o.rest,r))}return!1}var Yz=(t,e={})=>r=>{let o=Uc({...r,processors:e});return Rt(t,o),Lc(o,t),jc(o,t)},ef=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Uc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Lc(s,t),jc(s,t)};var tf=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},rf=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},rZ=(t,e)=>{tf(t,"minimum",e),rf(t,"maximum",e)},sZ=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},aZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},cZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},uZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},nZ=(t,e)=>tf(t,"minimum",e.minimum),oZ=(t,e)=>rf(t,"maximum",e.maximum),iZ=t=>(e,r)=>{uZ(e,r.format);let[o,n]=t[r.format];tf(e,"minimum",o),rf(e,"maximum",n)},SCe={greater_than:(t,e)=>tf(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>rf(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>sZ(t,e.value),number_format:iZ(ig),bigint_format:iZ(sg),min_length:nZ,max_length:oZ,length_equals:(t,e)=>rZ(t,e.length),min_size:nZ,max_size:oZ,size_equals:(t,e)=>rZ(t,e.size),string_format:(t,e)=>{uZ(t,e.format),e.pattern&&aZ(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>cZ(t,e.mime)};function kr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)SCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&tf(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&tf(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&rf(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&rf(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&sZ(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&cZ(e,n.mime);for(let i of n.patterns??[])aZ(e,i);return e}var xCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ECe=new Map([[HS,L1],[_g,j1]]),lZ=t=>ECe.get(t)??t,tM=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=kr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=xCe[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(lZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},rM=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=kr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let b of a)Number.isFinite(b)&&b!==0?m.add(Math.abs(b)):Pr(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=m;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},nM=(t,e,r,o)=>{r.type="boolean"},oM=(t,e,r,o)=>{Pr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},iM=(t,e,r,o)=>{Pr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},sM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},aM=(t,e,r,o)=>{Pr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},cM=(t,e,r,o)=>{Pr(t,e,r,o,"Void cannot be represented in JSON Schema")},uM=(t,e,r,o)=>{r.not={}},lM=(t,e,r,o)=>{},dM=(t,e,r,o)=>{},pM=(t,e,r,o)=>{Pr(t,e,r,o,"Date cannot be represented in JSON Schema")},fM=(t,e,r,o)=>{let n=t._zod.def,i=gp(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},mM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Pr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Pr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},hM=(t,e,r,o)=>{Pr(t,e,r,o,"NaN cannot be represented in JSON Schema")},gM=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},yM=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=kr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},vM=(t,e,r,o)=>{r.type="boolean"},wM=(t,e,r,o)=>{Pr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},_M=(t,e,r,o)=>{Pr(t,e,r,o,"Function types cannot be represented in JSON Schema")},bM=(t,e,r,o)=>{Pr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},SM=(t,e,r,o)=>{Pr(t,e,r,o,"Map cannot be represented in JSON Schema")},xM=(t,e,r,o)=>{Pr(t,e,r,o,"Set cannot be represented in JSON Schema")},EM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=kr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function ry(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?ry(e.out):e.type==="catch"?ry(e.innerType):t._zod.optin}var $M=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Pr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Zr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?ry(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},D0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},RM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},IM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?ry(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:m}=kr(t);typeof p=="number"&&(n.minItems=p),typeof m=="number"&&(n.maxItems=m)};function Qz(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let y=Qz(t,m,r);return y===m?e:y}for(let m of["anyOf","oneOf"]){let y=e[m];if(!Array.isArray(y))continue;let w=y.map(b=>Qz(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[m]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Ua:fg).source)),p}var eM=new WeakMap;function $Ce(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of eM.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=Qz(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var AM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=kr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Zr(n.patternProperties,lZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=eM.get(e);l||(l=[],eM.set(e,l),e.deferred.push(()=>$Ce(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&ry(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},PM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},kM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},TM=Symbol();function dZ(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Pr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),TM):JSON.parse(s)}var CM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=dZ(n.defaultValue,t,e,r,o);s!==TM&&(r.default=s)},OM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=dZ(n.defaultValue,t,e,r,o);s!==TM&&(r._prefault=s)},DM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Pr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},NM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},zM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},MM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},N0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},UM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},O0={string:tM,number:rM,boolean:nM,bigint:oM,symbol:iM,null:sM,undefined:aM,void:cM,never:uM,any:lM,unknown:dM,date:pM,enum:fM,literal:mM,nan:hM,template_literal:gM,file:yM,success:vM,custom:wM,function:_M,transform:bM,map:SM,set:xM,array:EM,object:$M,union:D0,intersection:RM,tuple:IM,record:AM,nullable:PM,nonoptional:kM,default:CM,prefault:OM,catch:DM,pipe:NM,readonly:zM,promise:MM,optional:N0,lazy:UM};function Gl(t,e){if("_idmap"in t){let o=t,n=Uc({...e,processors:O0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Lc(n,l),Zr(s,u,jc(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Uc({...e,processors:O0});return Rt(t,r),Lc(r,t),jc(r,t)}var z0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Uc({processors:O0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Lc(this.ctx,e);let o=jc(this.ctx,e),{"~standard":n,...i}=o;return i}};var pZ={};var df={};Ht(df,{ZodAny:()=>nU,ZodArray:()=>aU,ZodBase64:()=>tE,ZodBase64URL:()=>rE,ZodBigInt:()=>uf,ZodBigIntFormat:()=>iE,ZodBoolean:()=>cf,ZodCIDRv4:()=>Q0,ZodCIDRv6:()=>eE,ZodCUID:()=>B0,ZodCUID2:()=>K0,ZodCatch:()=>RU,ZodCodec:()=>dy,ZodCreditCard:()=>YM,ZodCustom:()=>py,ZodCustomStringFormat:()=>Bl,ZodDate:()=>sy,ZodDefault:()=>_U,ZodDiscriminatedUnion:()=>uU,ZodE164:()=>nE,ZodEmail:()=>q0,ZodEmoji:()=>G0,ZodEnum:()=>of,ZodExactOptional:()=>cE,ZodFile:()=>gU,ZodFunction:()=>zU,ZodGUID:()=>V0,ZodIBAN:()=>QM,ZodIPv4:()=>X0,ZodIPv6:()=>Y0,ZodISODate:()=>qc,ZodISODateTime:()=>Fc,ZodISODuration:()=>Gc,ZodISOTime:()=>Vc,ZodInstanceOf:()=>LU,ZodIntersection:()=>lU,ZodJWT:()=>oE,ZodKSUID:()=>J0,ZodLazy:()=>OU,ZodLiteral:()=>hU,ZodMAC:()=>XM,ZodMap:()=>fU,ZodNaN:()=>AU,ZodNanoID:()=>H0,ZodNever:()=>iU,ZodNonOptional:()=>uE,ZodNull:()=>rU,ZodNullable:()=>wU,ZodNumber:()=>af,ZodNumberFormat:()=>Kl,ZodObject:()=>ay,ZodOptional:()=>Zl,ZodPipe:()=>ly,ZodPrefault:()=>SU,ZodPreprocess:()=>PU,ZodPromise:()=>NU,ZodReadonly:()=>kU,ZodRecord:()=>nf,ZodSet:()=>mU,ZodString:()=>sf,ZodStringFormat:()=>Tt,ZodSuccess:()=>$U,ZodSymbol:()=>eU,ZodTemplateLiteral:()=>CU,ZodTransform:()=>yU,ZodTuple:()=>dU,ZodType:()=>Ce,ZodULID:()=>Z0,ZodURL:()=>oy,ZodUUID:()=>Ts,ZodUndefined:()=>tU,ZodUnion:()=>cy,ZodUnknown:()=>oU,ZodVoid:()=>sU,ZodXID:()=>W0,ZodXor:()=>cU,_ZodString:()=>F0,_default:()=>bU,_function:()=>_W,any:()=>tW,array:()=>qe,base64:()=>NZ,base64url:()=>zZ,bigint:()=>JZ,boolean:()=>hr,catch:()=>IU,check:()=>bW,cidrv4:()=>OZ,cidrv6:()=>DZ,codec:()=>gW,creditCard:()=>UZ,cuid:()=>$Z,cuid2:()=>RZ,currencyCode:()=>GZ,custom:()=>lE,date:()=>nW,describe:()=>SW,discriminatedUnion:()=>uy,e164:()=>MZ,email:()=>hZ,emoji:()=>xZ,enum:()=>Xr,exactOptional:()=>vU,file:()=>pW,float32:()=>BZ,float64:()=>KZ,function:()=>_W,guid:()=>gZ,hash:()=>HZ,hex:()=>VZ,hostname:()=>qZ,httpUrl:()=>SZ,iban:()=>LZ,instanceof:()=>EW,int:()=>L0,int32:()=>ZZ,int64:()=>XZ,intersection:()=>lf,invertCodec:()=>yW,ipv4:()=>kZ,ipv6:()=>CZ,json:()=>RW,jwt:()=>jZ,keyof:()=>oW,ksuid:()=>PZ,lazy:()=>DU,literal:()=>ae,looseObject:()=>Jr,looseRecord:()=>cW,mac:()=>TZ,map:()=>uW,meta:()=>xW,nan:()=>hW,nanoid:()=>EZ,nativeEnum:()=>dW,never:()=>sE,nonoptional:()=>EU,null:()=>iy,nullable:()=>ny,nullish:()=>fW,number:()=>yt,object:()=>X,optional:()=>kt,partialRecord:()=>aW,pipe:()=>j0,prefault:()=>xU,preprocess:()=>fy,promise:()=>wW,readonly:()=>TU,record:()=>Ct,refine:()=>MU,set:()=>lW,strictObject:()=>iW,string:()=>O,stringFormat:()=>FZ,stringbool:()=>$W,success:()=>mW,superRefine:()=>UU,symbol:()=>QZ,templateLiteral:()=>vW,transform:()=>aE,tuple:()=>pU,uint32:()=>WZ,uint64:()=>YZ,ulid:()=>IZ,undefined:()=>eW,union:()=>It,unknown:()=>Ut,url:()=>bZ,uuid:()=>yZ,uuidv4:()=>vZ,uuidv6:()=>wZ,uuidv7:()=>_Z,void:()=>rW,xid:()=>AZ,xor:()=>sW});var M0={};Ht(M0,{endsWith:()=>Bp,gt:()=>Ps,gte:()=>$o,includes:()=>Gp,length:()=>Vl,lowercase:()=>qp,lt:()=>As,lte:()=>Eo,maxLength:()=>ql,maxSize:()=>zc,mime:()=>Zp,minLength:()=>La,minSize:()=>ks,multipleOf:()=>Nc,negative:()=>S0,nonnegative:()=>E0,nonpositive:()=>x0,normalize:()=>Wp,overwrite:()=>Di,positive:()=>b0,properties:()=>Kp,property:()=>$0,regex:()=>Fp,size:()=>Fl,slugify:()=>Qp,startsWith:()=>Hp,toLowerCase:()=>Xp,toUpperCase:()=>Yp,trim:()=>Jp,uppercase:()=>Vp});var fZ=new WeakSet([Object.prototype,Error.prototype]);function U0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var mZ=(t,e)=>{w1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);fZ.has(r)||(fZ.add(r),U0(r,"format",o=>n=>dg(o,n)),U0(r,"flatten",o=>n=>lg(o,n)),U0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,yp,2)}),U0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,yp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ICe=$("ZodError",mZ),co=$("ZodError",mZ,void 0,{Parent:Error});var LM=Sp(co),jM=xp(co),FM=Ep(co),qM=Rp(co),VM=sS(co),GM=aS(co),HM=cS(co),BM=uS(co),KM=lS(co),ZM=dS(co),WM=pS(co),JM=fS(co);function PCe(){zr.localeError||cr(Gx())}function Hl(){zr.memoizer||cr({memoizer:Ag()})}var Ce=$("ZodType",(t,e)=>(PCe(),be.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(MU(t,e))},superRefine(t,e){return this.check(UU(t,e))},overwrite(t){return this.check(Di(t))},optional(){return kt(this)},exactOptional(){return vU(this)},nullable(){return ny(this)},nullish(){return kt(ny(this))},nonoptional(t){return EU(this,t)},array(){return qe(this)},or(t){return It([this,t])},and(t){return lf(this,t)},transform(t){return j0(this,aE(t))},default(t){return bU(this,t)},prefault(t){return xU(this,t)},catch(t){return IU(this,t)},pipe(t){return j0(this,t)},readonly(){return TU(this)},describe(t){let e=this.clone();return Wr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Wr.get(this);let e=this.clone();return Wr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return D.hide(this,"~standard",{...ES(this),jsonSchema:{input:ef(this,"input"),output:ef(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return LM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await jM(this,e,r,{callee:t})},safeParse(t,e){return FM(this,t,e)},async safeParseAsync(t,e){return qM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Ap(this,t,e)},validateAsync(t,e){return Pp(this,t,e)},encode:function t(e,r){return VM(this,e,r,{callee:t})},decode:function t(e,r){return GM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await HM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await BM(this,e,r,{callee:t})},safeEncode(t,e){return KM(this,t,e)},safeDecode(t,e){return ZM(this,t,e)},async safeEncodeAsync(t,e){return WM(this,t,e)},async safeDecodeAsync(t,e){return JM(this,t,e)},toJSONSchema(t){return Yz(this,{})(t)},get description(){return Wr.get(this)?.description},get _def(){return this._zod.def}}),F0=$("_ZodString",(t,e)=>{Dc.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tM(t,r,o,n)},D.derived({format:t=>kr(t).format??null,minLength:t=>kr(t).minimum??null,maxLength:t=>kr(t).maximum??null},{regex(...t){return this.check(Fp(...t))},includes(...t){return this.check(Gp(...t))},startsWith(...t){return this.check(Hp(...t))},endsWith(...t){return this.check(Bp(...t))},min(...t){return this.check(La(...t))},max(...t){return this.check(ql(...t))},length(...t){return this.check(Vl(...t))},nonempty(...t){return this.check(La(1,...t))},lowercase(t){return this.check(qp(t))},uppercase(t){return this.check(Vp(t))},trim(){return this.check(Jp())},normalize(...t){return this.check(Wp(...t))},toLowerCase(){return this.check(Xp())},toUpperCase(){return this.check(Yp())},slugify(){return this.check(Qp())}})),sf=$("ZodString",(t,e)=>{Dc.init(t,e),F0.init(t,e)},{email(t){return this.check(kg(q0,t))},url(t){return this.check(jp(oy,t))},jwt(t){return this.check(Jg(oE,t))},emoji(t){return this.check(zg(G0,t))},guid(t){return this.check(Tg(V0,t))},uuid(t){return this.check(Cg(Ts,t))},uuidv4(t){return this.check(Og(Ts,t))},uuidv6(t){return this.check(Dg(Ts,t))},uuidv7(t){return this.check(Ng(Ts,t))},nanoid(t){return this.check(Mg(H0,t))},cuid(t){return this.check(Ug(B0,t))},cuid2(t){return this.check(Lg(K0,t))},ulid(t){return this.check(jg(Z0,t))},base64(t){return this.check(Kg(tE,t))},base64url(t){return this.check(Zg(rE,t))},xid(t){return this.check(Fg(W0,t))},ksuid(t){return this.check(qg(J0,t))},ipv4(t){return this.check(Vg(X0,t))},ipv6(t){return this.check(Gg(Y0,t))},cidrv4(t){return this.check(Hg(Q0,t))},cidrv6(t){return this.check(Bg(eE,t))},e164(t){return this.check(Wg(nE,t))},datetime(t){return this.check(Xg(Fc,t))},date(t){return this.check(Yg(qc,t))},time(t){return this.check(Qg(Vc,t))},duration(t){return this.check(ey(Gc,t))}});function O(t){return Yx(sf,t)}var Tt=$("ZodStringFormat",(t,e)=>{St.init(t,e),F0.init(t,e)}),Fc=$("ZodISODateTime",(t,e)=>{Az.init(t,e),Tt.init(t,e)}),qc=$("ZodISODate",(t,e)=>{Pz.init(t,e),Tt.init(t,e)}),Vc=$("ZodISOTime",(t,e)=>{kz.init(t,e),Tt.init(t,e)}),Gc=$("ZodISODuration",(t,e)=>{Tz.init(t,e),Tt.init(t,e)}),q0=$("ZodEmail",(t,e)=>{IS.init(t,e),Tt.init(t,e)});function hZ(t){return kg(q0,t)}var V0=$("ZodGUID",(t,e)=>{$S.init(t,e),Tt.init(t,e)});function gZ(t){return Tg(V0,t)}var Ts=$("ZodUUID",(t,e)=>{RS.init(t,e),Tt.init(t,e)});function yZ(t){return Cg(Ts,t)}function vZ(t){return Og(Ts,t)}function wZ(t){return Dg(Ts,t)}function _Z(t){return Ng(Ts,t)}var oy=$("ZodURL",(t,e)=>{TS.init(t,e),Tt.init(t,e)});function bZ(t){return jp(oy,t)}function SZ(t){return jp(oy,{protocol:pg,hostname:q1,...D.normalizeParams(t)})}var G0=$("ZodEmoji",(t,e)=>{CS.init(t,e),Tt.init(t,e)});function xZ(t){return zg(G0,t)}var H0=$("ZodNanoID",(t,e)=>{OS.init(t,e),Tt.init(t,e)});function EZ(t){return Mg(H0,t)}var B0=$("ZodCUID",(t,e)=>{DS.init(t,e),Tt.init(t,e)});function $Z(t){return Ug(B0,t)}var K0=$("ZodCUID2",(t,e)=>{NS.init(t,e),Tt.init(t,e)});function RZ(t){return Lg(K0,t)}var Z0=$("ZodULID",(t,e)=>{zS.init(t,e),Tt.init(t,e)});function IZ(t){return jg(Z0,t)}var W0=$("ZodXID",(t,e)=>{MS.init(t,e),Tt.init(t,e)});function AZ(t){return Fg(W0,t)}var J0=$("ZodKSUID",(t,e)=>{US.init(t,e),Tt.init(t,e)});function PZ(t){return qg(J0,t)}var X0=$("ZodIPv4",(t,e)=>{LS.init(t,e),Tt.init(t,e)});function kZ(t){return Vg(X0,t)}var XM=$("ZodMAC",(t,e)=>{FS.init(t,e),Tt.init(t,e)});function TZ(t){return Qx(XM,t)}var Y0=$("ZodIPv6",(t,e)=>{jS.init(t,e),Tt.init(t,e)});function CZ(t){return Gg(Y0,t)}var Q0=$("ZodCIDRv4",(t,e)=>{qS.init(t,e),Tt.init(t,e)});function OZ(t){return Hg(Q0,t)}var eE=$("ZodCIDRv6",(t,e)=>{GS.init(t,e),Tt.init(t,e)});function DZ(t){return Bg(eE,t)}var tE=$("ZodBase64",(t,e)=>{BS.init(t,e),Tt.init(t,e)});function NZ(t){return Kg(tE,t)}var rE=$("ZodBase64URL",(t,e)=>{ZS.init(t,e),Tt.init(t,e)});function zZ(t){return Zg(rE,t)}var nE=$("ZodE164",(t,e)=>{WS.init(t,e),Tt.init(t,e)});function MZ(t){return Wg(nE,t)}var YM=$("ZodCreditCard",(t,e)=>{XS.init(t,e),Tt.init(t,e)});function UZ(t){return e0(YM,t)}var QM=$("ZodIBAN",(t,e)=>{QS.init(t,e),Tt.init(t,e)});function LZ(t){return t0(QM,t)}var oE=$("ZodJWT",(t,e)=>{tx.init(t,e),Tt.init(t,e)});function jZ(t){return Jg(oE,t)}var Bl=$("ZodCustomStringFormat",(t,e)=>{rx.init(t,e),Tt.init(t,e)});function FZ(t,e,r={}){return Mc(Bl,t,e,r)}function qZ(t){return Mc(Bl,"hostname",F1,t)}function VZ(t){return Mc(Bl,"hex",rz,t)}function GZ(t){return Mc(Bl,"currency_code",G1,t)}function HZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=xo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Mc(Bl,o,n,e)}var af=$("ZodNumber",(t,e)=>{bg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rM(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=kr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=kr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=kr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>kr(t).format??null},{gt(t,e){return this.check(Ps(t,e))},gte(t,e){return this.check($o(t,e))},min(t,e){return this.check($o(t,e))},lt(t,e){return this.check(As(t,e))},lte(t,e){return this.check(Eo(t,e))},max(t,e){return this.check(Eo(t,e))},int(t){return this.check(L0(t))},safe(t){return this.check(L0(t))},positive(t){return this.check(Ps(0,t))},nonnegative(t){return this.check($o(0,t))},negative(t){return this.check(As(0,t))},nonpositive(t){return this.check(Eo(0,t))},multipleOf(t,e){return this.check(Nc(t,e))},step(t,e){return this.check(Nc(t,e))},finite(){return this}}));function yt(t){return r0(af,t)}var Kl=$("ZodNumberFormat",(t,e)=>{nx.init(t,e),af.init(t,e)});function L0(t){return n0(Kl,t)}function BZ(t){return o0(Kl,t)}function KZ(t){return i0(Kl,t)}function ZZ(t){return s0(Kl,t)}function WZ(t){return a0(Kl,t)}var cf=$("ZodBoolean",(t,e)=>{Cp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nM(t,r,o,n)});function hr(t){return c0(cf,t)}var uf=$("ZodBigInt",(t,e)=>{Sg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oM(t,r,o,n)},D.derived({minValue:t=>kr(t).minimum??null,maxValue:t=>kr(t).maximum??null,format:t=>kr(t).format??null},{gte(t,e){return this.check($o(t,e))},min(t,e){return this.check($o(t,e))},gt(t,e){return this.check(Ps(t,e))},lt(t,e){return this.check(As(t,e))},lte(t,e){return this.check(Eo(t,e))},max(t,e){return this.check(Eo(t,e))},positive(t){return this.check(Ps(BigInt(0),t))},negative(t){return this.check(As(BigInt(0),t))},nonpositive(t){return this.check(Eo(BigInt(0),t))},nonnegative(t){return this.check($o(BigInt(0),t))},multipleOf(t,e){return this.check(Nc(t,e))}}));function JZ(t){return u0(uf,t)}var iE=$("ZodBigIntFormat",(t,e)=>{ox.init(t,e),uf.init(t,e)});function XZ(t){return l0(iE,t)}function YZ(t){return d0(iE,t)}var eU=$("ZodSymbol",(t,e)=>{ix.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iM(t,r,o,n)});function QZ(t){return p0(eU,t)}var tU=$("ZodUndefined",(t,e)=>{sx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aM(t,r,o,n)});function eW(t){return f0(tU,t)}var rU=$("ZodNull",(t,e)=>{ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sM(t,r,o,n)});function iy(t){return m0(rU,t)}var nU=$("ZodAny",(t,e)=>{cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n)});function tW(){return h0(nU)}var oU=$("ZodUnknown",(t,e)=>{ux.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n)});function Ut(){return g0(oU)}var iU=$("ZodNever",(t,e)=>{lx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n)});function sE(t){return y0(iU,t)}var sU=$("ZodVoid",(t,e)=>{dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cM(t,r,o,n)});function rW(t){return v0(sU,t)}var sy=$("ZodDate",(t,e)=>{px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pM(t,r,o,n),t.min=(r,o)=>t.check($o(r,o)),t.max=(r,o)=>t.check(Eo(r,o))},D.derived({minDate:t=>{let{minimum:e}=kr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=kr(t);return e?new Date(e):null}},{}));function nW(t){return w0(sy,t)}var aU=$("ZodArray",(t,e)=>{Hl(),fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(La(t,e))},nonempty(t){return this.check(La(1,t))},max(t,e){return this.check(ql(t,e))},length(t,e){return this.check(Vl(t,e))},unwrap(){return this.element}});function qe(t,e){return Jz(aU,t,e)}function oW(t){let e=t._zod.def.shape;return Xr(Object.keys(e))}var ay=$("ZodObject",(t,e)=>{Hl(),Cz.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$M(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Xr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:sE()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return D.extend(this,t)},safeExtend(t){return D.safeExtend(this,t)},merge(t){return D.merge(this,t)},pick(t){return D.pick(this,t)},omit(t){return D.omit(this,t)},partial(...t){return D.partial(Zl,this,t[0])},exactPartial(...t){return D.partial(cE,this,t[0],"exactPartial")},required(...t){return D.required(uE,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new ay(r)}function iW(t,e){return new ay({type:"object",shape:t,catchall:sE(),...D.normalizeParams(e)})}function Jr(t,e){return new ay({type:"object",shape:t,catchall:Ut(),...D.normalizeParams(e)})}var cy=$("ZodUnion",(t,e)=>{Op.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>D0(t,r,o,n),t.options=e.options});function It(t,e){return new cy({type:"union",options:t,...D.normalizeParams(e)})}var cU=$("ZodXor",(t,e)=>{cy.init(t,e),hx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>D0(t,r,o,n),t.options=e.options});function sW(t,e){return new cU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var uU=$("ZodDiscriminatedUnion",(t,e)=>{cy.init(t,e),gx.init(t,e)});function uy(t,e,r){return new uU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var lU=$("ZodIntersection",(t,e)=>{yx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RM(t,r,o,n)});function lf(t,e){return new lU({type:"intersection",left:t,right:e})}var dU=$("ZodTuple",(t,e)=>{Hl(),xg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Zl({type:"optional",innerType:e}))})}});function pU(t,e,r){let o=e instanceof be,n=o?r:e,i=o?e:null;return new dU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var nf=$("ZodRecord",(t,e)=>{Hl(),vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Ct(t,e,r){return!e||!e._zod?new nf({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new nf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function aW(t,e,r){return new nf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function cW(t,e,r){return new nf({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var fU=$("ZodMap",(t,e)=>{Hl(),wx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(ks(...r)),t.nonempty=r=>t.check(ks(1,r)),t.max=(...r)=>t.check(zc(...r)),t.size=(...r)=>t.check(Fl(...r))});function uW(t,e,r){return new fU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var mU=$("ZodSet",(t,e)=>{Hl(),_x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n),t.min=(...r)=>t.check(ks(...r)),t.nonempty=r=>t.check(ks(1,r)),t.max=(...r)=>t.check(zc(...r)),t.size=(...r)=>t.check(Fl(...r))});function lW(t,e){return new mU({type:"set",valueType:t,...D.normalizeParams(e)})}var of=$("ZodEnum",(t,e)=>{bx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(o,n,i)=>fM(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new of({...e,checks:[],...D.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new of({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Xr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new of({type:"enum",entries:r,...D.normalizeParams(e)})}function dW(t,e){return new of({type:"enum",entries:t,...D.normalizeParams(e)})}var hU=$("ZodLiteral",(t,e)=>{Sx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ae(t,e){return new hU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var gU=$("ZodFile",(t,e)=>{xx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n),t.min=(r,o)=>t.check(ks(r,o)),t.max=(r,o)=>t.check(zc(r,o)),t.mime=(r,o)=>t.check(Zp(Array.isArray(r)?r:[r],o))});function pW(t){return R0(gU,t)}var yU=$("ZodTransform",(t,e)=>{Hl(),Ex.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Oc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(D.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(D.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function aE(t){return new yU({type:"transform",transform:t})}var Zl=$("ZodOptional",(t,e)=>{Eg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function kt(t){return new Zl({type:"optional",innerType:t})}var cE=$("ZodExactOptional",(t,e)=>{$x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function vU(t){return new cE({type:"optional",innerType:t})}var wU=$("ZodNullable",(t,e)=>{Rx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ny(t){return new wU({type:"nullable",innerType:t})}function fW(t){return kt(ny(t))}var _U=$("ZodDefault",(t,e)=>{Ix.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function bU(t,e){return new _U({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var SU=$("ZodPrefault",(t,e)=>{Ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function xU(t,e){return new SU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var uE=$("ZodNonOptional",(t,e)=>{Px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function EU(t,e){return new uE({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var $U=$("ZodSuccess",(t,e)=>{kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function mW(t){return new $U({type:"success",innerType:t})}var RU=$("ZodCatch",(t,e)=>{Tx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>DM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function IU(t,e){return new RU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var AU=$("ZodNaN",(t,e)=>{Cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n)});function hW(t){return _0(AU,t)}var ly=$("ZodPipe",(t,e)=>{$g.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>NM(t,r,o,n),t.in=e.in,t.out=e.out});function j0(t,e){return new ly({type:"pipe",in:t,out:e})}var dy=$("ZodCodec",(t,e)=>{ly.init(t,e),Dp.init(t,e)});function gW(t,e,r){return new dy({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function yW(t){let e=t._zod.def;return new dy({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var PU=$("ZodPreprocess",(t,e)=>{ly.init(t,e),Dz.init(t,e)}),kU=$("ZodReadonly",(t,e)=>{Ox.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function TU(t){return new kU({type:"readonly",innerType:t})}var CU=$("ZodTemplateLiteral",(t,e)=>{Dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n)});function vW(t,e){return new CU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var OU=$("ZodLazy",(t,e)=>{Np.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>UM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function DU(t){return new OU({type:"lazy",getter:t})}var NU=$("ZodPromise",(t,e)=>{zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>MM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wW(t){return new NU({type:"promise",innerType:t})}var zU=$("ZodFunction",(t,e)=>{Nx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n)});function _W(t){return new zU({type:"function",input:Array.isArray(t?.input)?pU(t?.input):t?.input??qe(Ut()),output:t?.output??Ut()})}var py=$("ZodCustom",(t,e)=>{Mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n)});function bW(t){let e=new Pt({check:"custom"});return e._zod.check=t,e}function lE(t,e){return I0(py,t??(()=>!0),e)}function MU(t,e={}){return A0(py,t,e)}function UU(t,e){return P0(t,e)}var SW=k0,xW=T0,LU=$("ZodInstanceOf",(t,e)=>{py.init(t,e)},{properties(t,e){return this.check(Kp(t,e))}});function EW(t,e={}){let r=new LU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...D.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var $W=(...t)=>C0({Codec:dy,Boolean:cf,String:sf},...t);function RW(t){let e=DU(()=>It([O(t),yt(),hr(),iy(),qe(e),Ct(O(),e)]));return e}function fy(t,e){return new PU({type:"pipe",in:aE(t),out:e})}var kCe={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function TCe(t){cr({customError:t})}function CCe(){return cr().customError}var jU;jU||(jU={});var Wl={};Ht(Wl,{ZodISODate:()=>qc,ZodISODateTime:()=>Fc,ZodISODuration:()=>Gc,ZodISOTime:()=>Vc,date:()=>DCe,datetime:()=>OCe,duration:()=>zCe,time:()=>NCe});function OCe(t){return Xg(Fc,t)}function DCe(t){return Yg(qc,t)}function NCe(t){return Qg(Vc,t)}function zCe(t){return ey(Gc,t)}var W={...df,...M0,iso:Wl},MCe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function UCe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function IW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function LCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jCe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:LCe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function FCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function FU(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=FU(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=FU(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var qCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),VCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function my(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(my):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>qCe.has(e)?my(r):!VCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(my))}function AW(t){return t===1?"element":"elements"}function GCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=FU(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${AW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${AW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function PW(t,e){if(t!==!1)return t===void 0||t===!0?W.any():Vn(t,e)}var HCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function kW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return W.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=jCe(n,e),s=Vn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return W.null();if(n.length===0)return W.never();if(n.length===1)return W.literal(n[0]);if(n.every(s=>typeof s=="string"))return W.enum(n);let i=n.map(s=>W.literal(s));return i.length<2?i[0]:W.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return W.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return kW(s,e)});return n.length===0?W.never():n.length===1?n[0]:W.union(n)}if(!r)return W.any();let o;switch(r){case"string":{let n=W.string();if(t.format){let i=t.format;i==="email"?n=n.check(W.email()):i==="uri"||i==="uri-reference"?n=n.check(W.url()):i==="uuid"||i==="guid"?n=n.check(W.uuid()):i==="date-time"?n=n.check(W.iso.datetime({offset:!0})):i==="date"?n=n.check(W.iso.date()):i==="time"?n=n.check(W.regex(HCe)):i==="duration"?n=n.check(W.iso.duration()):i==="hostname"?n=n.check(W.hostname()):i==="ipv4"?n=n.check(W.ipv4()):i==="ipv6"?n=n.check(W.ipv6()):i==="mac"?n=n.check(W.mac()):i==="cidr"?n=n.check(W.cidrv4()):i==="cidr-v6"?n=n.check(W.cidrv6()):i==="base64"?n=n.check(W.base64()):i==="base64url"?n=n.check(W.base64url()):i==="e164"?n=n.check(W.e164()):i==="credit_card"?n=n.check(W.creditCard()):i==="iban"?n=n.check(W.iban()):i==="jwt"?n=n.check(W.jwt()):i==="emoji"?n=n.check(W.emoji()):i==="nanoid"?n=n.check(W.nanoid()):i==="cuid"?n=n.check(W.cuid()):i==="cuid2"?n=n.check(W.cuid2()):i==="ulid"?n=n.check(W.ulid()):i==="xid"?n=n.check(W.xid()):i==="ksuid"&&(n=n.check(W.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?W.number().int():W.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=W.boolean();break}case"null":{o=W.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Vn(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=Vn(f,e);Zr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let y of f){let w=Vn(d[y],e),b=W.string().regex(new RegExp(y));p.push(W.looseRecord(b,w))}let m=[];if(Object.keys(n).length>0&&m.push(W.object(n).passthrough()),m.push(...p),m.length===0)o=W.object({}).passthrough();else if(m.length===1)o=m[0];else{let y=W.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)y=W.intersection(y,m[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=f.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Wo(S.value))return;let x=[];for(let R of Object.keys(S.value))y.includes(R)||w.some(T=>T.test(R))||x.push(R);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=W.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=Vn(f,e)}o=FCe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>Vn(d,e)),c=IW(a,s),u=Array.isArray(i)?void 0:PW(i,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Vn(d,e)),c=IW(a,s),u=PW(t.additionalItems,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(i!==void 0){let s=Vn(i,e),a=W.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=W.array(W.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=GCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Vn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Vn(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r=kW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>Vn(u,e)),c=W.union(a);r=o?W.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Vn(u,e)),c=W.xor(a);r=o?W.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:W.any();else{let a=o?r:Vn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=W.intersection(a,Vn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=W.nullable(r)),t.readOnly===!0&&(r=W.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!my(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!my(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))MCe.has(a)||Zr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function TW(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=UCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Wr};return Vn(r,i)}var CW=Symbol("z.visit/resolving");function hy(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===CW)return new Np({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,CW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let m of l){let y=n(u[m]);y!==u[m]&&(d=!0),f[m]=y}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let m=n(p);m!==p&&(l=!0),d.push(m)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function OW(t){return hy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function BCe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Zo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function DW(t){return BCe(t.out,t.checks)}function KCe(t){return t.in._zod.traits.has("$ZodTransform")?DW(t):t.in}function NW(t){return hy(t,{pipe:e=>KCe(e._zod.def),default:(e,r)=>r?kt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function zW(t){return hy(t,{pipe:e=>DW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var qU={};Ht(qU,{bigint:()=>XCe,boolean:()=>JCe,date:()=>YCe,number:()=>WCe,string:()=>ZCe});function ZCe(t){return Gz(sf,t)}function WCe(t){return Bz(af,t)}function JCe(t){return Kz(cf,t)}function XCe(t){return Zz(uf,t)}function YCe(t){return Wz(sy,t)}var gy={name:"@tomato414941/foundation",version:"12.1.1",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&h.config({jitless:!0});function eOe(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var yy=h.string().trim().max(8192).refine(t=>eOe(t)!==null,"Use an OpenSSH public key from a .pub file."),vy=h.object({authorizedKeys:h.array(yy).max(32)}).strict(),Ugt=vy.extend({revision:h.number().int().positive().optional()}),VU=vy.extend({host:h.string().min(1).max(253).nullable(),port:h.number().int().min(1).max(65535),username:h.literal("root"),workingDirectory:h.literal("/workspace"),hostKey:yy.nullable(),fingerprint:h.string().nullable(),revision:h.number().int().positive(),appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),Lgt=VU.extend({state:h.enum(["starting","configuring","ready","disabled","stopped"])}),jgt=h.object({hostKey:yy,appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),tOe=vy.extend({port:h.number().int().min(1).max(65535),revision:h.number().int().positive()}).strict(),dE=h.object({configuration:tOe.nullable()}).strict();var pf=new TextEncoder,ff=new TextDecoder,MW=new TextDecoder("utf-8",{fatal:!0}),pE=2**32;function Gn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function GU(t,e,r){if(e<0||e>=pE)throw new RangeError(`value must be >= 0 and <= ${pE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function HU(t){let e=Math.floor(t/pE),r=t%pE,o=new Uint8Array(8);return GU(o,e,0),GU(o,r,4),o}function fE(t){let e=new Uint8Array(4);return GU(e,t),e}var rOe=/[^\x00-\x7f]/;function Yr(t){if(typeof t=="string"&&t.length>=128){if(rOe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return pf.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function UW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function LW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function mE(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var ja=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Jl=class extends ja{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ot=class extends ja{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Hc=class extends ja{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},G=class extends ja{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Xt=class extends ja{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var wy=class extends ja{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var hE=class extends ja{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var nOe="The input to be decoded is not correctly encoded.";function Xl(t){try{return LW(typeof t=="string"?t:ff.decode(t),!0)}catch(e){throw new TypeError(nOe,{cause:e})}}function nr(t){return UW(typeof t=="string"?pf.encode(t):t,!0)}function Ro(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function vr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Bc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Xo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function uo(t,e,r){try{return Xl(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function gE(t,e,r){try{return Yr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function mf(t,e,r){let o;try{o=JSON.parse(MW.decode(Xl(t)))}catch{throw new e(r)}if(!vr(o))throw new e(r);return o}var yE={__proto__:null,b64:!0},vE={__proto__:null};function _y(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function wE(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Kc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ot(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function _E(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Yl(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!vr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var oOe=t=>t[Symbol.toStringTag],iOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function zi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(vr(e)){if(s=XU(e),typeof s.kty!="string")throw jW(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(iOe(t,s,r),s.kty==="oct")return Xl(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!ZU(e))throw jW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${oOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Zc(e))return e;if(a=e,a.type==="secret")return a.export()}BU||=new WeakMap;let c=e,u=BU.get(c);if(u?.[o])return u[o];if(u||BU.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=sOe[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await gf(t,s)}var BU,sOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function SE(t){if(!Zc(t))throw new Error("CryptoKey instance expected")}var Zc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},KU=t=>t?.[Symbol.toStringTag]==="KeyObject",ZU=t=>Zc(t)||KU(t);function FW(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Fa=(t,...e)=>FW("Key must be ",t,...e);function jW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(FW(`Key for the ${t} algorithm must be `,e,...o))}var bE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function WU(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function hf(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function JU(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw bE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw bE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw bE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw bE(e.length,"algorithm.length");WU(t,r)}function xE(t){return{__proto__:null,...t}}function XU(t){let e=xE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function EE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function gf(t,e,r){if(!t.kty.includes(e.kty))throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Mi(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),JU(t,e,r),t}var Ql=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function $E(t,e){let r=t.byteLength<<3;if(r!==e)throw new G(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var aOe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function qW(t,e){if(e.length<<3!==t.ivBits)throw new G("Invalid Initialization Vector length")}async function VW(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Fa(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function GW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function cOe(t,e,r,o,n){let[i,s,a]=await VW(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Gn(n,o,c,HU(n.length*8)),l=await GW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function uOe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function lOe(t,e,r,o,n,i){let[s,a,c]=await VW(t,e,"decrypt"),u=Gn(i,o,r,HU(i.length*8)),l=await GW(a,u,c);try{if(await uOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Hc}async function RE(t,e,r,o,n){if(!Zc(r)&&!(r instanceof Uint8Array))throw new TypeError(Fa(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?qW(t,o):o=aOe(t),r instanceof Uint8Array&&$E(r,t.cekBits),t.cbc)return cOe(t,e,r,o,n);let i=await Mi(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function IE(t,e,r,o,n,i){if(!Zc(e)&&!(e instanceof Uint8Array))throw new TypeError(Fa(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new G("JWE Initialization Vector missing");if(!n)throw new G("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new G("Invalid Authentication Tag length");if(qW(t,o),e instanceof Uint8Array&&$E(e,t.cekBits),t.cbc)return lOe(t,e,r,o,n,i);let s=await Mi(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Gn(r,n)))}catch{throw new Hc}}function by(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var dOe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],pOe=[[],["deriveBits"]],kE=[[],[]];function AE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:dOe,ops:["wrapKey","unwrapKey"]}}function PE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:pOe,ops:[void 0,"deriveBits"]}}function yf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:kE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function YU(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:kE,ops:["deriveBits","deriveBits"]}}var qa=by({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:kE,ops:["encrypt","decrypt"]},"RSA-OAEP":AE(1),"RSA-OAEP-256":AE(256),"RSA-OAEP-384":AE(384),"RSA-OAEP-512":AE(512),"ECDH-ES":PE("direct-key-agreement"),"ECDH-ES+A128KW":PE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":PE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":PE("key-agreement-with-key-wrapping"),A128KW:yf(128),A192KW:yf(192),A256KW:yf(256),A128GCMKW:yf(128,!0),A192GCMKW:yf(192,!0),A256GCMKW:yf(256,!0),"PBES2-HS256+A128KW":YU(),"PBES2-HS384+A192KW":YU(),"PBES2-HS512+A256KW":YU()}),fOe=["encrypt","decrypt"];function vf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:kE,ops:fOe,cekBits:t,ivBits:e?128:96,cbc:e}}var mOe=by({A128GCM:vf(128),A192GCM:vf(192),A256GCM:vf(256),"A128CBC-HS256":vf(256,!0),"A192CBC-HS384":vf(384,!0),"A256CBC-HS512":vf(512,!0)});function HW(t,e){throw new Ot(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Ui(t){return(typeof t=="string"?qa[t]:void 0)??HW("alg","Algorithm")}function Li(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function ed(t){return(typeof t=="string"?mOe[t]:void 0)??HW("enc","Encryption Algorithm")}function BW(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");WU(t,e)}async function hOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function gOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function ZW(t,e,r){JU(e,Ui(t).subtle,r),hf(t,e)}async function WW(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new G("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new G("PBES2 Count Input must be a positive integer");let n=Gn(Yr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Mi(o,Ui(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function QU(t){return Gn(fE(t.length),t)}async function yOe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await mE("sha256",Gn(fE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function JW(t,e,r,o,n=new Uint8Array,i=new Uint8Array){BW(t),BW(e,"deriveBits");let s=Gn(QU(Yr(r)),QU(n),QU(i),fE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return yOe(a,o,s)}function XW(t){SE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ot("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function TE(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new G(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return uo(r,e,G)}}function YW(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new G('JOSE Header "apu" and "apv" values must be distinct')}}function vOe(t){if(t===void 0)throw new G("JWE Encrypted Key missing")}function KW(t){if(t!==void 0)throw new G("Encountered unexpected JWE Encrypted Key")}function wOe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function QW(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return KW(o),r;let c=a==="direct-key-agreement";switch(c?KW(o):vOe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!vr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new G('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');XW(r);let l=await gf(t,u),d=TE(n,"apu"),f=TE(n,"apv");YW(d,f);let p=await JW(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return SE(r),ZW(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new G('JOSE Header "p2c" (PBES2 Count) missing or invalid');wOe(i);let u=i??1e4;if(n.p2c>u)throw new G('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new G('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=uo(n.p2s,"p2s",G);r=await WW(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new G('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new G('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=uo(n.iv,"iv",G),l=uo(n.tag,"tag",G);if(u.byteLength!==12)throw new G("Invalid Initialization Vector length");if(l.byteLength!==16)throw new G("Invalid Authentication Tag length");return IE(ed(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return gOe(s.slice(-6),r,o)}async function CE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Li(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await zi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Ql(e):void 0;l&&$E(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{XW(u);let{apu:p,apv:m}=i;p!==void 0&&Ro(p,'"apu"'),m!==void 0&&Ro(m,'"apv"');let y=p??TE(o,"apu"),w=m??TE(o,"apv");YW(y,w);let b;i.epk!==void 0?b=await zi(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:R,y:T,crv:M,kty:K}=await S.exportKey("jwk",x),te=a==="direct-key-agreement",Ie=await JW(u,b,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),Te={x:R,crv:M,kty:K};if(K==="EC"&&(Te.y=T),f={epk:Te},p!==void 0&&(f.apu=nr(p)),m!==void 0&&(f.apv=nr(m)),te)return[Ie,void 0,f];u=Ie;break}case"RSA-OAEP":{SE(u),ZW(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await WW(m,s,p,u),f={p2c:p,p2s:nr(m)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await RE(ed(s.slice(0,-2)),l,u,p,new Uint8Array);d=m.ciphertext,f={iv:nr(m.iv),tag:nr(m.tag)}}}if(d??=await hOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,f]}function OE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ot('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new G('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function e5(t){if(typeof globalThis[t]>"u")throw new Ot(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function t5(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new G("Decompressed plaintext exceeded the configured limit")}return Gn(...n)}async function r5(t){return e5("CompressionStream"),t5(new CompressionStream("deflate-raw"),t)}async function n5(t,e){return e5("DecompressionStream"),t5(new DecompressionStream("deflate-raw"),t,e)}function o5(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new G("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new G("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new G("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new G("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new G("JWE AAD incorrect type");if(s!==void 0&&!vr(s))throw new G("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function i5(t){let e,r;try{let{header:o}=t;if(vr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function s5(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new G("JWE Encrypted Key incorrect type");if(r!==void 0&&!vr(r))throw new G("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new G("JOSE Header missing")}function eL(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=mf(e,G,"JWE Protected Header is invalid")),[s,uo(r,"ciphertext",G),o!==void 0?uo(o,"iv",G):void 0,n!==void 0?uo(n,"tag",G):void 0,gE((e??"")+(i!==void 0?`.${i}`:""),"aad",G)]}function DE(t){return[t&&_y("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&_y("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function tL(t,e,r,o=eL(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Bc(n,u,l))throw new G("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,m,y,w,b]=e,{encrypted_key:S}=t;Kc(G,vE,y,n,f),OE(f,n);let{alg:x,enc:R}=f;if(typeof x!="string"||!x)throw new G("missing JWE Algorithm (alg) in JWE Header");let T=qa[x];if(S===""&&(!T||!Li(T)))throw new G("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof R!="string"||!R))throw new G("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new Jl('"alg" (Algorithm) Header Parameter value not allowed');let K;if(M){if(R!==void 0)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new G("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new G("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(R))throw new Jl('"enc" (Encryption Algorithm) Header Parameter value not allowed');K=ed(R)}let te;if(S!==void 0)try{te=uo(S,"encrypted_key",G)}catch(Fe){if(!T||!Li(T))throw Fe;te=new Uint8Array}let Ie=!1;typeof r=="function"&&(r=await r(n,t),Ie=!0);let Te=T??Ui(x);Li(Te)&&te===void 0&&(te=new Uint8Array);let bt=await zi(Te.mode==="direct-encryption"?K:Te,r,"decrypt"),fe;if(Te.mode==="integrated-encryption")fe=await Te.decrypt(bt,te,i,c,n,f);else{let Fe=K,se;try{se=await QW(Te,Fe,bt,te,f,w),Li(Te)&&se instanceof Uint8Array&&se.byteLength<<3!==Fe.cekBits&&(se=Ql(Fe))}catch(tr){if(tr instanceof TypeError||tr instanceof G||tr instanceof Ot)throw tr;se=Ql(Fe)}fe=await IE(Fe,se,i,s,a,c)}if(f.zip==="DEF"){let Fe=b??25e4;if(Fe===0)throw new Ot('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Fe!==1/0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");fe=await n5(fe,Fe).catch(se=>{throw se instanceof G?se:new G("Failed to decompress plaintext",{cause:se})})}return{plaintext:fe,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:uo(d,"aad",G)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ie&&{key:bt}}}async function a5(t,e,r){if(t instanceof Uint8Array&&(t=ff.decode(t)),typeof t!="string")throw new G("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new G("Invalid Compact JWE");return tL({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Sy(t,e,r){return a5(t,DE(r),e)}async function rL(t,e,r){if(!vr(t))throw new G("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new G("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(vr))throw new G("JWE Recipients missing or incorrect type");if(!n.length)throw new G("JWE Recipients has no members");let i,s,a;try{i=DE(r),s=o5(t),a=eL(s)}catch{throw new Hc}let c=n.map(u=>i5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?qa[l]:void 0;if(d&&!Li(d))throw new G(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return s5(l),await tL(l,i,e,a)}catch{}throw new Hc}function NE(t,e,r){if(!Bc(t,e,r))throw new G("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function nL(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new G("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Ro(s,"JWE Additional Authenticated Data"),a!==void 0&&Ro(a,"JWE Content Encryption Key"),c!==void 0&&Ro(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Yl(G,o)[0],t[1]=o),n!==void 0&&(n=Yl(G,n)[0],t[2]=n),!r&&i!==void 0&&(i=Yl(G,i)[0],t[3]=i),u!==void 0&&!vr(u))throw new TypeError("JWE Key Management Parameters must be an object");NE(o,n,i);let d={...o,...n,...i};wE(G,o),Kc(G,vE,l,o,d),OE(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new G('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=qa[f];if(m?.mode==="integrated-encryption"){if(p!==void 0)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!="string"||!p)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,ed(p),m]}async function oL(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,m]=t,y=a,w=c,b=i??Ui(o.alg),S,x,R;b.mode==="integrated-encryption"?R=await zi(b,r,"encrypt"):[R,S,x]=await CE(b,n,r,o,d,p),x&&(m?w=w?{...w,...x}:x:y=y?{...y,...x}:x,NE(y,w,u));let T=y?nr(JSON.stringify(y)):"",M=l?.byteLength?nr(l):void 0,K=Yr(M?`${T}.${M}`:T),te=s;o.zip==="DEF"&&(te=await r5(te).catch(Fe=>{throw new G("Failed to compress plaintext",{cause:Fe})}));let Ie,Te,bt;b.mode==="integrated-encryption"?[S,Ie]=await b.encrypt(R,te,K,y,o,p):{ciphertext:Ie,tag:Te,iv:bt}=await RE(n,te,R,f,K);let fe={ciphertext:nr(Ie)};return bt&&(fe.iv=nr(bt)),Te&&(fe.tag=nr(Te)),S?.byteLength&&(fe.encrypted_key=nr(S)),M&&(fe.aad=M),y&&(fe.protected=T),u&&(fe.unprotected=u),w&&(fe.header=w),fe}async function c5(t,e,r){return oL(t,nL(t,r),e)}function u5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var iL=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Xo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Xo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},xy=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new iL(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Xo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Xo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new G("at least one recipient must be added");Ro(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[y,w,b,S]=m.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],R=nL(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,R,b]);let[{alg:T,enc:M},,K]=R;if(e&&K&&!Li(K))throw new G(`"${T}" alg may only have a single recipient`);if(!r)r=M;else if(r!==M)throw new G('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Ui(m[0].alg);let[s,a,c]=i[0],u=e?Ql(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await oL(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let m=1;m<i.length;m++){let[y,[w,b,S],x]=i[m],R=y[2],[,T,M]=await CE(S,b,x,w,u,y[7]),K={encrypted_key:nr(T)};if(R||M){let te={...R,...M};M&&NE(y[1],te,y[3]),K.header=te}p.recipients.push(K)}return p}};var Ey=[["verify"],["sign"]];function sL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Ey}}function wf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:Ey,minRsaBits:2048}}function aL(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Ey}}function l5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Ey}}function cL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Ey}}var uL=by({HS256:sL(256),HS384:sL(384),HS512:sL(512),RS256:wf(256),RS384:wf(384),RS512:wf(512),PS256:wf(256,32),PS384:wf(384,48),PS512:wf(512,64),ES256:aL("P-256",256),ES384:aL("P-384",384),ES512:aL("P-521",512),EdDSA:l5(),Ed25519:l5(),"ML-DSA-44":cL(44),"ML-DSA-65":cL(65),"ML-DSA-87":cL(87)});function zE(t){let e=typeof t=="string"?uL[t]:void 0;if(!e)throw new Ot(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function d5(t){return[t&&_y("algorithms",t.algorithms),t?.crit]}function _Oe(t){return t===void 0?{}:mf(t,Xt,"JWS Protected Header is invalid")}function bOe(t){try{return Yr(t)}catch{throw new Xt("JWS Compact Serialization payload must use only ASCII characters")}}async function SOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??_Oe(i);if(!Bc(c,s))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=_E(c,Kc(Xt,yE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new Jl('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Xt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let m=zE(d),y=Gn(i!==void 0?Yr(i):new Uint8Array,Yr("."),typeof f=="string"?e[2]??=gE(f,"payload",Xt):f),w=uo(t.signature,"signature",Xt),b=await zi(m,r,"verify"),S=await Mi(b,m.subtle,"verify");m.minRsaBits&&hf(m.alg,S);let x=!1;try{x=await crypto.subtle.verify(m.signing,S,w,y)}catch{}if(!x)throw new hE;let R={payload:typeof f=="string"?uo(f,"payload",Xt):f};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),p?[{...R,key:b},l]:[R,l]}async function p5(t,e,r){if(t instanceof Uint8Array&&(t=ff.decode(t)),typeof t!="string")throw new Xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Xt("Invalid Compact JWS");return SOe({payload:n,protected:o,signature:i},e,r,bOe)}async function lL(t,e,r){let[o]=await p5(t,d5(r),e);return o}var _f=class{#e;constructor(e){Ro(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Xo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Xo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Xo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Xo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return u5(await c5([...this.#e],e,r))}};async function xOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=Yl(Xt,n);n=b[0],a=nr(b[1])}if(i!==void 0&&(i=Yl(Xt,i)[0]),!n&&!i)throw new Xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Bc(n,i))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};wE(Xt,n);let u=_E(n,Kc(Xt,yE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=zE(l),f="",p=o,m;if(u){let b=t[4];b?(f=b[0]??=nr(o),p=b[1]??=Yr(f)):(f=nr(o),m=pf.encode(`${a}.${f}`))}m??=Gn(Yr(a),Yr("."),p);let y=await Mi(await zi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&hf(d.alg,y);let w={signature:nr(new Uint8Array(await crypto.subtle.sign(d.signing,y,m))),payload:f};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function f5(t,e,r,o,n){let[i]=await xOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var $y=class{#e;#t;constructor(e){Ro(e,"payload"),this.#e=e}setProtectedHeader(e){return Xo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return f5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var dL='"alg" (Algorithm)';function pL(t='JWK "alg" (Algorithm) Parameter'){throw new Ot(`Invalid or unsupported ${t} value`)}function Ry(t,e){return(typeof t=="string"?uL[t]??qa[t]:void 0)??pL(e)}async function Wc(t){if(KU(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:nr(t)};if(!Zc(t))throw new TypeError(Fa(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var Va=(t,e)=>{if(typeof t!="string"||!t)throw new wy(`${e} missing or invalid`)};async function fL(t,e){let r;if(vr(t)){if(r=xE(t),typeof r.kty!="string")throw new TypeError(Fa(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(ZU(t))r=xE(await Wc(t));else throw new TypeError(Fa(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":Va(r.alg,'"alg" (Algorithm) Parameter'),Va(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Va(r.crv,'"crv" (Curve) Parameter'),Va(r.x,'"x" (X Coordinate) Parameter'),Va(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Va(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Va(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Va(r.e,'"e" (Exponent) Parameter'),Va(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new wy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ot('"kty" (Key Type) Parameter missing or unsupported')}let n=Yr(JSON.stringify(o));return nr(await mE(e,n))}async function Yo(t,e,r){if(!vr(t))throw new TypeError("JWK must be an object");let o=XU(t),n=EE(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return Xl(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return gf(Ry(e),o,n)}case"RSA":case"EC":case"OKP":return gf(Ry(e),o,n);default:throw new Ot('Unsupported "kty" (Key Type) Parameter value')}}function mL(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return mf(e,TypeError,r)}function EOe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ot("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Iy(t,e){let r=EE(e?.extractable),o=Ry(t,dL);o.secret&&pL(dL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ot("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ot(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:EOe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var y5=h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),v5=h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),m5=h.string().min(1).max(128),h5=h.string().min(1).max(16384),$Oe=h.discriminatedUnion("kind",[h.object({kind:h.literal("access_key"),accessKeyId:m5,secretAccessKey:h5}).strict(),h.object({kind:h.literal("session"),accessKeyId:m5,secretAccessKey:h5,sessionToken:h.string().min(1).max(16384),expiresAt:h.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),h.object({kind:h.literal("environment")}).strict()]),ROe=h.object({arn:v5,externalId:h.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Ga=h.object({authentication:$Oe,region:y5,role:ROe.optional()}).strict(),ME=h.object({accountId:h.string().regex(/^\d{12}$/),principalId:h.string().min(1).max(256),arn:h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),UE=Ga.extend({sourceIdentity:ME.optional(),identity:ME.optional()}).strict();function bf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function g5(t){return{...t,arn:bf(t.arn)}}function w5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:g5(t.sourceIdentity)}:{},...t.identity?{identity:g5(t.identity)}:{}}}var LE=h.object({authentication:h.enum(["access_key","session","environment"]),region:y5,sourceAccountId:h.string().regex(/^\d{12}$/).optional(),sourceArn:h.string().max(2e3).optional(),roleArn:v5.optional(),expiresAt:h.number().int().positive().optional()}).strict();function _5(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var b5=h.object({method:h.enum(["GET","POST","PUT","DELETE","PATCH"]),path:h.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),Ay=h.object({account:h.string().min(1),identities:h.array(h.string()),user:h.string().nullable(),description:h.string().nullable(),roles:h.array(h.string()).nullable(),credentialId:h.number().int().positive(),rules:h.array(b5),allowedIPs:h.array(h.string()).nullable(),expiresAt:h.number().nullable()}).strict();function S5(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return b5.parse({method:r[1],path:r[2]})})}typeof window<"u"&&h.config({jitless:!0});var E=h.uuid(),me=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Ae=h.iso.datetime(),wr=h.json(),Lt=h.record(h.string(),wr),x5=h.enum(["ja","en"]),E5=h.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var $5=h.enum(["variable","connection","service","method","app","object","environment","function"]),bn=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),IOe=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:E}).strict(),GE=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return IOe.safeParse(mL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Io=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:E,epk:bn.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Swt=h.object({id:E,name:me,publicKey:bn}),Jc=h.object({id:E,name:me,owner:h.object({id:E,name:me}).nullable(),createdAt:Ae,permissions:h.array(E5),createKinds:h.array($5),publicKey:bn.nullable()}),R5=h.object({id:E,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:Ae,lastUsedAt:Ae.nullable(),expiresAt:Ae.nullable(),canOpen:h.boolean()}),I5=h.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),AOe=h.object({subjectId:E,relation:I5,objectId:E}).strict(),xwt=AOe.extend({objectType:h.enum(["principal",...$5.options]),subjectName:me,objectName:me,createdAt:Ae}),Ewt=h.object({error:h.object({code:h.string(),message:h.string(),details:wr.optional()})}),$wt=h.object({ok:h.literal(!0)}),POe=h.object({value:h.string().min(1).max(200),label:h.string().min(1).max(200),values:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).default({})}).strict(),hL=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional(),choices:h.array(POe).min(1).max(100).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),gL=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),A5=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),required:h.array(h.string()).optional(),separator:h.string().default(" "),docs:h.url().optional()}),td=h.string().min(1).max(4096),qE=h.union([h.string(),h.array(h.string()).min(1)]),kOe=h.object({application:h.enum(["required","implicit"]).default("required"),grantType:h.enum(["authorization_code","client_credentials"]).optional(),issuer:h.url().optional(),authorizeUrl:td.optional(),tokenUrl:td,identity:h.object({url:td.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:qE.default("/id"),name:qE.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),revoke:h.object({url:td,style:h.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:h.enum(["body","basic","none"]).optional()}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:A5.default({default:[],separator:" "}),fields:h.array(hL).default([]),outputs:gL.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),TOe=h.object({fields:h.array(hL).min(1),outputs:gL,identity:h.object({url:td,headers:h.record(h.string(),h.string()),id:qE,name:qE}).strict().optional(),console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}),yL=h.enum(["oauth","token","aws","ovh"]),COe=h.object({hint:h.string().optional()}).strict(),OOe=h.object({authorization:h.enum(["api_key","consumer_key"]),apiBaseUrl:td,fields:h.array(hL).min(1),scopes:A5.default({default:[],separator:`
129
129
  `}),outputs:gL,hint:h.string().optional()}).strict(),HE={name:me,docs:h.url().optional(),console:td.optional()},BE=h.object({...HE,kind:h.literal("oauth"),config:kOe}).strict(),KE=h.object({...HE,kind:h.literal("token"),config:TOe}).strict(),ZE=h.object({...HE,kind:h.literal("aws"),config:COe}).strict(),WE=h.object({...HE,kind:h.literal("ovh"),config:OOe}).strict(),Xc=h.discriminatedUnion("kind",[BE,KE,ZE,WE]),jE={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"]),defaultName:me,registration:h.object({kind:h.enum(["input","authorization"]),device:h.enum(["browser","cli"]),browserExchange:h.enum(["available","unavailable","unknown"]),tokenAlternatives:h.array(h.string())}).strict()},Py=h.discriminatedUnion("kind",[BE.extend(jE),KE.extend(jE),ZE.extend(jE),WE.extend(jE)]),vL=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),wL=h.object({name:me,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional()}).strict(),DOe=wL.extend({methods:h.record(vL,h.string().min(1))}).strict(),P5=wL.extend({methods:h.record(vL,h.union([h.string().min(1),Xc]))}).strict(),Rwt=wL.extend({id:h.string(),builtin:h.boolean(),methods:h.record(vL,Py)}),k5=h.object({id:E,output:h.string().min(1).max(100).optional()}).strict(),T5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),_L=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:k5,format:h.enum(["text","file","json"]).default("text"),pointer:h.string().optional()}).strict(),NOe=h.object({pointer:h.string().max(500),parts:h.array(h.union([h.string().max(8192),k5])).min(1).max(32)}).strict(),Ha=h.object({url:h.string().max(4096),method:h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:h.record(h.string(),h.string().max(8192)).default({}),body:h.string().max(1e6).optional(),json:wr.optional(),form:h.record(h.string(),h.string()).optional(),bindings:h.array(NOe).max(32).default([])}).strict(),Ba=h.object({command:h.array(h.string().max(8192)).min(1).max(100),stdin:h.string().max(1e6).optional(),timeoutSeconds:h.number().int().min(1).max(3600).default(60),inputs:h.array(_L).max(32).default([])}).strict(),C5=h.discriminatedUnion("kind",[Ba.omit({stdin:!0}).extend({kind:h.literal("command")}).strict(),h.object({kind:h.literal("http"),request:Ha}).strict()]),Qo=h.object({description:h.string().max(2e3).default(""),environmentId:E,program:C5,parameters:h.array(h.object({name:h.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:h.string().max(100),type:h.enum(["string","number","boolean","json"]).default("string"),required:h.boolean().default(!0),default:wr.optional()}).strict()).max(32).default([]),result:h.enum(["text","json"]).default("json")}).strict(),Yc={id:E,ownerId:E,name:me,createdAt:Ae,updatedAt:Ae,version:h.number().int().positive(),permissions:h.array(E5)},zOe=h.enum(["starting","running","stopping","stopped","failed"]),MOe=h.object({state:h.enum(["pending","failed","complete"]),error:h.string().nullable()}),UOe=h.object({idleSeconds:h.number().int().min(60).max(86400).default(3600),maxSeconds:h.number().int().min(60).max(86400).default(3600)}).strict(),O5=h.object({image:h.string().min(1).max(300).optional(),size:h.enum(["small","medium","large"]).default("small"),lifetime:UOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:vy.optional()}).strict(),bL={recipients:h.array(E).default([]),executors:h.array(E).default([]),custodyRevision:h.number().int().positive().nullable().default(null)},LOe=h.object({...Yc,kind:h.literal("variable"),data:h.object({...bL,bytes:h.number().int().nonnegative()})}),jOe=h.object({...Yc,kind:h.literal("connection"),data:h.object({...bL,methodId:h.string(),fields:h.record(h.string(),h.string()).default({}),settings:h.array(h.object({name:h.string(),label:h.string(),value:h.string()})).default([]),methodName:h.string(),methodKind:yL,services:h.array(h.object({id:h.string(),name:me})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:h.string().optional(),aws:LE.optional(),ovh:Ay.optional()})}),FOe=h.object({...Yc,kind:h.literal("service"),data:DOe}),qOe=h.object({...Yc,kind:h.literal("method"),data:Xc}),VOe=h.object({...Yc,kind:h.literal("app"),data:h.object({...bL,methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:E.optional()})}),GOe=h.object({...Yc,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),HOe=h.object({...Yc,kind:h.literal("environment"),data:O5.extend({executorId:E.optional(),operatorId:E.optional(),driver:h.enum(["attached","managed"]).optional(),capabilities:h.array(h.string()).optional(),isolation:h.enum(["process","container"]).optional(),manifestDigest:h.string().optional(),processes:h.object({workingDirectory:h.string()}).optional(),ssh:VU.optional(),awsPrincipal:h.string().optional(),state:zOe,deletion:MOe.optional(),startedAt:Ae.nullable(),stoppedAt:Ae.nullable(),lastActiveAt:Ae,error:h.string().nullable()})}),JE=h.object({...Yc,kind:h.literal("function"),data:Qo.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:C5.optional()})}),_r=h.discriminatedUnion("kind",[LOe,jOe,FOe,qOe,VOe,GOe,HOe,JE]),Iwt=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:me,definition:P5}).strict(),h.object({kind:h.literal("method"),name:me,definition:Xc}).strict(),h.object({kind:h.literal("environment"),name:me.optional(),options:O5}).strict()]),Awt=h.object({version:h.number().int().positive(),name:me.optional(),definition:h.union([P5,Xc]).optional()}).strict(),ji=h.object({name:h.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Lt}).strict(),XE=ji.extend({inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()}).strict()).max(16).default([])}),VE=h.object({ja:h.string(),en:h.string()}).strict(),SL=XE.extend({title:VE,execution:h.enum(["server","keyholder"]),configure:h.array(h.string()),environment:h.object({required:h.boolean(),reason:VE.nullable()}).strict()}),D5=h.object({to:E.optional(),executionId:E.optional(),message:h.string().max(1e3).default(""),operations:h.array(XE).min(1).max(8).optional(),expiresInMinutes:h.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),FE=h.object({id:E,name:me}),N5=h.discriminatedUnion("kind",[h.object({kind:h.literal("line"),subject:FE,relation:I5,object:FE}),h.object({kind:h.literal("transfer"),item:FE,to:FE})]),YE=h.object({id:E,executionId:E,from:Jc.pick({id:!0,name:!0}),to:Jc.pick({id:!0,name:!0}).nullable(),message:h.string(),purpose:h.enum(["input","approval"]),state:h.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:Ae,expiresAt:Ae,url:h.url(),code:h.string().optional(),returnUrl:h.url().nullable(),refreshUrl:h.url().nullable(),canRespond:h.boolean(),canCancel:h.boolean()}),Pwt=h.object({id:E,name:me,publicKey:bn,state:h.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:Ae,expiresAt:Ae}),kwt=h.object({available:h.boolean(),required:h.boolean(),active:h.boolean(),payer:Jc.pick({id:!0,name:!0}).nullable()}),Twt=h.object({storageBytes:h.number().nonnegative(),storageLimit:h.number().positive(),computeSeconds:h.number().nonnegative(),computeLimit:h.number().positive(),month:h.string()}),Cwt=h.object({id:h.string(),actorId:E.nullable(),action:h.string(),targetId:E.nullable(),createdAt:Ae,details:Lt}),Owt=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional()}).strict(),Qr=t=>h.object({items:h.array(t),next:h.string().nullable().default(null)}),Dwt=h.object({id:E}),Nwt=h.object({owner:E}),BOe=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()}),zwt=BOe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var KOe=h.object({email:h.boolean(),environments:h.boolean(),ssh:h.boolean(),objects:h.boolean(),payments:h.boolean()}),QE=h.object({principal:Jc.nullable(),credentialId:E.nullable(),wrappedKey:GE.nullable(),requestId:E.nullable(),server:h.object({name:me}),features:KOe,principals:h.array(Jc)}),jwt=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:x5.default("ja"),principalId:E.optional()}).strict(),Fwt=h.object({intent:h.enum(["register","authenticate"]),name:me.optional(),principalId:E.optional(),returnTo:h.string().max(2048).optional()}).strict(),qwt=h.object({challengeId:E,credential:h.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:GE.optional()}).strict();var ZOe=new TextEncoder,WOe=new TextDecoder,ky="ECDH-ES+A256KW",xL="A256GCM",tt=t=>ZOe.encode(t),Ao=t=>WOe.decode(t);function Cs(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function z5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function e$(){let t=await Iy(ky,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await Wc(t.publicKey)),privateKey:await Wc(t.privateKey)}}async function Ka(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new xy(t).setProtectedHeader({enc:xL}).setAdditionalAuthenticatedData(tt(r));for(let n of e)o.addRecipient(await Yo(n.publicKey,ky)).setUnprotectedHeader({alg:ky,kid:n.id});return Io.parse(await o.encrypt())}async function Po(t,e,r,o){if(t.aad!==Cs(tt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Yo(e,ky);return(await rL({...t,recipients:[n]},i,{keyManagementAlgorithms:[ky],contentEncryptionAlgorithms:[xL]})).plaintext}async function JOe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:tt("Foundation"),info:tt("passkey encryption key")},e,256))}async function M5(t,e,r){let o=await Sy(t,await JOe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[xL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Ao(o.plaintext))}var br=h.string().regex(/^[A-Za-z0-9_-]{43}$/),Sr=h.string().min(100).max(4e6),U5=bn.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Ty=h.object({encryption:U5,signing:U5}).strict(),or=h.object({id:E,principalId:E,generation:h.number().int().positive(),previous:br.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Sf(t){return fL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ee(t){return Cs(new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t)))))}async function rd(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function r$(){let[t,e]=await Promise.all([e$(),Iy("ES256",{crv:"P-256",extractable:!0})]),r=await Wc(e.privateKey);return Ty.parse({encryption:t.privateKey,signing:r})}function t$(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function n$(t,e){return or.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:t$(e.encryption),signing:t$(e.signing)})}async function ur(t,e,r){let o=e instanceof CryptoKey?e:await Yo(e,"ES256");return new $y(tt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Mr(t,e,r,o){if(C(await EL(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function EL(t,e,r){let o=await lL(t,await Yo(bn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(C(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Os=h.object({binding:or,signature:Sr}).strict();async function Cy(t,e){if(await Ds(t),await Sf(e.encryption)!==await Sf(t.encryption)||await Sf(e.signing)!==await Sf(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await ur(t,e.signing,"key-binding")}}async function Ds(t){let e=or.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Sf(e.encryption)===await Sf(e.signing))throw new Error("Use separate encryption and signing keys.");await Yo(e.encryption,"ECDH-ES+A256KW"),await Yo(e.signing,"ES256")}async function $L(t){let{binding:e,signature:r}=Os.parse(t);return await Ds(e),await Mr(e,r,e.signing,"key-binding"),e}var L5=h.object({ownerId:E,name:me,resourceId:E.optional(),version:h.number().int().positive().optional(),environmentIds:h.array(E).max(32).optional()}).strict(),j5=L5.extend({value:h.literal("").optional()}),RL=L5.extend({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}),xf=h.object({ownerId:E,name:me,definition:Qo,resourceId:E.optional(),version:h.number().int().positive().optional()}).strict(),o$=h.object({ownerId:E,connectionId:E,environmentId:E}).strict(),F5=h.object({ownerId:E,connectionId:E,version:h.number().int().positive(),users:h.array(E).max(32),expiresAt:h.iso.datetime().optional()}).strict(),q5=h.object({ownerId:E,methodId:h.string().min(1).max(200),connectionId:E.optional(),name:me.optional(),appId:E.optional(),redirectUri:h.url().optional(),users:h.array(E).max(32).optional(),scopes:h.array(h.string().min(1).max(1e3)).max(200).optional(),methodDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:h.string().max(1e3).optional(),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}).strict(),Oy=h.object({ownerId:E,environmentId:E.optional(),operation:h.union([h.object({kind:h.literal("http"),request:Ha}).strict(),Ba.extend({kind:h.literal("command")}),h.object({kind:h.enum(["http","command"]),programId:E,programDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:h.record(h.string(),me).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),i$=h.object({name:ji.shape.name,title:VE,execution:h.enum(["server","keyholder"]),configure:h.array(h.string()),environment:SL.shape.environment,input:Lt}).strict(),V5=h.object({id:E.optional(),operations:h.array(XE).min(1).max(8),responderId:E.optional(),message:h.string().max(1e3).default(""),expiresInMinutes:h.number().int().min(1).max(1440).default(1440)}).strict(),G5=h.object({values:h.array(Lt).max(8).default([]),configuration:h.array(Lt).max(8).default([]),code:h.string().max(20).optional()}).strict(),Ef=h.object({index:h.number().int().nonnegative(),invocation:ji,approval:h.object({id:E,index:h.number().int().nonnegative()}).strict().optional(),continuation:h.object({kind:h.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),Ze=h.object({id:E,actorId:E,ownerId:E,requests:h.array(E),steps:h.array(h.object({index:h.number().int().nonnegative(),name:ji.shape.name,state:h.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:h.array(h.object({kind:h.enum(["run","function"]),id:E}).strict())}).strict()),creator:Jc.pick({id:!0,name:!0}),operations:h.array(SL),approval:h.object({requestId:E.nullable(),proposal:N5.nullable()}).strict().nullable(),canContinue:h.boolean(),canCancel:h.boolean(),url:h.url(),code:h.string().optional(),error:h.object({code:h.string(),message:h.string()}).strict().nullable(),index:h.number().int().nonnegative(),state:h.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:h.enum(["approval","input","execution"]).nullable(),waiting:Ef.nullable(),results:h.array(wr.nullable()),createdAt:h.iso.datetime(),expiresAt:h.iso.datetime()}).strict(),H5=h.object({id:E,index:h.number().int().nonnegative(),invocation:ji,continuationId:E.optional()}).strict();var $f=h.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},XOe=h.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),K5=t=>t===ge.executionResult?14e5:1e6,ue={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},Dy=h.enum([ue.http,ue.command,ue.function,ue.connect,ue.refresh,ue.revoke]);var YOe={[ge.value]:[ue.http,ue.command,ue.function],[ge.tokenSet]:[ue.http,ue.command,ue.function,ue.refresh,ue.revoke],[ge.clientCredential]:[ue.connect,ue.refresh,ue.revoke],[ge.executionResult]:[]},Qc=t=>YOe[t],Z5=t=>Qc(t).filter(e=>e===ue.function||e===ue.refresh),IL=t=>t===ge.tokenSet,QOe=h.object({id:E,digest:br}).strict(),eDe=h.object({actor:or,executor:or,operations:h.array(Dy).min(1).max(6),functionDigests:h.array(br).max(100).default([]),origins:h.array($f).max(100).default([]),callerProgram:h.boolean().default(!1),expiresAt:Ae}).strict(),tDe=h.object({function:QOe,executor:or,operations:h.array(Dy).min(1).max(6),expiresAt:Ae}).strict(),rDe=h.union([eDe,tDe]),en=h.object({format:h.literal(2),origin:$f,id:E,ownerId:E,contentType:XOe,revision:h.number().int().positive(),authorities:h.array(or).min(1).max(100),readers:h.array(or).min(1).max(100),grants:h.array(rDe).max(100),observers:h.array(E).max(100).optional(),producers:h.array(h.object({executor:or,runId:E,expiresAt:Ae,materialRevision:h.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),B5=h.object({ownerId:E,authorities:h.array(or).min(1).max(100)}).strict(),W5=h.object({origin:$f,id:E,revision:h.number().int().positive(),from:B5,to:B5,policyDigest:br,previous:br.nullable(),signerId:E}).strict(),nDe=W5.extend({signature:Sr}),AL=h.array(nDe).max(16),Ny=h.object({policy:en,authorityId:E,signature:Sr,lineage:AL.optional()}).strict(),tn=h.object({policy:en,authorityId:E,authorization:Sr,lineage:AL.optional(),materialRevision:h.number().int().positive(),updatedAt:Ae,creationRunId:E.nullable(),metadata:Lt,sealed:Io,signerId:E,signature:Sr}).strict(),nd=t=>({ownerId:t.ownerId,authorities:t.authorities});async function J5(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||C(r.to)!==C(o.from))||o.previous!==(r?await ee(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Mr(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(nd(t)))throw new Error("Use the authorities approved by the latest handoff.")}function PL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function s$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(nd(t));return r===C(nd(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function X5(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(nd(t.policy))!==C(nd(e))){if(await ko(t),!t.policy.authorities.some(s=>C(s)===C(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=W5.parse({origin:e.origin,id:e.id,revision:e.revision,from:nd(t.policy),to:nd(e),policyDigest:await ee(e),previous:n.length?await ee(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ur(i,o.signing,"authority-handoff")})}return n.length?{lineage:AL.parse(n)}:{}}async function a$(t){let e=en.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Ds(n);let i=C(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!Qc(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ue.function&&i!==ue.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ue.http||i===ue.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ue.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function c$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function eu(t,e){return C({purpose:"resource",policyDigest:await ee(t),materialRevision:e})}async function Rf(t,e,r,o,n,i,s){if(t.byteLength>K5(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await a$(e),c=await X5(s,a,o,n);if(!a.authorities.some(f=>C(f)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Ka(t,c$(a).map(f=>({id:f.id,publicKey:f.encryption})),await eu(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ur(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=tn.parse({...l,signature:await ur(l,n.signing,"resource")});return await ko(d),d}async function ko(t){let e=tn.parse(t),{signature:r,...o}=e;await a$(e.policy),await J5(e.policy,e.lineage);let n=PL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ee(e.policy))throw new Error("The handoff approves a different access policy.");await Mr(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(IL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ue.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Mr(o,r,s.signing,"resource");let a=c$(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||e.sealed.aad!==Cs(tt(await eu(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function Y5(t,e,r,o,n=t.metadata){let i=await ko(t);if(!IL(i.policy.contentType)||!(i.policy.authorities.some(f=>C(f)===C(r))||i.policy.grants.some(f=>C(f.executor)===C(r)&&f.operations.includes(ue.refresh)&&Date.parse(f.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Ka(e,c$(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await eu(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await ur(l,o.signing,"resource")};return await ko(d),d}async function u$(t,e,r,o){let n=await a$(t);if(!n.authorities.some(s=>C(s)===C(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await X5(o,n,e,r),authorityId:e.id,signature:await ur(n,r.signing,"access-policy")};return await tu(i),i}async function tu(t){let e=Ny.parse(t);await a$(e.policy),await J5(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ee(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Mr(e.policy,e.signature,o.signing,"access-policy"),e}async function zy(t,e,r,o,n,i){let s=await tu(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&C(f.executor)===C(o)&&(a.contentType===ge.executionResult||Date.parse(f.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>K5(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Ka(t,c$(a).map(f=>({id:f.id,publicKey:f.encryption})),await eu(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await ur(l,n.signing,"resource")};return await ko(d),d}async function od(t,e,r){let o=await ko(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return Po(o.sealed,r,e.id,await eu(o.policy,o.materialRevision))}var oDe=h.object({id:E,policyDigest:br,materialRevision:h.number().int().positive(),authorizationDigest:br.optional()}).strict();async function kL(t,e){return e.id===t.policy.id&&e.policyDigest===await ee(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||IL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var l$=h.object({format:h.literal(2),id:E,origin:$f,ownerId:E,approval:h.object({id:E,index:h.number().int().min(0).max(7)}).strict().optional(),operationContext:H5.optional(),actor:or,environmentId:E,executor:or,environmentDigest:br,operation:Dy,functionDigest:br.nullable(),functionId:E.optional(),operationDigest:br,sources:h.array(oDe).max(100),resultRecipients:h.array(or).min(1).max(100),resultApproval:Ny.optional(),createdAt:Ae,expiresAt:Ae}).strict(),If=h.object({intent:l$,signature:Sr,sealed:Io}).strict();async function id(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ee(t)})}async function Q5(t,e,r){if(l$.parse(t),await ee(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Ka(tt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await id(t,"input"))};return If.parse({...o,signature:await ur(o,r.signing,"run")})}async function iDe(t,e=Date.now()){let r=If.parse(t),{signature:o,...n}=r;await Mr(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(i.resultApproval){let c=await tu(i.resultApproval),u=c.policy;if(c.authorityId!==i.actor.id||u.id!==i.id||u.origin!==i.origin||u.ownerId!==i.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(i.actor))||C(u.readers)!==C(i.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==i.id||C(u.producers[0].executor)!==C(i.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Cs(tt(await id(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function e8(t,e,r){let o=await iDe(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await Po(o.sealed,r.encryption,e.id,await id(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await ee(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function sd(t,e,r={}){let o=await ko(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await kL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ue.function||e.operation===ue.refresh:e.operation===ue.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ue.command&&e.operation!==ue.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function ru(t,e,r,o={}){return await sd(t,e,o),Po(t.sealed,r.encryption,e.executor.id,await eu(t.policy,t.materialRevision))}var TL=h.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),t8=h.object({format:h.literal(3),id:E,origin:$f,ownerId:E,name:me,executor:or,operatorId:E,driver:h.enum(["attached","managed"]),capabilities:h.array(Dy).min(1).max(6),functionVersion:h.number().int().positive().optional(),resultVersion:h.literal(1).optional(),isolation:h.enum(["process","container"]),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:TL.optional(),revision:h.number().int().positive()}).strict(),CL=h.object({manifest:t8,signature:Sr}).strict();async function OL(t,e){let r=t8.parse(t),o={manifest:r,signature:await ur(r,e.signing,"environment")};return await Pf(o),o}async function Pf(t){let e=CL.parse(t),{manifest:r}=e;if(await Ds(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ue.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(ue.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Mr(r,e.signature,r.executor.signing,"environment"),e}async function kf(t,e){let{manifest:r}=await Pf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ee(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ue.function&&r.functionVersion!==2)throw new Error("This environment does not authorize the requested execution.")}var d$=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),p$=h.object({ok:h.boolean(),result:wr.nullable(),error:h.object({code:h.string().max(100),message:h.string().max(1e3)}).nullable()}).strict(),r8={id:E,intentDigest:br,executorId:E,state:h.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Ae},n8=h.object({...r8,sealed:Io,signature:Sr}).strict(),o8=h.object({...r8,format:h.literal(2),accessDigest:br,proofDigest:br,approval:Ny,content:tn,previousDigest:br.optional(),previous:n8.optional(),signature:Sr}).strict(),My=h.union([n8,o8]),sDe=h.object({result:p$,proof:Sr}).strict(),i8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function DL(t,e,r,o,n,i){await tu(n);let s={format:2,id:t.id,intentDigest:await ee(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await ee(n),...i?{previousDigest:await ee(i)}:{}},a=await ur({...s,resultDigest:await ee(r)},o.signing,"execution-result"),c=tt(C({result:p$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Af;let u=await zy(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await ee(a)},d=o8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ur(l,o.signing,"receipt")});return await NL(d,t),d}var Af=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Tf(t,e,r,o){let n=p$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return DL(t,e,n,o,t.resultApproval);let i=tt(C(n));if(i.byteLength>14e5)throw new Af;let s=await Ka(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await id(t,"result")),a={id:t.id,intentDigest:await ee(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return My.parse({...a,signature:await ur(a,o.signing,"receipt")})}async function NL(t,e){let r=My.parse(t);if("content"in r){await Mr(i8(r),r.signature,e.executor.signing,"receipt");let i=await tu(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await ee(e)||r.executorId!==e.executor.id||r.accessDigest!==await ee(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>C(a)===C(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==ge.executionResult||s.grants.length||e.resultApproval&&C(e.resultApproval)!==C(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await ee(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await NL(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await ko(r.content),!s$(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Mr(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ee(e)||r.executorId!==e.executor.id||r.sealed.aad!==Cs(tt(await id(e,"result")))||C(r.sealed.recipients.map(i=>i.header.kid).sort())!==C(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function s8(t,e,r,o){if(await NL(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await Po(t.content.sealed,o.encryption,r,await eu(t.content.policy,t.content.materialRevision)),a=sDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await ee(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=i8(t);if(await Mr({...u,resultDigest:await ee(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await Po(t.sealed,o.encryption,r,await id(e,"result")),i=p$.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var aDe=h.enum(["http","command","function","connect","refresh","revoke"]),Hn=h.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:aDe,state:d$,intent:l$,requestSignature:Sr,receipt:My.nullable(),error:h.string().nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),f$=h.object({name:me,approval:Ny}).strict(),a8=h.object({kind:h.literal("function"),functionId:E,definition:Qo,arguments:Lt.default({}),outputs:h.record(h.string(),f$).default({})}).strict(),Za=h.discriminatedUnion("kind",[h.object({kind:h.literal("http"),request:Ha,save:h.record(h.string(),f$).default({})}).strict(),h.object({kind:h.literal("command"),...Ba.shape}).strict(),h.object({kind:h.enum(["connect","refresh","revoke"]),input:wr}).strict()]);var nu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Wa=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string()})}).parse(await n.json())}catch{throw new nu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new nu(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},QE)}};import{chmod as cDe,lstat as uDe,mkdir as lDe,open as zL,readFile as u8,rename as dDe,rm as pDe}from"node:fs/promises";import{dirname as fDe,join as ML,resolve as mDe}from"node:path";import{homedir as hDe}from"node:os";import{randomUUID as gDe}from"node:crypto";var UL=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:Ty.nullable(),binding:or.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),l8=h.object({current:h.uuid(),identities:h.array(UL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Ja(){return ML(process.env.XDG_CONFIG_HOME||ML(hDe(),".config"),"foundation","identity.json")}function ou(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function m$(t){let e;try{let n=Ja(),i=await uDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await cDe(n,384);let s=l8.parse(JSON.parse(await u8(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=ou(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==ou(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return UL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==ou(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Uy(t){let e=Ja(),r;try{r=l8.parse(JSON.parse(await u8(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=UL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Cf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
130
130
  `,!!r)}async function c8(t){if(process.platform==="win32")return;let e=await zL(t,"r");try{await e.sync()}finally{await e.close()}}async function Cf(t,e,r){let o=mDe(t),n=fDe(o);if(await lDe(n,{recursive:!0,mode:448}),!r){let s=await zL(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await c8(n);return}let i=ML(n,".foundation-"+gDe());try{let s=await zL(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await dDe(i,o),await c8(n)}finally{await pDe(i,{force:!0})}}import{spawn as _De}from"node:child_process";import{chmod as bDe,mkdtemp as SDe,rm as xDe,writeFile as EDe}from"node:fs/promises";import{tmpdir as $De}from"node:os";import{join as h8}from"node:path";import{StringDecoder as RDe}from"node:string_decoder";import{spawn as d8}from"node:child_process";import{mkdir as p8,mkdtemp as yDe,rm as vDe,writeFile as f8}from"node:fs/promises";import{tmpdir as wDe}from"node:os";import{join as Ly}from"node:path";import{StringDecoder as m8}from"node:string_decoder";function Fi(t={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...t}}var jy=class{constructor(e){this.options=e;if(e.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(e.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(e,r){r.throwIfAborted();let o=await yDe(Ly(wDe(),"foundation-job-")),n=Ly(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=e.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await p8(n,{mode:448});let l={...e.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[f,p]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(f))throw new Error("Use valid file variable names.");await f8(Ly(n,f),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),l[f]=s?"/run/foundation/"+f:Ly(n,f)}let d=e.command;if(s){if(Object.entries(l).some(([m,y])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m)||y.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let f=Object.entries(l).filter(([,m])=>/[\r\n]/.test(m)),p=Ly(o,"environment");await f8(p,Object.entries(l).filter(([,m])=>!/[\r\n]/.test(m)).map(([m,y])=>m+"="+y).join(`
131
- `),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await p8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...f.flatMap(([m,y])=>["--env",m+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(f=>{let p=d8(d[0],d.slice(1),{env:Fi(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),m={stdout:new m8("utf8"),stderr:new m8("utf8")},y=0,w=!1,b=(T,M)=>{let K=Math.max(0,1e6-y);M.length>K&&(c.truncated=!0);let te=M.subarray(0,K);y+=te.length,c[T]+=m[T].write(te)};p.stdout.on("data",T=>b("stdout",T)),p.stderr.on("data",T=>b("stderr",T)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let S=()=>{u=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let R=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=m.stdout.end(),c.stderr+=m.stderr.end(),f())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),p.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",R()}),p.once("close",(T,M)=>{c.exitCode=T,c.signal=M,R()})}),c}finally{s&&u&&await new Promise(l=>{let d=d8("docker",["rm","-f",i],{env:Fi(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await vDe(o,{recursive:!0,force:!0})}}};function IDe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var h$=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new RDe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function g8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await SDe(h8($De(),"foundation-"));await bDe(r,448);try{let o=Fi(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=h8(r,i);await EDe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=_De(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=IDe(n),u=new h$(c,m=>process.stdout.write(m)),l=new h$(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,y)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(m??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await xDe(r,{recursive:!0,force:!0})}}import{dirname as tHe,join as HV}from"node:path";function xr(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"ovh":{let r=t.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,fields:t.config.fields,outputs:Object.keys(t.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function qi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function iu(t){return xr(t).requiresApp}var ADe=new Set(["airtable.com","dash.cloudflare.com","api.ebay.com","accounts.secure.freee.co.jp","github.com","id.heroku.com","api.hubapi.com","api.netlify.com","api.notion.com","api.render.com","login.salesforce.com","cloud.digitalocean.com","api.vultr.com","api.x.com","zoom.us"]);function y8(t){if(!xr(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth")return"available";try{let e=new URL(t.config.tokenUrl).hostname;return ADe.has(e)||e==="login.microsoftonline.com"&&t.config.clientAuth!=="none"?"unavailable":t.config.tokenUrl.includes("{")?"unknown":"available"}catch{return"unknown"}}var PDe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),v8=Lt.refine(t=>Object.keys(t).every(e=>!PDe.has(e)),"Keep method-specific facts separate from common facts."),su=h.object({accountId:h.string().max(2e3).nullable(),accountName:h.string().max(2e3),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),authorization:v8,details:v8}).strict();function LL(t){if(t.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let e="requestedScopes"in t?t.requestedScopes:void 0;return su.parse({accountId:t.oauth?.account??"",accountName:t.oauth?.accountName??"",accountVerified:t.oauth?.accountVerified??!1,scopes:e??t.oauth?.scopes??[],scopesStatus:e?"requested":t.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function jL(t){if(t.method.kind!=="token"||!t.fields)throw new Error("Use token connection material.");return"facts"in t&&t.facts?su.parse(t.facts):su.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function FL(t){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let e="ovh"in t?t.ovh:void 0;if(!e){let r="requestedScopes"in t?t.requestedScopes:void 0;return su.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return su.parse({accountId:e.user?e.account+"/"+e.user:e.account,accountName:e.account+(e.user?" / "+e.user:""),accountVerified:!0,scopes:e.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:e},details:{ovh:e}})}function qL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return su.parse({accountId:t.aws.identity?bf(t.aws.identity.arn):null,accountName:t.aws.identity?t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1):"",accountVerified:!!t.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:w5(t.aws)},details:{aws:_5(t.aws)}})}var kDe={oauth:LL,token:jL,aws:qL,ovh:FL};function Fy(t){return kDe[t.method.kind](t)}var nJ=Vt(j8(),1);var ec=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},tNe=class extends ec{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},rNe=class extends ec{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},nNe=class extends ec{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},oNe=class extends ec{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},iNe=class extends ec{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},sNe=class extends ec{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},aNe=class extends ec{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},R$=class extends ec{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},XL=class extends R${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},cNe=class extends R${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},uNe=class extends R${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},F8=class extends R${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},lNe=class extends ec{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},dNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},pNe=class extends dNe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},fNe=["","+",".","/",";","?","&","#"],Z8={"":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!1},"+":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!0},".":{first:".",sep:".",named:!1,ifEmpty:"",allowReserved:!1},"/":{first:"/",sep:"/",named:!1,ifEmpty:"",allowReserved:!1},";":{first:";",sep:";",named:!0,ifEmpty:"",allowReserved:!1},"?":{first:"?",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"&":{first:"&",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"#":{first:"#",sep:",",named:!1,ifEmpty:"",allowReserved:!0}},mNe=new TextEncoder,q8="0123456789ABCDEF",V8=t=>uu(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),Hy=(t,e)=>t[e]==="%"&&e+2<t.length&&V8(t[e+1])&&V8(t[e+2]);function YL(t,e){let r=t[e];return r==null?0:uu(W8,J8,cd("_"))(r)?1:Hy(t,e)?3:0}function hNe(t,e){if(Hy(t,e))return 3;let{char:r,size:o}=By(t,e);return yNe(r)?o:0}function By(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var rj=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Hy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=By(e,o);r+=uu(X8,s=>t&&gNe(s))(n)?n:Y8(n),o+=i}return r};function Nf(t){let e="";for(let r=0;r<t.length;){if(Hy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=By(t,r);e+=X8(o)?o:Y8(o),r+=n}return e}function Vy(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Hy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=By(t,n);r+=i,n+=s}return r}var W8=t=>uu(En(65,90),En(97,122))(t.charCodeAt(0)),J8=t=>En(48,57)(t.charCodeAt(0)),X8=t=>uu(W8,J8,e=>"-._~".includes(e))(t),gNe=t=>":/?#[]@!$&'()*+,;=".includes(t),yNe=t=>vNe(t.codePointAt(0)),vNe=t=>t!=null&&uu(cd(33),En(35,36),cd(38),En(40,59),cd(61),En(63,91),cd(93),cd(95),En(97,122),cd(126),wNe,_Ne)(t);function wNe(t){if(t<65536)return uu(En(160,55295),En(63744,64975),En(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var _Ne=t=>uu(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),Y8=t=>Array.from(mNe.encode(t)).map(e=>`%${q8[e>>4]}${q8[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,cd=t=>e=>t===e,uu=(...t)=>e=>t.some(r=>r(e));function Q8(t,e,r){return t.map(o=>o.kind==="literal"?o.text:bNe(o.vars,o.operator,e,r)).join("")}function bNe(t,e,r,o){let n=Z8[e],i=t.flatMap(s=>SNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function SNe(t,e,r,o){if(e==null)return[];if(kNe(e)){let n=RNe(e,r.allowReserved);return n.length<1?[]:G8(t,"list",o)?ENe(t,n,r):[]}if(PNe(e)){let n=INe(e,r.allowReserved);return n.length<1?[]:G8(t,"associative",o)?$Ne(t,n,r):[]}return xNe(t,e,r)}function xNe(t,e,r){let o=String(e),n=t.prefix==null?o:Vy(o,t.prefix),i=rj(r.allowReserved)(n);return r.named?[Gy(Nf(t.name),i,r)]:[i]}function ENe(t,e,r){let o=Nf(t.name);if(t.explode)return r.named?e.map(i=>Gy(o,i,r)):[...e];let n=e.join(",");return r.named?[Gy(o,n,r)]:[n]}function $Ne(t,e,r){if(t.explode)return e.map(([n,i])=>Gy(n,i,r));let o=e.flat(1).join(",");return r.named?[Gy(Nf(t.name),o,r)]:[o]}var Gy=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,RNe=(t,e)=>t.filter(r=>r!=null).map(String).map(rj(e)),INe=(t,e)=>Object.entries(t).map(([r,o])=>[r,ANe(o)]).filter(([,r])=>r!=null).map(r=>r.map(rj(e)));function ANe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var PNe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),kNe=t=>Array.isArray(t);function G8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new pNe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function TNe(t,e,r){return QL(t,e,r,0,0,{})}function QL(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=o1e(i);return Q8(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?QL(t,e,r,o+1,n+s.text.length,i):null;for(let a of CNe(t,e,o,n)){let c=e.slice(n,a);for(let u of DNe(s.vars,s.operator,c)){let l=nj(i,u);if(l==null)continue;let d=QL(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*CNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*ONe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*ONe(t,e){for(let r=t;r>=e;r--)yield r}function*DNe(t,e,r){if(r===""){yield*NNe(t,e);return}let o=Z8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?GNe(t,o,n):zNe(t,o,n)}var NNe=(t,e)=>(e===""||e==="+")&&t.length===1?[cu(t[0],"")]:[{}],zNe=(t,e,r)=>ej(t,e,oj(r,e.sep),0,0);function*ej(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of MNe(i,e,r,n))for(let a of ej(t,e,r,o+1,s.index)){let c=nj(s.bindings,a);c!=null&&(yield c)}yield*ej(t,e,r,o+1,n)}function*MNe(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of UNe(t,e,s))yield{bindings:a,index:o+i}}}function*UNe(t,e,r){let o=eJ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*LNe(t,e,r)),yield*o}function*LNe(t,e,r){let o=tJ(r,e.allowReserved);if(o==null)return;let n=jNe(r,e);n!=null&&(yield cu(t,n)),yield cu(t,o)}var jNe=(t,e)=>FNe(t.join(e.sep),e);function FNe(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=qNe(t,i,e.sep),a=Qa(t.slice(o,n),e.allowReserved),c=Qa(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function qNe(t,e,r){for(let o=e;o<t.length;o++)if(VNe(t,o,r))return o;return t.length}var VNe=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*eJ(t,e,r){let o=Qa(r,e.allowReserved);if(o==null)return;let n=cu(t,o);if(t.prefix!=null){yield n;return}let i=oj(r,",");if(i.length<2){yield n;return}let s=tJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?QNe(i,e.allowReserved):null;a!=null&&(yield cu(t,a)),yield cu(t,s),yield n}var GNe=(t,e,r)=>tj(t,e,oj(r,e.sep).map(YNe),0,0);function*tj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of HNe(i,e,r,n,t))for(let a of tj(t,e,r,o+1,s.index)){let c=nj(s.bindings,a);c!=null&&(yield c)}yield*tj(t,e,r,o+1,n)}function*HNe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*KNe(t,e,r,o,n);return}yield*BNe(t,e,r,o)}}function*BNe(t,e,r,o){let n=r[o];if(n.name===Nf(t.name))for(let i of eJ(t,e,n.value))yield{bindings:i,index:o+1}}function*KNe(t,e,r,o,n){yield*ZNe(t,e,r,o),yield*JNe(t,e,r,o,n)}function*ZNe(t,e,r,o){let n=[...WNe(Nf(t.name),e,r,o)];n.length>0&&(yield{bindings:cu(t,n),index:o+n.length})}function*WNe(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Qa(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*JNe(t,e,r,o,n){let i=[...XNe(e,r,o,new Set(n.map(s=>Nf(s.name))))];i.length>0&&(yield{bindings:cu(t,Object.fromEntries(i)),index:o+i.length})}function*XNe(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=Qa(i.name,t.allowReserved),a=Qa(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function YNe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function QNe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Qa(t[o],e),i=Qa(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function tJ(t,e){let r=[];for(let o of t){let n=Qa(o,e);if(n==null)return null;r.push(n)}return r}function Qa(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var cu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function nj(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=e1e(i,n);if(s==null)return null;r[o]=s}return r}var e1e=(t,e)=>$$(t)||$$(e)?t1e(t,e):r1e(t.value,e.value)?t:null;function t1e(t,e){let r=H8(t.value),o=H8(e.value);if(r==null||o==null)return null;let n=$$(t),i=$$(e);if(!n&&!i)return null;if(n&&!i)return Vy(o,t.prefix)===r?e:null;if(!n&&i)return Vy(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Vy(o,s)===r?e:null:Vy(r,a)===o?t:null}var $$=t=>t.prefix!=null,H8=t=>typeof t=="string"?t:null;function r1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):B8(t)?B8(e)&&n1e(Object.entries(t),Object.entries(e)):t===e}var n1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),B8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),o1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),oj=(t,e)=>e===""?[t]:t.split(e),i1e=["=",",","!","@","|"];function s1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new iNe(e,r));let n=t[0];if(l1e(n))return o(new sNe(e,r+1,n));if(!K8(n)&&YL(t,0)<1)return o(new aNe(e,r+1,n));let i=K8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:a1e(t,e,r+1,s)}}function a1e(t,e,r,o){if(o>=t.length)throw new XL(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new F8(e,r+i):new XL(e,r+i);let s=i,a=c1e(t,i);if(a===s)throw new XL(e,r+i);let c=t.slice(s,a);i=a;let u=u1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new lNe(e,r+i,t[i]):new cNe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new F8(e,r+i-1)}return n}function c1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=YL(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||YL(t,r+1)<1)break;r++,o=!0}return r}function u1e(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&d1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new uNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function K8(t){return fNe.includes(t)&&t!==""}function l1e(t){return i1e.includes(t)}function d1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function p1e(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new tNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new nNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(s1e(f,t,i))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new rNe(t,i)),n(s),i++;continue}let a=hNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=By(t,i);r(new oNe(t,i,c)),n(c),i+=u}return o}var I$=class rJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=y1e(r),this.#e=f1e(p1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new rJ(e,r)}get tokens(){return this.#e}expand=e=>Q8(this.#e,e,this.#t);match=e=>TNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},f1e=t=>Object.freeze(t.map(m1e)),m1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(h1e))}),h1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),g1e=()=>{},y1e=({strict:t,report:e})=>(e??=g1e,t??=!0,e=t?v1e(e):e,{strict:t,report:e}),v1e=t=>e=>{throw t(e),e};var tc=class extends Error{constructor(r,o){super(o);this.code=r}code};function A$(t,e,r={}){let o=(i,s)=>{throw new tc(i,s)},n={...r,...e};for(let i of t)i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,nJ.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.");return Object.keys(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function lu(t,e,r={}){let o=A$(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new tc("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function P$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new tc("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new tc("encrypted_input_required","Supply private material directly with your encryption keys.")}return A$(t.map(r=>({...r,required:!1})),e)}function lo(t,e){return P$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function zf(t,e,r){P$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new tc("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}function oJ(t,e=Fy(t)){return e.accountVerified?e.accountId:null}function iJ(t,e=Fy(t)){let o=(t.method.kind==="oauth"||t.method.kind==="ovh"||t.method.kind==="token"&&!!t.method.config.identity)&&t.method.kind!=="aws"?lo(t.method.config.fields,t.fields??{}):{};return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...Object.keys(o).length?{fields:o}:{},...e.authorization,...t.state?{state:t.state}:{}}}var ld=h.record(h.string().max(100),h.string().max(16384)),po=h.object({format:h.literal(1),methodId:h.string().min(1),generation:E,clientId:h.string().max(1e3),clientSecret:h.string().max(16384).optional(),fields:ld}).strict(),ij=h.object({accessToken:h.string().min(1).max(16384),refreshToken:h.string().min(1).max(16384).optional(),expiresAt:h.number().nullable(),refreshExpiresAt:h.number().optional(),scopes:h.array(h.string()),requestedScopes:h.array(h.string()).optional(),account:h.string(),accountName:h.string(),accountVerified:h.boolean().optional(),scopesStatus:h.enum(["unknown","requested","reported"]).optional(),extra:ld,facts:Lt}).strict(),k$={format:h.literal(2),methodId:h.string().min(1),method:Xc,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:h.literal("reconnect").optional()},ud=h.never().optional(),Bn=h.union([h.object({...k$,method:BE,oauth:ij.optional(),requestedScopes:h.array(h.string()).optional(),fields:ld.optional(),aws:ud}).strict(),h.object({...k$,method:KE,fields:ld,facts:su.optional(),oauth:ud,aws:ud}).strict(),h.object({...k$,method:WE,fields:ld,ovh:Ay.optional(),requestedScopes:h.array(h.string()).optional(),oauth:ud,aws:ud}).strict(),h.object({...k$,method:ZE,aws:UE,oauth:ud,fields:ud}).strict()]).superRefine((t,e)=>{if(t.method.kind==="oauth"&&t.fields)try{P$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}iu(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the application required by this connection."}),!iu(t.method)&&t.appId!==null&&e.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!("requestedScopes"in t&&t.requestedScopes)&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),Pbt=h.object({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),generation:E,fields:ld.optional()}).strict(),w1e=h.object({methodId:h.string().min(1).max(200),methodKind:yL,generation:E,authorizationDigest:br,appId:E.nullable(),accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),outputs:h.array(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:h.enum(["ready","reconnect"]),fields:ld.optional(),aws:LE.optional(),ovh:Ay.optional()}).strict();async function Mf(t,e=Fy(t)){let r=xr(t.method).outputs,o=t.method.kind!=="aws"&&t.fields?lo(t.method.config.fields,t.fields):{},n=await ee(iJ(t,e));return w1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:n,appId:t.appId,accountId:oJ(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...Object.keys(o).length?{fields:o}:{},...e.details})}var _1e=h.array(h.object({name:h.string(),label:h.string(),value:h.string()}).strict()),sJ=h.object({methodName:me,account:h.string().max(2e3),settings:_1e.optional()}).strict();function T$(t){let e=xr(t.method).fields,r=t.method.kind!=="aws"&&t.fields?lo(e,t.fields):{},o=e.filter(n=>r[n.name]).map(n=>({name:n.name,label:n.label,value:n.choices?.find(i=>i.value===r[n.name])?.label??r[n.name]}));return{methodName:t.method.name,account:"",...o.length?{settings:o}:{}}}var sj=h.discriminatedUnion("action",[h.object({action:h.literal("refresh"),id:E}).strict(),h.object({action:h.literal("revoke"),id:E}).strict()]);var aJ=Os.extend({name:me}),Ubt=h.object({bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Os,token:h.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),cJ=h.object({id:E,executorId:E,ownerId:E,name:me,origin:h.url(),bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:h.object({port:h.number().int().min(1).max(65535)}).strict().optional(),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),Lbt=Os.extend({previousSignature:Sr.optional()}).strict(),uJ=h.object({name:me,content:tn,labels:sJ.optional(),version:h.number().int().positive().optional()}).strict(),C$=h.object({content:tn,version:h.number().int().positive()}).strict(),lJ=h.object({id:E,reason:h.enum(["grantExpired"])}).strict(),jbt=h.record(E,h.object({version:h.number().int().positive(),content:tn}).strict()),dJ=h.object({id:E,name:me,version:h.number().int().positive(),content:tn,policy:en}).strict(),pJ=h.object({registration:CL,stoppedAt:h.iso.datetime().nullable(),heartbeatAt:h.iso.datetime().nullable()}).strict(),fJ=h.object({lease:E,request:If,sources:h.array(tn).max(100)}).strict().nullable(),b1e=h.object({lease:E}).strict(),Fbt=b1e.extend({receipt:My}).strict(),Ky=h.object({id:E,resource_id:E,executor_id:E,expected_revision:h.number().int().positive(),state:h.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:h.string().regex(/^\d+$/),result:tn.nullable()}),qbt=h.object({id:E,resourceId:E,expectedRevision:h.number().int().positive()}).strict(),S1e=h.object({fence:h.string().regex(/^\d+$/)}).strict(),Vbt=S1e.extend({content:tn}).strict(),Gbt=h.object({id:E,executionId:E,index:h.number().int().nonnegative(),stateDigest:br,expiresAt:Ae}).strict(),aj=h.object({id:E,executionId:E,context:h.string(),sealed:Io.nullable(),expiresAt:Ae,receivedAt:Ae.nullable()}).strict(),mJ=(t,e)=>"oauth-callback:"+t+":"+e;var rc=class extends Error{constructor(r,o){super(o);this.code=r}code},cj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},O$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||C(r)!==C(e))throw new rc("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Os);return await $L(r),{...r,fingerprint:await rd(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new rc("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},pJ);if(await Pf(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},Qr(aJ));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await $L(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},C$);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await ko(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=PL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&en.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await ee(o)!==i.digest)throw new rc("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!s$(i.policy,o))throw new rc("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return od((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Qr(dJ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||C(i.content)!==C(n.content))throw new rc("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await Rf(await od(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...Qc(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return en.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await Rf(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},_r);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await Rf(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},h.union([_r,Ze]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Qr(lJ))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},_r),a=await od(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ge.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Qr(_r));s=d.items.find(f=>f.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ge.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await u$(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Za.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],f=await this.sourceContents([...d,...n.sourceIds??[]]);for(let w=0;w<f.length;w++){let b=f[w],S=b.policy.contentType===ge.clientCredential,x=S&&i.kind!=="revoke"?ue.refresh:ue[i.kind],R=S?void 0:l?new URL(l.url).origin:void 0;if(b.policy.grants.some(fe=>"actor"in fe&&C(fe.actor)===C(this.binding)&&C(fe.executor)===C(s.manifest.executor)&&fe.operations.includes(x)&&Date.parse(fe.expiresAt)>=Date.parse(c)&&(!R||!fe.origins.length||fe.origins.includes(R))&&(S||fe.callerProgram))||!b.policy.authorities.some(fe=>C(fe)===C(this.binding)))continue;let M=await this.read(b.policy.id),K=await this.api.json("/api/resources/"+b.policy.id,{},_r),te={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[ue.refresh]:[]])],origins:R?[R]:[],functionDigests:[],callerProgram:!S,expiresAt:c},Ie=fe=>C({...fe,expiresAt:null}),Te=M.content.policy.grants.filter(fe=>Ie(fe)===Ie(te)),bt=en.parse({...M.content.policy,revision:M.content.policy.revision+1,grants:[...M.content.policy.grants.filter(fe=>Date.parse(fe.expiresAt)>Date.now()&&Ie(fe)!==Ie(te)),{...te,expiresAt:new Date(Math.max(Date.parse(c),...Te.map(fe=>Date.parse(fe.expiresAt)))).toISOString()}]});await this.save(K.name,await od(M.content,this.binding,this.keys.encryption),bt,{previous:M,metadata:M.content.metadata}),f[w]=(await this.read(b.policy.id)).content}let p=await this.policy(e,ge.executionResult,[],{id:a});p.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let m={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await ee(s.manifest),operation:ue[i.kind],operationDigest:await ee(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(f.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await ee(w.policy),...w.policy.contentType===ge.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:p.readers,...s.manifest.resultVersion?{resultApproval:await u$(p,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await kf(s,m);let y=w=>w.policy.contentType===ge.clientCredential;for(let w of f)await sd(w,y(w)&&m.operation!==ue.connect&&m.operation!==ue.revoke?{...m,operation:ue.refresh}:m,y(w)?{}:{destination:l?.url});return Q5(m,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},Hn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new cj(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},Hn);if(C(o.intent)!==C(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await EL(e.requestSignature,e.intent.actor.signing,"run");if(C(r.intent)!==C(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new rc("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?s8(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(C(e.intent.actor)!==C(this.binding)||C(e.intent.executor)!==C(this.binding))throw new rc("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,ge.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await DL(e.intent,e.receipt.state,r,this.keys,await u$(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},Hn)}};import{lstat as x1e,mkdir as E1e,readFile as $1e,readdir as R1e}from"node:fs/promises";import{join as hJ}from"node:path";var gJ=h.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),dd=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:gJ.parse(e)})}async read(e){let r=this.context(e),o=hJ(this.directory,e+".json");try{let n=await x1e(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=h.string().max(32e6).parse(JSON.parse(await $1e(o,"utf8"))),s=await Sy(i,await Yo(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(Ao(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await Mr({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await ur(n,this.privateKeys.signing,"journal"),s=tt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new _f(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Yo(this.binding.encryption,"ECDH-ES+A256KW"));await E1e(this.directory,{recursive:!0,mode:448}),await Cf(hJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await R1e(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>gJ.parse(o.name.slice(0,-5)))}};var D$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Ds(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await ee(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&C(r)!==C(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var dt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function J(t,e,r,o){throw new dt(t,e,r,o)}var N$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},fJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},Hn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},h.object({id:E}))}connections(){let e=this.api;return{prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Ky),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Ky),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},tn),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Ky),state:r=>e.json("/api/connections/"+r+"/operation",{},Ky.nullable())}}};import{randomUUID as W3e}from"node:crypto";var gc=Vt(RV(),1);import{randomUUID as HGe}from"node:crypto";function ede(t){let e=ME.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&J(502,"invalid_response","The AWS account could not be verified."),e.data}function tde(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&bf(t.arn)===bf(e.arn)}function IV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&J(409,"reconnect_required","Reconnect with current AWS credentials.")}var rk=class{async obtain(e,r,o){let n=Ga.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};IV(s?.expiration);let a=new gc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();IV(d.expiration),c=new gc.STSClient({region:n.region,credentials:d});let f=r?.sourceIdentity?ede(await c.send(new gc.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&f&&!tde(f,r.sourceIdentity)&&J(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,m=f;if(n.role){l=!0;let b=(await c.send(new gc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+HGe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&J(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},IV(p.expiration),r?.identity&&(c.destroy(),c=new gc.STSClient({region:n.region,credentials:p}),m=ede(await c.send(new gc.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&m&&!tde(m,r.identity)&&J(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:UE.parse({...n,sourceIdentity:f,identity:m}),credentials:{AWS_ACCESS_KEY_ID:p.accessKeyId,AWS_SECRET_ACCESS_KEY:p.secretAccessKey,AWS_SESSION_TOKEN:p.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&J(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&J(409,"reconnect_required","Reconnect with current AWS credentials."),l&&J(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),J(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var nk=class{constructor(e){this.aws=e}aws;facts=qL;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var AV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(AV="oauth4webapi/v3.8.8");function lk(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var ba="ERR_INVALID_ARG_VALUE",yc="ERR_INVALID_ARG_TYPE";function Or(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var ode=Symbol(),BGe=Symbol(),KGe=Symbol(),MV=Symbol();var ok=Symbol();var ZGe=new TextEncoder,WGe=new TextDecoder;function PV(t){return typeof t=="string"?ZGe.encode(t):WGe.decode(t)}var kV;Uint8Array.prototype.toBase64?kV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):kV=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var TV;Uint8Array.fromBase64?TV=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Or("The input to be decoded is not correctly encoded.",ba,e)}}:TV=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw Or("The input to be decoded is not correctly encoded.",ba,e)}};function CV(t){return typeof t=="string"?TV(t):kV(t)}var sh=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=I3e,Error.captureStackTrace?.(this,this.constructor)}},Yw=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function De(t,e,r){return new Yw(t,{code:e,cause:r})}function ik(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function ide(t){lk(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(AV&&!e.has("user-agent")&&e.set("user-agent",AV),e.has("authorization"))throw Or('"options.headers" must not include the "authorization" header name',ba);return e}function JGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Or('"options.signal" must return or be an instance of AbortSignal',yc);return e}}function sk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Or(`${r} must be a number`,yc,n);if(t>0)return;if(e){if(t!==0)throw Or(`${r} must be a non-negative number`,ba,n);return}throw Or(`${r} must be a positive number`,ba,n)}catch(i){throw o?De(i.message,o,n):i}}function Cn(t,e,r,o){try{if(typeof t!="string")throw Or(`${e} must be a string`,yc,o);if(t.length===0)throw Or(`${e} must not be empty`,ba,o)}catch(n){throw r?De(n.message,r,o):n}}function sde(t){YGe(t,"application/json")}function XGe(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return De(r,P3e,t)}function YGe(t,e){if(p3e(t)!==e)throw XGe(t,e)}async function ade(t){return Cn(t,"codeVerifier"),CV(await crypto.subtle.digest("SHA-256",PV(t)))}function cde(t){let e=t?.[BGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function ude(t){let e=t?.[KGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function lde(){return Math.floor(Date.now()/1e3)}function ch(t){if(typeof t!="object"||t===null)throw Or('"as" must be an object',yc);Cn(t.issuer,'"as.issuer"')}function uh(t){if(typeof t!="object"||t===null)throw Or('"client" must be an object',yc);Cn(t.client_id,'"client.client_id"')}function rde(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function dde(t){return Cn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function pde(t){return Cn(t,'"clientSecret"'),(e,r,o,n)=>{let i=rde(r.client_id),s=rde(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function fde(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var QGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function e3e(t,e){if(e&&t.protocol!=="https:")throw De("only requests to HTTPS are allowed",T3e,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw De("only HTTP and HTTPS requests are allowed",C3e,t)}function nde(t,e,r,o){let n;if(typeof t!="string"||!(n=QGe(t)))throw De(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?O3e:D3e,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return e3e(n,o),n}function mde(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?nde(t.mtls_endpoint_aliases[e],e,r,o):nde(t[e],e,r,o)}var OV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=R3e,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Qw=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=A3e,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},DV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=$3e,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},ak="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",t3e="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",r3e='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',n3e="("+ak+")\\s*=\\s*"+r3e,o3e="("+ak+")\\s*=\\s*("+ak+")",i3e=new RegExp("^[,\\s]*("+ak+")"),s3e=new RegExp("^[,\\s]*"+n3e+"[,\\s]*(.*)"),a3e=new RegExp("^[,\\s]*"+o3e+"[,\\s]*(.*)"),c3e=new RegExp("^("+t3e+")(?:$|[,\\s])(.*)");function u3e(t){if(!lk(t,Response))throw Or('"response" must be an instance of Response',yc);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(i3e),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let f,p;if(n=o.match(s3e)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(a3e)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(c3e)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function l3e(t){if(t.status>399&&t.status<500){Tde(t),sde(t);try{let e=await t.clone().json();if(ik(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function hde(t,e,r){if(t.status!==e){m3e(t);let o;throw(o=await l3e(t))?(await t.body?.cancel(),new OV("server responded with an error in the response body",{cause:o,response:t})):De(`"response" is not a conform ${r} response (unexpected HTTP status code)`,k3e,t)}}function d3e(t){if(!LV.has(t))throw Or('"options.DPoP" is not a valid DPoPHandle',ba)}function p3e(t){return t.headers.get("content-type")?.split(";")[0]}async function gde(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[MV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:JGe(o,s?.signal)})}async function UV(t,e,r,o,n,i){let s=mde(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[ode]!==!0);n.set("grant_type",o);let a=ide(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(d3e(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await gde(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function yde(t,e,r,o,n){ch(t),uh(e),Cn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),UV(t,e,r,"refresh_token",i,n)}var vde=new WeakMap,f3e=new WeakMap;function wde(t){if(!t.id_token)return;let e=vde.get(t);if(!e)throw Or('"ref" was already garbage collected or did not resolve from the proper sources',ba);return e}async function dk(t,e,r,o,n,i){if(ch(t),uh(e),!lk(r,Response))throw Or('"response" must be an instance of Response',yc);await hde(r,200,"Token Endpoint"),Tde(r);let s=await L3e(r);if(Cn(s.access_token,'"response" body "access_token" property',Mt,{body:s}),Cn(s.token_type,'"response" body "token_type" property',Mt,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;sk(a,!0,'"response" body "expires_in" property',Mt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&Cn(s.refresh_token,'"response" body "refresh_token" property',Mt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw De('"response" body "scope" property must be a string',Mt,{body:s});if(s.id_token!==void 0){Cn(s.id_token,'"response" body "id_token" property',Mt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(sk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await _3e(t,e,s.id_token,a,n);S3e(e,c),b3e(c),f3e.set(r,u),vde.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new sh("unsupported `token_type` value",{cause:{body:s}});return s}function m3e(t){let e;if(e=u3e(t))throw new DV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function _de(t,e,r,o){return dk(t,e,r,void 0,o?.[ok],o?.recognizedTokenTypes)}function h3e(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw De('unexpected JWT "aud" (audience) claim value',ah,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw De('unexpected JWT "aud" (audience) claim value',ah,{expected:t,claims:e.claims,claim:"aud"});return e}function g3e(t,e){let r=t[j3e]?.(e)??t.issuer;if(e.claims.iss!==r)throw De('unexpected JWT "iss" (issuer) claim value',ah,{expected:r,claims:e.claims,claim:"iss"});return e}var LV=new WeakSet;function y3e(t){return LV.add(t),t}var jV=Symbol();async function bde(t,e,r,o,n,i,s){if(ch(t),uh(e),!LV.has(o))throw Or('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ba);Cn(n,'"redirectUri"');let a=Bd(o,"code");if(!a)throw De('no authorization code in "callbackParameters"',Mt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==jV&&(Cn(i,'"codeVerifier"'),c.set("code_verifier",i)),UV(t,e,r,"authorization_code",c,s)}var Sde={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function v3e(t,e){for(let r of t)if(e.claims[r]===void 0)throw De(`JWT "${r}" (${Sde[r]}) claim missing`,Mt,{claims:e.claims});return e}function w3e(t,e){if(typeof e.claims[t]!="string")throw De(`unexpected JWT "${t}" (${Sde[t]}) claim type`,Mt,{claims:e.claims});return e}function _3e(t,e,r,o,n){return N3e(r,z3e.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),cde(e),ude(e),n).then(v3e.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(g3e.bind(void 0,t)).then(h3e.bind(void 0,e.client_id)).then(w3e.bind(void 0,"sub"))}function xde(t,e){if(e===uk)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?uk:(sk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function b3e(t){t.auth_time!==void 0&&sk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Mt,{claims:t})}function Ede(t,e,r){if(r===uk)return;let o=lde()+cde(t),n=ude(t);if(e.auth_time+r<o-n)throw De("too much time has elapsed since the last End-User authentication",zV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function $de(t,e){let r=e===ck?void 0:e;if(t.nonce!==r)throw De('unexpected ID Token "nonce" claim value',ah,{expected:r,claims:t,claim:"nonce"})}function S3e(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw De('ID Token "aud" (audience) claim includes additional untrusted audiences',ah,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw De('unexpected ID Token "azp" (authorized party) claim value',ah,{expected:t.client_id,claims:e,claim:"azp"})}}var ck=Symbol(),uk=Symbol();async function Rde(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?x3e(t,e,r,o.expectedNonce,o.maxAge,o[ok],o.recognizedTokenTypes):E3e(t,e,r,o?.maxAge,o?.[ok],o?.recognizedTokenTypes)}async function x3e(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=ck;break;case ck:break;default:Cn(o,'"expectedNonce" argument'),a.push("nonce")}n=xde(e,n),n!==uk&&a.push("auth_time");let c=await dk(t,e,r,a,i,s);Cn(c.id_token,'"response" body "id_token" property',Mt,{body:c});let u=wde(c);return Ede(e,u,n),$de(u,o),c}async function E3e(t,e,r,o,n,i){let s=await dk(t,e,r,void 0,n,i),a=wde(s);return a&&(Ede(e,a,xde(e,o)),$de(a,ck)),s}var $3e="OAUTH_WWW_AUTHENTICATE_CHALLENGE",R3e="OAUTH_RESPONSE_BODY_ERROR",I3e="OAUTH_UNSUPPORTED_OPERATION",A3e="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var NV="OAUTH_PARSE_ERROR",Mt="OAUTH_INVALID_RESPONSE";var P3e="OAUTH_RESPONSE_IS_NOT_JSON",k3e="OAUTH_RESPONSE_IS_NOT_CONFORM",T3e="OAUTH_HTTP_REQUEST_FORBIDDEN",C3e="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",zV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",ah="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var O3e="OAUTH_MISSING_SERVER_METADATA",D3e="OAUTH_INVALID_SERVER_METADATA";async function Ide(t,e,r,o,n){return ch(t),uh(e),UV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Ade(t,e,r,o){return dk(t,e,r,void 0,o?.[ok],o?.recognizedTokenTypes)}async function Pde(t,e,r,o,n){ch(t),uh(e),Cn(o,'"token"');let i=mde(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[ode]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=ide(n?.headers);return a.delete("accept"),gde(t,e,r,i,s,a,n)}async function kde(t){if(!lk(t,Response))throw Or('"response" must be an instance of Response',yc);await hde(t,200,"Revocation Endpoint")}function Tde(t){if(t.bodyUsed)throw Or('"response" body has been used already',ba)}async function N3e(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new sh("JWE decryption is not configured",{cause:t});if(a!==3)throw De("Invalid JWT",Mt,t);let c;try{c=JSON.parse(PV(CV(i)))}catch(d){throw De("failed to parse JWT Header body as base64url encoded JSON",NV,d)}if(!ik(c))throw De("JWT Header must be a top level object",Mt,t);if(e(c),c.crit!==void 0)throw new sh('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(PV(CV(s)))}catch(d){throw De("failed to parse JWT Payload body as base64url encoded JSON",NV,d)}if(!ik(u))throw De("JWT Payload must be a top level object",Mt,t);let l=lde()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw De('unexpected JWT "exp" (expiration time) claim type',Mt,{claims:u});if(u.exp<=l-o)throw De('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',zV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw De('unexpected JWT "iat" (issued at) claim type',Mt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw De('unexpected JWT "iss" (issuer) claim type',Mt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw De('unexpected JWT "nbf" (not before) claim type',Mt,{claims:u});if(u.nbf>l+o)throw De('unexpected JWT "nbf" (not before) claim value',zV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw De('unexpected JWT "aud" (audience) claim type',Mt,{claims:u});return{header:c,claims:u,jwt:t}}function z3e(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:r,reason:"default value"});return}throw De('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Bd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw De(`"${e}" parameter must be provided only once`,Mt);return r}var M3e=Symbol(),U3e=Symbol();function Cde(t,e,r,o){if(ch(t),uh(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Or('"parameters" must be an instance of URLSearchParams, or URL',yc);if(Bd(r,"response"))throw De('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Mt,{parameters:r});let n=Bd(r,"iss"),i=Bd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw De('response parameter "iss" (issuer) missing',Mt,{parameters:r});if(n&&n!==t.issuer)throw De('unexpected "iss" (issuer) response parameter value',Mt,{expected:t.issuer,parameters:r});switch(o){case void 0:case U3e:if(i!==void 0)throw De('unexpected "state" response parameter encountered',Mt,{expected:void 0,parameters:r});break;case M3e:break;default:if(Cn(o,'"expectedState" argument'),i!==o)throw De(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Mt,{expected:o,parameters:r})}if(Bd(r,"error"))throw new Qw("authorization response from the server is an error",{cause:r});let a=Bd(r,"id_token"),c=Bd(r,"token");if(a!==void 0||c!==void 0)throw new sh("implicit and hybrid flows are not supported");return y3e(new URLSearchParams(r))}async function L3e(t,e=sde){let r;try{r=await t.json()}catch(o){throw e(t),De('failed to parse "response" body as JSON',NV,o)}if(!ik(r))throw De('"response" body must be a top level object',Mt,{body:r});return r}var j3e=Symbol();function e_(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function bi(t,e){for(let r of e_(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function FV(t,e,r){let o=e_(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function nl(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function ol(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}var lh=Vt(Dde(),1);var q3e=lh.default.IPv6.parseCIDR("2000::/3"),V3e=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function mk(t){if(!lh.default.isValid(t)||t.includes("%"))return!1;let e=lh.default.parse(t);return V3e.has(e.range())&&(!(e instanceof lh.default.IPv6)||e.match(q3e))}function Si(t,e){let r;try{r=new URL(t)}catch{J(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&J(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||lh.default.isValid(o)&&!mk(o))&&J(400,"private_destination","Choose a public HTTPS destination."),r}function dh(t){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.body))}catch{J(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&J(502,"invalid_response","The service returned an invalid response."),e}var fk=class{constructor(e){this.origin=e}origin;async send(e){let r=Si(e.url,this.origin),o=e.maxBytes??1048576;e.body&&(typeof e.body=="string"?new TextEncoder().encode(e.body).length:e.body.length)>o&&J(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:e.method??"GET",headers:e.headers,body:typeof e.body=="string"?e.body:e.body?new Uint8Array(e.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]])})}catch{e.signal?.aborted&&J(409,"cancelled","The operation was cancelled."),J(409,"browser_exchange_unavailable","Restart authorization using the CLI on this device.")}let i=n.body?.getReader(),s=[],a=0;if(i)try{for(;;){let l=await i.read();if(l.done)break;a+=l.value.length,a>o&&J(413,"body_limit","The response body is too large."),s.push(l.value)}}finally{await i.cancel()}let c=new Uint8Array(a),u=0;for(let l of s)c.set(l,u),u+=l.length;return{status:n.status,headers:Object.fromEntries(n.headers),body:c}}};function qV(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Nde=Object.assign(Object.create(null),{dpop:()=>J(502,"invalid_response","The service returned an unsupported token.")}),G3e={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Nde,{"user access token":()=>{}})},H3e={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&J(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},B3e={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+qV(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},K3e={tokenParameters(t){let e=t.get("redirect_uri");e!==null&&(t.set("redirect_url",e),t.delete("redirect_uri"))}};function Sa(t,e){let r=e?new URL(e):void 0;return{recognizedTokenTypes:Nde,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...t.adapter==="ebay"?G3e:t.adapter==="openrouter"?H3e:t.adapter==="vultr"?K3e:{},...t.revoke?.style==="github"?B3e:{}}}function vc(t,e){try{return Si(new I$(t).expand(e)).href}catch{J(400,"invalid_service_url","Check the service URL and its required fields.")}}var zde=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],hk=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&J(502,"invalid_response","The service returned an invalid expiry."),e};var Kd=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...lu(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof tc&&J(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&J(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(vc(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:Sa(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await ade(n),c.code_challenge_method="S256"),Sa(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(vc(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:vc(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Si(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?fde():(e.clientSecret||J(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?pde(e.clientSecret):dde(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[MV]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);e&&Sa(e).tokenParameters?.(c);let u=await this.transport.send({url:o,method:s,headers:r==="json"?{...i,"content-type":"application/json"}:i,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(e){return dh({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&bi(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&J(409,"reconnect_required","Reconnect this service to renew access."),r===429&&J(503,"service_rate_limit","The service is busy. Try again later."),J(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&J(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,Sa(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=hk(u.expires_in));try{let d=await(n?_de:e.grantType==="client_credentials"?Ade:Rde)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:Sa(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;J(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[Sa(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&J(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+hk(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&J(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?zde(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+hk(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&J(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=Sa(e);if(l.exchange){let f=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>vc(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,f.status,dh(f))}else{let{server:f,client:p}=this.configuration(e,r),m;try{let y=Cde(f,p,o.parameters,o.state);m=await bde(f,p,this.authentication(r,e.clientAuth),y,l.redirectUri?.(r,i)??i,e.pkce?n:jV,{...this.options(e),additionalParameters:e.tokenParams})}catch(y){throw(y instanceof Yw||y instanceof Qw)&&J(400,"invalid_state","Start the connection again."),y}u=await this.tokenResponse(e,r,m)}let d=this.token(e,u,s,a);return await c?.(d,u),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&J(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=Sa(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Ide(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e)),d=await this.tokenResponse(e,r,l),f={...this.token(e,d,o,n,!!n),requestedScopes:o};return await i?.(f,d),f}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||J(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&J(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await yde(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return i}async revoke(e,r,o){e.revoke||J(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=vc(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Pde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await kde(d)}catch{J(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+qV(r.clientId,r.clientSecret??"")),(await this.transport.send(Sa(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&J(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,nl(bi(n,s))]))}};function VV(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function GV(t){return t||J(409,"app_required","Choose an OAuth application."),t}function Z3e(t){return{token:ij.parse(t.token),response:Lt.parse(t.response)}}var gk=class{constructor(e){this.transport=e}transport;facts=LL;oauth(e){return new Kd({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(e){return!e.oauth||e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=e.material,o=VV(r),n=GV(e.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>e.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(e.signal).clientCredentials(o,n,i??qi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return Bn.parse({...e.material,oauth:a})}async recover(e,r,o){let i=Z3e(o).token;return Bn.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(VV(e),GV(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(VV(e),GV(r),e.oauth)}};function Mde(t){if(t.method.kind!=="token")throw new Error("Use a token connection provider.");return t.method.config}var yk=class{facts=jL;needsRenewal(){return!1}async outputs(e){let r=lu(Mde(e).fields,e.fields);return Object.fromEntries(Object.entries(Mde(e).outputs).map(([o,n])=>[o,nl(bi(r,n))]))}};function vk(t){if(t.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return t.method.config}var wk=class{facts=FL;values(e,r){let o=vk(e),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&J(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:e.fields;return lu(o.fields,i)}credentials(e,r){if(vk(e).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:e.fields.consumerKey};let o=this.values(e,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(e,r){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o="ovh"in e?e.ovh:void 0;o&&o.expiresAt!==null&&o.expiresAt<=Date.now()&&J(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=vk(e).authorization==="consumer_key"?{...this.values(e,r),...this.credentials(e,r)}:this.values(e,r);return Object.fromEntries(Object.entries(vk(e).outputs).map(([i,s])=>[i,nl(bi(n,s))]))}};function Ude(t,e){return{oauth:new gk(t),token:new yk,aws:new nk(e),ovh:new wk}}function xa(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function _k(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!T5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=tt(nl(bi(JSON.parse(xa(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=xa(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var ph=class{constructor(e,r,o,n,i,s=new rk){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=Ude(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers[xr(e).family]}metadata(e){return Mf(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||J(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=Bn.safeParse(JSON.parse(xa(await ru(e,r,this.keys,{destination:o}))));n.success||J(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&J(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==ue.revoke&&J(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,ge.clientCredential,n),s=po.parse(JSON.parse(xa(await ru(i,o,this.keys))));return s.methodId!==r&&J(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(xr(e.method).application==="none")return null;if(!iu(e.method))return po.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===ue.revoke?ue.revoke:ue.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&J(409,"app_changed","Reconnect this service with the current application."),xr(e.method).requiresApp&&e.method.kind!=="aws"&&Object.entries(lo(e.method.config.fields,e.fields??{})).some(([s,a])=>i.fields[s]!==a)&&J(409,"app_changed","Reconnect this service with the current application settings."),i}async validate(e,r,o){let n=sj.parse(e);r.operation!==ue[n.action]&&J(400,"wrong_operation","Use the approved connection operation.");let i=await this.material(this.source(n.id,ge.tokenSet,o),r);await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=sj.parse(e);this.active.has(i.id)&&J(409,"connection_busy","Another operation is updating this connection."),this.active.add(i.id);try{n.throwIfAborted();let s=this.source(i.id,ge.tokenSet,o),a=await this.material(s,r);if(i.action==="refresh"){let u=await this.refresh(s,a,r,o,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(u)}}let c=this.provider(a.method);return c.revoke||J(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await c.revoke(a,await this.connectionApp(a,r,o),n),{kind:"revoked",id:s.policy.id}}finally{this.active.delete(i.id)}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&J(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&J(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await Y5(e.previous,tt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||J(409,"reconnect_required","Reconnect this service to renew access.");try{await sd(e,{...o,operation:ue.refresh},{destination:s})}catch{J(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=W3e(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let f=await a.renew({material:r,app:c,signal:i,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,f)}catch(f){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),f instanceof dt&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(f.code))throw f;J(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};import{lookup as J3e}from"node:dns/promises";import{request as X3e}from"node:https";import{brotliDecompressSync as Y3e,gunzipSync as Q3e,inflateSync as eHe}from"node:zlib";var fh=class{constructor(e){this.origin=e}origin;async send(e){let r=Si(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&J(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&J(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await J3e(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!mk(u.address)))&&J(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,m,y)=>{m.all?y(null,[a]):y(null,a.address,a.family)}},f=X3e(r,d,p=>{let m=[],y=0;p.on("data",w=>{y+=w.length,y>n?p.destroy(new dt(413,"body_limit","The response body is too large.")):m.push(w)}),p.on("error",l),p.on("end",()=>{try{let w=Buffer.concat(m),b=p.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?Q3e:b==="deflate"?eHe:b==="br"?Y3e:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,R]of Object.entries(p.headers))R!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(R)?R.join(", "):R);u({status:p.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&J(409,"cancelled","The operation was cancelled."),J(502,"service_unavailable","The service could not be reached. Try again.")}}};function On(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=HV(tHe(Ja()),"custody",r.id),i=new dd(HV(n,"client"),o,r,e),s=new O$(t,o,r,e,new D$(i)),a=new N$(t),c=new fh(o),u=new ph(r,e,a.connections(),new dd(HV(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Lde(t,e){let{custody:r,keys:o,binding:n,connections:i}=On(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await ee(n),operation:ue.command,functionDigest:null,operationDigest:await ee(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await ee(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ge.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return _k(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ge.value)return ru(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return tt(d[u.output])})}import{mkdir as Bnt}from"node:fs/promises";import{join as Z_}from"node:path";import{setTimeout as Knt}from"node:timers/promises";function rHe(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[o.name]=n}return r}function bk(t,e){let r=rHe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ba.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(f=>f.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,f)=>{if(!t.parameters.some(p=>p.name===f))throw new Error("Declare every function parameter.");return Object.hasOwn(r,f)?n(r[f]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,f])=>[d,i(f,l)])):u},s=new I$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Ha.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.");return{kind:"http",request:a}}function jde(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var Fde=h.object({operation:Za,save:h.record(h.string(),me)}).strict();function Sk(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function qde(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=o$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=Oy.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await ee(Sk(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(C(e.request)!==C(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(e)!==C(Za.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&C(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==C(o.save))throw new Error("Use the reviewed output destinations.")}function nHe(t,e){return t.policy.contentType===ge.value?e.output===void 0:t.policy.contentType===ge.tokenSet&&e.output!==void 0}var Ea=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},xk=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Tf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Tf(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await ee(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let f=await Tf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:f,delivered:!1}),await this.broker.finish(r.lease,f),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(f=>{f.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let f=await e8(r.request,this.binding,this.keys);await kf(this.environment,f.intent);let p=Za.parse(f.operation);if(ue[p.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await qde(o,p),await this.validateOperation(p,o,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.executeOperation(p,o,r.sources,c);d=await Tf(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(f){if(f instanceof Ea)throw f;f instanceof Af&&(f=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let p=l&&(c.aborted||!(f instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(f.code));d=await Tf(o,p?"uncertain":"failed",{ok:!1,result:null,error:f instanceof dt?{code:f.code,message:f.message}:{code:p?"execution_uncertain":"invalid_execution",message:p?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?bk(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async validateOperation(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await ko(c);let u=r.sources.find(f=>f.id===c.policy.id);if(!u||!await kL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await ee(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(ue[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Si(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=e_(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");FV(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(e_(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await tu(u.approval);if(C(l.policy.authorities.find(d=>d.id===l.authorityId))!==C(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==ge.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&C(d.executor)===C(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?bk(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!nHe(u,c))throw new Error("Use the input named in the signed request.");await sd(u,r,{...n?{destination:n.url}:{}}),await ru(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async executeOperation(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?bk(e.definition,e.arguments):e,a=[],c=new Map,u=async m=>{let y=o.find(b=>b.policy.id===m.id);if(y.policy.contentType===ge.value)return ru(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(m.id)||c.set(m.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(m.id);if(!m.output||!Object.hasOwn(w,m.output))throw new Error("Choose an available connection output.");return tt(w[m.output])};if(s.kind==="command"){let m=await _k(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:m.environment,files:m.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new dt(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new dt(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new dt(422,"function_failed",ol(y.stderr,m.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,ol(y.stdout,m.sensitive))}return{...y,stdout:ol(y.stdout,m.sensitive),stderr:ol(y.stderr,m.sensitive)}}let l=structuredClone(i);for(let m of l.bindings){let y="";for(let w of m.parts)if(typeof w=="string")y+=w;else{let b=xa(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}FV(l,m.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(f.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,ol(xa(f.body),a))}let p=e.kind==="http"?e.save:{};if(Object.keys(p).length){if(f.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let m={};for(let[y,w]of Object.entries(p)){let b=f.body;if(y!==""){let x=bi(JSON.parse(xa(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=tt(typeof x=="string"?x:JSON.stringify(x))}let S=await zy(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});m[w.name]=(await this.broker.capture(w.name,S)).id}return{status:f.status,saved:m}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([m,y])=>[m,ol(y,a)])),body:ol(xa(f.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:wr.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:bi(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=tt(typeof c=="string"?c:JSON.stringify(c)),l=await zy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};import{spawn as oHe}from"node:child_process";import{constants as BV}from"node:fs";import{open as Vde,rm as iHe}from"node:fs/promises";async function Gde(t){if(process.platform!=="linux"){let r=await Vde(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await iHe(t,{force:!0})}}let e=await Vde(t,BV.O_CREAT|BV.O_WRONLY|BV.O_NOFOLLOW,384);try{let r=oHe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var yD=Vt(RV(),1),vD=Vt(E0e(),1);function $0e(t){return TL.safeParse(t).success?t:null}async function R0e(t=3e3){let e=new yD.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new yD.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=$0e(n.Arn);if(i)return i;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new vD.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new vD.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=$0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var jG=h.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),FG=jG.max(4096).startsWith("/"),I0e=h.object({command:h.array(jG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:FG.optional(),environment:h.record(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),jG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:h.string().max(1e6).default(""),timeoutSeconds:h.number().int().min(1).max(3600).default(60)}).strict(),yKt=I0e.extend({id:E.optional()}),A0e=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),P0e=h.object({exitCode:h.number().int().nullable(),signal:h.string().max(32).nullable(),stdout:h.string().max(1e6),stderr:h.string().max(1e6),timedOut:h.boolean(),truncated:h.boolean()}).strict(),vKt=h.object({state:A0e.exclude(["queued","running"]),result:P0e.nullable(),error:h.string().max(100).nullable()}).strict(),wD=I0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:FG,state:A0e,result:P0e.nullable(),error:h.string().nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),wKt=wD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),_Kt=h.object({workingDirectory:FG}).strict(),k0e=h.object({lease:E,process:wD}).strict().nullable();var _D=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},k0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},wD)}},bD=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Ea}return!0}};var SD=h.object({format:h.literal(1),functionId:E,ownerId:E,revision:h.number().int().positive(),definition:Qo,author:or,executor:or,createdAt:Ae,signature:Sr}).strict();async function T0e(t,e){return SD.parse({...t,signature:await ur(t,e.signing,"function-publication")})}async function C0e(t,e){let r=SD.parse(t),{signature:o,...n}=r;if(await Ds(n.author),await Mr(n,o,n.author.signing,"function-publication"),e&&C(n.executor)!==C(e))throw new Error("This function is approved for another executor.");return r}var qG=h.object({functionId:E,publication:SD,contents:h.record(E,h.object({version:h.number().int().positive(),content:tn}).strict())}).strict(),Ont=h.object({name:me,definition:Qo,authorization:qG}).strict(),TKt=Ont.extend({version:h.number().int().positive()}),Dnt=h.object({id:E.optional(),ownerId:E.optional(),arguments:Lt.default({}),outputs:h.record(h.string().max(500),f$).default({})}).strict(),O0e=h.object({code:h.string().max(100),message:h.string().max(1e3)}).strict(),D0e=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,state:d$,result:wr.nullable(),error:O0e.nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),Nnt=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,actor:or.nullable(),arguments:Lt,outputs:Dnt.shape.outputs,definitionDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:Ae,expiresAt:Ae}).strict(),N0e=h.object({id:E,requestDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),state:d$.exclude(["queued","running"]),result:wr.nullable(),error:O0e.nullable(),finishedAt:Ae,signature:Sr}).strict(),z0e=h.object({lease:E,request:Nnt,publication:SD,sources:h.array(tn).max(100)}).strict().nullable();var xD=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/invocations/claim",{method:"POST",body:{}},z0e)}dispatch(e,r){return this.api.json("/api/runtime/functions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/runtime/functions/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean(),reason:h.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(e,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:e,completion:r}},D0e)}},ED=class{constructor(e,r,o,n=15e3){this.executor=e;this.broker=r;this.journal=o;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(e,r,o,n){let i={id:e.id,requestDigest:e.digest,state:r,result:o,error:n,finishedAt:new Date().toISOString()};e.completion=N0e.parse({...i,signature:await ur(i,this.executor.keys.signing,"function-result")}),e.phase="settled",await this.journal.write("invocation_"+e.id,e)}async deliver(e){await this.broker.finish(e.lease,e.completion),e.delivered=!0,await this.journal.write("invocation_"+e.id,e)}async reconcile(){let e=[];for(let r of await this.journal.keys("invocation_"))try{let o=await this.journal.read(r);if(!o||o.delivered||o.phase==="prepared")continue;o.completion||await this.complete(o,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(o)}catch{e.push(r.slice(11))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:o,publication:n,sources:i,lease:s}=r,a=await ee(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),f=!1,p=!1,m=setInterval(()=>{p||(p=!0,this.broker.renew(o.id,s).then(y=>{y.active||(f||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{p=!1}))},this.renewalMilliseconds);m.unref();try{if(await C0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await ee(n.definition)!==o.definitionDigest||Date.parse(o.expiresAt)<=Date.now())throw new Error("Run the current approved function in its configured environment.");let y="function_"+n.functionId,w=await this.journal.read(y),b=await ee(n);if(w&&(n.revision<w.revision||n.revision===w.revision&&w.digest!==b))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(y,{revision:n.revision,digest:b});let S=a8.parse({kind:"function",functionId:o.functionId,definition:n.definition,arguments:o.arguments,outputs:o.outputs}),x={format:2,id:o.id,origin:this.executor.environment.manifest.origin,ownerId:o.ownerId,actor:o.actor??this.executor.binding,executor:this.executor.binding,environmentId:n.definition.environmentId,environmentDigest:await ee(this.executor.environment.manifest),operation:ue.function,operationDigest:await ee(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await ee(T.policy),materialRevision:T.materialRevision,...T.policy.contentType===ge.tokenSet&&typeof T.metadata.authorizationDigest=="string"?{authorizationDigest:T.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:o.createdAt,expiresAt:o.expiresAt};await kf(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let R=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(R)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",R,null)}catch(y){if(y instanceof Ea)throw y;let w=u.phase==="dispatched",b=d.aborted&&f?"cancelled":w&&(d.aborted||!(y instanceof dt))?"uncertain":"failed";await this.complete(u,b,null,!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="uncertain"?"execution_uncertain":b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="uncertain"?"Check the result before invoking this function again.":b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(m)}try{await this.deliver(u)}catch{throw new Ea}return!0}};import{spawn as znt,execFile as Mnt}from"node:child_process";import{chmod as Unt,lstat as M0e,mkdir as VG,readFile as U0e,readdir as Lnt,realpath as L0e,rename as jnt,rm as Fnt,symlink as qnt,writeFile as j0e}from"node:fs/promises";import{join as fl}from"node:path";import{promisify as Vnt}from"node:util";import{createConnection as Gnt}from"node:net";import{setTimeout as Hnt}from"node:timers/promises";var GG=Vnt(Mnt),K_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',$D=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=fl(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await VG(this.options.directory,{recursive:!0,mode:448}),await VG(this.sessions,{recursive:!0,mode:448}),await VG(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await M0e(this.options.workspaceLink),await L0e(this.options.workspaceLink)!==await L0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await qnt(this.options.workspace,this.options.workspaceLink)}let e=fl(this.options.directory,"host_ed25519");try{await M0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await GG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Fi(),timeout:1e4})}await Unt(e,384),this.hostKey=yy.parse((await GG("ssh-keygen",["-y","-f",e],{env:Fi(),timeout:1e4})).stdout);let r=fl(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+K_(e),"PidFile "+K_(fl(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+K_(fl(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+K_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+K_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
131
+ `),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await p8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...f.flatMap(([m,y])=>["--env",m+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(f=>{let p=d8(d[0],d.slice(1),{env:Fi(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),m={stdout:new m8("utf8"),stderr:new m8("utf8")},y=0,w=!1,b=(T,M)=>{let K=Math.max(0,1e6-y);M.length>K&&(c.truncated=!0);let te=M.subarray(0,K);y+=te.length,c[T]+=m[T].write(te)};p.stdout.on("data",T=>b("stdout",T)),p.stderr.on("data",T=>b("stderr",T)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let S=()=>{u=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let R=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=m.stdout.end(),c.stderr+=m.stderr.end(),f())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),p.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",R()}),p.once("close",(T,M)=>{c.exitCode=T,c.signal=M,R()})}),c}finally{s&&u&&await new Promise(l=>{let d=d8("docker",["rm","-f",i],{env:Fi(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await vDe(o,{recursive:!0,force:!0})}}};function IDe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var h$=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new RDe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function g8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await SDe(h8($De(),"foundation-"));await bDe(r,448);try{let o=Fi(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=h8(r,i);await EDe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=_De(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=IDe(n),u=new h$(c,m=>process.stdout.write(m)),l=new h$(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,y)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(m??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await xDe(r,{recursive:!0,force:!0})}}import{dirname as tHe,join as HV}from"node:path";function xr(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"ovh":{let r=t.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,fields:t.config.fields,outputs:Object.keys(t.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function qi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function iu(t){return xr(t).requiresApp}var ADe=new Set(["airtable.com","dash.cloudflare.com","api.ebay.com","accounts.secure.freee.co.jp","github.com","id.heroku.com","api.hubapi.com","api.netlify.com","api.notion.com","api.render.com","login.salesforce.com","cloud.digitalocean.com","api.vultr.com","api.x.com","zoom.us"]);function y8(t){if(!xr(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth")return"available";try{let e=new URL(t.config.tokenUrl).hostname;return ADe.has(e)||e==="login.microsoftonline.com"&&t.config.clientAuth!=="none"?"unavailable":t.config.tokenUrl.includes("{")?"unknown":"available"}catch{return"unknown"}}var PDe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),v8=Lt.refine(t=>Object.keys(t).every(e=>!PDe.has(e)),"Keep method-specific facts separate from common facts."),su=h.object({accountId:h.string().max(2e3).nullable(),accountName:h.string().max(2e3),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),authorization:v8,details:v8}).strict();function LL(t){if(t.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let e="requestedScopes"in t?t.requestedScopes:void 0;return su.parse({accountId:t.oauth?.account??"",accountName:t.oauth?.accountName??"",accountVerified:t.oauth?.accountVerified??!1,scopes:e??t.oauth?.scopes??[],scopesStatus:e?"requested":t.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function jL(t){if(t.method.kind!=="token"||!t.fields)throw new Error("Use token connection material.");return"facts"in t&&t.facts?su.parse(t.facts):su.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function FL(t){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let e="ovh"in t?t.ovh:void 0;if(!e){let r="requestedScopes"in t?t.requestedScopes:void 0;return su.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return su.parse({accountId:e.user?e.account+"/"+e.user:e.account,accountName:e.account+(e.user?" / "+e.user:""),accountVerified:!0,scopes:e.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:e},details:{ovh:e}})}function qL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return su.parse({accountId:t.aws.identity?bf(t.aws.identity.arn):null,accountName:t.aws.identity?t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1):"",accountVerified:!!t.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:w5(t.aws)},details:{aws:_5(t.aws)}})}var kDe={oauth:LL,token:jL,aws:qL,ovh:FL};function Fy(t){return kDe[t.method.kind](t)}var nJ=Vt(j8(),1);var ec=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},tNe=class extends ec{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},rNe=class extends ec{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},nNe=class extends ec{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},oNe=class extends ec{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},iNe=class extends ec{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},sNe=class extends ec{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},aNe=class extends ec{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},R$=class extends ec{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},XL=class extends R${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},cNe=class extends R${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},uNe=class extends R${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},F8=class extends R${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},lNe=class extends ec{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},dNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},pNe=class extends dNe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},fNe=["","+",".","/",";","?","&","#"],Z8={"":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!1},"+":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!0},".":{first:".",sep:".",named:!1,ifEmpty:"",allowReserved:!1},"/":{first:"/",sep:"/",named:!1,ifEmpty:"",allowReserved:!1},";":{first:";",sep:";",named:!0,ifEmpty:"",allowReserved:!1},"?":{first:"?",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"&":{first:"&",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"#":{first:"#",sep:",",named:!1,ifEmpty:"",allowReserved:!0}},mNe=new TextEncoder,q8="0123456789ABCDEF",V8=t=>uu(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),Hy=(t,e)=>t[e]==="%"&&e+2<t.length&&V8(t[e+1])&&V8(t[e+2]);function YL(t,e){let r=t[e];return r==null?0:uu(W8,J8,cd("_"))(r)?1:Hy(t,e)?3:0}function hNe(t,e){if(Hy(t,e))return 3;let{char:r,size:o}=By(t,e);return yNe(r)?o:0}function By(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var rj=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Hy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=By(e,o);r+=uu(X8,s=>t&&gNe(s))(n)?n:Y8(n),o+=i}return r};function Nf(t){let e="";for(let r=0;r<t.length;){if(Hy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=By(t,r);e+=X8(o)?o:Y8(o),r+=n}return e}function Vy(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Hy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=By(t,n);r+=i,n+=s}return r}var W8=t=>uu(En(65,90),En(97,122))(t.charCodeAt(0)),J8=t=>En(48,57)(t.charCodeAt(0)),X8=t=>uu(W8,J8,e=>"-._~".includes(e))(t),gNe=t=>":/?#[]@!$&'()*+,;=".includes(t),yNe=t=>vNe(t.codePointAt(0)),vNe=t=>t!=null&&uu(cd(33),En(35,36),cd(38),En(40,59),cd(61),En(63,91),cd(93),cd(95),En(97,122),cd(126),wNe,_Ne)(t);function wNe(t){if(t<65536)return uu(En(160,55295),En(63744,64975),En(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var _Ne=t=>uu(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),Y8=t=>Array.from(mNe.encode(t)).map(e=>`%${q8[e>>4]}${q8[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,cd=t=>e=>t===e,uu=(...t)=>e=>t.some(r=>r(e));function Q8(t,e,r){return t.map(o=>o.kind==="literal"?o.text:bNe(o.vars,o.operator,e,r)).join("")}function bNe(t,e,r,o){let n=Z8[e],i=t.flatMap(s=>SNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function SNe(t,e,r,o){if(e==null)return[];if(kNe(e)){let n=RNe(e,r.allowReserved);return n.length<1?[]:G8(t,"list",o)?ENe(t,n,r):[]}if(PNe(e)){let n=INe(e,r.allowReserved);return n.length<1?[]:G8(t,"associative",o)?$Ne(t,n,r):[]}return xNe(t,e,r)}function xNe(t,e,r){let o=String(e),n=t.prefix==null?o:Vy(o,t.prefix),i=rj(r.allowReserved)(n);return r.named?[Gy(Nf(t.name),i,r)]:[i]}function ENe(t,e,r){let o=Nf(t.name);if(t.explode)return r.named?e.map(i=>Gy(o,i,r)):[...e];let n=e.join(",");return r.named?[Gy(o,n,r)]:[n]}function $Ne(t,e,r){if(t.explode)return e.map(([n,i])=>Gy(n,i,r));let o=e.flat(1).join(",");return r.named?[Gy(Nf(t.name),o,r)]:[o]}var Gy=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,RNe=(t,e)=>t.filter(r=>r!=null).map(String).map(rj(e)),INe=(t,e)=>Object.entries(t).map(([r,o])=>[r,ANe(o)]).filter(([,r])=>r!=null).map(r=>r.map(rj(e)));function ANe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var PNe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),kNe=t=>Array.isArray(t);function G8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new pNe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function TNe(t,e,r){return QL(t,e,r,0,0,{})}function QL(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=o1e(i);return Q8(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?QL(t,e,r,o+1,n+s.text.length,i):null;for(let a of CNe(t,e,o,n)){let c=e.slice(n,a);for(let u of DNe(s.vars,s.operator,c)){let l=nj(i,u);if(l==null)continue;let d=QL(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*CNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*ONe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*ONe(t,e){for(let r=t;r>=e;r--)yield r}function*DNe(t,e,r){if(r===""){yield*NNe(t,e);return}let o=Z8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?GNe(t,o,n):zNe(t,o,n)}var NNe=(t,e)=>(e===""||e==="+")&&t.length===1?[cu(t[0],"")]:[{}],zNe=(t,e,r)=>ej(t,e,oj(r,e.sep),0,0);function*ej(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of MNe(i,e,r,n))for(let a of ej(t,e,r,o+1,s.index)){let c=nj(s.bindings,a);c!=null&&(yield c)}yield*ej(t,e,r,o+1,n)}function*MNe(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of UNe(t,e,s))yield{bindings:a,index:o+i}}}function*UNe(t,e,r){let o=eJ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*LNe(t,e,r)),yield*o}function*LNe(t,e,r){let o=tJ(r,e.allowReserved);if(o==null)return;let n=jNe(r,e);n!=null&&(yield cu(t,n)),yield cu(t,o)}var jNe=(t,e)=>FNe(t.join(e.sep),e);function FNe(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=qNe(t,i,e.sep),a=Qa(t.slice(o,n),e.allowReserved),c=Qa(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function qNe(t,e,r){for(let o=e;o<t.length;o++)if(VNe(t,o,r))return o;return t.length}var VNe=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*eJ(t,e,r){let o=Qa(r,e.allowReserved);if(o==null)return;let n=cu(t,o);if(t.prefix!=null){yield n;return}let i=oj(r,",");if(i.length<2){yield n;return}let s=tJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?QNe(i,e.allowReserved):null;a!=null&&(yield cu(t,a)),yield cu(t,s),yield n}var GNe=(t,e,r)=>tj(t,e,oj(r,e.sep).map(YNe),0,0);function*tj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of HNe(i,e,r,n,t))for(let a of tj(t,e,r,o+1,s.index)){let c=nj(s.bindings,a);c!=null&&(yield c)}yield*tj(t,e,r,o+1,n)}function*HNe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*KNe(t,e,r,o,n);return}yield*BNe(t,e,r,o)}}function*BNe(t,e,r,o){let n=r[o];if(n.name===Nf(t.name))for(let i of eJ(t,e,n.value))yield{bindings:i,index:o+1}}function*KNe(t,e,r,o,n){yield*ZNe(t,e,r,o),yield*JNe(t,e,r,o,n)}function*ZNe(t,e,r,o){let n=[...WNe(Nf(t.name),e,r,o)];n.length>0&&(yield{bindings:cu(t,n),index:o+n.length})}function*WNe(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Qa(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*JNe(t,e,r,o,n){let i=[...XNe(e,r,o,new Set(n.map(s=>Nf(s.name))))];i.length>0&&(yield{bindings:cu(t,Object.fromEntries(i)),index:o+i.length})}function*XNe(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=Qa(i.name,t.allowReserved),a=Qa(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function YNe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function QNe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Qa(t[o],e),i=Qa(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function tJ(t,e){let r=[];for(let o of t){let n=Qa(o,e);if(n==null)return null;r.push(n)}return r}function Qa(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var cu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function nj(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=e1e(i,n);if(s==null)return null;r[o]=s}return r}var e1e=(t,e)=>$$(t)||$$(e)?t1e(t,e):r1e(t.value,e.value)?t:null;function t1e(t,e){let r=H8(t.value),o=H8(e.value);if(r==null||o==null)return null;let n=$$(t),i=$$(e);if(!n&&!i)return null;if(n&&!i)return Vy(o,t.prefix)===r?e:null;if(!n&&i)return Vy(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Vy(o,s)===r?e:null:Vy(r,a)===o?t:null}var $$=t=>t.prefix!=null,H8=t=>typeof t=="string"?t:null;function r1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):B8(t)?B8(e)&&n1e(Object.entries(t),Object.entries(e)):t===e}var n1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),B8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),o1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),oj=(t,e)=>e===""?[t]:t.split(e),i1e=["=",",","!","@","|"];function s1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new iNe(e,r));let n=t[0];if(l1e(n))return o(new sNe(e,r+1,n));if(!K8(n)&&YL(t,0)<1)return o(new aNe(e,r+1,n));let i=K8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:a1e(t,e,r+1,s)}}function a1e(t,e,r,o){if(o>=t.length)throw new XL(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new F8(e,r+i):new XL(e,r+i);let s=i,a=c1e(t,i);if(a===s)throw new XL(e,r+i);let c=t.slice(s,a);i=a;let u=u1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new lNe(e,r+i,t[i]):new cNe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new F8(e,r+i-1)}return n}function c1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=YL(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||YL(t,r+1)<1)break;r++,o=!0}return r}function u1e(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&d1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new uNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function K8(t){return fNe.includes(t)&&t!==""}function l1e(t){return i1e.includes(t)}function d1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function p1e(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new tNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new nNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(s1e(f,t,i))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new rNe(t,i)),n(s),i++;continue}let a=hNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=By(t,i);r(new oNe(t,i,c)),n(c),i+=u}return o}var I$=class rJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=y1e(r),this.#e=f1e(p1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new rJ(e,r)}get tokens(){return this.#e}expand=e=>Q8(this.#e,e,this.#t);match=e=>TNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},f1e=t=>Object.freeze(t.map(m1e)),m1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(h1e))}),h1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),g1e=()=>{},y1e=({strict:t,report:e})=>(e??=g1e,t??=!0,e=t?v1e(e):e,{strict:t,report:e}),v1e=t=>e=>{throw t(e),e};var tc=class extends Error{constructor(r,o){super(o);this.code=r}code};function A$(t,e,r={}){let o=(i,s)=>{throw new tc(i,s)},n={...r,...e};for(let i of t)i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,nJ.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.");return Object.keys(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function lu(t,e,r={}){let o=A$(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new tc("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function P$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new tc("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new tc("encrypted_input_required","Supply private material directly with your encryption keys.")}return A$(t.map(r=>({...r,required:!1})),e)}function lo(t,e){return P$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function zf(t,e,r){P$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new tc("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}function oJ(t,e=Fy(t)){return e.accountVerified?e.accountId:null}function iJ(t,e=Fy(t)){let o=(t.method.kind==="oauth"||t.method.kind==="ovh"||t.method.kind==="token"&&!!t.method.config.identity)&&t.method.kind!=="aws"?lo(t.method.config.fields,t.fields??{}):{};return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...Object.keys(o).length?{fields:o}:{},...e.authorization,...t.state?{state:t.state}:{}}}var ld=h.record(h.string().max(100),h.string().max(16384)),po=h.object({format:h.literal(1),methodId:h.string().min(1),generation:E,clientId:h.string().max(1e3),clientSecret:h.string().max(16384).optional(),fields:ld}).strict(),ij=h.object({accessToken:h.string().min(1).max(16384),refreshToken:h.string().min(1).max(16384).optional(),expiresAt:h.number().nullable(),refreshExpiresAt:h.number().optional(),scopes:h.array(h.string()),requestedScopes:h.array(h.string()).optional(),account:h.string(),accountName:h.string(),accountVerified:h.boolean().optional(),scopesStatus:h.enum(["unknown","requested","reported"]).optional(),extra:ld,facts:Lt}).strict(),k$={format:h.literal(2),methodId:h.string().min(1),method:Xc,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:h.literal("reconnect").optional()},ud=h.never().optional(),Bn=h.union([h.object({...k$,method:BE,oauth:ij.optional(),requestedScopes:h.array(h.string()).optional(),fields:ld.optional(),aws:ud}).strict(),h.object({...k$,method:KE,fields:ld,facts:su.optional(),oauth:ud,aws:ud}).strict(),h.object({...k$,method:WE,fields:ld,ovh:Ay.optional(),requestedScopes:h.array(h.string()).optional(),oauth:ud,aws:ud}).strict(),h.object({...k$,method:ZE,aws:UE,oauth:ud,fields:ud}).strict()]).superRefine((t,e)=>{if(t.method.kind==="oauth"&&t.fields)try{P$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}iu(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the application required by this connection."}),!iu(t.method)&&t.appId!==null&&e.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!("requestedScopes"in t&&t.requestedScopes)&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),Pbt=h.object({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),generation:E,fields:ld.optional()}).strict(),w1e=h.object({methodId:h.string().min(1).max(200),methodKind:yL,generation:E,authorizationDigest:br,appId:E.nullable(),accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),outputs:h.array(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:h.enum(["ready","reconnect"]),fields:ld.optional(),aws:LE.optional(),ovh:Ay.optional()}).strict();async function Mf(t,e=Fy(t)){let r=xr(t.method).outputs,o=t.method.kind!=="aws"&&t.fields?lo(t.method.config.fields,t.fields):{},n=await ee(iJ(t,e));return w1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:n,appId:t.appId,accountId:oJ(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...Object.keys(o).length?{fields:o}:{},...e.details})}var _1e=h.array(h.object({name:h.string(),label:h.string(),value:h.string()}).strict()),sJ=h.object({methodName:me,account:h.string().max(2e3),settings:_1e.optional()}).strict();function T$(t){let e=xr(t.method).fields,r=t.method.kind!=="aws"&&t.fields?lo(e,t.fields):{},o=e.filter(n=>r[n.name]).map(n=>({name:n.name,label:n.label,value:n.choices?.find(i=>i.value===r[n.name])?.label??r[n.name]}));return{methodName:t.method.name,account:"",...o.length?{settings:o}:{}}}var sj=h.discriminatedUnion("action",[h.object({action:h.literal("refresh"),id:E}).strict(),h.object({action:h.literal("revoke"),id:E}).strict()]);var aJ=Os.extend({name:me}),Ubt=h.object({bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Os,token:h.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),cJ=h.object({id:E,executorId:E,ownerId:E,name:me,origin:h.url(),bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:h.object({port:h.number().int().min(1).max(65535)}).strict().optional(),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),Lbt=Os.extend({previousSignature:Sr.optional()}).strict(),uJ=h.object({name:me,content:tn,labels:sJ.optional(),version:h.number().int().positive().optional()}).strict(),C$=h.object({content:tn,version:h.number().int().positive()}).strict(),lJ=h.object({id:E,reason:h.enum(["grantExpired","recipients"])}).strict(),jbt=h.record(E,h.object({version:h.number().int().positive(),content:tn}).strict()),dJ=h.object({id:E,name:me,version:h.number().int().positive(),content:tn,policy:en}).strict(),pJ=h.object({registration:CL,stoppedAt:h.iso.datetime().nullable(),heartbeatAt:h.iso.datetime().nullable()}).strict(),fJ=h.object({lease:E,request:If,sources:h.array(tn).max(100)}).strict().nullable(),b1e=h.object({lease:E}).strict(),Fbt=b1e.extend({receipt:My}).strict(),Ky=h.object({id:E,resource_id:E,executor_id:E,expected_revision:h.number().int().positive(),state:h.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:h.string().regex(/^\d+$/),result:tn.nullable()}),qbt=h.object({id:E,resourceId:E,expectedRevision:h.number().int().positive()}).strict(),S1e=h.object({fence:h.string().regex(/^\d+$/)}).strict(),Vbt=S1e.extend({content:tn}).strict(),Gbt=h.object({id:E,executionId:E,index:h.number().int().nonnegative(),stateDigest:br,expiresAt:Ae}).strict(),aj=h.object({id:E,executionId:E,context:h.string(),sealed:Io.nullable(),expiresAt:Ae,receivedAt:Ae.nullable()}).strict(),mJ=(t,e)=>"oauth-callback:"+t+":"+e;var rc=class extends Error{constructor(r,o){super(o);this.code=r}code},cj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},O$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||C(r)!==C(e))throw new rc("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Os);return await $L(r),{...r,fingerprint:await rd(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new rc("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},pJ);if(await Pf(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},Qr(aJ));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await $L(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},C$);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await ko(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=PL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&en.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await ee(o)!==i.digest)throw new rc("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!s$(i.policy,o))throw new rc("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return od((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Qr(dJ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||C(i.content)!==C(n.content))throw new rc("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await Rf(await od(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...Qc(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return en.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await Rf(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},_r);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await Rf(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},h.union([_r,Ze]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Qr(lJ))).items}async reprotect(e,r="grantExpired"){let o=await this.read(e),{policy:n}=o.content,i=Date.now(),s=n.grants.filter(l=>Date.parse(l.expiresAt)>i),a=r==="recipients"?(await this.recipients(n.ownerId)).filter(l=>!n.readers.some(d=>d.id===l.id)):[];if(s.length===n.grants.length&&!a.length||n.producers.some(l=>Date.parse(l.expiresAt)>i))return null;let c=await this.api.json("/api/resources/"+n.id,{},_r),u=await od(o.content,this.binding,this.keys.encryption);return this.save(c.name,u,{...n,revision:n.revision+1,grants:s,producers:[],readers:[...n.readers,...a],authorities:[...n.authorities,...a.filter(l=>!n.authorities.some(d=>d.id===l.id))]},{metadata:o.content.metadata,previous:o})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id,o.reason)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ge.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Qr(_r));s=d.items.find(f=>f.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ge.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await u$(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Za.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],f=await this.sourceContents([...d,...n.sourceIds??[]]);for(let w=0;w<f.length;w++){let b=f[w],S=b.policy.contentType===ge.clientCredential,x=S&&i.kind!=="revoke"?ue.refresh:ue[i.kind],R=S?void 0:l?new URL(l.url).origin:void 0;if(b.policy.grants.some(fe=>"actor"in fe&&C(fe.actor)===C(this.binding)&&C(fe.executor)===C(s.manifest.executor)&&fe.operations.includes(x)&&Date.parse(fe.expiresAt)>=Date.parse(c)&&(!R||!fe.origins.length||fe.origins.includes(R))&&(S||fe.callerProgram))||!b.policy.authorities.some(fe=>C(fe)===C(this.binding)))continue;let M=await this.read(b.policy.id),K=await this.api.json("/api/resources/"+b.policy.id,{},_r),te={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[ue.refresh]:[]])],origins:R?[R]:[],functionDigests:[],callerProgram:!S,expiresAt:c},Ie=fe=>C({...fe,expiresAt:null}),Te=M.content.policy.grants.filter(fe=>Ie(fe)===Ie(te)),bt=en.parse({...M.content.policy,revision:M.content.policy.revision+1,grants:[...M.content.policy.grants.filter(fe=>Date.parse(fe.expiresAt)>Date.now()&&Ie(fe)!==Ie(te)),{...te,expiresAt:new Date(Math.max(Date.parse(c),...Te.map(fe=>Date.parse(fe.expiresAt)))).toISOString()}]});await this.save(K.name,await od(M.content,this.binding,this.keys.encryption),bt,{previous:M,metadata:M.content.metadata}),f[w]=(await this.read(b.policy.id)).content}let p=await this.policy(e,ge.executionResult,[],{id:a});p.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let m={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await ee(s.manifest),operation:ue[i.kind],operationDigest:await ee(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(f.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await ee(w.policy),...w.policy.contentType===ge.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:p.readers,...s.manifest.resultVersion?{resultApproval:await u$(p,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await kf(s,m);let y=w=>w.policy.contentType===ge.clientCredential;for(let w of f)await sd(w,y(w)&&m.operation!==ue.connect&&m.operation!==ue.revoke?{...m,operation:ue.refresh}:m,y(w)?{}:{destination:l?.url});return Q5(m,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},Hn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new cj(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},Hn);if(C(o.intent)!==C(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await EL(e.requestSignature,e.intent.actor.signing,"run");if(C(r.intent)!==C(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new rc("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?s8(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(C(e.intent.actor)!==C(this.binding)||C(e.intent.executor)!==C(this.binding))throw new rc("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,ge.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await DL(e.intent,e.receipt.state,r,this.keys,await u$(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},Hn)}};import{lstat as x1e,mkdir as E1e,readFile as $1e,readdir as R1e}from"node:fs/promises";import{join as hJ}from"node:path";var gJ=h.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),dd=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:gJ.parse(e)})}async read(e){let r=this.context(e),o=hJ(this.directory,e+".json");try{let n=await x1e(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=h.string().max(32e6).parse(JSON.parse(await $1e(o,"utf8"))),s=await Sy(i,await Yo(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(Ao(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await Mr({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await ur(n,this.privateKeys.signing,"journal"),s=tt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new _f(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Yo(this.binding.encryption,"ECDH-ES+A256KW"));await E1e(this.directory,{recursive:!0,mode:448}),await Cf(hJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await R1e(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>gJ.parse(o.name.slice(0,-5)))}};var D$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Ds(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await ee(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&C(r)!==C(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var dt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function J(t,e,r,o){throw new dt(t,e,r,o)}var N$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},fJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},Hn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},h.object({id:E}))}connections(){let e=this.api;return{prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Ky),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Ky),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},tn),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Ky),state:r=>e.json("/api/connections/"+r+"/operation",{},Ky.nullable())}}};import{randomUUID as W3e}from"node:crypto";var gc=Vt(RV(),1);import{randomUUID as HGe}from"node:crypto";function ede(t){let e=ME.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&J(502,"invalid_response","The AWS account could not be verified."),e.data}function tde(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&bf(t.arn)===bf(e.arn)}function IV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&J(409,"reconnect_required","Reconnect with current AWS credentials.")}var rk=class{async obtain(e,r,o){let n=Ga.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};IV(s?.expiration);let a=new gc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();IV(d.expiration),c=new gc.STSClient({region:n.region,credentials:d});let f=r?.sourceIdentity?ede(await c.send(new gc.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&f&&!tde(f,r.sourceIdentity)&&J(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,m=f;if(n.role){l=!0;let b=(await c.send(new gc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+HGe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&J(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},IV(p.expiration),r?.identity&&(c.destroy(),c=new gc.STSClient({region:n.region,credentials:p}),m=ede(await c.send(new gc.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&m&&!tde(m,r.identity)&&J(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:UE.parse({...n,sourceIdentity:f,identity:m}),credentials:{AWS_ACCESS_KEY_ID:p.accessKeyId,AWS_SECRET_ACCESS_KEY:p.secretAccessKey,AWS_SESSION_TOKEN:p.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&J(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&J(409,"reconnect_required","Reconnect with current AWS credentials."),l&&J(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),J(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var nk=class{constructor(e){this.aws=e}aws;facts=qL;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var AV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(AV="oauth4webapi/v3.8.8");function lk(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var ba="ERR_INVALID_ARG_VALUE",yc="ERR_INVALID_ARG_TYPE";function Or(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var ode=Symbol(),BGe=Symbol(),KGe=Symbol(),MV=Symbol();var ok=Symbol();var ZGe=new TextEncoder,WGe=new TextDecoder;function PV(t){return typeof t=="string"?ZGe.encode(t):WGe.decode(t)}var kV;Uint8Array.prototype.toBase64?kV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):kV=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var TV;Uint8Array.fromBase64?TV=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Or("The input to be decoded is not correctly encoded.",ba,e)}}:TV=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw Or("The input to be decoded is not correctly encoded.",ba,e)}};function CV(t){return typeof t=="string"?TV(t):kV(t)}var sh=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=I3e,Error.captureStackTrace?.(this,this.constructor)}},Yw=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function De(t,e,r){return new Yw(t,{code:e,cause:r})}function ik(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function ide(t){lk(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(AV&&!e.has("user-agent")&&e.set("user-agent",AV),e.has("authorization"))throw Or('"options.headers" must not include the "authorization" header name',ba);return e}function JGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Or('"options.signal" must return or be an instance of AbortSignal',yc);return e}}function sk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Or(`${r} must be a number`,yc,n);if(t>0)return;if(e){if(t!==0)throw Or(`${r} must be a non-negative number`,ba,n);return}throw Or(`${r} must be a positive number`,ba,n)}catch(i){throw o?De(i.message,o,n):i}}function Cn(t,e,r,o){try{if(typeof t!="string")throw Or(`${e} must be a string`,yc,o);if(t.length===0)throw Or(`${e} must not be empty`,ba,o)}catch(n){throw r?De(n.message,r,o):n}}function sde(t){YGe(t,"application/json")}function XGe(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return De(r,P3e,t)}function YGe(t,e){if(p3e(t)!==e)throw XGe(t,e)}async function ade(t){return Cn(t,"codeVerifier"),CV(await crypto.subtle.digest("SHA-256",PV(t)))}function cde(t){let e=t?.[BGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function ude(t){let e=t?.[KGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function lde(){return Math.floor(Date.now()/1e3)}function ch(t){if(typeof t!="object"||t===null)throw Or('"as" must be an object',yc);Cn(t.issuer,'"as.issuer"')}function uh(t){if(typeof t!="object"||t===null)throw Or('"client" must be an object',yc);Cn(t.client_id,'"client.client_id"')}function rde(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function dde(t){return Cn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function pde(t){return Cn(t,'"clientSecret"'),(e,r,o,n)=>{let i=rde(r.client_id),s=rde(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function fde(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var QGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function e3e(t,e){if(e&&t.protocol!=="https:")throw De("only requests to HTTPS are allowed",T3e,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw De("only HTTP and HTTPS requests are allowed",C3e,t)}function nde(t,e,r,o){let n;if(typeof t!="string"||!(n=QGe(t)))throw De(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?O3e:D3e,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return e3e(n,o),n}function mde(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?nde(t.mtls_endpoint_aliases[e],e,r,o):nde(t[e],e,r,o)}var OV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=R3e,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Qw=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=A3e,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},DV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=$3e,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},ak="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",t3e="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",r3e='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',n3e="("+ak+")\\s*=\\s*"+r3e,o3e="("+ak+")\\s*=\\s*("+ak+")",i3e=new RegExp("^[,\\s]*("+ak+")"),s3e=new RegExp("^[,\\s]*"+n3e+"[,\\s]*(.*)"),a3e=new RegExp("^[,\\s]*"+o3e+"[,\\s]*(.*)"),c3e=new RegExp("^("+t3e+")(?:$|[,\\s])(.*)");function u3e(t){if(!lk(t,Response))throw Or('"response" must be an instance of Response',yc);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(i3e),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let f,p;if(n=o.match(s3e)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(a3e)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(c3e)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function l3e(t){if(t.status>399&&t.status<500){Tde(t),sde(t);try{let e=await t.clone().json();if(ik(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function hde(t,e,r){if(t.status!==e){m3e(t);let o;throw(o=await l3e(t))?(await t.body?.cancel(),new OV("server responded with an error in the response body",{cause:o,response:t})):De(`"response" is not a conform ${r} response (unexpected HTTP status code)`,k3e,t)}}function d3e(t){if(!LV.has(t))throw Or('"options.DPoP" is not a valid DPoPHandle',ba)}function p3e(t){return t.headers.get("content-type")?.split(";")[0]}async function gde(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[MV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:JGe(o,s?.signal)})}async function UV(t,e,r,o,n,i){let s=mde(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[ode]!==!0);n.set("grant_type",o);let a=ide(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(d3e(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await gde(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function yde(t,e,r,o,n){ch(t),uh(e),Cn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),UV(t,e,r,"refresh_token",i,n)}var vde=new WeakMap,f3e=new WeakMap;function wde(t){if(!t.id_token)return;let e=vde.get(t);if(!e)throw Or('"ref" was already garbage collected or did not resolve from the proper sources',ba);return e}async function dk(t,e,r,o,n,i){if(ch(t),uh(e),!lk(r,Response))throw Or('"response" must be an instance of Response',yc);await hde(r,200,"Token Endpoint"),Tde(r);let s=await L3e(r);if(Cn(s.access_token,'"response" body "access_token" property',Mt,{body:s}),Cn(s.token_type,'"response" body "token_type" property',Mt,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;sk(a,!0,'"response" body "expires_in" property',Mt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&Cn(s.refresh_token,'"response" body "refresh_token" property',Mt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw De('"response" body "scope" property must be a string',Mt,{body:s});if(s.id_token!==void 0){Cn(s.id_token,'"response" body "id_token" property',Mt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(sk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await _3e(t,e,s.id_token,a,n);S3e(e,c),b3e(c),f3e.set(r,u),vde.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new sh("unsupported `token_type` value",{cause:{body:s}});return s}function m3e(t){let e;if(e=u3e(t))throw new DV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function _de(t,e,r,o){return dk(t,e,r,void 0,o?.[ok],o?.recognizedTokenTypes)}function h3e(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw De('unexpected JWT "aud" (audience) claim value',ah,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw De('unexpected JWT "aud" (audience) claim value',ah,{expected:t,claims:e.claims,claim:"aud"});return e}function g3e(t,e){let r=t[j3e]?.(e)??t.issuer;if(e.claims.iss!==r)throw De('unexpected JWT "iss" (issuer) claim value',ah,{expected:r,claims:e.claims,claim:"iss"});return e}var LV=new WeakSet;function y3e(t){return LV.add(t),t}var jV=Symbol();async function bde(t,e,r,o,n,i,s){if(ch(t),uh(e),!LV.has(o))throw Or('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ba);Cn(n,'"redirectUri"');let a=Bd(o,"code");if(!a)throw De('no authorization code in "callbackParameters"',Mt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==jV&&(Cn(i,'"codeVerifier"'),c.set("code_verifier",i)),UV(t,e,r,"authorization_code",c,s)}var Sde={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function v3e(t,e){for(let r of t)if(e.claims[r]===void 0)throw De(`JWT "${r}" (${Sde[r]}) claim missing`,Mt,{claims:e.claims});return e}function w3e(t,e){if(typeof e.claims[t]!="string")throw De(`unexpected JWT "${t}" (${Sde[t]}) claim type`,Mt,{claims:e.claims});return e}function _3e(t,e,r,o,n){return N3e(r,z3e.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),cde(e),ude(e),n).then(v3e.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(g3e.bind(void 0,t)).then(h3e.bind(void 0,e.client_id)).then(w3e.bind(void 0,"sub"))}function xde(t,e){if(e===uk)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?uk:(sk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function b3e(t){t.auth_time!==void 0&&sk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Mt,{claims:t})}function Ede(t,e,r){if(r===uk)return;let o=lde()+cde(t),n=ude(t);if(e.auth_time+r<o-n)throw De("too much time has elapsed since the last End-User authentication",zV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function $de(t,e){let r=e===ck?void 0:e;if(t.nonce!==r)throw De('unexpected ID Token "nonce" claim value',ah,{expected:r,claims:t,claim:"nonce"})}function S3e(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw De('ID Token "aud" (audience) claim includes additional untrusted audiences',ah,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw De('unexpected ID Token "azp" (authorized party) claim value',ah,{expected:t.client_id,claims:e,claim:"azp"})}}var ck=Symbol(),uk=Symbol();async function Rde(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?x3e(t,e,r,o.expectedNonce,o.maxAge,o[ok],o.recognizedTokenTypes):E3e(t,e,r,o?.maxAge,o?.[ok],o?.recognizedTokenTypes)}async function x3e(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=ck;break;case ck:break;default:Cn(o,'"expectedNonce" argument'),a.push("nonce")}n=xde(e,n),n!==uk&&a.push("auth_time");let c=await dk(t,e,r,a,i,s);Cn(c.id_token,'"response" body "id_token" property',Mt,{body:c});let u=wde(c);return Ede(e,u,n),$de(u,o),c}async function E3e(t,e,r,o,n,i){let s=await dk(t,e,r,void 0,n,i),a=wde(s);return a&&(Ede(e,a,xde(e,o)),$de(a,ck)),s}var $3e="OAUTH_WWW_AUTHENTICATE_CHALLENGE",R3e="OAUTH_RESPONSE_BODY_ERROR",I3e="OAUTH_UNSUPPORTED_OPERATION",A3e="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var NV="OAUTH_PARSE_ERROR",Mt="OAUTH_INVALID_RESPONSE";var P3e="OAUTH_RESPONSE_IS_NOT_JSON",k3e="OAUTH_RESPONSE_IS_NOT_CONFORM",T3e="OAUTH_HTTP_REQUEST_FORBIDDEN",C3e="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",zV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",ah="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var O3e="OAUTH_MISSING_SERVER_METADATA",D3e="OAUTH_INVALID_SERVER_METADATA";async function Ide(t,e,r,o,n){return ch(t),uh(e),UV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Ade(t,e,r,o){return dk(t,e,r,void 0,o?.[ok],o?.recognizedTokenTypes)}async function Pde(t,e,r,o,n){ch(t),uh(e),Cn(o,'"token"');let i=mde(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[ode]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=ide(n?.headers);return a.delete("accept"),gde(t,e,r,i,s,a,n)}async function kde(t){if(!lk(t,Response))throw Or('"response" must be an instance of Response',yc);await hde(t,200,"Revocation Endpoint")}function Tde(t){if(t.bodyUsed)throw Or('"response" body has been used already',ba)}async function N3e(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new sh("JWE decryption is not configured",{cause:t});if(a!==3)throw De("Invalid JWT",Mt,t);let c;try{c=JSON.parse(PV(CV(i)))}catch(d){throw De("failed to parse JWT Header body as base64url encoded JSON",NV,d)}if(!ik(c))throw De("JWT Header must be a top level object",Mt,t);if(e(c),c.crit!==void 0)throw new sh('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(PV(CV(s)))}catch(d){throw De("failed to parse JWT Payload body as base64url encoded JSON",NV,d)}if(!ik(u))throw De("JWT Payload must be a top level object",Mt,t);let l=lde()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw De('unexpected JWT "exp" (expiration time) claim type',Mt,{claims:u});if(u.exp<=l-o)throw De('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',zV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw De('unexpected JWT "iat" (issued at) claim type',Mt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw De('unexpected JWT "iss" (issuer) claim type',Mt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw De('unexpected JWT "nbf" (not before) claim type',Mt,{claims:u});if(u.nbf>l+o)throw De('unexpected JWT "nbf" (not before) claim value',zV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw De('unexpected JWT "aud" (audience) claim type',Mt,{claims:u});return{header:c,claims:u,jwt:t}}function z3e(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:r,reason:"default value"});return}throw De('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Bd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw De(`"${e}" parameter must be provided only once`,Mt);return r}var M3e=Symbol(),U3e=Symbol();function Cde(t,e,r,o){if(ch(t),uh(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Or('"parameters" must be an instance of URLSearchParams, or URL',yc);if(Bd(r,"response"))throw De('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Mt,{parameters:r});let n=Bd(r,"iss"),i=Bd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw De('response parameter "iss" (issuer) missing',Mt,{parameters:r});if(n&&n!==t.issuer)throw De('unexpected "iss" (issuer) response parameter value',Mt,{expected:t.issuer,parameters:r});switch(o){case void 0:case U3e:if(i!==void 0)throw De('unexpected "state" response parameter encountered',Mt,{expected:void 0,parameters:r});break;case M3e:break;default:if(Cn(o,'"expectedState" argument'),i!==o)throw De(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Mt,{expected:o,parameters:r})}if(Bd(r,"error"))throw new Qw("authorization response from the server is an error",{cause:r});let a=Bd(r,"id_token"),c=Bd(r,"token");if(a!==void 0||c!==void 0)throw new sh("implicit and hybrid flows are not supported");return y3e(new URLSearchParams(r))}async function L3e(t,e=sde){let r;try{r=await t.json()}catch(o){throw e(t),De('failed to parse "response" body as JSON',NV,o)}if(!ik(r))throw De('"response" body must be a top level object',Mt,{body:r});return r}var j3e=Symbol();function e_(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function bi(t,e){for(let r of e_(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function FV(t,e,r){let o=e_(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function nl(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function ol(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}var lh=Vt(Dde(),1);var q3e=lh.default.IPv6.parseCIDR("2000::/3"),V3e=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function mk(t){if(!lh.default.isValid(t)||t.includes("%"))return!1;let e=lh.default.parse(t);return V3e.has(e.range())&&(!(e instanceof lh.default.IPv6)||e.match(q3e))}function Si(t,e){let r;try{r=new URL(t)}catch{J(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&J(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||lh.default.isValid(o)&&!mk(o))&&J(400,"private_destination","Choose a public HTTPS destination."),r}function dh(t){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.body))}catch{J(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&J(502,"invalid_response","The service returned an invalid response."),e}var fk=class{constructor(e){this.origin=e}origin;async send(e){let r=Si(e.url,this.origin),o=e.maxBytes??1048576;e.body&&(typeof e.body=="string"?new TextEncoder().encode(e.body).length:e.body.length)>o&&J(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:e.method??"GET",headers:e.headers,body:typeof e.body=="string"?e.body:e.body?new Uint8Array(e.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]])})}catch{e.signal?.aborted&&J(409,"cancelled","The operation was cancelled."),J(409,"browser_exchange_unavailable","Restart authorization using the CLI on this device.")}let i=n.body?.getReader(),s=[],a=0;if(i)try{for(;;){let l=await i.read();if(l.done)break;a+=l.value.length,a>o&&J(413,"body_limit","The response body is too large."),s.push(l.value)}}finally{await i.cancel()}let c=new Uint8Array(a),u=0;for(let l of s)c.set(l,u),u+=l.length;return{status:n.status,headers:Object.fromEntries(n.headers),body:c}}};function qV(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Nde=Object.assign(Object.create(null),{dpop:()=>J(502,"invalid_response","The service returned an unsupported token.")}),G3e={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Nde,{"user access token":()=>{}})},H3e={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&J(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},B3e={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+qV(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},K3e={tokenParameters(t){let e=t.get("redirect_uri");e!==null&&(t.set("redirect_url",e),t.delete("redirect_uri"))}};function Sa(t,e){let r=e?new URL(e):void 0;return{recognizedTokenTypes:Nde,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...t.adapter==="ebay"?G3e:t.adapter==="openrouter"?H3e:t.adapter==="vultr"?K3e:{},...t.revoke?.style==="github"?B3e:{}}}function vc(t,e){try{return Si(new I$(t).expand(e)).href}catch{J(400,"invalid_service_url","Check the service URL and its required fields.")}}var zde=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],hk=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&J(502,"invalid_response","The service returned an invalid expiry."),e};var Kd=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...lu(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof tc&&J(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&J(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(vc(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:Sa(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await ade(n),c.code_challenge_method="S256"),Sa(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(vc(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:vc(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Si(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?fde():(e.clientSecret||J(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?pde(e.clientSecret):dde(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[MV]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);e&&Sa(e).tokenParameters?.(c);let u=await this.transport.send({url:o,method:s,headers:r==="json"?{...i,"content-type":"application/json"}:i,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(e){return dh({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&bi(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&J(409,"reconnect_required","Reconnect this service to renew access."),r===429&&J(503,"service_rate_limit","The service is busy. Try again later."),J(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&J(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,Sa(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=hk(u.expires_in));try{let d=await(n?_de:e.grantType==="client_credentials"?Ade:Rde)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:Sa(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;J(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[Sa(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&J(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+hk(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&J(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?zde(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+hk(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&J(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=Sa(e);if(l.exchange){let f=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>vc(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,f.status,dh(f))}else{let{server:f,client:p}=this.configuration(e,r),m;try{let y=Cde(f,p,o.parameters,o.state);m=await bde(f,p,this.authentication(r,e.clientAuth),y,l.redirectUri?.(r,i)??i,e.pkce?n:jV,{...this.options(e),additionalParameters:e.tokenParams})}catch(y){throw(y instanceof Yw||y instanceof Qw)&&J(400,"invalid_state","Start the connection again."),y}u=await this.tokenResponse(e,r,m)}let d=this.token(e,u,s,a);return await c?.(d,u),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&J(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=Sa(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Ide(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e)),d=await this.tokenResponse(e,r,l),f={...this.token(e,d,o,n,!!n),requestedScopes:o};return await i?.(f,d),f}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||J(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&J(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await yde(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return i}async revoke(e,r,o){e.revoke||J(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=vc(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Pde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await kde(d)}catch{J(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+qV(r.clientId,r.clientSecret??"")),(await this.transport.send(Sa(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&J(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,nl(bi(n,s))]))}};function VV(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function GV(t){return t||J(409,"app_required","Choose an OAuth application."),t}function Z3e(t){return{token:ij.parse(t.token),response:Lt.parse(t.response)}}var gk=class{constructor(e){this.transport=e}transport;facts=LL;oauth(e){return new Kd({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(e){return!e.oauth||e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=e.material,o=VV(r),n=GV(e.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>e.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(e.signal).clientCredentials(o,n,i??qi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return Bn.parse({...e.material,oauth:a})}async recover(e,r,o){let i=Z3e(o).token;return Bn.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(VV(e),GV(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(VV(e),GV(r),e.oauth)}};function Mde(t){if(t.method.kind!=="token")throw new Error("Use a token connection provider.");return t.method.config}var yk=class{facts=jL;needsRenewal(){return!1}async outputs(e){let r=lu(Mde(e).fields,e.fields);return Object.fromEntries(Object.entries(Mde(e).outputs).map(([o,n])=>[o,nl(bi(r,n))]))}};function vk(t){if(t.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return t.method.config}var wk=class{facts=FL;values(e,r){let o=vk(e),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&J(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:e.fields;return lu(o.fields,i)}credentials(e,r){if(vk(e).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:e.fields.consumerKey};let o=this.values(e,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(e,r){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o="ovh"in e?e.ovh:void 0;o&&o.expiresAt!==null&&o.expiresAt<=Date.now()&&J(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=vk(e).authorization==="consumer_key"?{...this.values(e,r),...this.credentials(e,r)}:this.values(e,r);return Object.fromEntries(Object.entries(vk(e).outputs).map(([i,s])=>[i,nl(bi(n,s))]))}};function Ude(t,e){return{oauth:new gk(t),token:new yk,aws:new nk(e),ovh:new wk}}function xa(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function _k(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!T5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=tt(nl(bi(JSON.parse(xa(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=xa(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var ph=class{constructor(e,r,o,n,i,s=new rk){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=Ude(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers[xr(e).family]}metadata(e){return Mf(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||J(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=Bn.safeParse(JSON.parse(xa(await ru(e,r,this.keys,{destination:o}))));n.success||J(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&J(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==ue.revoke&&J(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,ge.clientCredential,n),s=po.parse(JSON.parse(xa(await ru(i,o,this.keys))));return s.methodId!==r&&J(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(xr(e.method).application==="none")return null;if(!iu(e.method))return po.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===ue.revoke?ue.revoke:ue.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&J(409,"app_changed","Reconnect this service with the current application."),xr(e.method).requiresApp&&e.method.kind!=="aws"&&Object.entries(lo(e.method.config.fields,e.fields??{})).some(([s,a])=>i.fields[s]!==a)&&J(409,"app_changed","Reconnect this service with the current application settings."),i}async validate(e,r,o){let n=sj.parse(e);r.operation!==ue[n.action]&&J(400,"wrong_operation","Use the approved connection operation.");let i=await this.material(this.source(n.id,ge.tokenSet,o),r);await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=sj.parse(e);this.active.has(i.id)&&J(409,"connection_busy","Another operation is updating this connection."),this.active.add(i.id);try{n.throwIfAborted();let s=this.source(i.id,ge.tokenSet,o),a=await this.material(s,r);if(i.action==="refresh"){let u=await this.refresh(s,a,r,o,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(u)}}let c=this.provider(a.method);return c.revoke||J(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await c.revoke(a,await this.connectionApp(a,r,o),n),{kind:"revoked",id:s.policy.id}}finally{this.active.delete(i.id)}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&J(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&J(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await Y5(e.previous,tt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||J(409,"reconnect_required","Reconnect this service to renew access.");try{await sd(e,{...o,operation:ue.refresh},{destination:s})}catch{J(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=W3e(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let f=await a.renew({material:r,app:c,signal:i,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,f)}catch(f){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),f instanceof dt&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(f.code))throw f;J(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};import{lookup as J3e}from"node:dns/promises";import{request as X3e}from"node:https";import{brotliDecompressSync as Y3e,gunzipSync as Q3e,inflateSync as eHe}from"node:zlib";var fh=class{constructor(e){this.origin=e}origin;async send(e){let r=Si(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&J(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&J(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await J3e(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!mk(u.address)))&&J(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,m,y)=>{m.all?y(null,[a]):y(null,a.address,a.family)}},f=X3e(r,d,p=>{let m=[],y=0;p.on("data",w=>{y+=w.length,y>n?p.destroy(new dt(413,"body_limit","The response body is too large.")):m.push(w)}),p.on("error",l),p.on("end",()=>{try{let w=Buffer.concat(m),b=p.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?Q3e:b==="deflate"?eHe:b==="br"?Y3e:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,R]of Object.entries(p.headers))R!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(R)?R.join(", "):R);u({status:p.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&J(409,"cancelled","The operation was cancelled."),J(502,"service_unavailable","The service could not be reached. Try again.")}}};function On(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=HV(tHe(Ja()),"custody",r.id),i=new dd(HV(n,"client"),o,r,e),s=new O$(t,o,r,e,new D$(i)),a=new N$(t),c=new fh(o),u=new ph(r,e,a.connections(),new dd(HV(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Lde(t,e){let{custody:r,keys:o,binding:n,connections:i}=On(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await ee(n),operation:ue.command,functionDigest:null,operationDigest:await ee(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await ee(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ge.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return _k(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ge.value)return ru(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return tt(d[u.output])})}import{mkdir as Bnt}from"node:fs/promises";import{join as Z_}from"node:path";import{setTimeout as Knt}from"node:timers/promises";function rHe(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[o.name]=n}return r}function bk(t,e){let r=rHe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ba.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(f=>f.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,f)=>{if(!t.parameters.some(p=>p.name===f))throw new Error("Declare every function parameter.");return Object.hasOwn(r,f)?n(r[f]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,f])=>[d,i(f,l)])):u},s=new I$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Ha.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.");return{kind:"http",request:a}}function jde(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var Fde=h.object({operation:Za,save:h.record(h.string(),me)}).strict();function Sk(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function qde(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=o$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=Oy.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await ee(Sk(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(C(e.request)!==C(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(e)!==C(Za.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&C(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==C(o.save))throw new Error("Use the reviewed output destinations.")}function nHe(t,e){return t.policy.contentType===ge.value?e.output===void 0:t.policy.contentType===ge.tokenSet&&e.output!==void 0}var Ea=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},xk=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Tf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Tf(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await ee(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let f=await Tf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:f,delivered:!1}),await this.broker.finish(r.lease,f),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(f=>{f.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let f=await e8(r.request,this.binding,this.keys);await kf(this.environment,f.intent);let p=Za.parse(f.operation);if(ue[p.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await qde(o,p),await this.validateOperation(p,o,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.executeOperation(p,o,r.sources,c);d=await Tf(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(f){if(f instanceof Ea)throw f;f instanceof Af&&(f=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let p=l&&(c.aborted||!(f instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(f.code));d=await Tf(o,p?"uncertain":"failed",{ok:!1,result:null,error:f instanceof dt?{code:f.code,message:f.message}:{code:p?"execution_uncertain":"invalid_execution",message:p?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?bk(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async validateOperation(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await ko(c);let u=r.sources.find(f=>f.id===c.policy.id);if(!u||!await kL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await ee(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(ue[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Si(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=e_(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");FV(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(e_(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await tu(u.approval);if(C(l.policy.authorities.find(d=>d.id===l.authorityId))!==C(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==ge.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&C(d.executor)===C(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?bk(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!nHe(u,c))throw new Error("Use the input named in the signed request.");await sd(u,r,{...n?{destination:n.url}:{}}),await ru(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async executeOperation(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?bk(e.definition,e.arguments):e,a=[],c=new Map,u=async m=>{let y=o.find(b=>b.policy.id===m.id);if(y.policy.contentType===ge.value)return ru(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(m.id)||c.set(m.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(m.id);if(!m.output||!Object.hasOwn(w,m.output))throw new Error("Choose an available connection output.");return tt(w[m.output])};if(s.kind==="command"){let m=await _k(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:m.environment,files:m.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new dt(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new dt(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new dt(422,"function_failed",ol(y.stderr,m.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,ol(y.stdout,m.sensitive))}return{...y,stdout:ol(y.stdout,m.sensitive),stderr:ol(y.stderr,m.sensitive)}}let l=structuredClone(i);for(let m of l.bindings){let y="";for(let w of m.parts)if(typeof w=="string")y+=w;else{let b=xa(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}FV(l,m.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(f.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,ol(xa(f.body),a))}let p=e.kind==="http"?e.save:{};if(Object.keys(p).length){if(f.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let m={};for(let[y,w]of Object.entries(p)){let b=f.body;if(y!==""){let x=bi(JSON.parse(xa(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=tt(typeof x=="string"?x:JSON.stringify(x))}let S=await zy(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});m[w.name]=(await this.broker.capture(w.name,S)).id}return{status:f.status,saved:m}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([m,y])=>[m,ol(y,a)])),body:ol(xa(f.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:wr.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:bi(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=tt(typeof c=="string"?c:JSON.stringify(c)),l=await zy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};import{spawn as oHe}from"node:child_process";import{constants as BV}from"node:fs";import{open as Vde,rm as iHe}from"node:fs/promises";async function Gde(t){if(process.platform!=="linux"){let r=await Vde(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await iHe(t,{force:!0})}}let e=await Vde(t,BV.O_CREAT|BV.O_WRONLY|BV.O_NOFOLLOW,384);try{let r=oHe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var yD=Vt(RV(),1),vD=Vt(E0e(),1);function $0e(t){return TL.safeParse(t).success?t:null}async function R0e(t=3e3){let e=new yD.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new yD.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=$0e(n.Arn);if(i)return i;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new vD.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new vD.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=$0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var jG=h.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),FG=jG.max(4096).startsWith("/"),I0e=h.object({command:h.array(jG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:FG.optional(),environment:h.record(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),jG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:h.string().max(1e6).default(""),timeoutSeconds:h.number().int().min(1).max(3600).default(60)}).strict(),yKt=I0e.extend({id:E.optional()}),A0e=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),P0e=h.object({exitCode:h.number().int().nullable(),signal:h.string().max(32).nullable(),stdout:h.string().max(1e6),stderr:h.string().max(1e6),timedOut:h.boolean(),truncated:h.boolean()}).strict(),vKt=h.object({state:A0e.exclude(["queued","running"]),result:P0e.nullable(),error:h.string().max(100).nullable()}).strict(),wD=I0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:FG,state:A0e,result:P0e.nullable(),error:h.string().nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),wKt=wD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),_Kt=h.object({workingDirectory:FG}).strict(),k0e=h.object({lease:E,process:wD}).strict().nullable();var _D=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},k0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},wD)}},bD=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Ea}return!0}};var SD=h.object({format:h.literal(1),functionId:E,ownerId:E,revision:h.number().int().positive(),definition:Qo,author:or,executor:or,createdAt:Ae,signature:Sr}).strict();async function T0e(t,e){return SD.parse({...t,signature:await ur(t,e.signing,"function-publication")})}async function C0e(t,e){let r=SD.parse(t),{signature:o,...n}=r;if(await Ds(n.author),await Mr(n,o,n.author.signing,"function-publication"),e&&C(n.executor)!==C(e))throw new Error("This function is approved for another executor.");return r}var qG=h.object({functionId:E,publication:SD,contents:h.record(E,h.object({version:h.number().int().positive(),content:tn}).strict())}).strict(),Ont=h.object({name:me,definition:Qo,authorization:qG}).strict(),TKt=Ont.extend({version:h.number().int().positive()}),Dnt=h.object({id:E.optional(),ownerId:E.optional(),arguments:Lt.default({}),outputs:h.record(h.string().max(500),f$).default({})}).strict(),O0e=h.object({code:h.string().max(100),message:h.string().max(1e3)}).strict(),D0e=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,state:d$,result:wr.nullable(),error:O0e.nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),Nnt=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,actor:or.nullable(),arguments:Lt,outputs:Dnt.shape.outputs,definitionDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:Ae,expiresAt:Ae}).strict(),N0e=h.object({id:E,requestDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),state:d$.exclude(["queued","running"]),result:wr.nullable(),error:O0e.nullable(),finishedAt:Ae,signature:Sr}).strict(),z0e=h.object({lease:E,request:Nnt,publication:SD,sources:h.array(tn).max(100)}).strict().nullable();var xD=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/invocations/claim",{method:"POST",body:{}},z0e)}dispatch(e,r){return this.api.json("/api/runtime/functions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/runtime/functions/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean(),reason:h.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(e,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:e,completion:r}},D0e)}},ED=class{constructor(e,r,o,n=15e3){this.executor=e;this.broker=r;this.journal=o;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(e,r,o,n){let i={id:e.id,requestDigest:e.digest,state:r,result:o,error:n,finishedAt:new Date().toISOString()};e.completion=N0e.parse({...i,signature:await ur(i,this.executor.keys.signing,"function-result")}),e.phase="settled",await this.journal.write("invocation_"+e.id,e)}async deliver(e){await this.broker.finish(e.lease,e.completion),e.delivered=!0,await this.journal.write("invocation_"+e.id,e)}async reconcile(){let e=[];for(let r of await this.journal.keys("invocation_"))try{let o=await this.journal.read(r);if(!o||o.delivered||o.phase==="prepared")continue;o.completion||await this.complete(o,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(o)}catch{e.push(r.slice(11))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:o,publication:n,sources:i,lease:s}=r,a=await ee(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),f=!1,p=!1,m=setInterval(()=>{p||(p=!0,this.broker.renew(o.id,s).then(y=>{y.active||(f||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{p=!1}))},this.renewalMilliseconds);m.unref();try{if(await C0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await ee(n.definition)!==o.definitionDigest||Date.parse(o.expiresAt)<=Date.now())throw new Error("Run the current approved function in its configured environment.");let y="function_"+n.functionId,w=await this.journal.read(y),b=await ee(n);if(w&&(n.revision<w.revision||n.revision===w.revision&&w.digest!==b))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(y,{revision:n.revision,digest:b});let S=a8.parse({kind:"function",functionId:o.functionId,definition:n.definition,arguments:o.arguments,outputs:o.outputs}),x={format:2,id:o.id,origin:this.executor.environment.manifest.origin,ownerId:o.ownerId,actor:o.actor??this.executor.binding,executor:this.executor.binding,environmentId:n.definition.environmentId,environmentDigest:await ee(this.executor.environment.manifest),operation:ue.function,operationDigest:await ee(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await ee(T.policy),materialRevision:T.materialRevision,...T.policy.contentType===ge.tokenSet&&typeof T.metadata.authorizationDigest=="string"?{authorizationDigest:T.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:o.createdAt,expiresAt:o.expiresAt};await kf(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let R=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(R)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",R,null)}catch(y){if(y instanceof Ea)throw y;let w=u.phase==="dispatched",b=d.aborted&&f?"cancelled":w&&(d.aborted||!(y instanceof dt))?"uncertain":"failed";await this.complete(u,b,null,!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="uncertain"?"execution_uncertain":b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="uncertain"?"Check the result before invoking this function again.":b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(m)}try{await this.deliver(u)}catch{throw new Ea}return!0}};import{spawn as znt,execFile as Mnt}from"node:child_process";import{chmod as Unt,lstat as M0e,mkdir as VG,readFile as U0e,readdir as Lnt,realpath as L0e,rename as jnt,rm as Fnt,symlink as qnt,writeFile as j0e}from"node:fs/promises";import{join as fl}from"node:path";import{promisify as Vnt}from"node:util";import{createConnection as Gnt}from"node:net";import{setTimeout as Hnt}from"node:timers/promises";var GG=Vnt(Mnt),K_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',$D=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=fl(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await VG(this.options.directory,{recursive:!0,mode:448}),await VG(this.sessions,{recursive:!0,mode:448}),await VG(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await M0e(this.options.workspaceLink),await L0e(this.options.workspaceLink)!==await L0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await qnt(this.options.workspace,this.options.workspaceLink)}let e=fl(this.options.directory,"host_ed25519");try{await M0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await GG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Fi(),timeout:1e4})}await Unt(e,384),this.hostKey=yy.parse((await GG("ssh-keygen",["-y","-f",e],{env:Fi(),timeout:1e4})).stdout);let r=fl(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+K_(e),"PidFile "+K_(fl(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+K_(fl(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+K_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+K_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
132
132
  `)+`
133
133
  `;await j0e(r,o,{mode:384}),await this.sync(),await GG("/usr/sbin/sshd",["-t","-f",r],{env:Fi(),timeout:1e4});let n=znt("/usr/sbin/sshd",["-D","-e","-f",r],{env:Fi(),detached:!0,stdio:"ignore"});this.child=n;let i=null;n.once("error",s=>{i=s});try{for(let s=0;;s++){if(i||n.exitCode!==null||n.signalCode!==null||s>=100)throw i??new Error("The SSH server could not start.");if(await this.listening())break;await Hnt(50)}await this.sync(),this.timer=setInterval(()=>{!this.pending&&!this.closing&&(this.pending=this.sync().catch(()=>{process.stderr.write(JSON.stringify({event:"ssh_settings_pending"})+`
134
134
  `)}).finally(()=>{this.pending=null}))},1e4),this.timer.unref()}catch(s){throw await this.stop(),s}}ensureRunning(){if(!this.child?.pid||this.child.exitCode!==null||this.child.signalCode!==null)throw new Error("The SSH server has stopped.")}listening(){return new Promise(e=>{let r=Gnt({host:this.options.listenAddress==="::1"?"::1":"127.0.0.1",port:this.options.port});r.setTimeout(500),r.once("connect",()=>{r.destroy(),e(!0)}),r.once("error",()=>{r.destroy(),e(!1)}),r.once("timeout",()=>{r.destroy(),e(!1)})})}async activeSessions(){let e=0;for(let r of await Lnt(this.sessions)){if(!/^[1-9][0-9]*$/.test(r))continue;let o=fl(this.sessions,r);try{let[n,i]=await Promise.all([U0e(o,"utf8"),U0e("/proc/"+r+"/stat","utf8")]),s=a=>a.slice(a.lastIndexOf(")")+2).trim().split(/\s+/)[19];if(!s(n)||s(n)!==s(i))throw new Error("The SSH session has ended.");e++}catch{await Fnt(o,{force:!0})}}return Math.min(e,1024)}async sync(){let{configuration:e}=dE.parse(await this.heartbeat({hostKey:this.hostKey,appliedRevision:this.child?.pid&&this.child.exitCode===null&&this.child.signalCode===null?this.appliedRevision:0,activeSessions:await this.activeSessions()}));if(!e||e.port!==this.options.port)throw new Error("The SSH settings belong to another listener.");if(this.appliedRevision!==e.revision){let r=fl(this.options.directory,"authorized_keys."+crypto.randomUUID());await j0e(r,e.authorizedKeys.join(`
@@ -225,7 +225,7 @@ The last two values are base64url-encoded JSON; omit both for metadata-only acce
225
225
  `,At={type:"string"},fp={type:"boolean"},qpt={name:At,key:At,origin:At,owner:At,to:At,message:At,body:At,file:At,stdin:fp,for:{type:"string",multiple:!0},fingerprint:At,id:At,isolation:At,image:At,managed:fp,once:fp,method:At,"client-id":At,"client-secret":At,app:At,connection:At,fields:At,scopes:At,aws:At,parameters:At,"redirect-uri":At,inputs:At,request:At,save:At,arguments:At,environment:At,timeout:At,wait:fp,output:At,force:fp,upload:At,help:fp,version:fp};function Vpt(t){return Dpt({args:t,options:qpt,allowPositionals:!0,allowNegative:!0,strict:!0})}function Yb(t){process.stdout.write(JSON.stringify(t,null,2)+`
226
226
  `)}function er(t,e){if(!t)throw new Error(e);return t}async function xAe(t=22e5){let e=[],r=0;for await(let o of process.stdin){let n=Buffer.from(o);if(r+=n.length,r>t)throw new Error("The input is too large.");e.push(n)}return Buffer.concat(e)}async function t1(t){return t==="@-"?(await xAe()).toString("utf8"):t.startsWith("@")?await AB(t.slice(1),"utf8"):t}async function wn(t,e={}){if(!t)return e;let r=await t1(t);try{return JSON.parse(r)}catch{throw new Error("Invalid JSON. Supply JSON text, @FILE, or @-.")}}function mp(t,e,r=86400){if(t===void 0)return e;let o=Number(t);if(!Number.isInteger(o)||o<1||o>r)throw new Error("Choose a time limit between 1 and "+r+" seconds.");return o}async function qt(t,e){let r=JSON.stringify(t,null,2)+`
227
227
  `;e.values.output?await Cf(e.values.output,r,!!e.values.force):process.stdout.write(r)}async function yAe(t,e,r){if(!t.body)throw new Error("Foundation returned an empty response.");let o=_Ae(e),n=r?Lpt(Upt(o),".foundation-"+jpt()):o,i=await Npt(n,"wx",384),s=!1;try{await SAe(bAe.fromWeb(t.body),i.createWriteStream()),r&&await zpt(n,o),s=!0}finally{await i.close().catch(()=>{}),s||await Mpt(n,{force:!0})}}async function vAe(t,e){let r=e.trim().split(".");if(r.length!==2||!/^[A-Za-z0-9_-]+$/.test(r[0])||!/^[A-Za-z0-9_-]{43}$/.test(r[1]))throw new Error("Use a sign-in key containing an authentication token and a separate encryption unlock code.");let[o,n]=r,i;try{i=await fetch(t+"/api/session",{headers:{authorization:"Bearer "+o},redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!i.ok)throw new Error("Sign-in failed (HTTP "+i.status+").");let s=QE.parse(await i.json());if(!s.principal)throw new Error("The key was not accepted.");if(!s.wrappedKey)throw new Error("This key does not carry an encryption key. Issue it from a browser that can open encrypted values.");let a=Ty.parse(await M5(s.wrappedKey,z5(n),s.principal.id).catch(()=>{throw new Error("The encryption key could not be unlocked with this key.")})),c=new Wa({origin:t,principalId:s.principal.id,token:o,keys:null,binding:null}),{binding:u}=await c.json("/api/identities/"+s.principal.id+"/binding",{},Os);await Cy(u,a);let l={origin:t,principalId:s.principal.id,token:o,keys:a,binding:u};await Uy(l);let{done:d,failed:f}=await On(new Wa(l)).custody.reprotectPending().catch(p=>(process.stderr.write("Could not check for items to seal again: "+(p instanceof Error?p.message:String(p))+`
228
- `),{done:[],failed:[]}));d.length&&process.stderr.write("Sealed "+d.length+` item(s) again without their expired grants.
228
+ `),{done:[],failed:[]}));d.length&&process.stderr.write("Sealed "+d.length+` item(s) again for their current readers and grants.
229
229
  `),f.length&&process.stderr.write(f.length+` item(s) could not be sealed again yet; signing in again retries them.
230
230
  `),Yb({principal:{id:s.principal.id,name:s.principal.name},origin:t,identity:Ja(),fingerprint:await rd(u)})}async function Gpt(t){let e=ou(t.values.origin);if(t.values.key)return vAe(e,await t1(t.values.key));let r=me.parse(t.values.name||e1()),o=await e$(),n;try{n=await fetch(e+"/api/auth/devices",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:r,publicKey:o.publicKey}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!n.ok)throw new Error("Sign-in could not start (HTTP "+n.status+").");let i=h.object({id:E,code:h.string(),poll:h.string(),url:h.url(),expiresAt:h.string()}).parse(await n.json());process.stderr.write(`Open ${i.url}
231
231
  and enter the code ${i.code.slice(0,4)}-${i.code.slice(4)} to sign in as yourself.