@tomato414941/foundation 22.1.0 → 22.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.
package/dist/agent.mjs CHANGED
@@ -119,7 +119,7 @@ ${c}
119
119
  }`,m;try{m=new l(...s,d)(...a)}catch(p){throw new Ae(`this schema (generated code failed to evaluate: ${p.message})`)}return t?.debug&&(m.code=u),m.definite=i.definite,m}function ie(e,t){for(let[i,n]of e.constants)if(n===t)return i;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function ec(e,t){return e.definite=!1,ie(e,t)}function Y(e){return`v${e.varCounter++}`}function Eve(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return Cr;let i=r;return i.issues.length===0?i.value:Cr}function yr(e,t,r,i,n=!0){let o=e.content.length,s=t.constants.size,a=t.constantCounter,c=t.varCounter;try{return ht(e,t,r,i,n)}catch(u){if(!(u instanceof Ae)||!u.islandable)throw u;if(e.content.length=o,t.constants.size>s){let l=Array.from(t.constants.keys()).slice(s);for(let d of l)t.constants.delete(d)}return t.constantCounter=a,t.varCounter=c,Ave(e,t,r,i)}}function Ave(e,t,r,i){t.definite=!1;let n=ie(t,r),o=ie(t,Eve),s=Y(t);return e.write(`const ${s} = ${o}(${n}, ${i});`),e.write(`if (${s} === INVALID) return INVALID;`),s}var Rve=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Ive(e,t,r,i){let n=r._zod.def.checks;if(!n||n.length===0)return i;let o=i;for(let s of n){let a=s._zod.def;if(a.when&&!Rve.has(a.check))throw new Ae('check with a custom "when" condition');switch(a.check){case"greater_than":$ve(e,t,a,o);break;case"less_than":Pve(e,t,a,o);break;case"multiple_of":Tve(e,t,a,o);break;case"number_format":N2(e,a,o);break;case"min_length":{let c=Ya(a.minimum,"min_length"),u=zT(e,t,o,`${o}.length >= ${c} && ${o}.length < ${a.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Ya(a.maximum,"max_length"),u=zT(e,t,o,`${o}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Ya(a.length,"length_equals"),u=zT(e,t,o,`${o}.length >= ${c} && ${o}.length <= ${a.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Ya(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Ya(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Ya(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=U2(e,t,a,o);break;case"custom":o=Uve(e,t,s,o);break;case"bigint_format":Cve(e,a,o);break;case"mime_type":kve(e,t,a,o);break;case"property":Ove(e,t,a,o);break;case"properties":Dve(e,t,a,o);break;case"overwrite":{let c=Y(t);Nve(e,t,s,o,c),o=c;break}default:throw new Ae(`check type ${a.check}`)}}return o}function zT(e,t,r,i){let n=ie(t,Wa),o=Y(t);return e.write(`const ${o} = typeof ${r} === "string" && ${i} ? ${n}(${r}) : ${r}.length;`),o}function Ya(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Ae(`${t} bound of type ${typeof e}`);return`${e}`}function O2(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Ae("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Ae("comparison check with Invalid Date bound");return ie(e,t)}throw new Ae(`comparison check bound of type ${typeof t}`)}function $ve(e,t,r,i){let n=r.inclusive?"<":"<=";e.write(`if (${i} ${n} ${O2(t,r.value)}) return INVALID;`)}function Pve(e,t,r,i){let n=r.inclusive?">":">=";e.write(`if (${i} ${n} ${O2(t,r.value)}) return INVALID;`)}function Tve(e,t,r,i){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Ae("multiple_of check with a zero divisor");e.write(`if (${i} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ie(t,pp);e.write(`if (${n}(${i}, ${Ya(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function N2(e,t,r){let i=t.format;switch(i){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Ae(`number format ${i}`)}}function Cve(e,t,r){let i=t.format;if(i)switch(i){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Ae(`bigint format ${i}`)}}function kve(e,t,r,i){let n=r.mime;if(n&&n.length>0){let o=ie(t,new Set(n));e.write(`if (!${o}.has(${i}.type)) return INVALID;`)}}function Dve(e,t,r,i){if(r.when)throw new Ae('check with a custom "when" condition');e.write(`if (${i} == null) return INVALID;`);let n=r.shape;for(let o of Reflect.ownKeys(n)){let s=typeof o=="symbol"?ie(t,o):Pr(o),a=Y(t);e.write(`const ${a} = ${i}[${s}];`),yr(e,t,n[o],a,!1)}}function Ove(e,t,r,i){let n=`${i}[${JSON.stringify(r.property)}]`;ht(e,t,r.schema,n)}function Nve(e,t,r,i,n){let o=r._zod.def.tx;if(!o)throw new Ae("overwrite check without a transform function");if(tc(o))throw new Yn("z.compile: async overwrite transforms are not supported");let s=ie(t,o);e.write(`const ${n} = ${s}(${i});`)}function jT(){throw new Hr}function qT(e){this.issues.push(e)}function Uve(e,t,r,i){let n=r._zod.def;if(n.fn){if(tc(n.fn))throw new Yn("z.compile: async .refine() predicates are not supported");let o=ec(t,n.fn),s=ie(t,jT),a=Y(t);return e.write(`const ${a} = ${o}(${i});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`),i}if(r._zod.check){if(tc(r._zod.check))throw new Yn("z.compile: async .superRefine() / check functions are not supported");let o=r._zod.check,a=ec(t,u=>{let l={value:u,issues:[],addIssue:qT};return o(l)instanceof Promise&&jT(),l.issues.length===0?l.value:Cr}),c=Y(t);return e.write(`const ${c} = ${a}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new Ae("custom check without a predicate or check function")}var Lve=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 U2(e,t,r,i,n=!0){let o=r.format;if(o==="base64"){let u=ie(t,Cp);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="base64url"){let u=ie(t,Sy);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="jwt"){let u=ie(t,_y),l=ie(t,r.alg??null);return e.write(`if (!${u}(${i}, ${l})) return INVALID;`),i}if(o==="ipv6"){let u=ie(t,Tp);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="cidrv6"){let u=ie(t,yy);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="credit_card"){let u=ie(t,wy);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(o==="iban"){let u=ie(t,by);return e.write(`if (!${u}(${i})) return INVALID;`),i}let s=r;if(o==="url"||o==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=ie(t,my),l=ie(t,r),d=Y(t),m=Y(t);if(e.write(`const ${d} = ${i}.trim();`),e.write(`const ${m} = ${u}(${d}, ${l});`),e.write(`if (typeof ${m} === "number") return INVALID;`),s.hostname!==void 0){let v=ie(t,hy);e.write(`if (!${v}(${m}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let v=ie(t,gy);e.write(`if (!${v}(${m}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=Y(t),g=s.normalize?`${m}.href`:`${ie(t,Pp)}(${d})`;return e.write(`const ${p} = ${g};`),p}let a=r.fn;if(a){if(tc(a))throw new Ae(`async string format ${o}`);let u=ie(t,a);return e.write(`if (!${u}(${i})) return INVALID;`),i}if(Lve.has(o)&&r.pattern){let u=ie(t,r.pattern);return e.write(`${u}.lastIndex = 0;`),e.write(`if (!${u}.test(${i})) return INVALID;`),i}let c=r.format;switch(c){case"regex":throw new Ae("regex format without a pattern");case"lowercase":e.write(`if (${i} !== ${i}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${i} !== ${i}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${i}.includes(${Pr(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;e.write(`if (${i}.slice(0, ${u.length}) !== ${Pr(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;e.write(`if (${i}.slice(-${u.length}) !== ${Pr(u)}) return INVALID;`);break}default:throw new Ae(`string format ${c}`)}return i}function ht(e,t,r,i,n=!0){let o=r._zod.def,s=o.type;if(o.coerce)throw new Ae(`coercion (z.coerce.${s}())`);let a=n||!!o.checks?.length,c;switch(s){case"string":c=Mve(e,t,r,i,a);break;case"number":c=zve(e,r,i);break;case"boolean":c=jve(e,i);break;case"bigint":c=Fve(e,r,i);break;case"symbol":c=Gve(e,i);break;case"undefined":c=qve(e,i);break;case"null":c=Vve(e,i);break;case"any":case"unknown":c=i;break;case"never":e.write("return INVALID;"),c=i;break;case"void":c=Kve(e,i);break;case"nan":c=Bve(e,i);break;case"date":c=Hve(e,i);break;case"object":c=Wve(e,t,r,i,a);break;case"optional":c=Jve(e,t,r,i,a);break;case"nullable":c=Yve(e,t,r,i,a);break;case"array":c=Qve(e,t,r,i,a);break;case"literal":c=eSe(e,t,r,i);break;case"enum":c=tSe(e,t,r,i);break;case"readonly":{let u=C2(e,t,r,i),l=Y(t);e.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":C2(e,t,r,i),c="true";break;case"default":case"prefault":c=rSe(e,t,r,i);break;case"nonoptional":c=nSe(e,t,r,i);break;case"tuple":c=iSe(e,t,r,i);break;case"union":c=oSe(e,t,r,i);break;case"intersection":c=cSe(e,t,r,i);break;case"record":c=uSe(e,t,r,i);break;case"map":c=dSe(e,t,r,i);break;case"set":c=pSe(e,t,r,i);break;case"file":c=fSe(e,i);break;case"template_literal":c=mSe(e,t,r,i);break;case"lazy":c=hSe(e,t,r,i);break;case"pipe":c=gSe(e,t,r,i);break;case"custom":c=ySe(e,t,r,i);break;case"transform":c=wSe(e,t,r,i);break;case"catch":c=SSe(e,t,r,i);break;default:throw new Ae(`schema type ${s}`)}return c===null?null:Ive(e,t,r,c)}function Mve(e,t,r,i,n=!0){e.write(`if (typeof ${i} !== "string") return INVALID;`);let o=r._zod.def;return o.format===void 0?i:U2(e,t,o,i,n)}function zve(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let i=t._zod.def;return i.check==="number_format"&&i.format&&N2(e,{format:i.format},r),r}function jve(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function Fve(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let i=t._zod.def;if(i.format)switch(i.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function Gve(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function qve(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Vve(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function Kve(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Bve(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function Hve(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function Wve(e,t,r,i,n=!0){let o=r._zod.def;e.write(`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) return INVALID;`);let s=o.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=_=>typeof _=="symbol"?ie(t,_):Pr(_),d=_=>typeof _=="symbol"?`[${l(_)}]`:Pr(_),m=s;if(a.includes("__proto__"))throw new Ae('object shape key "__proto__"');let p=new Map;for(let _ of u){let x=m[_],T=l(_),U=Y(t);if(e.write(`const ${U} = ${i}[${T}];`),x._zod.optin!==void 0){let C=Y(t);e.write(`let ${C} = (() => {`),e.indented(G=>{let B=yr(G,t,x,U);G.write(`return ${B};`)}),e.write("})();"),x._zod.optout==="optional"?(e.write(`if (${C} === INVALID) {`),e.indented(G=>{G.write(`if (${T} in ${i}) return INVALID;`),G.write(`${C} = undefined;`)}),e.write("}")):e.write(`if (${C} === INVALID) return INVALID;`),p.set(_,C)}else{Xve(x)&&e.write(`if (!(${T} in ${i})) return INVALID;`);let C=yr(e,t,x,U,n);C!==null&&p.set(_,C)}}let g=o.catchall,v="none";if(g){let _=g._zod.def.type;if(_==="never"){let x=a.map(T=>`k !== ${Pr(T)}`).join(" && ")||"true";e.write(`for (const k in ${i}) {`),e.indented(T=>{T.write(`if (${x}) return INVALID;`)}),e.write("}")}else(_==="unknown"||_==="any")&&!g._zod.def.checks?.length?v="passthrough":v="schema"}let S=Y(t),b=u.some(_=>T2(m[_])||FT(m[_]));if(!n){if(v==="schema"){let _=a.length>0?ie(t,new Set(a)):null;e.write(`for (const k in ${i}) {`),e.indented(x=>{x.write('if (k === "__proto__") continue;'),_&&x.write(`if (${_}.has(k)) continue;`);let T=Y(t);x.write(`const ${T} = ${i}[k];`),yr(x,t,g,T,!1)}),e.write("}")}return null}if(b){e.write(`const ${S} = {};`);for(let _ of u){let x=l(_),T=p.get(_);FT(m[_])?e.write(`if (${x} in ${i}) ${S}[${x}] = ${T};`):T2(m[_])?e.write(`if (${T} !== undefined || ${x} in ${i}) ${S}[${x}] = ${T};`):e.write(`${S}[${x}] = ${T};`)}}else{let _=u.map(x=>`${d(x)}: ${p.get(x)}`).join(", ");e.write(`const ${S} = { ${_} };`)}if(v!=="none"){let _=a.length>0?ie(t,new Set(a)):null;e.write(`for (const k in ${i}) {`),e.indented(x=>{if(x.write('if (k === "__proto__") continue;'),_&&x.write(`if (${_}.has(k)) continue;`),v==="passthrough")x.write(`${S}[k] = ${i}[k];`);else{let T=Y(t);x.write(`const ${T} = ${i}[k];`);let U=yr(x,t,g,T);x.write(`${S}[k] = ${U};`)}}),e.write("}")}return S}function Jve(e,t,r,i,n=!0){let o=r._zod.def;if(Zve(r))return ht(e,t,o.innerType,i,n);if(o.innerType._zod.optin==="defaulted"){let a=Y(t),c=Y(t);return e.write(`let ${a};`),e.write(`if (${i} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=ht(l,t,o.innerType,i);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),e.write("} else {"),e.indented(u=>{let l=ht(u,t,o.innerType,i);u.write(`${a} = ${l};`)}),e.write("}"),a}let s=n?Y(t):null;return s&&e.write(`let ${s};`),e.write(`if (${i} !== undefined) {`),e.indented(a=>{let c=ht(a,t,o.innerType,i,n);s&&c!==null&&a.write(`${s} = ${c};`)}),e.write("}"),s}function Zve(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function Xve(e){return e._zod.optin===void 0&&Qa(e)}function Qa(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.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 t.innerType?Qa(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Qa(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Qa):!0;case"intersection":return!t.left||!t.right?!0:Qa(t.left)&&Qa(t.right);case"pipe":return t.in?Qa(t.in):!0;default:return!0}}function FT(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function T2(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Cu(e)}function Cu(e){let t=e._zod.def;switch(t.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!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?Cu(t.innerType):!0;case"union":return t.options?t.options.some(Cu):!0;case"intersection":return!t.left||!t.right||Cu(t.left)||Cu(t.right);case"pipe":return t.out?Cu(t.out):!0;default:return!0}}function Yve(e,t,r,i,n=!0){let o=r._zod.def,s=n?Y(t):null;return s&&e.write(`let ${s} = null;`),e.write(`if (${i} !== null) {`),e.indented(a=>{let c=ht(a,t,o.innerType,i,n);s&&c!==null&&a.write(`${s} = ${c};`)}),e.write("}"),s}function Qve(e,t,r,i,n=!0){let o=r._zod.def;e.write(`if (!Array.isArray(${i})) return INVALID;`);let s=n?Y(t):null,a=Y(t),c=Y(t);return s&&e.write(`const ${s} = new Array(${i}.length);`),e.write(`for (let ${a} = 0; ${a} < ${i}.length; ${a}++) {`),e.indented(u=>{u.write(`const ${c} = ${i}[${a}];`);let l=yr(u,t,o.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),e.write("}"),s}function eSe(e,t,r,i){let o=r._zod.def.values;if(o.length!==1){let a=ie(t,new Set(o));return e.write(`if (!${a}.has(${i})) return INVALID;`),i}let s=o[0];if(typeof s=="number"&&Number.isNaN(s)){let a=ie(t,new Set(o));return e.write(`if (!${a}.has(${i})) return INVALID;`),i}if(typeof s=="string")e.write(`if (${i} !== ${Pr(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")e.write(`if (${i} !== ${s}) return INVALID;`);else if(s===null)e.write(`if (${i} !== null) return INVALID;`);else if(s===void 0)e.write(`if (${i} !== undefined) return INVALID;`);else if(typeof s=="bigint")e.write(`if (${i} !== ${s}n) return INVALID;`);else throw new Ae(`literal type ${typeof s}`);return i}function tSe(e,t,r,i){let n=r._zod.values;if(!n)throw new Ae("enum schema without enumerated values");let o=ie(t,n);return e.write(`if (!${o}.has(${i})) return INVALID;`),i}function C2(e,t,r,i){let n=r._zod.def;return ht(e,t,n.innerType,i)}function rSe(e,t,r,i){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 ht(e,t,n.innerType,i);let c=ie(t,s),u=Y(t);return e.write(`let ${u} = ${i};`),e.write(`if (${i} === undefined) ${u} = ${c}();`),ht(e,t,n.innerType,u)}let a=Y(t);if(s){let c=ie(t,s),u=ie(t,fp);e.write(`let ${a};`),e.write(`if (${i} === undefined) {`),e.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),e.write("} else {"),e.indented(l=>{let d=ht(l,t,n.innerType,i);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${i} !== undefined) {`),e.indented(c=>{let u=ht(c,t,n.innerType,i);c.write(`${a} = ${u};`)}),e.write("}");return a}function nSe(e,t,r,i){let n=r._zod.def,o=ht(e,t,n.innerType,i),s=Y(t);return e.write(`const ${s} = ${o};`),e.write(`if (${s} === undefined) return INVALID;`),s}function iSe(e,t,r,i){let n=r._zod.def,o=n.items,s=n.rest;e.write(`if (!Array.isArray(${i})) return INVALID;`);let a=k2(o,"optin"),c=k2(o,"optout");s?e.write(`if (${i}.length < ${a}) return INVALID;`):e.write(`if (${i}.length < ${a} || ${i}.length > ${o.length}) return INVALID;`);let u=Y(t);e.write(`const ${u} = [];`);for(let l=0;l<o.length;l++){let d=o[l];if(l>=c)e.write(`if (${u}.length === ${l}) {`),e.indented(m=>{m.write(`if (${l} < ${i}.length) {`),m.indented(p=>{let g=Y(t);p.write(`const ${g} = ${i}[${l}];`);let v=yr(p,t,d,g);p.write(`${u}[${l}] = ${v};`)}),m.write("} else {"),m.indented(p=>{if(FT(d)){p.write(`${u}.length = ${l};`);return}let g=Y(t),v=Y(t);p.write(`const ${g} = undefined;`),p.write(`const ${v} = (() => {`),p.indented(S=>{let b=yr(S,t,d,g);S.write(`return ${b};`)}),p.write("})();"),p.write(`if (${v} === INVALID || ${v} === undefined) ${u}.length = ${l};`),p.write(`else ${u}[${l}] = ${v};`)}),m.write("}")}),e.write("}");else{let m=Y(t);e.write(`const ${m} = ${i}[${l}];`);let p=yr(e,t,d,m);e.write(`${u}[${l}] = ${p};`)}}if(s){let l=Y(t),d=Y(t);e.write(`for (let ${l} = ${o.length}; ${l} < ${i}.length; ${l}++) {`),e.indented(m=>{m.write(`const ${d} = ${i}[${l}];`);let p=yr(m,t,s,d);m.write(`${u}[${l}] = ${p};`)}),e.write("}")}return u}function k2(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function oSe(e,t,r,i){let n=r._zod.def,o=n.options;if(n.discriminator)return sSe(e,t,n,i);if(n.inclusive===!1)throw new Ae("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),i;if(o.length===1)return ht(e,t,o[0],i);if(o.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(o.flatMap(l=>l._zod.def.values)),u=ie(t,c);return e.write(`if (!${u}.has(${i})) return INVALID;`),i}let a=Y(t);e.write(`let ${a};`);for(let c=0;c<o.length;c++){let u=o[c];c===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(l=>{let d=ht(l,t,u,i);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function sSe(e,t,r,i){if(r.unionFallback)throw new Ae("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),i;let n=Y(t),o=Y(t);e.write(`const ${n} = ${i}?.[${Pr(r.discriminator)}];`),e.write(`let ${o};`);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 Ae("discriminated union option without static discriminator values");for(let m of u){if(a.has(m))throw new Ae(`duplicate discriminator value ${String(m)}`);a.add(m)}let l=Array.from(u,m=>aSe(t,n,m)),d=s?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(m=>{let p=ht(m,t,c,i);m.write(`${o} = ${p};`)}),e.write("}"),s=!1}return e.write("else { return INVALID; }"),o}function aSe(e,t,r){if(typeof r=="string")return`${t} === ${Pr(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let i=ie(e,r);return`${t} === ${i}`}throw new Ae(`literal discriminator value ${String(r)}`)}function cSe(e,t,r,i){let n=r._zod.def;t.definite=!1;let o=yr(e,t,n.left,i),s=yr(e,t,n.right,i),a=ie(t,$u),c=Y(t);return e.write(`const ${c} = ${a}(${o}, ${s});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function uSe(e,t,r,i){let n=r._zod.def,o=ie(t,bn);e.write(`if (!${o}(${i})) return INVALID;`);let s=Y(t),a=Y(t),c=Y(t);e.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let v of l){if(!(typeof v=="string"||typeof v=="number"||typeof v=="symbol"))throw new Ae(`record key value ${String(v)}`);let S=typeof v=="number"?v.toString():v;if(S==="__proto__")throw new Ae('record key "__proto__"');p.push(S);let b=ie(t,v),_=ht(e,t,n.keyType,b),x=Y(t);e.write(`const ${x} = ${i}[${lSe(t,S)}];`);let T=yr(e,t,n.valueType,x);e.write(`${s}[${_}] = ${T};`)}let g=ie(t,new Set(p));return e.write(`for (const ${a} in ${i}) {`),e.indented(v=>{v.write(`if (${g}.has(${a})) continue;`),u.mode==="loose"?v.write(`if (${a} !== "__proto__") ${s}[${a}] = ${i}[${a}];`):v.write("return INVALID;")}),e.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",g=jy(n.keyType);g.definite===!1&&(t.definite=!1);let v=ie(t,g),S=ie(t,Do),b=Y(t);return D2(e,t,i,a,_=>{_.write(`let ${b} = ${v}(${a});`),_.write(`if (${b} === INVALID && typeof ${a} === "string" && ${S}.test(${a})) ${b} = ${v}(Number(${a}));`),p?_.write(`if (${b} === INVALID) { ${s}[${a}] = ${i}[${a}]; continue; }`):_.write(`if (${b} === INVALID) return INVALID;`),_.write(`if (${b} === "__proto__") continue;`);let x=Y(t);_.write(`const ${x} = ${i}[${a}];`);let T=yr(_,t,n.valueType,x);_.write(`${s}[${b}] = ${T};`)}),s}return D2(e,t,i,a,p=>{p.write(`const ${c} = ${i}[${a}];`);let g=yr(p,t,n.valueType,c);p.write(`${s}[${a}] = ${g};`)},"return INVALID;"),s}function D2(e,t,r,i,n,o){let s=ie(t,Object.prototype.propertyIsEnumerable),a=Y(t),c=Y(t),u=Y(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${c} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),e.indented(l=>{l.write(`const ${i} = ${c}[${u}];`),l.write(`if (${i} === "__proto__" || !${s}.call(${r}, ${i})) continue;`),n(l)}),e.write("}"),e.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),e.indented(l=>{l.write(`const ${i} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${i})) continue;`),o?l.write(o):n(l)}),e.write("}")}function lSe(e,t){return typeof t=="string"?Pr(t):ie(e,t)}function dSe(e,t,r,i){let n=r._zod.def;e.write(`if (!(${i} instanceof Map)) return INVALID;`);let o=Y(t),s=Y(t),a=Y(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${s}, ${a}] of ${i}) {`),e.indented(c=>{let u=ht(c,t,n.keyType,s),l=ht(c,t,n.valueType,a);c.write(`${o}.set(${u}, ${l});`)}),e.write("}"),o}function pSe(e,t,r,i){let n=r._zod.def;e.write(`if (!(${i} instanceof Set)) return INVALID;`);let o=Y(t),s=Y(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${s} of ${i}) {`),e.indented(a=>{let c=ht(a,t,n.valueType,s);a.write(`${o}.add(${c});`)}),e.write("}"),o}function fSe(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function mSe(e,t,r,i){e.write(`if (typeof ${i} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let o=ie(t,n);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${i})) return INVALID;`)}return i}function hSe(e,t,r,i){let n=r._zod.def,o=ec(t,n.getter),s=ie(t,{parser:null});e.write(`if (!${s}.parser) {`),e.indented(c=>{c.write(`const inner = ${o}();`),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("};")}),e.write("}");let a=Y(t);return e.write(`const ${a} = ${s}.parser(${i});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function gSe(e,t,r,i){let n=r._zod.def,o=ht(e,t,n.in,i);if(n.transform){if(tc(n.transform))throw new Yn("z.compile: async transforms in pipes are not supported");let s=n.transform,c=ec(t,l=>{let d={value:l,issues:[],addIssue:qT},m=s(l,d);return m instanceof Promise?Cr:d.issues.length===0?m:Cr}),u=Y(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),ht(e,t,n.out,u)}else return ht(e,t,n.out,o)}function tc(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function ySe(e,t,r,i){let n=r._zod.def;if(n.fn){if(tc(n.fn))throw new Yn("z.compile: async custom predicates are not supported");let o=ec(t,n.fn),s=ie(t,jT),a=Y(t);e.write(`const ${a} = ${o}(${i});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Ae("custom schema without a predicate function");return i}function vSe(e,t,r){let i=e._zod.run({value:r,issues:[]},{});if(i&&typeof i.then=="function")return Cr;let n=i;return n.issues.length===0?n.value:t()}function SSe(e,t,r,i){let n=r._zod.def;if(!n.catchValue[Kg])throw new Ae("catch with a callback (only a constant catch value compiles)",!1);let o=Y(t);e.write(`let ${o} = (() => {`),e.indented(u=>{let l=yr(u,t,n.innerType,i);u.write(`return ${l};`)}),e.write("})();");let s=ie(t,n.innerType),a=ec(t,n.catchValue),c=ie(t,vSe);return e.write(`if (${o} === INVALID) {`),e.indented(u=>{u.write(`${o} = ${c}(${s}, ${a}, ${i});`),u.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function wSe(e,t,r,i){let n=r._zod.def;if(n.transform){if(tc(n.transform))throw new Yn("z.compile: async transforms are not supported");let o=n.transform,a=ec(t,u=>{let l={value:u,issues:[],addIssue:qT},d=o(u,l);return d instanceof Promise?Cr:l.issues.length===0?d:Cr}),c=Y(t);return e.write(`const ${c} = ${a}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return i}function Fy(e){return e.checks&&(e.checks=[...e.checks]),e}function VT(e,t){return new e(Fy({type:"string",...L(t)}))}function KT(e,t){return new e(Fy({type:"string",coerce:!0,...L(t)}))}function Gy(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...L(t)})}function qy(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...L(t)})}function Vy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...L(t)})}function Ky(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(t)})}function By(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(t)})}function Hy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(t)})}function Gp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...L(t)})}function Wy(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...L(t)})}function Jy(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(t)})}function Zy(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...L(t)})}function Xy(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(t)})}function Yy(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...L(t)})}function Qy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...L(t)})}function ev(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(t)})}function tv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(t)})}function rv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(t)})}function BT(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...L(t)})}function nv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(t)})}function iv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(t)})}function ov(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...L(t)})}function sv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...L(t)})}function av(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...L(t)})}function HT(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...L(t)})}function WT(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...L(t)})}function cv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...L(t)})}var JT={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function qp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(t)})}function Vp(e,t){return new e({type:"string",format:"date",check:"string_format",...L(t)})}function Kp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...L(t)})}function Bp(e,t){return new e({type:"string",format:"duration",check:"string_format",...L(t)})}function ZT(e,t){return new e(Fy({type:"number",checks:[],...L(t)}))}function XT(e,t){return new e(Fy({type:"number",coerce:!0,checks:[],...L(t)}))}function YT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...L(t)})}function QT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...L(t)})}function eC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...L(t)})}function tC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...L(t)})}function rC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...L(t)})}function nC(e,t){return new e({type:"boolean",...L(t)})}function iC(e,t){return new e({type:"boolean",coerce:!0,...L(t)})}function oC(e,t){return new e({type:"bigint",...L(t)})}function sC(e,t){return new e({type:"bigint",coerce:!0,...L(t)})}function aC(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...L(t)})}function cC(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...L(t)})}function uC(e,t){return new e({type:"symbol",...L(t)})}function lC(e,t){return new e({type:"undefined",...L(t)})}function dC(e,t){return new e({type:"null",...L(t)})}function pC(e){return new e({type:"any"})}function fC(e){return new e({type:"unknown"})}function mC(e,t){return new e({type:"never",...L(t)})}function hC(e,t){return new e({type:"void",...L(t)})}function gC(e,t){return new e({type:"date",...L(t)})}function yC(e,t){return new e({type:"date",coerce:!0,...L(t)})}function vC(e,t){return new e({type:"nan",...L(t)})}function Oi(e,t){return new ay({check:"less_than",...L(t),value:e,inclusive:!1})}function rn(e,t){return new ay({check:"less_than",...L(t),value:e,inclusive:!0})}function Ni(e,t){return new cy({check:"greater_than",...L(t),value:e,inclusive:!1})}function nn(e,t){return new cy({check:"greater_than",...L(t),value:e,inclusive:!0})}function uv(e){return Ni(0,e)}function lv(e){return Oi(0,e)}function dv(e){return rn(0,e)}function pv(e){return nn(0,e)}function vs(e,t){return new rP({check:"multiple_of",...L(t),value:e})}function Ss(e,t){return new oP({check:"max_size",...L(t),maximum:e})}function Ui(e,t){return new sP({check:"min_size",...L(t),minimum:e})}function rc(e,t){return new aP({check:"size_equals",...L(t),size:e})}function nc(e,t){return new cP({check:"max_length",...L(t),maximum:e})}function Oo(e,t){return new uP({check:"min_length",...L(t),minimum:e})}function ic(e,t){return new lP({check:"length_equals",...L(t),length:e})}function ku(e,t){return new dP({check:"string_format",format:"regex",...L(t),pattern:e})}function Du(e){return new pP({check:"string_format",format:"lowercase",...L(e)})}function Ou(e){return new fP({check:"string_format",format:"uppercase",...L(e)})}function Nu(e,t){return new mP({check:"string_format",format:"includes",...L(t),includes:e})}function Uu(e,t){return new hP({check:"string_format",format:"starts_with",...L(t),prefix:e})}function Lu(e,t){return new gP({check:"string_format",format:"ends_with",...L(t),suffix:e})}function fv(e,t,r){return new yP({check:"property",property:e,schema:t,...L(r)})}function Mu(e,t){return new vP({check:"properties",shape:e,...L(t)})}function zu(e,t){return new SP({check:"mime_type",mime:e,...L(t)})}function Qn(e){return new wP({check:"overwrite",tx:e})}function ju(e){return Qn(t=>t.normalize(e))}function Fu(){return Qn(e=>e.trim())}function Gu(){return Qn(e=>e.toLowerCase())}function qu(){return Qn(e=>e.toUpperCase())}function Vu(){return Qn(e=>i$(e))}function SC(e,t,r){return new e({type:"array",element:t,...L(r)})}function bSe(e,t,r){return new e({type:"union",options:t,...L(r)})}function _Se(e,t,r){return new e({type:"union",options:t,inclusive:!1,...L(r)})}function xSe(e,t,r,i){return new e({type:"union",options:r,discriminator:t,...L(i)})}function ESe(e,t,r){return new e({type:"intersection",left:t,right:r})}function ASe(e,t,r,i){let n=r instanceof ue,o=n?i:r,s=n?r:null;return new e({type:"tuple",items:t,rest:s,...L(o)})}function RSe(e,t,r,i){return new e({type:"record",keyType:t,valueType:r,...L(i)})}function ISe(e,t,r,i){return new e({type:"map",keyType:t,valueType:r,...L(i)})}function $Se(e,t,r){return new e({type:"set",valueType:t,...L(r)})}function PSe(e,t,r){let i=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:i,...L(r)})}function TSe(e,t,r){return new e({type:"enum",entries:t,...L(r)})}function CSe(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...L(r)})}function wC(e,t){return new e({type:"file",...L(t)})}function kSe(e,t){return new e({type:"transform",transform:t})}function DSe(e,t){return new e({type:"optional",innerType:t})}function OSe(e,t){return new e({type:"nullable",innerType:t})}function NSe(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():fp(r)}})}function USe(e,t,r){return new e({type:"nonoptional",innerType:t,...L(r)})}function LSe(e,t){return new e({type:"success",innerType:t})}function MSe(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:l$(r)})}function zSe(e,t,r){return new e({type:"pipe",in:t,out:r})}function jSe(e,t){return new e({type:"readonly",innerType:t})}function FSe(e,t,r){return new e({type:"template_literal",parts:t,...L(r)})}function GSe(e,t){return new e({type:"lazy",getter:t})}function qSe(e,t){return new e({type:"promise",innerType:t})}function bC(e,t,r){let i=L(r);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function _C(e,t,r){return new e({type:"custom",check:"custom",fn:t,...L(r)})}function xC(e,t){let r=L2(i=>(i.addIssue=n=>{if(typeof n=="string")i.issues.push(_u(n,i.value,r._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=i.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),i.issues.push(_u(o))}},e(i.value,i)),t);return r}function L2(e,t){let r=new rt({check:"custom",...L(t)});return r._zod.check=e,r}function EC(e){let t=new rt({check:"describe"});return t._zod.onattach=[r=>{let i=tr.get(r)??{};tr.add(r,{...i,description:e})}],t._zod.check=()=>{},t}function AC(e){let t=new rt({check:"meta"});return t._zod.onattach=[r=>{let i=tr.get(r)??{};tr.add(r,{...i,...e})}],t._zod.check=()=>{},t}function RC(e,t){let r=L(t),i=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(i=i.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));let o=new Set(i),s=new Set(n),a=e.Codec??Np,c=e.Boolean??Dp,u=e.String??Xa,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:l,out:d,transform:((p,g)=>{let v=p;return r.case!=="sensitive"&&(v=v.toLowerCase()),o.has(v)?!0:s.has(v)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((p,g)=>p===!0?i[0]||"true":n[0]||"false"),error:r.error});return m._zod.bag.truthy=i,m._zod.bag.falsy=n,m._zod.bag.case=r.case??"insensitive",m}function oc(e,t,r,i={}){let n=L(i),o={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(o.pattern=r),new e(o)}function Hp(e,...t){for(let r of t)for(let i of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,i)&&er(e,i,r[i]);return e}function ws(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??tr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ut(e,t,r,i,n){let o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:i.path,message:n}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(n);return Object.assign(r,o),!0}function Ze(e,t,r={path:[],schemaPath:[]}){var i;let n=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let m=s.schema,p=t.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(e,t,m,l)}let d=e._zod.parent;d&&(s.ref||(s.ref=d),Ze(d,t,l),t.seen.get(d).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Hp(s.schema,c),t.io==="input"&&kr(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function M2(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function bs(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let i=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=i.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.`);i.set(a,s[0])}}let n=s=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,m=e.external.uri??(g=>g);if(d)return{ref:m(d)};let p=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=p,{defId:p,ref:`${m("__shared")}#/${a}/${M2(p)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+M2(l)}},o=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(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
120
120
 
121
121
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}a.count>1&&e.reused==="ref"&&o(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function F2(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let i of t){if(!i||typeof i!="object")return;F2(i);let n=Object.keys(i);if(n.length!==1||n[0]!=="type")return;let o=i.type;for(let s of Array.isArray(o)?o:[o]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var G2=new Set(["type","properties","required","additionalProperties"]),z2=["oneOf","anyOf"];function j2(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function IC(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let s in o)if(!G2.has(s))return null;t.push(o)}let r={},i=new Set;for(let o of t){for(let s in o.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??j2(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:IC(a)??{allOf:a};er(r,s,c)}for(let s of o.required??[])i.add(s)}let n={type:"object",properties:r};if(i.size&&(n.required=[...i]),t.every(o=>o.additionalProperties===!1))n.additionalProperties=!1;else{let o=[];for(let s of t){let a=j2(s);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?n.additionalProperties=o[0]:o.length>1&&(n.additionalProperties={allOf:o})}return n}function VSe(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of G2)if(n in e)return;let r=t.filter(n=>z2.some(o=>Array.isArray(n[o]))),i=null;if(!r.length)i=IC(t);else{let n=r[0],o=z2.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=t.filter(c=>c!==n),a=n[o].map(c=>IC([...s,c]));if(a.some(c=>!c))return;i={[o]:a}}i&&(delete e.allOf,Hp(e,i))}function _s(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){i(d);let p=e.seen.get(d),g=p.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Hp(u,g),Hp(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(g.$ref&&p.def)for(let S in u)S==="$ref"||S==="allOf"||S in p.def&&JSON.stringify(u[S])===JSON.stringify(p.def[S])&&delete u[S]}let m=a._zod.parent;if(m&&m!==d){i(m);let p=e.seen.get(m);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let g in u)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(u[g])===JSON.stringify(p.def[g])&&delete u[g]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())i(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())F2(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.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 e.intersections)for(let u of a.get(c)??[])VSe(u)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Hp(n,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&n.id===o&&delete n.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,er(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ku(t,"input",e.processors),output:Ku(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function kr(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return kr(i.element,r);if(i.type==="set")return kr(i.valueType,r);if(i.type==="lazy")return kr(i.getter(),r);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault"||i.type==="catch")return kr(i.innerType,r);if(i.type==="intersection")return kr(i.left,r)||kr(i.right,r);if(i.type==="record"||i.type==="map")return kr(i.keyType,r)||kr(i.valueType,r);if(i.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:kr(i.in,r)||kr(i.out,r);if(i.type==="object"){for(let n in i.shape)if(kr(i.shape[n],r))return!0;return!1}if(i.type==="union"){for(let n of i.options)if(kr(n,r))return!0;return!1}if(i.type==="tuple"){for(let n of i.items)if(kr(n,r))return!0;return!!(i.rest&&kr(i.rest,r))}return!1}var $C=(e,t={})=>r=>{let i=ws({...r,processors:t});return Ze(e,i),bs(i,e),_s(i,e)},Ku=(e,t,r={})=>i=>{let{libraryOptions:n,target:o}=i??{},s=ws({...n??{},target:o,io:t,processors:r});return Ze(e,s),bs(s,e),_s(s,e)};var Bu=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Hu=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},q2=(e,t)=>{Bu(e,"minimum",t),Hu(e,"maximum",t)},H2=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},W2=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},J2=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Z2=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},V2=(e,t)=>Bu(e,"minimum",t.minimum),K2=(e,t)=>Hu(e,"maximum",t.maximum),B2=e=>(t,r)=>{Z2(t,r.format);let[i,n]=e[r.format];Bu(t,"minimum",i),Hu(t,"maximum",n)},KSe={greater_than:(e,t)=>Bu(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Hu(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>H2(e,t.value),number_format:B2(hp),bigint_format:B2(gp),min_length:V2,max_length:K2,length_equals:(e,t)=>q2(e,t.length),min_size:V2,max_size:K2,size_equals:(e,t)=>q2(e,t.size),string_format:(e,t)=>{Z2(e,t.format),t.pattern&&W2(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>J2(e,t.mime)};function Lt(e){let t={},r=e._zod.def,i=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of i)KSe[o._zod.def.check]?.(t,o._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Bu(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Bu(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Hu(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Hu(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&H2(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&J2(t,n.mime);for(let o of n.patterns??[])W2(t,o);return t}var BSe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},HSe=new Map([[vy,U$],[kp,L$]]),X2=e=>HSe.get(e)??e,CC=(e,t,r,i)=>{let n=r;n.type="string";let{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Lt(e);if(typeof o=="number"&&(n.minLength=o),typeof s=="number"&&(n.maxLength=s),a&&(n.format=BSe[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(X2);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},kC=(e,t,r,i)=>{let n=r,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Lt(e);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof o=="number"&&(n.minimum=o),m?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let g=new Set;for(let b of a)Number.isFinite(b)&&b!==0?g.add(Math.abs(b)):Ut(e,t,n,i,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[v,...S]=g;v!==void 0&&(n.multipleOf=v),S.length&&(n.allOf=[...n.allOf??[],...S.map(b=>({multipleOf:b}))])}},DC=(e,t,r,i)=>{r.type="boolean"},OC=(e,t,r,i)=>{Ut(e,t,r,i,"BigInt cannot be represented in JSON Schema")},NC=(e,t,r,i)=>{Ut(e,t,r,i,"Symbols cannot be represented in JSON Schema")},UC=(e,t,r,i)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},LC=(e,t,r,i)=>{Ut(e,t,r,i,"Undefined cannot be represented in JSON Schema")},MC=(e,t,r,i)=>{Ut(e,t,r,i,"Void cannot be represented in JSON Schema")},zC=(e,t,r,i)=>{r.not={}},jC=(e,t,r,i)=>{},FC=(e,t,r,i)=>{},GC=(e,t,r,i)=>{Ut(e,t,r,i,"Date cannot be represented in JSON Schema")},qC=(e,t,r,i)=>{let n=e._zod.def,o=vu(n.entries);if(o.length===0){r.not={};return}o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),r.enum=o},VC=(e,t,r,i)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let o=[];for(let s of n.values)if(s===void 0){if(Ut(e,t,r,i,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Ut(e,t,r,i,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){let s=o[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),o.every(s=>typeof s=="boolean")&&(r.type="boolean"),o.every(s=>s===null)&&(r.type="null"),r.enum=o},KC=(e,t,r,i)=>{Ut(e,t,r,i,"NaN cannot be represented in JSON Schema")},BC=(e,t,r,i)=>{let n=r,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=o.source},HC=(e,t,r,i)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:o,maximum:s,mime:a}=Lt(e);o!==void 0&&(n.minLength=o),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})))},WC=(e,t,r,i)=>{r.type="boolean"},JC=(e,t,r,i)=>{Ut(e,t,r,i,"Custom types cannot be represented in JSON Schema")},ZC=(e,t,r,i)=>{Ut(e,t,r,i,"Function types cannot be represented in JSON Schema")},XC=(e,t,r,i)=>{Ut(e,t,r,i,"Transforms cannot be represented in JSON Schema")},YC=(e,t,r,i)=>{Ut(e,t,r,i,"Map cannot be represented in JSON Schema")},QC=(e,t,r,i)=>{Ut(e,t,r,i,"Set cannot be represented in JSON Schema")},ek=(e,t,r,i)=>{let n=r,o=e._zod.def,{minimum:s,maximum:a}=Lt(e);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Ze(o.element,t,{...i,path:[...i.path,"items"]})};function Wp(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Wp(t.out):t.type==="catch"?Wp(t.innerType):e._zod.optin}var tk=(e,t,r,i)=>{let n=r,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Ut(e,t,n,i,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)er(n.properties,u,Ze(s[u],t,{...i,path:[...i.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=o.shape[u];(t.io==="input"?Wp(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),o.catchall?._zod.def.type==="never"?n.additionalProperties=!1:o.catchall?o.catchall&&(n.additionalProperties=Ze(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},hv=(e,t,r,i)=>{let n=e._zod.def,o=n.inclusive===!1,s=n.options.map((a,c)=>Ze(a,t,{...i,path:[...i.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=s:r.anyOf=s},rk=(e,t,r,i)=>{let n=e._zod.def,o=Ze(n.left,t,{...i,path:[...i.path,"allOf",0]}),s=Ze(n.right,t,{...i,path:[...i.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)},nk=(e,t,r,i)=>{let n=r,o=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((v,S)=>Ze(v,t,{...i,path:[...i.path,s,S]})),u=o.rest?Ze(o.rest,t,{...i,path:[...i.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,l=o.items.length;for(;l>0;){let v=o.items[l-1];if(!(t.io==="input"?Wp(v)!==void 0:v._zod.optout==="optional"))break;l--}let d=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(n.prefixItems=c,m?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),m&&(n.maxItems=d)):t.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),m&&(n.maxItems=d)):(n.items=c,m?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),m&&(n.maxItems=d));let{minimum:p,maximum:g}=Lt(e);typeof p=="number"&&(n.minItems=p),typeof g=="number"&&(n.maxItems=g)};function PC(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let v=PC(e,g,r);return v===g?t:v}for(let g of["anyOf","oneOf"]){let v=t[g];if(!Array.isArray(v))continue;let S=v.map(b=>PC(e,b,r));S.some((b,_)=>b!==v[_])&&(t={...t,[g]:S})}let i=Array.isArray(t.type)?t.type:[t.type],n=!i.includes("string")&&i.some(g=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!o?.some(g=>typeof g=="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:m,...p}=t;return p.enum?p.enum=p.enum.map(g=>typeof g=="number"?String(g):g):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",o||(p.pattern=(i.includes("number")?Do:Ap).source)),p}var TC=new WeakMap;function WSe(e){let t=new Map;for(let i of e.seen.values())i.def&&!t.has(i.schema)&&t.set(i.schema,i);let r=new Map;for(let i of TC.get(e)??[]){let n=e.seen.get(i),o=(n?.def??n?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let s=PC(t,o,new Set);s!==o&&r.set(o,s)}if(r.size)for(let i of e.seen.values())for(let n of[i.schema,i.def]){let o=n&&r.get(n.propertyNames);o&&(n.propertyNames=o)}}var ik=(e,t,r,i)=>{let n=r,o=e._zod.def;n.type="object";let s=o.keyType,a=Lt(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let l=Ze(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)er(n.patternProperties,X2(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=Ze(o.keyType,t,{...i,path:[...i.path,"propertyNames"]});let l=TC.get(t);l||(l=[],TC.set(t,l),t.deferred.push(()=>WSe(t))),l.push(e)}n.additionalProperties=Ze(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&Wp(o.valueType)!==void 0;if(c&&!o.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},ok=(e,t,r,i)=>{let n=e._zod.def,o=Ze(n.innerType,t,i),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},sk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType},ak=Symbol();function Y2(e,t,r,i,n){let o=!1,s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(Ut(t,r,i,n,"BigInt defaults cannot be represented in JSON Schema"),ak):JSON.parse(s)}var ck=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType;let s=Y2(n.defaultValue,e,t,r,i);s!==ak&&(r.default=s)},uk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);if(o.ref=n.innerType,t.io!=="input")return;let s=Y2(n.defaultValue,e,t,r,i);s!==ak&&(r._prefault=s)},lk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Ut(e,t,r,i,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},dk=(e,t,r,i)=>{let n=e._zod.def,o=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?n.out:n.in:n.out;Ze(s,t,i);let a=t.seen.get(e);a.ref=s},pk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType,r.readOnly=!0},fk=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType},gv=(e,t,r,i)=>{let n=e._zod.def;Ze(n.innerType,t,i);let o=t.seen.get(e);o.ref=n.innerType},mk=(e,t,r,i)=>{let n=e._zod.innerType;Ze(n,t,i);let o=t.seen.get(e);o.ref=n},mv={string:CC,number:kC,boolean:DC,bigint:OC,symbol:NC,null:UC,undefined:LC,void:MC,never:zC,any:jC,unknown:FC,date:GC,enum:qC,literal:VC,nan:KC,template_literal:BC,file:HC,success:WC,custom:JC,function:ZC,transform:XC,map:YC,set:QC,array:ek,object:tk,union:hv,intersection:rk,tuple:nk,record:ik,nullable:ok,nonoptional:sk,default:ck,prefault:uk,catch:lk,pipe:dk,readonly:pk,promise:fk,optional:gv,lazy:mk};function yv(e,t){if("_idmap"in e){let i=e,n=ws({...t,processors:mv}),o={};for(let c of i._idmap.entries()){let[u,l]=c;Ze(l,n)}let s={},a={registry:i,uri:t?.uri,defs:o};n.external=a;for(let c of i._idmap.entries()){let[u,l]=c;bs(n,l),er(s,u,_s(n,l))}if(Object.keys(o).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:o}}return{schemas:s}}let r=ws({...t,processors:mv});return Ze(e,r),bs(r,e),_s(r,e)}var vv=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(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ws({processors:mv,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return Ze(t,this.ctx,r)}emit(t,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,bs(this.ctx,t);let i=_s(this.ctx,t),{"~standard":n,...o}=i;return o}};var Q2={};var tl={};it(tl,{ZodAny:()=>Uk,ZodArray:()=>jk,ZodBase64:()=>Lv,ZodBase64URL:()=>Mv,ZodBigInt:()=>Qu,ZodBigIntFormat:()=>Fv,ZodBoolean:()=>Yu,ZodCIDRv4:()=>Nv,ZodCIDRv6:()=>Uv,ZodCUID:()=>$v,ZodCUID2:()=>Pv,ZodCatch:()=>aD,ZodCodec:()=>of,ZodCreditCard:()=>$k,ZodCustom:()=>sf,ZodCustomStringFormat:()=>uc,ZodDate:()=>Yp,ZodDefault:()=>tD,ZodDiscriminatedUnion:()=>Gk,ZodE164:()=>zv,ZodEmail:()=>Ev,ZodEmoji:()=>Rv,ZodEnum:()=>Ju,ZodExactOptional:()=>Kv,ZodFile:()=>Xk,ZodFunction:()=>yD,ZodGUID:()=>Av,ZodIBAN:()=>Pk,ZodIPv4:()=>Dv,ZodIPv6:()=>Ov,ZodISODate:()=>Es,ZodISODateTime:()=>xs,ZodISODuration:()=>Rs,ZodISOTime:()=>As,ZodInstanceOf:()=>wD,ZodIntersection:()=>qk,ZodJWT:()=>jv,ZodKSUID:()=>kv,ZodLazy:()=>mD,ZodLiteral:()=>Zk,ZodMAC:()=>Ik,ZodMap:()=>Wk,ZodNaN:()=>uD,ZodNanoID:()=>Iv,ZodNever:()=>Mk,ZodNonOptional:()=>Bv,ZodNull:()=>Ok,ZodNullable:()=>eD,ZodNumber:()=>Xu,ZodNumberFormat:()=>lc,ZodObject:()=>ef,ZodOptional:()=>rf,ZodPipe:()=>nf,ZodPrefault:()=>nD,ZodPreprocess:()=>lD,ZodPromise:()=>gD,ZodReadonly:()=>dD,ZodRecord:()=>Wu,ZodSet:()=>Jk,ZodString:()=>Zu,ZodStringFormat:()=>Xe,ZodSuccess:()=>sD,ZodSymbol:()=>kk,ZodTemplateLiteral:()=>fD,ZodTransform:()=>Yk,ZodTuple:()=>Kk,ZodType:()=>he,ZodULID:()=>Tv,ZodURL:()=>Xp,ZodUUID:()=>Li,ZodUndefined:()=>Dk,ZodUnion:()=>tf,ZodUnknown:()=>Lk,ZodVoid:()=>zk,ZodXID:()=>Cv,ZodXor:()=>Fk,_ZodString:()=>xv,_default:()=>rD,_function:()=>dG,any:()=>G6,array:()=>Qp,base64:()=>_6,base64url:()=>x6,bigint:()=>L6,boolean:()=>Ck,catch:()=>cD,check:()=>pG,cidrv4:()=>w6,cidrv6:()=>b6,codec:()=>aG,creditCard:()=>A6,cuid:()=>p6,cuid2:()=>f6,currencyCode:()=>C6,custom:()=>fG,date:()=>V6,describe:()=>mG,discriminatedUnion:()=>Z6,e164:()=>E6,email:()=>r6,emoji:()=>l6,enum:()=>qv,exactOptional:()=>Qk,file:()=>nG,float32:()=>D6,float64:()=>O6,function:()=>dG,guid:()=>n6,hash:()=>k6,hex:()=>T6,hostname:()=>P6,httpUrl:()=>u6,iban:()=>R6,instanceof:()=>gG,int:()=>bv,int32:()=>N6,int64:()=>M6,intersection:()=>Vk,invertCodec:()=>cG,ipv4:()=>y6,ipv6:()=>S6,json:()=>vG,jwt:()=>I6,keyof:()=>K6,ksuid:()=>g6,lazy:()=>hD,literal:()=>rG,looseObject:()=>W6,looseRecord:()=>Y6,mac:()=>v6,map:()=>Q6,meta:()=>hG,nan:()=>sG,nanoid:()=>d6,nativeEnum:()=>tG,never:()=>Gv,nonoptional:()=>oD,null:()=>Nk,nullable:()=>Zp,nullish:()=>iG,number:()=>Tk,object:()=>B6,optional:()=>ac,partialRecord:()=>X6,pipe:()=>_v,prefault:()=>iD,preprocess:()=>SG,promise:()=>lG,readonly:()=>pD,record:()=>Hk,refine:()=>vD,set:()=>eG,strictObject:()=>H6,string:()=>Jp,stringFormat:()=>$6,stringbool:()=>yG,success:()=>oG,superRefine:()=>SD,symbol:()=>j6,templateLiteral:()=>uG,transform:()=>Vv,tuple:()=>Bk,uint32:()=>U6,uint64:()=>z6,ulid:()=>m6,undefined:()=>F6,union:()=>el,unknown:()=>sc,url:()=>c6,uuid:()=>i6,uuidv4:()=>o6,uuidv6:()=>s6,uuidv7:()=>a6,void:()=>q6,xid:()=>h6,xor:()=>J6});var Sv={};it(Sv,{endsWith:()=>Lu,gt:()=>Ni,gte:()=>nn,includes:()=>Nu,length:()=>ic,lowercase:()=>Du,lt:()=>Oi,lte:()=>rn,maxLength:()=>nc,maxSize:()=>Ss,mime:()=>zu,minLength:()=>Oo,minSize:()=>Ui,multipleOf:()=>vs,negative:()=>lv,nonnegative:()=>pv,nonpositive:()=>dv,normalize:()=>ju,overwrite:()=>Qn,positive:()=>uv,properties:()=>Mu,property:()=>fv,regex:()=>ku,size:()=>rc,slugify:()=>Vu,startsWith:()=>Uu,toLowerCase:()=>Gu,toUpperCase:()=>qu,trim:()=>Fu,uppercase:()=>Ou});var e6=new WeakSet([Object.prototype,Error.prototype]);function wv(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let i=r(this);return Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0})}})}var t6=(e,t)=>{g$.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);e6.has(r)||(e6.add(r),wv(r,"format",i=>n=>bp(i,n)),wv(r,"flatten",i=>n=>wp(i,n)),wv(r,"addIssue",i=>n=>{i.issues.push(n),i.message=JSON.stringify(i.issues,Su,2)}),wv(r,"addIssues",i=>n=>{i.issues.push(...n),i.message=JSON.stringify(i.issues,Su,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZSe=E("ZodError",t6),Jr=E("ZodError",t6,void 0,{Parent:Error});var hk=xu(Jr),gk=Eu(Jr),yk=Au(Jr),vk=Ru(Jr),Sk=Jg(Jr),wk=Zg(Jr),bk=Xg(Jr),_k=Yg(Jr),xk=Qg(Jr),Ek=ey(Jr),Ak=ty(Jr),Rk=ry(Jr);function YSe(){qt.localeError||bt(Oy())}function cc(){qt.memoizer||bt({memoizer:zp()})}var he=E("ZodType",(e,t)=>(YSe(),ue.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(D.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return We(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(vD(e,t))},superRefine(e,t){return this.check(SD(e,t))},overwrite(e){return this.check(Qn(e))},optional(){return ac(this)},exactOptional(){return Qk(this)},nullable(){return Zp(this)},nullish(){return ac(Zp(this))},nonoptional(e){return oD(this,e)},array(){return Qp(this)},or(e){return el([this,e])},and(e){return Vk(this,e)},transform(e){return _v(this,Vv(e))},default(e){return rD(this,e)},prefault(e){return iD(this,e)},catch(e){return cD(this,e)},pipe(e){return _v(this,e)},readonly(){return pD(this)},describe(e){let t=this.clone();return tr.add(t,{description:e}),t},meta(...e){if(e.length===0)return tr.get(this);let t=this.clone();return tr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return D.hide(this,"~standard",{...fy(this),jsonSchema:{input:Ku(this,"input"),output:Ku(this,"output")}})},set"~standard"(e){D.own(this,"~standard",e)},parse:function e(t,r){return hk(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await gk(this,t,r,{callee:e})},safeParse(e,t){return yk(this,e,t)},async safeParseAsync(e,t){return vk(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){D.own(this,"spa",e)},validate(e,t){return _p(this,e,t)},validateAsync(e,t){return xp(this,e,t)},encode:function e(t,r){return Sk(this,t,r,{callee:e})},decode:function e(t,r){return wk(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await bk(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await _k(this,t,r,{callee:e})},safeEncode(e,t){return xk(this,e,t)},safeDecode(e,t){return Ek(this,e,t)},async safeEncodeAsync(e,t){return Ak(this,e,t)},async safeDecodeAsync(e,t){return Rk(this,e,t)},toJSONSchema(e){return $C(this,{})(e)},get description(){return tr.get(this)?.description},get _def(){return this._zod.def}}),xv=E("_ZodString",(e,t)=>{Xa.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>CC(e,r,i,n)},D.derived({format:e=>Lt(e).format??null,minLength:e=>Lt(e).minimum??null,maxLength:e=>Lt(e).maximum??null},{regex(...e){return this.check(ku(...e))},includes(...e){return this.check(Nu(...e))},startsWith(...e){return this.check(Uu(...e))},endsWith(...e){return this.check(Lu(...e))},min(...e){return this.check(Oo(...e))},max(...e){return this.check(nc(...e))},length(...e){return this.check(ic(...e))},nonempty(...e){return this.check(Oo(1,...e))},lowercase(e){return this.check(Du(e))},uppercase(e){return this.check(Ou(e))},trim(){return this.check(Fu())},normalize(...e){return this.check(ju(...e))},toLowerCase(){return this.check(Gu())},toUpperCase(){return this.check(qu())},slugify(){return this.check(Vu())}})),Zu=E("ZodString",(e,t)=>{Xa.init(e,t),xv.init(e,t)},{email(e){return this.check(Gy(Ev,e))},url(e){return this.check(Gp(Xp,e))},jwt(e){return this.check(cv(jv,e))},emoji(e){return this.check(Wy(Rv,e))},guid(e){return this.check(qy(Av,e))},uuid(e){return this.check(Vy(Li,e))},uuidv4(e){return this.check(Ky(Li,e))},uuidv6(e){return this.check(By(Li,e))},uuidv7(e){return this.check(Hy(Li,e))},nanoid(e){return this.check(Jy(Iv,e))},cuid(e){return this.check(Zy($v,e))},cuid2(e){return this.check(Xy(Pv,e))},ulid(e){return this.check(Yy(Tv,e))},base64(e){return this.check(ov(Lv,e))},base64url(e){return this.check(sv(Mv,e))},xid(e){return this.check(Qy(Cv,e))},ksuid(e){return this.check(ev(kv,e))},ipv4(e){return this.check(tv(Dv,e))},ipv6(e){return this.check(rv(Ov,e))},cidrv4(e){return this.check(nv(Nv,e))},cidrv6(e){return this.check(iv(Uv,e))},e164(e){return this.check(av(zv,e))},datetime(e){return this.check(qp(xs,e))},date(e){return this.check(Vp(Es,e))},time(e){return this.check(Kp(As,e))},duration(e){return this.check(Bp(Rs,e))}});function Jp(e){return VT(Zu,e)}var Xe=E("ZodStringFormat",(e,t)=>{Je.init(e,t),xv.init(e,t)}),xs=E("ZodISODateTime",(e,t)=>{UP.init(e,t),Xe.init(e,t)}),Es=E("ZodISODate",(e,t)=>{LP.init(e,t),Xe.init(e,t)}),As=E("ZodISOTime",(e,t)=>{MP.init(e,t),Xe.init(e,t)}),Rs=E("ZodISODuration",(e,t)=>{zP.init(e,t),Xe.init(e,t)}),Ev=E("ZodEmail",(e,t)=>{AP.init(e,t),Xe.init(e,t)});function r6(e){return Gy(Ev,e)}var Av=E("ZodGUID",(e,t)=>{xP.init(e,t),Xe.init(e,t)});function n6(e){return qy(Av,e)}var Li=E("ZodUUID",(e,t)=>{EP.init(e,t),Xe.init(e,t)});function i6(e){return Vy(Li,e)}function o6(e){return Ky(Li,e)}function s6(e){return By(Li,e)}function a6(e){return Hy(Li,e)}var Xp=E("ZodURL",(e,t)=>{$P.init(e,t),Xe.init(e,t)});function c6(e){return Gp(Xp,e)}function u6(e){return Gp(Xp,{protocol:Ep,hostname:z$,...D.normalizeParams(e)})}var Rv=E("ZodEmoji",(e,t)=>{PP.init(e,t),Xe.init(e,t)});function l6(e){return Wy(Rv,e)}var Iv=E("ZodNanoID",(e,t)=>{TP.init(e,t),Xe.init(e,t)});function d6(e){return Jy(Iv,e)}var $v=E("ZodCUID",(e,t)=>{CP.init(e,t),Xe.init(e,t)});function p6(e){return Zy($v,e)}var Pv=E("ZodCUID2",(e,t)=>{kP.init(e,t),Xe.init(e,t)});function f6(e){return Xy(Pv,e)}var Tv=E("ZodULID",(e,t)=>{DP.init(e,t),Xe.init(e,t)});function m6(e){return Yy(Tv,e)}var Cv=E("ZodXID",(e,t)=>{OP.init(e,t),Xe.init(e,t)});function h6(e){return Qy(Cv,e)}var kv=E("ZodKSUID",(e,t)=>{NP.init(e,t),Xe.init(e,t)});function g6(e){return ev(kv,e)}var Dv=E("ZodIPv4",(e,t)=>{jP.init(e,t),Xe.init(e,t)});function y6(e){return tv(Dv,e)}var Ik=E("ZodMAC",(e,t)=>{GP.init(e,t),Xe.init(e,t)});function v6(e){return BT(Ik,e)}var Ov=E("ZodIPv6",(e,t)=>{FP.init(e,t),Xe.init(e,t)});function S6(e){return rv(Ov,e)}var Nv=E("ZodCIDRv4",(e,t)=>{qP.init(e,t),Xe.init(e,t)});function w6(e){return nv(Nv,e)}var Uv=E("ZodCIDRv6",(e,t)=>{VP.init(e,t),Xe.init(e,t)});function b6(e){return iv(Uv,e)}var Lv=E("ZodBase64",(e,t)=>{KP.init(e,t),Xe.init(e,t)});function _6(e){return ov(Lv,e)}var Mv=E("ZodBase64URL",(e,t)=>{BP.init(e,t),Xe.init(e,t)});function x6(e){return sv(Mv,e)}var zv=E("ZodE164",(e,t)=>{HP.init(e,t),Xe.init(e,t)});function E6(e){return av(zv,e)}var $k=E("ZodCreditCard",(e,t)=>{WP.init(e,t),Xe.init(e,t)});function A6(e){return HT($k,e)}var Pk=E("ZodIBAN",(e,t)=>{JP.init(e,t),Xe.init(e,t)});function R6(e){return WT(Pk,e)}var jv=E("ZodJWT",(e,t)=>{ZP.init(e,t),Xe.init(e,t)});function I6(e){return cv(jv,e)}var uc=E("ZodCustomStringFormat",(e,t)=>{XP.init(e,t),Xe.init(e,t)});function $6(e,t,r={}){return oc(uc,e,t,r)}function P6(e){return oc(uc,"hostname",M$,e)}function T6(e){return oc(uc,"hex",Q$,e)}function C6(e){return oc(uc,"currency_code",F$,e)}function k6(e,t){let r=t?.enc??"hex",i=`${e}_${r}`,n=xn[i];if(!n)throw new Error(`Unrecognized hash format: ${i}`);return oc(uc,i,n,t)}var Xu=E("ZodNumber",(e,t)=>{xy.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>kC(e,r,i,n),e.isFinite=!0},D.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=Lt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=Lt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=Lt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>Lt(e).format??null},{gt(e,t){return this.check(Ni(e,t))},gte(e,t){return this.check(nn(e,t))},min(e,t){return this.check(nn(e,t))},lt(e,t){return this.check(Oi(e,t))},lte(e,t){return this.check(rn(e,t))},max(e,t){return this.check(rn(e,t))},int(e){return this.check(bv(e))},safe(e){return this.check(bv(e))},positive(e){return this.check(Ni(0,e))},nonnegative(e){return this.check(nn(0,e))},negative(e){return this.check(Oi(0,e))},nonpositive(e){return this.check(rn(0,e))},multipleOf(e,t){return this.check(vs(e,t))},step(e,t){return this.check(vs(e,t))},finite(){return this}}));function Tk(e){return ZT(Xu,e)}var lc=E("ZodNumberFormat",(e,t)=>{YP.init(e,t),Xu.init(e,t)});function bv(e){return YT(lc,e)}function D6(e){return QT(lc,e)}function O6(e){return eC(lc,e)}function N6(e){return tC(lc,e)}function U6(e){return rC(lc,e)}var Yu=E("ZodBoolean",(e,t)=>{Dp.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>DC(e,r,i,n)});function Ck(e){return nC(Yu,e)}var Qu=E("ZodBigInt",(e,t)=>{Ey.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>OC(e,r,i,n)},D.derived({minValue:e=>Lt(e).minimum??null,maxValue:e=>Lt(e).maximum??null,format:e=>Lt(e).format??null},{gte(e,t){return this.check(nn(e,t))},min(e,t){return this.check(nn(e,t))},gt(e,t){return this.check(Ni(e,t))},lt(e,t){return this.check(Oi(e,t))},lte(e,t){return this.check(rn(e,t))},max(e,t){return this.check(rn(e,t))},positive(e){return this.check(Ni(BigInt(0),e))},negative(e){return this.check(Oi(BigInt(0),e))},nonpositive(e){return this.check(rn(BigInt(0),e))},nonnegative(e){return this.check(nn(BigInt(0),e))},multipleOf(e,t){return this.check(vs(e,t))}}));function L6(e){return oC(Qu,e)}var Fv=E("ZodBigIntFormat",(e,t)=>{QP.init(e,t),Qu.init(e,t)});function M6(e){return aC(Fv,e)}function z6(e){return cC(Fv,e)}var kk=E("ZodSymbol",(e,t)=>{eT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>NC(e,r,i,n)});function j6(e){return uC(kk,e)}var Dk=E("ZodUndefined",(e,t)=>{tT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>LC(e,r,i,n)});function F6(e){return lC(Dk,e)}var Ok=E("ZodNull",(e,t)=>{rT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>UC(e,r,i,n)});function Nk(e){return dC(Ok,e)}var Uk=E("ZodAny",(e,t)=>{nT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>jC(e,r,i,n)});function G6(){return pC(Uk)}var Lk=E("ZodUnknown",(e,t)=>{iT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>FC(e,r,i,n)});function sc(){return fC(Lk)}var Mk=E("ZodNever",(e,t)=>{oT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>zC(e,r,i,n)});function Gv(e){return mC(Mk,e)}var zk=E("ZodVoid",(e,t)=>{sT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>MC(e,r,i,n)});function q6(e){return hC(zk,e)}var Yp=E("ZodDate",(e,t)=>{aT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>GC(e,r,i,n),e.min=(r,i)=>e.check(nn(r,i)),e.max=(r,i)=>e.check(rn(r,i))},D.derived({minDate:e=>{let{minimum:t}=Lt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=Lt(e);return t?new Date(t):null}},{}));function V6(e){return gC(Yp,e)}var jk=E("ZodArray",(e,t)=>{cc(),cT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ek(e,r,i,n),e.element=t.element},{min(e,t){return this.check(Oo(e,t))},nonempty(e){return this.check(Oo(1,e))},max(e,t){return this.check(nc(e,t))},length(e,t){return this.check(ic(e,t))},unwrap(){return this.element}});function Qp(e,t){return SC(jk,e,t)}function K6(e){let t=e._zod.def.shape;return qv(Object.keys(t))}var ef=E("ZodObject",(e,t)=>{cc(),uT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>tk(e,r,i,n),D.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return qv(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(D.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:sc()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:sc()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Gv()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return D.extend(this,e)},safeExtend(e){return D.safeExtend(this,e)},merge(e){return D.merge(this,e)},pick(e){return D.pick(this,e)},omit(e){return D.omit(this,e)},partial(...e){return D.partial(rf,this,e[0])},exactPartial(...e){return D.partial(Kv,this,e[0],"exactPartial")},required(...e){return D.required(Bv,this,e[0])}});function B6(e,t){let r={type:"object",shape:e??{},...D.normalizeParams(t)};return new ef(r)}function H6(e,t){return new ef({type:"object",shape:e,catchall:Gv(),...D.normalizeParams(t)})}function W6(e,t){return new ef({type:"object",shape:e,catchall:sc(),...D.normalizeParams(t)})}var tf=E("ZodUnion",(e,t)=>{Op.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>hv(e,r,i,n),e.options=t.options});function el(e,t){return new tf({type:"union",options:e,...D.normalizeParams(t)})}var Fk=E("ZodXor",(e,t)=>{tf.init(e,t),lT.init(e,t),e._zod.processJSONSchema=(r,i,n)=>hv(e,r,i,n),e.options=t.options});function J6(e,t){return new Fk({type:"union",options:e,inclusive:!1,...D.normalizeParams(t)})}var Gk=E("ZodDiscriminatedUnion",(e,t)=>{tf.init(e,t),pT.init(e,t)});function Z6(e,t,r){return new Gk({type:"union",options:t,discriminator:e,...D.normalizeParams(r)})}var qk=E("ZodIntersection",(e,t)=>{fT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>rk(e,r,i,n)});function Vk(e,t){return new qk({type:"intersection",left:e,right:t})}var Kk=E("ZodTuple",(e,t)=>{cc(),Ay.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>nk(e,r,i,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new rf({type:"optional",innerType:t}))})}});function Bk(e,t,r){let i=t instanceof ue,n=i?r:t,o=i?t:null;return new Kk({type:"tuple",items:e,rest:o,...D.normalizeParams(n)})}var Wu=E("ZodRecord",(e,t)=>{cc(),mT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ik(e,r,i,n),e.keyType=t.keyType,e.valueType=t.valueType});function Hk(e,t,r){return!t||!t._zod?new Wu({type:"record",keyType:Jp(),valueType:e,...D.normalizeParams(t)}):new Wu({type:"record",keyType:e,valueType:t,...D.normalizeParams(r)})}function X6(e,t,r){return new Wu({type:"record",keyType:e,valueType:t,...D.normalizeParams(r),partial:!0})}function Y6(e,t,r){return new Wu({type:"record",keyType:e,valueType:t,mode:"loose",...D.normalizeParams(r)})}var Wk=E("ZodMap",(e,t)=>{cc(),hT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>YC(e,r,i,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ui(...r)),e.nonempty=r=>e.check(Ui(1,r)),e.max=(...r)=>e.check(Ss(...r)),e.size=(...r)=>e.check(rc(...r))});function Q6(e,t,r){return new Wk({type:"map",keyType:e,valueType:t,...D.normalizeParams(r)})}var Jk=E("ZodSet",(e,t)=>{cc(),gT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>QC(e,r,i,n),e.min=(...r)=>e.check(Ui(...r)),e.nonempty=r=>e.check(Ui(1,r)),e.max=(...r)=>e.check(Ss(...r)),e.size=(...r)=>e.check(rc(...r))});function eG(e,t){return new Jk({type:"set",valueType:e,...D.normalizeParams(t)})}var Ju=E("ZodEnum",(e,t)=>{yT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,n,o)=>qC(e,i,n,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(i,n)=>{let o={};for(let s of i)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ju({...t,checks:[],...D.normalizeParams(n),entries:o})},e.exclude=(i,n)=>{let o={...t.entries};for(let s of i)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Ju({...t,checks:[],...D.normalizeParams(n),entries:o})}});function qv(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new Ju({type:"enum",entries:r,...D.normalizeParams(t)})}function tG(e,t){return new Ju({type:"enum",entries:e,...D.normalizeParams(t)})}var Zk=E("ZodLiteral",(e,t)=>{vT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>VC(e,r,i,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function rG(e,t){return new Zk({type:"literal",values:Array.isArray(e)?e:[e],...D.normalizeParams(t)})}var Xk=E("ZodFile",(e,t)=>{ST.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>HC(e,r,i,n),e.min=(r,i)=>e.check(Ui(r,i)),e.max=(r,i)=>e.check(Ss(r,i)),e.mime=(r,i)=>e.check(zu(Array.isArray(r)?r:[r],i))});function nG(e){return wC(Xk,e)}var Yk=E("ZodTransform",(e,t)=>{cc(),wT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>XC(e,r,i,n),e._zod.parse=(r,i)=>{if(i.direction==="backward")throw new ys(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(D.issue(o,r.value,t));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(D.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(o=>(r.value=o,r)):(r.value=n,r)}});function Vv(e){return new Yk({type:"transform",transform:e})}var rf=E("ZodOptional",(e,t)=>{Ry.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>gv(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function ac(e){return new rf({type:"optional",innerType:e})}var Kv=E("ZodExactOptional",(e,t)=>{bT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>gv(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function Qk(e){return new Kv({type:"optional",innerType:e})}var eD=E("ZodNullable",(e,t)=>{_T.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ok(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function Zp(e){return new eD({type:"nullable",innerType:e})}function iG(e){return ac(Zp(e))}var tD=E("ZodDefault",(e,t)=>{xT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ck(e,r,i,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function rD(e,t){return new tD({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():D.shallowClone(t)}})}var nD=E("ZodPrefault",(e,t)=>{ET.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>uk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function iD(e,t){return new nD({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():D.shallowClone(t)}})}var Bv=E("ZodNonOptional",(e,t)=>{AT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>sk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function oD(e,t){return new Bv({type:"nonoptional",innerType:e,...D.normalizeParams(t)})}var sD=E("ZodSuccess",(e,t)=>{RT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>WC(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function oG(e){return new sD({type:"success",innerType:e})}var aD=E("ZodCatch",(e,t)=>{IT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>lk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function cD(e,t){return new aD({type:"catch",innerType:e,catchValue:typeof t=="function"?t:D.constantCatch(t)})}var uD=E("ZodNaN",(e,t)=>{$T.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>KC(e,r,i,n)});function sG(e){return vC(uD,e)}var nf=E("ZodPipe",(e,t)=>{Iy.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>dk(e,r,i,n),e.in=t.in,e.out=t.out});function _v(e,t){return new nf({type:"pipe",in:e,out:t})}var of=E("ZodCodec",(e,t)=>{nf.init(e,t),Np.init(e,t)});function aG(e,t,r){return new of({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function cG(e){let t=e._zod.def;return new of({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var lD=E("ZodPreprocess",(e,t)=>{nf.init(e,t),PT.init(e,t)}),dD=E("ZodReadonly",(e,t)=>{TT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>pk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function pD(e){return new dD({type:"readonly",innerType:e})}var fD=E("ZodTemplateLiteral",(e,t)=>{CT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>BC(e,r,i,n)});function uG(e,t){return new fD({type:"template_literal",parts:e,...D.normalizeParams(t)})}var mD=E("ZodLazy",(e,t)=>{Up.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>mk(e,r,i,n),e.unwrap=()=>e._zod.def.getter()});function hD(e){return new mD({type:"lazy",getter:e})}var gD=E("ZodPromise",(e,t)=>{DT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>fk(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function lG(e){return new gD({type:"promise",innerType:e})}var yD=E("ZodFunction",(e,t)=>{kT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ZC(e,r,i,n)});function dG(e){return new yD({type:"function",input:Array.isArray(e?.input)?Bk(e?.input):e?.input??Qp(sc()),output:e?.output??sc()})}var sf=E("ZodCustom",(e,t)=>{OT.init(e,t),he.init(e,t),e._zod.processJSONSchema=(r,i,n)=>JC(e,r,i,n)});function pG(e){let t=new rt({check:"custom"});return t._zod.check=e,t}function fG(e,t){return bC(sf,e??(()=>!0),t)}function vD(e,t={}){return _C(sf,e,t)}function SD(e,t){return xC(e,t)}var mG=EC,hG=AC,wD=E("ZodInstanceOf",(e,t)=>{sf.init(e,t)},{properties(e,t){return this.check(Mu(e,t))}});function gG(e,t={}){let r=new wD({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...D.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=i=>{i.value instanceof e||i.issues.push({code:"invalid_type",expected:e.name,input:i.value,inst:r,path:[...r._zod.def.path??[]]})},r}var yG=(...e)=>RC({Codec:of,Boolean:Yu,String:Zu},...e);function vG(e){let t=hD(()=>el([Jp(e),Tk(),Ck(),Nk(),Qp(t),Hk(Jp(),t)]));return t}function SG(e,t){return new lD({type:"pipe",in:Vv(e),out:t})}var QSe={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 ewe(e){bt({customError:e})}function twe(){return bt().customError}var bD;bD||(bD={});var af={};it(af,{ZodISODate:()=>Es,ZodISODateTime:()=>xs,ZodISODuration:()=>Rs,ZodISOTime:()=>As,date:()=>nwe,datetime:()=>rwe,duration:()=>owe,time:()=>iwe});function rwe(e){return qp(xs,e)}function nwe(e){return Vp(Es,e)}function iwe(e){return Kp(As,e)}function owe(e){return Bp(Rs,e)}var K={...tl,...Sv,iso:af},swe=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 awe(e,t){let r=e.$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":t??"draft-2020-12"}function wG(e,t){return e.map((r,i)=>i<t?r:r.optional())}function cwe(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function uwe(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let i=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===i){let n=r[1]===void 0?void 0:cwe(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function lwe(e,t){return K.transform(i=>i).check(i=>{let n=i.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let o=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&o.length<t.minProperties&&i.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&i.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let s of o){let a=t.keySchema.safeParse(s);a.success||i.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(e)}function _D(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let i=String(e);return`${r[0]}${i.length}:${i}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let o=[];for(let s of e){let a=_D(s,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}let i=Object.keys(e).sort(),n=[];for(let o of i){let s=_D(e[o],t);if(s===null)return null;n.push(`${o.length}:${o}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var dwe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),pwe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function cf(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(cf):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>dwe.has(t)?cf(r):!pwe.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(cf))}function bG(e){return e===1?"element":"elements"}function fwe(e,t){return K.transform(i=>i).check(i=>{let n=i.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let o=new Map;for(let s=0;s<n.length;s++){let a=_D(n[s],new Set);if(a===null)continue;let c=o.get(a);if(c===void 0){o.set(a,s);continue}i.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(t.containsSchema){let o=t.minContains??1,s=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(t.containsSchema.safeParse(c).success&&++a>=s)break;a<o&&i.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${bG(o)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&i.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${bG(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function _G(e,t){if(e!==!1)return e===void 0||e===!0?K.any():Dr(e,t)}var mwe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function xG(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return K.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return K.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let o=uwe(n,t),s=Dr(o,t);return t.refs.set(n,s),t.processing.delete(n),s}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return K.null();if(n.length===0)return K.never();if(n.length===1)return K.literal(n[0]);if(n.every(s=>typeof s=="string"))return K.enum(n);let o=n.map(s=>K.literal(s));return o.length<2?o[0]:K.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return K.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(o=>{let s={...e,type:o};return xG(s,t)});return n.length===0?K.never():n.length===1?n[0]:K.union(n)}if(!r)return K.any();let i;switch(r){case"string":{let n=K.string();if(e.format){let o=e.format;o==="email"?n=n.check(K.email()):o==="uri"||o==="uri-reference"?n=n.check(K.url()):o==="uuid"||o==="guid"?n=n.check(K.uuid()):o==="date-time"?n=n.check(K.iso.datetime({offset:!0})):o==="date"?n=n.check(K.iso.date()):o==="time"?n=n.check(K.regex(mwe)):o==="duration"?n=n.check(K.iso.duration()):o==="hostname"?n=n.check(K.hostname()):o==="ipv4"?n=n.check(K.ipv4()):o==="ipv6"?n=n.check(K.ipv6()):o==="mac"?n=n.check(K.mac()):o==="cidr"?n=n.check(K.cidrv4()):o==="cidr-v6"?n=n.check(K.cidrv6()):o==="base64"?n=n.check(K.base64()):o==="base64url"?n=n.check(K.base64url()):o==="e164"?n=n.check(K.e164()):o==="credit_card"?n=n.check(K.creditCard()):o==="iban"?n=n.check(K.iban()):o==="jwt"?n=n.check(K.jwt()):o==="emoji"?n=n.check(K.emoji()):o==="nanoid"?n=n.check(K.nanoid()):o==="cuid"?n=n.check(K.cuid()):o==="cuid2"?n=n.check(K.cuid2()):o==="ulid"?n=n.check(K.ulid()):o==="xid"?n=n.check(K.xid()):o==="ksuid"&&(n=n.check(K.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),i=n;break}case"number":case"integer":{let n=r==="integer"?K.number().int():K.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),i=n;break}case"boolean":{i=K.boolean();break}case"null":{i=K.null();break}case"object":{let n={},o=e.properties||{},s=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Dr(e.additionalProperties,t):void 0;for(let[d,m]of Object.entries(o)){let p=Dr(m,t);er(n,d,s.has(d)?p:p.optional())}if(e.patternProperties){let d=e.patternProperties,m=Object.keys(d),p=[];for(let v of m){let S=Dr(d[v],t),b=K.string().regex(new RegExp(v));p.push(K.looseRecord(b,S))}let g=[];if(Object.keys(n).length>0&&g.push(K.object(n).passthrough()),g.push(...p),g.length===0)i=K.object({}).passthrough();else if(g.length===1)i=g[0];else{let v=K.intersection(g[0],g[1]);for(let S=2;S<g.length;S++)v=K.intersection(v,g[S]);i=v}if(e.additionalProperties===!1){let v=Object.keys(n),S=m.map(_=>new RegExp(_)),b=i;i=i.check(_=>{if(!bn(_.value))return;let x=[];for(let T of Object.keys(_.value))v.includes(T)||S.some(U=>U.test(T))||x.push(T);x.length&&_.issues.push({code:"unrecognized_keys",keys:x,input:_.value,inst:b})})}}else{let d=K.object(n);e.additionalProperties===!1?i=d.strict():a?i=d.catchall(a):i=d.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=Dr(m,t)}i=lwe(i,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=e.prefixItems,o=e.items;if(n&&Array.isArray(n)){let s=typeof e.minItems=="number"?e.minItems:0,a=n.map(d=>Dr(d,t)),c=wG(a,s),u=Array.isArray(o)?void 0:_G(o,t),l=K.tuple(c);i=u?l.rest(u):l,typeof e.minItems=="number"&&(i=i.check(K.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(K.maxLength(e.maxItems)))}else if(Array.isArray(o)){let s=typeof e.minItems=="number"?e.minItems:0,a=o.map(d=>Dr(d,t)),c=wG(a,s),u=_G(e.additionalItems,t),l=K.tuple(c);i=u?l.rest(u):l,typeof e.minItems=="number"&&(i=i.check(K.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(K.maxLength(e.maxItems)))}else if(o!==void 0){let s=Dr(o,t),a=K.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),i=a}else i=K.array(K.any());(e.uniqueItems===!0||e.contains!==void 0)&&(i=fwe(i,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Dr(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return i}function Dr(e,t){if(typeof e=="boolean")return e?K.any():K.never();let r=xG(e,t),i=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Dr(u,t)),c=K.union(a);r=i?K.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Dr(u,t)),c=K.xor(a);r=i?K.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=i?r:K.any();else{let a=i?r:Dr(e.allOf[0],t),c=i?0:1;for(let u=c;u<e.allOf.length;u++)a=K.intersection(a,Dr(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=K.nullable(r)),e.readOnly===!0&&(r=K.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(n[a]=e[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in e&&(n[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!cf(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(n[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!cf(e.contains)&&(n.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(n[a]=e[a])}for(let a of Object.keys(e))swe.has(a)||er(n,a,e[a]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function EG(e,t){if(typeof e=="boolean")return e?K.any():K.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let i=awe(r,t?.defaultTarget),n=r.$defs||r.definitions||{},o={version:i,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??tr};return Dr(r,o)}var AG=Symbol("z.visit/resolving");function uf(e,t){let r=typeof t=="function"?t:(s,a)=>{let c=t[s._zod.def.type];return c?c(s,a):s},i=new Map;function n(s){let a=i.get(s);if(a===AG)return new Up({type:"lazy",getter:()=>i.get(s)});if(a!==void 0)return a;i.set(s,AG);let c=o(s),u=r(c,c!==s);return i.set(s,u),u}function o(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,m={};for(let g of l){let v=n(u[g]);v!==u[g]&&(d=!0),m[g]=v}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?We(s,{...a,shape:m,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:We(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let g=n(p);g!==p&&(l=!0),d.push(g)}let m=a.rest;return a.rest&&(m=n(a.rest),m!==a.rest&&(l=!0)),l?We(s,{...a,items:d,rest:m}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:We(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:We(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let m of u){let p=n(m);p!==m&&(l=!0),d.push(p)}return l?We(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:We(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:We(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:We(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:We(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return We(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(e)}function RG(e){return uf(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:el(r.options)}})}function hwe(e,t){if(!t?.length)return e;let r=e._zod.def;return We(e,Xn(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function IG(e){return hwe(e.out,e.checks)}function gwe(e){return e.in._zod.traits.has("$ZodTransform")?IG(e):e.in}function $G(e){return uf(e,{pipe:t=>gwe(t._zod.def),default:(t,r)=>r?ac(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function PG(e){return uf(e,{pipe:t=>IG(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var xD={};it(xD,{bigint:()=>wwe,boolean:()=>Swe,date:()=>bwe,number:()=>vwe,string:()=>ywe});function ywe(e){return KT(Zu,e)}function vwe(e){return XT(Xu,e)}function Swe(e){return iC(Yu,e)}function wwe(e){return sC(Qu,e)}function bwe(e){return yC(Yp,e)}typeof window<"u"&&f.config({jitless:!0});function _we(e){let t=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(e.trim());if(!t)return null;try{let r=Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)),i=new DataView(r.buffer),n=0,o=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=i.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(o())!==t[1])return null;if(t[1]==="ssh-ed25519"){if(o().length!==32)return null}else if(t[1]==="ssh-rsa"){let a=o(),c=o();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(o()),c=o(),u={nistp256:65,nistp384:97,nistp521:133};if(t[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var TG=f.string().trim().max(8192).refine(e=>_we(e)!==null,"Use an OpenSSH public key from a .pub file."),Hv=f.object({authorizedKeys:f.array(TG).max(32)}).strict(),o9e=Hv.extend({revision:f.number().int().positive().optional()}),ED=Hv.extend({host:f.string().min(1).max(253).nullable(),port:f.number().int().min(1).max(65535),username:f.string().regex(/^[a-z_][a-z0-9_-]*$/),workingDirectory:f.string().startsWith("/").max(4096),hostKey:TG.nullable(),fingerprint:f.string().nullable(),revision:f.number().int().positive(),appliedRevision:f.number().int().nonnegative(),activeSessions:f.number().int().min(0).max(1024)}).strict(),s9e=ED.extend({state:f.enum(["starting","configuring","ready","disabled","stopped"])});var rl=new TextEncoder,nl=new TextDecoder,CG=new TextDecoder("utf-8",{fatal:!0}),Wv=2**32;function Or(...e){let t=e.reduce((n,{length:o})=>n+o,0),r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r}function AD(e,t,r){if(t<0||t>=Wv)throw new RangeError(`value must be >= 0 and <= ${Wv-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function RD(e){let t=Math.floor(e/Wv),r=e%Wv,i=new Uint8Array(8);return AD(i,t,0),AD(i,r,4),i}function Jv(e){let t=new Uint8Array(4);return AD(t,e),t}var xwe=/[^\x00-\x7f]/;function rr(e){if(typeof e=="string"&&e.length>=128){if(xwe.test(e))throw new TypeError("non-ASCII string encountered in encode()");return rl.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=i}return t}function kG(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,i=[];for(let o=0;o<e.length;o+=r)i.push(String.fromCharCode.apply(null,e.subarray(o,o+r)));let n=btoa(i.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function DG(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),i=new Uint8Array(r.length);for(let n=0;n<r.length;n++)i[n]=r.charCodeAt(n);return i}async function Zv(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}var Uo=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var dc=class extends Uo{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},dt=class extends Uo{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Is=class extends Uo{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},F=class extends Uo{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},pt=class extends Uo{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var lf=class extends Uo{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var Xv=class extends Uo{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var Ewe="The input to be decoded is not correctly encoded.";function pc(e){try{return DG(typeof e=="string"?e:nl.decode(e),!0)}catch(t){throw new TypeError(Ewe,{cause:t})}}function gt(e){return kG(typeof e=="string"?rl.encode(e):e,!0)}function on(e,t){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be an instance of Uint8Array`)}function Pt(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function $s(...e){let t=new Set;for(let r of e)if(r)for(let i of Object.keys(r)){if(t.has(i))return!1;t.add(i)}return!0}function En(e,t){if(e!==void 0)throw new TypeError(`${t} can only be called once`)}function Zr(e,t,r){try{return pc(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function Yv(e,t,r){try{return rr(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}function il(e,t,r){let i;try{i=JSON.parse(CG.decode(pc(e)))}catch{throw new t(r)}if(!Pt(i))throw new t(r);return i}var Qv={__proto__:null,b64:!0},eS={__proto__:null};function df(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function tS(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Ps(e,t,r,i,n){if(n.crit!==void 0&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||i.crit===void 0)return[];if(!Array.isArray(i.crit)||i.crit.length===0||i.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o=r===void 0?t:{__proto__:null,...r,...t};for(let s of i.crit){if(!(s in o))throw new dt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o[s]&&(!Object.hasOwn(i,s)||i[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return i.crit}function rS(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new pt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function fc(e,t){let r,i;try{r=JSON.stringify(t),i=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!Pt(i))throw new e("JOSE Header is not a JSON object");return[i,r]}var Awe=e=>e[Symbol.toStringTag],Rwe=(e,t,r)=>{let{alg:i}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==i)throw new TypeError(`Invalid key for this operation, its "alg" must be "${i}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function ei(e,t,r){let{alg:i,secret:n}=e,o=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return t;let s,a;if(Pt(t)){if(s=kD(t),typeof s.kty!="string")throw OG(i,t,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(o?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 ${o?"private":"public"} JWK`);if(Rwe(e,s,r),s.kty==="oct")return pc(s.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!PD(t))throw OG(i,t,n);let l=n?"secret":o?"private":"public";if(t.type!==l&&(n||["secret","public","private"].includes(t.type)))throw new TypeError(`${Awe(t)} instances must be of type "${l}" for the ${i} algorithm`);if(Ts(t))return t;if(a=t,a.type==="secret")return a.export()}ID||=new WeakMap;let c=t,u=ID.get(c);if(u?.[i])return u[i];if(u||ID.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=Iwe[a.asymmetricKeyDetails?.namedCurve],m=e.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[i]=a.toCryptoKey(m,l,e.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=i,u[i]=await sl(e,s)}var ID,Iwe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function iS(e){if(!Ts(e))throw new Error("CryptoKey instance expected")}var Ts=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},$D=e=>e?.[Symbol.toStringTag]==="KeyObject",PD=e=>Ts(e)||$D(e);function NG(e,t,...r){if(r.length>2){let i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Lo=(e,...t)=>NG("Key must be ",e,...t);function OG(e,t,r){let i=["CryptoKey","KeyObject","JSON Web Key"];return r&&i.push("Uint8Array"),new TypeError(NG(`Key for the ${e} algorithm must be `,t,...i))}var nS=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function TD(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ol(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function CD(e,t,r){let i=e.algorithm;if(i.name!==t.name)throw nS(t.name);if(t.hash&&i.hash?.name!==t.hash)throw nS(t.hash,"algorithm.hash");if(t.namedCurve&&i.namedCurve!==t.namedCurve)throw nS(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&i.length!==t.length)throw nS(t.length,"algorithm.length");TD(e,r)}function oS(e){return{__proto__:null,...e}}function kD(e){let t=oS(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,i=Array.isArray(r)?[...r]:void 0;if(!i||i.some(n=>typeof n!="string")||new Set(i).size!==i.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=i}return t}function UG(e){if(e!==void 0&&typeof e!="boolean")throw new TypeError('"extractable" option must be a boolean');return e}async function sl(e,t,r){if(!e.kty.includes(t.kty))throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let i=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),o={...t,ext:r??t.ext};return o.kty!=="AKP"&&delete o.alg,delete o.use,crypto.subtle.importKey("jwk",o,i,o.ext??!n,t.key_ops??e.usages[n?1:0])}async function ti(e,t,r,i=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,i,[r])),CD(e,t,r),e}var mc=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function sS(e,t){let r=e.byteLength<<3;if(r!==t)throw new F(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var $we=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function LG(e,t){if(t.length<<3!==e.ivBits)throw new F("Invalid Initialization Vector length")}async function MG(e,t,r){if(!(t instanceof Uint8Array))throw new TypeError(Lo(t,"Uint8Array"));let i=e.cekBits>>1,n=await crypto.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,[r]),o=await crypto.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]);return[n,o,i]}async function zG(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function Pwe(e,t,r,i,n){let[o,s,a]=await MG(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:i,name:"AES-CBC"},o,t)),u=Or(n,i,c,RD(n.length*8)),l=await zG(s,u,a);return{ciphertext:c,tag:l,iv:i}}async function Twe(e,t){let r={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,i,e);return crypto.subtle.verify(r,i,n,t)}async function Cwe(e,t,r,i,n,o){let[s,a,c]=await MG(e,t,"decrypt"),u=Or(o,i,r,RD(o.length*8)),l=await zG(a,u,c);try{if(await Twe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:i,name:"AES-CBC"},s,r))}catch{}throw new Is}async function aS(e,t,r,i,n){if(!Ts(r)&&!(r instanceof Uint8Array))throw new TypeError(Lo(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(i?LG(e,i):i=$we(e),r instanceof Uint8Array&&sS(r,e.cekBits),e.cbc)return Pwe(e,t,r,i,n);let o=await ti(r,e.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:i,name:"AES-GCM",tagLength:128},o,t));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:i}}async function cS(e,t,r,i,n,o){if(!Ts(t)&&!(t instanceof Uint8Array))throw new TypeError(Lo(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!i)throw new F("JWE Initialization Vector missing");if(!n)throw new F("JWE Authentication Tag missing");if(!e.cbc&&n.length!==16)throw new F("Invalid Authentication Tag length");if(LG(e,i),t instanceof Uint8Array&&sS(t,e.cekBits),e.cbc)return Cwe(e,t,r,i,n,o);let s=await ti(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:i,name:"AES-GCM",tagLength:128},s,Or(r,n)))}catch{throw new Is}}function pf(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var kwe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Dwe=[[],["deriveBits"]],dS=[[],[]];function uS(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:kwe,ops:["wrapKey","unwrapKey"]}}function lS(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:t,crv:r,asymmetricKeyType:i})=>{if(r==="X25519"||i==="x25519")return{name:"X25519"};if(t==="OKP")throw new dt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Dwe,ops:[void 0,"deriveBits"]}}function al(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:dS,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function DD(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:dS,ops:["deriveBits","deriveBits"]}}var Mo=pf({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:dS,ops:["encrypt","decrypt"]},"RSA-OAEP":uS(1),"RSA-OAEP-256":uS(256),"RSA-OAEP-384":uS(384),"RSA-OAEP-512":uS(512),"ECDH-ES":lS("direct-key-agreement"),"ECDH-ES+A128KW":lS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":lS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":lS("key-agreement-with-key-wrapping"),A128KW:al(128),A192KW:al(192),A256KW:al(256),A128GCMKW:al(128,!0),A192GCMKW:al(192,!0),A256GCMKW:al(256,!0),"PBES2-HS256+A128KW":DD(),"PBES2-HS384+A192KW":DD(),"PBES2-HS512+A256KW":DD()}),Owe=["encrypt","decrypt"];function cl(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:dS,ops:Owe,cekBits:e,ivBits:t?128:96,cbc:t}}var Nwe=pf({A128GCM:cl(128),A192GCM:cl(192),A256GCM:cl(256),"A128CBC-HS256":cl(256,!0),"A192CBC-HS384":cl(384,!0),"A256CBC-HS512":cl(512,!0)});function jG(e,t){throw new dt(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function ri(e){return(typeof e=="string"?Mo[e]:void 0)??jG("alg","Algorithm")}function ni(e){return e.mode==="key-wrapping"||e.mode==="key-encryption"||e.mode==="key-agreement-with-key-wrapping"}function hc(e){return(typeof e=="string"?Nwe[e]:void 0)??jG("enc","Encryption Algorithm")}function FG(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");TD(e,t)}async function Uwe(e,t,r){let i=await ti(t,ri(e).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,i,"AES-KW"))}async function Lwe(e,t,r){let i=await ti(t,ri(e).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,i,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function qG(e,t,r){CD(t,ri(e).subtle,r),ol(e,t)}async function VG(e,t,r,i){if(!(e instanceof Uint8Array)||e.length<8)throw new F("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new F("PBES2 Count Input must be a positive integer");let n=Or(rr(t),Uint8Array.of(0),e),o=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await ti(i,ri(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,o))}function OD(e){return Or(Jv(e.length),e)}async function Mwe(e,t,r){let i=t>>3,n=32,o=Math.ceil(i/n),s=new Uint8Array(o*n);for(let a=1;a<=o;a++){let c=await Zv("sha256",Or(Jv(a),e,r));s.set(c,(a-1)*n)}return s.slice(0,i)}async function KG(e,t,r,i,n=new Uint8Array,o=new Uint8Array){FG(e),FG(t,"deriveBits");let s=Or(OD(rr(r)),OD(n),OD(o),Jv(i)),a=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return Mwe(a,i,s)}function BG(e){iS(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new dt("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function pS(e,t){let r=e[t];if(r!==void 0){if(typeof r!="string")throw new F(`JOSE Header "${t}" (Agreement Party${t==="apu"?"U":"V"}Info) invalid`);return Zr(r,t,F)}}function HG(e,t){if(!(e===void 0||t===void 0||e.byteLength!==t.byteLength)){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new F('JOSE Header "apu" and "apv" values must be distinct')}}function zwe(e){if(e===void 0)throw new F("JWE Encrypted Key missing")}function GG(e){if(e!==void 0)throw new F("Encountered unexpected JWE Encrypted Key")}function jwe(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function WG(e,t,r,i,n,o){let{alg:s}=e,a=e.mode;if(a==="direct-encryption")return GG(i),r;let c=a==="direct-key-agreement";switch(c?GG(i):zwe(i),e.subtle.name){case"ECDH":{let{epk:u}=n;if(!Pt(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(g=>Object.hasOwn(u,g)))throw new F('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');BG(r);let l=await sl(e,u),d=pS(n,"apu"),m=pS(n,"apv");HG(d,m);let p=await KG(l,r,c?t.alg:s,c?t.cekBits:parseInt(s.slice(-5,-2),10),d,m);if(c)return p;r=p;break}case"RSA-OAEP":return iS(r),qG(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,i));case"PBKDF2":{if(typeof n.p2c!="number")throw new F('JOSE Header "p2c" (PBES2 Count) missing or invalid');jwe(o);let u=o??1e4;if(n.p2c>u)throw new F('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new F('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=Zr(n.p2s,"p2s",F);r=await VG(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new F('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new F('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=Zr(n.iv,"iv",F),l=Zr(n.tag,"tag",F);if(u.byteLength!==12)throw new F("Invalid Initialization Vector length");if(l.byteLength!==16)throw new F("Invalid Authentication Tag length");return cS(hc(s.slice(0,-2)),r,i,u,l,new Uint8Array)}}return Lwe(s.slice(-6),r,i)}async function fS(e,t,r,i,n,o={}){let{alg:s,mode:a}=e,c=ni(e);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await ei(a==="direct-encryption"?t:e,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??mc(t):void 0;l&&sS(l,t.cekBits);let d,m;switch(e.subtle.name){case"ECDH":{BG(u);let{apu:p,apv:g}=o;p!==void 0&&on(p,'"apu"'),g!==void 0&&on(g,'"apv"');let v=p??pS(i,"apu"),S=g??pS(i,"apv");HG(v,S);let b;o.epk!==void 0?b=await ei(e,o.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let _=crypto.subtle,x=b;if(!x.extractable){if(typeof _.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await _.getPublicKey(b,[])}let{x:T,y:U,crv:C,kty:G}=await _.exportKey("jwk",x),B=a==="direct-key-agreement",de=await KG(u,b,B?t.alg:s,B?t.cekBits:parseInt(s.slice(-5,-2),10),v,S),pe={x:T,crv:C,kty:G};if(G==="EC"&&(pe.y=U),m={epk:pe},p!==void 0&&(m.apu=gt(p)),g!==void 0&&(m.apv=gt(g)),B)return[de,void 0,m];u=de;break}case"RSA-OAEP":{iS(u),qG(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:g=crypto.getRandomValues(new Uint8Array(16))}=o;u=await VG(g,s,p,u),m={p2c:p,p2s:gt(g)};break}case"AES-GCM":{let p=o.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):o.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let g=await aS(hc(s.slice(0,-2)),l,u,p,new Uint8Array);d=g.ciphertext,m={iv:gt(g.iv),tag:gt(g.tag)}}}if(d??=await Uwe(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,m]}function mS(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new dt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new F('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function JG(e){if(typeof globalThis[e]>"u")throw new dt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function ZG(e,t,r=1/0){let i=e.writable.getWriter();i.write(t).catch(()=>{}),i.close().catch(()=>{});let n=[],o=0,s=e.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),o+=a.byteLength,r!==1/0&&o>r)throw new F("Decompressed plaintext exceeded the configured limit")}return Or(...n)}async function XG(e){return JG("CompressionStream"),ZG(new CompressionStream("deflate-raw"),e)}async function YG(e,t){return JG("DecompressionStream"),ZG(new DecompressionStream("deflate-raw"),e,t)}function QG(e){let{aad:t,ciphertext:r,iv:i,protected:n,tag:o,unprotected:s}=e;if(i!==void 0&&(typeof i!="string"||!i))throw new F("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new F("JWE Ciphertext missing or incorrect type");if(o!==void 0&&(typeof o!="string"||!o))throw new F("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new F("JWE Protected Header incorrect type");if(t!==void 0&&(typeof t!="string"||!t))throw new F("JWE AAD incorrect type");if(s!==void 0&&!Pt(s))throw new F("JWE Shared Unprotected Header incorrect type");return{aad:t,ciphertext:r,iv:i,protected:n,tag:o,unprotected:s===void 0?void 0:{...s}}}function eq(e){let t,r;try{let{header:i}=e;if(Pt(i)){r=i.alg;let o=Object.keys(i);o.includes("alg")||(r=void 0),t=Object.fromEntries(o.map(s=>[s,s==="alg"?r:i[s]]))}else t=i;let{encrypted_key:n}=e;return[{encrypted_key:n,header:t},r]}catch(i){return[void 0,r,i]}}function tq(e){let{encrypted_key:t,header:r}=e;if(t!==void 0&&typeof t!="string")throw new F("JWE Encrypted Key incorrect type");if(r!==void 0&&!Pt(r))throw new F("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected===void 0&&r===void 0&&e.unprotected===void 0)throw new F("JOSE Header missing")}function ND(e){let{protected:t,ciphertext:r,iv:i,tag:n,aad:o}=e,s;return t!==void 0&&(s=il(t,F,"JWE Protected Header is invalid")),[s,Zr(r,"ciphertext",F),i!==void 0?Zr(i,"iv",F):void 0,n!==void 0?Zr(n,"tag",F):void 0,Yv((t??"")+(o!==void 0?`.${o}`:""),"aad",F)]}function hS(e){return[e&&df("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&df("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function UD(e,t,r,i=ND(e)){let[n,o,s,a,c]=i,{header:u,unprotected:l,aad:d}=e,m;if(u!==void 0||l!==void 0){if(!$s(n,u,l))throw new F("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");m={...n,...u,...l}}else m=n??{};let[p,g,v,S,b]=t,{encrypted_key:_}=e;Ps(F,eS,v,n,m),mS(m,n);let{alg:x,enc:T}=m;if(typeof x!="string"||!x)throw new F("missing JWE Algorithm (alg) in JWE Header");let U=Mo[x];if(_===""&&(!U||!ni(U)))throw new F("JWE Encrypted Key incorrect type");let C=U?.mode==="integrated-encryption";if(!C&&(typeof T!="string"||!T))throw new F("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new dc('"alg" (Algorithm) Header Parameter value not allowed');let G;if(C){if(T!==void 0)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new F("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new F("JWE Authentication Tag must be empty for integrated encryption")}else{if(g&&!g.has(T))throw new dc('"enc" (Encryption Algorithm) Header Parameter value not allowed');G=hc(T)}let B;if(_!==void 0)try{B=Zr(_,"encrypted_key",F)}catch(Ne){if(!U||!ni(U))throw Ne;B=new Uint8Array}let de=!1;typeof r=="function"&&(r=await r(n,e),de=!0);let pe=U??ri(x);ni(pe)&&B===void 0&&(B=new Uint8Array);let qe=await ei(pe.mode==="direct-encryption"?G:pe,r,"decrypt"),ee;if(pe.mode==="integrated-encryption")ee=await pe.decrypt(qe,B,o,c,n,m);else{let Ne=G,X;try{X=await WG(pe,Ne,qe,B,m,S),ni(pe)&&X instanceof Uint8Array&&X.byteLength<<3!==Ne.cekBits&&(X=mc(Ne))}catch(mt){if(mt instanceof TypeError||mt instanceof F||mt instanceof dt)throw mt;X=mc(Ne)}ee=await cS(Ne,X,o,s,a,c)}if(m.zip==="DEF"){let Ne=b??25e4;if(Ne===0)throw new dt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ne!==1/0&&(!Number.isSafeInteger(Ne)||Ne<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");ee=await YG(ee,Ne).catch(X=>{throw X instanceof F?X:new F("Failed to decompress plaintext",{cause:X})})}return{plaintext:ee,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:Zr(d,"aad",F)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...de&&{key:qe}}}async function rq(e,t,r){if(e instanceof Uint8Array&&(e=nl.decode(e)),typeof e!="string")throw new F("Compact JWE must be a string or Uint8Array");let{0:i,1:n,2:o,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new F("Invalid Compact JWE");return UD({ciphertext:s,iv:o||void 0,protected:i,tag:a||void 0,encrypted_key:n||void 0},t,r)}async function gS(e,t,r){return rq(e,hS(r),t)}async function LD(e,t,r){if(!Pt(e))throw new F("General JWE must be an object");let i=e.recipients;if(!Array.isArray(i))throw new F("JWE Recipients missing or incorrect type");let n=Array.from(i);if(!n.every(Pt))throw new F("JWE Recipients missing or incorrect type");if(!n.length)throw new F("JWE Recipients has no members");let o,s,a;try{o=hS(r),s=QG(e),a=ND(s)}catch{throw new Is}let c=n.map(u=>eq(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Mo[l]:void 0;if(d&&!ni(d))throw new F(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return tq(l),await UD(l,o,t,a)}catch{}throw new Is}function yS(e,t,r){if(!$s(e,t,r))throw new F("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function MD(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new F("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");t!==void 0&&(e[8]=t?.crit);let[,i,n,o,s,a,c,u,l]=e;if(s!==void 0&&on(s,"JWE Additional Authenticated Data"),a!==void 0&&on(a,"JWE Content Encryption Key"),c!==void 0&&on(c,"JWE Initialization Vector"),!r&&i!==void 0&&(i=fc(F,i)[0],e[1]=i),n!==void 0&&(n=fc(F,n)[0],e[2]=n),!r&&o!==void 0&&(o=fc(F,o)[0],e[3]=o),u!==void 0&&!Pt(u))throw new TypeError("JWE Key Management Parameters must be an object");yS(i,n,o);let d={...i,...n,...o};tS(F,i),Ps(F,eS,l,i,d),mS(d,i);let{alg:m,enc:p}=d;if(typeof m!="string"||!m)throw new F('JWE "alg" (Algorithm) Header Parameter missing or invalid');let g=Mo[m];if(g?.mode==="integrated-encryption"){if(p!==void 0)throw new F('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 ${m}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${m}`);return[d,void 0,g]}if(typeof p!="string"||!p)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,hc(p),g]}async function zD(e,t,r){let[i,n,o]=t,[s,a,c,u,l,d,m,p,,g]=e,v=a,S=c,b=o??ri(i.alg),_,x,T;b.mode==="integrated-encryption"?T=await ei(b,r,"encrypt"):[T,_,x]=await fS(b,n,r,i,d,p),x&&(g?S=S?{...S,...x}:x:v=v?{...v,...x}:x,yS(v,S,u));let U=v?gt(JSON.stringify(v)):"",C=l?.byteLength?gt(l):void 0,G=rr(C?`${U}.${C}`:U),B=s;i.zip==="DEF"&&(B=await XG(B).catch(Ne=>{throw new F("Failed to compress plaintext",{cause:Ne})}));let de,pe,qe;b.mode==="integrated-encryption"?[_,de]=await b.encrypt(T,B,G,v,i,p):{ciphertext:de,tag:pe,iv:qe}=await aS(n,B,T,m,G);let ee={ciphertext:gt(de)};return qe&&(ee.iv=gt(qe)),pe&&(ee.tag=gt(pe)),_?.byteLength&&(ee.encrypted_key=gt(_)),C&&(ee.aad=C),v&&(ee.protected=U),u&&(ee.unprotected=u),S&&(ee.header=S),ee}async function nq(e,t,r){return zD(e,MD(e,r),t)}function iq(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(".")}var jD=class{#e;state;constructor(t,r,i){this.#e=t,this.state=[void 0,void 0,r,i]}setUnprotectedHeader(t){return En(this.state[0],"setUnprotectedHeader"),this.state[0]=t,this}setKeyManagementParameters(t){return En(this.state[1],"setKeyManagementParameters"),this.state[1]=t,this}addRecipient(...t){return this.#e.addRecipient(...t)}encrypt(...t){return this.#e.encrypt(...t)}done(){return this.#e}},ff=class{#e;#t=[];#r;#n;#i;constructor(t){this.#e=t}addRecipient(t,r){let i=new jD(this,t,r?.crit);return this.#t.push(i),i}setProtectedHeader(t){return En(this.#r,"setProtectedHeader"),this.#r=t,this}setSharedUnprotectedHeader(t){return En(this.#n,"setSharedUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#i=t,this}async encrypt(){if(!this.#t.length)throw new F("at least one recipient must be added");on(this.#e,"plaintext");let t=this.#t.length>1,r,i=this.#r,n=this.#n,o=[];for(let g of this.#t){let[v,S,b,_]=g.state,x=[this.#e,i,v,n,this.#i,void 0,void 0,S,_,t],T=MD(x,void 0,o.length>0);o.length||(i=x[1],n=x[3]),o.push([x,T,b]);let[{alg:U,enc:C},,G]=T;if(t&&G&&!ni(G))throw new F(`"${U}" alg may only have a single recipient`);if(!r)r=C;else if(r!==C)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,g]of o)g[2]??=ri(g[0].alg);let[s,a,c]=o[0],u=t?mc(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...m}=await zD(s,a,c),p={...m,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let g=1;g<o.length;g++){let[v,[S,b,_],x]=o[g],T=v[2],[,U,C]=await fS(_,b,x,S,u,v[7]),G={encrypted_key:gt(U)};if(T||C){let B={...T,...C};C&&yS(v[1],B,v[3]),G.header=B}p.recipients.push(G)}return p}};var mf=[["verify"],["sign"]];function FD(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:mf}}function ul(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:mf,minRsaBits:2048}}function GD(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:mf}}function oq(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:mf}}function qD(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:mf}}var VD=pf({HS256:FD(256),HS384:FD(384),HS512:FD(512),RS256:ul(256),RS384:ul(384),RS512:ul(512),PS256:ul(256,32),PS384:ul(384,48),PS512:ul(512,64),ES256:GD("P-256",256),ES384:GD("P-384",384),ES512:GD("P-521",512),EdDSA:oq(),Ed25519:oq(),"ML-DSA-44":qD(44),"ML-DSA-65":qD(65),"ML-DSA-87":qD(87)});function vS(e){let t=typeof e=="string"?VD[e]:void 0;if(!t)throw new dt(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function sq(e){return[e&&df("algorithms",e.algorithms),e?.crit]}function Fwe(e){return e===void 0?{}:il(e,pt,"JWS Protected Header is invalid")}function Gwe(e){try{return rr(e)}catch{throw new pt("JWS Compact Serialization payload must use only ASCII characters")}}async function qwe(e,t,r,i,n){let{protected:o,header:s,payload:a}=e,c=n??Fwe(o);if(!$s(c,s))throw new pt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=rS(c,Ps(pt,Qv,t[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new pt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(d))throw new dc('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new pt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new pt("JWS Payload must be a string or an Uint8Array instance");let m=l||typeof a!="string"?a:i(a),p=!1;typeof r=="function"&&(r=await r(c,e),p=!0);let g=vS(d),v=Or(o!==void 0?rr(o):new Uint8Array,rr("."),typeof m=="string"?t[2]??=Yv(m,"payload",pt):m),S=Zr(e.signature,"signature",pt),b=await ei(g,r,"verify"),_=await ti(b,g.subtle,"verify");g.minRsaBits&&ol(g.alg,_);let x=!1;try{x=await crypto.subtle.verify(g.signing,_,S,v)}catch{}if(!x)throw new Xv;let T={payload:typeof m=="string"?Zr(m,"payload",pt):m};return o!==void 0&&(T.protectedHeader=c),s!==void 0&&(T.unprotectedHeader=s),p?[{...T,key:b},l]:[T,l]}async function aq(e,t,r){if(e instanceof Uint8Array&&(e=nl.decode(e)),typeof e!="string")throw new pt("Compact JWS must be a string or Uint8Array");let{0:i,1:n,2:o,length:s}=e.split(".");if(s!==3)throw new pt("Invalid Compact JWS");return qwe({payload:n,protected:i,signature:o},t,r,Gwe)}async function KD(e,t,r){let[i]=await aq(e,sq(r),t);return i}var ll=class{#e;constructor(t){on(t,"plaintext"),this.#e=[t]}setContentEncryptionKey(t){return En(this.#e[5],"setContentEncryptionKey"),this.#e[5]=t,this}setInitializationVector(t){return En(this.#e[6],"setInitializationVector"),this.#e[6]=t,this}setProtectedHeader(t){return En(this.#e[1],"setProtectedHeader"),this.#e[1]=t,this}setKeyManagementParameters(t){return En(this.#e[7],"setKeyManagementParameters"),this.#e[7]=t,this}async encrypt(t,r){return iq(await nq([...this.#e],t,r))}};async function Vwe(e,t,r){let[i,n,o,s]=e,a="";if(n!==void 0){let b=fc(pt,n);n=b[0],a=gt(b[1])}if(o!==void 0&&(o=fc(pt,o)[0]),!n&&!o)throw new pt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!$s(n,o))throw new pt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...o};tS(pt,n);let u=rS(n,Ps(pt,Qv,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new pt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=vS(l),m="",p=i,g;if(u){let b=e[4];b?(m=b[0]??=gt(i),p=b[1]??=rr(m)):(m=gt(i),g=rl.encode(`${a}.${m}`))}g??=Or(rr(a),rr("."),p);let v=await ti(await ei(d,t,"sign"),d.subtle,"sign");d.minRsaBits&&ol(d.alg,v);let S={signature:gt(new Uint8Array(await crypto.subtle.sign(d.signing,v,g))),payload:m};return n&&(S.protected=a),o&&(S.header=o),[S,u]}async function cq(e,t,r,i,n){let[o]=await Vwe([e,t,void 0,r],i,n);return`${o.protected}.${o.payload}.${o.signature}`}var hf=class{#e;#t;constructor(t){on(t,"payload"),this.#e=t}setProtectedHeader(t){return En(this.#t,"setProtectedHeader"),this.#t=t,this}async sign(t,r){return cq(this.#e,this.#t,r?.crit,t,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};function Kwe(e='JWK "alg" (Algorithm) Parameter'){throw new dt(`Invalid or unsupported ${e} value`)}function BD(e,t){return(typeof e=="string"?VD[e]??Mo[e]:void 0)??Kwe(t)}async function SS(e){if($D(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:gt(e)};if(!Ts(e))throw new TypeError(Lo(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,t.kty!=="AKP"&&delete t.alg;for(let r of Object.keys(t))t[r]===void 0&&delete t[r];return t}var zo=(e,t)=>{if(typeof e!="string"||!e)throw new lf(`${t} missing or invalid`)};async function HD(e,t){let r;if(Pt(e)){if(r=oS(e),typeof r.kty!="string")throw new TypeError(Lo(e,"CryptoKey","KeyObject","JSON Web Key"))}else if(PD(e))r=oS(await SS(e));else throw new TypeError(Lo(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let i;switch(r.kty){case"AKP":zo(r.alg,'"alg" (Algorithm) Parameter'),zo(r.pub,'"pub" (Public key) Parameter'),i={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":zo(r.crv,'"crv" (Curve) Parameter'),zo(r.x,'"x" (X Coordinate) Parameter'),zo(r.y,'"y" (Y Coordinate) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":zo(r.crv,'"crv" (Subtype of Key Pair) Parameter'),zo(r.x,'"x" (Public Key) Parameter'),i={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":zo(r.e,'"e" (Exponent) Parameter'),zo(r.n,'"n" (Modulus) Parameter'),i={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new lf('"k" (Key Value) Parameter missing or invalid');i={k:r.k,kty:r.kty};break;default:throw new dt('"kty" (Key Type) Parameter missing or unsupported')}let n=rr(JSON.stringify(i));return gt(await Zv(t,n))}async function An(e,t,r){if(!Pt(e))throw new TypeError("JWK must be an object");let i=kD(e),n=UG(r?.extractable),{alg:o}=i;if(t??=o,i.kty!=="oct"&&!t)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(i.kty){case"oct":if(typeof i.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return pc(i.k);case"AKP":{if(typeof o!="string"||!o)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==o)throw new TypeError("JWK alg and alg option value mismatch");return sl(BD(t),i,n)}case"RSA":case"EC":case"OKP":return sl(BD(t),i,n);default:throw new dt('Unsupported "kty" (Key Type) Parameter value')}}function WD(e){let t;if(typeof e=="string"){let i=e.split(".");(i.length===3||i.length===5)&&([t]=i)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof t!="string"||!t)throw new TypeError(r);return il(t,TypeError,r)}var pq=f.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),fq=f.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),uq=f.string().min(1).max(128),lq=f.string().min(1).max(16384),Bwe=f.discriminatedUnion("kind",[f.object({kind:f.literal("access_key"),accessKeyId:uq,secretAccessKey:lq}).strict(),f.object({kind:f.literal("session"),accessKeyId:uq,secretAccessKey:lq,sessionToken:f.string().min(1).max(16384),expiresAt:f.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),f.object({kind:f.literal("environment")}).strict()]),Hwe=f.object({arn:fq,externalId:f.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),JD=f.object({authentication:Bwe,region:pq,role:Hwe.optional()}).strict(),wS=f.object({accountId:f.string().regex(/^\d{12}$/),principalId:f.string().min(1).max(256),arn:f.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),bS=JD.extend({sourceIdentity:wS.optional(),identity:wS.optional()}).strict();function dl(e){return e.includes(":assumed-role/")?e.slice(0,e.lastIndexOf("/")):e}function dq(e){return{...e,arn:dl(e.arn)}}function mq(e){return{authentication:e.authentication.kind,region:e.region,role:e.role??null,...e.sourceIdentity?{sourceIdentity:dq(e.sourceIdentity)}:{},...e.identity?{identity:dq(e.identity)}:{}}}var _S=f.object({authentication:f.enum(["access_key","session","environment"]),region:pq,sourceAccountId:f.string().regex(/^\d{12}$/).optional(),sourceArn:f.string().max(2e3).optional(),roleArn:fq.optional(),expiresAt:f.number().int().positive().optional()}).strict();function hq(e){return{authentication:e.authentication.kind,region:e.region,...e.sourceIdentity?{sourceAccountId:e.sourceIdentity.accountId,sourceArn:e.sourceIdentity.arn}:{},...e.role?{roleArn:e.role.arn}:{},...e.authentication.kind==="session"?{expiresAt:e.authentication.expiresAt}:{}}}var Wwe=f.object({method:f.enum(["GET","POST","PUT","DELETE","PATCH"]),path:f.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),gf=f.object({account:f.string().min(1),identities:f.array(f.string()),user:f.string().nullable(),description:f.string().nullable(),roles:f.array(f.string()).nullable(),credentialId:f.number().int().positive(),rules:f.array(Wwe),allowedIPs:f.array(f.string()).nullable(),expiresAt:f.number().nullable()}).strict();typeof window<"u"&&f.config({jitless:!0});var P=f.uuid(),be=f.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),ne=f.iso.datetime(),Nr=f.json(),Mt=f.record(f.string(),Nr),yq=f.enum(["ja","en"]),vq=f.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var Sq=f.enum(["variable","connection","service","method","app","object","environment","function","keyring"]),Ur=f.object({kty:f.literal("EC"),crv:f.literal("P-256"),x:f.string().min(40).max(50),y:f.string().min(40).max(50)}).strict(),Jwe=f.object({alg:f.literal("dir"),enc:f.literal("A256GCM"),sub:P}).strict(),Sf=f.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(e=>{try{return Jwe.safeParse(WD(e)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),jo=f.object({protected:f.string().max(2048),iv:f.string().max(64),ciphertext:f.string().max(2e6),tag:f.string().max(64),aad:f.string().max(2048).optional(),recipients:f.array(f.object({encrypted_key:f.string().max(2048),header:f.object({kid:P,epk:Ur.optional(),alg:f.string().optional()}).passthrough()})).min(1).max(100)}).strict(),O7e=f.object({id:P,name:be,publicKey:Ur}),Cs=f.object({id:P,name:be,owner:f.object({id:P,name:be}).nullable(),createdAt:ne,permissions:f.array(vq),createKinds:f.array(Sq),publicKey:Ur.nullable()}),N7e=f.object({id:P,kind:f.enum(["passkey","email","key"]),name:f.string(),createdAt:ne,lastUsedAt:ne.nullable(),expiresAt:ne.nullable(),canOpen:f.boolean()}),ZD=f.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),Zwe=f.object({subjectId:P,relation:ZD,objectId:P}).strict(),wq=f.enum(["principal",...Sq.options]),U7e=Zwe.extend({objectType:wq,subjectName:be,objectName:be,createdAt:ne}),L7e=f.object({error:f.object({code:f.string(),message:f.string(),details:Nr.optional()})}),M7e=f.object({ok:f.literal(!0)}),Xwe=f.object({value:f.string().min(1).max(200),label:f.string().min(1).max(200),values:f.record(f.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),f.string()).default({})}).strict(),RS=f.object({name:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:f.string(),secret:f.boolean().optional(),inputType:f.enum(["text","password"]).optional(),required:f.boolean().optional(),placeholder:f.string().optional(),note:f.string().optional(),pattern:f.string().optional(),choices:f.array(Xwe).min(1).max(100).optional(),defaultValue:f.string().max(1e3).optional(),when:f.object({field:f.string(),values:f.array(f.string()).min(1)}).strict().optional(),visibility:f.enum(["application","connection"]).optional()}).superRefine((e,t)=>{let r=e.choices??[];new Set(r.map(i=>i.value)).size!==r.length&&t.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),XD=f.record(f.string().regex(/^[A-Z_][A-Z0-9_]*$/),f.string()),Ywe=f.record(f.string().regex(/^[A-Z_][A-Z0-9_]*$/),f.union([f.string(),f.array(f.union([f.string().max(8192),f.object({pointer:f.string().max(1e3)}).strict()])).min(1).max(32)])),YD=f.object({values:f.array(f.object({id:f.string(),name:f.string(),description:f.string().optional()})).optional(),default:f.array(f.string()).default([]),required:f.array(f.string()).optional(),separator:f.string().default(" "),docs:f.url().optional()}),gc=f.string().min(1).max(4096),ES=f.union([f.string(),f.array(f.string()).min(1)]),Qwe=f.object({browserTokenExchange:f.enum(["available","unavailable","unknown"]).optional(),application:f.enum(["required","implicit"]).default("required"),grantType:f.enum(["authorization_code","client_credentials"]).optional(),issuer:f.url().optional(),registrationUrl:f.url().optional(),authorizeUrl:gc.optional(),tokenUrl:gc,identity:f.object({url:gc.optional(),from:f.enum(["token","app"]).optional(),method:f.enum(["GET","POST"]).default("GET"),id:ES.default("/id"),name:ES.default("/name"),headers:f.record(f.string(),f.string()).default({})}).optional(),revoke:f.object({url:gc,style:f.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:f.enum(["body","basic","none"]).optional(),tokenOnly:f.literal(!0).optional()}).optional(),clientAuth:f.enum(["body","basic","none"]).default("body"),pkce:f.boolean().default(!0),tokenFormat:f.enum(["form","json"]).default("form"),okPointer:f.string().optional(),authorizeParams:f.record(f.string(),f.string()).default({}),tokenParams:f.record(f.string(),f.string()).default({}),defaults:f.record(f.string(),f.string()).default({}),scopes:YD.default({default:[],separator:" "}),fields:f.array(RS).default([]),outputs:XD.default({ACCESS_TOKEN:"/accessToken"}),adapter:f.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:f.array(f.string()).default([]),hint:f.string().optional()}).refine(e=>e.grantType==="client_credentials"||!!e.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),ebe=f.object({fields:f.array(RS).min(1),outputs:Ywe,resolver:f.literal("vultr-role").optional(),bindFields:f.boolean().optional(),constants:f.record(f.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),f.string()).optional(),identity:f.object({url:gc,headers:f.record(f.string(),f.string()),id:ES,name:ES}).strict().optional(),console:f.url().optional(),instructions:f.string().optional(),hint:f.string().optional()}),QD=f.enum(["oauth","token","aws","ovh","approval"]),tbe=f.object({hint:f.string().optional()}).strict(),rbe=f.object({authorization:f.enum(["api_key","consumer_key"]),apiBaseUrl:gc,fields:f.array(RS).min(1),scopes:YD.default({default:[],separator:`
122
- `}),outputs:XD,hint:f.string().optional()}).strict(),pl=f.string().regex(/^[A-Z_][A-Z0-9_]*$/),gq=f.union([f.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),f.object({output:pl}).strict()]),IS=f.object({urlField:f.string().min(1).max(100).optional(),authentication:f.discriminatedUnion("kind",[f.object({kind:f.literal("none")}).strict(),f.object({kind:f.literal("bearer"),token:pl}).strict(),f.object({kind:f.literal("basic"),username:pl,password:pl}).strict(),f.object({kind:f.literal("header"),name:gq,value:pl}).strict(),f.object({kind:f.literal("query"),name:gq,value:pl}).strict()])}).strict(),wf={name:be,docs:f.url().optional(),console:gc.optional(),http:IS.optional(),preparation:f.object({scopeSelection:f.enum(["optional","required","hidden"]).default("optional"),instructions:f.array(f.union([f.string().max(2e3),f.object({ja:f.string().max(2e3),en:f.string().max(2e3)}).strict()])).max(10).default([]),docs:f.boolean().default(!1)}).strict().optional()},$S=f.object({...wf,kind:f.literal("oauth"),config:Qwe}).strict(),PS=f.object({...wf,kind:f.literal("token"),config:ebe}).strict(),TS=f.object({...wf,kind:f.literal("aws"),config:tbe}).strict(),CS=f.object({...wf,kind:f.literal("ovh"),config:rbe}).strict(),kS=f.object({...wf,kind:f.literal("approval"),config:f.object({adapter:f.literal("runpod-flash"),fields:f.array(RS).default([]),scopes:YD.default({default:[],separator:" "}),outputs:XD,hint:f.string().optional()}).strict()}).strict(),fl=f.discriminatedUnion("kind",[$S,PS,TS,CS,kS]),yf={id:f.string().min(1),builtin:f.boolean(),availability:f.enum(["ready","app-required","unavailable"]),defaultName:be,registration:f.object({kind:f.enum(["input","authorization"]),device:f.enum(["browser","cli"]),browserExchange:f.enum(["available","unavailable","unknown"]),tokenAlternatives:f.array(f.string())}).strict()},nbe=f.discriminatedUnion("kind",[$S.extend(yf),PS.extend(yf),TS.extend(yf),CS.extend(yf),kS.extend(yf)]),vf=f.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),eO=f.object({name:be,logo:f.string().regex(/^[a-z0-9-]+$/).optional(),api:f.url().optional(),docs:f.url().optional(),console:f.url().optional(),targets:f.array(f.object({id:vf,name:be,api:f.url().optional(),methods:f.array(vf).min(1)}).strict()).max(32).optional()}).strict(),ibe=eO.extend({methods:f.record(vf,f.string().min(1))}).strict(),bq=eO.extend({methods:f.record(vf,f.union([f.string().min(1),fl]))}).strict(),z7e=eO.extend({id:f.string(),builtin:f.boolean(),methods:f.record(vf,nbe)}),_q=f.object({id:P,output:f.string().min(1).max(100).optional()}).strict(),xq=e=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(e),obe=f.object({name:f.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:_q,format:f.enum(["text","file","json"]).default("text"),pointer:f.string().optional()}).strict(),sbe=f.object({pointer:f.string().max(500),parts:f.array(f.union([f.string().max(8192),_q])).min(1).max(32)}).strict(),yc=f.object({url:f.string().min(1).max(4096).optional(),connectionId:P.optional(),method:f.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:f.record(f.string(),f.string().max(8192)).default({}),body:f.string().max(1e6).optional(),json:Nr.optional(),form:f.record(f.string(),f.string()).optional(),bindings:f.array(sbe).max(32).default([])}).strict().refine(e=>!!(e.url||e.connectionId),{message:"Choose a connection or enter a destination URL."}),vc=f.object({command:f.array(f.string().max(8192)).min(1).max(100),stdin:f.string().max(1e6).optional(),timeoutSeconds:f.number().int().min(1).max(3600).default(60),inputs:f.array(obe).max(32).default([])}).strict(),Eq=f.discriminatedUnion("kind",[vc.omit({stdin:!0}).extend({kind:f.literal("command")}).strict(),f.object({kind:f.literal("http"),request:yc,responseFormat:f.enum(["text","json"]).default("json")}).strict()]),ks=f.object({description:f.string().max(2e3).default(""),program:Eq,parameters:f.array(f.object({name:f.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:f.string().max(100),type:f.enum(["string","number","boolean","json"]).default("string"),required:f.boolean().default(!0),default:Nr.optional()}).strict()).max(32).default([]),result:f.enum(["text","json"]).default("json")}).strict(),bf=f.object({expiresAt:ne.nullable().default(null)}).strict(),j7e=f.object({version:f.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:bf,state:f.enum(["publication_required","unconfigured","configured","approval_required","unavailable","expired"])}).strict(),Fo={id:P,ownerId:P,name:be,createdAt:ne,updatedAt:ne,version:f.number().int().positive(),permissions:f.array(vq)},abe=f.enum(["starting","running","stopping","stopped","failed"]),cbe=f.enum(["manual","idle","timeout","quota","capacity","payment"]),ube=f.object({state:f.enum(["pending","failed","complete"]),error:f.string().nullable()}),lbe=f.object({idleSeconds:f.number().int().min(60).max(2147483647).nullable().default(null),maxSeconds:f.number().int().min(60).max(2147483647).nullable().default(null)}).strict(),Aq=f.object({size:f.enum(["small","medium","large"]).default("small"),lifetime:lbe.default({idleSeconds:null,maxSeconds:null}),ssh:Hv.optional()}).strict(),tO={recipients:f.array(P).default([]),executors:f.array(P).default([]),custodyRevision:f.number().int().positive().nullable().default(null)},dbe=f.object({...Fo,kind:f.literal("variable"),data:f.object({...tO,bytes:f.number().int().nonnegative()})}),pbe=f.object({...Fo,kind:f.literal("connection"),data:f.object({...tO,methodId:f.string(),fields:f.record(f.string(),f.string()).default({}),settings:f.array(f.object({name:f.string(),label:f.string(),value:f.string()})).default([]),methodName:f.string(),methodKind:QD,http:IS.optional(),services:f.array(f.object({id:f.string(),name:be})).default([]),account:f.string(),accountId:f.string().nullable().default(null),accountVerified:f.boolean().default(!1),scopes:f.array(f.string()),scopesStatus:f.enum(["unknown","requested","reported"]).default("unknown"),outputs:f.array(f.string()),state:f.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:f.boolean().default(!1),appId:P.nullable(),generation:P.optional(),authorizationDigest:f.string().optional(),aws:_S.optional(),ovh:gf.optional()})}),fbe=f.object({...Fo,kind:f.literal("service"),data:ibe}),mbe=f.object({...Fo,kind:f.literal("method"),data:fl}),hbe=f.object({...Fo,kind:f.literal("app"),data:f.object({...tO,methodId:f.string(),clientId:f.string(),fields:f.record(f.string(),f.string()).default({}),generation:P.optional()})}),gbe=f.object({...Fo,kind:f.literal("object"),data:f.object({size:f.number().int().nonnegative(),contentType:f.string()})}),ybe=f.object({...Fo,kind:f.literal("environment"),data:Aq.extend({executorId:P.optional(),operatorId:P.optional(),driver:f.enum(["attached","managed"]).optional(),capabilities:f.array(f.string()).optional(),isolation:f.enum(["process","container"]).optional(),manifestDigest:f.string().optional(),processes:f.object({workingDirectory:f.string()}).optional(),ssh:ED.optional(),awsPrincipal:f.string().optional(),state:abe,connected:f.boolean(),deletion:ube.optional(),startedAt:ne.nullable(),stoppedAt:ne.nullable(),stopReason:cbe.nullable().default(null),lastActiveAt:ne,error:f.string().nullable()})}),vbe=f.object({...Fo,kind:f.literal("function"),data:ks.omit({program:!0}).extend({program:Eq.optional()})}),Sbe=f.object({...Fo,kind:f.literal("keyring"),data:f.object({revision:f.number().int().positive(),signature:f.string()})}),ml=f.discriminatedUnion("kind",[dbe,pbe,fbe,mbe,hbe,gbe,ybe,vbe,Sbe]),F7e=f.discriminatedUnion("kind",[f.object({kind:f.literal("service"),name:be,definition:bq}).strict(),f.object({kind:f.literal("method"),name:be,definition:fl}).strict(),f.object({kind:f.literal("environment"),name:be.optional(),options:Aq}).strict()]),G7e=f.object({version:f.number().int().positive(),name:be.optional(),definition:f.union([bq,fl]).optional()}).strict(),Sc=f.object({name:f.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Mt}).strict(),DS=Sc.extend({inputs:f.array(f.object({pointer:f.string(),label:f.string().min(1).max(100),secret:f.boolean().default(!1),multiline:f.boolean().default(!1),site:f.url().optional()}).strict()).max(16).default([])}),AS=f.object({ja:f.string(),en:f.string()}).strict(),rO=DS.extend({title:AS,execution:f.enum(["server","keyholder"]),configure:f.array(f.string()),environment:f.object({required:f.boolean(),reason:AS.nullable()}).strict()}),q7e=f.object({to:P.optional(),executionId:P.optional(),message:f.string().max(1e3).default(""),operations:f.array(DS).min(1).max(8).optional(),expiresInMinutes:f.number().int().min(1).max(1440).default(30)}).strict().superRefine((e,t)=>{!!e.executionId==!!e.operations&&t.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),xS=f.object({id:P,name:be}),Rq=f.discriminatedUnion("kind",[f.object({kind:f.literal("line"),subject:xS,relation:ZD,object:xS}),f.object({kind:f.literal("transfer"),item:xS,to:xS})]),V7e=f.object({id:P,executionId:P,from:Cs.pick({id:!0,name:!0}),to:Cs.pick({id:!0,name:!0}).nullable(),message:f.string(),purpose:f.enum(["input","approval"]),state:f.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:ne,expiresAt:ne,url:f.url(),code:f.string().optional(),returnUrl:f.url().nullable(),refreshUrl:f.url().nullable(),canRespond:f.boolean(),canCancel:f.boolean()}),K7e=f.object({id:P,name:be,publicKey:Ur,state:f.enum(["pending","approving","approved"]),principalId:P.nullable(),createdAt:ne,expiresAt:ne}),B7e=f.object({available:f.boolean(),required:f.boolean(),active:f.boolean(),payer:Cs.pick({id:!0,name:!0}).nullable()}),H7e=f.object({storageBytes:f.number().nonnegative(),storageLimit:f.number().positive(),computeSeconds:f.number().nonnegative(),computeLimit:f.number().positive(),month:f.string()}),W7e=f.object({id:f.string(),actorId:P.nullable(),action:f.string(),targetId:P.nullable(),createdAt:ne,details:Mt}),J7e=f.object({returnUrl:f.url().optional(),refreshUrl:f.url().optional()}).strict(),hl=e=>f.object({items:f.array(e),next:f.string().nullable().default(null)}),Z7e=f.object({id:P}),X7e=f.object({owner:P}),wbe=f.object({limit:f.coerce.number().int().min(1).max(200).default(100),after:f.string().optional()}),Y7e=wbe.extend({object:P.optional(),subject:P.optional(),relation:ZD.optional(),objectType:wq.optional()}).refine(e=>!!e.object!=!!e.subject,"Choose the object or the subject of the lines.");var _be=new TextEncoder,xbe=new TextDecoder,OS="ECDH-ES+A256KW",Iq="A256GCM",ft=e=>_be.encode(e),NS=e=>xbe.decode(e);function Ds(e){let t="";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function $q(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}async function wc(e,t,r){if(!t.length||new Set(t.map(n=>n.id)).size!==t.length)throw new Error("Recipients must be distinct and nonempty.");let i=new ff(e).setProtectedHeader({enc:Iq}).setAdditionalAuthenticatedData(ft(r));for(let n of t)i.addRecipient(await An(n.publicKey,OS)).setUnprotectedHeader({alg:OS,kid:n.id});return jo.parse(await i.encrypt())}async function bc(e,t,r,i){if(e.aad!==Ds(ft(i)))throw new Error("The encrypted content belongs to a different item.");let n=e.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let o=t instanceof CryptoKey?t:await An(t,OS);return(await LD({...e,recipients:[n]},o,{keyManagementAlgorithms:[OS],contentEncryptionAlgorithms:[Iq]})).plaintext}var yt=f.string().regex(/^[A-Za-z0-9_-]{43}$/),_t=f.string().min(100).max(4e6),Pq=Ur.extend({d:f.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Cq=f.object({encryption:Pq,signing:Pq}).strict(),vt=f.object({id:P,principalId:P,generation:f.number().int().positive(),previous:yt.nullable(),encryption:Ur,signing:Ur}).strict();function k(e){if(e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&!/[\uD800-\uDFFF]/u.test(e))return JSON.stringify(e);if(Array.isArray(e))return"["+Array.from(e,k).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(t=>{if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Use Unicode property names.");return JSON.stringify(t)+":"+k(e[t])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Tq(e){return HD(Ur.parse({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),"sha256")}async function te(e){return Ds(new Uint8Array(await crypto.subtle.digest("SHA-256",ft(k(e)))))}async function US(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",ft(k(e))));return"sha256:"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}async function Tt(e,t,r){let i=t instanceof CryptoKey?t:await An(t,"ES256");return new hf(ft(k(e))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(i)}async function nr(e,t,r,i){if(k(await _f(t,r,i))!==k(e))throw new Error("The signature does not authorize this content.")}async function _f(e,t,r){let i=await KD(e,await An(Ur.parse(t),"ES256"),{algorithms:["ES256"]});if(i.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(i.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(i.payload),o=JSON.parse(n);if(k(o)!==n)throw new Error("Sign canonical JSON content.");return o}var gl=f.object({binding:vt,signature:_t}).strict();async function Mi(e){let t=vt.parse(e);if(t.generation===1!=(t.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Tq(t.encryption)===await Tq(t.signing))throw new Error("Use separate encryption and signing keys.");await An(t.encryption,"ECDH-ES+A256KW"),await An(t.signing,"ES256")}async function LS(e){let{binding:t,signature:r}=gl.parse(e);return await Mi(t),await nr(t,r,t.signing,"key-binding"),t}var kq=f.object({ownerId:P,name:be,resourceId:P.optional(),version:f.number().int().positive().optional(),environmentIds:f.array(P).max(32).optional()}).strict(),dXe=kq.extend({value:f.literal("").optional()}),pXe=kq.extend({methodId:f.string().min(1).max(200),clientId:f.string().max(1e3),fields:f.record(f.string(),f.string()).optional(),clientSecret:f.literal("").optional()}),fXe=f.object({ownerId:P,name:be,definition:ks,resourceId:P.optional(),version:f.number().int().positive().optional()}).strict(),mXe=f.object({functionId:P,functionVersion:f.number().int().positive(),version:f.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:bf.default({expiresAt:null})}).strict(),Dq=f.object({ownerId:P,connectionId:P,environmentId:P}).strict(),hXe=f.object({ownerId:P,connectionId:P,version:f.number().int().positive(),users:f.array(P).max(32),expiresAt:f.iso.datetime().optional()}).strict(),gXe=f.object({ownerId:P,methodId:f.string().min(1).max(200),connectionId:P.optional(),name:be.optional(),appId:P.optional(),redirectUri:f.url().optional(),users:f.array(P).max(32).optional(),scopes:f.array(f.string().min(1).max(1e3)).max(200).optional(),methodDigest:f.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:f.string().max(1e3).optional(),fields:f.record(f.string(),f.string()).optional(),clientSecret:f.literal("").optional()}).strict(),Oq=f.object({ownerId:P,environmentId:P.optional(),operation:f.union([f.object({kind:f.literal("http"),request:yc}).strict(),vc.extend({kind:f.literal("command")}),f.object({kind:f.enum(["http","command"]),programId:P,programDigest:f.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:f.record(f.string(),be).default({})}).strict().superRefine((e,t)=>{e.environmentId||t.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),yXe=f.object({name:Sc.shape.name,title:AS,execution:f.enum(["server","keyholder"]),configure:f.array(f.string()),environment:rO.shape.environment,input:Mt}).strict(),vXe=f.object({id:P.optional(),operations:f.array(DS).min(1).max(8),responderId:P.optional(),message:f.string().max(1e3).default(""),expiresInMinutes:f.number().int().min(1).max(1440).default(1440)}).strict(),SXe=f.object({values:f.array(Mt).max(8).default([]),configuration:f.array(Mt).max(8).default([]),code:f.string().max(20).optional()}).strict(),Ebe=f.object({index:f.number().int().nonnegative(),invocation:Sc,approval:f.object({id:P,index:f.number().int().nonnegative()}).strict().optional(),continuation:f.object({kind:f.enum(["connection","run"]),id:P}).strict().nullable()}).strict(),Nq=f.object({id:P,actorId:P,ownerId:P,requests:f.array(P),steps:f.array(f.object({index:f.number().int().nonnegative(),name:Sc.shape.name,state:f.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:f.array(f.object({kind:f.enum(["run","function","process"]),id:P}).strict())}).strict()),creator:Cs.pick({id:!0,name:!0}),operations:f.array(rO),approval:f.object({requestId:P.nullable(),proposal:Rq.nullable()}).strict().nullable(),canContinue:f.boolean(),canCancel:f.boolean(),url:f.url(),code:f.string().optional(),error:f.object({code:f.string(),message:f.string()}).strict().nullable(),index:f.number().int().nonnegative(),state:f.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:f.enum(["approval","input","execution"]).nullable(),waiting:Ebe.nullable(),results:f.array(Nr.nullable()),createdAt:f.iso.datetime(),expiresAt:f.iso.datetime()}).strict(),Uq=f.object({id:P,index:f.number().int().nonnegative(),invocation:Sc,continuationId:P.optional()}).strict();var yl=f.url().refine(e=>{let t=new URL(e);return t.origin===e&&!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.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"},Abe=f.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),Mq=e=>e===ge.executionResult?14e5:1e6,Q={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"},xf=f.enum([Q.http,Q.command,Q.function,Q.connect,Q.refresh,Q.revoke]);var Rbe={[ge.value]:[Q.http,Q.command,Q.function],[ge.tokenSet]:[Q.http,Q.command,Q.function,Q.refresh,Q.revoke],[ge.clientCredential]:[Q.connect,Q.refresh,Q.revoke],[ge.executionResult]:[]},nO=e=>Rbe[e];var iO=e=>e===ge.tokenSet,Ibe=f.object({id:P,digest:yt}).strict(),$be=f.object({actor:vt,executor:vt,operations:f.array(xf).min(1).max(6),functionDigests:f.array(yt).max(100).default([]),origins:f.array(yl).max(100).default([]),callerProgram:f.boolean().default(!1),expiresAt:ne}).strict(),Pbe=f.object({function:Ibe,executor:vt,operations:f.array(xf).min(1).max(6),expiresAt:ne.nullable()}).strict(),Tbe=f.union([$be,Pbe]);function Go(e,t=Date.now()){return e.expiresAt===null||Date.parse(e.expiresAt)>t}function vl(e){return e.expiresAt===null?1/0:Date.parse(e.expiresAt)}var qo=f.object({format:f.literal(2),origin:yl,id:P,ownerId:P,contentType:Abe,revision:f.number().int().positive(),authorities:f.array(vt).min(1).max(100),readers:f.array(vt).min(1).max(100),grants:f.array(Tbe).max(100),observers:f.array(P).max(100).optional(),producers:f.array(f.object({executor:vt,runId:P,expiresAt:ne,materialRevision:f.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),Lq=f.object({ownerId:P,authorities:f.array(vt).min(1).max(100)}).strict(),zq=f.object({origin:yl,id:P,revision:f.number().int().positive(),from:Lq,to:Lq,policyDigest:yt,previous:yt.nullable(),signerId:P}).strict(),Cbe=zq.extend({signature:_t}),oO=f.array(Cbe).max(16),Ef=f.object({policy:qo,authorityId:P,signature:_t,lineage:oO.optional()}).strict(),ir=f.object({policy:qo,authorityId:P,authorization:_t,lineage:oO.optional(),materialRevision:f.number().int().positive(),updatedAt:ne,creationRunId:P.nullable(),metadata:Mt,sealed:jo,signerId:P,signature:_t}).strict(),_c=e=>({ownerId:e.ownerId,authorities:e.authorities});async function jq(e,t=[]){let r;for(let i of t){let{signature:n,...o}=i;if(i.origin!==e.origin||i.id!==e.id||i.revision>e.revision||r&&(i.revision<=r.revision||k(r.to)!==k(i.from))||i.previous!==(r?await te(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=i.from.authorities.find(a=>a.id===i.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await nr(o,n,s.signing,"authority-handoff"),r=i}if(r&&k(r.to)!==k(_c(e)))throw new Error("Use the authorities approved by the latest handoff.")}function sO(e){let t=e.policy.authorities.find(n=>n.id===e.authorityId);if(t)return t;let r=e.lineage?.at(-1),i=r?.revision===e.policy.revision?r.from.authorities.find(n=>n.id===e.authorityId):void 0;if(!i||i.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return i}function MS(e,t){if(e.id!==t.policy.id||e.origin!==t.policy.origin||e.contentType!==t.policy.contentType)return!1;let r=k(_c(e));return r===k(_c(t.policy))?!0:!!t.lineage?.some(i=>i.revision>e.revision&&k(i.from)===r)}async function Fq(e,t,r,i){let n=[...e?.lineage??[]];if(e&&k(_c(e.policy))!==k(_c(t))){if(await sn(e),!e.policy.authorities.some(s=>k(s)===k(r))||e.policy.id!==t.id||e.policy.origin!==t.origin||e.policy.contentType!==t.contentType||t.revision!==e.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let o=zq.parse({origin:t.origin,id:t.id,revision:t.revision,from:_c(e.policy),to:_c(t),policyDigest:await te(t),previous:n.length?await te(n.at(-1)):null,signerId:r.id});n.push({...o,signature:await Tt(o,i.signing,"authority-handoff")})}return n.length?{lineage:oO.parse(n)}:{}}async function zS(e){let t=qo.parse(e),r=[...t.authorities,...t.readers,...t.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...t.producers.map(n=>n.executor)],i=new Map;for(let n of r){await Mi(n);let o=k(n);if(i.has(n.id)&&i.get(n.id)!==o)throw new Error("Each key binding must identify the same keys throughout a policy.");i.set(n.id,o)}for(let n of[t.readers,t.authorities])if(new Set(n.map(o=>o.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of t.authorities)if(!t.readers.some(o=>o.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of t.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(o=>!nO(t.contentType).includes(o)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(o=>o!==Q.function&&o!==Q.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(o=>o===Q.http||o===Q.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(Q.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return t}function jS(e){return[...new Map([...e.readers,...e.grants.map(t=>t.executor)].map(t=>[t.id,t])).values()]}async function Ns(e,t){return k({purpose:"resource",policyDigest:await te(e),materialRevision:t})}async function Af(e,t,r,i,n,o,s){if(e.byteLength>Mq(t.contentType))throw new Error("The content exceeds its storage limit.");let a=await zS(t),c=await Fq(s,a,i,n);if(!a.authorities.some(m=>k(m)===k(i))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(a,r)),l={policy:a,...c,authorityId:i.id,authorization:await Tt(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:o??(a.contentType===ge.value?{bytes:e.byteLength}:{}),sealed:u,signerId:i.id},d=ir.parse({...l,signature:await Tt(l,n.signing,"resource")});return await sn(d),d}async function sn(e){let t=ir.parse(e),{signature:r,...i}=t;await zS(t.policy),await jq(t.policy,t.lineage);let n=sO(t),o=t.lineage?.at(-1);if(o?.revision===t.policy.revision&&o.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");await nr(t.policy,t.authorization,n.signing,"access-policy");let s=(t.signerId===n.id?n:void 0)??t.policy.authorities.find(u=>u.id===t.signerId)??t.policy.producers.find(u=>u.executor.id===t.signerId&&u.runId===t.creationRunId&&u.materialRevision===t.materialRevision&&(t.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(t.updatedAt)))?.executor??(iO(t.policy.contentType)?t.policy.grants.find(u=>u.executor.id===t.signerId&&u.operations.includes(Q.refresh)&&Go(u,Date.parse(t.updatedAt)))?.executor:void 0);if(!s||Date.parse(t.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await nr(i,r,s.signing,"resource");let a=jS(t.policy).map(u=>u.id).sort(),c=t.sealed.recipients.map(u=>u.header.kid).sort();if(k(a)!==k(c)||t.sealed.aad!==Ds(ft(await Ns(t.policy,t.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return t}async function Gq(e,t,r,i,n=e.metadata){let o=await sn(e);if(!iO(o.policy.contentType)||!(o.policy.authorities.some(m=>k(m)===k(r))||o.policy.grants.some(m=>k(m.executor)===k(r)&&m.operations.includes(Q.refresh)&&Go(m))))throw new Error("This executor cannot renew this connection.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=o.materialRevision+1,a=await wc(t,jS(o.policy).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(o.policy,s)),{signature:c,...u}=o,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await Tt(l,i.signing,"resource")};return await sn(d),d}async function FS(e,t,r,i){let n=await zS(e);if(!n.authorities.some(s=>k(s)===k(t)))throw new Error("Only an authority can approve this policy.");let o={policy:n,...await Fq(i,n,t,r),authorityId:t.id,signature:await Tt(n,r.signing,"access-policy")};return await Us(o),o}async function Us(e){let t=Ef.parse(e);await zS(t.policy),await jq(t.policy,t.lineage);let r=t.lineage?.at(-1);if(r?.revision===t.policy.revision&&r.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");let i=t.policy.authorities.find(n=>n.id===t.authorityId);if(!i)throw new Error("The policy must be signed by an authority.");return await nr(t.policy,t.signature,i.signing,"access-policy"),t}async function Rf(e,t,r,i,n,o){let s=await Us(t),{policy:a}=s,c=a.producers.find(m=>m.runId===r&&k(m.executor)===k(i)&&(a.contentType===ge.executionResult||Date.parse(m.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(e.byteLength>Mq(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(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:o,sealed:u,signerId:i.id},d={...l,signature:await Tt(l,n.signing,"resource")};return await sn(d),d}async function If(e,t,r){let i=await sn(e);if(!i.policy.readers.some(n=>k(n)===k(t)))throw new Error("This identity cannot reveal the content.");return bc(i.sealed,r,t.id,await Ns(i.policy,i.materialRevision))}var kbe=f.object({id:P,policyDigest:yt,materialRevision:f.number().int().positive(),authorizationDigest:yt.optional()}).strict();async function aO(e,t){return t.id===e.policy.id&&t.policyDigest===await te(e.policy)&&(t.authorizationDigest===void 0||t.authorizationDigest===e.metadata.authorizationDigest)&&(t.materialRevision===e.materialRevision||iO(e.policy.contentType)&&t.authorizationDigest!==void 0&&t.authorizationDigest===e.metadata.authorizationDigest&&e.materialRevision>=t.materialRevision)}var GS=f.object({format:f.literal(2),id:P,origin:yl,ownerId:P,approval:f.object({id:P,index:f.number().int().min(0).max(7)}).strict().optional(),operationContext:Uq.optional(),actor:vt,environmentId:P,executor:vt,environmentDigest:yt,operation:xf,functionDigest:yt.nullable(),functionId:P.optional(),operationDigest:yt,sources:f.array(kbe).max(100),resultRecipients:f.array(vt).min(1).max(100),resultApproval:Ef.optional(),createdAt:ne,expiresAt:ne}).strict(),qS=f.object({intent:GS,signature:_t,sealed:jo}).strict();async function xc(e,t){return k({purpose:"run-"+t,origin:e.origin,id:e.id,intentDigest:await te(e)})}async function qq(e,t,r){if(GS.parse(e),await te(t)!==e.operationDigest)throw new Error("The operation does not match the execution intent.");let i={intent:e,sealed:await wc(ft(k(t)),[{id:e.executor.id,publicKey:e.executor.encryption}],await xc(e,"input"))};return qS.parse({...i,signature:await Tt(i,r.signing,"run")})}async function Dbe(e,t=Date.now()){let r=qS.parse(e),{signature:i,...n}=r;await nr(n,i,r.intent.actor.signing,"run");let{intent:o}=r,s=Date.parse(o.createdAt),a=Date.parse(o.expiresAt);if(s>t+3e4||a<=t||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(o.sources.map(c=>c.id)).size!==o.sources.length||new Set(o.resultRecipients.map(c=>c.id)).size!==o.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(o.resultApproval){let c=await Us(o.resultApproval),u=c.policy;if(c.authorityId!==o.actor.id||u.id!==o.id||u.origin!==o.origin||u.ownerId!==o.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>k(l)===k(o.actor))||k(u.readers)!==k(o.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==o.id||k(u.producers[0].executor)!==k(o.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!==o.executor.id||r.sealed.aad!==Ds(ft(await xc(o,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function Vq(e,t,r){let i=await Dbe(e);if(k(i.intent.executor)!==k(t))throw new Error("This operation belongs to another executor.");let n=await bc(i.sealed,r.encryption,t.id,await xc(i.intent,"input")),o=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(o);if(k(s)!==o||await te(s)!==i.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:i.intent,operation:s}}async function Os(e,t,r={}){let i=await sn(e),n=i.policy,o=t.sources.find(c=>c.id===n.id);if(!o||t.origin!==n.origin||!await aO(i,o))throw new Error("The input changed after this execution was authorized.");if(k(t.actor)===k(t.executor)&&n.readers.some(c=>k(c)===k(t.actor)))return i;if(!n.grants.filter(c=>("actor"in c?k(c.actor)===k(t.actor):c.function.id===t.functionId&&c.function.digest===t.functionDigest)&&k(c.executor)===k(t.executor)&&c.operations.includes(t.operation)&&Go(c,r.now)&&vl(c)>=Date.parse(t.expiresAt)).some(c=>"function"in c?t.operation===Q.function||t.operation===Q.refresh:t.operation===Q.function&&!c.callerProgram&&(!t.functionDigest||!c.functionDigests.includes(t.functionDigest))||!r.destinationPending&&c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:t.operation!==Q.command&&t.operation!==Q.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return i}async function Ec(e,t,r,i={}){let n=i.destination;await Os(e,t,{now:i.now,...typeof n=="function"?{destinationPending:!0}:{destination:n}});let o=await bc(e.sealed,r.encryption,t.executor.id,await Ns(e.policy,e.materialRevision));return typeof n=="function"&&await Os(e,t,{now:i.now,destination:n(o)}),o}var Ac=5,zi=1,cO=f.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Kq=f.object({format:f.literal(3),id:P,origin:yl,ownerId:P,name:be,executor:vt,operatorId:P,driver:f.literal("attached"),capabilities:f.array(xf).min(1).max(6),functionVersion:f.number().int().positive().optional(),httpVersion:f.number().int().positive().optional(),resultVersion:f.literal(1).optional(),isolation:f.enum(["process","container"]),commandImage:f.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),functionImage:f.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:cO.optional(),revision:f.number().int().positive()}).strict(),uO=f.object({manifest:Kq,signature:_t}).strict();async function lO(e,t){let r=Kq.parse(e),i={manifest:r,signature:await Tt(r,t.signing,"environment")};return await wl(i),i}async function wl(e){let t=uO.parse(e),{manifest:r}=t;if(await Mi(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(Q.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");return await nr(r,t.signature,r.executor.signing,"environment"),t}async function bl(e,t){let{manifest:r}=await wl(e);if(t.environmentId!==r.id||t.origin!==r.origin||t.environmentDigest!==await te(r)||k(t.executor)!==k(r.executor)||!r.capabilities.includes(t.operation)||t.operation===Q.function&&r.functionVersion!==Ac)throw new Error("This environment does not authorize the requested execution.")}var VS=f.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),KS=f.object({ok:f.boolean(),result:Nr.nullable(),error:f.object({code:f.string().max(100),message:f.string().max(1e3)}).nullable()}).strict(),Bq={id:P,intentDigest:yt,executorId:P,state:f.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ne},Hq=f.object({...Bq,sealed:jo,signature:_t}).strict(),Wq=f.object({...Bq,format:f.literal(2),accessDigest:yt,proofDigest:yt,approval:Ef,content:ir,previousDigest:yt.optional(),previous:Hq.optional(),signature:_t}).strict(),$f=f.union([Hq,Wq]),Obe=f.object({result:KS,proof:_t}).strict(),Jq=e=>{let{signature:t,content:r,approval:i,previous:n,...o}=e;return o};async function dO(e,t,r,i,n,o){await Us(n);let s={format:2,id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:o?.finishedAt??new Date().toISOString(),accessDigest:await te(n),...o?{previousDigest:await te(o)}:{}},a=await Tt({...s,resultDigest:await te(r)},i.signing,"execution-result"),c=ft(k({result:KS.parse(r),proof:a}));if(c.byteLength>14e5)throw new Sl;let u=await Rf(c,n,e.id,e.executor,i,{bytes:c.byteLength}),l={...s,proofDigest:await te(a)},d=Wq.parse({...l,approval:n,content:u,...o?{previous:o}:{},signature:await Tt(l,i.signing,"receipt")});return await pO(d,e),d}var Sl=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function _l(e,t,r,i){let n=KS.parse(r);if(t==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(e.resultApproval)return dO(e,t,n,i,e.resultApproval);let o=ft(k(n));if(o.byteLength>14e5)throw new Sl;let s=await wc(o,e.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await xc(e,"result")),a={id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:new Date().toISOString(),sealed:s};return $f.parse({...a,signature:await Tt(a,i.signing,"receipt")})}async function pO(e,t){let r=$f.parse(e);if("content"in r){await nr(Jq(r),r.signature,t.executor.signing,"receipt");let o=await Us(r.approval),s=o.policy;if(r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.accessDigest!==await te(o)||o.authorityId!==t.actor.id||!s.authorities.some(a=>k(a)===k(t.actor))||s.id!==t.id||s.origin!==t.origin||s.ownerId!==t.ownerId||s.contentType!==ge.executionResult||s.grants.length||t.resultApproval&&k(t.resultApproval)!==k(o))throw new Error("The result does not belong to the requested execution.");if(!t.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await te(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await pO(r.previous,t),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 sn(r.content),!MS(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(t.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:i,...n}=r;if(await nr(n,i,t.executor.signing,"receipt"),r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.sealed.aad!==Ds(ft(await xc(t,"result")))||k(r.sealed.recipients.map(o=>o.header.kid).sort())!==k(t.resultRecipients.map(o=>o.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function Zq(e,t,r,i){if(await pO(e,t),"content"in e){if(!e.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await bc(e.content.sealed,i.encryption,r,await Ns(e.content.policy,e.content.materialRevision)),a=Obe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await te(a.proof)!==e.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=Jq(e);if(await nr({...u,resultDigest:await te(a.result)},a.proof,t.executor.signing,"execution-result"),e.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await bc(e.sealed,i.encryption,r,await xc(t,"result")),o=KS.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(e.state==="succeeded"!==o.ok)throw new Error("The encrypted result does not match its completion state.");return o}var Nbe=f.enum(["http","command","function","connect","refresh","revoke"]),Rc=f.object({id:P,ownerId:P,actorId:P,environmentId:P,kind:Nbe,state:VS,intent:GS,requestSignature:_t,receipt:$f.nullable(),error:f.string().nullable(),createdAt:ne,startedAt:ne.nullable(),finishedAt:ne.nullable()}).strict(),BS=f.object({name:be,approval:Ef}).strict(),Xq=f.object({kind:f.literal("function"),functionId:P,definition:ks,arguments:Mt.default({}),outputs:f.record(f.string(),BS).default({})}).strict(),Ic=f.discriminatedUnion("kind",[f.object({kind:f.literal("http"),request:yc,save:f.record(f.string(),BS).default({})}).strict(),f.object({kind:f.literal("command"),...vc.shape}).strict(),f.object({kind:f.enum(["connect","refresh","revoke"]),input:Nr}).strict()]);var Ube=f.object({requestedAt:ne,readyAt:ne}).strict(),Lbe=f.object({email:f.boolean(),environments:f.boolean(),ssh:f.boolean(),storage:f.boolean(),payments:f.boolean()}),Yq=f.object({principal:Cs.nullable(),credentialId:P.nullable(),wrappedKey:Sf.nullable(),requestId:P.nullable(),keyReset:Ube.nullable(),server:f.object({name:be}),features:Lbe,principals:f.array(Cs)}),UXe=f.object({email:f.email().max(254),returnTo:f.string().max(2048).optional(),locale:yq.default("ja"),principalId:P.optional()}).strict(),LXe=f.object({intent:f.enum(["register","authenticate"]),name:be.optional(),principalId:P.optional(),credentialId:P.optional(),returnTo:f.string().max(2048).optional()}).strict(),MXe=f.object({challengeId:P,credential:f.json(),publicKey:Ur.optional(),existingPublicKey:Ur.optional(),wrappedKey:Sf.optional()}).strict(),zXe=f.object({publicKey:Ur,wrappedKey:Sf}).strict();var HS=class extends Error{constructor(r,i,n){super(n);this.code=r;this.status=i}code;status},WS=class{constructor(t){this.identity=t}identity;async response(t,r={}){if(!t.startsWith("/api/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Use a path beginning with /api/.");let i=new URL(t,this.identity.origin);if(i.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(i,{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 o;try{o=f.object({error:f.object({code:f.string(),message:f.string()})}).parse(await n.json())}catch{throw new HS("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new HS(o.error.code,n.status,o.error.message)}return n}async json(t,r={},i){let n=await this.response(t,r),o=n.status===204?null:await n.json();return i?i.parse(o):o}async session(){return this.json("/api/session",{},Yq)}};import{chmod as Mbe,lstat as zbe,mkdir as jbe,open as mO,readFile as Fbe,rename as Gbe,rm as qbe}from"node:fs/promises";import{dirname as Vbe,join as hO,resolve as Kbe}from"node:path";import{homedir as Bbe}from"node:os";import{randomUUID as Hbe}from"node:crypto";var eV=f.object({origin:f.url(),principalId:f.uuid(),token:f.string().min(20),keys:Cq.nullable(),binding:vt.nullable()}).strict().refine(e=>!!e.keys==!!e.binding&&(!e.binding||e.binding.principalId===e.principalId),"Use the keys bound to this identity."),Wbe=f.object({current:f.uuid(),identities:f.array(eV).min(1)}).strict().refine(e=>e.identities.some(t=>t.principalId===e.current),"The current identity is missing.");function gO(){return hO(process.env.XDG_CONFIG_HOME||hO(Bbe(),".config"),"foundation","identity.json")}function fO(e=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let t;try{t=new URL(e)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return t.origin}async function Jbe(){try{let e=gO(),t=await zbe(e);if(!t.isFile()||t.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&t.mode&63&&await Mbe(e,384),Wbe.parse(JSON.parse(await Fbe(e,"utf8")))}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function tV(e,t){let r=process.env.FOUNDATION_TOKEN,i=t||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await Jbe(),o;if(n){if(o=n.identities.find(a=>a.principalId===(i??n.current)),i&&!o&&!r)throw new Error("No saved identity has principal "+i+". Run foundation identity list.")}else if(i&&!r)throw new Error("Run foundation login to sign in on this machine.");let s=fO(e||process.env.FOUNDATION_ORIGIN||o?.origin);if(r){if(e&&process.env.FOUNDATION_ORIGIN&&s!==fO(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let a=process.env.FOUNDATION_PRINCIPAL_ID,c=process.env.FOUNDATION_PRIVATE_KEYS,u=process.env.FOUNDATION_KEY_BINDING;if(!a)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return eV.parse({origin:s,principalId:a,token:r,keys:c?JSON.parse(Buffer.from(c,"base64url").toString("utf8")):null,binding:u?JSON.parse(Buffer.from(u,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!o)throw new Error("Run foundation login to sign in on this machine.");if(s!==fO(o.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...o,origin:s}}async function Qq(e){if(process.platform==="win32")return;let t=await mO(e,"r");try{await t.sync()}finally{await t.close()}}async function yO(e,t,r){let i=Kbe(e),n=Vbe(i);if(await jbe(n,{recursive:!0,mode:448}),!r){let s=await mO(i,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Qq(n);return}let o=hO(n,".foundation-"+Hbe());try{let s=await mO(o,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Gbe(o,i),await Qq(n)}finally{await qbe(o,{force:!0})}}import{mkdir as Ihe}from"node:fs/promises";import{join as Tj}from"node:path";import{setTimeout as pWe}from"node:timers/promises";import{dirname as $Ue,join as T4}from"node:path";function Ls(e){switch(e.kind){case"oauth":let t=e.config.application;return{family:"oauth",application:t,requiresApp:t==="required",browserAuthorization:e.config.grantType!=="client_credentials",revocable:e.config.revoke?.tokenOnly===!0,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"ovh":{let r=e.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function rV(e,t){return[...new Set([...e.required??[],...t??e.default])]}function xl(e){return Ls(e).requiresApp}var Zbe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),nV=Mt.refine(e=>Object.keys(e).every(t=>!Zbe.has(t)),"Keep method-specific facts separate from common facts."),Ms=f.object({accountId:f.string().max(2e3).nullable(),accountName:f.string().max(2e3),accountVerified:f.boolean(),scopes:f.array(f.string().max(1e3)).max(200),scopesStatus:f.enum(["unknown","requested","reported"]),authorization:nV,details:nV}).strict();function vO(e){if(e.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let t="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:e.oauth?.account??"",accountName:e.oauth?.accountName??"",accountVerified:e.oauth?.accountVerified??!1,scopes:t??e.oauth?.scopes??[],scopesStatus:t?"requested":e.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function El(e){if(e.method.kind!=="token"&&e.method.kind!=="approval"||!e.fields)throw new Error("Use input credential material.");return"facts"in e&&e.facts?Ms.parse(e.facts):Ms.parse({accountId:null,accountName:e.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function SO(e){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let t="ovh"in e?e.ovh:void 0;if(!t){let r="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return Ms.parse({accountId:t.user?t.account+"/"+t.user:t.account,accountName:t.account+(t.user?" / "+t.user:""),accountVerified:!0,scopes:t.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:t},details:{ovh:t}})}function wO(e){if(e.method.kind!=="aws"||!e.aws)throw new Error("Use AWS connection material.");return Ms.parse({accountId:e.aws.identity?dl(e.aws.identity.arn):null,accountName:e.aws.identity?e.aws.identity.accountId+" / "+e.aws.identity.arn.split(":").at(-1):"",accountVerified:!!e.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:mq(e.aws)},details:{aws:hq(e.aws)}})}var Xbe={oauth:vO,token:El,aws:wO,ovh:SO,approval:El};function Pf(e){return Xbe[e.method.kind](e)}var GV=lt(AV(),1);var Ho=class extends Error{template;position;hint;constructor(e,t,r,i){super(`${i} (at position ${t}): ${r}`),this.template=e,this.position=t,this.hint=r,this.name="TemplateParseError"}},__e=class extends Ho{constructor(e,t){super(e,t,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},x_e=class extends Ho{constructor(e,t){super(e,t,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},E_e=class extends Ho{constructor(e,t){super(e,t,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},A_e=class extends Ho{char;constructor(e,t,r){super(e,t,`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"}},R_e=class extends Ho{constructor(e,t){super(e,t,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},I_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`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"}},$_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},ow=class extends Ho{varSpec;constructor(e,t,r,i,n){super(e,t,r,i),this.varSpec=n,this.name="InvalidVarSpecError"}},PO=class extends ow{constructor(e,t){super(e,t,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},P_e=class extends ow{offendingChar;constructor(e,t,r,i){super(e,t,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${i}' or pct-encode it.`,`Invalid character '${i}' in varname`,r),this.offendingChar=i,this.name="InvalidVarNameError"}},T_e=class extends ow{prefix;constructor(e,t,r,i){super(e,t,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${i}'`,r),this.prefix=i,this.name="InvalidPrefixError"}},RV=class extends ow{constructor(e,t){super(e,t,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},C_e=class extends Ho{char;constructor(e,t,r){super(e,t,"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"}},k_e=class extends Error{variableName;hint;constructor(e,t,r){super(`${r} for '${e}': ${t}`),this.variableName=e,this.hint=t,this.name="TemplateExpansionError"}},D_e=class extends k_e{prefix;valueType;constructor(e,t,r){super(e,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${t}' is not applicable to ${r} values`),this.prefix=t,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},O_e=["","+",".","/",";","?","&","#"],DV={"":{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}},N_e=new TextEncoder,IV="0123456789ABCDEF",$V=e=>Fs(wr(48,57),wr(65,70),wr(97,102))(e.charCodeAt(0)),Df=(e,t)=>e[t]==="%"&&t+2<e.length&&$V(e[t+1])&&$V(e[t+2]);function TO(e,t){let r=e[t];return r==null?0:Fs(OV,NV,Pc("_"))(r)?1:Df(e,t)?3:0}function U_e(e,t){if(Df(e,t))return 3;let{char:r,size:i}=Of(e,t);return M_e(r)?i:0}function Of(e,t){let r=e.codePointAt(t);if(r==null)return{char:"",size:0};let i=r>65535?2:1;return{char:e.slice(t,t+i),size:i}}var OO=e=>t=>{let r="";for(let i=0;i<t.length;){if(e&&Df(t,i)){r+=t.slice(i,i+3),i+=3;continue}let{char:n,size:o}=Of(t,i);r+=Fs(UV,s=>e&&L_e(s))(n)?n:LV(n),i+=o}return r};function Il(e){let t="";for(let r=0;r<e.length;){if(Df(e,r)){t+=e.slice(r,r+3),r+=3;continue}let{char:i,size:n}=Of(e,r);t+=UV(i)?i:LV(i),r+=n}return t}function Cf(e,t){let r="",i=0;for(let n=0;n<e.length&&i<t;i++){if(Df(e,n)){r+=e.slice(n,n+3),n+=3;continue}let{char:o,size:s}=Of(e,n);r+=o,n+=s}return r}var OV=e=>Fs(wr(65,90),wr(97,122))(e.charCodeAt(0)),NV=e=>wr(48,57)(e.charCodeAt(0)),UV=e=>Fs(OV,NV,t=>"-._~".includes(t))(e),L_e=e=>":/?#[]@!$&'()*+,;=".includes(e),M_e=e=>z_e(e.codePointAt(0)),z_e=e=>e!=null&&Fs(Pc(33),wr(35,36),Pc(38),wr(40,59),Pc(61),wr(63,91),Pc(93),Pc(95),wr(97,122),Pc(126),j_e,F_e)(e);function j_e(e){if(e<65536)return Fs(wr(160,55295),wr(63744,64975),wr(65008,65519))(e);if(e>983037)return!1;let t=e%65536;return t<=65533&&(e<917504||t>=4096)}var F_e=e=>Fs(wr(57344,63743),wr(983040,1048573),wr(1048576,1114109))(e),LV=e=>Array.from(N_e.encode(e)).map(t=>`%${IV[t>>4]}${IV[t&15]}`).join(""),wr=(e,t)=>r=>e<=r&&r<=t,Pc=e=>t=>e===t,Fs=(...e)=>t=>e.some(r=>r(t));function MV(e,t,r){return e.map(i=>i.kind==="literal"?i.text:G_e(i.vars,i.operator,t,r)).join("")}function G_e(e,t,r,i){let n=DV[t],o=e.flatMap(s=>q_e(s,r[s.name],n,i));return o.length<1?"":`${n.first}${o.join(n.sep)}`}function q_e(e,t,r,i){if(t==null)return[];if(X_e(t)){let n=H_e(t,r.allowReserved);return n.length<1?[]:PV(e,"list",i)?K_e(e,n,r):[]}if(Z_e(t)){let n=W_e(t,r.allowReserved);return n.length<1?[]:PV(e,"associative",i)?B_e(e,n,r):[]}return V_e(e,t,r)}function V_e(e,t,r){let i=String(t),n=e.prefix==null?i:Cf(i,e.prefix),o=OO(r.allowReserved)(n);return r.named?[kf(Il(e.name),o,r)]:[o]}function K_e(e,t,r){let i=Il(e.name);if(e.explode)return r.named?t.map(o=>kf(i,o,r)):[...t];let n=t.join(",");return r.named?[kf(i,n,r)]:[n]}function B_e(e,t,r){if(e.explode)return t.map(([n,o])=>kf(n,o,r));let i=t.flat(1).join(",");return r.named?[kf(Il(e.name),i,r)]:[i]}var kf=(e,t,r)=>t===""?`${e}${r.ifEmpty}`:`${e}=${t}`,H_e=(e,t)=>e.filter(r=>r!=null).map(String).map(OO(t)),W_e=(e,t)=>Object.entries(e).map(([r,i])=>[r,J_e(i)]).filter(([,r])=>r!=null).map(r=>r.map(OO(t)));function J_e(e){if(e==null)return null;if(!Array.isArray(e))return String(e);let t=e.filter(r=>r!=null).map(String);return t.length<1?null:t.join(",")}var Z_e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X_e=e=>Array.isArray(e);function PV(e,t,{report:r,strict:i}){if(e.prefix==null)return!0;let n=new D_e(e.name,e.prefix,t);if(r(n),i)throw n;return!1}function Y_e(e,t,r){return CO(e,t,r,0,0,{})}function CO(e,t,r,i,n,o){if(i>=e.length){if(n!==t.length)return null;let a=Axe(o);return MV(e,a,r)===t?a:null}let s=e[i];if(s.kind==="literal")return t.startsWith(s.text,n)?CO(e,t,r,i+1,n+s.text.length,o):null;for(let a of Q_e(e,t,i,n)){let c=t.slice(n,a);for(let u of txe(s.vars,s.operator,c)){let l=NO(o,u);if(l==null)continue;let d=CO(e,t,r,i+1,a,l);if(d!=null)return d}}return null}function*Q_e(e,t,r,i){let n=e.slice(r+1).find(o=>o.kind==="literal"&&o.text!=="");if(n==null||n.kind!=="literal"){yield*exe(t.length,i);return}for(let o=t.indexOf(n.text,i);o>=0;o=t.indexOf(n.text,o+1))yield o}function*exe(e,t){for(let r=e;r>=t;r--)yield r}function*txe(e,t,r){if(r===""){yield*rxe(e,t);return}let i=DV[t];if(!r.startsWith(i.first))return;let n=r.slice(i.first.length);yield*i.named?dxe(e,i,n):nxe(e,i,n)}var rxe=(e,t)=>(t===""||t==="+")&&e.length===1?[js(e[0],"")]:[{}],nxe=(e,t,r)=>kO(e,t,UO(r,t.sep),0,0);function*kO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of ixe(o,t,r,n))for(let a of kO(e,t,r,i+1,s.index)){let c=NO(s.bindings,a);c!=null&&(yield c)}yield*kO(e,t,r,i+1,n)}function*ixe(e,t,r,i){if(i>=r.length)return;let n=r.length-i;for(let o=1;o<=n;o++){let s=r.slice(i,i+o);for(let a of oxe(e,t,s))yield{bindings:a,index:i+o}}}function*oxe(e,t,r){let i=zV(e,t,r.join(t.sep));if(e.prefix!=null){yield*i;return}e.explode&&r.length>0&&(yield*sxe(e,t,r)),yield*i}function*sxe(e,t,r){let i=jV(r,t.allowReserved);if(i==null)return;let n=axe(r,t);n!=null&&(yield js(e,n)),yield js(e,i)}var axe=(e,t)=>cxe(e.join(t.sep),t);function cxe(e,t){let r=[];for(let i=0;i<e.length;){let n=e.indexOf("=",i);if(n<0)return null;let o=n+1,s=uxe(e,o,t.sep),a=Bo(e.slice(i,n),t.allowReserved),c=Bo(e.slice(o,s),t.allowReserved);if(a==null||c==null)return null;r.push([a,c]),i=s+t.sep.length}return r.length<1?null:Object.fromEntries(r)}function uxe(e,t,r){for(let i=t;i<e.length;i++)if(lxe(e,i,r))return i;return e.length}var lxe=(e,t,r)=>{if(!e.startsWith(r,t))return!1;let i=t+r.length;for(let n=i;n<e.length;n++){if(e[n]==="=")return n>i;if(e.startsWith(r,n))return!1}return!1};function*zV(e,t,r){let i=Bo(r,t.allowReserved);if(i==null)return;let n=js(e,i);if(e.prefix!=null){yield n;return}let o=UO(r,",");if(o.length<2){yield n;return}let s=jV(o,t.allowReserved);if(s==null){yield n;return}let a=o.length%2===0?wxe(o,t.allowReserved):null;a!=null&&(yield js(e,a)),yield js(e,s),yield n}var dxe=(e,t,r)=>DO(e,t,UO(r,t.sep).map(Sxe),0,0);function*DO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of pxe(o,t,r,n,e))for(let a of DO(e,t,r,i+1,s.index)){let c=NO(s.bindings,a);c!=null&&(yield c)}yield*DO(e,t,r,i+1,n)}function*pxe(e,t,r,i,n){if(!(i>=r.length)){if(e.explode&&e.prefix==null){yield*mxe(e,t,r,i,n);return}yield*fxe(e,t,r,i)}}function*fxe(e,t,r,i){let n=r[i];if(n.name===Il(e.name))for(let o of zV(e,t,n.value))yield{bindings:o,index:i+1}}function*mxe(e,t,r,i,n){yield*hxe(e,t,r,i),yield*yxe(e,t,r,i,n)}function*hxe(e,t,r,i){let n=[...gxe(Il(e.name),t,r,i)];n.length>0&&(yield{bindings:js(e,n),index:i+n.length})}function*gxe(e,t,r,i){for(let n=i;n<r.length&&r[n].name===e;n++){let o=Bo(r[n].value,t.allowReserved);if(o==null)return;yield o}}function*yxe(e,t,r,i,n){let o=[...vxe(t,r,i,new Set(n.map(s=>Il(s.name))))];o.length>0&&(yield{bindings:js(e,Object.fromEntries(o)),index:i+o.length})}function*vxe(e,t,r,i){for(let n=r;n<t.length;n++){let o=t[n];if(n>r&&i.has(o.name))return;let s=Bo(o.name,e.allowReserved),a=Bo(o.value,e.allowReserved);if(s==null||a==null)return;yield[s,a]}}function Sxe(e){let t=e.indexOf("=");return t<0?{name:e,value:""}:{name:e.slice(0,t),value:e.slice(t+1)}}function wxe(e,t){let r=[];for(let i=0;i<e.length;i+=2){let n=Bo(e[i],t),o=Bo(e[i+1],t);if(n==null||o==null)return null;r.push([n,o])}return Object.fromEntries(r)}function jV(e,t){let r=[];for(let i of e){let n=Bo(i,t);if(n==null)return null;r.push(n)}return r}function Bo(e,t){if(t)return e;try{return decodeURIComponent(e)}catch{return null}}var js=({name:e,prefix:t},r)=>({[e]:{value:r,prefix:t}});function NO(e,t){let r={...e};for(let[i,n]of Object.entries(t)){let o=r[i];if(o==null){r[i]=n;continue}let s=bxe(o,n);if(s==null)return null;r[i]=s}return r}var bxe=(e,t)=>iw(e)||iw(t)?_xe(e,t):xxe(e.value,t.value)?e:null;function _xe(e,t){let r=TV(e.value),i=TV(t.value);if(r==null||i==null)return null;let n=iw(e),o=iw(t);if(!n&&!o)return null;if(n&&!o)return Cf(i,e.prefix)===r?t:null;if(!n&&o)return Cf(r,t.prefix)===i?e:null;let s=e.prefix,a=t.prefix;return s<=a?Cf(i,s)===r?t:null:Cf(r,a)===i?e:null}var iw=e=>e.prefix!=null,TV=e=>typeof e=="string"?e:null;function xxe(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,i)=>r===t[i]):CV(e)?CV(t)&&Exe(Object.entries(e),Object.entries(t)):e===t}var Exe=(e,t)=>e.length===t.length&&e.every(([r,i],n)=>{let[o,s]=t[n];return r===o&&i===s}),CV=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Axe=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value])),UO=(e,t)=>t===""?[e]:e.split(t),Rxe=["=",",","!","@","|"];function Ixe(e,t,r){let i=a=>{throw a};if(e.length<1)return i(new R_e(t,r));let n=e[0];if(Cxe(n))return i(new I_e(t,r+1,n));if(!kV(n)&&TO(e,0)<1)return i(new $_e(t,r+1,n));let o=kV(n)?n:"",s=o===""?0:1;return{kind:"expression",operator:o,vars:$xe(e,t,r+1,s)}}function $xe(e,t,r,i){if(i>=e.length)throw new PO(t,r+i);let n=[];for(let o=i;o<e.length;){if(e[o]===",")throw o===e.length-1?new RV(t,r+o):new PO(t,r+o);let s=o,a=Pxe(e,o);if(a===s)throw new PO(t,r+o);let c=e.slice(s,a);o=a;let u=Txe(e,t,r,o,c);if(o=u.index,o<e.length&&e[o]!==",")throw u.used?new C_e(t,r+o,e[o]):new P_e(t,r+o,c,e[o]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),o<e.length&&(o++,o>=e.length))throw new RV(t,r+o-1)}return n}function Pxe(e,t){let r=t,i=!0;for(;r<e.length;){let n=TO(e,r);if(n>0){r+=n,i=!1;continue}if(e[r]!=="."||i||TO(e,r+1)<1)break;r++,i=!0}return r}function Txe(e,t,r,i,n){if(e[i]==="*")return{explode:!0,index:i+1,used:!0};if(e[i]!==":")return{explode:!1,index:i,used:!1};let o=i+1,s=o;for(;s<e.length&&kxe(e[s]);)s++;let a=e.slice(o,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new T_e(t,r+i,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function kV(e){return O_e.includes(e)&&e!==""}function Cxe(e){return Rxe.includes(e)}function kxe(e){let t=e.charCodeAt(0);return t>=48&&t<=57}function Dxe(e,t){let{report:r}=t,i=[],n=o=>{let s=i.at(-1);s?.kind==="literal"?i[i.length-1]={kind:"literal",text:s.text+o}:i.push({kind:"literal",text:o})};for(let o=0;o<e.length;){let s=e[o];if(s==="{"){let l=e.indexOf("}",o+1);if(l<0){r(new __e(e,o)),n(e.slice(o));break}let d=e.indexOf("{",o+1);if(d>=0&&d<l){r(new E_e(e,d)),n(e.slice(o,l+1)),o=l+1;continue}let m=e.slice(o+1,l);try{i.push(Ixe(m,e,o))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(e.slice(o,l+1))}o=l+1;continue}if(s==="}"){r(new x_e(e,o)),n(s),o++;continue}let a=U_e(e,o);if(a>0){n(e.slice(o,o+a)),o+=a;continue}let{char:c,size:u}=Of(e,o);r(new A_e(e,o,c)),n(c),o+=u}return i}var sw=class FV{uriTemplate;options;#e;#t;constructor(t,r={}){this.uriTemplate=t,this.options=r,this.#t=Mxe(r),this.#e=Oxe(Dxe(t,this.#t)),Object.freeze(this)}static parse(t,r={}){return new FV(t,r)}get tokens(){return this.#e}expand=t=>MV(this.#e,t,this.#t);match=t=>Y_e(this.#e,t,this.#t);toString=()=>this.uriTemplate},Oxe=e=>Object.freeze(e.map(Nxe)),Nxe=e=>e.kind==="literal"?Object.freeze({kind:"literal",text:e.text}):Object.freeze({kind:"expression",operator:e.operator,vars:Object.freeze(e.vars.map(Uxe))}),Uxe=e=>Object.freeze({name:e.name,explode:e.explode,...e.prefix==null?{}:{prefix:e.prefix}}),Lxe=()=>{},Mxe=({strict:e,report:t})=>(t??=Lxe,e??=!0,t=e?zxe(t):t,{strict:e,report:t}),zxe=e=>t=>{throw e(t),t};var Gs=class extends Error{constructor(r,i){super(i);this.code=r}code};function jxe(e,t){return!e.when||t[e.when.field]===void 0||e.when.values.includes(t[e.when.field])}function qV(e,t,r={}){let i=(o,s)=>{throw new Gs(o,s)},n={...r,...t};for(let o of e)n[o.name]===void 0&&o.defaultValue!==void 0&&(n[o.name]=o.defaultValue);for(let o of e){if(!jxe(o,n)){delete n[o.name];continue}o.required!==!1&&!n[o.name]&&i("missing_field","Complete the required service fields."),n[o.name]?.includes("\0")&&i("invalid_field","Check the service fields."),o.choices&&n[o.name]&&!o.choices.some(s=>s.value===n[o.name])&&i("invalid_field","Choose an available service setting."),o.pattern&&(o.pattern.length>200||!(0,GV.default)(o.pattern))&&i("invalid_pattern","Use a simple field validation pattern."),o.pattern&&n[o.name]&&!new RegExp(o.pattern,"u").test(n[o.name].slice(0,1e3))&&i("invalid_field","Check the service fields.")}return Object.keys(t).some(o=>!e.some(s=>s.name===o))&&i("invalid_field","Remove unrecognized service fields."),n}function qs(e,t,r={}){let i=qV(e,t,r),n={};for(let o of e){let s=o.choices?.find(a=>a.value===i[o.name]);for(let[a,c]of Object.entries(s?.values??{})){if(e.some(u=>u.name===a)||a in n&&n[a]!==c)throw new Gs("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...i,...n}}function LO(e,t){for(let[r,i]of Object.entries(t)){let n=e.find(o=>o.name===r);if(!n)throw new Gs("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&i!=="")throw new Gs("encrypted_input_required","Supply private material directly with your encryption keys.")}return qV(e.map(r=>({...r,required:!1,defaultValue:void 0})),t)}function $l(e,t){return LO(e,Object.fromEntries(e.filter(r=>r.secret===!1&&t[r.name]).map(r=>[r.name,t[r.name]])))}function VV(e,t=Pf(e)){return t.accountVerified?t.accountId:null}function KV(e,t=Pf(e)){let i=(e.method.kind==="oauth"||e.method.kind==="ovh"||e.method.kind==="token"&&!!(e.method.config.identity||e.method.config.resolver||e.method.config.bindFields))&&e.method.kind!=="aws"?$l(e.method.config.fields,e.fields??{}):{};return{format:e.format,generation:e.generation,methodId:e.methodId,method:e.method,appId:e.appId,appGeneration:e.appGeneration,..."implicitApp"in e&&e.implicitApp?{implicitApp:{clientId:e.implicitApp.clientId,generation:e.implicitApp.generation,fields:e.implicitApp.fields}}:{},account:t.accountId,accountVerified:t.accountVerified,scopes:[...t.scopes].sort(),...Object.keys(i).length?{fields:i}:{},...t.authorization,...e.state?{state:e.state}:{}}}var Vs=f.record(f.string().max(100),f.string().max(16384)),aw=f.object({format:f.literal(1),methodId:f.string().min(1),generation:P,clientId:f.string().max(1e3),clientSecret:f.string().max(16384).optional(),fields:Vs}).strict(),MO=f.object({accessToken:f.string().min(1).max(16384),refreshToken:f.string().min(1).max(16384).optional(),expiresAt:f.number().nullable(),refreshExpiresAt:f.number().optional(),scopes:f.array(f.string()),requestedScopes:f.array(f.string()).optional(),account:f.string(),accountName:f.string(),accountVerified:f.boolean().optional(),scopesStatus:f.enum(["unknown","requested","reported"]).optional(),extra:Vs,facts:Mt}).strict(),Nf={format:f.literal(2),methodId:f.string().min(1),method:fl,generation:P,appId:P.nullable(),appGeneration:P.nullable(),state:f.literal("reconnect").optional()},Wo=f.never().optional(),Pl=f.union([f.object({...Nf,method:$S,oauth:MO.optional(),requestedScopes:f.array(f.string()).optional(),implicitApp:aw.optional(),fields:Vs.optional(),aws:Wo}).strict(),f.object({...Nf,method:PS,fields:Vs,facts:Ms.optional(),oauth:Wo,aws:Wo}).strict(),f.object({...Nf,method:kS,fields:Vs,oauth:Wo,aws:Wo}).strict(),f.object({...Nf,method:CS,fields:Vs,ovh:gf.optional(),requestedScopes:f.array(f.string()).optional(),oauth:Wo,aws:Wo}).strict(),f.object({...Nf,method:TS,aws:bS,oauth:Wo,fields:Wo}).strict()]).superRefine((e,t)=>{if("implicitApp"in e&&e.implicitApp&&(e.method.kind!=="oauth"||e.method.config.application!=="implicit"||e.implicitApp.methodId!==e.methodId)&&t.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),e.method.kind==="oauth"&&e.fields)try{LO(e.method.config.fields,e.fields)}catch{t.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}xl(e.method)&&(!e.appId||!e.appGeneration)&&t.addIssue({code:"custom",message:"Bind the application required by this connection."}),!xl(e.method)&&e.appId!==null&&t.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!e.appId!=!!e.appGeneration&&t.addIssue({code:"custom",message:"Bind the application and its generation together."}),e.method.kind==="oauth"&&e.method.config.grantType==="client_credentials"&&!("requestedScopes"in e&&e.requestedScopes)&&!e.oauth?.requestedScopes&&t.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),qYe=f.object({methodId:f.string().min(1).max(200),clientId:f.string().max(1e3),generation:P,fields:Vs.optional()}).strict(),Fxe=f.object({methodId:f.string().min(1).max(200),methodKind:QD,http:IS.optional(),generation:P,authorizationDigest:yt,appId:P.nullable(),accountId:f.string().max(2e3).nullable(),accountVerified:f.boolean(),scopes:f.array(f.string().max(1e3)).max(200),scopesStatus:f.enum(["unknown","requested","reported"]),outputs:f.array(f.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:f.enum(["ready","reconnect"]),revocable:f.literal(!0).optional(),fields:Vs.optional(),aws:_S.optional(),ovh:gf.optional()}).strict();async function BV(e,t=Pf(e)){let{outputs:r,revocable:i}=Ls(e.method),n=e.method.kind!=="aws"&&e.fields?$l(e.method.config.fields,e.fields):{},o=await te(KV(e,t));return Fxe.parse({methodId:e.methodId,methodKind:e.method.kind,...e.method.http?{http:e.method.http}:{},generation:e.generation,authorizationDigest:o,appId:e.appId,accountId:VV(e,t),accountVerified:t.accountVerified,scopes:t.scopes,scopesStatus:t.scopesStatus,outputs:r,state:e.state??"ready",...i?{revocable:i}:{},...Object.keys(n).length?{fields:n}:{},...t.details})}var Gxe=f.array(f.object({name:f.string(),label:f.string(),value:f.string()}).strict()),HV=f.object({methodName:be,account:f.string().max(2e3),settings:Gxe.optional()}).strict();var zO=f.discriminatedUnion("action",[f.object({action:f.literal("refresh"),id:P}).strict(),f.object({action:f.literal("revoke"),id:P}).strict()]);var jO=gl.extend({name:be}),YYe=gl.extend({previousSignature:_t.optional()}).strict(),QYe=f.object({name:be,content:ir,labels:HV.optional(),version:f.number().int().positive().optional()}).strict(),FO=f.object({content:ir,version:f.number().int().positive()}).strict(),WV=f.object({id:P,reason:f.enum(["grantExpired","recipients"]),remove:f.array(P).max(1e3).default([])}).strict(),eQe=f.record(P,f.object({version:f.number().int().positive(),content:ir}).strict()),JV=f.object({id:P,name:be,version:f.number().int().positive(),content:ir,policy:qo}).strict(),ZV=f.object({registration:uO,stoppedAt:f.iso.datetime().nullable(),heartbeatAt:f.iso.datetime().nullable()}).strict(),XV=f.object({lease:P,request:qS,sources:f.array(ir).max(100)}).strict().nullable(),qxe=f.object({lease:P}).strict(),tQe=qxe.extend({receipt:$f}).strict(),Uf=f.object({id:P,resource_id:P,executor_id:P,expected_revision:f.number().int().positive(),state:f.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:f.string().regex(/^\d+$/),result:ir.nullable()}),rQe=f.object({id:P,resourceId:P,expectedRevision:f.number().int().positive()}).strict(),Vxe=f.object({fence:f.string().regex(/^\d+$/)}).strict(),nQe=Vxe.extend({content:ir}).strict(),iQe=f.object({id:P,executionId:P,index:f.number().int().nonnegative(),stateDigest:yt,expiresAt:ne}).strict(),oQe=f.object({id:P,executionId:P,context:f.string(),sealed:jo.nullable(),expiresAt:ne,receivedAt:ne.nullable()}).strict();var Kxe=f.object({binding:vt,verifiedAt:ne}).strict(),GO=f.object({origin:f.url(),ownerId:P,signerId:P,revision:f.number().int().positive(),keys:f.array(Kxe).max(1e3)}).strict(),Bxe=f.object({version:f.number().int().positive(),signature:_t}).strict(),qO=f.object({keyring:Bxe.nullable()}).strict(),dQe=f.object({version:f.number().int().positive().nullable(),signature:_t}).strict();function YV(e,t){return Tt(GO.parse(e),t,"keyring")}function QV(e){return GO.parse(JSON.parse(NS($q(e.split(".")[1]??""))))}async function e3(e,t){let r=GO.parse(await _f(e,t.signing,"keyring"));if(r.signerId!==t.id)throw new Error("Another identity signed this keyring.");return r}var Tl=lt(r3(),1);var Me=class extends Error{constructor(r,i,n,o){super(n);this.status=r;this.code=i;this.details=o}status;code;details};function M(e,t,r,i){throw new Me(e,t,r,i)}var Hxe=Tl.default.IPv6.parseCIDR("2000::/3"),Wxe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function uw(e){if(!Tl.default.isValid(e)||e.includes("%"))return!1;let t=Tl.default.parse(e);return Wxe.has(t.range())&&(!(t instanceof Tl.default.IPv6)||t.match(Hxe))}function Pn(e,t){let r;try{r=new URL(e)}catch{M(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===t)&&M(400,"invalid_url","Choose a public HTTPS destination.");let i=r.hostname.replace(/^\[|\]$/g,"");return(i==="localhost"||i.endsWith(".localhost")||i.endsWith(".local")||Tl.default.isValid(i)&&!uw(i))&&M(400,"private_destination","Choose a public HTTPS destination."),r}function Cl(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.body))}catch{M(502,"invalid_response","The service returned an invalid response.")}return(!t||typeof t!="object"||Array.isArray(t))&&M(502,"invalid_response","The service returned an invalid response."),t}function Lf(e){return[...e.connectionId?[{id:e.connectionId}]:[],...e.bindings.flatMap(t=>t.parts.filter(r=>typeof r!="string"))]}function VO(e,t,r){e.method.http||M(400,"invalid_http_connection","This connection does not provide HTTP authentication.");let i=e.method.http.urlField,n=i&&e.fields?.[i];i&&!n&&M(409,"reconnect_required","Reconnect with a destination URL.");let o=Pn(t.url??n??"",r);return n&&o.origin!==Pn(n,r).origin&&M(400,"invalid_destination","Use this connection only at its configured destination host."),o.href}function n3(e,t,r,i){let n=new URL(e),o={...t},s=[];Object.keys(t).some(l=>["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase()))&&M(400,"invalid_authentication","Use HTTP headers that do not override routing or transport settings.");let a=(l,d=!0)=>{Object.hasOwn(i,l)||M(400,"invalid_authentication","Choose an available authentication output.");let m=i[l];return d&&s.push(m),m},c=(l,d)=>{(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(l)||["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase())||/[\r\n\0]/.test(d))&&M(400,"invalid_authentication","Use a valid authentication header."),Object.keys(o).some(m=>m.toLowerCase()===l.toLowerCase())&&M(400,"invalid_authentication","Let the selected connection supply its authentication header."),o[l]=d,s.push(d)},u=r.authentication;if(u.kind==="bearer")c("Authorization","Bearer "+a(u.token));else if(u.kind==="basic"){let l=a(u.username),d=a(u.password);l.includes(":")&&M(400,"invalid_authentication","A Basic authentication username cannot contain a colon.");let m=new TextEncoder().encode(l+":"+d),p=btoa(Array.from(m,g=>String.fromCharCode(g)).join(""));c("Authorization","Basic "+p),s.push(p)}else if(u.kind==="header"||u.kind==="query"){let l=typeof u.name=="string"?u.name:a(u.name.output,!1),d=a(u.value);u.kind==="header"?c(l,d):((!l||/[\r\n\0]/.test(l)||n.searchParams.has(l))&&M(400,"invalid_authentication","Let the selected connection supply its authentication query parameter."),n.searchParams.set(l,d))}return s.push(n.href),{url:n.href,headers:o,sensitive:s}}var Lr=class extends Error{constructor(r,i){super(i);this.code=r}code},BO=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},KO=(e,...t)=>!!e&&typeof e=="object"&&("code"in e&&t.includes(String(e.code))||"status"in e&&t.includes(Number(e.status))),lw=class{constructor(t,r,i,n,o){this.api=t;this.origin=r;this.binding=i;this.keys=n;this.trust=o}api;origin;binding;keys;trust;verifiedKeys;async trusted(t){if(!await this.verifies(t))throw t.principalId!==this.binding.principalId&&await this.known(t.principalId)?new Lr("identity_changed","Identity "+t.principalId+" replaced the keys verified before. Verify its current keys."):new Lr("identity_untrusted","Verify and trust the encryption and signing keys for identity "+t.principalId+" before sharing.");return t}async verifies(t){if(t.principalId===this.binding.principalId)return k(this.binding)===k(t);let r=await this.known(t.principalId);return!!r&&k(r)===k(t)}async known(t){return(await this.keyring()).get(t)?.binding??await this.trust.binding(t)}async verifiedIdentity(t){return this.verifies((await this.inspectIdentity(t)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(t=>{throw this.verifiedKeys=void 0,t})}async loadKeyring(){let t;try{t=(await this.readKeyring()).keyring?.keys??[]}catch(o){if(KO(o,401,403))return new Map;throw o}let r=new Set(t.map(o=>o.binding.principalId)),i=new Date().toISOString(),n=(await this.trust.bindings()).filter(o=>o.principalId!==this.binding.principalId&&!r.has(o.principalId));if(n.length)try{t=(await this.changeKeyring(o=>[...o,...n.filter(s=>!o.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:i}))])).keys}catch(o){if(o instanceof Lr)throw o}return new Map(t.map(o=>[o.binding.principalId,o]))}async readKeyring(){let t="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(t,{},qO),i=await this.trust.keyring(),n=()=>new Lr("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(i)throw n();return{version:null,revision:0,keyring:null}}let o=QV(r.signature);if(o.signerId!==this.binding.id)return{version:r.version,revision:o.revision,keyring:null};let s=await e3(r.signature,this.binding).catch(()=>{throw n()}),a=await te(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||i&&(s.revision<i.revision||s.revision===i.revision&&a!==i.digest))throw n();return(!i||s.revision>i.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(t){for(let r=1;;r++){let i=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:i.revision+1,keys:t(i.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:i.version,signature:await YV(n,this.keys.signing)}},qO)}catch(o){if(r<3&&KO(o,"changed"))continue;throw o}return await this.trust.rememberKeyring({revision:n.revision,digest:await te(n)}),n}}async inspectIdentity(t){let r=await this.api.json("/api/identities/"+P.parse(t)+"/binding",{},gl);return await LS(r),{...r,fingerprint:await US(r.binding)}}async trustIdentity(t,r){let i=await this.inspectIdentity(t);if(i.fingerprint!==r)throw new Lr("fingerprint_mismatch","The identity fingerprint does not match.");if(t===this.binding.principalId||k((await this.keyring()).get(t)?.binding??null)===k(i.binding))return i;let n=new Date().toISOString();try{let o=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==t),{binding:i.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(o.keys.map(s=>[s.binding.principalId,s])))}catch(o){if(!KO(o,401,403))throw o;await this.trust.rememberBinding(i.binding)}return i}async environment(t,r=!0){let{registration:i,stoppedAt:n}=await this.api.json("/api/environments/"+P.parse(t)+"/registration",{},ZV);if(await wl(i),i.manifest.origin!==this.origin||i.manifest.id!==t||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(i.manifest.executor),i}async recipients(t){let{items:r}=await this.api.json("/api/principals/"+P.parse(t)+"/bound-recipients",{},hl(jO));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...s}of r)await LS(s),await this.trusted(s.binding);let i=await this.api.json("/api/principals/"+P.parse(t)+"/bound-delegates",{},hl(jO)),n=[];for(let{name:o,...s}of i.items){await LS(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof Lr&&["identity_untrusted","identity_changed"].includes(a.code)))throw a}}return[...r.map(o=>o.binding),...n]}async read(t){let r=await this.latest(t);if(r.replaced)throw new Lr("key_replaced","This item is sealed only for keys this identity has since replaced. Enter its value again.");return r}async latest(t){let r=await this.api.json("/api/custody/"+P.parse(t),{},FO);return this.replaces(r.content.policy)?{...r,replaced:!0}:(await this.observe(r.content,t),{...r,replaced:!1})}replaces(t){return!t.readers.some(r=>k(r)===k(this.binding))&&t.readers.some(r=>r.principalId===this.binding.principalId)}async observe(t,r=t.policy.id){let i=await sn(t);if(i.policy.id!==r||i.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=sO(i);await this.trusted(n);let o=await this.trust.checkpoint(i);if(o&&qo.parse(o.policy),o){if(i.policy.revision<o.policy.revision||i.materialRevision<o.materialRevision||i.policy.revision===o.policy.revision&&k(i.policy)!==k(o.policy)||i.materialRevision===o.materialRevision&&await te(i)!==o.digest)throw new Lr("content_conflict","The encrypted content is older than this device has already observed.");if(i.policy.revision>o.policy.revision&&!MS(o.policy,i)&&!o.policy.authorities.some(s=>s.principalId===n.principalId&&s.id!==n.id))throw new Lr("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(i),i}async reveal(t){return If((await this.read(t)).content,this.binding,this.keys.encryption)}async sharing(t){let r=typeof t=="string"?(await this.api.json(t,{},hl(JV))).items:t,i={};for(let n of r){let o=await this.read(n.id);if(o.version!==n.version||k(o.content)!==k(n.content))throw new Lr("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);i[n.id]={version:n.version,content:await Af(await If(o.content,this.binding,this.keys.encryption),n.policy,o.content.materialRevision+1,this.binding,this.keys,o.content.metadata,o.content)}}return i}async policy(t,r,i=[],n={}){let o=n.previous?.readers??[...new Map([...await this.recipients(t),this.binding].map(c=>[c.id,c])).values()];if(!o.some(c=>k(c)===k(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)&&Go(c)):[];for(let c of i)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...nO(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return qo.parse({format:2,id:n.id??n.previous?.id??n.replacing?.id??crypto.randomUUID(),origin:this.origin,ownerId:t,contentType:r,revision:(n.previous?.revision??n.replacing?.revision??0)+1,authorities:n.previous?.authorities??o,readers:o,grants:a,producers:[]})}async save(t,r,i,n={}){let o=n.previous;o&&k(i)===k({...o.content.policy,revision:i.revision})&&(i={...i,revision:o.content.policy.revision});let s=await Af(r,i,(o?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,o&&!this.replaces(o.content.policy)?o.content:void 0),a={name:t,content:s,...n.labels?{labels:n.labels}:{},...o?{version:o.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:a},ml);return await this.trust.rememberContent(s),c}async pass(t,r,i,n){let o=await Af(r,i,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:{name:t,content:o,version:n.version}},f.union([ml,Nq]));return"kind"in s&&await this.trust.rememberContent(o),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},hl(WV))).items}async reprotect(t,r="grantExpired",i=[]){let n=await this.read(t),{policy:o}=n.content,s=Date.now(),a=new Set(i),c=r==="recipients"?await this.recipients(o.ownerId):[],u=new Map(c.map(C=>[C.principalId,C])),l=[...o.readers,...o.authorities,...o.grants.flatMap(C=>"actor"in C?[C.actor,C.executor]:[C.executor])];if(r==="recipients")for(let C of new Set(l.map(G=>G.principalId))){if(C===this.binding.principalId||u.has(C)||a.has(C))continue;let G=await this.inspectIdentity(C).then(B=>B.binding,()=>null);G&&l.some(B=>B.principalId===C&&B.id!==G.id)&&u.set(C,await this.trusted(G))}let d=C=>u.get(C.principalId)??C,m=C=>[...new Map(C.map(G=>[G.id,G])).values()],p=C=>!a.has(C.principalId),g=o.grants.filter(C=>Go(C,s)&&p(C.executor)&&(!("actor"in C)||p(C.actor))).map(C=>"actor"in C?{...C,actor:d(C.actor),executor:d(C.executor)}:{...C,executor:d(C.executor)}),v=m(o.readers.filter(p).map(d)),S=m(o.authorities.filter(p).map(d)),b=c.filter(C=>!v.some(G=>G.id===C.id)),_={...o,revision:o.revision+1,grants:g,producers:[],readers:[...v,...b],authorities:[...S,...b.filter(C=>!S.some(G=>G.id===C.id))],...o.observers?{observers:o.observers.filter(C=>!a.has(C))}:{}},x=o.contentType!==ge.executionResult&&o.producers.some(C=>Date.parse(C.expiresAt)>s);if(k({..._,revision:o.revision})===k(o)||x)return null;let T=await If(n.content,this.binding,this.keys.encryption);if(o.contentType===ge.executionResult){let C=await Af(T,_,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+t,{method:"PUT",body:{name:"Execution result",content:C,version:n.version}},FO),await this.trust.rememberContent(C),t}let U=await this.api.json("/api/resources/"+o.id,{},ml);return this.save(U.name,T,_,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let t=[],r=[];for(let i of await this.pendingProtection())try{await this.reprotect(i.id,i.reason,i.remove)&&t.push(i.id)}catch(n){r.push({id:i.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:t,failed:r}}async sourceContents(t){let r=new Map;for(let i of new Set(t))r.set(i,(await this.read(i)).content);for(let i of[...r.values()])i.policy.contentType===ge.tokenSet&&typeof i.metadata.appId=="string"&&!r.has(i.metadata.appId)&&r.set(i.metadata.appId,(await this.read(i.metadata.appId)).content);return[...r.values()]}async output(t,r,i,n,o){let s,a=null;do{let d=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),m=await this.api.json("/api/principals/"+t+"/resources?"+d,{},hl(ml));s=m.items.find(p=>p.name===r),a=m.next}while(!s&&a);let c=s?await this.latest(s.id):void 0,u=c?.content,l=u&&!c.replaced?{...u.policy,revision:u.policy.revision+1,producers:[]}:await this.policy(t,ge.value,[],{replacing:u?.policy});return l.producers=[{executor:n.manifest.executor,runId:i,expiresAt:o,materialRevision:(u?.materialRevision??0)+1}],{name:r,approval:await FS(l,this.binding,this.keys,c?.replaced?void 0:u)}}async prepare(t,r,i,n={}){let o=Ic.parse(i),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=o,l=u.kind==="http"?u.request:null;if(l?.connectionId&&s.manifest.httpVersion!==zi)throw new Lr("http_runtime_required","Update this execution environment to use HTTP connections.");if(o.kind==="http"){let S=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(S).map(async([_,x])=>[_,await this.output(t,x,a,s,c)])));o.save=b}let d=u.kind==="command"?u.inputs.map(S=>S.source.id):l?Lf(l).map(S=>S.id):[],m=await this.sourceContents([...d,...n.sourceIds??[]]);for(let S=0;S<m.length;S++){let b=m[S],_=b.policy.contentType===ge.clientCredential,x=_&&o.kind!=="revoke"?Q.refresh:Q[o.kind],T=_||!l?.url?void 0:new URL(l.url).origin;if(b.policy.grants.some(ee=>"actor"in ee&&k(ee.actor)===k(this.binding)&&k(ee.executor)===k(s.manifest.executor)&&ee.operations.includes(x)&&vl(ee)>=Date.parse(c)&&(!T||!ee.origins.length||ee.origins.includes(T))&&(_||ee.callerProgram))||!b.policy.authorities.some(ee=>k(ee)===k(this.binding)))continue;let C=await this.read(b.policy.id),G=await this.api.json("/api/resources/"+b.policy.id,{},ml),B={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[Q.refresh]:[]])],origins:T?[T]:[],functionDigests:[],callerProgram:!_,expiresAt:c},de=ee=>k({...ee,expiresAt:null}),pe=C.content.policy.grants.filter(ee=>de(ee)===de(B)),qe=qo.parse({...C.content.policy,revision:C.content.policy.revision+1,grants:[...C.content.policy.grants.filter(ee=>Go(ee)&&de(ee)!==de(B)),{...B,expiresAt:new Date(Math.max(Date.parse(c),...pe.map(ee=>vl(ee)))).toISOString()}]});await this.save(G.name,await If(C.content,this.binding,this.keys.encryption),qe,{previous:C,metadata:C.content.metadata}),m[S]=(await this.read(b.policy.id)).content}let p=await this.policy(t,ge.executionResult,[],{id:a});p.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let g={format:2,id:a,origin:this.origin,ownerId:t,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await te(s.manifest),operation:Q[o.kind],operationDigest:await te(o),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(m.map(async S=>({id:S.policy.id,materialRevision:S.materialRevision,policyDigest:await te(S.policy),...S.policy.contentType===ge.tokenSet&&typeof S.metadata.authorizationDigest=="string"?{authorizationDigest:S.metadata.authorizationDigest}:{}}))),resultRecipients:p.readers,...s.manifest.resultVersion?{resultApproval:await FS(p,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await bl(s,g);let v=S=>S.policy.contentType===ge.clientCredential;for(let S of m)await Os(S,v(S)&&g.operation!==Q.connect&&g.operation!==Q.revoke?{...g,operation:Q.refresh}:g,v(S)?{}:{destination:l?.url,destinationPending:!!(l?.connectionId&&!l.url)});return qq(g,o,this.keys)}async submit(t,r,i,n={}){return this.submitPrepared(await this.prepare(t,r,i,n))}async submitPrepared(t){await this.trust.rememberRun(t);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:t},Rc)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new BO(t.intent.id)}}async resume(t){let r=await this.trust.run(P.parse(t));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(k(r.intent.actor)!==k(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let i=await this.api.json("/api/runtime/runs/"+t,{},Rc);if(k(i.intent)!==k(r.intent)||i.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return i}catch(i){if(!i||typeof i!="object"||!("code"in i)||i.code!=="not_found")throw i}return this.submitPrepared(r)}async result(t){if(t.intent.origin!==this.origin||t.intent.id!==t.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(t.intent.actor);let r=await _f(t.requestSignature,t.intent.actor.signing,"run");if(k(r.intent)!==k(t.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(t.intent.executor),!(t.receipt&&"content"in t.receipt?t.receipt.content.policy.readers:t.intent.resultRecipients).some(n=>k(n)===k(this.binding)))throw new Lr("not_recipient","This identity is not a reader of the execution result.");return t.receipt&&"content"in t.receipt&&await this.observe(t.receipt.content,t.id),t.receipt?Zq(t.receipt,t.intent,this.binding.id,this.keys):null}async shareLegacyResult(t){if(!t.receipt||"content"in t.receipt)return t;if(k(t.intent.actor)!==k(this.binding)||k(t.intent.executor)!==k(this.binding))throw new Lr("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(t);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let i=await this.policy(t.ownerId,ge.executionResult,[],{id:t.id});i.producers=[{executor:this.binding,runId:t.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await dO(t.intent,t.receipt.state,r,this.keys,await FS(i,this.binding,this.keys),t.receipt);return this.api.json("/api/runtime/runs/"+t.id+"/result",{method:"PUT",body:{receipt:n}},Rc)}};import{lstat as Jxe,mkdir as i3,readFile as Zxe,readdir as o3,rm as Xxe}from"node:fs/promises";import{join as kl}from"node:path";var dw=f.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Tc=class{constructor(t,r,i,n){this.directory=t;this.origin=r;this.binding=i;this.privateKeys=n}directory;origin;binding;privateKeys;indexing;context(t){return k({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:dw.parse(t)})}async read(t){let r=this.context(t),i=kl(this.directory,t+".json");try{let n=await Jxe(i);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let o=f.string().max(32e6).parse(JSON.parse(await Zxe(i,"utf8"))),s=await gS(o,await An(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(NS(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await nr({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 writeEntry(t,r){let i=this.context(t),n={context:i,value:r},o=await Tt(n,this.privateKeys.signing,"journal"),s=ft(k({...n,signature:o}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new ll(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:i}).encrypt(await An(this.binding.encryption,"ECDH-ES+A256KW"));await i3(this.directory,{recursive:!0,mode:448}),await yO(kl(this.directory,t+".json"),k(a),!0)}delivery(t){return/^(run|process|invocation|refresh)_/.test(t)}delivered(t){return!!t&&typeof t=="object"&&"delivered"in t&&t.delivered===!0}async markPending(t){await i3(kl(this.directory,"pending"),{recursive:!0,mode:448}),await yO(kl(this.directory,"pending",dw.parse(t)),"",!0)}index(){return this.indexing??=(async()=>{let t="checkpoint_pending_index";if(!await this.read(t)){for(let r of await this.keys("")){if(!this.delivery(r))continue;let i=await this.read(r);i&&!this.delivered(i)&&await this.markPending(r)}await this.writeEntry(t,{version:1})}})()}async write(t,r){await this.index();let i=this.delivered(r);this.delivery(t)&&!i&&await this.markPending(t),await this.writeEntry(t,r),this.delivery(t)&&i&&await Xxe(kl(this.directory,"pending",t),{force:!0})}async pending(t){await this.index();let r;try{r=await o3(kl(this.directory,"pending"),{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)).map(i=>dw.parse(i.name))}async keys(t){let r;try{r=await o3(this.directory,{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)&&i.name.endsWith(".json")).map(i=>dw.parse(i.name.slice(0,-5)))}};var pw=class{constructor(t){this.journal=t}journal;binding(t){return this.journal.read("identity_"+t)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(t){await Mi(t),await this.journal.write("identity_"+t.principalId,t)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(t){await this.journal.write("checkpoint_keyring",t)}checkpoint(t){return this.journal.read("checkpoint_"+t.policy.format+"_"+t.policy.id)}async rememberContent(t){await this.journal.write("checkpoint_"+t.policy.format+"_"+t.policy.id,{policy:t.policy,materialRevision:t.materialRevision,digest:await te(t)})}run(t){return this.journal.read("run_"+t)}async rememberRun(t){let r=await this.run(t.intent.id);if(r&&k(r)!==k(t))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+t.intent.id,t)}};var fw=class{api;constructor(t){this.api={async json(r,i={},n){try{return await t.json(r,i,n)}catch(o){throw o instanceof Error&&"status"in o&&typeof o.status=="number"&&"code"in o&&typeof o.code=="string"?new Me(o.status,o.code,o.message):o}}}}claim(t){return this.api.json("/api/environments/"+t+"/claim",{method:"POST",body:{}},XV)}renew(t,r){return this.api.json("/api/runtime/runs/"+t+"/renew",{method:"POST",body:{lease:r}},f.object({active:f.boolean()}))}dispatch(t,r){return this.api.json("/api/runtime/runs/"+t+"/dispatch",{method:"POST",body:{lease:r}})}finish(t,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:t,receipt:r}},Rc)}capture(t,r,i){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:t,content:r,...i?{labels:i}:{}}},f.object({id:P}))}connections(){let t=this.api;return{prepare:(r,i,n)=>t.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:i,expectedRevision:n}},Uf),dispatch:(r,i)=>t.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:i}},Uf),commit:(r,i,n)=>t.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:i,content:n}},ir),uncertain:(r,i)=>t.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:i}}),abort:(r,i)=>t.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:i}},Uf),state:r=>t.json("/api/connections/"+r+"/operation",{},Uf.nullable())}}};import{randomUUID as _Ue}from"node:crypto";var cs=lt(l4(),1);import{randomUUID as gNe}from"node:crypto";function qte(e){let t=wS.safeParse({accountId:e.Account,arn:e.Arn,principalId:e.Arn?.includes(":assumed-role/")?e.UserId?.split(":")[0]:e.UserId});return(!t.success||t.data.arn.split(":")[4]!==t.data.accountId)&&M(502,"invalid_response","The AWS account could not be verified."),t.data}function Vte(e,t){return e.accountId===t.accountId&&e.principalId===t.principalId&&dl(e.arn)===dl(t.arn)}function d4(e){e&&(!Number.isFinite(e.getTime())||e.getTime()<=Date.now())&&M(409,"reconnect_required","Reconnect with current AWS credentials.")}var OE=class{async obtain(t,r,i){let n=JD.parse({authentication:t.authentication,region:t.region,...t.role?{role:t.role}:{}}),o=n.authentication,s=o.kind==="environment"?void 0:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.kind==="session"?{sessionToken:o.sessionToken,expiration:new Date(o.expiresAt)}:{}};d4(s?.expiration);let a=new cs.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...i?[i]:[]]),l=!1;try{let d=s??await a.config.credentials();d4(d.expiration),c=new cs.STSClient({region:n.region,credentials:d});let m=r?.sourceIdentity?qte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&m&&!Vte(m,r.sourceIdentity)&&M(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,g=m;if(n.role){l=!0;let b=(await c.send(new cs.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+gNe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&M(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},d4(p.expiration),r?.identity&&(c.destroy(),c=new cs.STSClient({region:n.region,credentials:p}),g=qte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&g&&!Vte(g,r.identity)&&M(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:bS.parse({...n,sourceIdentity:m,identity:g}),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 Me)throw d;i?.aborted&&M(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&M(409,"reconnect_required","Reconnect with current AWS credentials."),l&&M(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),M(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var NE=class{constructor(t){this.aws=t}aws;facts=wO;needsRenewal(){return!1}async outputs(t,r,i){return(await this.aws.obtain(t.aws,t.aws,i)).credentials}};var p4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(p4="oauth4webapi/v3.8.8");function GE(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var Io="ERR_INVALID_ARG_VALUE",us="ERR_INVALID_ARG_TYPE";function Ft(e,t,r){let i=new TypeError(e,{cause:r});return Object.assign(i,{code:t}),i}var Hte=Symbol(),yNe=Symbol(),vNe=Symbol(),b4=Symbol();var UE=Symbol();var SNe=new TextEncoder,wNe=new TextDecoder;function f4(e){return typeof e=="string"?SNe.encode(e):wNe.decode(e)}var m4;Uint8Array.prototype.toBase64?m4=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):m4=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let i=0;i<t.byteLength;i+=32768)r.push(String.fromCharCode.apply(null,t.subarray(i,i+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var h4;Uint8Array.fromBase64?h4=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}}:h4=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}};function g4(e){return typeof e=="string"?h4(e):m4(e)}var tp=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=YNe,Error.captureStackTrace?.(this,this.constructor)}},Gh=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function ve(e,t,r){return new Gh(e,{code:t,cause:r})}function LE(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Wte(e){GE(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(p4&&!t.has("user-agent")&&t.set("user-agent",p4),t.has("authorization"))throw Ft('"options.headers" must not include the "authorization" header name',Io);return t}function bNe(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw Ft('"options.signal" must return or be an instance of AbortSignal',us);return t}}function ME(e,t,r,i,n){try{if(typeof e!="number"||!Number.isFinite(e))throw Ft(`${r} must be a number`,us,n);if(e>0)return;if(t){if(e!==0)throw Ft(`${r} must be a non-negative number`,Io,n);return}throw Ft(`${r} must be a positive number`,Io,n)}catch(o){throw i?ve(o.message,i,n):o}}function $r(e,t,r,i){try{if(typeof e!="string")throw Ft(`${t} must be a string`,us,i);if(e.length===0)throw Ft(`${t} must not be empty`,Io,i)}catch(n){throw r?ve(n.message,r,i):n}}function Jte(e){xNe(e,"application/json")}function _Ne(e,...t){let r='"response" content-type must be ';if(t.length>2){let i=t.pop();r+=`${t.join(", ")}, or ${i}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return ve(r,eUe,e)}function xNe(e,t){if(LNe(e)!==t)throw _Ne(e,t)}async function Zte(e){return $r(e,"codeVerifier"),g4(await crypto.subtle.digest("SHA-256",f4(e)))}function Xte(e){let t=e?.[yNe];return typeof t=="number"&&Number.isFinite(t)?t:0}function Yte(e){let t=e?.[vNe];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Qte(){return Math.floor(Date.now()/1e3)}function np(e){if(typeof e!="object"||e===null)throw Ft('"as" must be an object',us);$r(e.issuer,'"as.issuer"')}function ip(e){if(typeof e!="object"||e===null)throw Ft('"client" must be an object',us);$r(e.client_id,'"client.client_id"')}function Kte(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function ere(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{i.set("client_id",r.client_id),i.set("client_secret",e)}}function tre(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{let o=Kte(r.client_id),s=Kte(e),a=btoa(`${o}:${s}`);n.set("authorization",`Basic ${a}`)}}function rre(){return(e,t,r,i)=>{r.set("client_id",t.client_id)}}var ENe=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function ANe(e,t){if(t&&e.protocol!=="https:")throw ve("only requests to HTTPS are allowed",rUe,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw ve("only HTTP and HTTPS requests are allowed",nUe,e)}function Bte(e,t,r,i){let n;if(typeof e!="string"||!(n=ENe(e)))throw ve(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?iUe:oUe,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return ANe(n,i),n}function nre(e,t,r,i){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Bte(e.mtls_endpoint_aliases[t],t,r,i):Bte(e[t],t,r,i)}var y4=class extends Error{cause;code;error;status;error_description;response;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=XNe,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)}},qh=class extends Error{cause;code;error;error_description;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=QNe,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)}},v4=class extends Error{cause;code;response;status;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=ZNe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},zE="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",RNe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",INe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',$Ne="("+zE+")\\s*=\\s*"+INe,PNe="("+zE+")\\s*=\\s*("+zE+")",TNe=new RegExp("^[,\\s]*("+zE+")"),CNe=new RegExp("^[,\\s]*"+$Ne+"[,\\s]*(.*)"),kNe=new RegExp("^[,\\s]*"+PNe+"[,\\s]*(.*)"),DNe=new RegExp("^("+RNe+")(?:$|[,\\s])(.*)");function ONe(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);let t=e.headers.get("www-authenticate");if(t===null)return;let r=[],i=t;for(;i;){let n=i.match(TNe),o=n?.[1].toLowerCase();if(!o)return;let s=i.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;i=a?a[1]:void 0;let u={},l;if(c)for(;i;){let m,p;if(n=i.match(CNe)){[,m,p,i]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[m.toLowerCase()]=p;continue}if(n=i.match(kNe)){[,m,p,i]=n,u[m.toLowerCase()]=p;continue}if(n=i.match(DNe)){if(Object.keys(u).length)break;[,l,i]=n;break}return}else i=s||void 0;let d={scheme:o,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function NNe(e){if(e.status>399&&e.status<500){wre(e),Jte(e);try{let t=await e.clone().json();if(LE(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function ire(e,t,r){if(e.status!==t){zNe(e);let i;throw(i=await NNe(e))?(await e.body?.cancel(),new y4("server responded with an error in the response body",{cause:i,response:e})):ve(`"response" is not a conform ${r} response (unexpected HTTP status code)`,tUe,e)}}function UNe(e){if(!x4.has(e))throw Ft('"options.DPoP" is not a valid DPoPHandle',Io)}function LNe(e){return e.headers.get("content-type")?.split(";")[0]}async function ore(e,t,r,i,n,o,s){return await r(e,t,n,o),o.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[b4]||fetch)(i.href,{body:n,headers:Object.fromEntries(o.entries()),method:"POST",redirect:"manual",signal:bNe(i,s?.signal)})}async function _4(e,t,r,i,n,o){let s=nre(e,"token_endpoint",t.use_mtls_endpoint_aliases,o?.[Hte]!==!0);n.set("grant_type",i);let a=Wte(o?.headers);a.set("accept","application/json"),o?.DPoP!==void 0&&(UNe(o.DPoP),await o.DPoP.addProof(s,a,"POST"));let c=await ore(e,t,r,s,n,a,o);return o?.DPoP?.cacheNonce(c,s),c}async function sre(e,t,r,i,n){np(e),ip(t),$r(i,'"refreshToken"');let o=new URLSearchParams(n?.additionalParameters);return o.set("refresh_token",i),_4(e,t,r,"refresh_token",o,n)}var are=new WeakMap,MNe=new WeakMap;function cre(e){if(!e.id_token)return;let t=are.get(e);if(!t)throw Ft('"ref" was already garbage collected or did not resolve from the proper sources',Io);return t}async function qE(e,t,r,i,n,o){if(np(e),ip(t),!GE(r,Response))throw Ft('"response" must be an instance of Response',us);await ire(r,200,"Token Endpoint"),wre(r);let s=await lUe(r);if($r(s.access_token,'"response" body "access_token" property',tt,{body:s}),$r(s.token_type,'"response" body "token_type" property',tt,{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;ME(a,!0,'"response" body "expires_in" property',tt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&$r(s.refresh_token,'"response" body "refresh_token" property',tt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw ve('"response" body "scope" property must be a string',tt,{body:s});if(s.id_token!==void 0){$r(s.id_token,'"response" body "id_token" property',tt,{body:s});let a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ME(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),i?.length&&a.push(...i);let{claims:c,jwt:u}=await KNe(e,t,s.id_token,a,n);HNe(t,c),BNe(c),MNe.set(r,u),are.set(s,c)}if(o?.[s.token_type]!==void 0)o[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new tp("unsupported `token_type` value",{cause:{body:s}});return s}function zNe(e){let t;if(t=ONe(e))throw new v4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function ure(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}function jNe(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"});return t}function FNe(e,t){let r=e[dUe]?.(t)??e.issuer;if(t.claims.iss!==r)throw ve('unexpected JWT "iss" (issuer) claim value',rp,{expected:r,claims:t.claims,claim:"iss"});return t}var x4=new WeakSet;function GNe(e){return x4.add(e),e}var E4=Symbol();async function lre(e,t,r,i,n,o,s){if(np(e),ip(t),!x4.has(i))throw Ft('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Io);$r(n,'"redirectUri"');let a=du(i,"code");if(!a)throw ve('no authorization code in "callbackParameters"',tt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),o!==E4&&($r(o,'"codeVerifier"'),c.set("code_verifier",o)),_4(e,t,r,"authorization_code",c,s)}var dre={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 qNe(e,t){for(let r of e)if(t.claims[r]===void 0)throw ve(`JWT "${r}" (${dre[r]}) claim missing`,tt,{claims:t.claims});return t}function VNe(e,t){if(typeof t.claims[e]!="string")throw ve(`unexpected JWT "${e}" (${dre[e]}) claim type`,tt,{claims:t.claims});return t}function KNe(e,t,r,i,n){return sUe(r,aUe.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Xte(t),Yte(t),n).then(qNe.bind(void 0,["aud","exp","iat","iss","sub",...i])).then(FNe.bind(void 0,e)).then(jNe.bind(void 0,t.client_id)).then(VNe.bind(void 0,"sub"))}function pre(e,t){if(t===FE)return t;let r=t===void 0;return r&&(t=e.default_max_age),t===void 0?FE:(ME(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function BNe(e){e.auth_time!==void 0&&ME(e.auth_time,!0,'ID Token "auth_time" (authentication time)',tt,{claims:e})}function fre(e,t,r){if(r===FE)return;let i=Qte()+Xte(e),n=Yte(e);if(t.auth_time+r<i-n)throw ve("too much time has elapsed since the last End-User authentication",w4,{claims:t,now:i,tolerance:n,claim:"auth_time"})}function mre(e,t){let r=t===jE?void 0:t;if(e.nonce!==r)throw ve('unexpected ID Token "nonce" claim value',rp,{expected:r,claims:e,claim:"nonce"})}function HNe(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw ve('ID Token "aud" (audience) claim includes additional untrusted audiences',rp,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw ve('unexpected ID Token "azp" (authorized party) claim value',rp,{expected:e.client_id,claims:t,claim:"azp"})}}var jE=Symbol(),FE=Symbol();async function hre(e,t,r,i){return typeof i?.expectedNonce=="string"||typeof i?.maxAge=="number"||i?.requireIdToken?WNe(e,t,r,i.expectedNonce,i.maxAge,i[UE],i.recognizedTokenTypes):JNe(e,t,r,i?.maxAge,i?.[UE],i?.recognizedTokenTypes)}async function WNe(e,t,r,i,n,o,s){let a=[];switch(i){case void 0:i=jE;break;case jE:break;default:$r(i,'"expectedNonce" argument'),a.push("nonce")}n=pre(t,n),n!==FE&&a.push("auth_time");let c=await qE(e,t,r,a,o,s);$r(c.id_token,'"response" body "id_token" property',tt,{body:c});let u=cre(c);return fre(t,u,n),mre(u,i),c}async function JNe(e,t,r,i,n,o){let s=await qE(e,t,r,void 0,n,o),a=cre(s);return a&&(fre(t,a,pre(t,i)),mre(a,jE)),s}var ZNe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",XNe="OAUTH_RESPONSE_BODY_ERROR",YNe="OAUTH_UNSUPPORTED_OPERATION",QNe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var S4="OAUTH_PARSE_ERROR",tt="OAUTH_INVALID_RESPONSE";var eUe="OAUTH_RESPONSE_IS_NOT_JSON",tUe="OAUTH_RESPONSE_IS_NOT_CONFORM",rUe="OAUTH_HTTP_REQUEST_FORBIDDEN",nUe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",w4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",rp="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var iUe="OAUTH_MISSING_SERVER_METADATA",oUe="OAUTH_INVALID_SERVER_METADATA";async function gre(e,t,r,i,n){return np(e),ip(t),_4(e,t,r,"client_credentials",new URLSearchParams(i),n)}async function yre(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}async function vre(e,t,r,i,n){np(e),ip(t),$r(i,'"token"');let o=nre(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,n?.[Hte]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",i);let a=Wte(n?.headers);return a.delete("accept"),ore(e,t,r,o,s,a,n)}async function Sre(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);await ire(e,200,"Revocation Endpoint")}function wre(e){if(e.bodyUsed)throw Ft('"response" body has been used already',Io)}async function sUe(e,t,r,i,n){let{0:o,1:s,length:a}=e.split(".");if(a===5)if(n!==void 0)e=await n(e),{0:o,1:s,length:a}=e.split(".");else throw new tp("JWE decryption is not configured",{cause:e});if(a!==3)throw ve("Invalid JWT",tt,e);let c;try{c=JSON.parse(f4(g4(o)))}catch(d){throw ve("failed to parse JWT Header body as base64url encoded JSON",S4,d)}if(!LE(c))throw ve("JWT Header must be a top level object",tt,e);if(t(c),c.crit!==void 0)throw new tp('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(f4(g4(s)))}catch(d){throw ve("failed to parse JWT Payload body as base64url encoded JSON",S4,d)}if(!LE(u))throw ve("JWT Payload must be a top level object",tt,e);let l=Qte()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw ve('unexpected JWT "exp" (expiration time) claim type',tt,{claims:u});if(u.exp<=l-i)throw ve('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',w4,{claims:u,now:l,tolerance:i,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw ve('unexpected JWT "iat" (issued at) claim type',tt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw ve('unexpected JWT "iss" (issuer) claim type',tt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw ve('unexpected JWT "nbf" (not before) claim type',tt,{claims:u});if(u.nbf>l+i)throw ve('unexpected JWT "nbf" (not before) claim value',w4,{claims:u,now:l,tolerance:i,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw ve('unexpected JWT "aud" (audience) claim type',tt,{claims:u});return{header:c,claims:u,jwt:e}}function aUe(e,t,r,i){if(e!==void 0){if(typeof e=="string"?i.alg!==e:!e.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?i.alg!==r:typeof r=="function"?!r(i.alg):!r.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:r,reason:"default value"});return}throw ve('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function du(e,t){let{0:r,length:i}=e.getAll(t);if(i>1)throw ve(`"${t}" parameter must be provided only once`,tt);return r}var cUe=Symbol(),uUe=Symbol();function bre(e,t,r,i){if(np(e),ip(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ft('"parameters" must be an instance of URLSearchParams, or URL',us);if(du(r,"response"))throw ve('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',tt,{parameters:r});let n=du(r,"iss"),o=du(r,"state");if(!n&&e.authorization_response_iss_parameter_supported)throw ve('response parameter "iss" (issuer) missing',tt,{parameters:r});if(n&&n!==e.issuer)throw ve('unexpected "iss" (issuer) response parameter value',tt,{expected:e.issuer,parameters:r});switch(i){case void 0:case uUe:if(o!==void 0)throw ve('unexpected "state" response parameter encountered',tt,{expected:void 0,parameters:r});break;case cUe:break;default:if($r(i,'"expectedState" argument'),o!==i)throw ve(o===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',tt,{expected:i,parameters:r})}if(du(r,"error"))throw new qh("authorization response from the server is an error",{cause:r});let a=du(r,"id_token"),c=du(r,"token");if(a!==void 0||c!==void 0)throw new tp("implicit and hybrid flows are not supported");return GNe(new URLSearchParams(r))}async function lUe(e,t=Jte){let r;try{r=await e.json()}catch(i){throw t(e),ve('failed to parse "response" body as JSON',S4,i)}if(!LE(r))throw ve('"response" body must be a top level object',tt,{body:r});return r}var dUe=Symbol();function Vh(e){if(e==="")return[];if(!e.startsWith("/")||/~(?![01])/u.test(e))throw new Error("Invalid JSON pointer.");let t=e.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(t.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return t}function Wn(e,t){for(let r of Vh(t)){if(e===null||typeof e!="object"||!Object.hasOwn(e,r))return;e=e[r]}return e}function A4(e,t,r){let i=Vh(t),n=i.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let o of i){if(e===null||typeof e!="object"||!Object.hasOwn(e,o))throw new Error("JSON pointer target does not exist.");e=e[o]}if(e===null||typeof e!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(e)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=e.length))throw new Error("Invalid array index.");e[n]=r}function La(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);throw new Error("The selected value is not text.")}function VE(e,t){return typeof t=="string"?La(Wn(e,t)):t.map(r=>typeof r=="string"?r:La(Wn(e,r.pointer))).join("")}function op(e,t){let r=new Set;for(let i of t)i&&(r.add(i),r.add(encodeURIComponent(i)),r.add(JSON.stringify(i).slice(1,-1)));for(let i of[...r].sort((n,o)=>o.length-n.length))e=e.split(i).join("[redacted]");return e}function R4(e,t){return btoa(Array.from(new TextEncoder().encode(e+":"+t),r=>String.fromCharCode(r)).join(""))}var _re=Object.assign(Object.create(null),{dpop:()=>M(502,"invalid_response","The service returned an unsupported token.")}),fUe={redirectUri:e=>e.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),_re,{"user access token":()=>{}})},mUe={authorize(e,t){delete e.response_type,delete e.client_id,delete e.redirect_uri,e.callback_url=t,e.key_label="Foundation"},async exchange({spec:e,transport:t,url:r,authorization:i,verifier:n}){let o=i.parameters;return(o.getAll("state").length!==1||o.get("state")!==i.state||o.getAll("code").length!==1||!o.get("code"))&&M(400,"invalid_state","Start the connection again."),t.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:o.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},hUe={revokeRequest({app:e,url:t,current:r}){return{url:t,method:"DELETE",headers:{authorization:"Basic "+R4(e.clientId,e.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},gUe={tokenParameters(e){let t=e.get("redirect_uri");t!==null&&(e.set("redirect_url",t),e.delete("redirect_uri"))}};function $o(e,t){let r=t?new URL(t):void 0;return{recognizedTokenTypes:_re,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(i){i.token_type===void 0&&(i.token_type="bearer")},...e.grantType==="client_credentials"?{clientCredentialsParameters(){return{...e.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(i){i.refresh_token===null&&delete i.refresh_token}}:{},...e.adapter==="ebay"?fUe:e.adapter==="openrouter"?mUe:e.adapter==="vultr"?gUe:{},...e.revoke?.style==="github"?hUe:{}}}function pu(e,t){try{return Pn(new sw(e).expand(t)).href}catch{M(400,"invalid_service_url","Check the service URL and its required fields.")}}var xre=(e,t=" ")=>typeof e=="string"?[...new Set(e.split(t).filter(Boolean))].sort():[],KE=e=>{let t=typeof e=="number"||typeof e=="string"?Number(e):NaN;return(!Number.isSafeInteger(t)||t<=0||t>315576e3)&&M(502,"invalid_response","The service returned an invalid expiry."),t};var BE=class{constructor(t){this.transport=t}transport;appValues(t,r){try{return{...qs(t.fields,r.fields,t.defaults),clientId:r.clientId}}catch(i){throw i instanceof Gs&&M(400,i.code,i.message),i}}async authorize(t,r,i,n,o,s){(t.grantType==="client_credentials"||!t.authorizeUrl)&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(pu(t.authorizeUrl,this.appValues(t,r))),c={...t.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:$o(t).redirectUri?.(r,o)??o,state:i};s.length&&(c.scope=s.join(t.scopes.separator)),t.pkce&&(c.code_challenge=await Zte(n),c.code_challenge_method="S256"),$o(t).authorize?.(c,o);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(t,r){let i={issuer:t.issuer??new URL(pu(t.grantType==="client_credentials"?t.tokenUrl:t.authorizeUrl,this.appValues(t,r))).origin,token_endpoint:pu(t.tokenUrl,this.appValues(t,r))};return t.issuer&&Pn(t.issuer),{server:i,client:{client_id:r.clientId}}}authentication(t,r){return r==="none"?rre():(t.clientSecret||M(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?tre(t.clientSecret):ere(t.clientSecret))}options(t){let r=t?.tokenFormat??"form";return{[b4]:async(i,{body:n,headers:o,method:s,signal:a})=>{let c=new URLSearchParams(n);t&&$o(t).tokenParameters?.(c);let u=await this.transport.send({url:i,method:s,headers:r==="json"?{...o,"content-type":"application/json"}:o,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(t){return Cl({status:t.status,headers:{},body:new Uint8Array(await t.arrayBuffer())})}checkResponse(t,r,i,n=!1){return(r>=400||i.error||t.okPointer&&Wn(i,t.okPointer)!==!0)&&(n&&(i.error==="invalid_grant"||i.error==="invalid_token")&&M(409,"reconnect_required","Reconnect this service to renew access."),r===429&&M(503,"service_rate_limit","The service is busy. Try again later."),M(502,"authorization_failed","The service did not authorize this connection.")),i}async tokenResponse(t,r,i,n=!1){i.status===429&&M(503,"service_rate_limit","The service is busy. Try again later.");let o=this.checkResponse(t,i.status,await this.json(i),n),{server:s,client:a}=this.configuration(t,r),c=new URL(s.token_endpoint),u={...o};delete u.id_token,$o(t,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=KE(u.expires_in));try{let d=await(n?ure:t.grantType==="client_credentials"?yre:hre)(s,a,Response.json(u,{status:i.status}),{recognizedTokenTypes:$o(t,c.href).recognizedTokenTypes});return{...o,...d}}catch(l){if(l instanceof Me)throw l;M(502,"invalid_response","The service did not return a valid access token.")}}token(t,r,i,n,o=!1){let s=r[$o(t).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&M(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+KE(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&M(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of t.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?xre(r.scope,t.scopes.separator):o?n?.scopes??i:i,scopesStatus:r.scope!==void 0?"reported":o?n?.scopesStatus??"unknown":i.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()+KE(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(t,r,i,n,o,s,a,c){t.grantType==="client_credentials"&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=$o(t);if(l.exchange){let m=await l.exchange({spec:t,app:r,transport:this.transport,url:()=>pu(t.tokenUrl,this.appValues(t,r)),authorization:i,verifier:n});u=this.checkResponse(t,m.status,Cl(m))}else{let{server:m,client:p}=this.configuration(t,r),g;try{let v=bre(m,p,i.parameters,i.state);g=await lre(m,p,this.authentication(r,t.clientAuth),v,l.redirectUri?.(r,o)??o,t.pkce?n:E4,{...this.options(t),additionalParameters:t.tokenParams})}catch(v){throw(v instanceof Gh||v instanceof qh)&&M(400,"invalid_state","Start the connection again."),v}u=await this.tokenResponse(t,r,g)}let d=this.token(t,u,s,a);return await c?.(d,u),d}async clientCredentials(t,r,i,n,o){t.grantType!=="client_credentials"&&M(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(t,r),c=$o(t,s.token_endpoint),u={...t.tokenParams,...i.length?{scope:i.join(t.scopes.separator)}:{}},l=await gre(s,a,this.authentication(r,t.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(t)),d=await this.tokenResponse(t,r,l),m={...this.token(t,d,i,n,!!n),requestedScopes:i};return await o?.(m,d),m}async refresh(t,r,i,n){let o=i;if(i.expiresAt!==null&&i.expiresAt<Date.now()+6e4){if(t.grantType==="client_credentials")return i.requestedScopes||M(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(t,r,i.requestedScopes,i,n);(!i.refreshToken||i.refreshExpiresAt&&i.refreshExpiresAt<=Date.now())&&M(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(t,r),c=await sre(s,a,this.authentication(r,t.clientAuth),i.refreshToken,{...this.options(t),additionalParameters:t.tokenParams}),u=await this.tokenResponse(t,r,c,!0);o=this.token(t,u,i.scopes,i,!0),await n?.(o,u)}return o}async revoke(t,r,i){if(!t.revoke?.tokenOnly)throw new Error("Revoke only with an endpoint that invalidates this token alone.");let n=pu(t.revoke.url,{...this.appValues(t,r),accessToken:i.accessToken,refreshToken:i.refreshToken??""});if(t.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(t,r),l=t.revoke.auth==="none"&&t.clientAuth!=="none"?()=>{}:this.authentication(r,t.revoke.auth??t.clientAuth),d=await vre({...c,revocation_endpoint:n},u,l,i.refreshToken??i.accessToken,this.options());try{await Sre(d)}catch{M(502,"revoke_failed","The service did not revoke the token.")}return}let o={},s=t.revoke.auth??t.clientAuth;t.revoke.style==="bearer"?o.authorization="Bearer "+i.accessToken:s==="basic"&&(o.authorization="Basic "+R4(r.clientId,r.clientSecret??"")),(await this.transport.send($o(t).revokeRequest?.({spec:t,app:r,transport:this.transport,url:n,current:i})??{url:n,method:t.revoke.style==="bearer"?"POST":"DELETE",headers:o})).status>=300&&M(502,"revoke_failed","The service did not revoke the token.")}outputs(t,r,i){let n={...this.appValues(t,r),...i.extra,...i,expiresAt:i.expiresAt===null?"":String(i.expiresAt)};return Object.fromEntries(Object.entries(t.outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};function I4(e){if(e.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return e.method.config}function $4(e){return e||M(409,"app_required","Choose an OAuth application."),e}function yUe(e){return{token:MO.parse(e.token),response:Mt.parse(e.response)}}var HE=class{constructor(t){this.transport=t}transport;facts=vO;oauth(t){return new BE({send:r=>this.transport.send({...r,...t?{signal:AbortSignal.any([t,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(t){return!t.oauth||t.oauth.expiresAt!==null&&t.oauth.expiresAt<Date.now()+6e4}async renew(t){let r=t.material,i=I4(r),n=$4(t.app),o=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>t.receive({token:c,response:u}),a=i.grantType==="client_credentials"?await this.oauth(t.signal).clientCredentials(i,n,o??rV(i.scopes),r.oauth,s):await this.oauth(t.signal).refresh(i,n,r.oauth,s);return Pl.parse({...t.material,oauth:a})}async recover(t,r,i){let o=yUe(i).token;return Pl.parse({...t,oauth:o})}async outputs(t,r){return this.oauth().outputs(I4(t),$4(r),t.oauth)}async revoke(t,r,i){t.oauth&&await this.oauth(i).revoke(I4(t),$4(r),t.oauth)}};function vUe(e){if(e.method.kind!=="token"&&e.method.kind!=="approval")throw new Error("Use an input credential provider.");return e.method.config}var Kh=class{facts=El;needsRenewal(){return!1}async outputs(t){let r=vUe(t),i=qs(r.fields,t.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,o])=>[n,VE(i,o)]))}};function WE(e){if(e.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return e.method.config}var JE=class{facts=SO;values(t,r){let i=WE(t),n=i.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&M(409,"app_required","Choose an OVHcloud API application with its key and secret.");let o=n?r.fields:t.fields;return qs(i.fields,o)}credentials(t,r){if(WE(t).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:t.fields.consumerKey};let i=this.values(t,r);return{applicationKey:i.applicationKey,applicationSecret:i.applicationSecret,consumerKey:i.consumerKey}}needsRenewal(){return!1}async outputs(t,r){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let i="ovh"in t?t.ovh:void 0;i&&i.expiresAt!==null&&i.expiresAt<=Date.now()&&M(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=WE(t).authorization==="consumer_key"?{...this.values(t,r),...this.credentials(t,r)}:this.values(t,r);return Object.fromEntries(Object.entries(WE(t).outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};import{readFile as SUe}from"node:fs/promises";var wUe=f.object({accessToken:f.string().min(1).max(16384).regex(/^\S+$/),expiresAt:f.number().int().positive()}).strict();async function bUe(e,t){if(e==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,o=n?await SUe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!o||o.length>16384)&&M(409,"authentication_required","Provide the current OIDC token to this executor."),o.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([t,AbortSignal.timeout(3e3)])});r.ok||M(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let i=(await r.text()).trim();return(!i||i.length>16384)&&M(502,"invalid_response","The instance did not return a valid identity token."),i}function Ere(e){if(e.method.kind!=="token"||e.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return e.method.config}var ZE=class{constructor(t,r=bUe){this.transport=t;this.identityToken=r}transport;identityToken;facts=El;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(t,r){let i=qs(Ere(t).fields,t.fields),n=i.authentication;["api_key","oidc","instance"].includes(n)||M(400,"invalid_field","Choose a Vultr authentication source.");let o=n==="api_key"?i.token:i.credential||await this.identityToken(n,r);(!o||o.length>16384||/\s/.test(o))&&M(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(i.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&M(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+o},signal:r,body:JSON.stringify({role_id:i.roleId,session_name:i.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:i.userId}:{},...n==="oidc"?{oidc_issuer_id:i.issuerId}:{}})});a.status>=400&&M(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=Cl(a);(c.role_id!==void 0&&c.role_id!==i.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==i.userId)&&M(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=wUe.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&M(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(t,r,i){let n=Ere(t);i.throwIfAborted();let o=await te(t),s=this.sessions.get(o);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(o);a||(a=this.obtain(t,i),this.pending.set(o,a));try{s=await a,this.sessions.set(o,s)}finally{this.pending.get(o)===a&&this.pending.delete(o)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,VE(s,c)]))}};function Are(e,t){let r={oauth:new HE(e),token:new Kh,aws:new NE(t),approval:new Kh,ovh:new JE},i=new ZE(e);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?i:r[n.kind]}function Ci(e){return new TextDecoder("utf-8",{fatal:!0}).decode(e)}async function P4(e,t){let r={},i={},n=[],o=new Set;for(let s of e){if(o.has(s.name)||!xq(s.name))throw new Error("Use distinct, unreserved environment variable names.");o.add(s.name);let a=await t(s.source);if(s.format==="json"&&(a=ft(La(Wn(JSON.parse(Ci(a)),s.pointer??"")))),s.format==="file")i[s.name]=Buffer.from(a).toString("base64");else{let c=Ci(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:i,sensitive:n}}var sp=class{constructor(t,r,i,n,o,s=new OE){this.binding=t;this.keys=r;this.broker=i;this.journal=n;this.providers=Are(o,s)}binding;keys;broker;journal;active=new Set;providers;provider(t){return this.providers(t)}metadata(t){return BV(t,this.provider(t.method).facts(t))}source(t,r,i){let n=i.find(o=>o.policy.id===t&&o.policy.contentType===r);return n||M(409,"input_required","Include the connection and its application in this execution."),n}async material(t,r,i){let n=typeof i=="function"?a=>i(Pl.parse(JSON.parse(Ci(a)))):i,o=Pl.safeParse(JSON.parse(Ci(await Ec(t,r,this.keys,{destination:n}))));o.success||M(409,"reconnect_required","Reconnect this service with the current connection format.");let s=o.data;return(await this.metadata(s)).authorizationDigest!==t.metadata.authorizationDigest&&M(409,"connection_changed","Approve the current service account and permissions before using this connection."),s.state==="reconnect"&&r.operation!==Q.revoke&&M(409,"reconnect_required","Reconnect this service before using it."),s}async app(t,r,i,n){let o=this.source(t,ge.clientCredential,n),s=aw.parse(JSON.parse(Ci(await Ec(o,i,this.keys))));return s.methodId!==r&&M(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(t,r,i){if(Ls(t.method).application==="none")return null;if(!xl(t.method))return"implicitApp"in t&&t.implicitApp?t.implicitApp:aw.parse({format:1,methodId:t.methodId,generation:t.generation,clientId:"",fields:{}});let n=r.operation===Q.revoke?Q.revoke:Q.refresh,o=await this.app(t.appId,t.methodId,{...r,operation:n},i);return o.generation!==t.appGeneration&&M(409,"app_changed","Reconnect this service with the current application."),Ls(t.method).requiresApp&&t.method.kind!=="aws"&&Object.entries($l(t.method.config.fields,t.fields??{})).some(([s,a])=>o.fields[s]!==a)&&M(409,"app_changed","Reconnect this service with the current application settings."),o}async validate(t,r,i){let n=zO.parse(t);r.operation!==Q[n.action]&&M(400,"wrong_operation","Use the approved connection operation.");let o=await this.material(this.source(n.id,ge.tokenSet,i),r);(n.action==="refresh"||Ls(o.method).revocable)&&await this.connectionApp(o,r,i)}async execute(t,r,i,n){let o=zO.parse(t);this.active.has(o.id)&&M(409,"connection_busy","Another operation is updating this connection."),this.active.add(o.id);try{n.throwIfAborted();let s=this.source(o.id,ge.tokenSet,i),a=await this.material(s,r);if(o.action==="refresh"){let l=await this.refresh(s,a,r,i,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(l)}}let c=this.provider(a.method),u=Ls(a.method).revocable&&!!c.revoke;return u&&await c.revoke(a,await this.connectionApp(a,r,i),n),{kind:"disconnected",id:s.policy.id,revoked:u}}finally{this.active.delete(o.id)}}async outputs(t,r,i,n,o){let s=await this.material(t,r,o);return this.provider(s.method).renew&&await this.broker.state(t.policy.id)&&M(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(t,s,r,i,n,o),this.provider(s.method).outputs(s,await this.connectionApp(s,r,i),n)}async httpDestination(t,r,i){let n=await this.material(t,r,o=>VO(o,i,r.origin));return VO(n,i,r.origin)}async http(t,r,i,n,o){let s=await this.httpDestination(t,r,o),a=await this.material(t,r,s),c=await this.outputs(t,r,i,n,s);return n3(s,o.headers,a.method.http,c)}async refreshed(t,r){let i=await this.metadata(r);return i.authorizationDigest!==t.previous.metadata.authorizationDigest&&M(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),t.material=r,t.content=await Gq(t.previous,ft(k(r)),this.binding,this.keys,i),t.phase="settled",await this.journal.write("refresh_"+t.operation.id,t),await this.broker.commit(t.operation.id,t.operation.fence,t.content),t.delivered=!0,await this.journal.write("refresh_"+t.operation.id,t),r}async refresh(t,r,i,n,o,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||M(409,"reconnect_required","Reconnect this service to renew access.");try{await Os(t,{...i,operation:Q.refresh},{destination:s})}catch{M(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,i,n),u=_Ue(),l=await this.broker.prepare(u,t.policy.id,t.materialRevision),d={operation:l,previous:t,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{o.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),o.throwIfAborted();let m=await a.renew({material:r,app:c,signal:o,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,m)}catch(m){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),m instanceof Me&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(m.code))throw m;M(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let t=[];for(let r of await this.journal.pending("refresh_"))try{let i=await this.journal.read(r);if(i.delivered)continue;if(i.content){await this.broker.commit(i.operation.id,i.operation.fence,i.content),i.delivered=!0,await this.journal.write(r,i);continue}let n=await this.broker.state(i.operation.resource_id);if(!n||n.id!==i.operation.id||n.state==="prepared")n?.id===i.operation.id&&n.state==="prepared"&&await this.broker.abort(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i);else if(i.checkpoint&&this.provider(i.material.method).recover){let o=await this.provider(i.material.method).recover(i.material,i.app,i.checkpoint);await this.refreshed(i,o)}else await this.broker.uncertain(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i)}catch{t.push(r.slice(8))}return t}};import{lookup as xUe}from"node:dns/promises";import{request as EUe}from"node:https";import{brotliDecompressSync as AUe,gunzipSync as RUe,inflateSync as IUe}from"node:zlib";var XE=class{constructor(t){this.origin=t}origin;async send(t){let r=Pn(t.url,this.origin),i=r.hostname.replace(/^\[|\]$/g,""),n=t.maxBytes??1048576;t.body&&Buffer.byteLength(t.body)>n&&M(413,"body_limit","The request body is too large.");let o={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(t.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))&&M(400,"invalid_header","Choose a valid request header."),o[c]=a}try{let s=await xUe(i,{all:!0,verbatim:!0});(!s.length||s.some(u=>!uw(u.address)))&&M(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]]);return await new Promise((u,l)=>{let d={method:t.method??"GET",headers:o,signal:c,agent:!1,lookup:(p,g,v)=>{g.all?v(null,[a]):v(null,a.address,a.family)}},m=EUe(r,d,p=>{let g=[],v=0;p.on("data",S=>{v+=S.length,v>n?p.destroy(new Me(413,"body_limit","The response body is too large.")):g.push(S)}),p.on("error",l),p.on("end",()=>{try{let S=Buffer.concat(g),b=p.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?RUe:b==="deflate"?IUe:b==="br"?AUe:null;if(!x)throw new Me(502,"invalid_response","The service returned an unsupported response.");S=x(S,{maxOutputLength:n})}let _={};for(let[x,T]of Object.entries(p.headers))T!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(_[x]=Array.isArray(T)?T.join(", "):T);u({status:p.statusCode??502,headers:_,body:new Uint8Array(S)})}catch(S){l(S)}})});m.on("error",l),m.end(t.body)})}catch(s){if(s instanceof Me)throw s;t.signal?.aborted&&M(409,"cancelled","The operation was cancelled."),M(502,"service_unavailable","The service could not be reached. Try again.")}}};function Rre(e){let{keys:t,binding:r,origin:i}=e.identity;if(!t||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=T4($Ue(gO()),"custody",r.id),o=new Tc(T4(n,"client"),i,r,t),s=new lw(e,i,r,t,new pw(o)),a=new fw(e),c=new XE(i),u=new sp(r,t,a.connections(),new Tc(T4(n,"connections"),i,r,t),c);return{custody:s,journal:o,directory:n,keys:t,binding:r,broker:a,transport:c,connections:u}}function PUe(e,t){let r={};if(Object.keys(t).some(i=>!e.parameters.some(n=>n.name===i)))throw new Error("Use the parameters this function declares.");for(let i of e.parameters){let n=Object.hasOwn(t,i.name)?t[i.name]:i.default;if(n===void 0){if(i.required)throw new Error("Complete the required function parameters.");continue}if(i.type!=="json"&&typeof n!==i.type||i.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(i.required&&i.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[i.name]=n}return r}function YE(e,t){let r=PUe(e,t);if(e.program.kind==="command"){let{kind:c,...u}=e.program;return{kind:c,...vc.parse({...u,stdin:JSON.stringify(r)})}}if(e.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");let i=e.program.request,n=c=>typeof c=="string"?c:JSON.stringify(c),o=(c,u=!1)=>{if(u&&typeof c=="string"){let l=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(c)?.[1];if(l){if(!e.parameters.some(d=>d.name===l))throw new Error("Declare every function parameter.");return Object.hasOwn(r,l)?r[l]:null}}return typeof c=="string"?c.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(l,d)=>{if(!e.parameters.some(m=>m.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?n(r[d]):""}):Array.isArray(c)?c.map(l=>o(l,u)):c&&typeof c=="object"?Object.fromEntries(Object.entries(c).map(([l,d])=>[l,o(d,u)])):c},s=i.url===void 0?void 0:new sw(i.url).expand(Object.fromEntries(Object.entries(r).map(([c,u])=>[c,n(u)]))),a=yc.parse({...o(i),...s===void 0?{}:{url:s},connectionId:i.connectionId,bindings:i.bindings,...i.json===void 0?{}:{json:o(i.json,!0)}});if(i.url!==void 0){let c=new URL(i.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,responseFormat:e.program.responseFormat}}var NPt=f.object({operation:Ic,save:f.record(f.string(),be)}).strict();function TUe(e){return e.kind==="http"?{kind:e.kind,request:e.request}:e}async function Ire(e,t){let r=e.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=Dq.parse(r.invocation.input);if(t.kind!=="revoke"||k(t.input)!==k({action:"revoke",id:n.connectionId})||n.ownerId!==e.ownerId||n.environmentId!==e.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 i=Oq.parse(r.invocation.input);if(i.ownerId!==e.ownerId||i.environmentId!==e.environmentId||i.operation.kind!==t.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in i.operation){if(await te(TUe(t))!==i.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(t.kind==="http"&&i.operation.kind==="http"){if(k(t.request)!==k(i.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(k(t)!==k(Ic.parse(i.operation)))throw new Error("Run the reviewed command.");if(t.kind==="http"&&k(Object.fromEntries(Object.entries(t.save).map(([n,o])=>[n,o.name])))!==k(i.save))throw new Error("Use the reviewed output destinations.")}function CUe(e,t){return e.policy.contentType===ge.value?t.output===void 0:e.policy.contentType===ge.tokenSet&&t.output!==void 0}var Po=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}};function C4(e){return!(e instanceof Me)||["service_unavailable","connection_uncertain","lease_lost"].includes(e.code)}var QE=class{constructor(t,r,i,n,o,s,a,c=s){this.environment=t;this.keys=r;this.broker=i;this.journal=n;this.transport=o;this.commands=s;this.extension=a;this.functionCommands=c}environment;keys;broker;journal;transport;commands;extension;functionCommands;get binding(){return this.environment.manifest.executor}async reconcile(){let t=[];for(let r of await this.journal.pending("run_"))try{let i=await this.journal.read(r);if(!i||i.delivered)continue;if(!i.receipt&&i.phase==="dispatched"){let n=i.operation?.kind==="connect"?await this.extension?.recover?.(i.operation.input,i.request.intent):null;i.receipt=n?await _l(i.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await _l(i.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),i.phase="settled",await this.journal.write(r,i)}i.receipt&&(await this.broker.finish(i.lease,i.receipt),i.delivered=!0,await this.journal.write(r,i))}catch{t.push(r.slice(4))}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:i}=r.request,n="run_"+i.id,o=await te(r.request),s=await this.journal.read(n);if(s&&s.digest!==o)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 m=await _l(i,"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:m,delivered:!1}),await this.broker.finish(r.lease,m),!0}s={digest:o,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([t,a.signal]),u=setInterval(()=>{this.broker.renew(i.id,r.lease).then(m=>{m.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let m=await Vq(r.request,this.binding,this.keys);await bl(this.environment,m.intent);let p=Ic.parse(m.operation);if(Q[p.kind]!==i.operation)throw new Error("Use the operation authorized by this intent.");await Ire(i,p),await this.validateOperation(p,i,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(i.id,r.lease),c.throwIfAborted();let g=await this.executeOperation(p,i,r.sources,c);d=await _l(i,"succeeded",{ok:!0,result:g,error:null},this.keys)}catch(m){if(m instanceof Po)throw m;m instanceof Sl&&(m=new Me(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||C4(m));d=await _l(i,p?"uncertain":"failed",{ok:!1,result:null,error:m instanceof Me?{code:m.code,message:m.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(t){let r=t.kind==="function"?YE(t.definition,t.arguments):t;return r.kind==="http"?r.request:null}async validateOperation(t,r,i){if(new Set(i.map(u=>u.policy.id)).size!==i.length||i.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let u of i){await sn(u);let l=r.sources.find(p=>p.id===u.policy.id);if(!l||!await aO(u,l))throw new Error("An execution input changed.");let d="checkpoint_"+u.policy.format+"_"+u.policy.id,m=await this.journal.read(d);if(m&&(u.policy.revision<m.policy||u.materialRevision<m.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(d,{policy:u.policy.revision,material:u.materialRevision})}if(t.kind==="function"&&(t.functionId!==r.functionId||await te(t.definition)!==r.functionDigest||!this.environment.manifest.capabilities.includes(Q[t.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(t.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(t),o=n?.url;if(n){if(n.connectionId){let u=i.find(l=>l.policy.id===n.connectionId);if(this.environment.manifest.httpVersion!==zi||!this.extension?.httpDestination||!u||u.policy.contentType!==ge.tokenSet)throw new Error("Choose an HTTP connection and a current execution environment.");o=await this.extension.httpDestination(u,r,n)}if(Pn(o,r.origin),[n.body,n.json,n.form].filter(u=>u!==void 0).length>1)throw new Error("Choose one request body format.");for(let u of n.bindings){let l=Vh(u.pointer);if(!l.length||!["headers","body","json","form"].includes(l[0])||l[0]==="body"&&l.length!==1||["headers","form"].includes(l[0])&&l.length!==2)throw new Error("Bind credentials to request headers or the body.");A4(structuredClone(n),u.pointer,"validation")}}let s=t.kind==="function"?t.outputs:t.kind==="http"?t.save:{};for(let[u,l]of Object.entries(s)){if(Vh(u),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let d=await Us(l.approval);if(k(d.policy.authorities.find(m=>m.id===d.authorityId))!==k(r.actor)||d.policy.origin!==r.origin||d.policy.contentType!==ge.value||d.policy.ownerId!==r.ownerId||!d.policy.producers.some(m=>m.runId===r.id&&k(m.executor)===k(this.binding)&&Date.parse(m.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let a=t.kind==="function"?YE(t.definition,t.arguments):t,c=a.kind==="command"?a.inputs.map(u=>u.source):n?Lf(n):[];for(let u of c){let l=i.find(m=>m.policy.id===u.id),d=n?.connectionId===u.id&&u.output===void 0;if(!l||!(d?l.policy.contentType===ge.tokenSet:CUe(l,u)))throw new Error("Use the input named in the signed request.");await Os(l,r,{destination:o}),await Ec(l,r,this.keys,{destination:o})}if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(t.input,r,i)}}async executeOperation(t,r,i,n){if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke")return this.extension.execute(t.input,r,i,n);let o=this.request(t),s=t.kind==="function"?YE(t.definition,t.arguments):t,a=o?.connectionId?await this.extension.httpDestination(i.find(v=>v.policy.id===o.connectionId),r,o):o?.url,c=[],u=new Map,l=async v=>{let S=i.find(_=>_.policy.id===v.id);if(S.policy.contentType===ge.value)return Ec(S,r,this.keys,{...o?{destination:a}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");u.has(v.id)||u.set(v.id,this.extension.outputs(S,r,i,n,a));let b=await u.get(v.id);if(!v.output||!Object.hasOwn(b,v.output))throw new Error("Choose an available connection output.");return ft(b[v.output])};if(s.kind==="command"){let v=await P4(s.inputs,l),b=await(t.kind==="function"?this.functionCommands:this.commands).execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:v.environment,files:v.files,...t.kind==="function"?{workspace:"temporary"}:{}},n);if(t.kind==="function"){if(b.timedOut)throw new Me(408,"function_timeout","The function exceeded its time limit.");if(b.truncated)throw new Me(413,"function_output_limit","The function output exceeded its size limit.");if(b.exitCode!==0)throw new Me(422,"function_failed",op(b.stderr,v.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(t,r,b.stdout)}return{...b,stdout:op(b.stdout,v.sensitive),stderr:op(b.stderr,v.sensitive)}}let d=structuredClone(o);for(let v of d.bindings){let S="";for(let b of v.parts)if(typeof b=="string")S+=b;else{let _=Ci(await l(b));c.push(_,Buffer.from(_).toString("base64"),Buffer.from(_).toString("base64url")),S+=_}A4(d,v.pointer,S)}if(d.connectionId){if(!this.extension?.http)throw new Error("This executor cannot use HTTP connections.");let v=await this.extension.http(i.find(S=>S.policy.id===d.connectionId),r,i,n,d);d.url=v.url,d.headers=v.headers,c.push(...v.sensitive)}let m=d.body;d.json!==void 0&&(m=JSON.stringify(d.json),d.headers["content-type"]="application/json"),d.form!==void 0&&(m=new URLSearchParams(d.form).toString(),d.headers["content-type"]="application/x-www-form-urlencoded");let p=await this.transport.send({url:d.url,method:d.method,headers:d.headers,...m===void 0?{}:{body:m},signal:n});if(t.kind==="function"){if(p.status<200||p.status>=300)throw new Me(502,"service_response","The service returned HTTP "+p.status+".");let v=t.definition.program.kind==="http"?t.definition.program.responseFormat:"json",S=Ci(p.body);if(v==="json")try{S=p.body.length===0&&([204,205].includes(p.status)||d.method==="HEAD")?null:Nr.parse(JSON.parse(S))}catch{throw new Me(422,"invalid_function_result","The HTTP response body must contain valid JSON.")}return this.functionResult(t,r,JSON.stringify({status:p.status,headers:p.headers,body:S}))}let g=t.kind==="http"?t.save:{};if(Object.keys(g).length){if(p.status>=400)throw new Me(502,"service_response","The service returned an unsuccessful response.");let v={};for(let[S,b]of Object.entries(g)){let _=p.body;if(S!==""){let T=Wn(JSON.parse(Ci(_)),S);if(T===void 0)throw new Me(400,"invalid_pointer","The response value was not found.");_=ft(typeof T=="string"?T:JSON.stringify(T))}let x=await Rf(_,b.approval,r.id,this.binding,this.keys,{bytes:_.length});v[b.name]=(await this.broker.capture(b.name,x)).id}return{status:p.status,saved:v}}return{status:p.status,headers:Object.fromEntries(Object.entries(p.headers).map(([v,S])=>[v,op(S,c)])),body:op(Ci(p.body),c)}}async functionResult(t,r,i){let n;try{n=t.definition.result==="text"?i:Nr.parse(JSON.parse(i))}catch{throw new Me(422,"invalid_function_result","The function must return valid JSON.")}let o={};for(let[s,a]of Object.entries(t.outputs)){let c=s===""?n:Wn(n,s);if(c===void 0)throw new Me(400,"invalid_pointer","The function result value was not found.");let u=ft(typeof c=="string"?c:JSON.stringify(c)),l=await Rf(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});o[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(o).length?{saved:o}:n}};import{spawn as $re}from"node:child_process";import{mkdir as Pre,mkdtemp as kUe,rm as DUe,writeFile as Tre}from"node:fs/promises";import{tmpdir as OUe}from"node:os";import{join as Bh}from"node:path";import{StringDecoder as Cre}from"node:string_decoder";function kre(e={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...e}}var Hh=class{constructor(t){this.options=t;if(t.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(t.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(t,r){r.throwIfAborted();let i=await kUe(Bh(OUe(),"foundation-job-")),n=Bh(i,"files"),o="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=t.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await Pre(n,{mode:448});let l={...t.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[m,p]of Object.entries(t.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m))throw new Error("Use valid file variable names.");await Tre(Bh(n,m),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),l[m]=s?"/run/foundation/"+m:Bh(n,m)}let d=t.command;if(s){if(Object.entries(l).some(([g,v])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(g)||v.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let m=Object.entries(l).filter(([,g])=>/[\r\n]/.test(g)),p=Bh(i,"environment");await Tre(p,Object.entries(l).filter(([,g])=>!/[\r\n]/.test(g)).map(([g,v])=>g+"="+v).join(`
122
+ `}),outputs:XD,hint:f.string().optional()}).strict(),pl=f.string().regex(/^[A-Z_][A-Z0-9_]*$/),gq=f.union([f.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),f.object({output:pl}).strict()]),IS=f.object({urlField:f.string().min(1).max(100).optional(),authentication:f.discriminatedUnion("kind",[f.object({kind:f.literal("none")}).strict(),f.object({kind:f.literal("bearer"),token:pl}).strict(),f.object({kind:f.literal("basic"),username:pl,password:pl}).strict(),f.object({kind:f.literal("header"),name:gq,value:pl}).strict(),f.object({kind:f.literal("query"),name:gq,value:pl}).strict()])}).strict(),wf={name:be,docs:f.url().optional(),console:gc.optional(),http:IS.optional(),preparation:f.object({scopeSelection:f.enum(["optional","required","hidden"]).default("optional"),instructions:f.array(f.union([f.string().max(2e3),f.object({ja:f.string().max(2e3),en:f.string().max(2e3)}).strict()])).max(10).default([]),docs:f.boolean().default(!1)}).strict().optional()},$S=f.object({...wf,kind:f.literal("oauth"),config:Qwe}).strict(),PS=f.object({...wf,kind:f.literal("token"),config:ebe}).strict(),TS=f.object({...wf,kind:f.literal("aws"),config:tbe}).strict(),CS=f.object({...wf,kind:f.literal("ovh"),config:rbe}).strict(),kS=f.object({...wf,kind:f.literal("approval"),config:f.object({adapter:f.literal("runpod-flash"),fields:f.array(RS).default([]),scopes:YD.default({default:[],separator:" "}),outputs:XD,hint:f.string().optional()}).strict()}).strict(),fl=f.discriminatedUnion("kind",[$S,PS,TS,CS,kS]),yf={id:f.string().min(1),builtin:f.boolean(),availability:f.enum(["ready","app-required","unavailable"]),defaultName:be,registration:f.object({kind:f.enum(["input","authorization"]),device:f.enum(["browser","cli"]),browserExchange:f.enum(["available","unavailable","unknown"]),tokenAlternatives:f.array(f.string())}).strict()},nbe=f.discriminatedUnion("kind",[$S.extend(yf),PS.extend(yf),TS.extend(yf),CS.extend(yf),kS.extend(yf)]),vf=f.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),eO=f.object({name:be,logo:f.string().regex(/^[a-z0-9-]+$/).optional(),api:f.url().optional(),docs:f.url().optional(),console:f.url().optional(),targets:f.array(f.object({id:vf,name:be,api:f.url().optional(),methods:f.array(vf).min(1)}).strict()).max(32).optional()}).strict(),ibe=eO.extend({methods:f.record(vf,f.string().min(1))}).strict(),bq=eO.extend({methods:f.record(vf,f.union([f.string().min(1),fl]))}).strict(),z7e=eO.extend({id:f.string(),builtin:f.boolean(),methods:f.record(vf,nbe)}),_q=f.object({id:P,output:f.string().min(1).max(100).optional()}).strict(),xq=e=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(e),obe=f.object({name:f.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:_q,format:f.enum(["text","file","json"]).default("text"),pointer:f.string().optional()}).strict(),sbe=f.object({pointer:f.string().max(500),parts:f.array(f.union([f.string().max(8192),_q])).min(1).max(32)}).strict(),yc=f.object({url:f.string().min(1).max(4096).optional(),connectionId:P.optional(),method:f.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:f.record(f.string(),f.string().max(8192)).default({}),body:f.string().max(1e6).optional(),json:Nr.optional(),form:f.record(f.string(),f.string()).optional(),bindings:f.array(sbe).max(32).default([])}).strict().refine(e=>!!(e.url||e.connectionId),{message:"Choose a connection or enter a destination URL."}),vc=f.object({command:f.array(f.string().max(8192)).min(1).max(100),stdin:f.string().max(1e6).optional(),timeoutSeconds:f.number().int().min(1).max(3600).default(60),inputs:f.array(obe).max(32).default([])}).strict(),Eq=f.discriminatedUnion("kind",[vc.omit({stdin:!0}).extend({kind:f.literal("command")}).strict(),f.object({kind:f.literal("http"),request:yc,responseFormat:f.enum(["text","json"]).default("json")}).strict()]),ks=f.object({description:f.string().max(2e3).default(""),program:Eq,parameters:f.array(f.object({name:f.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:f.string().max(100),type:f.enum(["string","number","boolean","json"]).default("string"),required:f.boolean().default(!0),default:Nr.optional()}).strict()).max(32).default([]),result:f.enum(["text","json"]).default("json")}).strict(),bf=f.object({expiresAt:ne.nullable().default(null)}).strict(),j7e=f.object({version:f.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:bf,state:f.enum(["publication_required","unconfigured","configured","approval_required","unavailable","expired"])}).strict(),Fo={id:P,ownerId:P,name:be,createdAt:ne,updatedAt:ne,version:f.number().int().positive(),permissions:f.array(vq)},abe=f.enum(["starting","running","stopping","stopped","failed"]),cbe=f.enum(["manual","idle","timeout","quota","capacity","payment"]),ube=f.object({state:f.enum(["pending","failed","complete"]),error:f.string().nullable()}),lbe=f.object({idleSeconds:f.number().int().min(60).max(2147483647).nullable().default(null),maxSeconds:f.number().int().min(60).max(2147483647).nullable().default(null)}).strict(),Aq=f.object({size:f.enum(["small","medium","large"]).default("small"),lifetime:lbe.default({idleSeconds:null,maxSeconds:null}),ssh:Hv.optional()}).strict(),tO={recipients:f.array(P).default([]),executors:f.array(P).default([]),custodyRevision:f.number().int().positive().nullable().default(null)},dbe=f.object({...Fo,kind:f.literal("variable"),data:f.object({...tO,bytes:f.number().int().nonnegative()})}),pbe=f.object({...Fo,kind:f.literal("connection"),data:f.object({...tO,methodId:f.string(),fields:f.record(f.string(),f.string()).default({}),settings:f.array(f.object({name:f.string(),label:f.string(),value:f.string()})).default([]),methodName:f.string(),methodKind:QD,http:IS.optional(),services:f.array(f.object({id:f.string(),name:be})).default([]),account:f.string(),accountId:f.string().nullable().default(null),accountVerified:f.boolean().default(!1),scopes:f.array(f.string()),scopesStatus:f.enum(["unknown","requested","reported"]).default("unknown"),outputs:f.array(f.string()),state:f.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:f.boolean().default(!1),appId:P.nullable(),generation:P.optional(),authorizationDigest:f.string().optional(),aws:_S.optional(),ovh:gf.optional()})}),fbe=f.object({...Fo,kind:f.literal("service"),data:ibe}),mbe=f.object({...Fo,kind:f.literal("method"),data:fl}),hbe=f.object({...Fo,kind:f.literal("app"),data:f.object({...tO,methodId:f.string(),clientId:f.string(),fields:f.record(f.string(),f.string()).default({}),generation:P.optional()})}),gbe=f.object({...Fo,kind:f.literal("object"),data:f.object({size:f.number().int().nonnegative(),contentType:f.string()})}),ybe=f.object({...Fo,kind:f.literal("environment"),data:Aq.extend({executorId:P.optional(),operatorId:P.optional(),driver:f.enum(["attached","managed"]).optional(),capabilities:f.array(f.string()).optional(),isolation:f.enum(["process","container"]).optional(),manifestDigest:f.string().optional(),processes:f.object({workingDirectory:f.string()}).optional(),ssh:ED.optional(),awsPrincipal:f.string().optional(),state:abe,connected:f.boolean(),deletion:ube.optional(),startedAt:ne.nullable(),stoppedAt:ne.nullable(),stopReason:cbe.nullable().default(null),lastActiveAt:ne,error:f.string().nullable()})}),vbe=f.object({...Fo,kind:f.literal("function"),data:ks.omit({program:!0}).extend({program:Eq.optional()})}),Sbe=f.object({...Fo,kind:f.literal("keyring"),data:f.object({revision:f.number().int().positive(),signature:f.string()})}),ml=f.discriminatedUnion("kind",[dbe,pbe,fbe,mbe,hbe,gbe,ybe,vbe,Sbe]),F7e=f.discriminatedUnion("kind",[f.object({kind:f.literal("service"),name:be,definition:bq}).strict(),f.object({kind:f.literal("method"),name:be,definition:fl}).strict(),f.object({kind:f.literal("environment"),name:be.optional(),options:Aq}).strict()]),G7e=f.object({version:f.number().int().positive(),name:be.optional(),definition:f.union([bq,fl]).optional()}).strict(),Sc=f.object({name:f.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Mt}).strict(),DS=Sc.extend({inputs:f.array(f.object({pointer:f.string(),label:f.string().min(1).max(100),secret:f.boolean().default(!1),multiline:f.boolean().default(!1),site:f.url().optional()}).strict()).max(16).default([])}),AS=f.object({ja:f.string(),en:f.string()}).strict(),rO=DS.extend({title:AS,execution:f.enum(["server","keyholder"]),configure:f.array(f.string()),environment:f.object({required:f.boolean(),reason:AS.nullable()}).strict()}),q7e=f.object({to:P.optional(),executionId:P.optional(),message:f.string().max(1e3).default(""),operations:f.array(DS).min(1).max(8).optional(),expiresInMinutes:f.number().int().min(1).max(1440).default(30)}).strict().superRefine((e,t)=>{!!e.executionId==!!e.operations&&t.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),xS=f.object({id:P,name:be}),Rq=f.discriminatedUnion("kind",[f.object({kind:f.literal("line"),subject:xS,relation:ZD,object:xS}),f.object({kind:f.literal("transfer"),item:xS,to:xS})]),V7e=f.object({id:P,executionId:P,from:Cs.pick({id:!0,name:!0}),to:Cs.pick({id:!0,name:!0}).nullable(),message:f.string(),purpose:f.enum(["input","approval"]),state:f.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:ne,expiresAt:ne,url:f.url(),code:f.string().optional(),returnUrl:f.url().nullable(),refreshUrl:f.url().nullable(),canRespond:f.boolean(),canCancel:f.boolean()}),K7e=f.object({id:P,name:be,publicKey:Ur,state:f.enum(["pending","approving","approved"]),principalId:P.nullable(),createdAt:ne,expiresAt:ne}),B7e=f.object({available:f.boolean(),required:f.boolean(),active:f.boolean(),payer:Cs.pick({id:!0,name:!0}).nullable()}),H7e=f.object({storageBytes:f.number().nonnegative(),storageLimit:f.number().positive(),computeSeconds:f.number().nonnegative(),computeLimit:f.number().positive(),month:f.string()}),W7e=f.object({id:f.string(),actorId:P.nullable(),action:f.string(),targetId:P.nullable(),createdAt:ne,details:Mt}),J7e=f.object({returnUrl:f.url().optional(),refreshUrl:f.url().optional()}).strict(),hl=e=>f.object({items:f.array(e),next:f.string().nullable().default(null)}),Z7e=f.object({id:P}),X7e=f.object({owner:P}),wbe=f.object({limit:f.coerce.number().int().min(1).max(200).default(100),after:f.string().optional()}),Y7e=wbe.extend({object:P.optional(),subject:P.optional(),relation:ZD.optional(),objectType:wq.optional()}).refine(e=>!!e.object!=!!e.subject,"Choose the object or the subject of the lines.");var _be=new TextEncoder,xbe=new TextDecoder,OS="ECDH-ES+A256KW",Iq="A256GCM",ft=e=>_be.encode(e),NS=e=>xbe.decode(e);function Ds(e){let t="";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function $q(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}async function wc(e,t,r){if(!t.length||new Set(t.map(n=>n.id)).size!==t.length)throw new Error("Recipients must be distinct and nonempty.");let i=new ff(e).setProtectedHeader({enc:Iq}).setAdditionalAuthenticatedData(ft(r));for(let n of t)i.addRecipient(await An(n.publicKey,OS)).setUnprotectedHeader({alg:OS,kid:n.id});return jo.parse(await i.encrypt())}async function bc(e,t,r,i){if(e.aad!==Ds(ft(i)))throw new Error("The encrypted content belongs to a different item.");let n=e.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let o=t instanceof CryptoKey?t:await An(t,OS);return(await LD({...e,recipients:[n]},o,{keyManagementAlgorithms:[OS],contentEncryptionAlgorithms:[Iq]})).plaintext}var yt=f.string().regex(/^[A-Za-z0-9_-]{43}$/),_t=f.string().min(100).max(4e6),Pq=Ur.extend({d:f.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Cq=f.object({encryption:Pq,signing:Pq}).strict(),vt=f.object({id:P,principalId:P,generation:f.number().int().positive(),previous:yt.nullable(),encryption:Ur,signing:Ur}).strict();function k(e){if(e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&!/[\uD800-\uDFFF]/u.test(e))return JSON.stringify(e);if(Array.isArray(e))return"["+Array.from(e,k).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(t=>{if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Use Unicode property names.");return JSON.stringify(t)+":"+k(e[t])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Tq(e){return HD(Ur.parse({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),"sha256")}async function te(e){return Ds(new Uint8Array(await crypto.subtle.digest("SHA-256",ft(k(e)))))}async function US(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",ft(k(e))));return"sha256:"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}async function Tt(e,t,r){let i=t instanceof CryptoKey?t:await An(t,"ES256");return new hf(ft(k(e))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(i)}async function nr(e,t,r,i){if(k(await _f(t,r,i))!==k(e))throw new Error("The signature does not authorize this content.")}async function _f(e,t,r){let i=await KD(e,await An(Ur.parse(t),"ES256"),{algorithms:["ES256"]});if(i.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(i.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(i.payload),o=JSON.parse(n);if(k(o)!==n)throw new Error("Sign canonical JSON content.");return o}var gl=f.object({binding:vt,signature:_t}).strict();async function Mi(e){let t=vt.parse(e);if(t.generation===1!=(t.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Tq(t.encryption)===await Tq(t.signing))throw new Error("Use separate encryption and signing keys.");await An(t.encryption,"ECDH-ES+A256KW"),await An(t.signing,"ES256")}async function LS(e){let{binding:t,signature:r}=gl.parse(e);return await Mi(t),await nr(t,r,t.signing,"key-binding"),t}var kq=f.object({ownerId:P,name:be,resourceId:P.optional(),version:f.number().int().positive().optional(),environmentIds:f.array(P).max(32).optional()}).strict(),dXe=kq.extend({value:f.literal("").optional()}),pXe=kq.extend({methodId:f.string().min(1).max(200),clientId:f.string().max(1e3),fields:f.record(f.string(),f.string()).optional(),clientSecret:f.literal("").optional()}),fXe=f.object({ownerId:P,name:be,definition:ks,resourceId:P.optional(),version:f.number().int().positive().optional()}).strict(),mXe=f.object({functionId:P,functionVersion:f.number().int().positive(),version:f.number().int().nonnegative(),environmentId:P.nullable(),inputAccess:bf.default({expiresAt:null})}).strict(),Dq=f.object({ownerId:P,connectionId:P,environmentId:P}).strict(),hXe=f.object({ownerId:P,connectionId:P,version:f.number().int().positive(),users:f.array(P).max(32),expiresAt:f.iso.datetime().optional()}).strict(),gXe=f.object({ownerId:P,methodId:f.string().min(1).max(200),connectionId:P.optional(),name:be.optional(),appId:P.optional(),redirectUri:f.url().optional(),users:f.array(P).max(32).optional(),scopes:f.array(f.string().min(1).max(1e3)).max(200).optional(),methodDigest:f.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:f.string().max(1e3).optional(),fields:f.record(f.string(),f.string()).optional(),clientSecret:f.literal("").optional()}).strict(),Oq=f.object({ownerId:P,environmentId:P.optional(),operation:f.union([f.object({kind:f.literal("http"),request:yc}).strict(),vc.extend({kind:f.literal("command")}),f.object({kind:f.enum(["http","command"]),programId:P,programDigest:f.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:f.record(f.string(),be).default({})}).strict().superRefine((e,t)=>{e.environmentId||t.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),yXe=f.object({name:Sc.shape.name,title:AS,execution:f.enum(["server","keyholder"]),configure:f.array(f.string()),environment:rO.shape.environment,input:Mt}).strict(),vXe=f.object({id:P.optional(),operations:f.array(DS).min(1).max(8),responderId:P.optional(),message:f.string().max(1e3).default(""),expiresInMinutes:f.number().int().min(1).max(1440).default(1440)}).strict(),SXe=f.object({values:f.array(Mt).max(8).default([]),configuration:f.array(Mt).max(8).default([]),code:f.string().max(20).optional()}).strict(),Ebe=f.object({index:f.number().int().nonnegative(),invocation:Sc,approval:f.object({id:P,index:f.number().int().nonnegative()}).strict().optional(),continuation:f.object({kind:f.enum(["connection","run"]),id:P}).strict().nullable()}).strict(),Nq=f.object({id:P,actorId:P,ownerId:P,requests:f.array(P),steps:f.array(f.object({index:f.number().int().nonnegative(),name:Sc.shape.name,state:f.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:f.array(f.object({kind:f.enum(["run","function","process"]),id:P}).strict())}).strict()),creator:Cs.pick({id:!0,name:!0}),operations:f.array(rO),approval:f.object({requestId:P.nullable(),proposal:Rq.nullable()}).strict().nullable(),canContinue:f.boolean(),canCancel:f.boolean(),url:f.url(),code:f.string().optional(),error:f.object({code:f.string(),message:f.string()}).strict().nullable(),index:f.number().int().nonnegative(),state:f.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:f.enum(["approval","input","execution"]).nullable(),waiting:Ebe.nullable(),results:f.array(Nr.nullable()),createdAt:f.iso.datetime(),expiresAt:f.iso.datetime()}).strict(),Uq=f.object({id:P,index:f.number().int().nonnegative(),invocation:Sc,continuationId:P.optional()}).strict();var yl=f.url().refine(e=>{let t=new URL(e);return t.origin===e&&!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.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"},Abe=f.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),Mq=e=>e===ge.executionResult?14e5:1e6,Q={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"},xf=f.enum([Q.http,Q.command,Q.function,Q.connect,Q.refresh,Q.revoke]);var Rbe={[ge.value]:[Q.http,Q.command,Q.function],[ge.tokenSet]:[Q.http,Q.command,Q.function,Q.refresh,Q.revoke],[ge.clientCredential]:[Q.connect,Q.refresh,Q.revoke],[ge.executionResult]:[]},nO=e=>Rbe[e];var iO=e=>e===ge.tokenSet,Ibe=f.object({id:P,digest:yt}).strict(),$be=f.object({actor:vt,executor:vt,operations:f.array(xf).min(1).max(6),functionDigests:f.array(yt).max(100).default([]),origins:f.array(yl).max(100).default([]),callerProgram:f.boolean().default(!1),expiresAt:ne}).strict(),Pbe=f.object({function:Ibe,executor:vt,operations:f.array(xf).min(1).max(6),expiresAt:ne.nullable()}).strict(),Tbe=f.union([$be,Pbe]);function Go(e,t=Date.now()){return e.expiresAt===null||Date.parse(e.expiresAt)>t}function vl(e){return e.expiresAt===null?1/0:Date.parse(e.expiresAt)}var qo=f.object({format:f.literal(2),origin:yl,id:P,ownerId:P,contentType:Abe,revision:f.number().int().positive(),authorities:f.array(vt).min(1).max(100),readers:f.array(vt).min(1).max(100),grants:f.array(Tbe).max(100),observers:f.array(P).max(100).optional(),producers:f.array(f.object({executor:vt,runId:P,expiresAt:ne,materialRevision:f.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),Lq=f.object({ownerId:P,authorities:f.array(vt).min(1).max(100)}).strict(),zq=f.object({origin:yl,id:P,revision:f.number().int().positive(),from:Lq,to:Lq,policyDigest:yt,previous:yt.nullable(),signerId:P}).strict(),Cbe=zq.extend({signature:_t}),oO=f.array(Cbe).max(16),Ef=f.object({policy:qo,authorityId:P,signature:_t,lineage:oO.optional()}).strict(),ir=f.object({policy:qo,authorityId:P,authorization:_t,lineage:oO.optional(),materialRevision:f.number().int().positive(),updatedAt:ne,creationRunId:P.nullable(),metadata:Mt,sealed:jo,signerId:P,signature:_t}).strict(),_c=e=>({ownerId:e.ownerId,authorities:e.authorities});async function jq(e,t=[]){let r;for(let i of t){let{signature:n,...o}=i;if(i.origin!==e.origin||i.id!==e.id||i.revision>e.revision||r&&(i.revision<=r.revision||k(r.to)!==k(i.from))||i.previous!==(r?await te(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=i.from.authorities.find(a=>a.id===i.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await nr(o,n,s.signing,"authority-handoff"),r=i}if(r&&k(r.to)!==k(_c(e)))throw new Error("Use the authorities approved by the latest handoff.")}function sO(e){let t=e.policy.authorities.find(n=>n.id===e.authorityId);if(t)return t;let r=e.lineage?.at(-1),i=r?.revision===e.policy.revision?r.from.authorities.find(n=>n.id===e.authorityId):void 0;if(!i||i.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return i}function MS(e,t){if(e.id!==t.policy.id||e.origin!==t.policy.origin||e.contentType!==t.policy.contentType)return!1;let r=k(_c(e));return r===k(_c(t.policy))?!0:!!t.lineage?.some(i=>i.revision>e.revision&&k(i.from)===r)}async function Fq(e,t,r,i){let n=[...e?.lineage??[]];if(e&&k(_c(e.policy))!==k(_c(t))){if(await sn(e),!e.policy.authorities.some(s=>k(s)===k(r))||e.policy.id!==t.id||e.policy.origin!==t.origin||e.policy.contentType!==t.contentType||t.revision!==e.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let o=zq.parse({origin:t.origin,id:t.id,revision:t.revision,from:_c(e.policy),to:_c(t),policyDigest:await te(t),previous:n.length?await te(n.at(-1)):null,signerId:r.id});n.push({...o,signature:await Tt(o,i.signing,"authority-handoff")})}return n.length?{lineage:oO.parse(n)}:{}}async function zS(e){let t=qo.parse(e),r=[...t.authorities,...t.readers,...t.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...t.producers.map(n=>n.executor)],i=new Map;for(let n of r){await Mi(n);let o=k(n);if(i.has(n.id)&&i.get(n.id)!==o)throw new Error("Each key binding must identify the same keys throughout a policy.");i.set(n.id,o)}for(let n of[t.readers,t.authorities])if(new Set(n.map(o=>o.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of t.authorities)if(!t.readers.some(o=>o.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of t.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(o=>!nO(t.contentType).includes(o)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(o=>o!==Q.function&&o!==Q.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(o=>o===Q.http||o===Q.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(Q.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return t}function jS(e){return[...new Map([...e.readers,...e.grants.map(t=>t.executor)].map(t=>[t.id,t])).values()]}async function Ns(e,t){return k({purpose:"resource",policyDigest:await te(e),materialRevision:t})}async function Af(e,t,r,i,n,o,s){if(e.byteLength>Mq(t.contentType))throw new Error("The content exceeds its storage limit.");let a=await zS(t),c=await Fq(s,a,i,n);if(!a.authorities.some(m=>k(m)===k(i))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(a,r)),l={policy:a,...c,authorityId:i.id,authorization:await Tt(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:o??(a.contentType===ge.value?{bytes:e.byteLength}:{}),sealed:u,signerId:i.id},d=ir.parse({...l,signature:await Tt(l,n.signing,"resource")});return await sn(d),d}async function sn(e){let t=ir.parse(e),{signature:r,...i}=t;await zS(t.policy),await jq(t.policy,t.lineage);let n=sO(t),o=t.lineage?.at(-1);if(o?.revision===t.policy.revision&&o.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");await nr(t.policy,t.authorization,n.signing,"access-policy");let s=(t.signerId===n.id?n:void 0)??t.policy.authorities.find(u=>u.id===t.signerId)??t.policy.producers.find(u=>u.executor.id===t.signerId&&u.runId===t.creationRunId&&u.materialRevision===t.materialRevision&&(t.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(t.updatedAt)))?.executor??(iO(t.policy.contentType)?t.policy.grants.find(u=>u.executor.id===t.signerId&&u.operations.includes(Q.refresh)&&Go(u,Date.parse(t.updatedAt)))?.executor:void 0);if(!s||Date.parse(t.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await nr(i,r,s.signing,"resource");let a=jS(t.policy).map(u=>u.id).sort(),c=t.sealed.recipients.map(u=>u.header.kid).sort();if(k(a)!==k(c)||t.sealed.aad!==Ds(ft(await Ns(t.policy,t.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return t}async function Gq(e,t,r,i,n=e.metadata){let o=await sn(e);if(!iO(o.policy.contentType)||!(o.policy.authorities.some(m=>k(m)===k(r))||o.policy.grants.some(m=>k(m.executor)===k(r)&&m.operations.includes(Q.refresh)&&Go(m))))throw new Error("This executor cannot renew this connection.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=o.materialRevision+1,a=await wc(t,jS(o.policy).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(o.policy,s)),{signature:c,...u}=o,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await Tt(l,i.signing,"resource")};return await sn(d),d}async function FS(e,t,r,i){let n=await zS(e);if(!n.authorities.some(s=>k(s)===k(t)))throw new Error("Only an authority can approve this policy.");let o={policy:n,...await Fq(i,n,t,r),authorityId:t.id,signature:await Tt(n,r.signing,"access-policy")};return await Us(o),o}async function Us(e){let t=Ef.parse(e);await zS(t.policy),await jq(t.policy,t.lineage);let r=t.lineage?.at(-1);if(r?.revision===t.policy.revision&&r.policyDigest!==await te(t.policy))throw new Error("The handoff approves a different access policy.");let i=t.policy.authorities.find(n=>n.id===t.authorityId);if(!i)throw new Error("The policy must be signed by an authority.");return await nr(t.policy,t.signature,i.signing,"access-policy"),t}async function Rf(e,t,r,i,n,o){let s=await Us(t),{policy:a}=s,c=a.producers.find(m=>m.runId===r&&k(m.executor)===k(i)&&(a.contentType===ge.executionResult||Date.parse(m.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(e.byteLength>Mq(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await wc(e,jS(a).map(m=>({id:m.id,publicKey:m.encryption})),await Ns(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:o,sealed:u,signerId:i.id},d={...l,signature:await Tt(l,n.signing,"resource")};return await sn(d),d}async function If(e,t,r){let i=await sn(e);if(!i.policy.readers.some(n=>k(n)===k(t)))throw new Error("This identity cannot reveal the content.");return bc(i.sealed,r,t.id,await Ns(i.policy,i.materialRevision))}var kbe=f.object({id:P,policyDigest:yt,materialRevision:f.number().int().positive(),authorizationDigest:yt.optional()}).strict();async function aO(e,t){return t.id===e.policy.id&&t.policyDigest===await te(e.policy)&&(t.authorizationDigest===void 0||t.authorizationDigest===e.metadata.authorizationDigest)&&(t.materialRevision===e.materialRevision||iO(e.policy.contentType)&&t.authorizationDigest!==void 0&&t.authorizationDigest===e.metadata.authorizationDigest&&e.materialRevision>=t.materialRevision)}var GS=f.object({format:f.literal(2),id:P,origin:yl,ownerId:P,approval:f.object({id:P,index:f.number().int().min(0).max(7)}).strict().optional(),operationContext:Uq.optional(),actor:vt,environmentId:P,executor:vt,environmentDigest:yt,operation:xf,functionDigest:yt.nullable(),functionId:P.optional(),operationDigest:yt,sources:f.array(kbe).max(100),resultRecipients:f.array(vt).min(1).max(100),resultApproval:Ef.optional(),createdAt:ne,expiresAt:ne}).strict(),qS=f.object({intent:GS,signature:_t,sealed:jo}).strict();async function xc(e,t){return k({purpose:"run-"+t,origin:e.origin,id:e.id,intentDigest:await te(e)})}async function qq(e,t,r){if(GS.parse(e),await te(t)!==e.operationDigest)throw new Error("The operation does not match the execution intent.");let i={intent:e,sealed:await wc(ft(k(t)),[{id:e.executor.id,publicKey:e.executor.encryption}],await xc(e,"input"))};return qS.parse({...i,signature:await Tt(i,r.signing,"run")})}async function Dbe(e,t=Date.now()){let r=qS.parse(e),{signature:i,...n}=r;await nr(n,i,r.intent.actor.signing,"run");let{intent:o}=r,s=Date.parse(o.createdAt),a=Date.parse(o.expiresAt);if(s>t+3e4||a<=t||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(o.sources.map(c=>c.id)).size!==o.sources.length||new Set(o.resultRecipients.map(c=>c.id)).size!==o.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(o.resultApproval){let c=await Us(o.resultApproval),u=c.policy;if(c.authorityId!==o.actor.id||u.id!==o.id||u.origin!==o.origin||u.ownerId!==o.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>k(l)===k(o.actor))||k(u.readers)!==k(o.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==o.id||k(u.producers[0].executor)!==k(o.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!==o.executor.id||r.sealed.aad!==Ds(ft(await xc(o,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function Vq(e,t,r){let i=await Dbe(e);if(k(i.intent.executor)!==k(t))throw new Error("This operation belongs to another executor.");let n=await bc(i.sealed,r.encryption,t.id,await xc(i.intent,"input")),o=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(o);if(k(s)!==o||await te(s)!==i.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:i.intent,operation:s}}async function Os(e,t,r={}){let i=await sn(e),n=i.policy,o=t.sources.find(c=>c.id===n.id);if(!o||t.origin!==n.origin||!await aO(i,o))throw new Error("The input changed after this execution was authorized.");if(k(t.actor)===k(t.executor)&&n.readers.some(c=>k(c)===k(t.actor)))return i;if(!n.grants.filter(c=>("actor"in c?k(c.actor)===k(t.actor):c.function.id===t.functionId&&c.function.digest===t.functionDigest)&&k(c.executor)===k(t.executor)&&c.operations.includes(t.operation)&&Go(c,r.now)&&vl(c)>=Date.parse(t.expiresAt)).some(c=>"function"in c?t.operation===Q.function||t.operation===Q.refresh:t.operation===Q.function&&!c.callerProgram&&(!t.functionDigest||!c.functionDigests.includes(t.functionDigest))||!r.destinationPending&&c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:t.operation!==Q.command&&t.operation!==Q.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return i}async function Ec(e,t,r,i={}){let n=i.destination;await Os(e,t,{now:i.now,...typeof n=="function"?{destinationPending:!0}:{destination:n}});let o=await bc(e.sealed,r.encryption,t.executor.id,await Ns(e.policy,e.materialRevision));return typeof n=="function"&&await Os(e,t,{now:i.now,destination:n(o)}),o}var Ac=5,zi=1,cO=f.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Kq=f.object({format:f.literal(3),id:P,origin:yl,ownerId:P,name:be,executor:vt,operatorId:P,driver:f.literal("attached"),capabilities:f.array(xf).min(1).max(6),functionVersion:f.number().int().positive().optional(),httpVersion:f.number().int().positive().optional(),resultVersion:f.literal(1).optional(),isolation:f.enum(["process","container"]),commandImage:f.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),functionImage:f.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:cO.optional(),revision:f.number().int().positive()}).strict(),uO=f.object({manifest:Kq,signature:_t}).strict();async function lO(e,t){let r=Kq.parse(e),i={manifest:r,signature:await Tt(r,t.signing,"environment")};return await wl(i),i}async function wl(e){let t=uO.parse(e),{manifest:r}=t;if(await Mi(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(Q.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");return await nr(r,t.signature,r.executor.signing,"environment"),t}async function bl(e,t){let{manifest:r}=await wl(e);if(t.environmentId!==r.id||t.origin!==r.origin||t.environmentDigest!==await te(r)||k(t.executor)!==k(r.executor)||!r.capabilities.includes(t.operation)||t.operation===Q.function&&r.functionVersion!==Ac)throw new Error("This environment does not authorize the requested execution.")}var VS=f.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),KS=f.object({ok:f.boolean(),result:Nr.nullable(),error:f.object({code:f.string().max(100),message:f.string().max(1e3)}).nullable()}).strict(),Bq={id:P,intentDigest:yt,executorId:P,state:f.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ne},Hq=f.object({...Bq,sealed:jo,signature:_t}).strict(),Wq=f.object({...Bq,format:f.literal(2),accessDigest:yt,proofDigest:yt,approval:Ef,content:ir,previousDigest:yt.optional(),previous:Hq.optional(),signature:_t}).strict(),$f=f.union([Hq,Wq]),Obe=f.object({result:KS,proof:_t}).strict(),Jq=e=>{let{signature:t,content:r,approval:i,previous:n,...o}=e;return o};async function dO(e,t,r,i,n,o){await Us(n);let s={format:2,id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:o?.finishedAt??new Date().toISOString(),accessDigest:await te(n),...o?{previousDigest:await te(o)}:{}},a=await Tt({...s,resultDigest:await te(r)},i.signing,"execution-result"),c=ft(k({result:KS.parse(r),proof:a}));if(c.byteLength>14e5)throw new Sl;let u=await Rf(c,n,e.id,e.executor,i,{bytes:c.byteLength}),l={...s,proofDigest:await te(a)},d=Wq.parse({...l,approval:n,content:u,...o?{previous:o}:{},signature:await Tt(l,i.signing,"receipt")});return await pO(d,e),d}var Sl=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function _l(e,t,r,i){let n=KS.parse(r);if(t==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(e.resultApproval)return dO(e,t,n,i,e.resultApproval);let o=ft(k(n));if(o.byteLength>14e5)throw new Sl;let s=await wc(o,e.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await xc(e,"result")),a={id:e.id,intentDigest:await te(e),executorId:e.executor.id,state:t,finishedAt:new Date().toISOString(),sealed:s};return $f.parse({...a,signature:await Tt(a,i.signing,"receipt")})}async function pO(e,t){let r=$f.parse(e);if("content"in r){await nr(Jq(r),r.signature,t.executor.signing,"receipt");let o=await Us(r.approval),s=o.policy;if(r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.accessDigest!==await te(o)||o.authorityId!==t.actor.id||!s.authorities.some(a=>k(a)===k(t.actor))||s.id!==t.id||s.origin!==t.origin||s.ownerId!==t.ownerId||s.contentType!==ge.executionResult||s.grants.length||t.resultApproval&&k(t.resultApproval)!==k(o))throw new Error("The result does not belong to the requested execution.");if(!t.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await te(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await pO(r.previous,t),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 sn(r.content),!MS(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(t.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:i,...n}=r;if(await nr(n,i,t.executor.signing,"receipt"),r.id!==t.id||r.intentDigest!==await te(t)||r.executorId!==t.executor.id||r.sealed.aad!==Ds(ft(await xc(t,"result")))||k(r.sealed.recipients.map(o=>o.header.kid).sort())!==k(t.resultRecipients.map(o=>o.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function Zq(e,t,r,i){if(await pO(e,t),"content"in e){if(!e.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await bc(e.content.sealed,i.encryption,r,await Ns(e.content.policy,e.content.materialRevision)),a=Obe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await te(a.proof)!==e.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=Jq(e);if(await nr({...u,resultDigest:await te(a.result)},a.proof,t.executor.signing,"execution-result"),e.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await bc(e.sealed,i.encryption,r,await xc(t,"result")),o=KS.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(e.state==="succeeded"!==o.ok)throw new Error("The encrypted result does not match its completion state.");return o}var Nbe=f.enum(["http","command","function","connect","refresh","revoke"]),Rc=f.object({id:P,ownerId:P,actorId:P,environmentId:P,kind:Nbe,state:VS,intent:GS,requestSignature:_t,receipt:$f.nullable(),error:f.string().nullable(),createdAt:ne,startedAt:ne.nullable(),finishedAt:ne.nullable()}).strict(),BS=f.object({name:be,approval:Ef}).strict(),Xq=f.object({kind:f.literal("function"),functionId:P,definition:ks,arguments:Mt.default({}),outputs:f.record(f.string(),BS).default({})}).strict(),Ic=f.discriminatedUnion("kind",[f.object({kind:f.literal("http"),request:yc,save:f.record(f.string(),BS).default({})}).strict(),f.object({kind:f.literal("command"),...vc.shape}).strict(),f.object({kind:f.enum(["connect","refresh","revoke"]),input:Nr}).strict()]);var Ube=f.object({requestedAt:ne,readyAt:ne}).strict(),Lbe=f.object({email:f.boolean(),environments:f.boolean(),ssh:f.boolean(),storage:f.boolean(),payments:f.boolean()}),Yq=f.object({principal:Cs.nullable(),credentialId:P.nullable(),wrappedKey:Sf.nullable(),requestId:P.nullable(),keyReset:Ube.nullable(),server:f.object({name:be}),features:Lbe,principals:f.array(Cs)}),UXe=f.object({email:f.email().max(254),returnTo:f.string().max(2048).optional(),locale:yq.default("ja"),principalId:P.optional()}).strict(),LXe=f.object({intent:f.enum(["register","authenticate"]),name:be.optional(),principalId:P.optional(),credentialId:P.optional(),returnTo:f.string().max(2048).optional()}).strict(),MXe=f.object({challengeId:P,credential:f.json(),publicKey:Ur.optional(),existingPublicKey:Ur.optional(),wrappedKey:Sf.optional()}).strict(),zXe=f.object({publicKey:Ur,wrappedKey:Sf}).strict();var HS=class extends Error{constructor(r,i,n){super(n);this.code=r;this.status=i}code;status},WS=class{constructor(t){this.identity=t}identity;async response(t,r={}){if(!t.startsWith("/api/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Use a path beginning with /api/.");let i=new URL(t,this.identity.origin);if(i.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(i,{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 o;try{o=f.object({error:f.object({code:f.string(),message:f.string()})}).parse(await n.json())}catch{throw new HS("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new HS(o.error.code,n.status,o.error.message)}return n}async json(t,r={},i){let n=await this.response(t,r),o=n.status===204?null:await n.json();return i?i.parse(o):o}async session(){return this.json("/api/session",{},Yq)}};import{chmod as Mbe,lstat as zbe,mkdir as jbe,open as mO,readFile as Fbe,rename as Gbe,rm as qbe}from"node:fs/promises";import{dirname as Vbe,join as hO,resolve as Kbe}from"node:path";import{homedir as Bbe}from"node:os";import{randomUUID as Hbe}from"node:crypto";var eV=f.object({origin:f.url(),principalId:f.uuid(),token:f.string().min(20),keys:Cq.nullable(),binding:vt.nullable()}).strict().refine(e=>!!e.keys==!!e.binding&&(!e.binding||e.binding.principalId===e.principalId),"Use the keys bound to this identity."),Wbe=f.object({current:f.uuid(),identities:f.array(eV).min(1)}).strict().refine(e=>e.identities.some(t=>t.principalId===e.current),"The current identity is missing.");function gO(){return hO(process.env.XDG_CONFIG_HOME||hO(Bbe(),".config"),"foundation","identity.json")}function fO(e=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let t;try{t=new URL(e)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return t.origin}async function Jbe(){try{let e=gO(),t=await zbe(e);if(!t.isFile()||t.isSymbolicLink())throw new Error("The identity must be a regular file.");return process.platform!=="win32"&&t.mode&63&&await Mbe(e,384),Wbe.parse(JSON.parse(await Fbe(e,"utf8")))}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw new Error("The saved identity could not be read. Check its contents and permissions.")}}async function tV(e,t){let r=process.env.FOUNDATION_TOKEN,i=t||(r?void 0:process.env.FOUNDATION_PRINCIPAL_ID),n=await Jbe(),o;if(n){if(o=n.identities.find(a=>a.principalId===(i??n.current)),i&&!o&&!r)throw new Error("No saved identity has principal "+i+". Run foundation identity list.")}else if(i&&!r)throw new Error("Run foundation login to sign in on this machine.");let s=fO(e||process.env.FOUNDATION_ORIGIN||o?.origin);if(r){if(e&&process.env.FOUNDATION_ORIGIN&&s!==fO(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let a=process.env.FOUNDATION_PRINCIPAL_ID,c=process.env.FOUNDATION_PRIVATE_KEYS,u=process.env.FOUNDATION_KEY_BINDING;if(!a)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return eV.parse({origin:s,principalId:a,token:r,keys:c?JSON.parse(Buffer.from(c,"base64url").toString("utf8")):null,binding:u?JSON.parse(Buffer.from(u,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!o)throw new Error("Run foundation login to sign in on this machine.");if(s!==fO(o.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...o,origin:s}}async function Qq(e){if(process.platform==="win32")return;let t=await mO(e,"r");try{await t.sync()}finally{await t.close()}}async function yO(e,t,r){let i=Kbe(e),n=Vbe(i);if(await jbe(n,{recursive:!0,mode:448}),!r){let s=await mO(i,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Qq(n);return}let o=hO(n,".foundation-"+Hbe());try{let s=await mO(o,"wx",384);try{await s.writeFile(t),await s.sync()}finally{await s.close()}await Gbe(o,i),await Qq(n)}finally{await qbe(o,{force:!0})}}import{mkdir as Ihe}from"node:fs/promises";import{join as Tj}from"node:path";import{setTimeout as pWe}from"node:timers/promises";import{dirname as $Ue,join as T4}from"node:path";function Ls(e){switch(e.kind){case"oauth":let t=e.config.application;return{family:"oauth",application:t,requiresApp:t==="required",browserAuthorization:e.config.grantType!=="client_credentials",revocable:e.config.revoke?.tokenOnly===!0,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)};case"ovh":{let r=e.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,revocable:!1,fields:e.config.fields,outputs:Object.keys(e.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function rV(e,t){return[...new Set([...e.required??[],...t??e.default])]}function xl(e){return Ls(e).requiresApp}var Zbe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),nV=Mt.refine(e=>Object.keys(e).every(t=>!Zbe.has(t)),"Keep method-specific facts separate from common facts."),Ms=f.object({accountId:f.string().max(2e3).nullable(),accountName:f.string().max(2e3),accountVerified:f.boolean(),scopes:f.array(f.string().max(1e3)).max(200),scopesStatus:f.enum(["unknown","requested","reported"]),authorization:nV,details:nV}).strict();function vO(e){if(e.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let t="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:e.oauth?.account??"",accountName:e.oauth?.accountName??"",accountVerified:e.oauth?.accountVerified??!1,scopes:t??e.oauth?.scopes??[],scopesStatus:t?"requested":e.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function El(e){if(e.method.kind!=="token"&&e.method.kind!=="approval"||!e.fields)throw new Error("Use input credential material.");return"facts"in e&&e.facts?Ms.parse(e.facts):Ms.parse({accountId:null,accountName:e.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function SO(e){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let t="ovh"in e?e.ovh:void 0;if(!t){let r="requestedScopes"in e?e.requestedScopes:void 0;return Ms.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return Ms.parse({accountId:t.user?t.account+"/"+t.user:t.account,accountName:t.account+(t.user?" / "+t.user:""),accountVerified:!0,scopes:t.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:t},details:{ovh:t}})}function wO(e){if(e.method.kind!=="aws"||!e.aws)throw new Error("Use AWS connection material.");return Ms.parse({accountId:e.aws.identity?dl(e.aws.identity.arn):null,accountName:e.aws.identity?e.aws.identity.accountId+" / "+e.aws.identity.arn.split(":").at(-1):"",accountVerified:!!e.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:mq(e.aws)},details:{aws:hq(e.aws)}})}var Xbe={oauth:vO,token:El,aws:wO,ovh:SO,approval:El};function Pf(e){return Xbe[e.method.kind](e)}var GV=lt(AV(),1);var Ho=class extends Error{template;position;hint;constructor(e,t,r,i){super(`${i} (at position ${t}): ${r}`),this.template=e,this.position=t,this.hint=r,this.name="TemplateParseError"}},__e=class extends Ho{constructor(e,t){super(e,t,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},x_e=class extends Ho{constructor(e,t){super(e,t,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},E_e=class extends Ho{constructor(e,t){super(e,t,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},A_e=class extends Ho{char;constructor(e,t,r){super(e,t,`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"}},R_e=class extends Ho{constructor(e,t){super(e,t,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},I_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`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"}},$_e=class extends Ho{operator;constructor(e,t,r){super(e,t,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},ow=class extends Ho{varSpec;constructor(e,t,r,i,n){super(e,t,r,i),this.varSpec=n,this.name="InvalidVarSpecError"}},PO=class extends ow{constructor(e,t){super(e,t,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},P_e=class extends ow{offendingChar;constructor(e,t,r,i){super(e,t,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${i}' or pct-encode it.`,`Invalid character '${i}' in varname`,r),this.offendingChar=i,this.name="InvalidVarNameError"}},T_e=class extends ow{prefix;constructor(e,t,r,i){super(e,t,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${i}'`,r),this.prefix=i,this.name="InvalidPrefixError"}},RV=class extends ow{constructor(e,t){super(e,t,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},C_e=class extends Ho{char;constructor(e,t,r){super(e,t,"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"}},k_e=class extends Error{variableName;hint;constructor(e,t,r){super(`${r} for '${e}': ${t}`),this.variableName=e,this.hint=t,this.name="TemplateExpansionError"}},D_e=class extends k_e{prefix;valueType;constructor(e,t,r){super(e,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${t}' is not applicable to ${r} values`),this.prefix=t,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},O_e=["","+",".","/",";","?","&","#"],DV={"":{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}},N_e=new TextEncoder,IV="0123456789ABCDEF",$V=e=>Fs(wr(48,57),wr(65,70),wr(97,102))(e.charCodeAt(0)),Df=(e,t)=>e[t]==="%"&&t+2<e.length&&$V(e[t+1])&&$V(e[t+2]);function TO(e,t){let r=e[t];return r==null?0:Fs(OV,NV,Pc("_"))(r)?1:Df(e,t)?3:0}function U_e(e,t){if(Df(e,t))return 3;let{char:r,size:i}=Of(e,t);return M_e(r)?i:0}function Of(e,t){let r=e.codePointAt(t);if(r==null)return{char:"",size:0};let i=r>65535?2:1;return{char:e.slice(t,t+i),size:i}}var OO=e=>t=>{let r="";for(let i=0;i<t.length;){if(e&&Df(t,i)){r+=t.slice(i,i+3),i+=3;continue}let{char:n,size:o}=Of(t,i);r+=Fs(UV,s=>e&&L_e(s))(n)?n:LV(n),i+=o}return r};function Il(e){let t="";for(let r=0;r<e.length;){if(Df(e,r)){t+=e.slice(r,r+3),r+=3;continue}let{char:i,size:n}=Of(e,r);t+=UV(i)?i:LV(i),r+=n}return t}function Cf(e,t){let r="",i=0;for(let n=0;n<e.length&&i<t;i++){if(Df(e,n)){r+=e.slice(n,n+3),n+=3;continue}let{char:o,size:s}=Of(e,n);r+=o,n+=s}return r}var OV=e=>Fs(wr(65,90),wr(97,122))(e.charCodeAt(0)),NV=e=>wr(48,57)(e.charCodeAt(0)),UV=e=>Fs(OV,NV,t=>"-._~".includes(t))(e),L_e=e=>":/?#[]@!$&'()*+,;=".includes(e),M_e=e=>z_e(e.codePointAt(0)),z_e=e=>e!=null&&Fs(Pc(33),wr(35,36),Pc(38),wr(40,59),Pc(61),wr(63,91),Pc(93),Pc(95),wr(97,122),Pc(126),j_e,F_e)(e);function j_e(e){if(e<65536)return Fs(wr(160,55295),wr(63744,64975),wr(65008,65519))(e);if(e>983037)return!1;let t=e%65536;return t<=65533&&(e<917504||t>=4096)}var F_e=e=>Fs(wr(57344,63743),wr(983040,1048573),wr(1048576,1114109))(e),LV=e=>Array.from(N_e.encode(e)).map(t=>`%${IV[t>>4]}${IV[t&15]}`).join(""),wr=(e,t)=>r=>e<=r&&r<=t,Pc=e=>t=>e===t,Fs=(...e)=>t=>e.some(r=>r(t));function MV(e,t,r){return e.map(i=>i.kind==="literal"?i.text:G_e(i.vars,i.operator,t,r)).join("")}function G_e(e,t,r,i){let n=DV[t],o=e.flatMap(s=>q_e(s,r[s.name],n,i));return o.length<1?"":`${n.first}${o.join(n.sep)}`}function q_e(e,t,r,i){if(t==null)return[];if(X_e(t)){let n=H_e(t,r.allowReserved);return n.length<1?[]:PV(e,"list",i)?K_e(e,n,r):[]}if(Z_e(t)){let n=W_e(t,r.allowReserved);return n.length<1?[]:PV(e,"associative",i)?B_e(e,n,r):[]}return V_e(e,t,r)}function V_e(e,t,r){let i=String(t),n=e.prefix==null?i:Cf(i,e.prefix),o=OO(r.allowReserved)(n);return r.named?[kf(Il(e.name),o,r)]:[o]}function K_e(e,t,r){let i=Il(e.name);if(e.explode)return r.named?t.map(o=>kf(i,o,r)):[...t];let n=t.join(",");return r.named?[kf(i,n,r)]:[n]}function B_e(e,t,r){if(e.explode)return t.map(([n,o])=>kf(n,o,r));let i=t.flat(1).join(",");return r.named?[kf(Il(e.name),i,r)]:[i]}var kf=(e,t,r)=>t===""?`${e}${r.ifEmpty}`:`${e}=${t}`,H_e=(e,t)=>e.filter(r=>r!=null).map(String).map(OO(t)),W_e=(e,t)=>Object.entries(e).map(([r,i])=>[r,J_e(i)]).filter(([,r])=>r!=null).map(r=>r.map(OO(t)));function J_e(e){if(e==null)return null;if(!Array.isArray(e))return String(e);let t=e.filter(r=>r!=null).map(String);return t.length<1?null:t.join(",")}var Z_e=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X_e=e=>Array.isArray(e);function PV(e,t,{report:r,strict:i}){if(e.prefix==null)return!0;let n=new D_e(e.name,e.prefix,t);if(r(n),i)throw n;return!1}function Y_e(e,t,r){return CO(e,t,r,0,0,{})}function CO(e,t,r,i,n,o){if(i>=e.length){if(n!==t.length)return null;let a=Axe(o);return MV(e,a,r)===t?a:null}let s=e[i];if(s.kind==="literal")return t.startsWith(s.text,n)?CO(e,t,r,i+1,n+s.text.length,o):null;for(let a of Q_e(e,t,i,n)){let c=t.slice(n,a);for(let u of txe(s.vars,s.operator,c)){let l=NO(o,u);if(l==null)continue;let d=CO(e,t,r,i+1,a,l);if(d!=null)return d}}return null}function*Q_e(e,t,r,i){let n=e.slice(r+1).find(o=>o.kind==="literal"&&o.text!=="");if(n==null||n.kind!=="literal"){yield*exe(t.length,i);return}for(let o=t.indexOf(n.text,i);o>=0;o=t.indexOf(n.text,o+1))yield o}function*exe(e,t){for(let r=e;r>=t;r--)yield r}function*txe(e,t,r){if(r===""){yield*rxe(e,t);return}let i=DV[t];if(!r.startsWith(i.first))return;let n=r.slice(i.first.length);yield*i.named?dxe(e,i,n):nxe(e,i,n)}var rxe=(e,t)=>(t===""||t==="+")&&e.length===1?[js(e[0],"")]:[{}],nxe=(e,t,r)=>kO(e,t,UO(r,t.sep),0,0);function*kO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of ixe(o,t,r,n))for(let a of kO(e,t,r,i+1,s.index)){let c=NO(s.bindings,a);c!=null&&(yield c)}yield*kO(e,t,r,i+1,n)}function*ixe(e,t,r,i){if(i>=r.length)return;let n=r.length-i;for(let o=1;o<=n;o++){let s=r.slice(i,i+o);for(let a of oxe(e,t,s))yield{bindings:a,index:i+o}}}function*oxe(e,t,r){let i=zV(e,t,r.join(t.sep));if(e.prefix!=null){yield*i;return}e.explode&&r.length>0&&(yield*sxe(e,t,r)),yield*i}function*sxe(e,t,r){let i=jV(r,t.allowReserved);if(i==null)return;let n=axe(r,t);n!=null&&(yield js(e,n)),yield js(e,i)}var axe=(e,t)=>cxe(e.join(t.sep),t);function cxe(e,t){let r=[];for(let i=0;i<e.length;){let n=e.indexOf("=",i);if(n<0)return null;let o=n+1,s=uxe(e,o,t.sep),a=Bo(e.slice(i,n),t.allowReserved),c=Bo(e.slice(o,s),t.allowReserved);if(a==null||c==null)return null;r.push([a,c]),i=s+t.sep.length}return r.length<1?null:Object.fromEntries(r)}function uxe(e,t,r){for(let i=t;i<e.length;i++)if(lxe(e,i,r))return i;return e.length}var lxe=(e,t,r)=>{if(!e.startsWith(r,t))return!1;let i=t+r.length;for(let n=i;n<e.length;n++){if(e[n]==="=")return n>i;if(e.startsWith(r,n))return!1}return!1};function*zV(e,t,r){let i=Bo(r,t.allowReserved);if(i==null)return;let n=js(e,i);if(e.prefix!=null){yield n;return}let o=UO(r,",");if(o.length<2){yield n;return}let s=jV(o,t.allowReserved);if(s==null){yield n;return}let a=o.length%2===0?wxe(o,t.allowReserved):null;a!=null&&(yield js(e,a)),yield js(e,s),yield n}var dxe=(e,t,r)=>DO(e,t,UO(r,t.sep).map(Sxe),0,0);function*DO(e,t,r,i,n){if(i>=e.length){n>=r.length&&(yield{});return}let o=e[i];for(let s of pxe(o,t,r,n,e))for(let a of DO(e,t,r,i+1,s.index)){let c=NO(s.bindings,a);c!=null&&(yield c)}yield*DO(e,t,r,i+1,n)}function*pxe(e,t,r,i,n){if(!(i>=r.length)){if(e.explode&&e.prefix==null){yield*mxe(e,t,r,i,n);return}yield*fxe(e,t,r,i)}}function*fxe(e,t,r,i){let n=r[i];if(n.name===Il(e.name))for(let o of zV(e,t,n.value))yield{bindings:o,index:i+1}}function*mxe(e,t,r,i,n){yield*hxe(e,t,r,i),yield*yxe(e,t,r,i,n)}function*hxe(e,t,r,i){let n=[...gxe(Il(e.name),t,r,i)];n.length>0&&(yield{bindings:js(e,n),index:i+n.length})}function*gxe(e,t,r,i){for(let n=i;n<r.length&&r[n].name===e;n++){let o=Bo(r[n].value,t.allowReserved);if(o==null)return;yield o}}function*yxe(e,t,r,i,n){let o=[...vxe(t,r,i,new Set(n.map(s=>Il(s.name))))];o.length>0&&(yield{bindings:js(e,Object.fromEntries(o)),index:i+o.length})}function*vxe(e,t,r,i){for(let n=r;n<t.length;n++){let o=t[n];if(n>r&&i.has(o.name))return;let s=Bo(o.name,e.allowReserved),a=Bo(o.value,e.allowReserved);if(s==null||a==null)return;yield[s,a]}}function Sxe(e){let t=e.indexOf("=");return t<0?{name:e,value:""}:{name:e.slice(0,t),value:e.slice(t+1)}}function wxe(e,t){let r=[];for(let i=0;i<e.length;i+=2){let n=Bo(e[i],t),o=Bo(e[i+1],t);if(n==null||o==null)return null;r.push([n,o])}return Object.fromEntries(r)}function jV(e,t){let r=[];for(let i of e){let n=Bo(i,t);if(n==null)return null;r.push(n)}return r}function Bo(e,t){if(t)return e;try{return decodeURIComponent(e)}catch{return null}}var js=({name:e,prefix:t},r)=>({[e]:{value:r,prefix:t}});function NO(e,t){let r={...e};for(let[i,n]of Object.entries(t)){let o=r[i];if(o==null){r[i]=n;continue}let s=bxe(o,n);if(s==null)return null;r[i]=s}return r}var bxe=(e,t)=>iw(e)||iw(t)?_xe(e,t):xxe(e.value,t.value)?e:null;function _xe(e,t){let r=TV(e.value),i=TV(t.value);if(r==null||i==null)return null;let n=iw(e),o=iw(t);if(!n&&!o)return null;if(n&&!o)return Cf(i,e.prefix)===r?t:null;if(!n&&o)return Cf(r,t.prefix)===i?e:null;let s=e.prefix,a=t.prefix;return s<=a?Cf(i,s)===r?t:null:Cf(r,a)===i?e:null}var iw=e=>e.prefix!=null,TV=e=>typeof e=="string"?e:null;function xxe(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,i)=>r===t[i]):CV(e)?CV(t)&&Exe(Object.entries(e),Object.entries(t)):e===t}var Exe=(e,t)=>e.length===t.length&&e.every(([r,i],n)=>{let[o,s]=t[n];return r===o&&i===s}),CV=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Axe=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value])),UO=(e,t)=>t===""?[e]:e.split(t),Rxe=["=",",","!","@","|"];function Ixe(e,t,r){let i=a=>{throw a};if(e.length<1)return i(new R_e(t,r));let n=e[0];if(Cxe(n))return i(new I_e(t,r+1,n));if(!kV(n)&&TO(e,0)<1)return i(new $_e(t,r+1,n));let o=kV(n)?n:"",s=o===""?0:1;return{kind:"expression",operator:o,vars:$xe(e,t,r+1,s)}}function $xe(e,t,r,i){if(i>=e.length)throw new PO(t,r+i);let n=[];for(let o=i;o<e.length;){if(e[o]===",")throw o===e.length-1?new RV(t,r+o):new PO(t,r+o);let s=o,a=Pxe(e,o);if(a===s)throw new PO(t,r+o);let c=e.slice(s,a);o=a;let u=Txe(e,t,r,o,c);if(o=u.index,o<e.length&&e[o]!==",")throw u.used?new C_e(t,r+o,e[o]):new P_e(t,r+o,c,e[o]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),o<e.length&&(o++,o>=e.length))throw new RV(t,r+o-1)}return n}function Pxe(e,t){let r=t,i=!0;for(;r<e.length;){let n=TO(e,r);if(n>0){r+=n,i=!1;continue}if(e[r]!=="."||i||TO(e,r+1)<1)break;r++,i=!0}return r}function Txe(e,t,r,i,n){if(e[i]==="*")return{explode:!0,index:i+1,used:!0};if(e[i]!==":")return{explode:!1,index:i,used:!1};let o=i+1,s=o;for(;s<e.length&&kxe(e[s]);)s++;let a=e.slice(o,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new T_e(t,r+i,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function kV(e){return O_e.includes(e)&&e!==""}function Cxe(e){return Rxe.includes(e)}function kxe(e){let t=e.charCodeAt(0);return t>=48&&t<=57}function Dxe(e,t){let{report:r}=t,i=[],n=o=>{let s=i.at(-1);s?.kind==="literal"?i[i.length-1]={kind:"literal",text:s.text+o}:i.push({kind:"literal",text:o})};for(let o=0;o<e.length;){let s=e[o];if(s==="{"){let l=e.indexOf("}",o+1);if(l<0){r(new __e(e,o)),n(e.slice(o));break}let d=e.indexOf("{",o+1);if(d>=0&&d<l){r(new E_e(e,d)),n(e.slice(o,l+1)),o=l+1;continue}let m=e.slice(o+1,l);try{i.push(Ixe(m,e,o))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(e.slice(o,l+1))}o=l+1;continue}if(s==="}"){r(new x_e(e,o)),n(s),o++;continue}let a=U_e(e,o);if(a>0){n(e.slice(o,o+a)),o+=a;continue}let{char:c,size:u}=Of(e,o);r(new A_e(e,o,c)),n(c),o+=u}return i}var sw=class FV{uriTemplate;options;#e;#t;constructor(t,r={}){this.uriTemplate=t,this.options=r,this.#t=Mxe(r),this.#e=Oxe(Dxe(t,this.#t)),Object.freeze(this)}static parse(t,r={}){return new FV(t,r)}get tokens(){return this.#e}expand=t=>MV(this.#e,t,this.#t);match=t=>Y_e(this.#e,t,this.#t);toString=()=>this.uriTemplate},Oxe=e=>Object.freeze(e.map(Nxe)),Nxe=e=>e.kind==="literal"?Object.freeze({kind:"literal",text:e.text}):Object.freeze({kind:"expression",operator:e.operator,vars:Object.freeze(e.vars.map(Uxe))}),Uxe=e=>Object.freeze({name:e.name,explode:e.explode,...e.prefix==null?{}:{prefix:e.prefix}}),Lxe=()=>{},Mxe=({strict:e,report:t})=>(t??=Lxe,e??=!0,t=e?zxe(t):t,{strict:e,report:t}),zxe=e=>t=>{throw e(t),t};var Gs=class extends Error{constructor(r,i){super(i);this.code=r}code};function jxe(e,t){return!e.when||t[e.when.field]===void 0||e.when.values.includes(t[e.when.field])}function qV(e,t,r={}){let i=(o,s)=>{throw new Gs(o,s)},n={...r,...t};for(let o of e)n[o.name]===void 0&&o.defaultValue!==void 0&&(n[o.name]=o.defaultValue);for(let o of e){if(!jxe(o,n)){delete n[o.name];continue}o.required!==!1&&!n[o.name]&&i("missing_field","Complete the required service fields."),n[o.name]?.includes("\0")&&i("invalid_field","Check the service fields."),o.choices&&n[o.name]&&!o.choices.some(s=>s.value===n[o.name])&&i("invalid_field","Choose an available service setting."),o.pattern&&(o.pattern.length>200||!(0,GV.default)(o.pattern))&&i("invalid_pattern","Use a simple field validation pattern."),o.pattern&&n[o.name]&&!new RegExp(o.pattern,"u").test(n[o.name].slice(0,1e3))&&i("invalid_field","Check the service fields.")}return Object.keys(t).some(o=>!e.some(s=>s.name===o))&&i("invalid_field","Remove unrecognized service fields."),n}function qs(e,t,r={}){let i=qV(e,t,r),n={};for(let o of e){let s=o.choices?.find(a=>a.value===i[o.name]);for(let[a,c]of Object.entries(s?.values??{})){if(e.some(u=>u.name===a)||a in n&&n[a]!==c)throw new Gs("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...i,...n}}function LO(e,t){for(let[r,i]of Object.entries(t)){let n=e.find(o=>o.name===r);if(!n)throw new Gs("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&i!=="")throw new Gs("encrypted_input_required","Supply private material directly with your encryption keys.")}return qV(e.map(r=>({...r,required:!1,defaultValue:void 0})),t)}function $l(e,t){return LO(e,Object.fromEntries(e.filter(r=>r.secret===!1&&t[r.name]).map(r=>[r.name,t[r.name]])))}function VV(e,t=Pf(e)){return t.accountVerified?t.accountId:null}function KV(e,t=Pf(e)){let i=(e.method.kind==="oauth"||e.method.kind==="ovh"||e.method.kind==="token"&&!!(e.method.config.identity||e.method.config.resolver||e.method.config.bindFields))&&e.method.kind!=="aws"?$l(e.method.config.fields,e.fields??{}):{};return{format:e.format,generation:e.generation,methodId:e.methodId,method:e.method,appId:e.appId,appGeneration:e.appGeneration,..."implicitApp"in e&&e.implicitApp?{implicitApp:{clientId:e.implicitApp.clientId,generation:e.implicitApp.generation,fields:e.implicitApp.fields}}:{},account:t.accountId,accountVerified:t.accountVerified,scopes:[...t.scopes].sort(),...Object.keys(i).length?{fields:i}:{},...t.authorization,...e.state?{state:e.state}:{}}}var Vs=f.record(f.string().max(100),f.string().max(16384)),aw=f.object({format:f.literal(1),methodId:f.string().min(1),generation:P,clientId:f.string().max(1e3),clientSecret:f.string().max(16384).optional(),fields:Vs}).strict(),MO=f.object({accessToken:f.string().min(1).max(16384),refreshToken:f.string().min(1).max(16384).optional(),expiresAt:f.number().nullable(),refreshExpiresAt:f.number().optional(),scopes:f.array(f.string()),requestedScopes:f.array(f.string()).optional(),account:f.string(),accountName:f.string(),accountVerified:f.boolean().optional(),scopesStatus:f.enum(["unknown","requested","reported"]).optional(),extra:Vs,facts:Mt}).strict(),Nf={format:f.literal(2),methodId:f.string().min(1),method:fl,generation:P,appId:P.nullable(),appGeneration:P.nullable(),state:f.literal("reconnect").optional()},Wo=f.never().optional(),Pl=f.union([f.object({...Nf,method:$S,oauth:MO.optional(),requestedScopes:f.array(f.string()).optional(),implicitApp:aw.optional(),fields:Vs.optional(),aws:Wo}).strict(),f.object({...Nf,method:PS,fields:Vs,facts:Ms.optional(),oauth:Wo,aws:Wo}).strict(),f.object({...Nf,method:kS,fields:Vs,oauth:Wo,aws:Wo}).strict(),f.object({...Nf,method:CS,fields:Vs,ovh:gf.optional(),requestedScopes:f.array(f.string()).optional(),oauth:Wo,aws:Wo}).strict(),f.object({...Nf,method:TS,aws:bS,oauth:Wo,fields:Wo}).strict()]).superRefine((e,t)=>{if("implicitApp"in e&&e.implicitApp&&(e.method.kind!=="oauth"||e.method.config.application!=="implicit"||e.implicitApp.methodId!==e.methodId)&&t.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),e.method.kind==="oauth"&&e.fields)try{LO(e.method.config.fields,e.fields)}catch{t.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}xl(e.method)&&(!e.appId||!e.appGeneration)&&t.addIssue({code:"custom",message:"Bind the application required by this connection."}),!xl(e.method)&&e.appId!==null&&t.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!e.appId!=!!e.appGeneration&&t.addIssue({code:"custom",message:"Bind the application and its generation together."}),e.method.kind==="oauth"&&e.method.config.grantType==="client_credentials"&&!("requestedScopes"in e&&e.requestedScopes)&&!e.oauth?.requestedScopes&&t.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),qYe=f.object({methodId:f.string().min(1).max(200),clientId:f.string().max(1e3),generation:P,fields:Vs.optional()}).strict(),Fxe=f.object({methodId:f.string().min(1).max(200),methodKind:QD,http:IS.optional(),generation:P,authorizationDigest:yt,appId:P.nullable(),accountId:f.string().max(2e3).nullable(),accountVerified:f.boolean(),scopes:f.array(f.string().max(1e3)).max(200),scopesStatus:f.enum(["unknown","requested","reported"]),outputs:f.array(f.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:f.enum(["ready","reconnect"]),revocable:f.literal(!0).optional(),fields:Vs.optional(),aws:_S.optional(),ovh:gf.optional()}).strict();async function BV(e,t=Pf(e)){let{outputs:r,revocable:i}=Ls(e.method),n=e.method.kind!=="aws"&&e.fields?$l(e.method.config.fields,e.fields):{},o=await te(KV(e,t));return Fxe.parse({methodId:e.methodId,methodKind:e.method.kind,...e.method.http?{http:e.method.http}:{},generation:e.generation,authorizationDigest:o,appId:e.appId,accountId:VV(e,t),accountVerified:t.accountVerified,scopes:t.scopes,scopesStatus:t.scopesStatus,outputs:r,state:e.state??"ready",...i?{revocable:i}:{},...Object.keys(n).length?{fields:n}:{},...t.details})}var Gxe=f.array(f.object({name:f.string(),label:f.string(),value:f.string()}).strict()),HV=f.object({methodName:be,account:f.string().max(2e3),settings:Gxe.optional()}).strict();var zO=f.discriminatedUnion("action",[f.object({action:f.literal("refresh"),id:P}).strict(),f.object({action:f.literal("revoke"),id:P}).strict()]);var jO=gl.extend({name:be}),YYe=gl.extend({previousSignature:_t.optional()}).strict(),QYe=f.object({name:be,content:ir,labels:HV.optional(),version:f.number().int().positive().optional()}).strict(),FO=f.object({content:ir,version:f.number().int().positive()}).strict(),WV=f.object({id:P,reason:f.enum(["grantExpired","recipients"]),remove:f.array(P).max(1e3).default([])}).strict(),eQe=f.record(P,f.object({version:f.number().int().positive(),content:ir}).strict()),JV=f.object({id:P,name:be,version:f.number().int().positive(),content:ir,policy:qo}).strict(),ZV=f.object({registration:uO,stoppedAt:f.iso.datetime().nullable(),heartbeatAt:f.iso.datetime().nullable()}).strict(),XV=f.object({lease:P,request:qS,sources:f.array(ir).max(100)}).strict().nullable(),qxe=f.object({lease:P}).strict(),tQe=qxe.extend({receipt:$f}).strict(),Uf=f.object({id:P,resource_id:P,executor_id:P,expected_revision:f.number().int().positive(),state:f.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:f.string().regex(/^\d+$/),result:ir.nullable()}),rQe=f.object({id:P,resourceId:P,expectedRevision:f.number().int().positive()}).strict(),Vxe=f.object({fence:f.string().regex(/^\d+$/)}).strict(),nQe=Vxe.extend({content:ir}).strict(),iQe=f.object({id:P,executionId:P,index:f.number().int().nonnegative(),stateDigest:yt,expiresAt:ne}).strict(),oQe=f.object({id:P,executionId:P,context:f.string(),sealed:jo.nullable(),expiresAt:ne,receivedAt:ne.nullable()}).strict();var Kxe=f.object({binding:vt,verifiedAt:ne}).strict(),GO=f.object({origin:f.url(),ownerId:P,signerId:P,revision:f.number().int().positive(),keys:f.array(Kxe).max(1e3)}).strict(),Bxe=f.object({version:f.number().int().positive(),signature:_t}).strict(),qO=f.object({keyring:Bxe.nullable()}).strict(),dQe=f.object({version:f.number().int().positive().nullable(),signature:_t}).strict();function YV(e,t){return Tt(GO.parse(e),t,"keyring")}function QV(e){return GO.parse(JSON.parse(NS($q(e.split(".")[1]??""))))}async function e3(e,t){let r=GO.parse(await _f(e,t.signing,"keyring"));if(r.signerId!==t.id)throw new Error("Another identity signed this keyring.");return r}var Tl=lt(r3(),1);var Me=class extends Error{constructor(r,i,n,o){super(n);this.status=r;this.code=i;this.details=o}status;code;details};function M(e,t,r,i){throw new Me(e,t,r,i)}var Hxe=Tl.default.IPv6.parseCIDR("2000::/3"),Wxe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function uw(e){if(!Tl.default.isValid(e)||e.includes("%"))return!1;let t=Tl.default.parse(e);return Wxe.has(t.range())&&(!(t instanceof Tl.default.IPv6)||t.match(Hxe))}function Pn(e,t){let r;try{r=new URL(e)}catch{M(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===t)&&M(400,"invalid_url","Choose a public HTTPS destination.");let i=r.hostname.replace(/^\[|\]$/g,"");return(i==="localhost"||i.endsWith(".localhost")||i.endsWith(".local")||Tl.default.isValid(i)&&!uw(i))&&M(400,"private_destination","Choose a public HTTPS destination."),r}function Cl(e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.body))}catch{M(502,"invalid_response","The service returned an invalid response.")}return(!t||typeof t!="object"||Array.isArray(t))&&M(502,"invalid_response","The service returned an invalid response."),t}function Lf(e){return[...e.connectionId?[{id:e.connectionId}]:[],...e.bindings.flatMap(t=>t.parts.filter(r=>typeof r!="string"))]}function VO(e,t,r){e.method.http||M(400,"invalid_http_connection","This connection does not provide HTTP authentication.");let i=e.method.http.urlField,n=i&&((e.method.kind==="token"?e.method.config.constants?.[i]:void 0)??e.fields?.[i]);i&&!n&&M(409,"reconnect_required","Reconnect with a destination URL.");let o=Pn(t.url??n??"",r);return n&&o.origin!==Pn(n,r).origin&&M(400,"invalid_destination","Use this connection only at its configured destination host."),o.href}function n3(e,t,r,i){let n=new URL(e),o={...t},s=[];Object.keys(t).some(l=>["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase()))&&M(400,"invalid_authentication","Use HTTP headers that do not override routing or transport settings.");let a=(l,d=!0)=>{Object.hasOwn(i,l)||M(400,"invalid_authentication","Choose an available authentication output.");let m=i[l];return d&&s.push(m),m},c=(l,d)=>{(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(l)||["host","connection","content-length","transfer-encoding","proxy-authorization"].includes(l.toLowerCase())||/[\r\n\0]/.test(d))&&M(400,"invalid_authentication","Use a valid authentication header."),Object.keys(o).some(m=>m.toLowerCase()===l.toLowerCase())&&M(400,"invalid_authentication","Let the selected connection supply its authentication header."),o[l]=d,s.push(d)},u=r.authentication;if(u.kind==="bearer")c("Authorization","Bearer "+a(u.token));else if(u.kind==="basic"){let l=a(u.username),d=a(u.password);l.includes(":")&&M(400,"invalid_authentication","A Basic authentication username cannot contain a colon.");let m=new TextEncoder().encode(l+":"+d),p=btoa(Array.from(m,g=>String.fromCharCode(g)).join(""));c("Authorization","Basic "+p),s.push(p)}else if(u.kind==="header"||u.kind==="query"){let l=typeof u.name=="string"?u.name:a(u.name.output,!1),d=a(u.value);u.kind==="header"?c(l,d):((!l||/[\r\n\0]/.test(l)||n.searchParams.has(l))&&M(400,"invalid_authentication","Let the selected connection supply its authentication query parameter."),n.searchParams.set(l,d))}return s.push(n.href),{url:n.href,headers:o,sensitive:s}}var Lr=class extends Error{constructor(r,i){super(i);this.code=r}code},BO=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},KO=(e,...t)=>!!e&&typeof e=="object"&&("code"in e&&t.includes(String(e.code))||"status"in e&&t.includes(Number(e.status))),lw=class{constructor(t,r,i,n,o){this.api=t;this.origin=r;this.binding=i;this.keys=n;this.trust=o}api;origin;binding;keys;trust;verifiedKeys;async trusted(t){if(!await this.verifies(t))throw t.principalId!==this.binding.principalId&&await this.known(t.principalId)?new Lr("identity_changed","Identity "+t.principalId+" replaced the keys verified before. Verify its current keys."):new Lr("identity_untrusted","Verify and trust the encryption and signing keys for identity "+t.principalId+" before sharing.");return t}async verifies(t){if(t.principalId===this.binding.principalId)return k(this.binding)===k(t);let r=await this.known(t.principalId);return!!r&&k(r)===k(t)}async known(t){return(await this.keyring()).get(t)?.binding??await this.trust.binding(t)}async verifiedIdentity(t){return this.verifies((await this.inspectIdentity(t)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(t=>{throw this.verifiedKeys=void 0,t})}async loadKeyring(){let t;try{t=(await this.readKeyring()).keyring?.keys??[]}catch(o){if(KO(o,401,403))return new Map;throw o}let r=new Set(t.map(o=>o.binding.principalId)),i=new Date().toISOString(),n=(await this.trust.bindings()).filter(o=>o.principalId!==this.binding.principalId&&!r.has(o.principalId));if(n.length)try{t=(await this.changeKeyring(o=>[...o,...n.filter(s=>!o.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:i}))])).keys}catch(o){if(o instanceof Lr)throw o}return new Map(t.map(o=>[o.binding.principalId,o]))}async readKeyring(){let t="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(t,{},qO),i=await this.trust.keyring(),n=()=>new Lr("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(i)throw n();return{version:null,revision:0,keyring:null}}let o=QV(r.signature);if(o.signerId!==this.binding.id)return{version:r.version,revision:o.revision,keyring:null};let s=await e3(r.signature,this.binding).catch(()=>{throw n()}),a=await te(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||i&&(s.revision<i.revision||s.revision===i.revision&&a!==i.digest))throw n();return(!i||s.revision>i.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(t){for(let r=1;;r++){let i=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:i.revision+1,keys:t(i.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:i.version,signature:await YV(n,this.keys.signing)}},qO)}catch(o){if(r<3&&KO(o,"changed"))continue;throw o}return await this.trust.rememberKeyring({revision:n.revision,digest:await te(n)}),n}}async inspectIdentity(t){let r=await this.api.json("/api/identities/"+P.parse(t)+"/binding",{},gl);return await LS(r),{...r,fingerprint:await US(r.binding)}}async trustIdentity(t,r){let i=await this.inspectIdentity(t);if(i.fingerprint!==r)throw new Lr("fingerprint_mismatch","The identity fingerprint does not match.");if(t===this.binding.principalId||k((await this.keyring()).get(t)?.binding??null)===k(i.binding))return i;let n=new Date().toISOString();try{let o=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==t),{binding:i.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(o.keys.map(s=>[s.binding.principalId,s])))}catch(o){if(!KO(o,401,403))throw o;await this.trust.rememberBinding(i.binding)}return i}async environment(t,r=!0){let{registration:i,stoppedAt:n}=await this.api.json("/api/environments/"+P.parse(t)+"/registration",{},ZV);if(await wl(i),i.manifest.origin!==this.origin||i.manifest.id!==t||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(i.manifest.executor),i}async recipients(t){let{items:r}=await this.api.json("/api/principals/"+P.parse(t)+"/bound-recipients",{},hl(jO));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...s}of r)await LS(s),await this.trusted(s.binding);let i=await this.api.json("/api/principals/"+P.parse(t)+"/bound-delegates",{},hl(jO)),n=[];for(let{name:o,...s}of i.items){await LS(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof Lr&&["identity_untrusted","identity_changed"].includes(a.code)))throw a}}return[...r.map(o=>o.binding),...n]}async read(t){let r=await this.latest(t);if(r.replaced)throw new Lr("key_replaced","This item is sealed only for keys this identity has since replaced. Enter its value again.");return r}async latest(t){let r=await this.api.json("/api/custody/"+P.parse(t),{},FO);return this.replaces(r.content.policy)?{...r,replaced:!0}:(await this.observe(r.content,t),{...r,replaced:!1})}replaces(t){return!t.readers.some(r=>k(r)===k(this.binding))&&t.readers.some(r=>r.principalId===this.binding.principalId)}async observe(t,r=t.policy.id){let i=await sn(t);if(i.policy.id!==r||i.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=sO(i);await this.trusted(n);let o=await this.trust.checkpoint(i);if(o&&qo.parse(o.policy),o){if(i.policy.revision<o.policy.revision||i.materialRevision<o.materialRevision||i.policy.revision===o.policy.revision&&k(i.policy)!==k(o.policy)||i.materialRevision===o.materialRevision&&await te(i)!==o.digest)throw new Lr("content_conflict","The encrypted content is older than this device has already observed.");if(i.policy.revision>o.policy.revision&&!MS(o.policy,i)&&!o.policy.authorities.some(s=>s.principalId===n.principalId&&s.id!==n.id))throw new Lr("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(i),i}async reveal(t){return If((await this.read(t)).content,this.binding,this.keys.encryption)}async sharing(t){let r=typeof t=="string"?(await this.api.json(t,{},hl(JV))).items:t,i={};for(let n of r){let o=await this.read(n.id);if(o.version!==n.version||k(o.content)!==k(n.content))throw new Lr("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);i[n.id]={version:n.version,content:await Af(await If(o.content,this.binding,this.keys.encryption),n.policy,o.content.materialRevision+1,this.binding,this.keys,o.content.metadata,o.content)}}return i}async policy(t,r,i=[],n={}){let o=n.previous?.readers??[...new Map([...await this.recipients(t),this.binding].map(c=>[c.id,c])).values()];if(!o.some(c=>k(c)===k(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)&&Go(c)):[];for(let c of i)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...nO(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return qo.parse({format:2,id:n.id??n.previous?.id??n.replacing?.id??crypto.randomUUID(),origin:this.origin,ownerId:t,contentType:r,revision:(n.previous?.revision??n.replacing?.revision??0)+1,authorities:n.previous?.authorities??o,readers:o,grants:a,producers:[]})}async save(t,r,i,n={}){let o=n.previous;o&&k(i)===k({...o.content.policy,revision:i.revision})&&(i={...i,revision:o.content.policy.revision});let s=await Af(r,i,(o?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,o&&!this.replaces(o.content.policy)?o.content:void 0),a={name:t,content:s,...n.labels?{labels:n.labels}:{},...o?{version:o.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:a},ml);return await this.trust.rememberContent(s),c}async pass(t,r,i,n){let o=await Af(r,i,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+i.id+"/custody",{method:"PUT",body:{name:t,content:o,version:n.version}},f.union([ml,Nq]));return"kind"in s&&await this.trust.rememberContent(o),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},hl(WV))).items}async reprotect(t,r="grantExpired",i=[]){let n=await this.read(t),{policy:o}=n.content,s=Date.now(),a=new Set(i),c=r==="recipients"?await this.recipients(o.ownerId):[],u=new Map(c.map(C=>[C.principalId,C])),l=[...o.readers,...o.authorities,...o.grants.flatMap(C=>"actor"in C?[C.actor,C.executor]:[C.executor])];if(r==="recipients")for(let C of new Set(l.map(G=>G.principalId))){if(C===this.binding.principalId||u.has(C)||a.has(C))continue;let G=await this.inspectIdentity(C).then(B=>B.binding,()=>null);G&&l.some(B=>B.principalId===C&&B.id!==G.id)&&u.set(C,await this.trusted(G))}let d=C=>u.get(C.principalId)??C,m=C=>[...new Map(C.map(G=>[G.id,G])).values()],p=C=>!a.has(C.principalId),g=o.grants.filter(C=>Go(C,s)&&p(C.executor)&&(!("actor"in C)||p(C.actor))).map(C=>"actor"in C?{...C,actor:d(C.actor),executor:d(C.executor)}:{...C,executor:d(C.executor)}),v=m(o.readers.filter(p).map(d)),S=m(o.authorities.filter(p).map(d)),b=c.filter(C=>!v.some(G=>G.id===C.id)),_={...o,revision:o.revision+1,grants:g,producers:[],readers:[...v,...b],authorities:[...S,...b.filter(C=>!S.some(G=>G.id===C.id))],...o.observers?{observers:o.observers.filter(C=>!a.has(C))}:{}},x=o.contentType!==ge.executionResult&&o.producers.some(C=>Date.parse(C.expiresAt)>s);if(k({..._,revision:o.revision})===k(o)||x)return null;let T=await If(n.content,this.binding,this.keys.encryption);if(o.contentType===ge.executionResult){let C=await Af(T,_,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+t,{method:"PUT",body:{name:"Execution result",content:C,version:n.version}},FO),await this.trust.rememberContent(C),t}let U=await this.api.json("/api/resources/"+o.id,{},ml);return this.save(U.name,T,_,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let t=[],r=[];for(let i of await this.pendingProtection())try{await this.reprotect(i.id,i.reason,i.remove)&&t.push(i.id)}catch(n){r.push({id:i.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:t,failed:r}}async sourceContents(t){let r=new Map;for(let i of new Set(t))r.set(i,(await this.read(i)).content);for(let i of[...r.values()])i.policy.contentType===ge.tokenSet&&typeof i.metadata.appId=="string"&&!r.has(i.metadata.appId)&&r.set(i.metadata.appId,(await this.read(i.metadata.appId)).content);return[...r.values()]}async output(t,r,i,n,o){let s,a=null;do{let d=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),m=await this.api.json("/api/principals/"+t+"/resources?"+d,{},hl(ml));s=m.items.find(p=>p.name===r),a=m.next}while(!s&&a);let c=s?await this.latest(s.id):void 0,u=c?.content,l=u&&!c.replaced?{...u.policy,revision:u.policy.revision+1,producers:[]}:await this.policy(t,ge.value,[],{replacing:u?.policy});return l.producers=[{executor:n.manifest.executor,runId:i,expiresAt:o,materialRevision:(u?.materialRevision??0)+1}],{name:r,approval:await FS(l,this.binding,this.keys,c?.replaced?void 0:u)}}async prepare(t,r,i,n={}){let o=Ic.parse(i),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=o,l=u.kind==="http"?u.request:null;if(l?.connectionId&&s.manifest.httpVersion!==zi)throw new Lr("http_runtime_required","Update this execution environment to use HTTP connections.");if(o.kind==="http"){let S=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(S).map(async([_,x])=>[_,await this.output(t,x,a,s,c)])));o.save=b}let d=u.kind==="command"?u.inputs.map(S=>S.source.id):l?Lf(l).map(S=>S.id):[],m=await this.sourceContents([...d,...n.sourceIds??[]]);for(let S=0;S<m.length;S++){let b=m[S],_=b.policy.contentType===ge.clientCredential,x=_&&o.kind!=="revoke"?Q.refresh:Q[o.kind],T=_||!l?.url?void 0:new URL(l.url).origin;if(b.policy.grants.some(ee=>"actor"in ee&&k(ee.actor)===k(this.binding)&&k(ee.executor)===k(s.manifest.executor)&&ee.operations.includes(x)&&vl(ee)>=Date.parse(c)&&(!T||!ee.origins.length||ee.origins.includes(T))&&(_||ee.callerProgram))||!b.policy.authorities.some(ee=>k(ee)===k(this.binding)))continue;let C=await this.read(b.policy.id),G=await this.api.json("/api/resources/"+b.policy.id,{},ml),B={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[Q.refresh]:[]])],origins:T?[T]:[],functionDigests:[],callerProgram:!_,expiresAt:c},de=ee=>k({...ee,expiresAt:null}),pe=C.content.policy.grants.filter(ee=>de(ee)===de(B)),qe=qo.parse({...C.content.policy,revision:C.content.policy.revision+1,grants:[...C.content.policy.grants.filter(ee=>Go(ee)&&de(ee)!==de(B)),{...B,expiresAt:new Date(Math.max(Date.parse(c),...pe.map(ee=>vl(ee)))).toISOString()}]});await this.save(G.name,await If(C.content,this.binding,this.keys.encryption),qe,{previous:C,metadata:C.content.metadata}),m[S]=(await this.read(b.policy.id)).content}let p=await this.policy(t,ge.executionResult,[],{id:a});p.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let g={format:2,id:a,origin:this.origin,ownerId:t,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await te(s.manifest),operation:Q[o.kind],operationDigest:await te(o),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(m.map(async S=>({id:S.policy.id,materialRevision:S.materialRevision,policyDigest:await te(S.policy),...S.policy.contentType===ge.tokenSet&&typeof S.metadata.authorizationDigest=="string"?{authorizationDigest:S.metadata.authorizationDigest}:{}}))),resultRecipients:p.readers,...s.manifest.resultVersion?{resultApproval:await FS(p,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await bl(s,g);let v=S=>S.policy.contentType===ge.clientCredential;for(let S of m)await Os(S,v(S)&&g.operation!==Q.connect&&g.operation!==Q.revoke?{...g,operation:Q.refresh}:g,v(S)?{}:{destination:l?.url,destinationPending:!!(l?.connectionId&&!l.url)});return qq(g,o,this.keys)}async submit(t,r,i,n={}){return this.submitPrepared(await this.prepare(t,r,i,n))}async submitPrepared(t){await this.trust.rememberRun(t);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:t},Rc)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new BO(t.intent.id)}}async resume(t){let r=await this.trust.run(P.parse(t));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(k(r.intent.actor)!==k(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let i=await this.api.json("/api/runtime/runs/"+t,{},Rc);if(k(i.intent)!==k(r.intent)||i.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return i}catch(i){if(!i||typeof i!="object"||!("code"in i)||i.code!=="not_found")throw i}return this.submitPrepared(r)}async result(t){if(t.intent.origin!==this.origin||t.intent.id!==t.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(t.intent.actor);let r=await _f(t.requestSignature,t.intent.actor.signing,"run");if(k(r.intent)!==k(t.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(t.intent.executor),!(t.receipt&&"content"in t.receipt?t.receipt.content.policy.readers:t.intent.resultRecipients).some(n=>k(n)===k(this.binding)))throw new Lr("not_recipient","This identity is not a reader of the execution result.");return t.receipt&&"content"in t.receipt&&await this.observe(t.receipt.content,t.id),t.receipt?Zq(t.receipt,t.intent,this.binding.id,this.keys):null}async shareLegacyResult(t){if(!t.receipt||"content"in t.receipt)return t;if(k(t.intent.actor)!==k(this.binding)||k(t.intent.executor)!==k(this.binding))throw new Lr("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(t);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let i=await this.policy(t.ownerId,ge.executionResult,[],{id:t.id});i.producers=[{executor:this.binding,runId:t.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await dO(t.intent,t.receipt.state,r,this.keys,await FS(i,this.binding,this.keys),t.receipt);return this.api.json("/api/runtime/runs/"+t.id+"/result",{method:"PUT",body:{receipt:n}},Rc)}};import{lstat as Jxe,mkdir as i3,readFile as Zxe,readdir as o3,rm as Xxe}from"node:fs/promises";import{join as kl}from"node:path";var dw=f.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Tc=class{constructor(t,r,i,n){this.directory=t;this.origin=r;this.binding=i;this.privateKeys=n}directory;origin;binding;privateKeys;indexing;context(t){return k({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:dw.parse(t)})}async read(t){let r=this.context(t),i=kl(this.directory,t+".json");try{let n=await Jxe(i);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let o=f.string().max(32e6).parse(JSON.parse(await Zxe(i,"utf8"))),s=await gS(o,await An(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(NS(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await nr({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 writeEntry(t,r){let i=this.context(t),n={context:i,value:r},o=await Tt(n,this.privateKeys.signing,"journal"),s=ft(k({...n,signature:o}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new ll(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:i}).encrypt(await An(this.binding.encryption,"ECDH-ES+A256KW"));await i3(this.directory,{recursive:!0,mode:448}),await yO(kl(this.directory,t+".json"),k(a),!0)}delivery(t){return/^(run|process|invocation|refresh)_/.test(t)}delivered(t){return!!t&&typeof t=="object"&&"delivered"in t&&t.delivered===!0}async markPending(t){await i3(kl(this.directory,"pending"),{recursive:!0,mode:448}),await yO(kl(this.directory,"pending",dw.parse(t)),"",!0)}index(){return this.indexing??=(async()=>{let t="checkpoint_pending_index";if(!await this.read(t)){for(let r of await this.keys("")){if(!this.delivery(r))continue;let i=await this.read(r);i&&!this.delivered(i)&&await this.markPending(r)}await this.writeEntry(t,{version:1})}})()}async write(t,r){await this.index();let i=this.delivered(r);this.delivery(t)&&!i&&await this.markPending(t),await this.writeEntry(t,r),this.delivery(t)&&i&&await Xxe(kl(this.directory,"pending",t),{force:!0})}async pending(t){await this.index();let r;try{r=await o3(kl(this.directory,"pending"),{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)).map(i=>dw.parse(i.name))}async keys(t){let r;try{r=await o3(this.directory,{withFileTypes:!0})}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isFile()&&i.name.startsWith(t)&&i.name.endsWith(".json")).map(i=>dw.parse(i.name.slice(0,-5)))}};var pw=class{constructor(t){this.journal=t}journal;binding(t){return this.journal.read("identity_"+t)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(t){await Mi(t),await this.journal.write("identity_"+t.principalId,t)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(t){await this.journal.write("checkpoint_keyring",t)}checkpoint(t){return this.journal.read("checkpoint_"+t.policy.format+"_"+t.policy.id)}async rememberContent(t){await this.journal.write("checkpoint_"+t.policy.format+"_"+t.policy.id,{policy:t.policy,materialRevision:t.materialRevision,digest:await te(t)})}run(t){return this.journal.read("run_"+t)}async rememberRun(t){let r=await this.run(t.intent.id);if(r&&k(r)!==k(t))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+t.intent.id,t)}};var fw=class{api;constructor(t){this.api={async json(r,i={},n){try{return await t.json(r,i,n)}catch(o){throw o instanceof Error&&"status"in o&&typeof o.status=="number"&&"code"in o&&typeof o.code=="string"?new Me(o.status,o.code,o.message):o}}}}claim(t){return this.api.json("/api/environments/"+t+"/claim",{method:"POST",body:{}},XV)}renew(t,r){return this.api.json("/api/runtime/runs/"+t+"/renew",{method:"POST",body:{lease:r}},f.object({active:f.boolean()}))}dispatch(t,r){return this.api.json("/api/runtime/runs/"+t+"/dispatch",{method:"POST",body:{lease:r}})}finish(t,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:t,receipt:r}},Rc)}capture(t,r,i){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:t,content:r,...i?{labels:i}:{}}},f.object({id:P}))}connections(){let t=this.api;return{prepare:(r,i,n)=>t.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:i,expectedRevision:n}},Uf),dispatch:(r,i)=>t.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:i}},Uf),commit:(r,i,n)=>t.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:i,content:n}},ir),uncertain:(r,i)=>t.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:i}}),abort:(r,i)=>t.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:i}},Uf),state:r=>t.json("/api/connections/"+r+"/operation",{},Uf.nullable())}}};import{randomUUID as _Ue}from"node:crypto";var cs=lt(l4(),1);import{randomUUID as gNe}from"node:crypto";function qte(e){let t=wS.safeParse({accountId:e.Account,arn:e.Arn,principalId:e.Arn?.includes(":assumed-role/")?e.UserId?.split(":")[0]:e.UserId});return(!t.success||t.data.arn.split(":")[4]!==t.data.accountId)&&M(502,"invalid_response","The AWS account could not be verified."),t.data}function Vte(e,t){return e.accountId===t.accountId&&e.principalId===t.principalId&&dl(e.arn)===dl(t.arn)}function d4(e){e&&(!Number.isFinite(e.getTime())||e.getTime()<=Date.now())&&M(409,"reconnect_required","Reconnect with current AWS credentials.")}var OE=class{async obtain(t,r,i){let n=JD.parse({authentication:t.authentication,region:t.region,...t.role?{role:t.role}:{}}),o=n.authentication,s=o.kind==="environment"?void 0:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.kind==="session"?{sessionToken:o.sessionToken,expiration:new Date(o.expiresAt)}:{}};d4(s?.expiration);let a=new cs.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...i?[i]:[]]),l=!1;try{let d=s??await a.config.credentials();d4(d.expiration),c=new cs.STSClient({region:n.region,credentials:d});let m=r?.sourceIdentity?qte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&m&&!Vte(m,r.sourceIdentity)&&M(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,g=m;if(n.role){l=!0;let b=(await c.send(new cs.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+gNe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&M(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},d4(p.expiration),r?.identity&&(c.destroy(),c=new cs.STSClient({region:n.region,credentials:p}),g=qte(await c.send(new cs.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&g&&!Vte(g,r.identity)&&M(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:bS.parse({...n,sourceIdentity:m,identity:g}),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 Me)throw d;i?.aborted&&M(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&M(409,"reconnect_required","Reconnect with current AWS credentials."),l&&M(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),M(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var NE=class{constructor(t){this.aws=t}aws;facts=wO;needsRenewal(){return!1}async outputs(t,r,i){return(await this.aws.obtain(t.aws,t.aws,i)).credentials}};var p4;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(p4="oauth4webapi/v3.8.8");function GE(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var Io="ERR_INVALID_ARG_VALUE",us="ERR_INVALID_ARG_TYPE";function Ft(e,t,r){let i=new TypeError(e,{cause:r});return Object.assign(i,{code:t}),i}var Hte=Symbol(),yNe=Symbol(),vNe=Symbol(),b4=Symbol();var UE=Symbol();var SNe=new TextEncoder,wNe=new TextDecoder;function f4(e){return typeof e=="string"?SNe.encode(e):wNe.decode(e)}var m4;Uint8Array.prototype.toBase64?m4=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):m4=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let i=0;i<t.byteLength;i+=32768)r.push(String.fromCharCode.apply(null,t.subarray(i,i+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var h4;Uint8Array.fromBase64?h4=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}}:h4=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}catch(t){throw Ft("The input to be decoded is not correctly encoded.",Io,t)}};function g4(e){return typeof e=="string"?h4(e):m4(e)}var tp=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=YNe,Error.captureStackTrace?.(this,this.constructor)}},Gh=class extends Error{code;constructor(t,r){super(t,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function ve(e,t,r){return new Gh(e,{code:t,cause:r})}function LE(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Wte(e){GE(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(p4&&!t.has("user-agent")&&t.set("user-agent",p4),t.has("authorization"))throw Ft('"options.headers" must not include the "authorization" header name',Io);return t}function bNe(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw Ft('"options.signal" must return or be an instance of AbortSignal',us);return t}}function ME(e,t,r,i,n){try{if(typeof e!="number"||!Number.isFinite(e))throw Ft(`${r} must be a number`,us,n);if(e>0)return;if(t){if(e!==0)throw Ft(`${r} must be a non-negative number`,Io,n);return}throw Ft(`${r} must be a positive number`,Io,n)}catch(o){throw i?ve(o.message,i,n):o}}function $r(e,t,r,i){try{if(typeof e!="string")throw Ft(`${t} must be a string`,us,i);if(e.length===0)throw Ft(`${t} must not be empty`,Io,i)}catch(n){throw r?ve(n.message,r,i):n}}function Jte(e){xNe(e,"application/json")}function _Ne(e,...t){let r='"response" content-type must be ';if(t.length>2){let i=t.pop();r+=`${t.join(", ")}, or ${i}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return ve(r,eUe,e)}function xNe(e,t){if(LNe(e)!==t)throw _Ne(e,t)}async function Zte(e){return $r(e,"codeVerifier"),g4(await crypto.subtle.digest("SHA-256",f4(e)))}function Xte(e){let t=e?.[yNe];return typeof t=="number"&&Number.isFinite(t)?t:0}function Yte(e){let t=e?.[vNe];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Qte(){return Math.floor(Date.now()/1e3)}function np(e){if(typeof e!="object"||e===null)throw Ft('"as" must be an object',us);$r(e.issuer,'"as.issuer"')}function ip(e){if(typeof e!="object"||e===null)throw Ft('"client" must be an object',us);$r(e.client_id,'"client.client_id"')}function Kte(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function ere(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{i.set("client_id",r.client_id),i.set("client_secret",e)}}function tre(e){return $r(e,'"clientSecret"'),(t,r,i,n)=>{let o=Kte(r.client_id),s=Kte(e),a=btoa(`${o}:${s}`);n.set("authorization",`Basic ${a}`)}}function rre(){return(e,t,r,i)=>{r.set("client_id",t.client_id)}}var ENe=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function ANe(e,t){if(t&&e.protocol!=="https:")throw ve("only requests to HTTPS are allowed",rUe,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw ve("only HTTP and HTTPS requests are allowed",nUe,e)}function Bte(e,t,r,i){let n;if(typeof e!="string"||!(n=ENe(e)))throw ve(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?iUe:oUe,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return ANe(n,i),n}function nre(e,t,r,i){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Bte(e.mtls_endpoint_aliases[t],t,r,i):Bte(e[t],t,r,i)}var y4=class extends Error{cause;code;error;status;error_description;response;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=XNe,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)}},qh=class extends Error{cause;code;error;error_description;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=QNe,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)}},v4=class extends Error{cause;code;response;status;constructor(t,r){super(t,r),this.name=this.constructor.name,this.code=ZNe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},zE="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",RNe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",INe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',$Ne="("+zE+")\\s*=\\s*"+INe,PNe="("+zE+")\\s*=\\s*("+zE+")",TNe=new RegExp("^[,\\s]*("+zE+")"),CNe=new RegExp("^[,\\s]*"+$Ne+"[,\\s]*(.*)"),kNe=new RegExp("^[,\\s]*"+PNe+"[,\\s]*(.*)"),DNe=new RegExp("^("+RNe+")(?:$|[,\\s])(.*)");function ONe(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);let t=e.headers.get("www-authenticate");if(t===null)return;let r=[],i=t;for(;i;){let n=i.match(TNe),o=n?.[1].toLowerCase();if(!o)return;let s=i.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;i=a?a[1]:void 0;let u={},l;if(c)for(;i;){let m,p;if(n=i.match(CNe)){[,m,p,i]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[m.toLowerCase()]=p;continue}if(n=i.match(kNe)){[,m,p,i]=n,u[m.toLowerCase()]=p;continue}if(n=i.match(DNe)){if(Object.keys(u).length)break;[,l,i]=n;break}return}else i=s||void 0;let d={scheme:o,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function NNe(e){if(e.status>399&&e.status<500){wre(e),Jte(e);try{let t=await e.clone().json();if(LE(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function ire(e,t,r){if(e.status!==t){zNe(e);let i;throw(i=await NNe(e))?(await e.body?.cancel(),new y4("server responded with an error in the response body",{cause:i,response:e})):ve(`"response" is not a conform ${r} response (unexpected HTTP status code)`,tUe,e)}}function UNe(e){if(!x4.has(e))throw Ft('"options.DPoP" is not a valid DPoPHandle',Io)}function LNe(e){return e.headers.get("content-type")?.split(";")[0]}async function ore(e,t,r,i,n,o,s){return await r(e,t,n,o),o.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[b4]||fetch)(i.href,{body:n,headers:Object.fromEntries(o.entries()),method:"POST",redirect:"manual",signal:bNe(i,s?.signal)})}async function _4(e,t,r,i,n,o){let s=nre(e,"token_endpoint",t.use_mtls_endpoint_aliases,o?.[Hte]!==!0);n.set("grant_type",i);let a=Wte(o?.headers);a.set("accept","application/json"),o?.DPoP!==void 0&&(UNe(o.DPoP),await o.DPoP.addProof(s,a,"POST"));let c=await ore(e,t,r,s,n,a,o);return o?.DPoP?.cacheNonce(c,s),c}async function sre(e,t,r,i,n){np(e),ip(t),$r(i,'"refreshToken"');let o=new URLSearchParams(n?.additionalParameters);return o.set("refresh_token",i),_4(e,t,r,"refresh_token",o,n)}var are=new WeakMap,MNe=new WeakMap;function cre(e){if(!e.id_token)return;let t=are.get(e);if(!t)throw Ft('"ref" was already garbage collected or did not resolve from the proper sources',Io);return t}async function qE(e,t,r,i,n,o){if(np(e),ip(t),!GE(r,Response))throw Ft('"response" must be an instance of Response',us);await ire(r,200,"Token Endpoint"),wre(r);let s=await lUe(r);if($r(s.access_token,'"response" body "access_token" property',tt,{body:s}),$r(s.token_type,'"response" body "token_type" property',tt,{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;ME(a,!0,'"response" body "expires_in" property',tt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&$r(s.refresh_token,'"response" body "refresh_token" property',tt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw ve('"response" body "scope" property must be a string',tt,{body:s});if(s.id_token!==void 0){$r(s.id_token,'"response" body "id_token" property',tt,{body:s});let a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ME(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),i?.length&&a.push(...i);let{claims:c,jwt:u}=await KNe(e,t,s.id_token,a,n);HNe(t,c),BNe(c),MNe.set(r,u),are.set(s,c)}if(o?.[s.token_type]!==void 0)o[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new tp("unsupported `token_type` value",{cause:{body:s}});return s}function zNe(e){let t;if(t=ONe(e))throw new v4("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function ure(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}function jNe(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw ve('unexpected JWT "aud" (audience) claim value',rp,{expected:e,claims:t.claims,claim:"aud"});return t}function FNe(e,t){let r=e[dUe]?.(t)??e.issuer;if(t.claims.iss!==r)throw ve('unexpected JWT "iss" (issuer) claim value',rp,{expected:r,claims:t.claims,claim:"iss"});return t}var x4=new WeakSet;function GNe(e){return x4.add(e),e}var E4=Symbol();async function lre(e,t,r,i,n,o,s){if(np(e),ip(t),!x4.has(i))throw Ft('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Io);$r(n,'"redirectUri"');let a=du(i,"code");if(!a)throw ve('no authorization code in "callbackParameters"',tt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),o!==E4&&($r(o,'"codeVerifier"'),c.set("code_verifier",o)),_4(e,t,r,"authorization_code",c,s)}var dre={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 qNe(e,t){for(let r of e)if(t.claims[r]===void 0)throw ve(`JWT "${r}" (${dre[r]}) claim missing`,tt,{claims:t.claims});return t}function VNe(e,t){if(typeof t.claims[e]!="string")throw ve(`unexpected JWT "${e}" (${dre[e]}) claim type`,tt,{claims:t.claims});return t}function KNe(e,t,r,i,n){return sUe(r,aUe.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Xte(t),Yte(t),n).then(qNe.bind(void 0,["aud","exp","iat","iss","sub",...i])).then(FNe.bind(void 0,e)).then(jNe.bind(void 0,t.client_id)).then(VNe.bind(void 0,"sub"))}function pre(e,t){if(t===FE)return t;let r=t===void 0;return r&&(t=e.default_max_age),t===void 0?FE:(ME(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function BNe(e){e.auth_time!==void 0&&ME(e.auth_time,!0,'ID Token "auth_time" (authentication time)',tt,{claims:e})}function fre(e,t,r){if(r===FE)return;let i=Qte()+Xte(e),n=Yte(e);if(t.auth_time+r<i-n)throw ve("too much time has elapsed since the last End-User authentication",w4,{claims:t,now:i,tolerance:n,claim:"auth_time"})}function mre(e,t){let r=t===jE?void 0:t;if(e.nonce!==r)throw ve('unexpected ID Token "nonce" claim value',rp,{expected:r,claims:e,claim:"nonce"})}function HNe(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw ve('ID Token "aud" (audience) claim includes additional untrusted audiences',rp,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw ve('unexpected ID Token "azp" (authorized party) claim value',rp,{expected:e.client_id,claims:t,claim:"azp"})}}var jE=Symbol(),FE=Symbol();async function hre(e,t,r,i){return typeof i?.expectedNonce=="string"||typeof i?.maxAge=="number"||i?.requireIdToken?WNe(e,t,r,i.expectedNonce,i.maxAge,i[UE],i.recognizedTokenTypes):JNe(e,t,r,i?.maxAge,i?.[UE],i?.recognizedTokenTypes)}async function WNe(e,t,r,i,n,o,s){let a=[];switch(i){case void 0:i=jE;break;case jE:break;default:$r(i,'"expectedNonce" argument'),a.push("nonce")}n=pre(t,n),n!==FE&&a.push("auth_time");let c=await qE(e,t,r,a,o,s);$r(c.id_token,'"response" body "id_token" property',tt,{body:c});let u=cre(c);return fre(t,u,n),mre(u,i),c}async function JNe(e,t,r,i,n,o){let s=await qE(e,t,r,void 0,n,o),a=cre(s);return a&&(fre(t,a,pre(t,i)),mre(a,jE)),s}var ZNe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",XNe="OAUTH_RESPONSE_BODY_ERROR",YNe="OAUTH_UNSUPPORTED_OPERATION",QNe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var S4="OAUTH_PARSE_ERROR",tt="OAUTH_INVALID_RESPONSE";var eUe="OAUTH_RESPONSE_IS_NOT_JSON",tUe="OAUTH_RESPONSE_IS_NOT_CONFORM",rUe="OAUTH_HTTP_REQUEST_FORBIDDEN",nUe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",w4="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",rp="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var iUe="OAUTH_MISSING_SERVER_METADATA",oUe="OAUTH_INVALID_SERVER_METADATA";async function gre(e,t,r,i,n){return np(e),ip(t),_4(e,t,r,"client_credentials",new URLSearchParams(i),n)}async function yre(e,t,r,i){return qE(e,t,r,void 0,i?.[UE],i?.recognizedTokenTypes)}async function vre(e,t,r,i,n){np(e),ip(t),$r(i,'"token"');let o=nre(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,n?.[Hte]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",i);let a=Wte(n?.headers);return a.delete("accept"),ore(e,t,r,o,s,a,n)}async function Sre(e){if(!GE(e,Response))throw Ft('"response" must be an instance of Response',us);await ire(e,200,"Revocation Endpoint")}function wre(e){if(e.bodyUsed)throw Ft('"response" body has been used already',Io)}async function sUe(e,t,r,i,n){let{0:o,1:s,length:a}=e.split(".");if(a===5)if(n!==void 0)e=await n(e),{0:o,1:s,length:a}=e.split(".");else throw new tp("JWE decryption is not configured",{cause:e});if(a!==3)throw ve("Invalid JWT",tt,e);let c;try{c=JSON.parse(f4(g4(o)))}catch(d){throw ve("failed to parse JWT Header body as base64url encoded JSON",S4,d)}if(!LE(c))throw ve("JWT Header must be a top level object",tt,e);if(t(c),c.crit!==void 0)throw new tp('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(f4(g4(s)))}catch(d){throw ve("failed to parse JWT Payload body as base64url encoded JSON",S4,d)}if(!LE(u))throw ve("JWT Payload must be a top level object",tt,e);let l=Qte()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw ve('unexpected JWT "exp" (expiration time) claim type',tt,{claims:u});if(u.exp<=l-i)throw ve('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',w4,{claims:u,now:l,tolerance:i,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw ve('unexpected JWT "iat" (issued at) claim type',tt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw ve('unexpected JWT "iss" (issuer) claim type',tt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw ve('unexpected JWT "nbf" (not before) claim type',tt,{claims:u});if(u.nbf>l+i)throw ve('unexpected JWT "nbf" (not before) claim value',w4,{claims:u,now:l,tolerance:i,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw ve('unexpected JWT "aud" (audience) claim type',tt,{claims:u});return{header:c,claims:u,jwt:e}}function aUe(e,t,r,i){if(e!==void 0){if(typeof e=="string"?i.alg!==e:!e.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?i.alg!==r:typeof r=="function"?!r(i.alg):!r.includes(i.alg))throw ve('unexpected JWT "alg" header parameter',tt,{header:i,expected:r,reason:"default value"});return}throw ve('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function du(e,t){let{0:r,length:i}=e.getAll(t);if(i>1)throw ve(`"${t}" parameter must be provided only once`,tt);return r}var cUe=Symbol(),uUe=Symbol();function bre(e,t,r,i){if(np(e),ip(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ft('"parameters" must be an instance of URLSearchParams, or URL',us);if(du(r,"response"))throw ve('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',tt,{parameters:r});let n=du(r,"iss"),o=du(r,"state");if(!n&&e.authorization_response_iss_parameter_supported)throw ve('response parameter "iss" (issuer) missing',tt,{parameters:r});if(n&&n!==e.issuer)throw ve('unexpected "iss" (issuer) response parameter value',tt,{expected:e.issuer,parameters:r});switch(i){case void 0:case uUe:if(o!==void 0)throw ve('unexpected "state" response parameter encountered',tt,{expected:void 0,parameters:r});break;case cUe:break;default:if($r(i,'"expectedState" argument'),o!==i)throw ve(o===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',tt,{expected:i,parameters:r})}if(du(r,"error"))throw new qh("authorization response from the server is an error",{cause:r});let a=du(r,"id_token"),c=du(r,"token");if(a!==void 0||c!==void 0)throw new tp("implicit and hybrid flows are not supported");return GNe(new URLSearchParams(r))}async function lUe(e,t=Jte){let r;try{r=await e.json()}catch(i){throw t(e),ve('failed to parse "response" body as JSON',S4,i)}if(!LE(r))throw ve('"response" body must be a top level object',tt,{body:r});return r}var dUe=Symbol();function Vh(e){if(e==="")return[];if(!e.startsWith("/")||/~(?![01])/u.test(e))throw new Error("Invalid JSON pointer.");let t=e.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(t.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return t}function Wn(e,t){for(let r of Vh(t)){if(e===null||typeof e!="object"||!Object.hasOwn(e,r))return;e=e[r]}return e}function A4(e,t,r){let i=Vh(t),n=i.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let o of i){if(e===null||typeof e!="object"||!Object.hasOwn(e,o))throw new Error("JSON pointer target does not exist.");e=e[o]}if(e===null||typeof e!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(e)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=e.length))throw new Error("Invalid array index.");e[n]=r}function La(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);throw new Error("The selected value is not text.")}function VE(e,t){return typeof t=="string"?La(Wn(e,t)):t.map(r=>typeof r=="string"?r:La(Wn(e,r.pointer))).join("")}function op(e,t){let r=new Set;for(let i of t)i&&(r.add(i),r.add(encodeURIComponent(i)),r.add(JSON.stringify(i).slice(1,-1)));for(let i of[...r].sort((n,o)=>o.length-n.length))e=e.split(i).join("[redacted]");return e}function R4(e,t){return btoa(Array.from(new TextEncoder().encode(e+":"+t),r=>String.fromCharCode(r)).join(""))}var _re=Object.assign(Object.create(null),{dpop:()=>M(502,"invalid_response","The service returned an unsupported token.")}),fUe={redirectUri:e=>e.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),_re,{"user access token":()=>{}})},mUe={authorize(e,t){delete e.response_type,delete e.client_id,delete e.redirect_uri,e.callback_url=t,e.key_label="Foundation"},async exchange({spec:e,transport:t,url:r,authorization:i,verifier:n}){let o=i.parameters;return(o.getAll("state").length!==1||o.get("state")!==i.state||o.getAll("code").length!==1||!o.get("code"))&&M(400,"invalid_state","Start the connection again."),t.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:o.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},hUe={revokeRequest({app:e,url:t,current:r}){return{url:t,method:"DELETE",headers:{authorization:"Basic "+R4(e.clientId,e.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},gUe={tokenParameters(e){let t=e.get("redirect_uri");t!==null&&(e.set("redirect_url",t),e.delete("redirect_uri"))}};function $o(e,t){let r=t?new URL(t):void 0;return{recognizedTokenTypes:_re,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(i){i.token_type===void 0&&(i.token_type="bearer")},...e.grantType==="client_credentials"?{clientCredentialsParameters(){return{...e.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(i){i.refresh_token===null&&delete i.refresh_token}}:{},...e.adapter==="ebay"?fUe:e.adapter==="openrouter"?mUe:e.adapter==="vultr"?gUe:{},...e.revoke?.style==="github"?hUe:{}}}function pu(e,t){try{return Pn(new sw(e).expand(t)).href}catch{M(400,"invalid_service_url","Check the service URL and its required fields.")}}var xre=(e,t=" ")=>typeof e=="string"?[...new Set(e.split(t).filter(Boolean))].sort():[],KE=e=>{let t=typeof e=="number"||typeof e=="string"?Number(e):NaN;return(!Number.isSafeInteger(t)||t<=0||t>315576e3)&&M(502,"invalid_response","The service returned an invalid expiry."),t};var BE=class{constructor(t){this.transport=t}transport;appValues(t,r){try{return{...qs(t.fields,r.fields,t.defaults),clientId:r.clientId}}catch(i){throw i instanceof Gs&&M(400,i.code,i.message),i}}async authorize(t,r,i,n,o,s){(t.grantType==="client_credentials"||!t.authorizeUrl)&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(pu(t.authorizeUrl,this.appValues(t,r))),c={...t.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:$o(t).redirectUri?.(r,o)??o,state:i};s.length&&(c.scope=s.join(t.scopes.separator)),t.pkce&&(c.code_challenge=await Zte(n),c.code_challenge_method="S256"),$o(t).authorize?.(c,o);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(t,r){let i={issuer:t.issuer??new URL(pu(t.grantType==="client_credentials"?t.tokenUrl:t.authorizeUrl,this.appValues(t,r))).origin,token_endpoint:pu(t.tokenUrl,this.appValues(t,r))};return t.issuer&&Pn(t.issuer),{server:i,client:{client_id:r.clientId}}}authentication(t,r){return r==="none"?rre():(t.clientSecret||M(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?tre(t.clientSecret):ere(t.clientSecret))}options(t){let r=t?.tokenFormat??"form";return{[b4]:async(i,{body:n,headers:o,method:s,signal:a})=>{let c=new URLSearchParams(n);t&&$o(t).tokenParameters?.(c);let u=await this.transport.send({url:i,method:s,headers:r==="json"?{...o,"content-type":"application/json"}:o,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(t){return Cl({status:t.status,headers:{},body:new Uint8Array(await t.arrayBuffer())})}checkResponse(t,r,i,n=!1){return(r>=400||i.error||t.okPointer&&Wn(i,t.okPointer)!==!0)&&(n&&(i.error==="invalid_grant"||i.error==="invalid_token")&&M(409,"reconnect_required","Reconnect this service to renew access."),r===429&&M(503,"service_rate_limit","The service is busy. Try again later."),M(502,"authorization_failed","The service did not authorize this connection.")),i}async tokenResponse(t,r,i,n=!1){i.status===429&&M(503,"service_rate_limit","The service is busy. Try again later.");let o=this.checkResponse(t,i.status,await this.json(i),n),{server:s,client:a}=this.configuration(t,r),c=new URL(s.token_endpoint),u={...o};delete u.id_token,$o(t,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=KE(u.expires_in));try{let d=await(n?ure:t.grantType==="client_credentials"?yre:hre)(s,a,Response.json(u,{status:i.status}),{recognizedTokenTypes:$o(t,c.href).recognizedTokenTypes});return{...o,...d}}catch(l){if(l instanceof Me)throw l;M(502,"invalid_response","The service did not return a valid access token.")}}token(t,r,i,n,o=!1){let s=r[$o(t).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&M(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+KE(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&M(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of t.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?xre(r.scope,t.scopes.separator):o?n?.scopes??i:i,scopesStatus:r.scope!==void 0?"reported":o?n?.scopesStatus??"unknown":i.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()+KE(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(t,r,i,n,o,s,a,c){t.grantType==="client_credentials"&&M(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=$o(t);if(l.exchange){let m=await l.exchange({spec:t,app:r,transport:this.transport,url:()=>pu(t.tokenUrl,this.appValues(t,r)),authorization:i,verifier:n});u=this.checkResponse(t,m.status,Cl(m))}else{let{server:m,client:p}=this.configuration(t,r),g;try{let v=bre(m,p,i.parameters,i.state);g=await lre(m,p,this.authentication(r,t.clientAuth),v,l.redirectUri?.(r,o)??o,t.pkce?n:E4,{...this.options(t),additionalParameters:t.tokenParams})}catch(v){throw(v instanceof Gh||v instanceof qh)&&M(400,"invalid_state","Start the connection again."),v}u=await this.tokenResponse(t,r,g)}let d=this.token(t,u,s,a);return await c?.(d,u),d}async clientCredentials(t,r,i,n,o){t.grantType!=="client_credentials"&&M(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(t,r),c=$o(t,s.token_endpoint),u={...t.tokenParams,...i.length?{scope:i.join(t.scopes.separator)}:{}},l=await gre(s,a,this.authentication(r,t.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(t)),d=await this.tokenResponse(t,r,l),m={...this.token(t,d,i,n,!!n),requestedScopes:i};return await o?.(m,d),m}async refresh(t,r,i,n){let o=i;if(i.expiresAt!==null&&i.expiresAt<Date.now()+6e4){if(t.grantType==="client_credentials")return i.requestedScopes||M(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(t,r,i.requestedScopes,i,n);(!i.refreshToken||i.refreshExpiresAt&&i.refreshExpiresAt<=Date.now())&&M(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(t,r),c=await sre(s,a,this.authentication(r,t.clientAuth),i.refreshToken,{...this.options(t),additionalParameters:t.tokenParams}),u=await this.tokenResponse(t,r,c,!0);o=this.token(t,u,i.scopes,i,!0),await n?.(o,u)}return o}async revoke(t,r,i){if(!t.revoke?.tokenOnly)throw new Error("Revoke only with an endpoint that invalidates this token alone.");let n=pu(t.revoke.url,{...this.appValues(t,r),accessToken:i.accessToken,refreshToken:i.refreshToken??""});if(t.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(t,r),l=t.revoke.auth==="none"&&t.clientAuth!=="none"?()=>{}:this.authentication(r,t.revoke.auth??t.clientAuth),d=await vre({...c,revocation_endpoint:n},u,l,i.refreshToken??i.accessToken,this.options());try{await Sre(d)}catch{M(502,"revoke_failed","The service did not revoke the token.")}return}let o={},s=t.revoke.auth??t.clientAuth;t.revoke.style==="bearer"?o.authorization="Bearer "+i.accessToken:s==="basic"&&(o.authorization="Basic "+R4(r.clientId,r.clientSecret??"")),(await this.transport.send($o(t).revokeRequest?.({spec:t,app:r,transport:this.transport,url:n,current:i})??{url:n,method:t.revoke.style==="bearer"?"POST":"DELETE",headers:o})).status>=300&&M(502,"revoke_failed","The service did not revoke the token.")}outputs(t,r,i){let n={...this.appValues(t,r),...i.extra,...i,expiresAt:i.expiresAt===null?"":String(i.expiresAt)};return Object.fromEntries(Object.entries(t.outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};function I4(e){if(e.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return e.method.config}function $4(e){return e||M(409,"app_required","Choose an OAuth application."),e}function yUe(e){return{token:MO.parse(e.token),response:Mt.parse(e.response)}}var HE=class{constructor(t){this.transport=t}transport;facts=vO;oauth(t){return new BE({send:r=>this.transport.send({...r,...t?{signal:AbortSignal.any([t,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(t){return!t.oauth||t.oauth.expiresAt!==null&&t.oauth.expiresAt<Date.now()+6e4}async renew(t){let r=t.material,i=I4(r),n=$4(t.app),o=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>t.receive({token:c,response:u}),a=i.grantType==="client_credentials"?await this.oauth(t.signal).clientCredentials(i,n,o??rV(i.scopes),r.oauth,s):await this.oauth(t.signal).refresh(i,n,r.oauth,s);return Pl.parse({...t.material,oauth:a})}async recover(t,r,i){let o=yUe(i).token;return Pl.parse({...t,oauth:o})}async outputs(t,r){return this.oauth().outputs(I4(t),$4(r),t.oauth)}async revoke(t,r,i){t.oauth&&await this.oauth(i).revoke(I4(t),$4(r),t.oauth)}};function vUe(e){if(e.method.kind!=="token"&&e.method.kind!=="approval")throw new Error("Use an input credential provider.");return e.method.config}var Kh=class{facts=El;needsRenewal(){return!1}async outputs(t){let r=vUe(t),i=qs(r.fields,t.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,o])=>[n,VE(i,o)]))}};function WE(e){if(e.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return e.method.config}var JE=class{facts=SO;values(t,r){let i=WE(t),n=i.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&M(409,"app_required","Choose an OVHcloud API application with its key and secret.");let o=n?r.fields:t.fields;return qs(i.fields,o)}credentials(t,r){if(WE(t).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:t.fields.consumerKey};let i=this.values(t,r);return{applicationKey:i.applicationKey,applicationSecret:i.applicationSecret,consumerKey:i.consumerKey}}needsRenewal(){return!1}async outputs(t,r){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let i="ovh"in t?t.ovh:void 0;i&&i.expiresAt!==null&&i.expiresAt<=Date.now()&&M(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=WE(t).authorization==="consumer_key"?{...this.values(t,r),...this.credentials(t,r)}:this.values(t,r);return Object.fromEntries(Object.entries(WE(t).outputs).map(([o,s])=>[o,La(Wn(n,s))]))}};import{readFile as SUe}from"node:fs/promises";var wUe=f.object({accessToken:f.string().min(1).max(16384).regex(/^\S+$/),expiresAt:f.number().int().positive()}).strict();async function bUe(e,t){if(e==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,o=n?await SUe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!o||o.length>16384)&&M(409,"authentication_required","Provide the current OIDC token to this executor."),o.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([t,AbortSignal.timeout(3e3)])});r.ok||M(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let i=(await r.text()).trim();return(!i||i.length>16384)&&M(502,"invalid_response","The instance did not return a valid identity token."),i}function Ere(e){if(e.method.kind!=="token"||e.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return e.method.config}var ZE=class{constructor(t,r=bUe){this.transport=t;this.identityToken=r}transport;identityToken;facts=El;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(t,r){let i=qs(Ere(t).fields,t.fields),n=i.authentication;["api_key","oidc","instance"].includes(n)||M(400,"invalid_field","Choose a Vultr authentication source.");let o=n==="api_key"?i.token:i.credential||await this.identityToken(n,r);(!o||o.length>16384||/\s/.test(o))&&M(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(i.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&M(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+o},signal:r,body:JSON.stringify({role_id:i.roleId,session_name:i.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:i.userId}:{},...n==="oidc"?{oidc_issuer_id:i.issuerId}:{}})});a.status>=400&&M(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=Cl(a);(c.role_id!==void 0&&c.role_id!==i.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==i.userId)&&M(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=wUe.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&M(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(t,r,i){let n=Ere(t);i.throwIfAborted();let o=await te(t),s=this.sessions.get(o);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(o);a||(a=this.obtain(t,i),this.pending.set(o,a));try{s=await a,this.sessions.set(o,s)}finally{this.pending.get(o)===a&&this.pending.delete(o)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,VE(s,c)]))}};function Are(e,t){let r={oauth:new HE(e),token:new Kh,aws:new NE(t),approval:new Kh,ovh:new JE},i=new ZE(e);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?i:r[n.kind]}function Ci(e){return new TextDecoder("utf-8",{fatal:!0}).decode(e)}async function P4(e,t){let r={},i={},n=[],o=new Set;for(let s of e){if(o.has(s.name)||!xq(s.name))throw new Error("Use distinct, unreserved environment variable names.");o.add(s.name);let a=await t(s.source);if(s.format==="json"&&(a=ft(La(Wn(JSON.parse(Ci(a)),s.pointer??"")))),s.format==="file")i[s.name]=Buffer.from(a).toString("base64");else{let c=Ci(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:i,sensitive:n}}var sp=class{constructor(t,r,i,n,o,s=new OE){this.binding=t;this.keys=r;this.broker=i;this.journal=n;this.providers=Are(o,s)}binding;keys;broker;journal;active=new Set;providers;provider(t){return this.providers(t)}metadata(t){return BV(t,this.provider(t.method).facts(t))}source(t,r,i){let n=i.find(o=>o.policy.id===t&&o.policy.contentType===r);return n||M(409,"input_required","Include the connection and its application in this execution."),n}async material(t,r,i){let n=typeof i=="function"?a=>i(Pl.parse(JSON.parse(Ci(a)))):i,o=Pl.safeParse(JSON.parse(Ci(await Ec(t,r,this.keys,{destination:n}))));o.success||M(409,"reconnect_required","Reconnect this service with the current connection format.");let s=o.data;return(await this.metadata(s)).authorizationDigest!==t.metadata.authorizationDigest&&M(409,"connection_changed","Approve the current service account and permissions before using this connection."),s.state==="reconnect"&&r.operation!==Q.revoke&&M(409,"reconnect_required","Reconnect this service before using it."),s}async app(t,r,i,n){let o=this.source(t,ge.clientCredential,n),s=aw.parse(JSON.parse(Ci(await Ec(o,i,this.keys))));return s.methodId!==r&&M(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(t,r,i){if(Ls(t.method).application==="none")return null;if(!xl(t.method))return"implicitApp"in t&&t.implicitApp?t.implicitApp:aw.parse({format:1,methodId:t.methodId,generation:t.generation,clientId:"",fields:{}});let n=r.operation===Q.revoke?Q.revoke:Q.refresh,o=await this.app(t.appId,t.methodId,{...r,operation:n},i);return o.generation!==t.appGeneration&&M(409,"app_changed","Reconnect this service with the current application."),Ls(t.method).requiresApp&&t.method.kind!=="aws"&&Object.entries($l(t.method.config.fields,t.fields??{})).some(([s,a])=>o.fields[s]!==a)&&M(409,"app_changed","Reconnect this service with the current application settings."),o}async validate(t,r,i){let n=zO.parse(t);r.operation!==Q[n.action]&&M(400,"wrong_operation","Use the approved connection operation.");let o=await this.material(this.source(n.id,ge.tokenSet,i),r);(n.action==="refresh"||Ls(o.method).revocable)&&await this.connectionApp(o,r,i)}async execute(t,r,i,n){let o=zO.parse(t);this.active.has(o.id)&&M(409,"connection_busy","Another operation is updating this connection."),this.active.add(o.id);try{n.throwIfAborted();let s=this.source(o.id,ge.tokenSet,i),a=await this.material(s,r);if(o.action==="refresh"){let l=await this.refresh(s,a,r,i,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(l)}}let c=this.provider(a.method),u=Ls(a.method).revocable&&!!c.revoke;return u&&await c.revoke(a,await this.connectionApp(a,r,i),n),{kind:"disconnected",id:s.policy.id,revoked:u}}finally{this.active.delete(o.id)}}async outputs(t,r,i,n,o){let s=await this.material(t,r,o);return this.provider(s.method).renew&&await this.broker.state(t.policy.id)&&M(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(t,s,r,i,n,o),this.provider(s.method).outputs(s,await this.connectionApp(s,r,i),n)}async httpDestination(t,r,i){let n=await this.material(t,r,o=>VO(o,i,r.origin));return VO(n,i,r.origin)}async http(t,r,i,n,o){let s=await this.httpDestination(t,r,o),a=await this.material(t,r,s),c=await this.outputs(t,r,i,n,s);return n3(s,o.headers,a.method.http,c)}async refreshed(t,r){let i=await this.metadata(r);return i.authorizationDigest!==t.previous.metadata.authorizationDigest&&M(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),t.material=r,t.content=await Gq(t.previous,ft(k(r)),this.binding,this.keys,i),t.phase="settled",await this.journal.write("refresh_"+t.operation.id,t),await this.broker.commit(t.operation.id,t.operation.fence,t.content),t.delivered=!0,await this.journal.write("refresh_"+t.operation.id,t),r}async refresh(t,r,i,n,o,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||M(409,"reconnect_required","Reconnect this service to renew access.");try{await Os(t,{...i,operation:Q.refresh},{destination:s})}catch{M(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,i,n),u=_Ue(),l=await this.broker.prepare(u,t.policy.id,t.materialRevision),d={operation:l,previous:t,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{o.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),o.throwIfAborted();let m=await a.renew({material:r,app:c,signal:o,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,m)}catch(m){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),m instanceof Me&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(m.code))throw m;M(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let t=[];for(let r of await this.journal.pending("refresh_"))try{let i=await this.journal.read(r);if(i.delivered)continue;if(i.content){await this.broker.commit(i.operation.id,i.operation.fence,i.content),i.delivered=!0,await this.journal.write(r,i);continue}let n=await this.broker.state(i.operation.resource_id);if(!n||n.id!==i.operation.id||n.state==="prepared")n?.id===i.operation.id&&n.state==="prepared"&&await this.broker.abort(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i);else if(i.checkpoint&&this.provider(i.material.method).recover){let o=await this.provider(i.material.method).recover(i.material,i.app,i.checkpoint);await this.refreshed(i,o)}else await this.broker.uncertain(i.operation.id,i.operation.fence),i.delivered=!0,await this.journal.write(r,i)}catch{t.push(r.slice(8))}return t}};import{lookup as xUe}from"node:dns/promises";import{request as EUe}from"node:https";import{brotliDecompressSync as AUe,gunzipSync as RUe,inflateSync as IUe}from"node:zlib";var XE=class{constructor(t){this.origin=t}origin;async send(t){let r=Pn(t.url,this.origin),i=r.hostname.replace(/^\[|\]$/g,""),n=t.maxBytes??1048576;t.body&&Buffer.byteLength(t.body)>n&&M(413,"body_limit","The request body is too large.");let o={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(t.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))&&M(400,"invalid_header","Choose a valid request header."),o[c]=a}try{let s=await xUe(i,{all:!0,verbatim:!0});(!s.length||s.some(u=>!uw(u.address)))&&M(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]]);return await new Promise((u,l)=>{let d={method:t.method??"GET",headers:o,signal:c,agent:!1,lookup:(p,g,v)=>{g.all?v(null,[a]):v(null,a.address,a.family)}},m=EUe(r,d,p=>{let g=[],v=0;p.on("data",S=>{v+=S.length,v>n?p.destroy(new Me(413,"body_limit","The response body is too large.")):g.push(S)}),p.on("error",l),p.on("end",()=>{try{let S=Buffer.concat(g),b=p.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?RUe:b==="deflate"?IUe:b==="br"?AUe:null;if(!x)throw new Me(502,"invalid_response","The service returned an unsupported response.");S=x(S,{maxOutputLength:n})}let _={};for(let[x,T]of Object.entries(p.headers))T!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(_[x]=Array.isArray(T)?T.join(", "):T);u({status:p.statusCode??502,headers:_,body:new Uint8Array(S)})}catch(S){l(S)}})});m.on("error",l),m.end(t.body)})}catch(s){if(s instanceof Me)throw s;t.signal?.aborted&&M(409,"cancelled","The operation was cancelled."),M(502,"service_unavailable","The service could not be reached. Try again.")}}};function Rre(e){let{keys:t,binding:r,origin:i}=e.identity;if(!t||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=T4($Ue(gO()),"custody",r.id),o=new Tc(T4(n,"client"),i,r,t),s=new lw(e,i,r,t,new pw(o)),a=new fw(e),c=new XE(i),u=new sp(r,t,a.connections(),new Tc(T4(n,"connections"),i,r,t),c);return{custody:s,journal:o,directory:n,keys:t,binding:r,broker:a,transport:c,connections:u}}function PUe(e,t){let r={};if(Object.keys(t).some(i=>!e.parameters.some(n=>n.name===i)))throw new Error("Use the parameters this function declares.");for(let i of e.parameters){let n=Object.hasOwn(t,i.name)?t[i.name]:i.default;if(n===void 0){if(i.required)throw new Error("Complete the required function parameters.");continue}if(i.type!=="json"&&typeof n!==i.type||i.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(i.required&&i.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[i.name]=n}return r}function YE(e,t){let r=PUe(e,t);if(e.program.kind==="command"){let{kind:c,...u}=e.program;return{kind:c,...vc.parse({...u,stdin:JSON.stringify(r)})}}if(e.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");let i=e.program.request,n=c=>typeof c=="string"?c:JSON.stringify(c),o=(c,u=!1)=>{if(u&&typeof c=="string"){let l=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(c)?.[1];if(l){if(!e.parameters.some(d=>d.name===l))throw new Error("Declare every function parameter.");return Object.hasOwn(r,l)?r[l]:null}}return typeof c=="string"?c.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(l,d)=>{if(!e.parameters.some(m=>m.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?n(r[d]):""}):Array.isArray(c)?c.map(l=>o(l,u)):c&&typeof c=="object"?Object.fromEntries(Object.entries(c).map(([l,d])=>[l,o(d,u)])):c},s=i.url===void 0?void 0:new sw(i.url).expand(Object.fromEntries(Object.entries(r).map(([c,u])=>[c,n(u)]))),a=yc.parse({...o(i),...s===void 0?{}:{url:s},connectionId:i.connectionId,bindings:i.bindings,...i.json===void 0?{}:{json:o(i.json,!0)}});if(i.url!==void 0){let c=new URL(i.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,responseFormat:e.program.responseFormat}}var NPt=f.object({operation:Ic,save:f.record(f.string(),be)}).strict();function TUe(e){return e.kind==="http"?{kind:e.kind,request:e.request}:e}async function Ire(e,t){let r=e.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=Dq.parse(r.invocation.input);if(t.kind!=="revoke"||k(t.input)!==k({action:"revoke",id:n.connectionId})||n.ownerId!==e.ownerId||n.environmentId!==e.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 i=Oq.parse(r.invocation.input);if(i.ownerId!==e.ownerId||i.environmentId!==e.environmentId||i.operation.kind!==t.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in i.operation){if(await te(TUe(t))!==i.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(t.kind==="http"&&i.operation.kind==="http"){if(k(t.request)!==k(i.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(k(t)!==k(Ic.parse(i.operation)))throw new Error("Run the reviewed command.");if(t.kind==="http"&&k(Object.fromEntries(Object.entries(t.save).map(([n,o])=>[n,o.name])))!==k(i.save))throw new Error("Use the reviewed output destinations.")}function CUe(e,t){return e.policy.contentType===ge.value?t.output===void 0:e.policy.contentType===ge.tokenSet&&t.output!==void 0}var Po=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}};function C4(e){return!(e instanceof Me)||["service_unavailable","connection_uncertain","lease_lost"].includes(e.code)}var QE=class{constructor(t,r,i,n,o,s,a,c=s){this.environment=t;this.keys=r;this.broker=i;this.journal=n;this.transport=o;this.commands=s;this.extension=a;this.functionCommands=c}environment;keys;broker;journal;transport;commands;extension;functionCommands;get binding(){return this.environment.manifest.executor}async reconcile(){let t=[];for(let r of await this.journal.pending("run_"))try{let i=await this.journal.read(r);if(!i||i.delivered)continue;if(!i.receipt&&i.phase==="dispatched"){let n=i.operation?.kind==="connect"?await this.extension?.recover?.(i.operation.input,i.request.intent):null;i.receipt=n?await _l(i.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await _l(i.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),i.phase="settled",await this.journal.write(r,i)}i.receipt&&(await this.broker.finish(i.lease,i.receipt),i.delivered=!0,await this.journal.write(r,i))}catch{t.push(r.slice(4))}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:i}=r.request,n="run_"+i.id,o=await te(r.request),s=await this.journal.read(n);if(s&&s.digest!==o)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 m=await _l(i,"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:m,delivered:!1}),await this.broker.finish(r.lease,m),!0}s={digest:o,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([t,a.signal]),u=setInterval(()=>{this.broker.renew(i.id,r.lease).then(m=>{m.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let m=await Vq(r.request,this.binding,this.keys);await bl(this.environment,m.intent);let p=Ic.parse(m.operation);if(Q[p.kind]!==i.operation)throw new Error("Use the operation authorized by this intent.");await Ire(i,p),await this.validateOperation(p,i,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(i.id,r.lease),c.throwIfAborted();let g=await this.executeOperation(p,i,r.sources,c);d=await _l(i,"succeeded",{ok:!0,result:g,error:null},this.keys)}catch(m){if(m instanceof Po)throw m;m instanceof Sl&&(m=new Me(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||C4(m));d=await _l(i,p?"uncertain":"failed",{ok:!1,result:null,error:m instanceof Me?{code:m.code,message:m.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(t){let r=t.kind==="function"?YE(t.definition,t.arguments):t;return r.kind==="http"?r.request:null}async validateOperation(t,r,i){if(new Set(i.map(u=>u.policy.id)).size!==i.length||i.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let u of i){await sn(u);let l=r.sources.find(p=>p.id===u.policy.id);if(!l||!await aO(u,l))throw new Error("An execution input changed.");let d="checkpoint_"+u.policy.format+"_"+u.policy.id,m=await this.journal.read(d);if(m&&(u.policy.revision<m.policy||u.materialRevision<m.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(d,{policy:u.policy.revision,material:u.materialRevision})}if(t.kind==="function"&&(t.functionId!==r.functionId||await te(t.definition)!==r.functionDigest||!this.environment.manifest.capabilities.includes(Q[t.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(t.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(t),o=n?.url;if(n){if(n.connectionId){let u=i.find(l=>l.policy.id===n.connectionId);if(this.environment.manifest.httpVersion!==zi||!this.extension?.httpDestination||!u||u.policy.contentType!==ge.tokenSet)throw new Error("Choose an HTTP connection and a current execution environment.");o=await this.extension.httpDestination(u,r,n)}if(Pn(o,r.origin),[n.body,n.json,n.form].filter(u=>u!==void 0).length>1)throw new Error("Choose one request body format.");for(let u of n.bindings){let l=Vh(u.pointer);if(!l.length||!["headers","body","json","form"].includes(l[0])||l[0]==="body"&&l.length!==1||["headers","form"].includes(l[0])&&l.length!==2)throw new Error("Bind credentials to request headers or the body.");A4(structuredClone(n),u.pointer,"validation")}}let s=t.kind==="function"?t.outputs:t.kind==="http"?t.save:{};for(let[u,l]of Object.entries(s)){if(Vh(u),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let d=await Us(l.approval);if(k(d.policy.authorities.find(m=>m.id===d.authorityId))!==k(r.actor)||d.policy.origin!==r.origin||d.policy.contentType!==ge.value||d.policy.ownerId!==r.ownerId||!d.policy.producers.some(m=>m.runId===r.id&&k(m.executor)===k(this.binding)&&Date.parse(m.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let a=t.kind==="function"?YE(t.definition,t.arguments):t,c=a.kind==="command"?a.inputs.map(u=>u.source):n?Lf(n):[];for(let u of c){let l=i.find(m=>m.policy.id===u.id),d=n?.connectionId===u.id&&u.output===void 0;if(!l||!(d?l.policy.contentType===ge.tokenSet:CUe(l,u)))throw new Error("Use the input named in the signed request.");await Os(l,r,{destination:o}),await Ec(l,r,this.keys,{destination:o})}if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(t.input,r,i)}}async executeOperation(t,r,i,n){if(t.kind==="connect"||t.kind==="refresh"||t.kind==="revoke")return this.extension.execute(t.input,r,i,n);let o=this.request(t),s=t.kind==="function"?YE(t.definition,t.arguments):t,a=o?.connectionId?await this.extension.httpDestination(i.find(v=>v.policy.id===o.connectionId),r,o):o?.url,c=[],u=new Map,l=async v=>{let S=i.find(_=>_.policy.id===v.id);if(S.policy.contentType===ge.value)return Ec(S,r,this.keys,{...o?{destination:a}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");u.has(v.id)||u.set(v.id,this.extension.outputs(S,r,i,n,a));let b=await u.get(v.id);if(!v.output||!Object.hasOwn(b,v.output))throw new Error("Choose an available connection output.");return ft(b[v.output])};if(s.kind==="command"){let v=await P4(s.inputs,l),b=await(t.kind==="function"?this.functionCommands:this.commands).execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:v.environment,files:v.files,...t.kind==="function"?{workspace:"temporary"}:{}},n);if(t.kind==="function"){if(b.timedOut)throw new Me(408,"function_timeout","The function exceeded its time limit.");if(b.truncated)throw new Me(413,"function_output_limit","The function output exceeded its size limit.");if(b.exitCode!==0)throw new Me(422,"function_failed",op(b.stderr,v.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(t,r,b.stdout)}return{...b,stdout:op(b.stdout,v.sensitive),stderr:op(b.stderr,v.sensitive)}}let d=structuredClone(o);for(let v of d.bindings){let S="";for(let b of v.parts)if(typeof b=="string")S+=b;else{let _=Ci(await l(b));c.push(_,Buffer.from(_).toString("base64"),Buffer.from(_).toString("base64url")),S+=_}A4(d,v.pointer,S)}if(d.connectionId){if(!this.extension?.http)throw new Error("This executor cannot use HTTP connections.");let v=await this.extension.http(i.find(S=>S.policy.id===d.connectionId),r,i,n,d);d.url=v.url,d.headers=v.headers,c.push(...v.sensitive)}let m=d.body;d.json!==void 0&&(m=JSON.stringify(d.json),d.headers["content-type"]="application/json"),d.form!==void 0&&(m=new URLSearchParams(d.form).toString(),d.headers["content-type"]="application/x-www-form-urlencoded");let p=await this.transport.send({url:d.url,method:d.method,headers:d.headers,...m===void 0?{}:{body:m},signal:n});if(t.kind==="function"){if(p.status<200||p.status>=300)throw new Me(502,"service_response","The service returned HTTP "+p.status+".");let v=t.definition.program.kind==="http"?t.definition.program.responseFormat:"json",S=Ci(p.body);if(v==="json")try{S=p.body.length===0&&([204,205].includes(p.status)||d.method==="HEAD")?null:Nr.parse(JSON.parse(S))}catch{throw new Me(422,"invalid_function_result","The HTTP response body must contain valid JSON.")}return this.functionResult(t,r,JSON.stringify({status:p.status,headers:p.headers,body:S}))}let g=t.kind==="http"?t.save:{};if(Object.keys(g).length){if(p.status>=400)throw new Me(502,"service_response","The service returned an unsuccessful response.");let v={};for(let[S,b]of Object.entries(g)){let _=p.body;if(S!==""){let T=Wn(JSON.parse(Ci(_)),S);if(T===void 0)throw new Me(400,"invalid_pointer","The response value was not found.");_=ft(typeof T=="string"?T:JSON.stringify(T))}let x=await Rf(_,b.approval,r.id,this.binding,this.keys,{bytes:_.length});v[b.name]=(await this.broker.capture(b.name,x)).id}return{status:p.status,saved:v}}return{status:p.status,headers:Object.fromEntries(Object.entries(p.headers).map(([v,S])=>[v,op(S,c)])),body:op(Ci(p.body),c)}}async functionResult(t,r,i){let n;try{n=t.definition.result==="text"?i:Nr.parse(JSON.parse(i))}catch{throw new Me(422,"invalid_function_result","The function must return valid JSON.")}let o={};for(let[s,a]of Object.entries(t.outputs)){let c=s===""?n:Wn(n,s);if(c===void 0)throw new Me(400,"invalid_pointer","The function result value was not found.");let u=ft(typeof c=="string"?c:JSON.stringify(c)),l=await Rf(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});o[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(o).length?{saved:o}:n}};import{spawn as $re}from"node:child_process";import{mkdir as Pre,mkdtemp as kUe,rm as DUe,writeFile as Tre}from"node:fs/promises";import{tmpdir as OUe}from"node:os";import{join as Bh}from"node:path";import{StringDecoder as Cre}from"node:string_decoder";function kre(e={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...e}}var Hh=class{constructor(t){this.options=t;if(t.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(t.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(t,r){r.throwIfAborted();let i=await kUe(Bh(OUe(),"foundation-job-")),n=Bh(i,"files"),o="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=t.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await Pre(n,{mode:448});let l={...t.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[m,p]of Object.entries(t.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m))throw new Error("Use valid file variable names.");await Tre(Bh(n,m),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),l[m]=s?"/run/foundation/"+m:Bh(n,m)}let d=t.command;if(s){if(Object.entries(l).some(([g,v])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(g)||v.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let m=Object.entries(l).filter(([,g])=>/[\r\n]/.test(g)),p=Bh(i,"environment");await Tre(p,Object.entries(l).filter(([,g])=>!/[\r\n]/.test(g)).map(([g,v])=>g+"="+v).join(`
123
123
  `),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await Pre(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",o,"--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,...m.flatMap(([g,v])=>["--env",g+"="+v]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:t.workingDirectory?["--workdir",t.workingDirectory]:[],"--entrypoint="+t.command[0],"-i",this.options.image,...t.command.slice(1)]}return await new Promise(m=>{let p=$re(d[0],d.slice(1),{env:kre(s?{}:a?{...l,HOME:i,TMPDIR:i}:l),cwd:s?this.options.cwd:a?i:t.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),g={stdout:new Cre("utf8"),stderr:new Cre("utf8")},v=0,S=!1,b=(U,C)=>{let G=Math.max(0,1e6-v);C.length>G&&(c.truncated=!0);let B=C.subarray(0,G);v+=B.length,c[U]+=g[U].write(B)};p.stdout.on("data",U=>b("stdout",U)),p.stderr.on("data",U=>b("stderr",U)),p.stdin.on("error",()=>{}),p.stdin.end(t.stdin??"");let _=()=>{u=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,_()},t.timeoutSeconds*1e3);x.unref();let T=()=>{S||(S=!0,clearTimeout(x),r.removeEventListener("abort",_),c.stdout+=g.stdout.end(),c.stderr+=g.stderr.end(),m())};r.addEventListener("abort",_,{once:!0}),r.aborted&&_(),p.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",T()}),p.once("close",(U,C)=>{c.exitCode=U,c.signal=C,T()})}),c}finally{s&&u&&await new Promise(l=>{let d=$re("docker",["rm","-f",o],{env:kre(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await DUe(i,{recursive:!0,force:!0})}}};import{spawn as NUe}from"node:child_process";import{constants as k4}from"node:fs";import{open as Dre,rm as UUe}from"node:fs/promises";async function Ore(e){if(process.platform!=="linux"){let r=await Dre(e,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+e+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await UUe(e,{force:!0})}}let t=await Dre(e,k4.O_CREAT|k4.O_WRONLY|k4.O_NOFOLLOW,384);try{let r=NUe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",t.fd]});await new Promise((i,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",o=>o===0?i():n(new Error(o===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await t.close(),r}return()=>t.close()}var HI=lt(l4(),1),WI=lt(mhe(),1);function hhe(e){return cO.safeParse(e).success?e:null}async function ghe(e=3e3){let t=new HI.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,i=AbortSignal.timeout(e);try{let n=await t.send(new HI.GetCallerIdentityCommand({}),{abortSignal:i});if(!n.Arn)return null;let o=hhe(n.Arn);if(o)return o;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 WI.IAMClient({region:t.config.region,credentials:t.config.credentials});let c=(await r.send(new WI.GetRoleCommand({RoleName:s[3]}),{abortSignal:i})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=hhe(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{t.destroy(),r?.destroy()}}var Rj=f.string().refine(e=>!e.includes("\0"),"Use text without null bytes."),Ij=Rj.max(4096).startsWith("/"),yhe=f.object({command:f.array(Rj.max(8192)).min(1).max(100).refine(e=>!!e[0],"Specify a program."),workingDirectory:Ij.optional(),environment:f.record(f.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),Rj.max(65536)).refine(e=>Object.keys(e).length<=128&&JSON.stringify(e).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:f.string().max(1e6).default(""),timeoutSeconds:f.number().int().min(1).max(3600).default(60)}).strict(),dTt=yhe.extend({id:P.optional()}),vhe=f.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),She=f.object({exitCode:f.number().int().nullable(),signal:f.string().max(32).nullable(),stdout:f.string().max(1e6),stderr:f.string().max(1e6),timedOut:f.boolean(),truncated:f.boolean()}).strict(),pTt=f.object({state:vhe.exclude(["queued","running"]),result:She.nullable(),error:f.string().max(100).nullable()}).strict(),JI=yhe.extend({id:P,environmentId:P,ownerId:P,actorId:P,workingDirectory:Ij,state:vhe,result:She.nullable(),error:f.string().nullable(),createdAt:ne,startedAt:ne.nullable(),finishedAt:ne.nullable()}).strict(),fTt=JI.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),mTt=f.object({workingDirectory:Ij}).strict(),whe=f.object({lease:P,process:JI}).strict().nullable();var ZI=class{constructor(t){this.api=t}api;claim(t){return this.api.json("/api/environments/"+t+"/processes/claim",{method:"POST",body:{}},whe)}dispatch(t,r){return this.api.json("/api/processes/"+t+"/dispatch",{method:"POST",body:{lease:r}})}renew(t,r){return this.api.json("/api/processes/"+t+"/renew",{method:"POST",body:{lease:r}},f.object({active:f.boolean()}))}finish(t,r,i){return this.api.json("/api/processes/"+t+"/finish",{method:"POST",body:{lease:r,...i}},JI)}},XI=class{constructor(t,r,i,n,o=15e3){this.environmentId=t;this.broker=r;this.journal=i;this.commands=n;this.renewalMilliseconds=o}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(t){await this.broker.finish(t.id,t.lease,t.completion),await this.journal.write("process_"+t.id,{...t,delivered:!0})}async reconcile(){let t=[];for(let r of await this.journal.pending("process_")){let i=await this.journal.read(r);if(!(!i||i.delivered||i.phase==="prepared")){i.completion??={state:"uncertain",result:null,error:"execution_interrupted"},i.phase="settled",await this.journal.write(r,i);try{await this.deliver(i)}catch{t.push(i.id)}}}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:i,process:n}=r,o=await this.journal.read("process_"+n.id);if(o&&o.phase!=="prepared"){let l=o.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,i,l),await this.journal.write("process_"+n.id,{...o,lease:i,completion:l,phase:"settled",delivered:!0}),!0}let s={id:n.id,lease:i,delivered:!1,completion:null,phase:"prepared"};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();t.addEventListener("abort",c,{once:!0}),t.aborted&&c();let u;try{s.phase="dispatched",await this.journal.write("process_"+n.id,s),await this.broker.dispatch(n.id,i),u=setInterval(()=>{this.broker.renew(n.id,i).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),t.removeEventListener("abort",c)}s.phase="settled",await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Po}return!0}};var $j=f.object({format:f.literal(2),functionId:P,ownerId:P,revision:f.number().int().positive(),definition:ks,author:vt,createdAt:ne,signature:_t}).strict();async function bhe(e){let t=$j.parse(e),{signature:r,...i}=t;return await Mi(i.author),await nr(i,r,i.author.signing,"function-publication"),t}var cWe=f.object({functionId:P,publication:$j}).strict(),Pj=f.object({format:f.literal(1),functionId:P,ownerId:P,definitionDigest:yt,revision:f.number().int().positive(),environmentId:P.nullable(),inputAccess:bf,author:vt,executor:vt.nullable(),createdAt:ne,signature:_t}).strict().refine(e=>e.environmentId===null==(e.executor===null),{message:"Approve the executor of the selected environment."});async function _he(e,t){let r=Pj.parse(e),{signature:i,...n}=r;if(await Mi(n.author),await nr(n,i,n.author.signing,"function-settings"),t&&k(n.executor)!==k(t))throw new Error("This function is approved for another executor.");return r}var ATt=f.object({approval:Pj,contents:f.record(P,f.object({version:f.number().int().positive(),content:ir}).strict())}).strict(),uWe=f.object({name:be,definition:ks,authorization:cWe}).strict(),RTt=uWe.extend({version:f.number().int().positive()}),lWe=f.object({id:P.optional(),ownerId:P.optional(),arguments:Mt.default({}),outputs:f.record(f.string().max(500),BS).default({})}).strict(),xhe=f.object({code:f.string().max(100),message:f.string().max(1e3)}).strict(),Ehe=f.object({id:P,functionId:P,functionVersion:f.number().int().positive(),ownerId:P,actorId:P,state:VS,result:Nr.nullable(),error:xhe.nullable(),createdAt:ne,startedAt:ne.nullable(),finishedAt:ne.nullable()}).strict(),dWe=f.object({id:P,functionId:P,functionVersion:f.number().int().positive(),ownerId:P,actorId:P,actor:vt.nullable(),arguments:Mt,outputs:lWe.shape.outputs,definitionDigest:yt,settingsDigest:yt,environmentId:P,createdAt:ne,expiresAt:ne}).strict(),Ahe=f.object({id:P,requestDigest:f.string().regex(/^[A-Za-z0-9_-]{43}$/),state:VS.exclude(["queued","running"]),result:Nr.nullable(),error:xhe.nullable(),finishedAt:ne,signature:_t}).strict(),Rhe=f.object({lease:P,request:dWe,publication:$j,settings:Pj,sources:f.array(ir).max(100)}).strict().nullable();var YI=class{api;constructor(t){this.api={async json(r,i={},n){try{return await t.json(r,i,n)}catch(o){throw o instanceof Error&&"status"in o&&typeof o.status=="number"&&"code"in o&&typeof o.code=="string"?new Me(o.status,o.code,o.message):o}}}}claim(t){return this.api.json("/api/environments/"+t+"/invocations/claim",{method:"POST",body:{}},Rhe)}dispatch(t,r){return this.api.json("/api/runtime/functions/"+t+"/dispatch",{method:"POST",body:{lease:r}})}renew(t,r){return this.api.json("/api/runtime/functions/"+t+"/renew",{method:"POST",body:{lease:r}},f.object({active:f.boolean(),reason:f.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(t,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:t,completion:r}},Ehe)}},QI=class{constructor(t,r,i,n=15e3){this.executor=t;this.broker=r;this.journal=i;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(t,r,i,n){let o={id:t.id,requestDigest:t.digest,state:r,result:i,error:n,finishedAt:new Date().toISOString()};t.completion=Ahe.parse({...o,signature:await Tt(o,this.executor.keys.signing,"function-result")}),t.phase="settled",await this.journal.write("invocation_"+t.id,t)}async deliver(t){await this.broker.finish(t.lease,t.completion),t.delivered=!0,await this.journal.write("invocation_"+t.id,t)}async reconcile(){let t=[];for(let r of await this.journal.pending("invocation_"))try{let i=await this.journal.read(r);if(!i||i.delivered||i.phase==="prepared")continue;i.completion||await this.complete(i,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(i)}catch{t.push(r.slice(11))}return t}async tick(t=new AbortController().signal){t.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:i,publication:n,settings:o,sources:s,lease:a}=r,c=await te(i),u="invocation_"+i.id,l=await this.journal.read(u);if(l&&l.digest!==c)throw new Error("An invocation ID was reused for different input.");if(l?.completion)return l.lease=a,await this.deliver(l),!0;if(l?.phase==="dispatched")return l.lease=a,await this.complete(l,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(l),!0;l={id:i.id,digest:c,lease:a,phase:"prepared",delivered:!1,completion:null},await this.journal.write(u,l);let d=new AbortController,m=AbortSignal.any([t,d.signal]),p=!1,g=!1,v=setInterval(()=>{g||(g=!0,this.broker.renew(i.id,a).then(S=>{S.active||(p||=S.reason==="cancelled",d.abort())},()=>d.abort()).finally(()=>{g=!1}))},this.renewalMilliseconds);v.unref();try{if(await bhe(n),await _he(o,this.executor.binding),n.functionId!==i.functionId||o.functionId!==i.functionId||o.ownerId!==n.ownerId||o.definitionDigest!==i.definitionDigest||await te(o)!==i.settingsDigest||o.environmentId!==this.executor.environment.manifest.id||i.environmentId!==o.environmentId||await te(n.definition)!==i.definitionDigest||Date.parse(i.expiresAt)<=Date.now()||!Go(o.inputAccess)||vl(o.inputAccess)<Date.parse(i.expiresAt))throw new Error("Run the current approved function in its configured environment.");let S="function_"+n.functionId,b=await this.journal.read(S),_=await te(n);if(b&&(n.revision<b.revision||n.revision===b.revision&&b.digest!==_))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(S,{revision:n.revision,digest:_});let x="checkpoint_function_settings_"+n.functionId,T=await this.journal.read(x);if(T&&(o.revision<T.revision||o.revision===T.revision&&i.settingsDigest!==T.digest))throw new Error("The execution settings are older than this executor has already observed.");await this.journal.write(x,{revision:o.revision,digest:i.settingsDigest});let U=Xq.parse({kind:"function",functionId:i.functionId,definition:n.definition,arguments:i.arguments,outputs:i.outputs}),C={format:2,id:i.id,origin:this.executor.environment.manifest.origin,ownerId:i.ownerId,actor:i.actor??this.executor.binding,executor:this.executor.binding,environmentId:o.environmentId,environmentDigest:await te(this.executor.environment.manifest),operation:Q.function,operationDigest:await te(U),functionId:i.functionId,functionDigest:i.definitionDigest,sources:await Promise.all(s.map(async B=>({id:B.policy.id,policyDigest:await te(B.policy),materialRevision:B.materialRevision,...B.policy.contentType===ge.tokenSet&&typeof B.metadata.authorizationDigest=="string"?{authorizationDigest:B.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:i.createdAt,expiresAt:i.expiresAt};await bl(this.executor.environment,C),await this.executor.validateOperation(U,C,s),m.throwIfAborted(),await this.broker.dispatch(i.id,a),l.phase="dispatched",await this.journal.write(u,l),m.throwIfAborted();let G=await this.executor.executeOperation(U,C,s,m);if(new TextEncoder().encode(JSON.stringify(G)).byteLength>1e6)throw new Me(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(l,"succeeded",G,null)}catch(S){if(S instanceof Po)throw S;let b=l.phase==="dispatched",_=m.aborted&&p?"cancelled":b&&(m.aborted||C4(S))?"uncertain":"failed";await this.complete(l,_,null,_==="uncertain"?{code:"execution_uncertain",message:"The outcome could not be confirmed. Check the destination before invoking this function again."}:!m.aborted&&S instanceof Me?{code:S.code,message:S.message}:{code:_==="cancelled"?"invocation_cancelled":"invalid_function",message:_==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(v)}try{await this.deliver(l)}catch{throw new Po}return!0}};async function $he(e,t){let{directory:r,keys:i,binding:n,broker:o,transport:s}=Rre(e),a=P.parse(t.id??crypto.randomUUID()),c=Tj(r,"executors",a);await Ihe(c,{recursive:!0,mode:448});let u=Tj(c,"workspace");await Ihe(u,{recursive:!0,mode:448});let l=await Ore(Tj(c,"process.lock")),d=new AbortController,m=()=>d.abort();process.on("SIGINT",m),process.on("SIGTERM",m);try{let p=new Tc(c,e.identity.origin,n,i),g=await p.read("environment_"+a),v=await ghe(),S=g?{isolation:g.manifest.isolation,image:g.manifest.commandImage,functionImage:g.manifest.functionImage}:t,b={isolation:S.isolation,...S.image?{commandImage:S.image}:{},...S.functionImage?{functionImage:S.functionImage}:{}};if(g){if(await wl(g),g.manifest.ownerId!==t.ownerId||k(g.manifest.executor)!==k(n))throw new Error("Use the owner and identity originally registered for this executor.");if(g.manifest.functionVersion!==Ac||g.manifest.httpVersion!==zi||g.manifest.resultVersion!==1||(g.manifest.awsPrincipal??null)!==v||g.manifest.isolation!==b.isolation||g.manifest.commandImage!==b.commandImage||g.manifest.functionImage!==b.functionImage){let{awsPrincipal:de,commandImage:pe,functionImage:qe,...ee}=g.manifest;g=await lO({...ee,functionVersion:Ac,httpVersion:zi,resultVersion:1,...b,...v?{awsPrincipal:v}:{},revision:ee.revision+1},i),await p.write("environment_"+a,g)}}else g=await lO({format:3,id:a,origin:e.identity.origin,ownerId:t.ownerId,name:t.name,executor:n,operatorId:n.principalId,driver:"attached",capabilities:Object.values(Q),functionVersion:Ac,httpVersion:zi,resultVersion:1,...b,...v?{awsPrincipal:v}:{},revision:1},i),await p.write("environment_"+a,g);await e.json("/api/environments/"+a+"/registration",{method:"PUT",body:g}),process.stdout.write(JSON.stringify({environmentId:a,identityId:n.principalId,fingerprint:await US(n),isolation:g.manifest.isolation,...g.manifest.awsPrincipal?{awsPrincipal:g.manifest.awsPrincipal}:{},...g.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
124
124
  `);let _=new sp(n,i,o.connections(),p,s),x=g.manifest.isolation==="container"?"/workspace":process.cwd(),T=new Hh({isolation:g.manifest.isolation,image:g.manifest.commandImage,workspace:u}),U=g.manifest.functionImage?new Hh({isolation:"container",image:g.manifest.functionImage}):T,C=new QE(g,i,o,p,s,T,_,U),G=new QI(C,new YI(e),p);await e.json("/api/environments/"+a+"/processes/registration",{method:"PUT",body:{workingDirectory:x}});let B=new XI(a,new ZI(e),p,T);do{let de=[...await _.reconcile(),...await C.reconcile(),...await G.reconcile(),...await B.reconcile()];de.length&&process.stderr.write(JSON.stringify({event:"reconciliation_pending",ids:de})+`
125
125
  `);let pe=!1;try{pe=await C.tick(d.signal),pe=await G.tick(d.signal)||pe,pe=await B.tick(d.signal)||pe}catch(qe){if(!(qe instanceof Po)||t.once)throw qe}if(t.once)break;pe||await pWe(1e3,void 0,{signal:d.signal})}while(!d.signal.aborted)}catch(p){if(!d.signal.aborted)throw p}finally{process.off("SIGINT",m),process.off("SIGTERM",m),await l()}return 0}async function hWe(){let e=fWe({allowPositionals:!0,options:{version:{type:"boolean"},origin:{type:"string"},owner:{type:"string"},id:{type:"string"},name:{type:"string"},isolation:{type:"string"},image:{type:"string"},once:{type:"boolean"}}});if(e.values.version)return process.stdout.write(`Foundation executor: functions ${Ac}, HTTP ${zi}