@tomato414941/foundation 10.0.0 → 10.0.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/cli.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -125,9 +125,9 @@ ${c}`:c:"",l=Function,d=`return (input) => {
|
|
|
125
125
|
${c}
|
|
126
126
|
}`,p;try{p=new l(...s,d)(...a)}catch(f){throw new Be(`this schema (generated code failed to evaluate: ${f.message})`)}return e?.debug&&(p.code=u),p.definite=o.definite,p}function he(t,e){for(let[o,n]of t.constants)if(n===e)return o;let r=`c${t.constantCounter++}`;return t.constants.set(r,e),r}function zl(t,e){return t.definite=!1,he(t,e)}function pe(t){return`v${t.varCounter++}`}function tTe(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return jn;let o=r;return o.issues.length===0?o.value:jn}function _n(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return rr(t,e,r,o,n)}catch(u){if(!(u instanceof Be)||!u.islandable)throw u;if(t.content.length=i,e.constants.size>s){let l=Array.from(e.constants.keys()).slice(s);for(let d of l)e.constants.delete(d)}return e.constantCounter=a,e.varCounter=c,rTe(t,e,r,o)}}function rTe(t,e,r,o){e.definite=!1;let n=he(e,r),i=he(e,tTe),s=pe(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var nTe=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function oTe(t,e,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let s of n){let a=s._zod.def;if(a.when&&!nTe.has(a.check))throw new Be('check with a custom "when" condition');switch(a.check){case"greater_than":iTe(t,e,a,i);break;case"less_than":sTe(t,e,a,i);break;case"multiple_of":aTe(t,e,a,i);break;case"number_format":B9(t,a,i);break;case"min_length":{let c=Dl(a.minimum,"min_length"),u=Oz(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Dl(a.maximum,"max_length"),u=Oz(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Dl(a.length,"length_equals"),u=Oz(t,e,i,`${i}.length >= ${c} && ${i}.length <= ${a.length*2}`);t.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":t.write(`if (${i}.size < ${Dl(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${Dl(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${Dl(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=K9(t,e,a,i);break;case"custom":i=fTe(t,e,s,i);break;case"bigint_format":cTe(t,a,i);break;case"mime_type":uTe(t,e,a,i);break;case"property":dTe(t,e,a,i);break;case"properties":lTe(t,e,a,i);break;case"overwrite":{let c=pe(e);pTe(t,e,s,i,c),i=c;break}default:throw new Be(`check type ${a.check}`)}}return i}function Oz(t,e,r,o){let n=he(e,Pl),i=pe(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function Dl(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Be(`${e} bound of type ${typeof t}`);return`${t}`}function H9(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Be("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Be("comparison check with Invalid Date bound");return he(t,e)}throw new Be(`comparison check bound of type ${typeof e}`)}function iTe(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${H9(e,r.value)}) return INVALID;`)}function sTe(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${H9(e,r.value)}) return INVALID;`)}function aTe(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Be("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=he(e,tg);t.write(`if (${n}(${o}, ${Dl(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function B9(t,e,r){let o=e.format;switch(o){case"safeint":t.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":t.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":t.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":t.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":t.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Be(`number format ${o}`)}}function cTe(t,e,r){let o=e.format;if(o)switch(o){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Be(`bigint format ${o}`)}}function uTe(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=he(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function lTe(t,e,r,o){if(r.when)throw new Be('check with a custom "when" condition');t.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?he(e,i):Un(i),a=pe(e);t.write(`const ${a} = ${o}[${s}];`),_n(t,e,n[i],a,!1)}}function dTe(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;rr(t,e,r.schema,n)}function pTe(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Be("overwrite check without a transform function");if(Ml(i))throw new Ti("z.compile: async overwrite transforms are not supported");let s=he(e,i);t.write(`const ${n} = ${s}(${o});`)}function Dz(){throw new no}function Mz(t){this.issues.push(t)}function fTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Ml(n.fn))throw new Ti("z.compile: async .refine() predicates are not supported");let i=zl(e,n.fn),s=he(e,Dz),a=pe(e);return t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`),o}if(r._zod.check){if(Ml(r._zod.check))throw new Ti("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=zl(e,u=>{let l={value:u,issues:[],addIssue:Mz};return i(l)instanceof Promise&&Dz(),l.issues.length===0?l.value:jn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Be("custom check without a predicate or check function")}var mTe=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function K9(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=he(e,yg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=he(e,ZS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=he(e,tx),l=he(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=he(e,gg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=he(e,GS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=he(e,XS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=he(e,QS);return t.write(`if (!${u}(${o})) return INVALID;`),o}let s=r;if(i==="url"||i==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=he(e,PS),l=he(e,r),d=pe(e),p=pe(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${p} = ${u}(${d}, ${l});`),t.write(`if (typeof ${p} === "number") return INVALID;`),s.hostname!==void 0){let y=he(e,kS);t.write(`if (!${y}(${p}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let y=he(e,TS);t.write(`if (!${y}(${p}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let f=pe(e),m=s.normalize?`${p}.href`:`${he(e,hg)}(${d})`;return t.write(`const ${f} = ${m};`),f}let a=r.fn;if(a){if(Ml(a))throw new Be(`async string format ${i}`);let u=he(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(mTe.has(i)&&r.pattern){let u=he(e,r.pattern);return t.write(`${u}.lastIndex = 0;`),t.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new Be("regex format without a pattern");case"lowercase":t.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":t.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":t.write(`if (!${o}.includes(${Un(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${Un(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${Un(u)}) return INVALID;`);break}default:throw new Be(`string format ${c}`)}return o}function rr(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Be(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=hTe(t,e,r,o,a);break;case"number":c=gTe(t,r,o);break;case"boolean":c=yTe(t,o);break;case"bigint":c=vTe(t,r,o);break;case"symbol":c=wTe(t,o);break;case"undefined":c=_Te(t,o);break;case"null":c=bTe(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=STe(t,o);break;case"nan":c=xTe(t,o);break;case"date":c=ETe(t,o);break;case"object":c=$Te(t,e,r,o,a);break;case"optional":c=RTe(t,e,r,o,a);break;case"nullable":c=PTe(t,e,r,o,a);break;case"array":c=kTe(t,e,r,o,a);break;case"literal":c=TTe(t,e,r,o);break;case"enum":c=CTe(t,e,r,o);break;case"readonly":{let u=q9(t,e,r,o),l=pe(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":q9(t,e,r,o),c="true";break;case"default":case"prefault":c=OTe(t,e,r,o);break;case"nonoptional":c=DTe(t,e,r,o);break;case"tuple":c=NTe(t,e,r,o);break;case"union":c=zTe(t,e,r,o);break;case"intersection":c=LTe(t,e,r,o);break;case"record":c=jTe(t,e,r,o);break;case"map":c=qTe(t,e,r,o);break;case"set":c=VTe(t,e,r,o);break;case"file":c=GTe(t,o);break;case"template_literal":c=HTe(t,e,r,o);break;case"lazy":c=BTe(t,e,r,o);break;case"pipe":c=KTe(t,e,r,o);break;case"custom":c=ZTe(t,e,r,o);break;case"transform":c=XTe(t,e,r,o);break;case"catch":c=JTe(t,e,r,o);break;default:throw new Be(`schema type ${s}`)}return c===null?null:oTe(t,e,r,c)}function hTe(t,e,r,o,n=!0){t.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:K9(t,e,i,o,n)}function gTe(t,e,r){t.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=e._zod.def;return o.check==="number_format"&&o.format&&B9(t,{format:o.format},r),r}function yTe(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function vTe(t,e,r){t.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=e._zod.def;if(o.format)switch(o.format){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function wTe(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function _Te(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function bTe(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function STe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function xTe(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function ETe(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function $Te(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let s=i.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=S=>typeof S=="symbol"?he(e,S):Un(S),d=S=>typeof S=="symbol"?`[${l(S)}]`:Un(S),p=s;if(a.includes("__proto__"))throw new Be('object shape key "__proto__"');let f=new Map;for(let S of u){let x=p[S],I=l(S),T=pe(e);if(t.write(`const ${T} = ${o}[${I}];`),x._zod.optin!==void 0){let M=pe(e);t.write(`let ${M} = (() => {`),t.indented(J=>{let le=_n(J,e,x,T);J.write(`return ${le};`)}),t.write("})();"),x._zod.optout==="optional"?(t.write(`if (${M} === INVALID) {`),t.indented(J=>{J.write(`if (${I} in ${o}) return INVALID;`),J.write(`${M} = undefined;`)}),t.write("}")):t.write(`if (${M} === INVALID) return INVALID;`),f.set(S,M)}else{ATe(x)&&t.write(`if (!(${I} in ${o})) return INVALID;`);let M=_n(t,e,x,T,n);M!==null&&f.set(S,M)}}let m=i.catchall,y="none";if(m){let S=m._zod.def.type;if(S==="never"){let x=a.map(I=>`k !== ${Un(I)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(I=>{I.write(`if (${x}) return INVALID;`)}),t.write("}")}else(S==="unknown"||S==="any")&&!m._zod.def.checks?.length?y="passthrough":y="schema"}let w=pe(e),b=u.some(S=>F9(p[S])||Nz(p[S]));if(!n){if(y==="schema"){let S=a.length>0?he(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`);let I=pe(e);x.write(`const ${I} = ${o}[k];`),_n(x,e,m,I,!1)}),t.write("}")}return null}if(b){t.write(`const ${w} = {};`);for(let S of u){let x=l(S),I=f.get(S);Nz(p[S])?t.write(`if (${x} in ${o}) ${w}[${x}] = ${I};`):F9(p[S])?t.write(`if (${I} !== undefined || ${x} in ${o}) ${w}[${x}] = ${I};`):t.write(`${w}[${x}] = ${I};`)}}else{let S=u.map(x=>`${d(x)}: ${f.get(x)}`).join(", ");t.write(`const ${w} = { ${S} };`)}if(y!=="none"){let S=a.length>0?he(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{if(x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`),y==="passthrough")x.write(`${w}[k] = ${o}[k];`);else{let I=pe(e);x.write(`const ${I} = ${o}[k];`);let T=_n(x,e,m,I);x.write(`${w}[k] = ${T};`)}}),t.write("}")}return w}function RTe(t,e,r,o,n=!0){let i=r._zod.def;if(ITe(r))return rr(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=pe(e),c=pe(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=rr(l,e,i.innerType,o);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),t.write("} else {"),t.indented(u=>{let l=rr(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?pe(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=rr(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function ITe(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function ATe(t){return t._zod.optin===void 0&&Nl(t)}function Nl(t){if(t._zod.def.coerce)return!0;let e=t._zod.def;switch(e.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return e.innerType?Nl(e.innerType):!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return e.innerType?Nl(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(Nl):!0;case"intersection":return!e.left||!e.right?!0:Nl(e.left)&&Nl(e.right);case"pipe":return e.in?Nl(e.in):!0;default:return!0}}function Nz(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function F9(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&Mp(t)}function Mp(t){let e=t._zod.def;switch(e.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return e.innerType?Mp(e.innerType):!0;case"union":return e.options?e.options.some(Mp):!0;case"intersection":return!e.left||!e.right||Mp(e.left)||Mp(e.right);case"pipe":return e.out?Mp(e.out):!0;default:return!0}}function PTe(t,e,r,o,n=!0){let i=r._zod.def,s=n?pe(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=rr(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function kTe(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?pe(e):null,a=pe(e),c=pe(e);return s&&t.write(`const ${s} = new Array(${o}.length);`),t.write(`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`),t.indented(u=>{u.write(`const ${c} = ${o}[${a}];`);let l=_n(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function TTe(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=he(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=he(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${Un(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")t.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)t.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)t.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")t.write(`if (${o} !== ${s}n) return INVALID;`);else throw new Be(`literal type ${typeof s}`);return o}function CTe(t,e,r,o){let n=r._zod.values;if(!n)throw new Be("enum schema without enumerated values");let i=he(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function q9(t,e,r,o){let n=r._zod.def;return rr(t,e,n.innerType,o)}function OTe(t,e,r,o){let n=r._zod.def,s=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!s)return rr(t,e,n.innerType,o);let c=he(e,s),u=pe(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),rr(t,e,n.innerType,u)}let a=pe(e);if(s){let c=he(e,s),u=he(e,vp);t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),t.write("} else {"),t.indented(l=>{let d=rr(l,e,n.innerType,o);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),t.write("}")}else t.write(`let ${a};`),t.write(`if (${o} !== undefined) {`),t.indented(c=>{let u=rr(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function DTe(t,e,r,o){let n=r._zod.def,i=rr(t,e,n.innerType,o),s=pe(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function NTe(t,e,r,o){let n=r._zod.def,i=n.items,s=n.rest;t.write(`if (!Array.isArray(${o})) return INVALID;`);let a=V9(i,"optin"),c=V9(i,"optout");s?t.write(`if (${o}.length < ${a}) return INVALID;`):t.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=pe(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(p=>{p.write(`if (${l} < ${o}.length) {`),p.indented(f=>{let m=pe(e);f.write(`const ${m} = ${o}[${l}];`);let y=_n(f,e,d,m);f.write(`${u}[${l}] = ${y};`)}),p.write("} else {"),p.indented(f=>{if(Nz(d)){f.write(`${u}.length = ${l};`);return}let m=pe(e),y=pe(e);f.write(`const ${m} = undefined;`),f.write(`const ${y} = (() => {`),f.indented(w=>{let b=_n(w,e,d,m);w.write(`return ${b};`)}),f.write("})();"),f.write(`if (${y} === INVALID || ${y} === undefined) ${u}.length = ${l};`),f.write(`else ${u}[${l}] = ${y};`)}),p.write("}")}),t.write("}");else{let p=pe(e);t.write(`const ${p} = ${o}[${l}];`);let f=_n(t,e,d,p);t.write(`${u}[${l}] = ${f};`)}}if(s){let l=pe(e),d=pe(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(p=>{p.write(`const ${d} = ${o}[${l}];`);let f=_n(p,e,s,d);p.write(`${u}[${l}] = ${f};`)}),t.write("}")}return u}function V9(t,e){for(let r=t.length-1;r>=0;r--)if(!(e==="optin"?t[r]._zod.optin!==void 0:t[r]._zod.optout==="optional"))return r+1;return 0}function zTe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return MTe(t,e,n,o);if(n.inclusive===!1)throw new Be("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return rr(t,e,i[0],o);if(i.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(i.flatMap(l=>l._zod.def.values)),u=he(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=pe(e);t.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?t.write(`${a} = (() => {`):t.write(`if (${a} === INVALID) ${a} = (() => {`),t.indented(l=>{let d=rr(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function MTe(t,e,r,o){if(r.unionFallback)throw new Be("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=pe(e),i=pe(e);t.write(`const ${n} = ${o}?.[${Un(r.discriminator)}];`),t.write(`let ${i};`);let s=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Be("discriminated union option without static discriminator values");for(let p of u){if(a.has(p))throw new Be(`duplicate discriminator value ${String(p)}`);a.add(p)}let l=Array.from(u,p=>UTe(e,n,p)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(p=>{let f=rr(p,e,c,o);p.write(`${i} = ${f};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function UTe(t,e,r){if(typeof r=="string")return`${e} === ${Un(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${e})`:`${e} === ${r}`;if(typeof r=="boolean")return`${e} === ${r}`;if(r===null)return`${e} === null`;if(r===void 0)return`${e} === undefined`;if(typeof r=="bigint")return`${e} === ${r}n`;if(typeof r=="symbol"){let o=he(t,r);return`${e} === ${o}`}throw new Be(`literal discriminator value ${String(r)}`)}function LTe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=_n(t,e,n.left,o),s=_n(t,e,n.right,o),a=he(e,Pp),c=pe(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function jTe(t,e,r,o){let n=r._zod.def,i=he(e,Wo);t.write(`if (!${i}(${o})) return INVALID;`);let s=pe(e),a=pe(e),c=pe(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let f=[];for(let y of l){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new Be(`record key value ${String(y)}`);let w=typeof y=="number"?y.toString():y;if(w==="__proto__")throw new Be('record key "__proto__"');f.push(w);let b=he(e,y),S=rr(t,e,n.keyType,b),x=pe(e);t.write(`const ${x} = ${o}[${FTe(e,w)}];`);let I=_n(t,e,n.valueType,x);t.write(`${s}[${S}] = ${I};`)}let m=he(e,new Set(f));return t.write(`for (const ${a} in ${o}) {`),t.indented(y=>{y.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?y.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):y.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let f=n.mode==="loose",m=Xx(n.keyType);m.definite===!1&&(e.definite=!1);let y=he(e,m),w=he(e,Ma),b=pe(e);return G9(t,e,o,a,S=>{S.write(`let ${b} = ${y}(${a});`),S.write(`if (${b} === INVALID && typeof ${a} === "string" && ${w}.test(${a})) ${b} = ${y}(Number(${a}));`),f?S.write(`if (${b} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):S.write(`if (${b} === INVALID) return INVALID;`),S.write(`if (${b} === "__proto__") continue;`);let x=pe(e);S.write(`const ${x} = ${o}[${a}];`);let I=_n(S,e,n.valueType,x);S.write(`${s}[${b}] = ${I};`)}),s}return G9(t,e,o,a,f=>{f.write(`const ${c} = ${o}[${a}];`);let m=_n(f,e,n.valueType,c);f.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function G9(t,e,r,o,n,i){let s=he(e,Object.prototype.propertyIsEnumerable),a=pe(e),c=pe(e),u=pe(e);t.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),t.write(`const ${c} = Object.getOwnPropertyNames(${r});`),t.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),t.write("}"),t.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),t.write("}")}function FTe(t,e){return typeof e=="string"?Un(e):he(t,e)}function qTe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=pe(e),s=pe(e),a=pe(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=rr(c,e,n.keyType,s),l=rr(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function VTe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=pe(e),s=pe(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=rr(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function GTe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function HTe(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=he(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function BTe(t,e,r,o){let n=r._zod.def,i=zl(e,n.getter),s=he(e,{parser:null});t.write(`if (!${s}.parser) {`),t.indented(c=>{c.write(`const inner = ${i}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),t.write("}");let a=pe(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function KTe(t,e,r,o){let n=r._zod.def,i=rr(t,e,n.in,o);if(n.transform){if(Ml(n.transform))throw new Ti("z.compile: async transforms in pipes are not supported");let s=n.transform,c=zl(e,l=>{let d={value:l,issues:[],addIssue:Mz},p=s(l,d);return p instanceof Promise?jn:d.issues.length===0?p:jn}),u=pe(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),rr(t,e,n.out,u)}else return rr(t,e,n.out,i)}function Ml(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function ZTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Ml(n.fn))throw new Ti("z.compile: async custom predicates are not supported");let i=zl(e,n.fn),s=he(e,Dz),a=pe(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Be("custom schema without a predicate function");return o}function WTe(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return jn;let n=o;return n.issues.length===0?n.value:e()}function JTe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[iS])throw new Be("catch with a callback (only a constant catch value compiles)",!1);let i=pe(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=_n(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=he(e,n.innerType),a=zl(e,n.catchValue),c=he(e,WTe);return t.write(`if (${i} === INVALID) {`),t.indented(u=>{u.write(`${i} = ${c}(${s}, ${a}, ${o});`),u.write(`if (${i} === INVALID) return INVALID;`)}),t.write("}"),i}function XTe(t,e,r,o){let n=r._zod.def;if(n.transform){if(Ml(n.transform))throw new Ti("z.compile: async transforms are not supported");let i=n.transform,a=zl(e,u=>{let l={value:u,issues:[],addIssue:Mz},d=i(u,l);return d instanceof Promise?jn:l.issues.length===0?d:jn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function Yx(t){return t.checks&&(t.checks=[...t.checks]),t}function Qx(t,e){return new t(Yx({type:"string",...j(e)}))}function Uz(t,e){return new t(Yx({type:"string",coerce:!0,...j(e)}))}function Ag(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Pg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function kg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Tg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Cg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Og(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Up(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function Dg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Ng(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function zg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function Mg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function Ug(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function Lg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function jg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function Fg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function qg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function e0(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...j(e)})}function Vg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function Gg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function Hg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Bg(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function Kg(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function t0(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...j(e)})}function r0(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...j(e)})}function Zg(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}var Lz={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Wg(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function Jg(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function Xg(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function Yg(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function n0(t,e){return new t(Yx({type:"number",checks:[],...j(e)}))}function jz(t,e){return new t(Yx({type:"number",coerce:!0,checks:[],...j(e)}))}function o0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function i0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...j(e)})}function s0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...j(e)})}function a0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...j(e)})}function c0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...j(e)})}function u0(t,e){return new t({type:"boolean",...j(e)})}function Fz(t,e){return new t({type:"boolean",coerce:!0,...j(e)})}function l0(t,e){return new t({type:"bigint",...j(e)})}function qz(t,e){return new t({type:"bigint",coerce:!0,...j(e)})}function d0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...j(e)})}function p0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...j(e)})}function f0(t,e){return new t({type:"symbol",...j(e)})}function m0(t,e){return new t({type:"undefined",...j(e)})}function h0(t,e){return new t({type:"null",...j(e)})}function g0(t){return new t({type:"any"})}function y0(t){return new t({type:"unknown"})}function v0(t,e){return new t({type:"never",...j(e)})}function w0(t,e){return new t({type:"void",...j(e)})}function _0(t,e){return new t({type:"date",...j(e)})}function Vz(t,e){return new t({type:"date",coerce:!0,...j(e)})}function b0(t,e){return new t({type:"nan",...j(e)})}function Rs(t,e){return new wS({check:"less_than",...j(e),value:t,inclusive:!1})}function So(t,e){return new wS({check:"less_than",...j(e),value:t,inclusive:!0})}function Is(t,e){return new _S({check:"greater_than",...j(e),value:t,inclusive:!1})}function xo(t,e){return new _S({check:"greater_than",...j(e),value:t,inclusive:!0})}function S0(t){return Is(0,t)}function x0(t){return Rs(0,t)}function E0(t){return So(0,t)}function $0(t){return xo(0,t)}function Oc(t,e){return new Q1({check:"multiple_of",...j(e),value:t})}function Dc(t,e){return new rz({check:"max_size",...j(e),maximum:t})}function As(t,e){return new nz({check:"min_size",...j(e),minimum:t})}function Ul(t,e){return new oz({check:"size_equals",...j(e),size:t})}function Ll(t,e){return new iz({check:"max_length",...j(e),maximum:t})}function Ua(t,e){return new sz({check:"min_length",...j(e),minimum:t})}function jl(t,e){return new az({check:"length_equals",...j(e),length:t})}function Lp(t,e){return new cz({check:"string_format",format:"regex",...j(e),pattern:t})}function jp(t){return new uz({check:"string_format",format:"lowercase",...j(t)})}function Fp(t){return new lz({check:"string_format",format:"uppercase",...j(t)})}function qp(t,e){return new dz({check:"string_format",format:"includes",...j(e),includes:t})}function Vp(t,e){return new pz({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Gp(t,e){return new fz({check:"string_format",format:"ends_with",...j(e),suffix:t})}function R0(t,e,r){return new mz({check:"property",property:t,schema:e,...j(r)})}function Hp(t,e){return new hz({check:"properties",shape:t,...j(e)})}function Bp(t,e){return new gz({check:"mime_type",mime:t,...j(e)})}function Ci(t){return new yz({check:"overwrite",tx:t})}function Kp(t){return Ci(e=>e.normalize(t))}function Zp(){return Ci(t=>t.trim())}function Wp(){return Ci(t=>t.toLowerCase())}function Jp(){return Ci(t=>t.toUpperCase())}function Xp(){return Ci(t=>e1(t))}function Gz(t,e,r){return new t({type:"array",element:e,...j(r)})}function YTe(t,e,r){return new t({type:"union",options:e,...j(r)})}function QTe(t,e,r){return new t({type:"union",options:e,inclusive:!1,...j(r)})}function eCe(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...j(o)})}function tCe(t,e,r){return new t({type:"intersection",left:e,right:r})}function rCe(t,e,r,o){let n=r instanceof _e,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...j(i)})}function nCe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...j(o)})}function oCe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...j(o)})}function iCe(t,e,r){return new t({type:"set",valueType:e,...j(r)})}function sCe(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...j(r)})}function aCe(t,e,r){return new t({type:"enum",entries:e,...j(r)})}function cCe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...j(r)})}function I0(t,e){return new t({type:"file",...j(e)})}function uCe(t,e){return new t({type:"transform",transform:e})}function lCe(t,e){return new t({type:"optional",innerType:e})}function dCe(t,e){return new t({type:"nullable",innerType:e})}function pCe(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():vp(r)}})}function fCe(t,e,r){return new t({type:"nonoptional",innerType:e,...j(r)})}function mCe(t,e){return new t({type:"success",innerType:e})}function hCe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:a1(r)})}function gCe(t,e,r){return new t({type:"pipe",in:e,out:r})}function yCe(t,e){return new t({type:"readonly",innerType:e})}function vCe(t,e,r){return new t({type:"template_literal",parts:e,...j(r)})}function wCe(t,e){return new t({type:"lazy",getter:e})}function _Ce(t,e){return new t({type:"promise",innerType:e})}function A0(t,e,r){let o=j(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function P0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function k0(t,e){let r=Z9(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(wp(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(wp(i))}},t(o.value,o)),e);return r}function Z9(t,e){let r=new Tt({check:"custom",...j(e)});return r._zod.check=t,r}function T0(t){let e=new Tt({check:"describe"});return e._zod.onattach=[r=>{let o=Zr.get(r)??{};Zr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function C0(t){let e=new Tt({check:"meta"});return e._zod.onattach=[r=>{let o=Zr.get(r)??{};Zr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function O0(t,e){let r=j(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),s=new Set(n),a=t.Codec??Cp,c=t.Boolean??kp,u=t.String??Cc,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new a({type:"pipe",in:l,out:d,transform:((f,m)=>{let y=f;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:s.has(y)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:p,continue:!1}),{})}),reverseTransform:((f,m)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return p._zod.bag.truthy=o,p._zod.bag.falsy=n,p._zod.bag.case=r.case??"insensitive",p}function Nc(t,e,r,o={}){let n=j(o),i={check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(i.pattern=r),new t(i)}function Qg(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&Kr(t,o,r[o]);return t}function zc(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Zr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function Ar(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function At(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let p=s.schema,f=e.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),At(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Qg(s.schema,c),e.io==="input"&&Fn(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function W9(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Mc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${W9(f)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+W9(l)}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
127
127
|
|
|
128
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function Y9(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;Y9(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var Q9=new Set(["type","properties","required","additionalProperties"]),J9=["oneOf","anyOf"];function X9(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function Hz(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!Q9.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??X9(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:Hz(a)??{allOf:a};Kr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=X9(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function bCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of Q9)if(n in t)return;let r=e.filter(n=>J9.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Hz(e);else{let n=r[0],i=J9.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>Hz([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,Qg(t,o))}function Uc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Qg(u,m),Qg(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&f.def)for(let w in u)w==="$ref"||w==="allOf"||w in f.def&&JSON.stringify(u[w])===JSON.stringify(f.def[w])&&delete u[w]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())Y9(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])bCe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Qg(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Kr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Yp(e,"input",t.processors),output:Yp(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Fn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Fn(o.element,r);if(o.type==="set")return Fn(o.valueType,r);if(o.type==="lazy")return Fn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Fn(o.innerType,r);if(o.type==="intersection")return Fn(o.left,r)||Fn(o.right,r);if(o.type==="record"||o.type==="map")return Fn(o.keyType,r)||Fn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Fn(o.in,r)||Fn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Fn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Fn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Fn(n,r))return!0;return!!(o.rest&&Fn(o.rest,r))}return!1}var Bz=(t,e={})=>r=>{let o=zc({...r,processors:e});return At(t,o),Mc(o,t),Uc(o,t)},Yp=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=zc({...n??{},target:i,io:e,processors:r});return At(t,s),Mc(s,t),Uc(s,t)};var Qp=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},ef=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},eZ=(t,e)=>{Qp(t,"minimum",e),ef(t,"maximum",e)},oZ=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},iZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},sZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},aZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},tZ=(t,e)=>Qp(t,"minimum",e.minimum),rZ=(t,e)=>ef(t,"maximum",e.maximum),nZ=t=>(e,r)=>{aZ(e,r.format);let[o,n]=t[r.format];Qp(e,"minimum",o),ef(e,"maximum",n)},SCe={greater_than:(t,e)=>Qp(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>ef(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>oZ(t,e.value),number_format:nZ(ng),bigint_format:nZ(og),min_length:tZ,max_length:rZ,length_equals:(t,e)=>eZ(t,e.length),min_size:tZ,max_size:rZ,size_equals:(t,e)=>eZ(t,e.size),string_format:(t,e)=>{aZ(t,e.format),e.pattern&&iZ(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>sZ(t,e.mime)};function Pr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)SCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Qp(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Qp(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&ef(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&ef(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&oZ(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&sZ(e,n.mime);for(let i of n.patterns??[])iZ(e,i);return e}var xCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ECe=new Map([[BS,O1],[vg,D1]]),cZ=t=>ECe.get(t)??t,Wz=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Pr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=xCe[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(cZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Jz=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Pr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let b of a)Number.isFinite(b)&&b!==0?m.add(Math.abs(b)):Ar(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=m;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},Xz=(t,e,r,o)=>{r.type="boolean"},Yz=(t,e,r,o)=>{Ar(t,e,r,o,"BigInt cannot be represented in JSON Schema")},Qz=(t,e,r,o)=>{Ar(t,e,r,o,"Symbols cannot be represented in JSON Schema")},eM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},tM=(t,e,r,o)=>{Ar(t,e,r,o,"Undefined cannot be represented in JSON Schema")},rM=(t,e,r,o)=>{Ar(t,e,r,o,"Void cannot be represented in JSON Schema")},nM=(t,e,r,o)=>{r.not={}},oM=(t,e,r,o)=>{},iM=(t,e,r,o)=>{},sM=(t,e,r,o)=>{Ar(t,e,r,o,"Date cannot be represented in JSON Schema")},aM=(t,e,r,o)=>{let n=t._zod.def,i=mp(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},cM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Ar(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Ar(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},uM=(t,e,r,o)=>{Ar(t,e,r,o,"NaN cannot be represented in JSON Schema")},lM=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},dM=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Pr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},pM=(t,e,r,o)=>{r.type="boolean"},fM=(t,e,r,o)=>{Ar(t,e,r,o,"Custom types cannot be represented in JSON Schema")},mM=(t,e,r,o)=>{Ar(t,e,r,o,"Function types cannot be represented in JSON Schema")},hM=(t,e,r,o)=>{Ar(t,e,r,o,"Transforms cannot be represented in JSON Schema")},gM=(t,e,r,o)=>{Ar(t,e,r,o,"Map cannot be represented in JSON Schema")},yM=(t,e,r,o)=>{Ar(t,e,r,o,"Set cannot be represented in JSON Schema")},vM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Pr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=At(i.element,e,{...o,path:[...o.path,"items"]})};function ey(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?ey(e.out):e.type==="catch"?ey(e.innerType):t._zod.optin}var wM=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Ar(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Kr(n.properties,u,At(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?ey(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=At(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},N0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>At(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},_M=(t,e,r,o)=>{let n=t._zod.def,i=At(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=At(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},bM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>At(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?At(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?ey(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=Pr(t);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function Kz(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let y=Kz(t,m,r);return y===m?e:y}for(let m of["anyOf","oneOf"]){let y=e[m];if(!Array.isArray(y))continue;let w=y.map(b=>Kz(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[m]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?Ma:dg).source)),f}var Zz=new WeakMap;function $Ce(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of Zz.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=Kz(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var SM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Pr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=At(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Kr(n.patternProperties,cZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=At(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=Zz.get(e);l||(l=[],Zz.set(e,l),e.deferred.push(()=>$Ce(e))),l.push(t)}n.additionalProperties=At(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&ey(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},xM=(t,e,r,o)=>{let n=t._zod.def,i=At(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},EM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},$M=Symbol();function uZ(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Ar(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),$M):JSON.parse(s)}var RM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=uZ(n.defaultValue,t,e,r,o);s!==$M&&(r.default=s)},IM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=uZ(n.defaultValue,t,e,r,o);s!==$M&&(r._prefault=s)},AM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Ar(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},PM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;At(s,e,o);let a=e.seen.get(t);a.ref=s},kM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},TM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},z0=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},CM=(t,e,r,o)=>{let n=t._zod.innerType;At(n,e,o);let i=e.seen.get(t);i.ref=n},D0={string:Wz,number:Jz,boolean:Xz,bigint:Yz,symbol:Qz,null:eM,undefined:tM,void:rM,never:nM,any:oM,unknown:iM,date:sM,enum:aM,literal:cM,nan:uM,template_literal:lM,file:dM,success:pM,custom:fM,function:mM,transform:hM,map:gM,set:yM,array:vM,object:wM,union:N0,intersection:_M,tuple:bM,record:SM,nullable:xM,nonoptional:EM,default:RM,prefault:IM,catch:AM,pipe:PM,readonly:kM,promise:TM,optional:z0,lazy:CM};function Fl(t,e){if("_idmap"in t){let o=t,n=zc({...e,processors:D0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;At(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Mc(n,l),Kr(s,u,Uc(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=zc({...e,processors:D0});return At(t,r),Mc(r,t),Uc(r,t)}var M0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=zc({processors:D0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return At(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Mc(this.ctx,e);let o=Uc(this.ctx,e),{"~standard":n,...i}=o;return i}};var lZ={};var uf={};Ht(uf,{ZodAny:()=>XM,ZodArray:()=>tU,ZodBase64:()=>rE,ZodBase64URL:()=>nE,ZodBigInt:()=>af,ZodBigIntFormat:()=>sE,ZodBoolean:()=>sf,ZodCIDRv4:()=>eE,ZodCIDRv6:()=>tE,ZodCUID:()=>K0,ZodCUID2:()=>Z0,ZodCatch:()=>_U,ZodCodec:()=>uy,ZodCreditCard:()=>BM,ZodCustom:()=>ly,ZodCustomStringFormat:()=>Vl,ZodDate:()=>oy,ZodDefault:()=>mU,ZodDiscriminatedUnion:()=>nU,ZodE164:()=>oE,ZodEmail:()=>V0,ZodEmoji:()=>H0,ZodEnum:()=>rf,ZodExactOptional:()=>uE,ZodFile:()=>lU,ZodFunction:()=>kU,ZodGUID:()=>G0,ZodIBAN:()=>KM,ZodIPv4:()=>Y0,ZodIPv6:()=>Q0,ZodISODate:()=>jc,ZodISODateTime:()=>Lc,ZodISODuration:()=>qc,ZodISOTime:()=>Fc,ZodInstanceOf:()=>OU,ZodIntersection:()=>oU,ZodJWT:()=>iE,ZodKSUID:()=>X0,ZodLazy:()=>IU,ZodLiteral:()=>uU,ZodMAC:()=>HM,ZodMap:()=>aU,ZodNaN:()=>SU,ZodNanoID:()=>B0,ZodNever:()=>QM,ZodNonOptional:()=>lE,ZodNull:()=>JM,ZodNullable:()=>fU,ZodNumber:()=>of,ZodNumberFormat:()=>Gl,ZodObject:()=>iy,ZodOptional:()=>Hl,ZodPipe:()=>cy,ZodPrefault:()=>gU,ZodPreprocess:()=>xU,ZodPromise:()=>PU,ZodReadonly:()=>EU,ZodRecord:()=>tf,ZodSet:()=>cU,ZodString:()=>nf,ZodStringFormat:()=>Ot,ZodSuccess:()=>wU,ZodSymbol:()=>ZM,ZodTemplateLiteral:()=>RU,ZodTransform:()=>dU,ZodTuple:()=>iU,ZodType:()=>ke,ZodULID:()=>W0,ZodURL:()=>ry,ZodUUID:()=>Ps,ZodUndefined:()=>WM,ZodUnion:()=>sy,ZodUnknown:()=>YM,ZodVoid:()=>eU,ZodXID:()=>J0,ZodXor:()=>rU,_ZodString:()=>q0,_default:()=>hU,_function:()=>vW,any:()=>QZ,array:()=>Fe,base64:()=>OZ,base64url:()=>DZ,bigint:()=>ZZ,boolean:()=>hr,catch:()=>bU,check:()=>wW,cidrv4:()=>TZ,cidrv6:()=>CZ,codec:()=>mW,creditCard:()=>zZ,cuid:()=>xZ,cuid2:()=>EZ,currencyCode:()=>qZ,custom:()=>dE,date:()=>tW,describe:()=>_W,discriminatedUnion:()=>ay,e164:()=>NZ,email:()=>fZ,emoji:()=>bZ,enum:()=>Jr,exactOptional:()=>pU,file:()=>lW,float32:()=>GZ,float64:()=>HZ,function:()=>vW,guid:()=>mZ,hash:()=>VZ,hex:()=>FZ,hostname:()=>jZ,httpUrl:()=>_Z,iban:()=>MZ,instanceof:()=>SW,int:()=>j0,int32:()=>BZ,int64:()=>WZ,intersection:()=>cf,invertCodec:()=>hW,ipv4:()=>AZ,ipv6:()=>kZ,json:()=>EW,jwt:()=>UZ,keyof:()=>rW,ksuid:()=>IZ,lazy:()=>AU,literal:()=>se,looseObject:()=>Wr,looseRecord:()=>sW,mac:()=>PZ,map:()=>aW,meta:()=>bW,nan:()=>fW,nanoid:()=>SZ,nativeEnum:()=>uW,never:()=>aE,nonoptional:()=>vU,null:()=>ny,nullable:()=>ty,nullish:()=>dW,number:()=>yt,object:()=>X,optional:()=>Ct,partialRecord:()=>iW,pipe:()=>F0,prefault:()=>yU,preprocess:()=>dy,promise:()=>yW,readonly:()=>$U,record:()=>Dt,refine:()=>TU,set:()=>cW,strictObject:()=>nW,string:()=>O,stringFormat:()=>LZ,stringbool:()=>xW,success:()=>pW,superRefine:()=>CU,symbol:()=>XZ,templateLiteral:()=>gW,transform:()=>cE,tuple:()=>sU,uint32:()=>KZ,uint64:()=>JZ,ulid:()=>$Z,undefined:()=>YZ,union:()=>Pt,unknown:()=>Lt,url:()=>wZ,uuid:()=>hZ,uuidv4:()=>gZ,uuidv6:()=>yZ,uuidv7:()=>vZ,void:()=>eW,xid:()=>RZ,xor:()=>oW});var U0={};Ht(U0,{endsWith:()=>Gp,gt:()=>Is,gte:()=>xo,includes:()=>qp,length:()=>jl,lowercase:()=>jp,lt:()=>Rs,lte:()=>So,maxLength:()=>Ll,maxSize:()=>Dc,mime:()=>Bp,minLength:()=>Ua,minSize:()=>As,multipleOf:()=>Oc,negative:()=>x0,nonnegative:()=>$0,nonpositive:()=>E0,normalize:()=>Kp,overwrite:()=>Ci,positive:()=>S0,properties:()=>Hp,property:()=>R0,regex:()=>Lp,size:()=>Ul,slugify:()=>Xp,startsWith:()=>Vp,toLowerCase:()=>Wp,toUpperCase:()=>Jp,trim:()=>Zp,uppercase:()=>Fp});var dZ=new WeakSet([Object.prototype,Error.prototype]);function L0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var pZ=(t,e)=>{f1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);dZ.has(r)||(dZ.add(r),L0(r,"format",o=>n=>ug(o,n)),L0(r,"flatten",o=>n=>cg(o,n)),L0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,hp,2)}),L0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,hp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ICe=$("ZodError",pZ),io=$("ZodError",pZ,void 0,{Parent:Error});var OM=_p(io),DM=bp(io),NM=Sp(io),zM=Ep(io),MM=aS(io),UM=cS(io),LM=uS(io),jM=lS(io),FM=dS(io),qM=pS(io),VM=fS(io),GM=mS(io);function PCe(){Dr.localeError||cr(Hx())}function ql(){Dr.memoizer||cr({memoizer:Rg()})}var ke=$("ZodType",(t,e)=>(PCe(),_e.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(TU(t,e))},superRefine(t,e){return this.check(CU(t,e))},overwrite(t){return this.check(Ci(t))},optional(){return Ct(this)},exactOptional(){return pU(this)},nullable(){return ty(this)},nullish(){return Ct(ty(this))},nonoptional(t){return vU(this,t)},array(){return Fe(this)},or(t){return Pt([this,t])},and(t){return cf(this,t)},transform(t){return F0(this,cE(t))},default(t){return hU(this,t)},prefault(t){return yU(this,t)},catch(t){return bU(this,t)},pipe(t){return F0(this,t)},readonly(){return $U(this)},describe(t){let e=this.clone();return Zr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Zr.get(this);let e=this.clone();return Zr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return D.hide(this,"~standard",{...$S(this),jsonSchema:{input:Yp(this,"input"),output:Yp(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return OM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await DM(this,e,r,{callee:t})},safeParse(t,e){return NM(this,t,e)},async safeParseAsync(t,e){return zM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Rp(this,t,e)},validateAsync(t,e){return Ip(this,t,e)},encode:function t(e,r){return MM(this,e,r,{callee:t})},decode:function t(e,r){return UM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await LM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await jM(this,e,r,{callee:t})},safeEncode(t,e){return FM(this,t,e)},safeDecode(t,e){return qM(this,t,e)},async safeEncodeAsync(t,e){return VM(this,t,e)},async safeDecodeAsync(t,e){return GM(this,t,e)},toJSONSchema(t){return Bz(this,{})(t)},get description(){return Zr.get(this)?.description},get _def(){return this._zod.def}}),q0=$("_ZodString",(t,e)=>{Cc.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Wz(t,r,o,n)},D.derived({format:t=>Pr(t).format??null,minLength:t=>Pr(t).minimum??null,maxLength:t=>Pr(t).maximum??null},{regex(...t){return this.check(Lp(...t))},includes(...t){return this.check(qp(...t))},startsWith(...t){return this.check(Vp(...t))},endsWith(...t){return this.check(Gp(...t))},min(...t){return this.check(Ua(...t))},max(...t){return this.check(Ll(...t))},length(...t){return this.check(jl(...t))},nonempty(...t){return this.check(Ua(1,...t))},lowercase(t){return this.check(jp(t))},uppercase(t){return this.check(Fp(t))},trim(){return this.check(Zp())},normalize(...t){return this.check(Kp(...t))},toLowerCase(){return this.check(Wp())},toUpperCase(){return this.check(Jp())},slugify(){return this.check(Xp())}})),nf=$("ZodString",(t,e)=>{Cc.init(t,e),q0.init(t,e)},{email(t){return this.check(Ag(V0,t))},url(t){return this.check(Up(ry,t))},jwt(t){return this.check(Zg(iE,t))},emoji(t){return this.check(Dg(H0,t))},guid(t){return this.check(Pg(G0,t))},uuid(t){return this.check(kg(Ps,t))},uuidv4(t){return this.check(Tg(Ps,t))},uuidv6(t){return this.check(Cg(Ps,t))},uuidv7(t){return this.check(Og(Ps,t))},nanoid(t){return this.check(Ng(B0,t))},cuid(t){return this.check(zg(K0,t))},cuid2(t){return this.check(Mg(Z0,t))},ulid(t){return this.check(Ug(W0,t))},base64(t){return this.check(Hg(rE,t))},base64url(t){return this.check(Bg(nE,t))},xid(t){return this.check(Lg(J0,t))},ksuid(t){return this.check(jg(X0,t))},ipv4(t){return this.check(Fg(Y0,t))},ipv6(t){return this.check(qg(Q0,t))},cidrv4(t){return this.check(Vg(eE,t))},cidrv6(t){return this.check(Gg(tE,t))},e164(t){return this.check(Kg(oE,t))},datetime(t){return this.check(Wg(Lc,t))},date(t){return this.check(Jg(jc,t))},time(t){return this.check(Xg(Fc,t))},duration(t){return this.check(Yg(qc,t))}});function O(t){return Qx(nf,t)}var Ot=$("ZodStringFormat",(t,e)=>{xt.init(t,e),q0.init(t,e)}),Lc=$("ZodISODateTime",(t,e)=>{Sz.init(t,e),Ot.init(t,e)}),jc=$("ZodISODate",(t,e)=>{xz.init(t,e),Ot.init(t,e)}),Fc=$("ZodISOTime",(t,e)=>{Ez.init(t,e),Ot.init(t,e)}),qc=$("ZodISODuration",(t,e)=>{$z.init(t,e),Ot.init(t,e)}),V0=$("ZodEmail",(t,e)=>{AS.init(t,e),Ot.init(t,e)});function fZ(t){return Ag(V0,t)}var G0=$("ZodGUID",(t,e)=>{RS.init(t,e),Ot.init(t,e)});function mZ(t){return Pg(G0,t)}var Ps=$("ZodUUID",(t,e)=>{IS.init(t,e),Ot.init(t,e)});function hZ(t){return kg(Ps,t)}function gZ(t){return Tg(Ps,t)}function yZ(t){return Cg(Ps,t)}function vZ(t){return Og(Ps,t)}var ry=$("ZodURL",(t,e)=>{CS.init(t,e),Ot.init(t,e)});function wZ(t){return Up(ry,t)}function _Z(t){return Up(ry,{protocol:lg,hostname:z1,...D.normalizeParams(t)})}var H0=$("ZodEmoji",(t,e)=>{OS.init(t,e),Ot.init(t,e)});function bZ(t){return Dg(H0,t)}var B0=$("ZodNanoID",(t,e)=>{DS.init(t,e),Ot.init(t,e)});function SZ(t){return Ng(B0,t)}var K0=$("ZodCUID",(t,e)=>{NS.init(t,e),Ot.init(t,e)});function xZ(t){return zg(K0,t)}var Z0=$("ZodCUID2",(t,e)=>{zS.init(t,e),Ot.init(t,e)});function EZ(t){return Mg(Z0,t)}var W0=$("ZodULID",(t,e)=>{MS.init(t,e),Ot.init(t,e)});function $Z(t){return Ug(W0,t)}var J0=$("ZodXID",(t,e)=>{US.init(t,e),Ot.init(t,e)});function RZ(t){return Lg(J0,t)}var X0=$("ZodKSUID",(t,e)=>{LS.init(t,e),Ot.init(t,e)});function IZ(t){return jg(X0,t)}var Y0=$("ZodIPv4",(t,e)=>{jS.init(t,e),Ot.init(t,e)});function AZ(t){return Fg(Y0,t)}var HM=$("ZodMAC",(t,e)=>{qS.init(t,e),Ot.init(t,e)});function PZ(t){return e0(HM,t)}var Q0=$("ZodIPv6",(t,e)=>{FS.init(t,e),Ot.init(t,e)});function kZ(t){return qg(Q0,t)}var eE=$("ZodCIDRv4",(t,e)=>{VS.init(t,e),Ot.init(t,e)});function TZ(t){return Vg(eE,t)}var tE=$("ZodCIDRv6",(t,e)=>{HS.init(t,e),Ot.init(t,e)});function CZ(t){return Gg(tE,t)}var rE=$("ZodBase64",(t,e)=>{KS.init(t,e),Ot.init(t,e)});function OZ(t){return Hg(rE,t)}var nE=$("ZodBase64URL",(t,e)=>{WS.init(t,e),Ot.init(t,e)});function DZ(t){return Bg(nE,t)}var oE=$("ZodE164",(t,e)=>{JS.init(t,e),Ot.init(t,e)});function NZ(t){return Kg(oE,t)}var BM=$("ZodCreditCard",(t,e)=>{YS.init(t,e),Ot.init(t,e)});function zZ(t){return t0(BM,t)}var KM=$("ZodIBAN",(t,e)=>{ex.init(t,e),Ot.init(t,e)});function MZ(t){return r0(KM,t)}var iE=$("ZodJWT",(t,e)=>{rx.init(t,e),Ot.init(t,e)});function UZ(t){return Zg(iE,t)}var Vl=$("ZodCustomStringFormat",(t,e)=>{nx.init(t,e),Ot.init(t,e)});function LZ(t,e,r={}){return Nc(Vl,t,e,r)}function jZ(t){return Nc(Vl,"hostname",N1,t)}function FZ(t){return Nc(Vl,"hex",J1,t)}function qZ(t){return Nc(Vl,"currency_code",U1,t)}function VZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=bo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Nc(Vl,o,n,e)}var of=$("ZodNumber",(t,e)=>{wg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Jz(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Pr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Pr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Pr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Pr(t).format??null},{gt(t,e){return this.check(Is(t,e))},gte(t,e){return this.check(xo(t,e))},min(t,e){return this.check(xo(t,e))},lt(t,e){return this.check(Rs(t,e))},lte(t,e){return this.check(So(t,e))},max(t,e){return this.check(So(t,e))},int(t){return this.check(j0(t))},safe(t){return this.check(j0(t))},positive(t){return this.check(Is(0,t))},nonnegative(t){return this.check(xo(0,t))},negative(t){return this.check(Rs(0,t))},nonpositive(t){return this.check(So(0,t))},multipleOf(t,e){return this.check(Oc(t,e))},step(t,e){return this.check(Oc(t,e))},finite(){return this}}));function yt(t){return n0(of,t)}var Gl=$("ZodNumberFormat",(t,e)=>{ox.init(t,e),of.init(t,e)});function j0(t){return o0(Gl,t)}function GZ(t){return i0(Gl,t)}function HZ(t){return s0(Gl,t)}function BZ(t){return a0(Gl,t)}function KZ(t){return c0(Gl,t)}var sf=$("ZodBoolean",(t,e)=>{kp.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Xz(t,r,o,n)});function hr(t){return u0(sf,t)}var af=$("ZodBigInt",(t,e)=>{_g.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Yz(t,r,o,n)},D.derived({minValue:t=>Pr(t).minimum??null,maxValue:t=>Pr(t).maximum??null,format:t=>Pr(t).format??null},{gte(t,e){return this.check(xo(t,e))},min(t,e){return this.check(xo(t,e))},gt(t,e){return this.check(Is(t,e))},lt(t,e){return this.check(Rs(t,e))},lte(t,e){return this.check(So(t,e))},max(t,e){return this.check(So(t,e))},positive(t){return this.check(Is(BigInt(0),t))},negative(t){return this.check(Rs(BigInt(0),t))},nonpositive(t){return this.check(So(BigInt(0),t))},nonnegative(t){return this.check(xo(BigInt(0),t))},multipleOf(t,e){return this.check(Oc(t,e))}}));function ZZ(t){return l0(af,t)}var sE=$("ZodBigIntFormat",(t,e)=>{ix.init(t,e),af.init(t,e)});function WZ(t){return d0(sE,t)}function JZ(t){return p0(sE,t)}var ZM=$("ZodSymbol",(t,e)=>{sx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Qz(t,r,o,n)});function XZ(t){return f0(ZM,t)}var WM=$("ZodUndefined",(t,e)=>{ax.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tM(t,r,o,n)});function YZ(t){return m0(WM,t)}var JM=$("ZodNull",(t,e)=>{cx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eM(t,r,o,n)});function ny(t){return h0(JM,t)}var XM=$("ZodAny",(t,e)=>{ux.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oM(t,r,o,n)});function QZ(){return g0(XM)}var YM=$("ZodUnknown",(t,e)=>{lx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iM(t,r,o,n)});function Lt(){return y0(YM)}var QM=$("ZodNever",(t,e)=>{dx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nM(t,r,o,n)});function aE(t){return v0(QM,t)}var eU=$("ZodVoid",(t,e)=>{px.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rM(t,r,o,n)});function eW(t){return w0(eU,t)}var oy=$("ZodDate",(t,e)=>{fx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sM(t,r,o,n),t.min=(r,o)=>t.check(xo(r,o)),t.max=(r,o)=>t.check(So(r,o))},D.derived({minDate:t=>{let{minimum:e}=Pr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Pr(t);return e?new Date(e):null}},{}));function tW(t){return _0(oy,t)}var tU=$("ZodArray",(t,e)=>{ql(),mx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ua(t,e))},nonempty(t){return this.check(Ua(1,t))},max(t,e){return this.check(Ll(t,e))},length(t,e){return this.check(jl(t,e))},unwrap(){return this.element}});function Fe(t,e){return Gz(tU,t,e)}function rW(t){let e=t._zod.def.shape;return Jr(Object.keys(e))}var iy=$("ZodObject",(t,e)=>{ql(),Rz.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Jr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Lt()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Lt()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:aE()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return D.extend(this,t)},safeExtend(t){return D.safeExtend(this,t)},merge(t){return D.merge(this,t)},pick(t){return D.pick(this,t)},omit(t){return D.omit(this,t)},partial(...t){return D.partial(Hl,this,t[0])},exactPartial(...t){return D.partial(uE,this,t[0],"exactPartial")},required(...t){return D.required(lE,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new iy(r)}function nW(t,e){return new iy({type:"object",shape:t,catchall:aE(),...D.normalizeParams(e)})}function Wr(t,e){return new iy({type:"object",shape:t,catchall:Lt(),...D.normalizeParams(e)})}var sy=$("ZodUnion",(t,e)=>{Tp.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.options=e.options});function Pt(t,e){return new sy({type:"union",options:t,...D.normalizeParams(e)})}var rU=$("ZodXor",(t,e)=>{sy.init(t,e),gx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.options=e.options});function oW(t,e){return new rU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var nU=$("ZodDiscriminatedUnion",(t,e)=>{sy.init(t,e),yx.init(t,e)});function ay(t,e,r){return new nU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var oU=$("ZodIntersection",(t,e)=>{vx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n)});function cf(t,e){return new oU({type:"intersection",left:t,right:e})}var iU=$("ZodTuple",(t,e)=>{ql(),bg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Hl({type:"optional",innerType:e}))})}});function sU(t,e,r){let o=e instanceof _e,n=o?r:e,i=o?e:null;return new iU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var tf=$("ZodRecord",(t,e)=>{ql(),wx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Dt(t,e,r){return!e||!e._zod?new tf({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new tf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function iW(t,e,r){return new tf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function sW(t,e,r){return new tf({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var aU=$("ZodMap",(t,e)=>{ql(),_x.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(As(...r)),t.nonempty=r=>t.check(As(1,r)),t.max=(...r)=>t.check(Dc(...r)),t.size=(...r)=>t.check(Ul(...r))});function aW(t,e,r){return new aU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var cU=$("ZodSet",(t,e)=>{ql(),bx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n),t.min=(...r)=>t.check(As(...r)),t.nonempty=r=>t.check(As(1,r)),t.max=(...r)=>t.check(Dc(...r)),t.size=(...r)=>t.check(Ul(...r))});function cW(t,e){return new cU({type:"set",valueType:t,...D.normalizeParams(e)})}var rf=$("ZodEnum",(t,e)=>{Sx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(o,n,i)=>aM(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new rf({...e,checks:[],...D.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new rf({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Jr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new rf({type:"enum",entries:r,...D.normalizeParams(e)})}function uW(t,e){return new rf({type:"enum",entries:t,...D.normalizeParams(e)})}var uU=$("ZodLiteral",(t,e)=>{xx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function se(t,e){return new uU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var lU=$("ZodFile",(t,e)=>{Ex.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n),t.min=(r,o)=>t.check(As(r,o)),t.max=(r,o)=>t.check(Dc(r,o)),t.mime=(r,o)=>t.check(Bp(Array.isArray(r)?r:[r],o))});function lW(t){return I0(lU,t)}var dU=$("ZodTransform",(t,e)=>{ql(),$x.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Tc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(D.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(D.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function cE(t){return new dU({type:"transform",transform:t})}var Hl=$("ZodOptional",(t,e)=>{Sg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>z0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Ct(t){return new Hl({type:"optional",innerType:t})}var uE=$("ZodExactOptional",(t,e)=>{Rx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>z0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pU(t){return new uE({type:"optional",innerType:t})}var fU=$("ZodNullable",(t,e)=>{Ix.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ty(t){return new fU({type:"nullable",innerType:t})}function dW(t){return Ct(ty(t))}var mU=$("ZodDefault",(t,e)=>{Ax.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function hU(t,e){return new mU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var gU=$("ZodPrefault",(t,e)=>{Px.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yU(t,e){return new gU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var lE=$("ZodNonOptional",(t,e)=>{kx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function vU(t,e){return new lE({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var wU=$("ZodSuccess",(t,e)=>{Tx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pW(t){return new wU({type:"success",innerType:t})}var _U=$("ZodCatch",(t,e)=>{Cx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function bU(t,e){return new _U({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var SU=$("ZodNaN",(t,e)=>{Ox.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n)});function fW(t){return b0(SU,t)}var cy=$("ZodPipe",(t,e)=>{xg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n),t.in=e.in,t.out=e.out});function F0(t,e){return new cy({type:"pipe",in:t,out:e})}var uy=$("ZodCodec",(t,e)=>{cy.init(t,e),Cp.init(t,e)});function mW(t,e,r){return new uy({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function hW(t){let e=t._zod.def;return new uy({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var xU=$("ZodPreprocess",(t,e)=>{cy.init(t,e),Az.init(t,e)}),EU=$("ZodReadonly",(t,e)=>{Dx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function $U(t){return new EU({type:"readonly",innerType:t})}var RU=$("ZodTemplateLiteral",(t,e)=>{Nx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n)});function gW(t,e){return new RU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var IU=$("ZodLazy",(t,e)=>{Op.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function AU(t){return new IU({type:"lazy",getter:t})}var PU=$("ZodPromise",(t,e)=>{Mx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yW(t){return new PU({type:"promise",innerType:t})}var kU=$("ZodFunction",(t,e)=>{zx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n)});function vW(t){return new kU({type:"function",input:Array.isArray(t?.input)?sU(t?.input):t?.input??Fe(Lt()),output:t?.output??Lt()})}var ly=$("ZodCustom",(t,e)=>{Ux.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fM(t,r,o,n)});function wW(t){let e=new Tt({check:"custom"});return e._zod.check=t,e}function dE(t,e){return A0(ly,t??(()=>!0),e)}function TU(t,e={}){return P0(ly,t,e)}function CU(t,e){return k0(t,e)}var _W=T0,bW=C0,OU=$("ZodInstanceOf",(t,e)=>{ly.init(t,e)},{properties(t,e){return this.check(Hp(t,e))}});function SW(t,e={}){let r=new OU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...D.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var xW=(...t)=>O0({Codec:uy,Boolean:sf,String:nf},...t);function EW(t){let e=AU(()=>Pt([O(t),yt(),hr(),ny(),Fe(e),Dt(O(),e)]));return e}function dy(t,e){return new xU({type:"pipe",in:cE(t),out:e})}var kCe={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function TCe(t){cr({customError:t})}function CCe(){return cr().customError}var DU;DU||(DU={});var Bl={};Ht(Bl,{ZodISODate:()=>jc,ZodISODateTime:()=>Lc,ZodISODuration:()=>qc,ZodISOTime:()=>Fc,date:()=>DCe,datetime:()=>OCe,duration:()=>zCe,time:()=>NCe});function OCe(t){return Wg(Lc,t)}function DCe(t){return Jg(jc,t)}function NCe(t){return Xg(Fc,t)}function zCe(t){return Yg(qc,t)}var W={...uf,...U0,iso:Bl},MCe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function UCe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function $W(t,e){return t.map((r,o)=>o<e?r:r.optional())}function LCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jCe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:LCe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function FCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function NU(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=NU(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=NU(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var qCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),VCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function py(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(py):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>qCe.has(e)?py(r):!VCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(py))}function RW(t){return t===1?"element":"elements"}function GCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=NU(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${RW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${RW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function IW(t,e){if(t!==!1)return t===void 0||t===!0?W.any():qn(t,e)}var HCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function AW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return W.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=jCe(n,e),s=qn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return W.null();if(n.length===0)return W.never();if(n.length===1)return W.literal(n[0]);if(n.every(s=>typeof s=="string"))return W.enum(n);let i=n.map(s=>W.literal(s));return i.length<2?i[0]:W.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return W.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return AW(s,e)});return n.length===0?W.never():n.length===1?n[0]:W.union(n)}if(!r)return W.any();let o;switch(r){case"string":{let n=W.string();if(t.format){let i=t.format;i==="email"?n=n.check(W.email()):i==="uri"||i==="uri-reference"?n=n.check(W.url()):i==="uuid"||i==="guid"?n=n.check(W.uuid()):i==="date-time"?n=n.check(W.iso.datetime({offset:!0})):i==="date"?n=n.check(W.iso.date()):i==="time"?n=n.check(W.regex(HCe)):i==="duration"?n=n.check(W.iso.duration()):i==="hostname"?n=n.check(W.hostname()):i==="ipv4"?n=n.check(W.ipv4()):i==="ipv6"?n=n.check(W.ipv6()):i==="mac"?n=n.check(W.mac()):i==="cidr"?n=n.check(W.cidrv4()):i==="cidr-v6"?n=n.check(W.cidrv6()):i==="base64"?n=n.check(W.base64()):i==="base64url"?n=n.check(W.base64url()):i==="e164"?n=n.check(W.e164()):i==="credit_card"?n=n.check(W.creditCard()):i==="iban"?n=n.check(W.iban()):i==="jwt"?n=n.check(W.jwt()):i==="emoji"?n=n.check(W.emoji()):i==="nanoid"?n=n.check(W.nanoid()):i==="cuid"?n=n.check(W.cuid()):i==="cuid2"?n=n.check(W.cuid2()):i==="ulid"?n=n.check(W.ulid()):i==="xid"?n=n.check(W.xid()):i==="ksuid"&&(n=n.check(W.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?W.number().int():W.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=W.boolean();break}case"null":{o=W.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?qn(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=qn(p,e);Kr(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let y of p){let w=qn(d[y],e),b=W.string().regex(new RegExp(y));f.push(W.looseRecord(b,w))}let m=[];if(Object.keys(n).length>0&&m.push(W.object(n).passthrough()),m.push(...f),m.length===0)o=W.object({}).passthrough();else if(m.length===1)o=m[0];else{let y=W.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)y=W.intersection(y,m[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=p.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Wo(S.value))return;let x=[];for(let I of Object.keys(S.value))y.includes(I)||w.some(T=>T.test(I))||x.push(I);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=W.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=qn(p,e)}o=FCe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>qn(d,e)),c=$W(a,s),u=Array.isArray(i)?void 0:IW(i,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>qn(d,e)),c=$W(a,s),u=IW(t.additionalItems,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(i!==void 0){let s=qn(i,e),a=W.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=W.array(W.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=GCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?qn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function qn(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r=AW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>qn(u,e)),c=W.union(a);r=o?W.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>qn(u,e)),c=W.xor(a);r=o?W.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:W.any();else{let a=o?r:qn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=W.intersection(a,qn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=W.nullable(r)),t.readOnly===!0&&(r=W.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!py(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!py(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))MCe.has(a)||Kr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function PW(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=UCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Zr};return qn(r,i)}var kW=Symbol("z.visit/resolving");function fy(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===kW)return new Op({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,kW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let y=n(u[m]);y!==u[m]&&(d=!0),p[m]=y}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function TW(t){return fy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:Pt(r.options)}})}function BCe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Zo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function CW(t){return BCe(t.out,t.checks)}function KCe(t){return t.in._zod.traits.has("$ZodTransform")?CW(t):t.in}function OW(t){return fy(t,{pipe:e=>KCe(e._zod.def),default:(e,r)=>r?Ct(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function DW(t){return fy(t,{pipe:e=>CW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var zU={};Ht(zU,{bigint:()=>XCe,boolean:()=>JCe,date:()=>YCe,number:()=>WCe,string:()=>ZCe});function ZCe(t){return Uz(nf,t)}function WCe(t){return jz(of,t)}function JCe(t){return Fz(sf,t)}function XCe(t){return qz(af,t)}function YCe(t){return Vz(oy,t)}var my={name:"@tomato414941/foundation",version:"10.0.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&h.config({jitless:!0});function eOe(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var hy=h.string().trim().max(8192).refine(t=>eOe(t)!==null,"Use an OpenSSH public key from a .pub file."),gy=h.object({authorizedKeys:h.array(hy).max(32)}).strict(),zgt=gy.extend({revision:h.number().int().positive().optional()}),MU=gy.extend({host:h.string().min(1).max(253).nullable(),port:h.number().int().min(1).max(65535),username:h.literal("root"),workingDirectory:h.literal("/workspace"),hostKey:hy.nullable(),fingerprint:h.string().nullable(),revision:h.number().int().positive(),appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),Mgt=MU.extend({state:h.enum(["starting","configuring","ready","disabled","stopped"])}),Ugt=h.object({hostKey:hy,appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),tOe=gy.extend({port:h.number().int().min(1).max(65535),revision:h.number().int().positive()}).strict(),pE=h.object({configuration:tOe.nullable()}).strict();var lf=new TextEncoder,df=new TextDecoder,NW=new TextDecoder("utf-8",{fatal:!0}),fE=2**32;function Vn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function UU(t,e,r){if(e<0||e>=fE)throw new RangeError(`value must be >= 0 and <= ${fE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function LU(t){let e=Math.floor(t/fE),r=t%fE,o=new Uint8Array(8);return UU(o,e,0),UU(o,r,4),o}function mE(t){let e=new Uint8Array(4);return UU(e,t),e}var rOe=/[^\x00-\x7f]/;function Xr(t){if(typeof t=="string"&&t.length>=128){if(rOe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return lf.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function zW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function MW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function hE(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var La=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Kl=class extends La{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Nt=class extends La{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Vc=class extends La{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends La{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Xt=class extends La{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var yy=class extends La{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var gE=class extends La{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var nOe="The input to be decoded is not correctly encoded.";function Zl(t){try{return MW(typeof t=="string"?t:df.decode(t),!0)}catch(e){throw new TypeError(nOe,{cause:e})}}function nr(t){return zW(typeof t=="string"?lf.encode(t):t,!0)}function Eo(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function wr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Gc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Xo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function so(t,e,r){try{return Zl(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function yE(t,e,r){try{return Xr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function pf(t,e,r){let o;try{o=JSON.parse(NW.decode(Zl(t)))}catch{throw new e(r)}if(!wr(o))throw new e(r);return o}var vE={__proto__:null,b64:!0},wE={__proto__:null};function vy(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function _E(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Hc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Nt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function bE(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Wl(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!wr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var oOe=t=>t[Symbol.toStringTag],iOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Di(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(wr(e)){if(s=HU(e),typeof s.kty!="string")throw UW(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(iOe(t,s,r),s.kty==="oct")return Zl(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!qU(e))throw UW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${oOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Bc(e))return e;if(a=e,a.type==="secret")return a.export()}jU||=new WeakMap;let c=e,u=jU.get(c);if(u?.[o])return u[o];if(u||jU.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=sOe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await mf(t,s)}var jU,sOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function xE(t){if(!Bc(t))throw new Error("CryptoKey instance expected")}var Bc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},FU=t=>t?.[Symbol.toStringTag]==="KeyObject",qU=t=>Bc(t)||FU(t);function LW(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var ja=(t,...e)=>LW("Key must be ",t,...e);function UW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(LW(`Key for the ${t} algorithm must be `,e,...o))}var SE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function VU(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function ff(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function GU(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw SE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw SE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw SE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw SE(e.length,"algorithm.length");VU(t,r)}function EE(t){return{__proto__:null,...t}}function HU(t){let e=EE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function $E(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function mf(t,e,r){if(!t.kty.includes(e.kty))throw new Nt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Ni(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),GU(t,e,r),t}var Jl=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function RE(t,e){let r=t.byteLength<<3;if(r!==e)throw new H(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var aOe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function jW(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function FW(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(ja(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function qW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function cOe(t,e,r,o,n){let[i,s,a]=await FW(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Vn(n,o,c,LU(n.length*8)),l=await qW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function uOe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function lOe(t,e,r,o,n,i){let[s,a,c]=await FW(t,e,"decrypt"),u=Vn(i,o,r,LU(i.length*8)),l=await qW(a,u,c);try{if(await uOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Vc}async function IE(t,e,r,o,n){if(!Bc(r)&&!(r instanceof Uint8Array))throw new TypeError(ja(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?jW(t,o):o=aOe(t),r instanceof Uint8Array&&RE(r,t.cekBits),t.cbc)return cOe(t,e,r,o,n);let i=await Ni(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function AE(t,e,r,o,n,i){if(!Bc(e)&&!(e instanceof Uint8Array))throw new TypeError(ja(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new H("JWE Initialization Vector missing");if(!n)throw new H("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new H("Invalid Authentication Tag length");if(jW(t,o),e instanceof Uint8Array&&RE(e,t.cekBits),t.cbc)return lOe(t,e,r,o,n,i);let s=await Ni(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Vn(r,n)))}catch{throw new Vc}}function wy(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var dOe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],pOe=[[],["deriveBits"]],TE=[[],[]];function PE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:dOe,ops:["wrapKey","unwrapKey"]}}function kE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Nt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:pOe,ops:[void 0,"deriveBits"]}}function hf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:TE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function BU(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:TE,ops:["deriveBits","deriveBits"]}}var Fa=wy({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:TE,ops:["encrypt","decrypt"]},"RSA-OAEP":PE(1),"RSA-OAEP-256":PE(256),"RSA-OAEP-384":PE(384),"RSA-OAEP-512":PE(512),"ECDH-ES":kE("direct-key-agreement"),"ECDH-ES+A128KW":kE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":kE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":kE("key-agreement-with-key-wrapping"),A128KW:hf(128),A192KW:hf(192),A256KW:hf(256),A128GCMKW:hf(128,!0),A192GCMKW:hf(192,!0),A256GCMKW:hf(256,!0),"PBES2-HS256+A128KW":BU(),"PBES2-HS384+A192KW":BU(),"PBES2-HS512+A256KW":BU()}),fOe=["encrypt","decrypt"];function gf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:TE,ops:fOe,cekBits:t,ivBits:e?128:96,cbc:e}}var mOe=wy({A128GCM:gf(128),A192GCM:gf(192),A256GCM:gf(256),"A128CBC-HS256":gf(256,!0),"A192CBC-HS384":gf(384,!0),"A256CBC-HS512":gf(512,!0)});function VW(t,e){throw new Nt(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function zi(t){return(typeof t=="string"?Fa[t]:void 0)??VW("alg","Algorithm")}function Mi(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function Xl(t){return(typeof t=="string"?mOe[t]:void 0)??VW("enc","Encryption Algorithm")}function GW(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");VU(t,e)}async function hOe(t,e,r){let o=await Ni(e,zi(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function gOe(t,e,r){let o=await Ni(e,zi(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function BW(t,e,r){GU(e,zi(t).subtle,r),ff(t,e)}async function KW(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new H("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new H("PBES2 Count Input must be a positive integer");let n=Vn(Xr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Ni(o,zi(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KU(t){return Vn(mE(t.length),t)}async function yOe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await hE("sha256",Vn(mE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function ZW(t,e,r,o,n=new Uint8Array,i=new Uint8Array){GW(t),GW(e,"deriveBits");let s=Vn(KU(Xr(r)),KU(n),KU(i),mE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return yOe(a,o,s)}function WW(t){xE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Nt("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function CE(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new H(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return so(r,e,H)}}function JW(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new H('JOSE Header "apu" and "apv" values must be distinct')}}function vOe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function HW(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function wOe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function XW(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return HW(o),r;let c=a==="direct-key-agreement";switch(c?HW(o):vOe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!wr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');WW(r);let l=await mf(t,u),d=CE(n,"apu"),p=CE(n,"apv");JW(d,p);let f=await ZW(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return xE(r),BW(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new H('JOSE Header "p2c" (PBES2 Count) missing or invalid');wOe(i);let u=i??1e4;if(n.p2c>u)throw new H('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new H('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=so(n.p2s,"p2s",H);r=await KW(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new H('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new H('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=so(n.iv,"iv",H),l=so(n.tag,"tag",H);if(u.byteLength!==12)throw new H("Invalid Initialization Vector length");if(l.byteLength!==16)throw new H("Invalid Authentication Tag length");return AE(Xl(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return gOe(s.slice(-6),r,o)}async function OE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Mi(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Di(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Jl(e):void 0;l&&RE(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{WW(u);let{apu:f,apv:m}=i;f!==void 0&&Eo(f,'"apu"'),m!==void 0&&Eo(m,'"apv"');let y=f??CE(o,"apu"),w=m??CE(o,"apv");JW(y,w);let b;i.epk!==void 0?b=await Di(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:I,y:T,crv:M,kty:J}=await S.exportKey("jwk",x),le=a==="direct-key-agreement",Le=await ZW(u,b,le?e.alg:s,le?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),ze={x:I,crv:M,kty:J};if(J==="EC"&&(ze.y=T),p={epk:ze},f!==void 0&&(p.apu=nr(f)),m!==void 0&&(p.apv=nr(m)),le)return[Le,void 0,p];u=Le;break}case"RSA-OAEP":{xE(u),BW(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await KW(m,s,f,u),p={p2c:f,p2s:nr(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await IE(Xl(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:nr(m.iv),tag:nr(m.tag)}}}if(d??=await hOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function DE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Nt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function YW(t){if(typeof globalThis[t]>"u")throw new Nt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function QW(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new H("Decompressed plaintext exceeded the configured limit")}return Vn(...n)}async function e5(t){return YW("CompressionStream"),QW(new CompressionStream("deflate-raw"),t)}async function t5(t,e){return YW("DecompressionStream"),QW(new DecompressionStream("deflate-raw"),t,e)}function r5(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new H("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new H("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new H("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new H("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new H("JWE AAD incorrect type");if(s!==void 0&&!wr(s))throw new H("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function n5(t){let e,r;try{let{header:o}=t;if(wr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function o5(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new H("JWE Encrypted Key incorrect type");if(r!==void 0&&!wr(r))throw new H("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new H("JOSE Header missing")}function ZU(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=pf(e,H,"JWE Protected Header is invalid")),[s,so(r,"ciphertext",H),o!==void 0?so(o,"iv",H):void 0,n!==void 0?so(n,"tag",H):void 0,yE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function NE(t){return[t&&vy("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&vy("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function WU(t,e,r,o=ZU(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Gc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,y,w,b]=e,{encrypted_key:S}=t;Hc(H,wE,y,n,p),DE(p,n);let{alg:x,enc:I}=p;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Fa[x];if(S===""&&(!T||!Mi(T)))throw new H("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof I!="string"||!I))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new Kl('"alg" (Algorithm) Header Parameter value not allowed');let J;if(M){if(I!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new H("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new H("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(I))throw new Kl('"enc" (Encryption Algorithm) Header Parameter value not allowed');J=Xl(I)}let le;if(S!==void 0)try{le=so(S,"encrypted_key",H)}catch(je){if(!T||!Mi(T))throw je;le=new Uint8Array}let Le=!1;typeof r=="function"&&(r=await r(n,t),Le=!0);let ze=T??zi(x);Mi(ze)&&le===void 0&&(le=new Uint8Array);let It=await Di(ze.mode==="direct-encryption"?J:ze,r,"decrypt"),lt;if(ze.mode==="integrated-encryption")lt=await ze.decrypt(It,le,i,c,n,p);else{let je=J,ie;try{ie=await XW(ze,je,It,le,p,w),Mi(ze)&&ie instanceof Uint8Array&&ie.byteLength<<3!==je.cekBits&&(ie=Jl(je))}catch(tr){if(tr instanceof TypeError||tr instanceof H||tr instanceof Nt)throw tr;ie=Jl(je)}lt=await AE(je,ie,i,s,a,c)}if(p.zip==="DEF"){let je=b??25e4;if(je===0)throw new Nt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(je!==1/0&&(!Number.isSafeInteger(je)||je<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");lt=await t5(lt,je).catch(ie=>{throw ie instanceof H?ie:new H("Failed to decompress plaintext",{cause:ie})})}return{plaintext:lt,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:so(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Le&&{key:It}}}async function i5(t,e,r){if(t instanceof Uint8Array&&(t=df.decode(t)),typeof t!="string")throw new H("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new H("Invalid Compact JWE");return WU({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function _y(t,e,r){return i5(t,NE(r),e)}async function JU(t,e,r){if(!wr(t))throw new H("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new H("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(wr))throw new H("JWE Recipients missing or incorrect type");if(!n.length)throw new H("JWE Recipients has no members");let i,s,a;try{i=NE(r),s=r5(t),a=ZU(s)}catch{throw new Vc}let c=n.map(u=>n5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Fa[l]:void 0;if(d&&!Mi(d))throw new H(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return o5(l),await WU(l,i,e,a)}catch{}throw new Vc}function zE(t,e,r){if(!Gc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function XU(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new H("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Eo(s,"JWE Additional Authenticated Data"),a!==void 0&&Eo(a,"JWE Content Encryption Key"),c!==void 0&&Eo(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Wl(H,o)[0],t[1]=o),n!==void 0&&(n=Wl(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=Wl(H,i)[0],t[3]=i),u!==void 0&&!wr(u))throw new TypeError("JWE Key Management Parameters must be an object");zE(o,n,i);let d={...o,...n,...i};_E(H,o),Hc(H,wE,l,o,d),DE(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Fa[p];if(m?.mode==="integrated-encryption"){if(f!==void 0)throw new H('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 ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,Xl(f),m]}async function YU(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,m]=t,y=a,w=c,b=i??zi(o.alg),S,x,I;b.mode==="integrated-encryption"?I=await Di(b,r,"encrypt"):[I,S,x]=await OE(b,n,r,o,d,f),x&&(m?w=w?{...w,...x}:x:y=y?{...y,...x}:x,zE(y,w,u));let T=y?nr(JSON.stringify(y)):"",M=l?.byteLength?nr(l):void 0,J=Xr(M?`${T}.${M}`:T),le=s;o.zip==="DEF"&&(le=await e5(le).catch(je=>{throw new H("Failed to compress plaintext",{cause:je})}));let Le,ze,It;b.mode==="integrated-encryption"?[S,Le]=await b.encrypt(I,le,J,y,o,f):{ciphertext:Le,tag:ze,iv:It}=await IE(n,le,I,p,J);let lt={ciphertext:nr(Le)};return It&&(lt.iv=nr(It)),ze&&(lt.tag=nr(ze)),S?.byteLength&&(lt.encrypted_key=nr(S)),M&&(lt.aad=M),y&&(lt.protected=T),u&&(lt.unprotected=u),w&&(lt.header=w),lt}async function s5(t,e,r){return YU(t,XU(t,r),e)}function a5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var QU=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Xo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Xo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},by=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new QU(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Xo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Xo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new H("at least one recipient must be added");Eo(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[y,w,b,S]=m.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],I=XU(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,I,b]);let[{alg:T,enc:M},,J]=I;if(e&&J&&!Mi(J))throw new H(`"${T}" alg may only have a single recipient`);if(!r)r=M;else if(r!==M)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=zi(m[0].alg);let[s,a,c]=i[0],u=e?Jl(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await YU(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[y,[w,b,S],x]=i[m],I=y[2],[,T,M]=await OE(S,b,x,w,u,y[7]),J={encrypted_key:nr(T)};if(I||M){let le={...I,...M};M&&zE(y[1],le,y[3]),J.header=le}f.recipients.push(J)}return f}};var Sy=[["verify"],["sign"]];function eL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Sy}}function yf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:Sy,minRsaBits:2048}}function tL(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Sy}}function c5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Sy}}function rL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Sy}}var nL=wy({HS256:eL(256),HS384:eL(384),HS512:eL(512),RS256:yf(256),RS384:yf(384),RS512:yf(512),PS256:yf(256,32),PS384:yf(384,48),PS512:yf(512,64),ES256:tL("P-256",256),ES384:tL("P-384",384),ES512:tL("P-521",512),EdDSA:c5(),Ed25519:c5(),"ML-DSA-44":rL(44),"ML-DSA-65":rL(65),"ML-DSA-87":rL(87)});function ME(t){let e=typeof t=="string"?nL[t]:void 0;if(!e)throw new Nt(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function u5(t){return[t&&vy("algorithms",t.algorithms),t?.crit]}function _Oe(t){return t===void 0?{}:pf(t,Xt,"JWS Protected Header is invalid")}function bOe(t){try{return Xr(t)}catch{throw new Xt("JWS Compact Serialization payload must use only ASCII characters")}}async function SOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??_Oe(i);if(!Gc(c,s))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=bE(c,Hc(Xt,vE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new Kl('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Xt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let m=ME(d),y=Vn(i!==void 0?Xr(i):new Uint8Array,Xr("."),typeof p=="string"?e[2]??=yE(p,"payload",Xt):p),w=so(t.signature,"signature",Xt),b=await Di(m,r,"verify"),S=await Ni(b,m.subtle,"verify");m.minRsaBits&&ff(m.alg,S);let x=!1;try{x=await crypto.subtle.verify(m.signing,S,w,y)}catch{}if(!x)throw new gE;let I={payload:typeof p=="string"?so(p,"payload",Xt):p};return i!==void 0&&(I.protectedHeader=c),s!==void 0&&(I.unprotectedHeader=s),f?[{...I,key:b},l]:[I,l]}async function l5(t,e,r){if(t instanceof Uint8Array&&(t=df.decode(t)),typeof t!="string")throw new Xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Xt("Invalid Compact JWS");return SOe({payload:n,protected:o,signature:i},e,r,bOe)}async function oL(t,e,r){let[o]=await l5(t,u5(r),e);return o}var vf=class{#e;constructor(e){Eo(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Xo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Xo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Xo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Xo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return a5(await s5([...this.#e],e,r))}};async function xOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=Wl(Xt,n);n=b[0],a=nr(b[1])}if(i!==void 0&&(i=Wl(Xt,i)[0]),!n&&!i)throw new Xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Gc(n,i))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};_E(Xt,n);let u=bE(n,Hc(Xt,vE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=ME(l),p="",f=o,m;if(u){let b=t[4];b?(p=b[0]??=nr(o),f=b[1]??=Xr(p)):(p=nr(o),m=lf.encode(`${a}.${p}`))}m??=Vn(Xr(a),Xr("."),f);let y=await Ni(await Di(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&ff(d.alg,y);let w={signature:nr(new Uint8Array(await crypto.subtle.sign(d.signing,y,m))),payload:p};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function d5(t,e,r,o,n){let[i]=await xOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var xy=class{#e;#t;constructor(e){Eo(e,"payload"),this.#e=e}setProtectedHeader(e){return Xo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return d5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var iL='"alg" (Algorithm)';function sL(t='JWK "alg" (Algorithm) Parameter'){throw new Nt(`Invalid or unsupported ${t} value`)}function Ey(t,e){return(typeof t=="string"?nL[t]??Fa[t]:void 0)??sL(e)}async function Kc(t){if(FU(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:nr(t)};if(!Bc(t))throw new TypeError(ja(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var qa=(t,e)=>{if(typeof t!="string"||!t)throw new yy(`${e} missing or invalid`)};async function aL(t,e){let r;if(wr(t)){if(r=EE(t),typeof r.kty!="string")throw new TypeError(ja(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(qU(t))r=EE(await Kc(t));else throw new TypeError(ja(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":qa(r.alg,'"alg" (Algorithm) Parameter'),qa(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":qa(r.crv,'"crv" (Curve) Parameter'),qa(r.x,'"x" (X Coordinate) Parameter'),qa(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":qa(r.crv,'"crv" (Subtype of Key Pair) Parameter'),qa(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":qa(r.e,'"e" (Exponent) Parameter'),qa(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new yy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Nt('"kty" (Key Type) Parameter missing or unsupported')}let n=Xr(JSON.stringify(o));return nr(await hE(e,n))}async function Yo(t,e,r){if(!wr(t))throw new TypeError("JWK must be an object");let o=HU(t),n=$E(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return Zl(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return mf(Ey(e),o,n)}case"RSA":case"EC":case"OKP":return mf(Ey(e),o,n);default:throw new Nt('Unsupported "kty" (Key Type) Parameter value')}}function cL(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return pf(e,TypeError,r)}function EOe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Nt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function $y(t,e){let r=$E(e?.extractable),o=Ey(t,iL);o.secret&&sL(iL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Nt("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Nt(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:EOe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var h5=h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),g5=h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),p5=h.string().min(1).max(128),f5=h.string().min(1).max(16384),$Oe=h.discriminatedUnion("kind",[h.object({kind:h.literal("access_key"),accessKeyId:p5,secretAccessKey:f5}).strict(),h.object({kind:h.literal("session"),accessKeyId:p5,secretAccessKey:f5,sessionToken:h.string().min(1).max(16384),expiresAt:h.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),h.object({kind:h.literal("environment")}).strict()]),ROe=h.object({arn:g5,externalId:h.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Va=h.object({authentication:$Oe,region:h5,role:ROe.optional()}).strict(),UE=h.object({accountId:h.string().regex(/^\d{12}$/),principalId:h.string().min(1).max(256),arn:h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),LE=Va.extend({sourceIdentity:UE,identity:UE}).strict();function wf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function m5(t){return{...t,arn:wf(t.arn)}}function y5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,sourceIdentity:m5(t.sourceIdentity),identity:m5(t.identity)}}var jE=h.object({authentication:h.enum(["access_key","session","environment"]),region:h5,sourceAccountId:h.string().regex(/^\d{12}$/),sourceArn:h.string().max(2e3),roleArn:g5.optional(),expiresAt:h.number().int().positive().optional()}).strict();function v5(t){return{authentication:t.authentication.kind,region:t.region,sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn,...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}typeof window<"u"&&h.config({jitless:!0});var E=h.uuid(),fe=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Ie=h.iso.datetime(),_r=h.json(),bt=h.record(h.string(),_r),_5=h.enum(["ja","en"]),b5=h.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var S5=h.enum(["variable","connection","service","method","app","object","environment","function"]),bn=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),IOe=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:E}).strict(),qE=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return IOe.safeParse(cL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),$o=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:E,epk:bn.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),ywt=h.object({id:E,name:fe,publicKey:bn}),Zc=h.object({id:E,name:fe,owner:h.object({id:E,name:fe}).nullable(),createdAt:Ie,permissions:h.array(b5),createKinds:h.array(S5),publicKey:bn.nullable()}),x5=h.object({id:E,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:Ie,lastUsedAt:Ie.nullable(),expiresAt:Ie.nullable(),canOpen:h.boolean()}),E5=h.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),AOe=h.object({subjectId:E,relation:E5,objectId:E}).strict(),vwt=AOe.extend({objectType:h.enum(["principal",...S5.options]),subjectName:fe,objectName:fe,createdAt:Ie}),wwt=h.object({error:h.object({code:h.string(),message:h.string(),details:_r.optional()})}),_wt=h.object({ok:h.literal(!0)}),POe=h.object({value:h.string().min(1).max(200),label:h.string().min(1).max(200),values:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).default({})}).strict(),$5=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional(),choices:h.array(POe).min(1).max(100).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),R5=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),kOe=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),required:h.array(h.string()).optional(),separator:h.string().default(" "),docs:h.url().optional()}),Ry=h.string().min(1).max(4096),w5=h.union([h.string(),h.array(h.string()).min(1)]),TOe=h.object({application:h.enum(["required","implicit"]).default("required"),grantType:h.enum(["authorization_code","client_credentials"]).optional(),issuer:h.url().optional(),authorizeUrl:Ry.optional(),tokenUrl:Ry,identity:h.object({url:Ry.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:w5.default("/id"),name:w5.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),revoke:h.object({url:Ry,style:h.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:h.enum(["body","basic","none"]).optional()}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:kOe.default({default:[],separator:" "}),fields:h.array($5).default([]),outputs:R5.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),COe=h.object({fields:h.array($5).min(1),outputs:R5,console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}),lL=h.enum(["oauth","token","aws"]),OOe=h.object({hint:h.string().optional()}).strict(),dL={name:fe,docs:h.url().optional(),console:Ry.optional()},VE=h.object({...dL,kind:h.literal("oauth"),config:TOe}).strict(),GE=h.object({...dL,kind:h.literal("token"),config:COe}).strict(),HE=h.object({...dL,kind:h.literal("aws"),config:OOe}).strict(),Yl=h.discriminatedUnion("kind",[VE,GE,HE]),uL={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"])},Iy=h.discriminatedUnion("kind",[VE.extend(uL),GE.extend(uL),HE.extend(uL)]),pL=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),fL=h.object({name:fe,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional()}).strict(),DOe=fL.extend({methods:h.record(pL,h.string().min(1))}).strict(),I5=fL.extend({methods:h.record(pL,h.union([h.string().min(1),Yl]))}).strict(),bwt=fL.extend({id:h.string(),builtin:h.boolean(),methods:h.record(pL,Iy)}),A5=h.object({id:E,output:h.string().min(1).max(100).optional()}).strict(),P5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),mL=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:A5,format:h.enum(["text","file","json"]).default("text"),pointer:h.string().optional()}).strict(),NOe=h.object({pointer:h.string().max(500),parts:h.array(h.union([h.string().max(8192),A5])).min(1).max(32)}).strict(),Ga=h.object({url:h.string().max(4096),method:h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:h.record(h.string(),h.string().max(8192)).default({}),body:h.string().max(1e6).optional(),json:_r.optional(),form:h.record(h.string(),h.string()).optional(),bindings:h.array(NOe).max(32).default([])}).strict(),Ha=h.object({command:h.array(h.string().max(8192)).min(1).max(100),stdin:h.string().max(1e6).optional(),timeoutSeconds:h.number().int().min(1).max(3600).default(60),inputs:h.array(mL).max(32).default([])}).strict(),k5=h.discriminatedUnion("kind",[Ha.omit({stdin:!0}).extend({kind:h.literal("command")}).strict(),h.object({kind:h.literal("http"),request:Ga}).strict()]),Qo=h.object({description:h.string().max(2e3).default(""),environmentId:E,program:k5,parameters:h.array(h.object({name:h.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:h.string().max(100),type:h.enum(["string","number","boolean","json"]).default("string"),required:h.boolean().default(!0),default:_r.optional()}).strict()).max(32).default([]),result:h.enum(["text","json"]).default("json")}).strict(),Wc={id:E,ownerId:E,name:fe,createdAt:Ie,updatedAt:Ie,version:h.number().int().positive(),permissions:h.array(b5)},zOe=h.enum(["starting","running","stopping","stopped","failed"]),MOe=h.object({state:h.enum(["pending","failed","complete"]),error:h.string().nullable()}),UOe=h.object({idleSeconds:h.number().int().min(60).max(86400).default(3600),maxSeconds:h.number().int().min(60).max(86400).default(3600)}).strict(),T5=h.object({image:h.string().min(1).max(300).optional(),size:h.enum(["small","medium","large"]).default("small"),lifetime:UOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:gy.optional()}).strict(),hL={recipients:h.array(E).default([]),executors:h.array(E).default([]),custodyRevision:h.number().int().positive().nullable().default(null)},LOe=h.object({...Wc,kind:h.literal("variable"),data:h.object({...hL,bytes:h.number().int().nonnegative()})}),jOe=h.object({...Wc,kind:h.literal("connection"),data:h.object({...hL,methodId:h.string(),fields:h.record(h.string(),h.string()).default({}),settings:h.array(h.object({name:h.string(),label:h.string(),value:h.string()})).default([]),methodName:h.string(),methodKind:lL,services:h.array(h.object({id:h.string(),name:fe})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:h.string().optional(),aws:jE.optional()})}),FOe=h.object({...Wc,kind:h.literal("service"),data:DOe}),qOe=h.object({...Wc,kind:h.literal("method"),data:Yl}),VOe=h.object({...Wc,kind:h.literal("app"),data:h.object({...hL,methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:E.optional()})}),GOe=h.object({...Wc,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),HOe=h.object({...Wc,kind:h.literal("environment"),data:T5.extend({executorId:E.optional(),operatorId:E.optional(),driver:h.enum(["attached","managed"]).optional(),capabilities:h.array(h.string()).optional(),isolation:h.enum(["process","container"]).optional(),manifestDigest:h.string().optional(),processes:h.object({workingDirectory:h.string()}).optional(),ssh:MU.optional(),awsPrincipal:h.string().optional(),state:zOe,deletion:MOe.optional(),startedAt:Ie.nullable(),stoppedAt:Ie.nullable(),lastActiveAt:Ie,error:h.string().nullable()})}),BE=h.object({...Wc,kind:h.literal("function"),data:Qo.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:k5.optional()})}),Yr=h.discriminatedUnion("kind",[LOe,jOe,FOe,qOe,VOe,GOe,HOe,BE]),Swt=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:fe,definition:I5}).strict(),h.object({kind:h.literal("method"),name:fe,definition:Yl}).strict(),h.object({kind:h.literal("environment"),name:fe.optional(),options:T5}).strict()]),xwt=h.object({version:h.number().int().positive(),name:fe.optional(),definition:h.union([I5,Yl]).optional()}).strict(),Ui=h.object({name:h.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:bt}).strict(),KE=Ui.extend({inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()}).strict()).max(16).default([])}),gL=h.object({ja:h.string(),en:h.string()}).strict(),C5=KE.extend({title:gL,execution:h.enum(["server","keyholder"]),configure:h.array(h.string())}),O5=h.object({to:E.optional(),executionId:E.optional(),message:h.string().max(1e3).default(""),operations:h.array(KE).min(1).max(8).optional(),expiresInMinutes:h.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),FE=h.object({id:E,name:fe}),D5=h.discriminatedUnion("kind",[h.object({kind:h.literal("line"),subject:FE,relation:E5,object:FE}),h.object({kind:h.literal("transfer"),item:FE,to:FE})]),ZE=h.object({id:E,executionId:E,from:Zc.pick({id:!0,name:!0}),to:Zc.pick({id:!0,name:!0}).nullable(),message:h.string(),purpose:h.enum(["input","approval"]),state:h.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:Ie,expiresAt:Ie,url:h.url(),code:h.string().optional(),returnUrl:h.url().nullable(),refreshUrl:h.url().nullable(),canRespond:h.boolean(),canCancel:h.boolean()}),Ewt=h.object({id:E,name:fe,publicKey:bn,state:h.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:Ie,expiresAt:Ie}),$wt=h.object({available:h.boolean(),required:h.boolean(),active:h.boolean(),payer:Zc.pick({id:!0,name:!0}).nullable()}),Rwt=h.object({storageBytes:h.number().nonnegative(),storageLimit:h.number().positive(),computeSeconds:h.number().nonnegative(),computeLimit:h.number().positive(),month:h.string()}),Iwt=h.object({id:h.string(),actorId:E.nullable(),action:h.string(),targetId:E.nullable(),createdAt:Ie,details:bt}),Awt=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional()}).strict(),Qr=t=>h.object({items:h.array(t),next:h.string().nullable().default(null)}),Pwt=h.object({id:E}),kwt=h.object({owner:E}),BOe=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()}),Twt=BOe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var KOe=h.object({email:h.boolean(),environments:h.boolean(),ssh:h.boolean(),objects:h.boolean(),payments:h.boolean()}),WE=h.object({principal:Zc.nullable(),credentialId:E.nullable(),wrappedKey:qE.nullable(),requestId:E.nullable(),server:h.object({name:fe}),features:KOe,principals:h.array(Zc)}),Nwt=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:_5.default("ja"),principalId:E.optional()}).strict(),zwt=h.object({intent:h.enum(["register","authenticate"]),name:fe.optional(),principalId:E.optional(),returnTo:h.string().max(2048).optional()}).strict(),Mwt=h.object({challengeId:E,credential:h.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:qE.optional()}).strict();var ZOe=new TextEncoder,WOe=new TextDecoder,Ay="ECDH-ES+A256KW",yL="A256GCM",nt=t=>ZOe.encode(t),ks=t=>WOe.decode(t);function Jc(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function N5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function JE(){let t=await $y(Ay,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await Kc(t.publicKey)),privateKey:await Kc(t.privateKey)}}async function Ba(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new by(t).setProtectedHeader({enc:yL}).setAdditionalAuthenticatedData(nt(r));for(let n of e)o.addRecipient(await Yo(n.publicKey,Ay)).setUnprotectedHeader({alg:Ay,kid:n.id});return $o.parse(await o.encrypt())}async function Ro(t,e,r,o){if(t.aad!==Jc(nt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Yo(e,Ay);return(await JU({...t,recipients:[n]},i,{keyManagementAlgorithms:[Ay],contentEncryptionAlgorithms:[yL]})).plaintext}async function JOe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:nt("Foundation"),info:nt("passkey encryption key")},e,256))}async function z5(t,e,r){let o=await _y(t,await JOe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[yL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(ks(o.plaintext))}var gr=h.string().regex(/^[A-Za-z0-9_-]{43}$/),br=h.string().min(100).max(4e6),M5=bn.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Py=h.object({encryption:M5,signing:M5}).strict(),or=h.object({id:E,principalId:E,generation:h.number().int().positive(),previous:gr.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function _f(t){return aL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ee(t){return Jc(new Uint8Array(await crypto.subtle.digest("SHA-256",nt(C(t)))))}async function Ql(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",nt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function YE(){let[t,e]=await Promise.all([JE(),$y("ES256",{crv:"P-256",extractable:!0})]),r=await Kc(e.privateKey);return Py.parse({encryption:t.privateKey,signing:r})}function XE(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function QE(t,e){return or.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:XE(e.encryption),signing:XE(e.signing)})}async function ur(t,e,r){let o=e instanceof CryptoKey?e:await Yo(e,"ES256");return new xy(nt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Nr(t,e,r,o){if(C(await vL(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function vL(t,e,r){let o=await oL(t,await Yo(bn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(C(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Ts=h.object({binding:or,signature:br}).strict();async function ky(t,e){if(await Cs(t),await _f(e.encryption)!==await _f(t.encryption)||await _f(e.signing)!==await _f(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await ur(t,e.signing,"key-binding")}}async function Cs(t){let e=or.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await _f(e.encryption)===await _f(e.signing))throw new Error("Use separate encryption and signing keys.");await Yo(e.encryption,"ECDH-ES+A256KW"),await Yo(e.signing,"ES256")}async function wL(t){let{binding:e,signature:r}=Ts.parse(t);return await Cs(e),await Nr(e,r,e.signing,"key-binding"),e}var U5=h.object({ownerId:E,name:fe,resourceId:E.optional(),version:h.number().int().positive().optional(),environmentIds:h.array(E).max(32).optional()}).strict(),L5=U5.extend({value:h.literal("").optional()}),_L=U5.extend({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}),bf=h.object({ownerId:E,name:fe,definition:Qo,resourceId:E.optional(),version:h.number().int().positive().optional()}).strict(),e$=h.object({ownerId:E,connectionId:E,environmentId:E}).strict(),j5=h.object({ownerId:E,connectionId:E,version:h.number().int().positive(),users:h.array(E).max(32),expiresAt:h.iso.datetime().optional()}).strict(),t$=h.object({ownerId:E,methodId:h.string().min(1).max(200),connectionId:E.optional(),environmentId:E.optional(),name:fe.optional(),appId:E.optional(),environments:h.array(E).max(32).optional(),redirectUri:h.url().optional(),users:h.array(E).max(32).optional(),methodDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:h.string().max(1e3).optional(),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}).strict(),Ty=h.object({ownerId:E,environmentId:E.optional(),operation:h.union([h.object({kind:h.literal("http"),request:Ga}).strict(),Ha.extend({kind:h.literal("command")}),h.object({kind:h.enum(["http","command"]),programId:E,programDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:h.record(h.string(),fe).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),r$=h.object({name:Ui.shape.name,title:gL,execution:h.enum(["server","keyholder"]),configure:h.array(h.string()),input:bt}).strict(),F5=h.object({id:E.optional(),operations:h.array(KE).min(1).max(8),responderId:E.optional(),message:h.string().max(1e3).default(""),expiresInMinutes:h.number().int().min(1).max(1440).default(1440)}).strict(),q5=h.object({values:h.array(bt).max(8).default([]),configuration:h.array(bt).max(8).default([]),code:h.string().max(20).optional()}).strict(),Sf=h.object({index:h.number().int().nonnegative(),invocation:Ui,approval:h.object({id:E,index:h.number().int().nonnegative()}).strict().optional(),continuation:h.object({kind:h.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),st=h.object({id:E,actorId:E,ownerId:E,requests:h.array(E),steps:h.array(h.object({index:h.number().int().nonnegative(),name:Ui.shape.name,state:h.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:h.array(h.object({kind:h.enum(["run","function"]),id:E}).strict())}).strict()),creator:Zc.pick({id:!0,name:!0}),operations:h.array(C5),approval:h.object({requestId:E.nullable(),proposal:D5.nullable()}).strict().nullable(),canContinue:h.boolean(),canCancel:h.boolean(),url:h.url(),code:h.string().optional(),error:h.object({code:h.string(),message:h.string()}).strict().nullable(),index:h.number().int().nonnegative(),state:h.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:h.enum(["approval","input","execution"]).nullable(),waiting:Sf.nullable(),results:h.array(_r.nullable()),createdAt:h.iso.datetime(),expiresAt:h.iso.datetime()}).strict(),V5=h.object({id:E,index:h.number().int().nonnegative(),invocation:Ui,continuationId:E.optional()}).strict();var xf=h.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},XOe=h.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),H5=t=>t===ge.executionResult?14e5:1e6,de={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"},Cy=h.enum([de.http,de.command,de.function,de.connect,de.refresh,de.revoke]);var YOe={[ge.value]:[de.http,de.command,de.function],[ge.tokenSet]:[de.http,de.command,de.function,de.refresh,de.revoke],[ge.clientCredential]:[de.connect,de.refresh,de.revoke],[ge.executionResult]:[]},Ef=t=>YOe[t],B5=t=>Ef(t).filter(e=>e===de.function||e===de.refresh),bL=t=>t===ge.tokenSet,QOe=h.object({id:E,digest:gr}).strict(),eDe=h.object({actor:or,executor:or,operations:h.array(Cy).min(1).max(6),functionDigests:h.array(gr).max(100).default([]),origins:h.array(xf).max(100).default([]),callerProgram:h.boolean().default(!1),expiresAt:Ie}).strict(),tDe=h.object({function:QOe,executor:or,operations:h.array(Cy).min(1).max(6),expiresAt:Ie}).strict(),rDe=h.union([eDe,tDe]),ao=h.object({format:h.literal(2),origin:xf,id:E,ownerId:E,contentType:XOe,revision:h.number().int().positive(),authorities:h.array(or).min(1).max(100),readers:h.array(or).min(1).max(100),grants:h.array(rDe).max(100),observers:h.array(E).max(100).optional(),producers:h.array(h.object({executor:or,runId:E,expiresAt:Ie,materialRevision:h.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),G5=h.object({ownerId:E,authorities:h.array(or).min(1).max(100)}).strict(),K5=h.object({origin:xf,id:E,revision:h.number().int().positive(),from:G5,to:G5,policyDigest:gr,previous:gr.nullable(),signerId:E}).strict(),nDe=K5.extend({signature:br}),SL=h.array(nDe).max(16),td=h.object({policy:ao,authorityId:E,signature:br,lineage:SL.optional()}).strict(),en=h.object({policy:ao,authorityId:E,authorization:br,lineage:SL.optional(),materialRevision:h.number().int().positive(),updatedAt:Ie,creationRunId:E.nullable(),metadata:bt,sealed:$o,signerId:E,signature:br}).strict(),ed=t=>({ownerId:t.ownerId,authorities:t.authorities});async function Z5(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||C(r.to)!==C(o.from))||o.previous!==(r?await ee(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Nr(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(ed(t)))throw new Error("Use the authorities approved by the latest handoff.")}function xL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function n$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(ed(t));return r===C(ed(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function W5(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(ed(t.policy))!==C(ed(e))){if(await Io(t),!t.policy.authorities.some(s=>C(s)===C(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=K5.parse({origin:e.origin,id:e.id,revision:e.revision,from:ed(t.policy),to:ed(e),policyDigest:await ee(e),previous:n.length?await ee(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ur(i,o.signing,"authority-handoff")})}return n.length?{lineage:SL.parse(n)}:{}}async function o$(t){let e=ao.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Cs(n);let i=C(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!Ef(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==de.function&&i!==de.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===de.http||i===de.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(de.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function i$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Xc(t,e){return C({purpose:"resource",policyDigest:await ee(t),materialRevision:e})}async function $f(t,e,r,o,n,i,s){if(t.byteLength>H5(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await o$(e),c=await W5(s,a,o,n);if(!a.authorities.some(p=>C(p)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Ba(t,i$(a).map(p=>({id:p.id,publicKey:p.encryption})),await Xc(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ur(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=en.parse({...l,signature:await ur(l,n.signing,"resource")});return await Io(d),d}async function Io(t){let e=en.parse(t),{signature:r,...o}=e;await o$(e.policy),await Z5(e.policy,e.lineage);let n=xL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ee(e.policy))throw new Error("The handoff approves a different access policy.");await Nr(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(bL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(de.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Nr(o,r,s.signing,"resource");let a=i$(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||e.sealed.aad!==Jc(nt(await Xc(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function J5(t,e,r,o,n=t.metadata){let i=await Io(t);if(!bL(i.policy.contentType)||!(i.policy.authorities.some(p=>C(p)===C(r))||i.policy.grants.some(p=>C(p.executor)===C(r)&&p.operations.includes(de.refresh)&&Date.parse(p.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Ba(e,i$(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await Xc(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await ur(l,o.signing,"resource")};return await Io(d),d}async function Rf(t,e,r,o){let n=await o$(t);if(!n.authorities.some(s=>C(s)===C(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await W5(o,n,e,r),authorityId:e.id,signature:await ur(n,r.signing,"access-policy")};return await Os(i),i}async function Os(t){let e=td.parse(t);await o$(e.policy),await Z5(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ee(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Nr(e.policy,e.signature,o.signing,"access-policy"),e}async function rd(t,e,r,o,n,i){let s=await Os(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&C(p.executor)===C(o)&&(a.contentType===ge.executionResult||Date.parse(p.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>H5(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Ba(t,i$(a).map(p=>({id:p.id,publicKey:p.encryption})),await Xc(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await ur(l,n.signing,"resource")};return await Io(d),d}async function If(t,e,r){let o=await Io(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return Ro(o.sealed,r,e.id,await Xc(o.policy,o.materialRevision))}var oDe=h.object({id:E,policyDigest:gr,materialRevision:h.number().int().positive(),authorizationDigest:gr.optional()}).strict();async function EL(t,e){return e.id===t.policy.id&&e.policyDigest===await ee(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||bL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var s$=h.object({format:h.literal(2),id:E,origin:xf,ownerId:E,approval:h.object({id:E,index:h.number().int().min(0).max(7)}).strict().optional(),operationContext:V5.optional(),actor:or,environmentId:E,executor:or,environmentDigest:gr,operation:Cy,functionDigest:gr.nullable(),functionId:E.optional(),operationDigest:gr,sources:h.array(oDe).max(100),resultRecipients:h.array(or).min(1).max(100),resultApproval:td.optional(),createdAt:Ie,expiresAt:Ie}).strict(),Yc=h.object({intent:s$,signature:br,sealed:$o}).strict();async function nd(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ee(t)})}async function X5(t,e,r){if(s$.parse(t),await ee(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Ba(nt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await nd(t,"input"))};return Yc.parse({...o,signature:await ur(o,r.signing,"run")})}async function iDe(t,e=Date.now()){let r=Yc.parse(t),{signature:o,...n}=r;await Nr(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(i.resultApproval){let c=await Os(i.resultApproval),u=c.policy;if(c.authorityId!==i.actor.id||u.id!==i.id||u.origin!==i.origin||u.ownerId!==i.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(i.actor))||C(u.readers)!==C(i.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==i.id||C(u.producers[0].executor)!==C(i.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Jc(nt(await nd(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function Y5(t,e,r){let o=await iDe(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await Ro(o.sealed,r.encryption,e.id,await nd(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await ee(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function od(t,e,r={}){let o=await Io(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await EL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===de.function||e.operation===de.refresh:e.operation===de.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==de.command&&e.operation!==de.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function Qc(t,e,r,o={}){return await od(t,e,o),Ro(t.sealed,r.encryption,e.executor.id,await Xc(t.policy,t.materialRevision))}var $L=h.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Q5=h.object({format:h.literal(3),id:E,origin:xf,ownerId:E,name:fe,executor:or,operatorId:E,driver:h.enum(["attached","managed"]),capabilities:h.array(Cy).min(1).max(6),functionVersion:h.number().int().positive().optional(),resultVersion:h.literal(1).optional(),isolation:h.enum(["process","container"]),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:$L.optional(),revision:h.number().int().positive()}).strict(),RL=h.object({manifest:Q5,signature:br}).strict();async function IL(t,e){let r=Q5.parse(t),o={manifest:r,signature:await ur(r,e.signing,"environment")};return await Pf(o),o}async function Pf(t){let e=RL.parse(t),{manifest:r}=e;if(await Cs(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(de.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(de.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Nr(r,e.signature,r.executor.signing,"environment"),e}async function kf(t,e){let{manifest:r}=await Pf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ee(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===de.function&&r.functionVersion!==2)throw new Error("This environment does not authorize the requested execution.")}var a$=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),c$=h.object({ok:h.boolean(),result:_r.nullable(),error:h.object({code:h.string().max(100),message:h.string().max(1e3)}).nullable()}).strict(),e8={id:E,intentDigest:gr,executorId:E,state:h.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Ie},t8=h.object({...e8,sealed:$o,signature:br}).strict(),r8=h.object({...e8,format:h.literal(2),accessDigest:gr,proofDigest:gr,approval:td,content:en,previousDigest:gr.optional(),previous:t8.optional(),signature:br}).strict(),Oy=h.union([t8,r8]),sDe=h.object({result:c$,proof:br}).strict(),n8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function AL(t,e,r,o,n,i){await Os(n);let s={format:2,id:t.id,intentDigest:await ee(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await ee(n),...i?{previousDigest:await ee(i)}:{}},a=await ur({...s,resultDigest:await ee(r)},o.signing,"execution-result"),c=nt(C({result:c$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Af;let u=await rd(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await ee(a)},d=r8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ur(l,o.signing,"receipt")});return await PL(d,t),d}var Af=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Tf(t,e,r,o){let n=c$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return AL(t,e,n,o,t.resultApproval);let i=nt(C(n));if(i.byteLength>14e5)throw new Af;let s=await Ba(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await nd(t,"result")),a={id:t.id,intentDigest:await ee(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Oy.parse({...a,signature:await ur(a,o.signing,"receipt")})}async function PL(t,e){let r=Oy.parse(t);if("content"in r){await Nr(n8(r),r.signature,e.executor.signing,"receipt");let i=await Os(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await ee(e)||r.executorId!==e.executor.id||r.accessDigest!==await ee(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>C(a)===C(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==ge.executionResult||s.grants.length||e.resultApproval&&C(e.resultApproval)!==C(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await ee(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await PL(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await Io(r.content),!n$(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Nr(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ee(e)||r.executorId!==e.executor.id||r.sealed.aad!==Jc(nt(await nd(e,"result")))||C(r.sealed.recipients.map(i=>i.header.kid).sort())!==C(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function o8(t,e,r,o){if(await PL(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await Ro(t.content.sealed,o.encryption,r,await Xc(t.content.policy,t.content.materialRevision)),a=sDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await ee(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=n8(t);if(await Nr({...u,resultDigest:await ee(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await Ro(t.sealed,o.encryption,r,await nd(e,"result")),i=c$.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var aDe=h.enum(["http","command","function","connect","refresh","revoke"]),zr=h.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:aDe,state:a$,intent:s$,requestSignature:br,receipt:Oy.nullable(),error:h.string().nullable(),createdAt:Ie,startedAt:Ie.nullable(),finishedAt:Ie.nullable()}).strict(),u$=h.object({name:fe,approval:td}).strict(),i8=h.object({kind:h.literal("function"),functionId:E,definition:Qo,arguments:bt.default({}),outputs:h.record(h.string(),u$).default({})}).strict(),Ka=h.discriminatedUnion("kind",[h.object({kind:h.literal("http"),request:Ga,save:h.record(h.string(),u$).default({})}).strict(),h.object({kind:h.literal("command"),...Ha.shape}).strict(),h.object({kind:h.enum(["connect","refresh","revoke"]),input:_r}).strict()]);var eu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Za=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string()})}).parse(await n.json())}catch{throw new eu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new eu(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},WE)}};import{chmod as cDe,lstat as uDe,mkdir as lDe,open as kL,readFile as a8,rename as dDe,rm as pDe}from"node:fs/promises";import{dirname as fDe,join as TL,resolve as mDe}from"node:path";import{homedir as hDe}from"node:os";import{randomUUID as gDe}from"node:crypto";var CL=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:Py.nullable(),binding:or.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),c8=h.object({current:h.uuid(),identities:h.array(CL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Wa(){return TL(process.env.XDG_CONFIG_HOME||TL(hDe(),".config"),"foundation","identity.json")}function tu(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function l$(t){let e;try{let n=Wa(),i=await uDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await cDe(n,384);let s=c8.parse(JSON.parse(await a8(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=tu(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==tu(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return CL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==tu(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Dy(t){let e=Wa(),r;try{r=c8.parse(JSON.parse(await a8(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=CL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Cf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
128
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function Y9(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;Y9(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var Q9=new Set(["type","properties","required","additionalProperties"]),J9=["oneOf","anyOf"];function X9(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function Hz(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!Q9.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??X9(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:Hz(a)??{allOf:a};Kr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=X9(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function bCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of Q9)if(n in t)return;let r=e.filter(n=>J9.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Hz(e);else{let n=r[0],i=J9.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>Hz([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,Qg(t,o))}function Uc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Qg(u,m),Qg(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(m.$ref&&f.def)for(let w in u)w==="$ref"||w==="allOf"||w in f.def&&JSON.stringify(u[w])===JSON.stringify(f.def[w])&&delete u[w]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())Y9(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])bCe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Qg(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Kr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Yp(e,"input",t.processors),output:Yp(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Fn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Fn(o.element,r);if(o.type==="set")return Fn(o.valueType,r);if(o.type==="lazy")return Fn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Fn(o.innerType,r);if(o.type==="intersection")return Fn(o.left,r)||Fn(o.right,r);if(o.type==="record"||o.type==="map")return Fn(o.keyType,r)||Fn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Fn(o.in,r)||Fn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Fn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Fn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Fn(n,r))return!0;return!!(o.rest&&Fn(o.rest,r))}return!1}var Bz=(t,e={})=>r=>{let o=zc({...r,processors:e});return At(t,o),Mc(o,t),Uc(o,t)},Yp=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=zc({...n??{},target:i,io:e,processors:r});return At(t,s),Mc(s,t),Uc(s,t)};var Qp=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},ef=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},eZ=(t,e)=>{Qp(t,"minimum",e),ef(t,"maximum",e)},oZ=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},iZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},sZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},aZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},tZ=(t,e)=>Qp(t,"minimum",e.minimum),rZ=(t,e)=>ef(t,"maximum",e.maximum),nZ=t=>(e,r)=>{aZ(e,r.format);let[o,n]=t[r.format];Qp(e,"minimum",o),ef(e,"maximum",n)},SCe={greater_than:(t,e)=>Qp(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>ef(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>oZ(t,e.value),number_format:nZ(ng),bigint_format:nZ(og),min_length:tZ,max_length:rZ,length_equals:(t,e)=>eZ(t,e.length),min_size:tZ,max_size:rZ,size_equals:(t,e)=>eZ(t,e.size),string_format:(t,e)=>{aZ(t,e.format),e.pattern&&iZ(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>sZ(t,e.mime)};function Pr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)SCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Qp(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Qp(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&ef(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&ef(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&oZ(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&sZ(e,n.mime);for(let i of n.patterns??[])iZ(e,i);return e}var xCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ECe=new Map([[BS,O1],[vg,D1]]),cZ=t=>ECe.get(t)??t,Wz=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Pr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=xCe[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(cZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Jz=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Pr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let b of a)Number.isFinite(b)&&b!==0?m.add(Math.abs(b)):Ar(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=m;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},Xz=(t,e,r,o)=>{r.type="boolean"},Yz=(t,e,r,o)=>{Ar(t,e,r,o,"BigInt cannot be represented in JSON Schema")},Qz=(t,e,r,o)=>{Ar(t,e,r,o,"Symbols cannot be represented in JSON Schema")},eM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},tM=(t,e,r,o)=>{Ar(t,e,r,o,"Undefined cannot be represented in JSON Schema")},rM=(t,e,r,o)=>{Ar(t,e,r,o,"Void cannot be represented in JSON Schema")},nM=(t,e,r,o)=>{r.not={}},oM=(t,e,r,o)=>{},iM=(t,e,r,o)=>{},sM=(t,e,r,o)=>{Ar(t,e,r,o,"Date cannot be represented in JSON Schema")},aM=(t,e,r,o)=>{let n=t._zod.def,i=mp(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},cM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Ar(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Ar(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},uM=(t,e,r,o)=>{Ar(t,e,r,o,"NaN cannot be represented in JSON Schema")},lM=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},dM=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Pr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},pM=(t,e,r,o)=>{r.type="boolean"},fM=(t,e,r,o)=>{Ar(t,e,r,o,"Custom types cannot be represented in JSON Schema")},mM=(t,e,r,o)=>{Ar(t,e,r,o,"Function types cannot be represented in JSON Schema")},hM=(t,e,r,o)=>{Ar(t,e,r,o,"Transforms cannot be represented in JSON Schema")},gM=(t,e,r,o)=>{Ar(t,e,r,o,"Map cannot be represented in JSON Schema")},yM=(t,e,r,o)=>{Ar(t,e,r,o,"Set cannot be represented in JSON Schema")},vM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Pr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=At(i.element,e,{...o,path:[...o.path,"items"]})};function ey(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?ey(e.out):e.type==="catch"?ey(e.innerType):t._zod.optin}var wM=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Ar(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Kr(n.properties,u,At(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?ey(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=At(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},N0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>At(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},_M=(t,e,r,o)=>{let n=t._zod.def,i=At(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=At(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},bM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>At(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?At(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?ey(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=Pr(t);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function Kz(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let y=Kz(t,m,r);return y===m?e:y}for(let m of["anyOf","oneOf"]){let y=e[m];if(!Array.isArray(y))continue;let w=y.map(b=>Kz(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[m]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?Ma:dg).source)),f}var Zz=new WeakMap;function $Ce(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of Zz.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=Kz(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var SM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Pr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=At(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Kr(n.patternProperties,cZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=At(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=Zz.get(e);l||(l=[],Zz.set(e,l),e.deferred.push(()=>$Ce(e))),l.push(t)}n.additionalProperties=At(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&ey(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},xM=(t,e,r,o)=>{let n=t._zod.def,i=At(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},EM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},$M=Symbol();function uZ(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Ar(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),$M):JSON.parse(s)}var RM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=uZ(n.defaultValue,t,e,r,o);s!==$M&&(r.default=s)},IM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=uZ(n.defaultValue,t,e,r,o);s!==$M&&(r._prefault=s)},AM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Ar(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},PM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;At(s,e,o);let a=e.seen.get(t);a.ref=s},kM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},TM=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},z0=(t,e,r,o)=>{let n=t._zod.def;At(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},CM=(t,e,r,o)=>{let n=t._zod.innerType;At(n,e,o);let i=e.seen.get(t);i.ref=n},D0={string:Wz,number:Jz,boolean:Xz,bigint:Yz,symbol:Qz,null:eM,undefined:tM,void:rM,never:nM,any:oM,unknown:iM,date:sM,enum:aM,literal:cM,nan:uM,template_literal:lM,file:dM,success:pM,custom:fM,function:mM,transform:hM,map:gM,set:yM,array:vM,object:wM,union:N0,intersection:_M,tuple:bM,record:SM,nullable:xM,nonoptional:EM,default:RM,prefault:IM,catch:AM,pipe:PM,readonly:kM,promise:TM,optional:z0,lazy:CM};function Fl(t,e){if("_idmap"in t){let o=t,n=zc({...e,processors:D0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;At(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Mc(n,l),Kr(s,u,Uc(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=zc({...e,processors:D0});return At(t,r),Mc(r,t),Uc(r,t)}var M0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=zc({processors:D0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return At(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Mc(this.ctx,e);let o=Uc(this.ctx,e),{"~standard":n,...i}=o;return i}};var lZ={};var uf={};Ht(uf,{ZodAny:()=>XM,ZodArray:()=>tU,ZodBase64:()=>rE,ZodBase64URL:()=>nE,ZodBigInt:()=>af,ZodBigIntFormat:()=>sE,ZodBoolean:()=>sf,ZodCIDRv4:()=>eE,ZodCIDRv6:()=>tE,ZodCUID:()=>K0,ZodCUID2:()=>Z0,ZodCatch:()=>_U,ZodCodec:()=>uy,ZodCreditCard:()=>BM,ZodCustom:()=>ly,ZodCustomStringFormat:()=>Vl,ZodDate:()=>oy,ZodDefault:()=>mU,ZodDiscriminatedUnion:()=>nU,ZodE164:()=>oE,ZodEmail:()=>V0,ZodEmoji:()=>H0,ZodEnum:()=>rf,ZodExactOptional:()=>uE,ZodFile:()=>lU,ZodFunction:()=>kU,ZodGUID:()=>G0,ZodIBAN:()=>KM,ZodIPv4:()=>Y0,ZodIPv6:()=>Q0,ZodISODate:()=>jc,ZodISODateTime:()=>Lc,ZodISODuration:()=>qc,ZodISOTime:()=>Fc,ZodInstanceOf:()=>OU,ZodIntersection:()=>oU,ZodJWT:()=>iE,ZodKSUID:()=>X0,ZodLazy:()=>IU,ZodLiteral:()=>uU,ZodMAC:()=>HM,ZodMap:()=>aU,ZodNaN:()=>SU,ZodNanoID:()=>B0,ZodNever:()=>QM,ZodNonOptional:()=>lE,ZodNull:()=>JM,ZodNullable:()=>fU,ZodNumber:()=>of,ZodNumberFormat:()=>Gl,ZodObject:()=>iy,ZodOptional:()=>Hl,ZodPipe:()=>cy,ZodPrefault:()=>gU,ZodPreprocess:()=>xU,ZodPromise:()=>PU,ZodReadonly:()=>EU,ZodRecord:()=>tf,ZodSet:()=>cU,ZodString:()=>nf,ZodStringFormat:()=>Ot,ZodSuccess:()=>wU,ZodSymbol:()=>ZM,ZodTemplateLiteral:()=>RU,ZodTransform:()=>dU,ZodTuple:()=>iU,ZodType:()=>ke,ZodULID:()=>W0,ZodURL:()=>ry,ZodUUID:()=>Ps,ZodUndefined:()=>WM,ZodUnion:()=>sy,ZodUnknown:()=>YM,ZodVoid:()=>eU,ZodXID:()=>J0,ZodXor:()=>rU,_ZodString:()=>q0,_default:()=>hU,_function:()=>vW,any:()=>QZ,array:()=>Fe,base64:()=>OZ,base64url:()=>DZ,bigint:()=>ZZ,boolean:()=>hr,catch:()=>bU,check:()=>wW,cidrv4:()=>TZ,cidrv6:()=>CZ,codec:()=>mW,creditCard:()=>zZ,cuid:()=>xZ,cuid2:()=>EZ,currencyCode:()=>qZ,custom:()=>dE,date:()=>tW,describe:()=>_W,discriminatedUnion:()=>ay,e164:()=>NZ,email:()=>fZ,emoji:()=>bZ,enum:()=>Jr,exactOptional:()=>pU,file:()=>lW,float32:()=>GZ,float64:()=>HZ,function:()=>vW,guid:()=>mZ,hash:()=>VZ,hex:()=>FZ,hostname:()=>jZ,httpUrl:()=>_Z,iban:()=>MZ,instanceof:()=>SW,int:()=>j0,int32:()=>BZ,int64:()=>WZ,intersection:()=>cf,invertCodec:()=>hW,ipv4:()=>AZ,ipv6:()=>kZ,json:()=>EW,jwt:()=>UZ,keyof:()=>rW,ksuid:()=>IZ,lazy:()=>AU,literal:()=>se,looseObject:()=>Wr,looseRecord:()=>sW,mac:()=>PZ,map:()=>aW,meta:()=>bW,nan:()=>fW,nanoid:()=>SZ,nativeEnum:()=>uW,never:()=>aE,nonoptional:()=>vU,null:()=>ny,nullable:()=>ty,nullish:()=>dW,number:()=>yt,object:()=>X,optional:()=>Ct,partialRecord:()=>iW,pipe:()=>F0,prefault:()=>yU,preprocess:()=>dy,promise:()=>yW,readonly:()=>$U,record:()=>Dt,refine:()=>TU,set:()=>cW,strictObject:()=>nW,string:()=>O,stringFormat:()=>LZ,stringbool:()=>xW,success:()=>pW,superRefine:()=>CU,symbol:()=>XZ,templateLiteral:()=>gW,transform:()=>cE,tuple:()=>sU,uint32:()=>KZ,uint64:()=>JZ,ulid:()=>$Z,undefined:()=>YZ,union:()=>Pt,unknown:()=>Lt,url:()=>wZ,uuid:()=>hZ,uuidv4:()=>gZ,uuidv6:()=>yZ,uuidv7:()=>vZ,void:()=>eW,xid:()=>RZ,xor:()=>oW});var U0={};Ht(U0,{endsWith:()=>Gp,gt:()=>Is,gte:()=>xo,includes:()=>qp,length:()=>jl,lowercase:()=>jp,lt:()=>Rs,lte:()=>So,maxLength:()=>Ll,maxSize:()=>Dc,mime:()=>Bp,minLength:()=>Ua,minSize:()=>As,multipleOf:()=>Oc,negative:()=>x0,nonnegative:()=>$0,nonpositive:()=>E0,normalize:()=>Kp,overwrite:()=>Ci,positive:()=>S0,properties:()=>Hp,property:()=>R0,regex:()=>Lp,size:()=>Ul,slugify:()=>Xp,startsWith:()=>Vp,toLowerCase:()=>Wp,toUpperCase:()=>Jp,trim:()=>Zp,uppercase:()=>Fp});var dZ=new WeakSet([Object.prototype,Error.prototype]);function L0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var pZ=(t,e)=>{f1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);dZ.has(r)||(dZ.add(r),L0(r,"format",o=>n=>ug(o,n)),L0(r,"flatten",o=>n=>cg(o,n)),L0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,hp,2)}),L0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,hp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ICe=$("ZodError",pZ),io=$("ZodError",pZ,void 0,{Parent:Error});var OM=_p(io),DM=bp(io),NM=Sp(io),zM=Ep(io),MM=aS(io),UM=cS(io),LM=uS(io),jM=lS(io),FM=dS(io),qM=pS(io),VM=fS(io),GM=mS(io);function PCe(){Dr.localeError||cr(Hx())}function ql(){Dr.memoizer||cr({memoizer:Rg()})}var ke=$("ZodType",(t,e)=>(PCe(),_e.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(TU(t,e))},superRefine(t,e){return this.check(CU(t,e))},overwrite(t){return this.check(Ci(t))},optional(){return Ct(this)},exactOptional(){return pU(this)},nullable(){return ty(this)},nullish(){return Ct(ty(this))},nonoptional(t){return vU(this,t)},array(){return Fe(this)},or(t){return Pt([this,t])},and(t){return cf(this,t)},transform(t){return F0(this,cE(t))},default(t){return hU(this,t)},prefault(t){return yU(this,t)},catch(t){return bU(this,t)},pipe(t){return F0(this,t)},readonly(){return $U(this)},describe(t){let e=this.clone();return Zr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Zr.get(this);let e=this.clone();return Zr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return D.hide(this,"~standard",{...$S(this),jsonSchema:{input:Yp(this,"input"),output:Yp(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return OM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await DM(this,e,r,{callee:t})},safeParse(t,e){return NM(this,t,e)},async safeParseAsync(t,e){return zM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Rp(this,t,e)},validateAsync(t,e){return Ip(this,t,e)},encode:function t(e,r){return MM(this,e,r,{callee:t})},decode:function t(e,r){return UM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await LM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await jM(this,e,r,{callee:t})},safeEncode(t,e){return FM(this,t,e)},safeDecode(t,e){return qM(this,t,e)},async safeEncodeAsync(t,e){return VM(this,t,e)},async safeDecodeAsync(t,e){return GM(this,t,e)},toJSONSchema(t){return Bz(this,{})(t)},get description(){return Zr.get(this)?.description},get _def(){return this._zod.def}}),q0=$("_ZodString",(t,e)=>{Cc.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Wz(t,r,o,n)},D.derived({format:t=>Pr(t).format??null,minLength:t=>Pr(t).minimum??null,maxLength:t=>Pr(t).maximum??null},{regex(...t){return this.check(Lp(...t))},includes(...t){return this.check(qp(...t))},startsWith(...t){return this.check(Vp(...t))},endsWith(...t){return this.check(Gp(...t))},min(...t){return this.check(Ua(...t))},max(...t){return this.check(Ll(...t))},length(...t){return this.check(jl(...t))},nonempty(...t){return this.check(Ua(1,...t))},lowercase(t){return this.check(jp(t))},uppercase(t){return this.check(Fp(t))},trim(){return this.check(Zp())},normalize(...t){return this.check(Kp(...t))},toLowerCase(){return this.check(Wp())},toUpperCase(){return this.check(Jp())},slugify(){return this.check(Xp())}})),nf=$("ZodString",(t,e)=>{Cc.init(t,e),q0.init(t,e)},{email(t){return this.check(Ag(V0,t))},url(t){return this.check(Up(ry,t))},jwt(t){return this.check(Zg(iE,t))},emoji(t){return this.check(Dg(H0,t))},guid(t){return this.check(Pg(G0,t))},uuid(t){return this.check(kg(Ps,t))},uuidv4(t){return this.check(Tg(Ps,t))},uuidv6(t){return this.check(Cg(Ps,t))},uuidv7(t){return this.check(Og(Ps,t))},nanoid(t){return this.check(Ng(B0,t))},cuid(t){return this.check(zg(K0,t))},cuid2(t){return this.check(Mg(Z0,t))},ulid(t){return this.check(Ug(W0,t))},base64(t){return this.check(Hg(rE,t))},base64url(t){return this.check(Bg(nE,t))},xid(t){return this.check(Lg(J0,t))},ksuid(t){return this.check(jg(X0,t))},ipv4(t){return this.check(Fg(Y0,t))},ipv6(t){return this.check(qg(Q0,t))},cidrv4(t){return this.check(Vg(eE,t))},cidrv6(t){return this.check(Gg(tE,t))},e164(t){return this.check(Kg(oE,t))},datetime(t){return this.check(Wg(Lc,t))},date(t){return this.check(Jg(jc,t))},time(t){return this.check(Xg(Fc,t))},duration(t){return this.check(Yg(qc,t))}});function O(t){return Qx(nf,t)}var Ot=$("ZodStringFormat",(t,e)=>{xt.init(t,e),q0.init(t,e)}),Lc=$("ZodISODateTime",(t,e)=>{Sz.init(t,e),Ot.init(t,e)}),jc=$("ZodISODate",(t,e)=>{xz.init(t,e),Ot.init(t,e)}),Fc=$("ZodISOTime",(t,e)=>{Ez.init(t,e),Ot.init(t,e)}),qc=$("ZodISODuration",(t,e)=>{$z.init(t,e),Ot.init(t,e)}),V0=$("ZodEmail",(t,e)=>{AS.init(t,e),Ot.init(t,e)});function fZ(t){return Ag(V0,t)}var G0=$("ZodGUID",(t,e)=>{RS.init(t,e),Ot.init(t,e)});function mZ(t){return Pg(G0,t)}var Ps=$("ZodUUID",(t,e)=>{IS.init(t,e),Ot.init(t,e)});function hZ(t){return kg(Ps,t)}function gZ(t){return Tg(Ps,t)}function yZ(t){return Cg(Ps,t)}function vZ(t){return Og(Ps,t)}var ry=$("ZodURL",(t,e)=>{CS.init(t,e),Ot.init(t,e)});function wZ(t){return Up(ry,t)}function _Z(t){return Up(ry,{protocol:lg,hostname:z1,...D.normalizeParams(t)})}var H0=$("ZodEmoji",(t,e)=>{OS.init(t,e),Ot.init(t,e)});function bZ(t){return Dg(H0,t)}var B0=$("ZodNanoID",(t,e)=>{DS.init(t,e),Ot.init(t,e)});function SZ(t){return Ng(B0,t)}var K0=$("ZodCUID",(t,e)=>{NS.init(t,e),Ot.init(t,e)});function xZ(t){return zg(K0,t)}var Z0=$("ZodCUID2",(t,e)=>{zS.init(t,e),Ot.init(t,e)});function EZ(t){return Mg(Z0,t)}var W0=$("ZodULID",(t,e)=>{MS.init(t,e),Ot.init(t,e)});function $Z(t){return Ug(W0,t)}var J0=$("ZodXID",(t,e)=>{US.init(t,e),Ot.init(t,e)});function RZ(t){return Lg(J0,t)}var X0=$("ZodKSUID",(t,e)=>{LS.init(t,e),Ot.init(t,e)});function IZ(t){return jg(X0,t)}var Y0=$("ZodIPv4",(t,e)=>{jS.init(t,e),Ot.init(t,e)});function AZ(t){return Fg(Y0,t)}var HM=$("ZodMAC",(t,e)=>{qS.init(t,e),Ot.init(t,e)});function PZ(t){return e0(HM,t)}var Q0=$("ZodIPv6",(t,e)=>{FS.init(t,e),Ot.init(t,e)});function kZ(t){return qg(Q0,t)}var eE=$("ZodCIDRv4",(t,e)=>{VS.init(t,e),Ot.init(t,e)});function TZ(t){return Vg(eE,t)}var tE=$("ZodCIDRv6",(t,e)=>{HS.init(t,e),Ot.init(t,e)});function CZ(t){return Gg(tE,t)}var rE=$("ZodBase64",(t,e)=>{KS.init(t,e),Ot.init(t,e)});function OZ(t){return Hg(rE,t)}var nE=$("ZodBase64URL",(t,e)=>{WS.init(t,e),Ot.init(t,e)});function DZ(t){return Bg(nE,t)}var oE=$("ZodE164",(t,e)=>{JS.init(t,e),Ot.init(t,e)});function NZ(t){return Kg(oE,t)}var BM=$("ZodCreditCard",(t,e)=>{YS.init(t,e),Ot.init(t,e)});function zZ(t){return t0(BM,t)}var KM=$("ZodIBAN",(t,e)=>{ex.init(t,e),Ot.init(t,e)});function MZ(t){return r0(KM,t)}var iE=$("ZodJWT",(t,e)=>{rx.init(t,e),Ot.init(t,e)});function UZ(t){return Zg(iE,t)}var Vl=$("ZodCustomStringFormat",(t,e)=>{nx.init(t,e),Ot.init(t,e)});function LZ(t,e,r={}){return Nc(Vl,t,e,r)}function jZ(t){return Nc(Vl,"hostname",N1,t)}function FZ(t){return Nc(Vl,"hex",J1,t)}function qZ(t){return Nc(Vl,"currency_code",U1,t)}function VZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=bo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Nc(Vl,o,n,e)}var of=$("ZodNumber",(t,e)=>{wg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Jz(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Pr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Pr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Pr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Pr(t).format??null},{gt(t,e){return this.check(Is(t,e))},gte(t,e){return this.check(xo(t,e))},min(t,e){return this.check(xo(t,e))},lt(t,e){return this.check(Rs(t,e))},lte(t,e){return this.check(So(t,e))},max(t,e){return this.check(So(t,e))},int(t){return this.check(j0(t))},safe(t){return this.check(j0(t))},positive(t){return this.check(Is(0,t))},nonnegative(t){return this.check(xo(0,t))},negative(t){return this.check(Rs(0,t))},nonpositive(t){return this.check(So(0,t))},multipleOf(t,e){return this.check(Oc(t,e))},step(t,e){return this.check(Oc(t,e))},finite(){return this}}));function yt(t){return n0(of,t)}var Gl=$("ZodNumberFormat",(t,e)=>{ox.init(t,e),of.init(t,e)});function j0(t){return o0(Gl,t)}function GZ(t){return i0(Gl,t)}function HZ(t){return s0(Gl,t)}function BZ(t){return a0(Gl,t)}function KZ(t){return c0(Gl,t)}var sf=$("ZodBoolean",(t,e)=>{kp.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Xz(t,r,o,n)});function hr(t){return u0(sf,t)}var af=$("ZodBigInt",(t,e)=>{_g.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Yz(t,r,o,n)},D.derived({minValue:t=>Pr(t).minimum??null,maxValue:t=>Pr(t).maximum??null,format:t=>Pr(t).format??null},{gte(t,e){return this.check(xo(t,e))},min(t,e){return this.check(xo(t,e))},gt(t,e){return this.check(Is(t,e))},lt(t,e){return this.check(Rs(t,e))},lte(t,e){return this.check(So(t,e))},max(t,e){return this.check(So(t,e))},positive(t){return this.check(Is(BigInt(0),t))},negative(t){return this.check(Rs(BigInt(0),t))},nonpositive(t){return this.check(So(BigInt(0),t))},nonnegative(t){return this.check(xo(BigInt(0),t))},multipleOf(t,e){return this.check(Oc(t,e))}}));function ZZ(t){return l0(af,t)}var sE=$("ZodBigIntFormat",(t,e)=>{ix.init(t,e),af.init(t,e)});function WZ(t){return d0(sE,t)}function JZ(t){return p0(sE,t)}var ZM=$("ZodSymbol",(t,e)=>{sx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Qz(t,r,o,n)});function XZ(t){return f0(ZM,t)}var WM=$("ZodUndefined",(t,e)=>{ax.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tM(t,r,o,n)});function YZ(t){return m0(WM,t)}var JM=$("ZodNull",(t,e)=>{cx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eM(t,r,o,n)});function ny(t){return h0(JM,t)}var XM=$("ZodAny",(t,e)=>{ux.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oM(t,r,o,n)});function QZ(){return g0(XM)}var YM=$("ZodUnknown",(t,e)=>{lx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iM(t,r,o,n)});function Lt(){return y0(YM)}var QM=$("ZodNever",(t,e)=>{dx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nM(t,r,o,n)});function aE(t){return v0(QM,t)}var eU=$("ZodVoid",(t,e)=>{px.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rM(t,r,o,n)});function eW(t){return w0(eU,t)}var oy=$("ZodDate",(t,e)=>{fx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sM(t,r,o,n),t.min=(r,o)=>t.check(xo(r,o)),t.max=(r,o)=>t.check(So(r,o))},D.derived({minDate:t=>{let{minimum:e}=Pr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Pr(t);return e?new Date(e):null}},{}));function tW(t){return _0(oy,t)}var tU=$("ZodArray",(t,e)=>{ql(),mx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ua(t,e))},nonempty(t){return this.check(Ua(1,t))},max(t,e){return this.check(Ll(t,e))},length(t,e){return this.check(jl(t,e))},unwrap(){return this.element}});function Fe(t,e){return Gz(tU,t,e)}function rW(t){let e=t._zod.def.shape;return Jr(Object.keys(e))}var iy=$("ZodObject",(t,e)=>{ql(),Rz.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Jr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Lt()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Lt()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:aE()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return D.extend(this,t)},safeExtend(t){return D.safeExtend(this,t)},merge(t){return D.merge(this,t)},pick(t){return D.pick(this,t)},omit(t){return D.omit(this,t)},partial(...t){return D.partial(Hl,this,t[0])},exactPartial(...t){return D.partial(uE,this,t[0],"exactPartial")},required(...t){return D.required(lE,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new iy(r)}function nW(t,e){return new iy({type:"object",shape:t,catchall:aE(),...D.normalizeParams(e)})}function Wr(t,e){return new iy({type:"object",shape:t,catchall:Lt(),...D.normalizeParams(e)})}var sy=$("ZodUnion",(t,e)=>{Tp.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.options=e.options});function Pt(t,e){return new sy({type:"union",options:t,...D.normalizeParams(e)})}var rU=$("ZodXor",(t,e)=>{sy.init(t,e),gx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>N0(t,r,o,n),t.options=e.options});function oW(t,e){return new rU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var nU=$("ZodDiscriminatedUnion",(t,e)=>{sy.init(t,e),yx.init(t,e)});function ay(t,e,r){return new nU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var oU=$("ZodIntersection",(t,e)=>{vx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n)});function cf(t,e){return new oU({type:"intersection",left:t,right:e})}var iU=$("ZodTuple",(t,e)=>{ql(),bg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Hl({type:"optional",innerType:e}))})}});function sU(t,e,r){let o=e instanceof _e,n=o?r:e,i=o?e:null;return new iU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var tf=$("ZodRecord",(t,e)=>{ql(),wx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Dt(t,e,r){return!e||!e._zod?new tf({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new tf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function iW(t,e,r){return new tf({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function sW(t,e,r){return new tf({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var aU=$("ZodMap",(t,e)=>{ql(),_x.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(As(...r)),t.nonempty=r=>t.check(As(1,r)),t.max=(...r)=>t.check(Dc(...r)),t.size=(...r)=>t.check(Ul(...r))});function aW(t,e,r){return new aU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var cU=$("ZodSet",(t,e)=>{ql(),bx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n),t.min=(...r)=>t.check(As(...r)),t.nonempty=r=>t.check(As(1,r)),t.max=(...r)=>t.check(Dc(...r)),t.size=(...r)=>t.check(Ul(...r))});function cW(t,e){return new cU({type:"set",valueType:t,...D.normalizeParams(e)})}var rf=$("ZodEnum",(t,e)=>{Sx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(o,n,i)=>aM(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new rf({...e,checks:[],...D.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new rf({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Jr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new rf({type:"enum",entries:r,...D.normalizeParams(e)})}function uW(t,e){return new rf({type:"enum",entries:t,...D.normalizeParams(e)})}var uU=$("ZodLiteral",(t,e)=>{xx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function se(t,e){return new uU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var lU=$("ZodFile",(t,e)=>{Ex.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n),t.min=(r,o)=>t.check(As(r,o)),t.max=(r,o)=>t.check(Dc(r,o)),t.mime=(r,o)=>t.check(Bp(Array.isArray(r)?r:[r],o))});function lW(t){return I0(lU,t)}var dU=$("ZodTransform",(t,e)=>{ql(),$x.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Tc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(D.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(D.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function cE(t){return new dU({type:"transform",transform:t})}var Hl=$("ZodOptional",(t,e)=>{Sg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>z0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Ct(t){return new Hl({type:"optional",innerType:t})}var uE=$("ZodExactOptional",(t,e)=>{Rx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>z0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pU(t){return new uE({type:"optional",innerType:t})}var fU=$("ZodNullable",(t,e)=>{Ix.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ty(t){return new fU({type:"nullable",innerType:t})}function dW(t){return Ct(ty(t))}var mU=$("ZodDefault",(t,e)=>{Ax.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function hU(t,e){return new mU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var gU=$("ZodPrefault",(t,e)=>{Px.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yU(t,e){return new gU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var lE=$("ZodNonOptional",(t,e)=>{kx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function vU(t,e){return new lE({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var wU=$("ZodSuccess",(t,e)=>{Tx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pW(t){return new wU({type:"success",innerType:t})}var _U=$("ZodCatch",(t,e)=>{Cx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function bU(t,e){return new _U({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var SU=$("ZodNaN",(t,e)=>{Ox.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n)});function fW(t){return b0(SU,t)}var cy=$("ZodPipe",(t,e)=>{xg.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n),t.in=e.in,t.out=e.out});function F0(t,e){return new cy({type:"pipe",in:t,out:e})}var uy=$("ZodCodec",(t,e)=>{cy.init(t,e),Cp.init(t,e)});function mW(t,e,r){return new uy({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function hW(t){let e=t._zod.def;return new uy({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var xU=$("ZodPreprocess",(t,e)=>{cy.init(t,e),Az.init(t,e)}),EU=$("ZodReadonly",(t,e)=>{Dx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function $U(t){return new EU({type:"readonly",innerType:t})}var RU=$("ZodTemplateLiteral",(t,e)=>{Nx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n)});function gW(t,e){return new RU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var IU=$("ZodLazy",(t,e)=>{Op.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function AU(t){return new IU({type:"lazy",getter:t})}var PU=$("ZodPromise",(t,e)=>{Mx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yW(t){return new PU({type:"promise",innerType:t})}var kU=$("ZodFunction",(t,e)=>{zx.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n)});function vW(t){return new kU({type:"function",input:Array.isArray(t?.input)?sU(t?.input):t?.input??Fe(Lt()),output:t?.output??Lt()})}var ly=$("ZodCustom",(t,e)=>{Ux.init(t,e),ke.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fM(t,r,o,n)});function wW(t){let e=new Tt({check:"custom"});return e._zod.check=t,e}function dE(t,e){return A0(ly,t??(()=>!0),e)}function TU(t,e={}){return P0(ly,t,e)}function CU(t,e){return k0(t,e)}var _W=T0,bW=C0,OU=$("ZodInstanceOf",(t,e)=>{ly.init(t,e)},{properties(t,e){return this.check(Hp(t,e))}});function SW(t,e={}){let r=new OU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...D.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var xW=(...t)=>O0({Codec:uy,Boolean:sf,String:nf},...t);function EW(t){let e=AU(()=>Pt([O(t),yt(),hr(),ny(),Fe(e),Dt(O(),e)]));return e}function dy(t,e){return new xU({type:"pipe",in:cE(t),out:e})}var kCe={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function TCe(t){cr({customError:t})}function CCe(){return cr().customError}var DU;DU||(DU={});var Bl={};Ht(Bl,{ZodISODate:()=>jc,ZodISODateTime:()=>Lc,ZodISODuration:()=>qc,ZodISOTime:()=>Fc,date:()=>DCe,datetime:()=>OCe,duration:()=>zCe,time:()=>NCe});function OCe(t){return Wg(Lc,t)}function DCe(t){return Jg(jc,t)}function NCe(t){return Xg(Fc,t)}function zCe(t){return Yg(qc,t)}var W={...uf,...U0,iso:Bl},MCe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function UCe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function $W(t,e){return t.map((r,o)=>o<e?r:r.optional())}function LCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jCe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:LCe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function FCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function NU(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=NU(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=NU(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var qCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),VCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function py(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(py):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>qCe.has(e)?py(r):!VCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(py))}function RW(t){return t===1?"element":"elements"}function GCe(t,e){return W.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=NU(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${RW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${RW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function IW(t,e){if(t!==!1)return t===void 0||t===!0?W.any():qn(t,e)}var HCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function AW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return W.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return W.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=jCe(n,e),s=qn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return W.null();if(n.length===0)return W.never();if(n.length===1)return W.literal(n[0]);if(n.every(s=>typeof s=="string"))return W.enum(n);let i=n.map(s=>W.literal(s));return i.length<2?i[0]:W.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return W.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return AW(s,e)});return n.length===0?W.never():n.length===1?n[0]:W.union(n)}if(!r)return W.any();let o;switch(r){case"string":{let n=W.string();if(t.format){let i=t.format;i==="email"?n=n.check(W.email()):i==="uri"||i==="uri-reference"?n=n.check(W.url()):i==="uuid"||i==="guid"?n=n.check(W.uuid()):i==="date-time"?n=n.check(W.iso.datetime({offset:!0})):i==="date"?n=n.check(W.iso.date()):i==="time"?n=n.check(W.regex(HCe)):i==="duration"?n=n.check(W.iso.duration()):i==="hostname"?n=n.check(W.hostname()):i==="ipv4"?n=n.check(W.ipv4()):i==="ipv6"?n=n.check(W.ipv6()):i==="mac"?n=n.check(W.mac()):i==="cidr"?n=n.check(W.cidrv4()):i==="cidr-v6"?n=n.check(W.cidrv6()):i==="base64"?n=n.check(W.base64()):i==="base64url"?n=n.check(W.base64url()):i==="e164"?n=n.check(W.e164()):i==="credit_card"?n=n.check(W.creditCard()):i==="iban"?n=n.check(W.iban()):i==="jwt"?n=n.check(W.jwt()):i==="emoji"?n=n.check(W.emoji()):i==="nanoid"?n=n.check(W.nanoid()):i==="cuid"?n=n.check(W.cuid()):i==="cuid2"?n=n.check(W.cuid2()):i==="ulid"?n=n.check(W.ulid()):i==="xid"?n=n.check(W.xid()):i==="ksuid"&&(n=n.check(W.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?W.number().int():W.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=W.boolean();break}case"null":{o=W.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?qn(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=qn(p,e);Kr(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let y of p){let w=qn(d[y],e),b=W.string().regex(new RegExp(y));f.push(W.looseRecord(b,w))}let m=[];if(Object.keys(n).length>0&&m.push(W.object(n).passthrough()),m.push(...f),m.length===0)o=W.object({}).passthrough();else if(m.length===1)o=m[0];else{let y=W.intersection(m[0],m[1]);for(let w=2;w<m.length;w++)y=W.intersection(y,m[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=p.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Wo(S.value))return;let x=[];for(let I of Object.keys(S.value))y.includes(I)||w.some(T=>T.test(I))||x.push(I);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=W.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=qn(p,e)}o=FCe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>qn(d,e)),c=$W(a,s),u=Array.isArray(i)?void 0:IW(i,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>qn(d,e)),c=$W(a,s),u=IW(t.additionalItems,e),l=W.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(W.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(W.maxLength(t.maxItems)))}else if(i!==void 0){let s=qn(i,e),a=W.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=W.array(W.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=GCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?qn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function qn(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r=AW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>qn(u,e)),c=W.union(a);r=o?W.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>qn(u,e)),c=W.xor(a);r=o?W.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:W.any();else{let a=o?r:qn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=W.intersection(a,qn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=W.nullable(r)),t.readOnly===!0&&(r=W.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!py(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!py(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))MCe.has(a)||Kr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function PW(t,e){if(typeof t=="boolean")return t?W.any():W.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=UCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Zr};return qn(r,i)}var kW=Symbol("z.visit/resolving");function fy(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===kW)return new Op({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,kW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let y=n(u[m]);y!==u[m]&&(d=!0),p[m]=y}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function TW(t){return fy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:Pt(r.options)}})}function BCe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Zo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function CW(t){return BCe(t.out,t.checks)}function KCe(t){return t.in._zod.traits.has("$ZodTransform")?CW(t):t.in}function OW(t){return fy(t,{pipe:e=>KCe(e._zod.def),default:(e,r)=>r?Ct(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function DW(t){return fy(t,{pipe:e=>CW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var zU={};Ht(zU,{bigint:()=>XCe,boolean:()=>JCe,date:()=>YCe,number:()=>WCe,string:()=>ZCe});function ZCe(t){return Uz(nf,t)}function WCe(t){return jz(of,t)}function JCe(t){return Fz(sf,t)}function XCe(t){return qz(af,t)}function YCe(t){return Vz(oy,t)}var my={name:"@tomato414941/foundation",version:"10.0.1",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&h.config({jitless:!0});function eOe(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var hy=h.string().trim().max(8192).refine(t=>eOe(t)!==null,"Use an OpenSSH public key from a .pub file."),gy=h.object({authorizedKeys:h.array(hy).max(32)}).strict(),zgt=gy.extend({revision:h.number().int().positive().optional()}),MU=gy.extend({host:h.string().min(1).max(253).nullable(),port:h.number().int().min(1).max(65535),username:h.literal("root"),workingDirectory:h.literal("/workspace"),hostKey:hy.nullable(),fingerprint:h.string().nullable(),revision:h.number().int().positive(),appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),Mgt=MU.extend({state:h.enum(["starting","configuring","ready","disabled","stopped"])}),Ugt=h.object({hostKey:hy,appliedRevision:h.number().int().nonnegative(),activeSessions:h.number().int().min(0).max(1024)}).strict(),tOe=gy.extend({port:h.number().int().min(1).max(65535),revision:h.number().int().positive()}).strict(),pE=h.object({configuration:tOe.nullable()}).strict();var lf=new TextEncoder,df=new TextDecoder,NW=new TextDecoder("utf-8",{fatal:!0}),fE=2**32;function Vn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function UU(t,e,r){if(e<0||e>=fE)throw new RangeError(`value must be >= 0 and <= ${fE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function LU(t){let e=Math.floor(t/fE),r=t%fE,o=new Uint8Array(8);return UU(o,e,0),UU(o,r,4),o}function mE(t){let e=new Uint8Array(4);return UU(e,t),e}var rOe=/[^\x00-\x7f]/;function Xr(t){if(typeof t=="string"&&t.length>=128){if(rOe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return lf.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function zW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function MW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function hE(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var La=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var Kl=class extends La{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Nt=class extends La{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Vc=class extends La{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends La{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Xt=class extends La{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var yy=class extends La{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var gE=class extends La{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var nOe="The input to be decoded is not correctly encoded.";function Zl(t){try{return MW(typeof t=="string"?t:df.decode(t),!0)}catch(e){throw new TypeError(nOe,{cause:e})}}function nr(t){return zW(typeof t=="string"?lf.encode(t):t,!0)}function Eo(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function wr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Gc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Xo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function so(t,e,r){try{return Zl(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function yE(t,e,r){try{return Xr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function pf(t,e,r){let o;try{o=JSON.parse(NW.decode(Zl(t)))}catch{throw new e(r)}if(!wr(o))throw new e(r);return o}var vE={__proto__:null,b64:!0},wE={__proto__:null};function vy(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function _E(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Hc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Nt(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function bE(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Wl(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!wr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var oOe=t=>t[Symbol.toStringTag],iOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Di(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(wr(e)){if(s=HU(e),typeof s.kty!="string")throw UW(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(iOe(t,s,r),s.kty==="oct")return Zl(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!qU(e))throw UW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${oOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Bc(e))return e;if(a=e,a.type==="secret")return a.export()}jU||=new WeakMap;let c=e,u=jU.get(c);if(u?.[o])return u[o];if(u||jU.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=sOe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await mf(t,s)}var jU,sOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function xE(t){if(!Bc(t))throw new Error("CryptoKey instance expected")}var Bc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},FU=t=>t?.[Symbol.toStringTag]==="KeyObject",qU=t=>Bc(t)||FU(t);function LW(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var ja=(t,...e)=>LW("Key must be ",t,...e);function UW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(LW(`Key for the ${t} algorithm must be `,e,...o))}var SE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function VU(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function ff(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function GU(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw SE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw SE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw SE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw SE(e.length,"algorithm.length");VU(t,r)}function EE(t){return{__proto__:null,...t}}function HU(t){let e=EE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function $E(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function mf(t,e,r){if(!t.kty.includes(e.kty))throw new Nt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Ni(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),GU(t,e,r),t}var Jl=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function RE(t,e){let r=t.byteLength<<3;if(r!==e)throw new H(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var aOe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function jW(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function FW(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(ja(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function qW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function cOe(t,e,r,o,n){let[i,s,a]=await FW(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Vn(n,o,c,LU(n.length*8)),l=await qW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function uOe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function lOe(t,e,r,o,n,i){let[s,a,c]=await FW(t,e,"decrypt"),u=Vn(i,o,r,LU(i.length*8)),l=await qW(a,u,c);try{if(await uOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Vc}async function IE(t,e,r,o,n){if(!Bc(r)&&!(r instanceof Uint8Array))throw new TypeError(ja(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?jW(t,o):o=aOe(t),r instanceof Uint8Array&&RE(r,t.cekBits),t.cbc)return cOe(t,e,r,o,n);let i=await Ni(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function AE(t,e,r,o,n,i){if(!Bc(e)&&!(e instanceof Uint8Array))throw new TypeError(ja(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new H("JWE Initialization Vector missing");if(!n)throw new H("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new H("Invalid Authentication Tag length");if(jW(t,o),e instanceof Uint8Array&&RE(e,t.cekBits),t.cbc)return lOe(t,e,r,o,n,i);let s=await Ni(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Vn(r,n)))}catch{throw new Vc}}function wy(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var dOe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],pOe=[[],["deriveBits"]],TE=[[],[]];function PE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:dOe,ops:["wrapKey","unwrapKey"]}}function kE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Nt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:pOe,ops:[void 0,"deriveBits"]}}function hf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:TE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function BU(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:TE,ops:["deriveBits","deriveBits"]}}var Fa=wy({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:TE,ops:["encrypt","decrypt"]},"RSA-OAEP":PE(1),"RSA-OAEP-256":PE(256),"RSA-OAEP-384":PE(384),"RSA-OAEP-512":PE(512),"ECDH-ES":kE("direct-key-agreement"),"ECDH-ES+A128KW":kE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":kE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":kE("key-agreement-with-key-wrapping"),A128KW:hf(128),A192KW:hf(192),A256KW:hf(256),A128GCMKW:hf(128,!0),A192GCMKW:hf(192,!0),A256GCMKW:hf(256,!0),"PBES2-HS256+A128KW":BU(),"PBES2-HS384+A192KW":BU(),"PBES2-HS512+A256KW":BU()}),fOe=["encrypt","decrypt"];function gf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:TE,ops:fOe,cekBits:t,ivBits:e?128:96,cbc:e}}var mOe=wy({A128GCM:gf(128),A192GCM:gf(192),A256GCM:gf(256),"A128CBC-HS256":gf(256,!0),"A192CBC-HS384":gf(384,!0),"A256CBC-HS512":gf(512,!0)});function VW(t,e){throw new Nt(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function zi(t){return(typeof t=="string"?Fa[t]:void 0)??VW("alg","Algorithm")}function Mi(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function Xl(t){return(typeof t=="string"?mOe[t]:void 0)??VW("enc","Encryption Algorithm")}function GW(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");VU(t,e)}async function hOe(t,e,r){let o=await Ni(e,zi(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function gOe(t,e,r){let o=await Ni(e,zi(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function BW(t,e,r){GU(e,zi(t).subtle,r),ff(t,e)}async function KW(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new H("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new H("PBES2 Count Input must be a positive integer");let n=Vn(Xr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Ni(o,zi(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function KU(t){return Vn(mE(t.length),t)}async function yOe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await hE("sha256",Vn(mE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function ZW(t,e,r,o,n=new Uint8Array,i=new Uint8Array){GW(t),GW(e,"deriveBits");let s=Vn(KU(Xr(r)),KU(n),KU(i),mE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return yOe(a,o,s)}function WW(t){xE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Nt("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function CE(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new H(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return so(r,e,H)}}function JW(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new H('JOSE Header "apu" and "apv" values must be distinct')}}function vOe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function HW(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function wOe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function XW(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return HW(o),r;let c=a==="direct-key-agreement";switch(c?HW(o):vOe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!wr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');WW(r);let l=await mf(t,u),d=CE(n,"apu"),p=CE(n,"apv");JW(d,p);let f=await ZW(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return xE(r),BW(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new H('JOSE Header "p2c" (PBES2 Count) missing or invalid');wOe(i);let u=i??1e4;if(n.p2c>u)throw new H('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new H('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=so(n.p2s,"p2s",H);r=await KW(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new H('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new H('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=so(n.iv,"iv",H),l=so(n.tag,"tag",H);if(u.byteLength!==12)throw new H("Invalid Initialization Vector length");if(l.byteLength!==16)throw new H("Invalid Authentication Tag length");return AE(Xl(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return gOe(s.slice(-6),r,o)}async function OE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Mi(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Di(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Jl(e):void 0;l&&RE(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{WW(u);let{apu:f,apv:m}=i;f!==void 0&&Eo(f,'"apu"'),m!==void 0&&Eo(m,'"apv"');let y=f??CE(o,"apu"),w=m??CE(o,"apv");JW(y,w);let b;i.epk!==void 0?b=await Di(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:I,y:T,crv:M,kty:J}=await S.exportKey("jwk",x),le=a==="direct-key-agreement",Le=await ZW(u,b,le?e.alg:s,le?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),ze={x:I,crv:M,kty:J};if(J==="EC"&&(ze.y=T),p={epk:ze},f!==void 0&&(p.apu=nr(f)),m!==void 0&&(p.apv=nr(m)),le)return[Le,void 0,p];u=Le;break}case"RSA-OAEP":{xE(u),BW(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await KW(m,s,f,u),p={p2c:f,p2s:nr(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await IE(Xl(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:nr(m.iv),tag:nr(m.tag)}}}if(d??=await hOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function DE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Nt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function YW(t){if(typeof globalThis[t]>"u")throw new Nt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function QW(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new H("Decompressed plaintext exceeded the configured limit")}return Vn(...n)}async function e5(t){return YW("CompressionStream"),QW(new CompressionStream("deflate-raw"),t)}async function t5(t,e){return YW("DecompressionStream"),QW(new DecompressionStream("deflate-raw"),t,e)}function r5(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new H("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new H("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new H("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new H("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new H("JWE AAD incorrect type");if(s!==void 0&&!wr(s))throw new H("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function n5(t){let e,r;try{let{header:o}=t;if(wr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function o5(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new H("JWE Encrypted Key incorrect type");if(r!==void 0&&!wr(r))throw new H("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new H("JOSE Header missing")}function ZU(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=pf(e,H,"JWE Protected Header is invalid")),[s,so(r,"ciphertext",H),o!==void 0?so(o,"iv",H):void 0,n!==void 0?so(n,"tag",H):void 0,yE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function NE(t){return[t&&vy("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&vy("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function WU(t,e,r,o=ZU(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Gc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,y,w,b]=e,{encrypted_key:S}=t;Hc(H,wE,y,n,p),DE(p,n);let{alg:x,enc:I}=p;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Fa[x];if(S===""&&(!T||!Mi(T)))throw new H("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof I!="string"||!I))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new Kl('"alg" (Algorithm) Header Parameter value not allowed');let J;if(M){if(I!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new H("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new H("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(I))throw new Kl('"enc" (Encryption Algorithm) Header Parameter value not allowed');J=Xl(I)}let le;if(S!==void 0)try{le=so(S,"encrypted_key",H)}catch(je){if(!T||!Mi(T))throw je;le=new Uint8Array}let Le=!1;typeof r=="function"&&(r=await r(n,t),Le=!0);let ze=T??zi(x);Mi(ze)&&le===void 0&&(le=new Uint8Array);let It=await Di(ze.mode==="direct-encryption"?J:ze,r,"decrypt"),lt;if(ze.mode==="integrated-encryption")lt=await ze.decrypt(It,le,i,c,n,p);else{let je=J,ie;try{ie=await XW(ze,je,It,le,p,w),Mi(ze)&&ie instanceof Uint8Array&&ie.byteLength<<3!==je.cekBits&&(ie=Jl(je))}catch(tr){if(tr instanceof TypeError||tr instanceof H||tr instanceof Nt)throw tr;ie=Jl(je)}lt=await AE(je,ie,i,s,a,c)}if(p.zip==="DEF"){let je=b??25e4;if(je===0)throw new Nt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(je!==1/0&&(!Number.isSafeInteger(je)||je<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");lt=await t5(lt,je).catch(ie=>{throw ie instanceof H?ie:new H("Failed to decompress plaintext",{cause:ie})})}return{plaintext:lt,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:so(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Le&&{key:It}}}async function i5(t,e,r){if(t instanceof Uint8Array&&(t=df.decode(t)),typeof t!="string")throw new H("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new H("Invalid Compact JWE");return WU({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function _y(t,e,r){return i5(t,NE(r),e)}async function JU(t,e,r){if(!wr(t))throw new H("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new H("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(wr))throw new H("JWE Recipients missing or incorrect type");if(!n.length)throw new H("JWE Recipients has no members");let i,s,a;try{i=NE(r),s=r5(t),a=ZU(s)}catch{throw new Vc}let c=n.map(u=>n5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Fa[l]:void 0;if(d&&!Mi(d))throw new H(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return o5(l),await WU(l,i,e,a)}catch{}throw new Vc}function zE(t,e,r){if(!Gc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function XU(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new H("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Eo(s,"JWE Additional Authenticated Data"),a!==void 0&&Eo(a,"JWE Content Encryption Key"),c!==void 0&&Eo(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=Wl(H,o)[0],t[1]=o),n!==void 0&&(n=Wl(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=Wl(H,i)[0],t[3]=i),u!==void 0&&!wr(u))throw new TypeError("JWE Key Management Parameters must be an object");zE(o,n,i);let d={...o,...n,...i};_E(H,o),Hc(H,wE,l,o,d),DE(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Fa[p];if(m?.mode==="integrated-encryption"){if(f!==void 0)throw new H('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 ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,Xl(f),m]}async function YU(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,m]=t,y=a,w=c,b=i??zi(o.alg),S,x,I;b.mode==="integrated-encryption"?I=await Di(b,r,"encrypt"):[I,S,x]=await OE(b,n,r,o,d,f),x&&(m?w=w?{...w,...x}:x:y=y?{...y,...x}:x,zE(y,w,u));let T=y?nr(JSON.stringify(y)):"",M=l?.byteLength?nr(l):void 0,J=Xr(M?`${T}.${M}`:T),le=s;o.zip==="DEF"&&(le=await e5(le).catch(je=>{throw new H("Failed to compress plaintext",{cause:je})}));let Le,ze,It;b.mode==="integrated-encryption"?[S,Le]=await b.encrypt(I,le,J,y,o,f):{ciphertext:Le,tag:ze,iv:It}=await IE(n,le,I,p,J);let lt={ciphertext:nr(Le)};return It&&(lt.iv=nr(It)),ze&&(lt.tag=nr(ze)),S?.byteLength&&(lt.encrypted_key=nr(S)),M&&(lt.aad=M),y&&(lt.protected=T),u&&(lt.unprotected=u),w&&(lt.header=w),lt}async function s5(t,e,r){return YU(t,XU(t,r),e)}function a5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var QU=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Xo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Xo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},by=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new QU(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Xo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Xo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new H("at least one recipient must be added");Eo(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[y,w,b,S]=m.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],I=XU(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,I,b]);let[{alg:T,enc:M},,J]=I;if(e&&J&&!Mi(J))throw new H(`"${T}" alg may only have a single recipient`);if(!r)r=M;else if(r!==M)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=zi(m[0].alg);let[s,a,c]=i[0],u=e?Jl(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await YU(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[y,[w,b,S],x]=i[m],I=y[2],[,T,M]=await OE(S,b,x,w,u,y[7]),J={encrypted_key:nr(T)};if(I||M){let le={...I,...M};M&&zE(y[1],le,y[3]),J.header=le}f.recipients.push(J)}return f}};var Sy=[["verify"],["sign"]];function eL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Sy}}function yf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:Sy,minRsaBits:2048}}function tL(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Sy}}function c5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Sy}}function rL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Sy}}var nL=wy({HS256:eL(256),HS384:eL(384),HS512:eL(512),RS256:yf(256),RS384:yf(384),RS512:yf(512),PS256:yf(256,32),PS384:yf(384,48),PS512:yf(512,64),ES256:tL("P-256",256),ES384:tL("P-384",384),ES512:tL("P-521",512),EdDSA:c5(),Ed25519:c5(),"ML-DSA-44":rL(44),"ML-DSA-65":rL(65),"ML-DSA-87":rL(87)});function ME(t){let e=typeof t=="string"?nL[t]:void 0;if(!e)throw new Nt(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function u5(t){return[t&&vy("algorithms",t.algorithms),t?.crit]}function _Oe(t){return t===void 0?{}:pf(t,Xt,"JWS Protected Header is invalid")}function bOe(t){try{return Xr(t)}catch{throw new Xt("JWS Compact Serialization payload must use only ASCII characters")}}async function SOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??_Oe(i);if(!Gc(c,s))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=bE(c,Hc(Xt,vE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new Kl('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Xt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let m=ME(d),y=Vn(i!==void 0?Xr(i):new Uint8Array,Xr("."),typeof p=="string"?e[2]??=yE(p,"payload",Xt):p),w=so(t.signature,"signature",Xt),b=await Di(m,r,"verify"),S=await Ni(b,m.subtle,"verify");m.minRsaBits&&ff(m.alg,S);let x=!1;try{x=await crypto.subtle.verify(m.signing,S,w,y)}catch{}if(!x)throw new gE;let I={payload:typeof p=="string"?so(p,"payload",Xt):p};return i!==void 0&&(I.protectedHeader=c),s!==void 0&&(I.unprotectedHeader=s),f?[{...I,key:b},l]:[I,l]}async function l5(t,e,r){if(t instanceof Uint8Array&&(t=df.decode(t)),typeof t!="string")throw new Xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Xt("Invalid Compact JWS");return SOe({payload:n,protected:o,signature:i},e,r,bOe)}async function oL(t,e,r){let[o]=await l5(t,u5(r),e);return o}var vf=class{#e;constructor(e){Eo(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Xo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Xo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Xo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Xo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return a5(await s5([...this.#e],e,r))}};async function xOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=Wl(Xt,n);n=b[0],a=nr(b[1])}if(i!==void 0&&(i=Wl(Xt,i)[0]),!n&&!i)throw new Xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Gc(n,i))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};_E(Xt,n);let u=bE(n,Hc(Xt,vE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=ME(l),p="",f=o,m;if(u){let b=t[4];b?(p=b[0]??=nr(o),f=b[1]??=Xr(p)):(p=nr(o),m=lf.encode(`${a}.${p}`))}m??=Vn(Xr(a),Xr("."),f);let y=await Ni(await Di(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&ff(d.alg,y);let w={signature:nr(new Uint8Array(await crypto.subtle.sign(d.signing,y,m))),payload:p};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function d5(t,e,r,o,n){let[i]=await xOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var xy=class{#e;#t;constructor(e){Eo(e,"payload"),this.#e=e}setProtectedHeader(e){return Xo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return d5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var iL='"alg" (Algorithm)';function sL(t='JWK "alg" (Algorithm) Parameter'){throw new Nt(`Invalid or unsupported ${t} value`)}function Ey(t,e){return(typeof t=="string"?nL[t]??Fa[t]:void 0)??sL(e)}async function Kc(t){if(FU(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:nr(t)};if(!Bc(t))throw new TypeError(ja(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var qa=(t,e)=>{if(typeof t!="string"||!t)throw new yy(`${e} missing or invalid`)};async function aL(t,e){let r;if(wr(t)){if(r=EE(t),typeof r.kty!="string")throw new TypeError(ja(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(qU(t))r=EE(await Kc(t));else throw new TypeError(ja(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":qa(r.alg,'"alg" (Algorithm) Parameter'),qa(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":qa(r.crv,'"crv" (Curve) Parameter'),qa(r.x,'"x" (X Coordinate) Parameter'),qa(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":qa(r.crv,'"crv" (Subtype of Key Pair) Parameter'),qa(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":qa(r.e,'"e" (Exponent) Parameter'),qa(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new yy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Nt('"kty" (Key Type) Parameter missing or unsupported')}let n=Xr(JSON.stringify(o));return nr(await hE(e,n))}async function Yo(t,e,r){if(!wr(t))throw new TypeError("JWK must be an object");let o=HU(t),n=$E(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return Zl(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return mf(Ey(e),o,n)}case"RSA":case"EC":case"OKP":return mf(Ey(e),o,n);default:throw new Nt('Unsupported "kty" (Key Type) Parameter value')}}function cL(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return pf(e,TypeError,r)}function EOe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Nt("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function $y(t,e){let r=$E(e?.extractable),o=Ey(t,iL);o.secret&&sL(iL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Nt("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Nt(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:EOe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var h5=h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),g5=h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),p5=h.string().min(1).max(128),f5=h.string().min(1).max(16384),$Oe=h.discriminatedUnion("kind",[h.object({kind:h.literal("access_key"),accessKeyId:p5,secretAccessKey:f5}).strict(),h.object({kind:h.literal("session"),accessKeyId:p5,secretAccessKey:f5,sessionToken:h.string().min(1).max(16384),expiresAt:h.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),h.object({kind:h.literal("environment")}).strict()]),ROe=h.object({arn:g5,externalId:h.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Va=h.object({authentication:$Oe,region:h5,role:ROe.optional()}).strict(),UE=h.object({accountId:h.string().regex(/^\d{12}$/),principalId:h.string().min(1).max(256),arn:h.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),LE=Va.extend({sourceIdentity:UE,identity:UE}).strict();function wf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function m5(t){return{...t,arn:wf(t.arn)}}function y5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,sourceIdentity:m5(t.sourceIdentity),identity:m5(t.identity)}}var jE=h.object({authentication:h.enum(["access_key","session","environment"]),region:h5,sourceAccountId:h.string().regex(/^\d{12}$/),sourceArn:h.string().max(2e3),roleArn:g5.optional(),expiresAt:h.number().int().positive().optional()}).strict();function v5(t){return{authentication:t.authentication.kind,region:t.region,sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn,...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}typeof window<"u"&&h.config({jitless:!0});var E=h.uuid(),fe=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Ie=h.iso.datetime(),_r=h.json(),bt=h.record(h.string(),_r),_5=h.enum(["ja","en"]),b5=h.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var S5=h.enum(["variable","connection","service","method","app","object","environment","function"]),bn=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),IOe=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:E}).strict(),qE=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return IOe.safeParse(cL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),$o=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:E,epk:bn.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),ywt=h.object({id:E,name:fe,publicKey:bn}),Zc=h.object({id:E,name:fe,owner:h.object({id:E,name:fe}).nullable(),createdAt:Ie,permissions:h.array(b5),createKinds:h.array(S5),publicKey:bn.nullable()}),x5=h.object({id:E,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:Ie,lastUsedAt:Ie.nullable(),expiresAt:Ie.nullable(),canOpen:h.boolean()}),E5=h.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),AOe=h.object({subjectId:E,relation:E5,objectId:E}).strict(),vwt=AOe.extend({objectType:h.enum(["principal",...S5.options]),subjectName:fe,objectName:fe,createdAt:Ie}),wwt=h.object({error:h.object({code:h.string(),message:h.string(),details:_r.optional()})}),_wt=h.object({ok:h.literal(!0)}),POe=h.object({value:h.string().min(1).max(200),label:h.string().min(1).max(200),values:h.record(h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),h.string()).default({})}).strict(),$5=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional(),choices:h.array(POe).min(1).max(100).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),R5=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),kOe=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),required:h.array(h.string()).optional(),separator:h.string().default(" "),docs:h.url().optional()}),Ry=h.string().min(1).max(4096),w5=h.union([h.string(),h.array(h.string()).min(1)]),TOe=h.object({application:h.enum(["required","implicit"]).default("required"),grantType:h.enum(["authorization_code","client_credentials"]).optional(),issuer:h.url().optional(),authorizeUrl:Ry.optional(),tokenUrl:Ry,identity:h.object({url:Ry.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:w5.default("/id"),name:w5.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),revoke:h.object({url:Ry,style:h.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:h.enum(["body","basic","none"]).optional()}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:kOe.default({default:[],separator:" "}),fields:h.array($5).default([]),outputs:R5.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),COe=h.object({fields:h.array($5).min(1),outputs:R5,console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}),lL=h.enum(["oauth","token","aws"]),OOe=h.object({hint:h.string().optional()}).strict(),dL={name:fe,docs:h.url().optional(),console:Ry.optional()},VE=h.object({...dL,kind:h.literal("oauth"),config:TOe}).strict(),GE=h.object({...dL,kind:h.literal("token"),config:COe}).strict(),HE=h.object({...dL,kind:h.literal("aws"),config:OOe}).strict(),Yl=h.discriminatedUnion("kind",[VE,GE,HE]),uL={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"])},Iy=h.discriminatedUnion("kind",[VE.extend(uL),GE.extend(uL),HE.extend(uL)]),pL=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),fL=h.object({name:fe,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional()}).strict(),DOe=fL.extend({methods:h.record(pL,h.string().min(1))}).strict(),I5=fL.extend({methods:h.record(pL,h.union([h.string().min(1),Yl]))}).strict(),bwt=fL.extend({id:h.string(),builtin:h.boolean(),methods:h.record(pL,Iy)}),A5=h.object({id:E,output:h.string().min(1).max(100).optional()}).strict(),P5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),mL=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:A5,format:h.enum(["text","file","json"]).default("text"),pointer:h.string().optional()}).strict(),NOe=h.object({pointer:h.string().max(500),parts:h.array(h.union([h.string().max(8192),A5])).min(1).max(32)}).strict(),Ga=h.object({url:h.string().max(4096),method:h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:h.record(h.string(),h.string().max(8192)).default({}),body:h.string().max(1e6).optional(),json:_r.optional(),form:h.record(h.string(),h.string()).optional(),bindings:h.array(NOe).max(32).default([])}).strict(),Ha=h.object({command:h.array(h.string().max(8192)).min(1).max(100),stdin:h.string().max(1e6).optional(),timeoutSeconds:h.number().int().min(1).max(3600).default(60),inputs:h.array(mL).max(32).default([])}).strict(),k5=h.discriminatedUnion("kind",[Ha.omit({stdin:!0}).extend({kind:h.literal("command")}).strict(),h.object({kind:h.literal("http"),request:Ga}).strict()]),Qo=h.object({description:h.string().max(2e3).default(""),environmentId:E,program:k5,parameters:h.array(h.object({name:h.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:h.string().max(100),type:h.enum(["string","number","boolean","json"]).default("string"),required:h.boolean().default(!0),default:_r.optional()}).strict()).max(32).default([]),result:h.enum(["text","json"]).default("json")}).strict(),Wc={id:E,ownerId:E,name:fe,createdAt:Ie,updatedAt:Ie,version:h.number().int().positive(),permissions:h.array(b5)},zOe=h.enum(["starting","running","stopping","stopped","failed"]),MOe=h.object({state:h.enum(["pending","failed","complete"]),error:h.string().nullable()}),UOe=h.object({idleSeconds:h.number().int().min(60).max(86400).default(3600),maxSeconds:h.number().int().min(60).max(86400).default(3600)}).strict(),T5=h.object({image:h.string().min(1).max(300).optional(),size:h.enum(["small","medium","large"]).default("small"),lifetime:UOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:gy.optional()}).strict(),hL={recipients:h.array(E).default([]),executors:h.array(E).default([]),custodyRevision:h.number().int().positive().nullable().default(null)},LOe=h.object({...Wc,kind:h.literal("variable"),data:h.object({...hL,bytes:h.number().int().nonnegative()})}),jOe=h.object({...Wc,kind:h.literal("connection"),data:h.object({...hL,methodId:h.string(),fields:h.record(h.string(),h.string()).default({}),settings:h.array(h.object({name:h.string(),label:h.string(),value:h.string()})).default([]),methodName:h.string(),methodKind:lL,services:h.array(h.object({id:h.string(),name:fe})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:h.string().optional(),aws:jE.optional()})}),FOe=h.object({...Wc,kind:h.literal("service"),data:DOe}),qOe=h.object({...Wc,kind:h.literal("method"),data:Yl}),VOe=h.object({...Wc,kind:h.literal("app"),data:h.object({...hL,methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:E.optional()})}),GOe=h.object({...Wc,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),HOe=h.object({...Wc,kind:h.literal("environment"),data:T5.extend({executorId:E.optional(),operatorId:E.optional(),driver:h.enum(["attached","managed"]).optional(),capabilities:h.array(h.string()).optional(),isolation:h.enum(["process","container"]).optional(),manifestDigest:h.string().optional(),processes:h.object({workingDirectory:h.string()}).optional(),ssh:MU.optional(),awsPrincipal:h.string().optional(),state:zOe,deletion:MOe.optional(),startedAt:Ie.nullable(),stoppedAt:Ie.nullable(),lastActiveAt:Ie,error:h.string().nullable()})}),BE=h.object({...Wc,kind:h.literal("function"),data:Qo.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:k5.optional()})}),Yr=h.discriminatedUnion("kind",[LOe,jOe,FOe,qOe,VOe,GOe,HOe,BE]),Swt=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:fe,definition:I5}).strict(),h.object({kind:h.literal("method"),name:fe,definition:Yl}).strict(),h.object({kind:h.literal("environment"),name:fe.optional(),options:T5}).strict()]),xwt=h.object({version:h.number().int().positive(),name:fe.optional(),definition:h.union([I5,Yl]).optional()}).strict(),Ui=h.object({name:h.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:bt}).strict(),KE=Ui.extend({inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()}).strict()).max(16).default([])}),gL=h.object({ja:h.string(),en:h.string()}).strict(),C5=KE.extend({title:gL,execution:h.enum(["server","keyholder"]),configure:h.array(h.string())}),O5=h.object({to:E.optional(),executionId:E.optional(),message:h.string().max(1e3).default(""),operations:h.array(KE).min(1).max(8).optional(),expiresInMinutes:h.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),FE=h.object({id:E,name:fe}),D5=h.discriminatedUnion("kind",[h.object({kind:h.literal("line"),subject:FE,relation:E5,object:FE}),h.object({kind:h.literal("transfer"),item:FE,to:FE})]),ZE=h.object({id:E,executionId:E,from:Zc.pick({id:!0,name:!0}),to:Zc.pick({id:!0,name:!0}).nullable(),message:h.string(),purpose:h.enum(["input","approval"]),state:h.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:Ie,expiresAt:Ie,url:h.url(),code:h.string().optional(),returnUrl:h.url().nullable(),refreshUrl:h.url().nullable(),canRespond:h.boolean(),canCancel:h.boolean()}),Ewt=h.object({id:E,name:fe,publicKey:bn,state:h.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:Ie,expiresAt:Ie}),$wt=h.object({available:h.boolean(),required:h.boolean(),active:h.boolean(),payer:Zc.pick({id:!0,name:!0}).nullable()}),Rwt=h.object({storageBytes:h.number().nonnegative(),storageLimit:h.number().positive(),computeSeconds:h.number().nonnegative(),computeLimit:h.number().positive(),month:h.string()}),Iwt=h.object({id:h.string(),actorId:E.nullable(),action:h.string(),targetId:E.nullable(),createdAt:Ie,details:bt}),Awt=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional()}).strict(),Qr=t=>h.object({items:h.array(t),next:h.string().nullable().default(null)}),Pwt=h.object({id:E}),kwt=h.object({owner:E}),BOe=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()}),Twt=BOe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var KOe=h.object({email:h.boolean(),environments:h.boolean(),ssh:h.boolean(),objects:h.boolean(),payments:h.boolean()}),WE=h.object({principal:Zc.nullable(),credentialId:E.nullable(),wrappedKey:qE.nullable(),requestId:E.nullable(),server:h.object({name:fe}),features:KOe,principals:h.array(Zc)}),Nwt=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:_5.default("ja"),principalId:E.optional()}).strict(),zwt=h.object({intent:h.enum(["register","authenticate"]),name:fe.optional(),principalId:E.optional(),returnTo:h.string().max(2048).optional()}).strict(),Mwt=h.object({challengeId:E,credential:h.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:qE.optional()}).strict();var ZOe=new TextEncoder,WOe=new TextDecoder,Ay="ECDH-ES+A256KW",yL="A256GCM",nt=t=>ZOe.encode(t),ks=t=>WOe.decode(t);function Jc(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function N5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function JE(){let t=await $y(Ay,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await Kc(t.publicKey)),privateKey:await Kc(t.privateKey)}}async function Ba(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new by(t).setProtectedHeader({enc:yL}).setAdditionalAuthenticatedData(nt(r));for(let n of e)o.addRecipient(await Yo(n.publicKey,Ay)).setUnprotectedHeader({alg:Ay,kid:n.id});return $o.parse(await o.encrypt())}async function Ro(t,e,r,o){if(t.aad!==Jc(nt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Yo(e,Ay);return(await JU({...t,recipients:[n]},i,{keyManagementAlgorithms:[Ay],contentEncryptionAlgorithms:[yL]})).plaintext}async function JOe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:nt("Foundation"),info:nt("passkey encryption key")},e,256))}async function z5(t,e,r){let o=await _y(t,await JOe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[yL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(ks(o.plaintext))}var gr=h.string().regex(/^[A-Za-z0-9_-]{43}$/),br=h.string().min(100).max(4e6),M5=bn.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Py=h.object({encryption:M5,signing:M5}).strict(),or=h.object({id:E,principalId:E,generation:h.number().int().positive(),previous:gr.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function _f(t){return aL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ee(t){return Jc(new Uint8Array(await crypto.subtle.digest("SHA-256",nt(C(t)))))}async function Ql(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",nt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function YE(){let[t,e]=await Promise.all([JE(),$y("ES256",{crv:"P-256",extractable:!0})]),r=await Kc(e.privateKey);return Py.parse({encryption:t.privateKey,signing:r})}function XE(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function QE(t,e){return or.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:XE(e.encryption),signing:XE(e.signing)})}async function ur(t,e,r){let o=e instanceof CryptoKey?e:await Yo(e,"ES256");return new xy(nt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Nr(t,e,r,o){if(C(await vL(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function vL(t,e,r){let o=await oL(t,await Yo(bn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(C(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Ts=h.object({binding:or,signature:br}).strict();async function ky(t,e){if(await Cs(t),await _f(e.encryption)!==await _f(t.encryption)||await _f(e.signing)!==await _f(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await ur(t,e.signing,"key-binding")}}async function Cs(t){let e=or.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await _f(e.encryption)===await _f(e.signing))throw new Error("Use separate encryption and signing keys.");await Yo(e.encryption,"ECDH-ES+A256KW"),await Yo(e.signing,"ES256")}async function wL(t){let{binding:e,signature:r}=Ts.parse(t);return await Cs(e),await Nr(e,r,e.signing,"key-binding"),e}var U5=h.object({ownerId:E,name:fe,resourceId:E.optional(),version:h.number().int().positive().optional(),environmentIds:h.array(E).max(32).optional()}).strict(),L5=U5.extend({value:h.literal("").optional()}),_L=U5.extend({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}),bf=h.object({ownerId:E,name:fe,definition:Qo,resourceId:E.optional(),version:h.number().int().positive().optional()}).strict(),e$=h.object({ownerId:E,connectionId:E,environmentId:E}).strict(),j5=h.object({ownerId:E,connectionId:E,version:h.number().int().positive(),users:h.array(E).max(32),expiresAt:h.iso.datetime().optional()}).strict(),t$=h.object({ownerId:E,methodId:h.string().min(1).max(200),connectionId:E.optional(),environmentId:E.optional(),name:fe.optional(),appId:E.optional(),environments:h.array(E).max(32).optional(),redirectUri:h.url().optional(),users:h.array(E).max(32).optional(),methodDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:h.string().max(1e3).optional(),fields:h.record(h.string(),h.string()).optional(),clientSecret:h.literal("").optional()}).strict(),Ty=h.object({ownerId:E,environmentId:E.optional(),operation:h.union([h.object({kind:h.literal("http"),request:Ga}).strict(),Ha.extend({kind:h.literal("command")}),h.object({kind:h.enum(["http","command"]),programId:E,programDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:h.record(h.string(),fe).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),r$=h.object({name:Ui.shape.name,title:gL,execution:h.enum(["server","keyholder"]),configure:h.array(h.string()),input:bt}).strict(),F5=h.object({id:E.optional(),operations:h.array(KE).min(1).max(8),responderId:E.optional(),message:h.string().max(1e3).default(""),expiresInMinutes:h.number().int().min(1).max(1440).default(1440)}).strict(),q5=h.object({values:h.array(bt).max(8).default([]),configuration:h.array(bt).max(8).default([]),code:h.string().max(20).optional()}).strict(),Sf=h.object({index:h.number().int().nonnegative(),invocation:Ui,approval:h.object({id:E,index:h.number().int().nonnegative()}).strict().optional(),continuation:h.object({kind:h.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),st=h.object({id:E,actorId:E,ownerId:E,requests:h.array(E),steps:h.array(h.object({index:h.number().int().nonnegative(),name:Ui.shape.name,state:h.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:h.array(h.object({kind:h.enum(["run","function"]),id:E}).strict())}).strict()),creator:Zc.pick({id:!0,name:!0}),operations:h.array(C5),approval:h.object({requestId:E.nullable(),proposal:D5.nullable()}).strict().nullable(),canContinue:h.boolean(),canCancel:h.boolean(),url:h.url(),code:h.string().optional(),error:h.object({code:h.string(),message:h.string()}).strict().nullable(),index:h.number().int().nonnegative(),state:h.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:h.enum(["approval","input","execution"]).nullable(),waiting:Sf.nullable(),results:h.array(_r.nullable()),createdAt:h.iso.datetime(),expiresAt:h.iso.datetime()}).strict(),V5=h.object({id:E,index:h.number().int().nonnegative(),invocation:Ui,continuationId:E.optional()}).strict();var xf=h.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),ge={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},XOe=h.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),H5=t=>t===ge.executionResult?14e5:1e6,de={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"},Cy=h.enum([de.http,de.command,de.function,de.connect,de.refresh,de.revoke]);var YOe={[ge.value]:[de.http,de.command,de.function],[ge.tokenSet]:[de.http,de.command,de.function,de.refresh,de.revoke],[ge.clientCredential]:[de.connect,de.refresh,de.revoke],[ge.executionResult]:[]},Ef=t=>YOe[t],B5=t=>Ef(t).filter(e=>e===de.function||e===de.refresh),bL=t=>t===ge.tokenSet,QOe=h.object({id:E,digest:gr}).strict(),eDe=h.object({actor:or,executor:or,operations:h.array(Cy).min(1).max(6),functionDigests:h.array(gr).max(100).default([]),origins:h.array(xf).max(100).default([]),callerProgram:h.boolean().default(!1),expiresAt:Ie}).strict(),tDe=h.object({function:QOe,executor:or,operations:h.array(Cy).min(1).max(6),expiresAt:Ie}).strict(),rDe=h.union([eDe,tDe]),ao=h.object({format:h.literal(2),origin:xf,id:E,ownerId:E,contentType:XOe,revision:h.number().int().positive(),authorities:h.array(or).min(1).max(100),readers:h.array(or).min(1).max(100),grants:h.array(rDe).max(100),observers:h.array(E).max(100).optional(),producers:h.array(h.object({executor:or,runId:E,expiresAt:Ie,materialRevision:h.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),G5=h.object({ownerId:E,authorities:h.array(or).min(1).max(100)}).strict(),K5=h.object({origin:xf,id:E,revision:h.number().int().positive(),from:G5,to:G5,policyDigest:gr,previous:gr.nullable(),signerId:E}).strict(),nDe=K5.extend({signature:br}),SL=h.array(nDe).max(16),td=h.object({policy:ao,authorityId:E,signature:br,lineage:SL.optional()}).strict(),en=h.object({policy:ao,authorityId:E,authorization:br,lineage:SL.optional(),materialRevision:h.number().int().positive(),updatedAt:Ie,creationRunId:E.nullable(),metadata:bt,sealed:$o,signerId:E,signature:br}).strict(),ed=t=>({ownerId:t.ownerId,authorities:t.authorities});async function Z5(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||C(r.to)!==C(o.from))||o.previous!==(r?await ee(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Nr(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(ed(t)))throw new Error("Use the authorities approved by the latest handoff.")}function xL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function n$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(ed(t));return r===C(ed(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function W5(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(ed(t.policy))!==C(ed(e))){if(await Io(t),!t.policy.authorities.some(s=>C(s)===C(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=K5.parse({origin:e.origin,id:e.id,revision:e.revision,from:ed(t.policy),to:ed(e),policyDigest:await ee(e),previous:n.length?await ee(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ur(i,o.signing,"authority-handoff")})}return n.length?{lineage:SL.parse(n)}:{}}async function o$(t){let e=ao.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Cs(n);let i=C(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!Ef(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==de.function&&i!==de.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===de.http||i===de.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(de.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function i$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Xc(t,e){return C({purpose:"resource",policyDigest:await ee(t),materialRevision:e})}async function $f(t,e,r,o,n,i,s){if(t.byteLength>H5(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await o$(e),c=await W5(s,a,o,n);if(!a.authorities.some(p=>C(p)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Ba(t,i$(a).map(p=>({id:p.id,publicKey:p.encryption})),await Xc(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ur(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=en.parse({...l,signature:await ur(l,n.signing,"resource")});return await Io(d),d}async function Io(t){let e=en.parse(t),{signature:r,...o}=e;await o$(e.policy),await Z5(e.policy,e.lineage);let n=xL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ee(e.policy))throw new Error("The handoff approves a different access policy.");await Nr(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===ge.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(bL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(de.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Nr(o,r,s.signing,"resource");let a=i$(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||e.sealed.aad!==Jc(nt(await Xc(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function J5(t,e,r,o,n=t.metadata){let i=await Io(t);if(!bL(i.policy.contentType)||!(i.policy.authorities.some(p=>C(p)===C(r))||i.policy.grants.some(p=>C(p.executor)===C(r)&&p.operations.includes(de.refresh)&&Date.parse(p.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Ba(e,i$(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await Xc(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await ur(l,o.signing,"resource")};return await Io(d),d}async function Rf(t,e,r,o){let n=await o$(t);if(!n.authorities.some(s=>C(s)===C(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await W5(o,n,e,r),authorityId:e.id,signature:await ur(n,r.signing,"access-policy")};return await Os(i),i}async function Os(t){let e=td.parse(t);await o$(e.policy),await Z5(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ee(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Nr(e.policy,e.signature,o.signing,"access-policy"),e}async function rd(t,e,r,o,n,i){let s=await Os(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&C(p.executor)===C(o)&&(a.contentType===ge.executionResult||Date.parse(p.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>H5(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Ba(t,i$(a).map(p=>({id:p.id,publicKey:p.encryption})),await Xc(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await ur(l,n.signing,"resource")};return await Io(d),d}async function If(t,e,r){let o=await Io(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return Ro(o.sealed,r,e.id,await Xc(o.policy,o.materialRevision))}var oDe=h.object({id:E,policyDigest:gr,materialRevision:h.number().int().positive(),authorizationDigest:gr.optional()}).strict();async function EL(t,e){return e.id===t.policy.id&&e.policyDigest===await ee(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||bL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var s$=h.object({format:h.literal(2),id:E,origin:xf,ownerId:E,approval:h.object({id:E,index:h.number().int().min(0).max(7)}).strict().optional(),operationContext:V5.optional(),actor:or,environmentId:E,executor:or,environmentDigest:gr,operation:Cy,functionDigest:gr.nullable(),functionId:E.optional(),operationDigest:gr,sources:h.array(oDe).max(100),resultRecipients:h.array(or).min(1).max(100),resultApproval:td.optional(),createdAt:Ie,expiresAt:Ie}).strict(),Yc=h.object({intent:s$,signature:br,sealed:$o}).strict();async function nd(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ee(t)})}async function X5(t,e,r){if(s$.parse(t),await ee(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Ba(nt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await nd(t,"input"))};return Yc.parse({...o,signature:await ur(o,r.signing,"run")})}async function iDe(t,e=Date.now()){let r=Yc.parse(t),{signature:o,...n}=r;await Nr(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(i.resultApproval){let c=await Os(i.resultApproval),u=c.policy;if(c.authorityId!==i.actor.id||u.id!==i.id||u.origin!==i.origin||u.ownerId!==i.ownerId||u.contentType!==ge.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(i.actor))||C(u.readers)!==C(i.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==i.id||C(u.producers[0].executor)!==C(i.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Jc(nt(await nd(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function Y5(t,e,r){let o=await iDe(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await Ro(o.sealed,r.encryption,e.id,await nd(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await ee(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function od(t,e,r={}){let o=await Io(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await EL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===de.function||e.operation===de.refresh:e.operation===de.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==de.command&&e.operation!==de.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function Qc(t,e,r,o={}){return await od(t,e,o),Ro(t.sealed,r.encryption,e.executor.id,await Xc(t.policy,t.materialRevision))}var $L=h.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),Q5=h.object({format:h.literal(3),id:E,origin:xf,ownerId:E,name:fe,executor:or,operatorId:E,driver:h.enum(["attached","managed"]),capabilities:h.array(Cy).min(1).max(6),functionVersion:h.number().int().positive().optional(),resultVersion:h.literal(1).optional(),isolation:h.enum(["process","container"]),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:$L.optional(),revision:h.number().int().positive()}).strict(),RL=h.object({manifest:Q5,signature:br}).strict();async function IL(t,e){let r=Q5.parse(t),o={manifest:r,signature:await ur(r,e.signing,"environment")};return await Pf(o),o}async function Pf(t){let e=RL.parse(t),{manifest:r}=e;if(await Cs(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(de.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(de.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Nr(r,e.signature,r.executor.signing,"environment"),e}async function kf(t,e){let{manifest:r}=await Pf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ee(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===de.function&&r.functionVersion!==2)throw new Error("This environment does not authorize the requested execution.")}var a$=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),c$=h.object({ok:h.boolean(),result:_r.nullable(),error:h.object({code:h.string().max(100),message:h.string().max(1e3)}).nullable()}).strict(),e8={id:E,intentDigest:gr,executorId:E,state:h.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Ie},t8=h.object({...e8,sealed:$o,signature:br}).strict(),r8=h.object({...e8,format:h.literal(2),accessDigest:gr,proofDigest:gr,approval:td,content:en,previousDigest:gr.optional(),previous:t8.optional(),signature:br}).strict(),Oy=h.union([t8,r8]),sDe=h.object({result:c$,proof:br}).strict(),n8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function AL(t,e,r,o,n,i){await Os(n);let s={format:2,id:t.id,intentDigest:await ee(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await ee(n),...i?{previousDigest:await ee(i)}:{}},a=await ur({...s,resultDigest:await ee(r)},o.signing,"execution-result"),c=nt(C({result:c$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Af;let u=await rd(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await ee(a)},d=r8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ur(l,o.signing,"receipt")});return await PL(d,t),d}var Af=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Tf(t,e,r,o){let n=c$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return AL(t,e,n,o,t.resultApproval);let i=nt(C(n));if(i.byteLength>14e5)throw new Af;let s=await Ba(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await nd(t,"result")),a={id:t.id,intentDigest:await ee(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Oy.parse({...a,signature:await ur(a,o.signing,"receipt")})}async function PL(t,e){let r=Oy.parse(t);if("content"in r){await Nr(n8(r),r.signature,e.executor.signing,"receipt");let i=await Os(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await ee(e)||r.executorId!==e.executor.id||r.accessDigest!==await ee(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>C(a)===C(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==ge.executionResult||s.grants.length||e.resultApproval&&C(e.resultApproval)!==C(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await ee(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await PL(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await Io(r.content),!n$(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Nr(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ee(e)||r.executorId!==e.executor.id||r.sealed.aad!==Jc(nt(await nd(e,"result")))||C(r.sealed.recipients.map(i=>i.header.kid).sort())!==C(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function o8(t,e,r,o){if(await PL(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await Ro(t.content.sealed,o.encryption,r,await Xc(t.content.policy,t.content.materialRevision)),a=sDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await ee(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=n8(t);if(await Nr({...u,resultDigest:await ee(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await Ro(t.sealed,o.encryption,r,await nd(e,"result")),i=c$.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var aDe=h.enum(["http","command","function","connect","refresh","revoke"]),zr=h.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:aDe,state:a$,intent:s$,requestSignature:br,receipt:Oy.nullable(),error:h.string().nullable(),createdAt:Ie,startedAt:Ie.nullable(),finishedAt:Ie.nullable()}).strict(),u$=h.object({name:fe,approval:td}).strict(),i8=h.object({kind:h.literal("function"),functionId:E,definition:Qo,arguments:bt.default({}),outputs:h.record(h.string(),u$).default({})}).strict(),Ka=h.discriminatedUnion("kind",[h.object({kind:h.literal("http"),request:Ga,save:h.record(h.string(),u$).default({})}).strict(),h.object({kind:h.literal("command"),...Ha.shape}).strict(),h.object({kind:h.enum(["connect","refresh","revoke"]),input:_r}).strict()]);var eu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Za=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string()})}).parse(await n.json())}catch{throw new eu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new eu(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},WE)}};import{chmod as cDe,lstat as uDe,mkdir as lDe,open as kL,readFile as a8,rename as dDe,rm as pDe}from"node:fs/promises";import{dirname as fDe,join as TL,resolve as mDe}from"node:path";import{homedir as hDe}from"node:os";import{randomUUID as gDe}from"node:crypto";var CL=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:Py.nullable(),binding:or.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),c8=h.object({current:h.uuid(),identities:h.array(CL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Wa(){return TL(process.env.XDG_CONFIG_HOME||TL(hDe(),".config"),"foundation","identity.json")}function tu(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function l$(t){let e;try{let n=Wa(),i=await uDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await cDe(n,384);let s=c8.parse(JSON.parse(await a8(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=tu(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==tu(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return CL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==tu(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Dy(t){let e=Wa(),r;try{r=c8.parse(JSON.parse(await a8(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=CL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Cf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
129
129
|
`,!!r)}async function s8(t){if(process.platform==="win32")return;let e=await kL(t,"r");try{await e.sync()}finally{await e.close()}}async function Cf(t,e,r){let o=mDe(t),n=fDe(o);if(await lDe(n,{recursive:!0,mode:448}),!r){let s=await kL(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await s8(n);return}let i=TL(n,".foundation-"+gDe());try{let s=await kL(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await dDe(i,o),await s8(n)}finally{await pDe(i,{force:!0})}}import{spawn as _De}from"node:child_process";import{chmod as bDe,mkdtemp as SDe,rm as xDe,writeFile as EDe}from"node:fs/promises";import{tmpdir as $De}from"node:os";import{join as f8}from"node:path";import{StringDecoder as RDe}from"node:string_decoder";import{spawn as u8}from"node:child_process";import{mkdir as l8,mkdtemp as yDe,rm as vDe,writeFile as d8}from"node:fs/promises";import{tmpdir as wDe}from"node:os";import{join as Ny}from"node:path";import{StringDecoder as p8}from"node:string_decoder";function Li(t={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...t}}var zy=class{constructor(e){this.options=e;if(e.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(e.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(e,r){r.throwIfAborted();let o=await yDe(Ny(wDe(),"foundation-job-")),n=Ny(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=e.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await l8(n,{mode:448});let l={...e.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[p,f]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(p))throw new Error("Use valid file variable names.");await d8(Ny(n,p),Buffer.from(f,"base64"),{mode:384,flag:"wx"}),l[p]=s?"/run/foundation/"+p:Ny(n,p)}let d=e.command;if(s){if(Object.entries(l).some(([m,y])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m)||y.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let p=Object.entries(l).filter(([,m])=>/[\r\n]/.test(m)),f=Ny(o,"environment");await d8(f,Object.entries(l).filter(([,m])=>!/[\r\n]/.test(m)).map(([m,y])=>m+"="+y).join(`
|
|
130
|
-
`),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await l8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",f,...p.flatMap(([m,y])=>["--env",m+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(p=>{let f=u8(d[0],d.slice(1),{env:Li(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),m={stdout:new p8("utf8"),stderr:new p8("utf8")},y=0,w=!1,b=(T,M)=>{let J=Math.max(0,1e6-y);M.length>J&&(c.truncated=!0);let le=M.subarray(0,J);y+=le.length,c[T]+=m[T].write(le)};f.stdout.on("data",T=>b("stdout",T)),f.stderr.on("data",T=>b("stderr",T)),f.stdin.on("error",()=>{}),f.stdin.end(e.stdin??"");let S=()=>{u=!0;try{f.pid&&process.platform!=="win32"?process.kill(-f.pid,"SIGKILL"):f.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let I=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=m.stdout.end(),c.stderr+=m.stderr.end(),p())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),f.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",I()}),f.once("close",(T,M)=>{c.exitCode=T,c.signal=M,I()})}),c}finally{s&&u&&await new Promise(l=>{let d=u8("docker",["rm","-f",i],{env:Li(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await vDe(o,{recursive:!0,force:!0})}}};function IDe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var d$=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new RDe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function m8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await SDe(f8($De(),"foundation-"));await bDe(r,448);try{let o=Li(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=f8(r,i);await EDe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=_De(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=IDe(n),u=new d$(c,m=>process.stdout.write(m)),l=new d$(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,y)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(m??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await xDe(r,{recursive:!0,force:!0})}}import{dirname as rHe,join as VV}from"node:path";function Ao(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function p$(t,e){return[...new Set([...t.required??[],...e??t.default])]}function Ds(t){return Ao(t).requiresApp}var ADe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),h8=bt.refine(t=>Object.keys(t).every(e=>!ADe.has(e)),"Keep method-specific facts separate from common facts."),OL=h.object({accountId:h.string().max(2e3).nullable(),accountName:h.string().max(2e3),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),authorization:h8,details:h8}).strict();function DL(t){if(t.method.kind!=="oauth"||!t.oauth)throw new Error("Use OAuth connection material.");return OL.parse({accountId:t.oauth.account,accountName:t.oauth.accountName,accountVerified:t.oauth.accountVerified??!1,scopes:t.oauth.scopes,scopesStatus:t.oauth.scopesStatus??"unknown",authorization:{},details:{}})}function NL(t){if(t.method.kind!=="token"||!t.fields)throw new Error("Use token connection material.");return OL.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function zL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return OL.parse({accountId:wf(t.aws.identity.arn),accountName:t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1),accountVerified:!0,scopes:[],scopesStatus:"unknown",authorization:{aws:y5(t.aws)},details:{aws:v5(t.aws)}})}var PDe={oauth:DL,token:NL,aws:zL};function Of(t){return PDe[t.method.kind](t)}function g8(t,e=Of(t)){return e.accountVerified?e.accountId:null}function y8(t,e=Of(t)){return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...t.method.kind==="oauth"&&t.fields&&Object.keys(t.fields).length?{fields:t.fields}:{},...e.authorization,...t.state?{state:t.state}:{}}}var rJ=Vt(L8(),1);var Qa=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},eNe=class extends Qa{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},tNe=class extends Qa{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},rNe=class extends Qa{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},nNe=class extends Qa{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},oNe=class extends Qa{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},iNe=class extends Qa{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},sNe=class extends Qa{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},x$=class extends Qa{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},HL=class extends x${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},aNe=class extends x${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},cNe=class extends x${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},j8=class extends x${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},uNe=class extends Qa{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},lNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},dNe=class extends lNe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},pNe=["","+",".","/",";","?","&","#"],K8={"":{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}},fNe=new TextEncoder,F8="0123456789ABCDEF",q8=t=>ou(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),jy=(t,e)=>t[e]==="%"&&e+2<t.length&&q8(t[e+1])&&q8(t[e+2]);function BL(t,e){let r=t[e];return r==null?0:ou(Z8,W8,sd("_"))(r)?1:jy(t,e)?3:0}function mNe(t,e){if(jy(t,e))return 3;let{char:r,size:o}=Fy(t,e);return gNe(r)?o:0}function Fy(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var JL=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&jy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Fy(e,o);r+=ou(J8,s=>t&&hNe(s))(n)?n:X8(n),o+=i}return r};function zf(t){let e="";for(let r=0;r<t.length;){if(jy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Fy(t,r);e+=J8(o)?o:X8(o),r+=n}return e}function Uy(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(jy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Fy(t,n);r+=i,n+=s}return r}var Z8=t=>ou(En(65,90),En(97,122))(t.charCodeAt(0)),W8=t=>En(48,57)(t.charCodeAt(0)),J8=t=>ou(Z8,W8,e=>"-._~".includes(e))(t),hNe=t=>":/?#[]@!$&'()*+,;=".includes(t),gNe=t=>yNe(t.codePointAt(0)),yNe=t=>t!=null&&ou(sd(33),En(35,36),sd(38),En(40,59),sd(61),En(63,91),sd(93),sd(95),En(97,122),sd(126),vNe,wNe)(t);function vNe(t){if(t<65536)return ou(En(160,55295),En(63744,64975),En(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var wNe=t=>ou(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),X8=t=>Array.from(fNe.encode(t)).map(e=>`%${F8[e>>4]}${F8[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,sd=t=>e=>t===e,ou=(...t)=>e=>t.some(r=>r(e));function Y8(t,e,r){return t.map(o=>o.kind==="literal"?o.text:_Ne(o.vars,o.operator,e,r)).join("")}function _Ne(t,e,r,o){let n=K8[e],i=t.flatMap(s=>bNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function bNe(t,e,r,o){if(e==null)return[];if(PNe(e)){let n=$Ne(e,r.allowReserved);return n.length<1?[]:V8(t,"list",o)?xNe(t,n,r):[]}if(ANe(e)){let n=RNe(e,r.allowReserved);return n.length<1?[]:V8(t,"associative",o)?ENe(t,n,r):[]}return SNe(t,e,r)}function SNe(t,e,r){let o=String(e),n=t.prefix==null?o:Uy(o,t.prefix),i=JL(r.allowReserved)(n);return r.named?[Ly(zf(t.name),i,r)]:[i]}function xNe(t,e,r){let o=zf(t.name);if(t.explode)return r.named?e.map(i=>Ly(o,i,r)):[...e];let n=e.join(",");return r.named?[Ly(o,n,r)]:[n]}function ENe(t,e,r){if(t.explode)return e.map(([n,i])=>Ly(n,i,r));let o=e.flat(1).join(",");return r.named?[Ly(zf(t.name),o,r)]:[o]}var Ly=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,$Ne=(t,e)=>t.filter(r=>r!=null).map(String).map(JL(e)),RNe=(t,e)=>Object.entries(t).map(([r,o])=>[r,INe(o)]).filter(([,r])=>r!=null).map(r=>r.map(JL(e)));function INe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var ANe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),PNe=t=>Array.isArray(t);function V8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new dNe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function kNe(t,e,r){return KL(t,e,r,0,0,{})}function KL(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=n1e(i);return Y8(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?KL(t,e,r,o+1,n+s.text.length,i):null;for(let a of TNe(t,e,o,n)){let c=e.slice(n,a);for(let u of ONe(s.vars,s.operator,c)){let l=XL(i,u);if(l==null)continue;let d=KL(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*TNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*CNe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*CNe(t,e){for(let r=t;r>=e;r--)yield r}function*ONe(t,e,r){if(r===""){yield*DNe(t,e);return}let o=K8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?VNe(t,o,n):NNe(t,o,n)}var DNe=(t,e)=>(e===""||e==="+")&&t.length===1?[nu(t[0],"")]:[{}],NNe=(t,e,r)=>ZL(t,e,YL(r,e.sep),0,0);function*ZL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of zNe(i,e,r,n))for(let a of ZL(t,e,r,o+1,s.index)){let c=XL(s.bindings,a);c!=null&&(yield c)}yield*ZL(t,e,r,o+1,n)}function*zNe(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of MNe(t,e,s))yield{bindings:a,index:o+i}}}function*MNe(t,e,r){let o=Q8(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*UNe(t,e,r)),yield*o}function*UNe(t,e,r){let o=eJ(r,e.allowReserved);if(o==null)return;let n=LNe(r,e);n!=null&&(yield nu(t,n)),yield nu(t,o)}var LNe=(t,e)=>jNe(t.join(e.sep),e);function jNe(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=FNe(t,i,e.sep),a=Ya(t.slice(o,n),e.allowReserved),c=Ya(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function FNe(t,e,r){for(let o=e;o<t.length;o++)if(qNe(t,o,r))return o;return t.length}var qNe=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*Q8(t,e,r){let o=Ya(r,e.allowReserved);if(o==null)return;let n=nu(t,o);if(t.prefix!=null){yield n;return}let i=YL(r,",");if(i.length<2){yield n;return}let s=eJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?YNe(i,e.allowReserved):null;a!=null&&(yield nu(t,a)),yield nu(t,s),yield n}var VNe=(t,e,r)=>WL(t,e,YL(r,e.sep).map(XNe),0,0);function*WL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of GNe(i,e,r,n,t))for(let a of WL(t,e,r,o+1,s.index)){let c=XL(s.bindings,a);c!=null&&(yield c)}yield*WL(t,e,r,o+1,n)}function*GNe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*BNe(t,e,r,o,n);return}yield*HNe(t,e,r,o)}}function*HNe(t,e,r,o){let n=r[o];if(n.name===zf(t.name))for(let i of Q8(t,e,n.value))yield{bindings:i,index:o+1}}function*BNe(t,e,r,o,n){yield*KNe(t,e,r,o),yield*WNe(t,e,r,o,n)}function*KNe(t,e,r,o){let n=[...ZNe(zf(t.name),e,r,o)];n.length>0&&(yield{bindings:nu(t,n),index:o+n.length})}function*ZNe(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Ya(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*WNe(t,e,r,o,n){let i=[...JNe(e,r,o,new Set(n.map(s=>zf(s.name))))];i.length>0&&(yield{bindings:nu(t,Object.fromEntries(i)),index:o+i.length})}function*JNe(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=Ya(i.name,t.allowReserved),a=Ya(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function XNe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function YNe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Ya(t[o],e),i=Ya(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function eJ(t,e){let r=[];for(let o of t){let n=Ya(o,e);if(n==null)return null;r.push(n)}return r}function Ya(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var nu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function XL(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=QNe(i,n);if(s==null)return null;r[o]=s}return r}var QNe=(t,e)=>S$(t)||S$(e)?e1e(t,e):t1e(t.value,e.value)?t:null;function e1e(t,e){let r=G8(t.value),o=G8(e.value);if(r==null||o==null)return null;let n=S$(t),i=S$(e);if(!n&&!i)return null;if(n&&!i)return Uy(o,t.prefix)===r?e:null;if(!n&&i)return Uy(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Uy(o,s)===r?e:null:Uy(r,a)===o?t:null}var S$=t=>t.prefix!=null,G8=t=>typeof t=="string"?t:null;function t1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):H8(t)?H8(e)&&r1e(Object.entries(t),Object.entries(e)):t===e}var r1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),H8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),n1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),YL=(t,e)=>e===""?[t]:t.split(e),o1e=["=",",","!","@","|"];function i1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new oNe(e,r));let n=t[0];if(u1e(n))return o(new iNe(e,r+1,n));if(!B8(n)&&BL(t,0)<1)return o(new sNe(e,r+1,n));let i=B8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:s1e(t,e,r+1,s)}}function s1e(t,e,r,o){if(o>=t.length)throw new HL(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new j8(e,r+i):new HL(e,r+i);let s=i,a=a1e(t,i);if(a===s)throw new HL(e,r+i);let c=t.slice(s,a);i=a;let u=c1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new uNe(e,r+i,t[i]):new aNe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new j8(e,r+i-1)}return n}function a1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=BL(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||BL(t,r+1)<1)break;r++,o=!0}return r}function c1e(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&l1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new cNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function B8(t){return pNe.includes(t)&&t!==""}function u1e(t){return o1e.includes(t)}function l1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function d1e(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new eNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new rNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(i1e(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new tNe(t,i)),n(s),i++;continue}let a=mNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Fy(t,i);r(new nNe(t,i,c)),n(c),i+=u}return o}var E$=class tJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=g1e(r),this.#e=p1e(d1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new tJ(e,r)}get tokens(){return this.#e}expand=e=>Y8(this.#e,e,this.#t);match=e=>kNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},p1e=t=>Object.freeze(t.map(f1e)),f1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(m1e))}),m1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),h1e=()=>{},g1e=({strict:t,report:e})=>(e??=h1e,t??=!0,e=t?y1e(e):e,{strict:t,report:e}),y1e=t=>e=>{throw t(e),e};var ji=class extends Error{constructor(r,o){super(o);this.code=r}code};function Mf(t,e,r={}){let o=(i,s)=>{throw new ji(i,s)},n={...r,...e};for(let i of t)i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,rJ.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.");return Object.keys(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function $$(t,e,r={}){let o=Mf(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new ji("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function R$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new ji("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new ji("encrypted_input_required","Supply private material directly with your encryption keys.")}return Mf(t.map(r=>({...r,required:!1})),e)}function ec(t,e){return R$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function Uf(t,e,r){R$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new ji("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}var ad=h.record(h.string().max(100),h.string().max(16384)),iu=h.object({format:h.literal(1),methodId:h.string().min(1),generation:E,clientId:h.string().max(1e3),clientSecret:h.string().max(16384).optional(),fields:ad}).strict(),ej=h.object({accessToken:h.string().min(1).max(16384),refreshToken:h.string().min(1).max(16384).optional(),expiresAt:h.number().nullable(),refreshExpiresAt:h.number().optional(),scopes:h.array(h.string()),requestedScopes:h.array(h.string()).optional(),account:h.string(),accountName:h.string(),accountVerified:h.boolean().optional(),scopesStatus:h.enum(["unknown","requested","reported"]).optional(),extra:ad,facts:bt}).strict(),QL={format:h.literal(2),methodId:h.string().min(1),method:Yl,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:h.literal("reconnect").optional()},qy=h.never().optional(),co=h.union([h.object({...QL,method:VE,oauth:ej,fields:ad.optional(),aws:qy}).strict(),h.object({...QL,method:GE,fields:ad,oauth:qy,aws:qy}).strict(),h.object({...QL,method:HE,aws:LE,oauth:qy,fields:qy}).strict()]).superRefine((t,e)=>{if(t.method.kind==="oauth"&&t.fields)try{R$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}t.method.kind==="oauth"&&Ds(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the OAuth application required by this connection."}),t.method.kind!=="oauth"&&t.appId!==null&&e.addIssue({code:"custom",message:"Only OAuth connections use an application."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),xbt=h.object({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),generation:E,fields:ad.optional()}).strict(),v1e=h.object({methodId:h.string().min(1).max(200),methodKind:lL,generation:E,authorizationDigest:gr,appId:E.nullable(),accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),outputs:h.array(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:h.enum(["ready","reconnect"]),fields:ad.optional(),aws:jE.optional()}).strict();async function I$(t,e=Of(t)){let r=Ao(t.method).outputs,o=t.method.kind!=="aws"&&t.fields?ec(t.method.config.fields,t.fields):{},n=await ee(y8(t,e));return v1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:n,appId:t.appId,accountId:g8(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...Object.keys(o).length?{fields:o}:{},...e.details})}var w1e=h.array(h.object({name:h.string(),label:h.string(),value:h.string()}).strict()),nJ=h.object({methodName:fe,account:h.string().max(2e3),settings:w1e.optional()}).strict();function A$(t,e=Of(t)){let r=Ao(t.method).fields,o=t.method.kind!=="aws"&&t.fields?ec(r,t.fields):{},n=r.filter(i=>o[i.name]).map(i=>({name:i.name,label:i.label,value:i.choices?.find(s=>s.value===o[i.name])?.label??o[i.name]}));return{methodName:t.method.name,account:e.accountName,...n.length?{settings:n}:{}}}var _1e=h.object({action:h.literal("start"),flowId:E,name:fe,methodId:h.string().min(1),method:Yl,appId:E.nullable(),fields:ad.default({}),scopes:h.array(h.string().max(1e3)).max(200).default([]),redirectUri:h.url().optional(),aws:Va.optional()}).strict().superRefine((t,e)=>{t.aws&&t.method.kind!=="aws"&&e.addIssue({code:"custom",message:"Choose one authentication configuration for this connection method."})}),Vy=h.discriminatedUnion("action",[_1e,h.object({action:h.literal("exchange"),flowId:E,parameters:h.string().max(16384)}).strict(),h.object({action:h.literal("commit"),flowId:E,authorizationDigest:gr,approval:td}).strict(),h.object({action:h.literal("refresh"),id:E}).strict(),h.object({action:h.literal("revoke"),id:E}).strict()]);var oJ=Ts.extend({name:fe}),Cbt=h.object({bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ts,token:h.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),iJ=h.object({id:E,executorId:E,ownerId:E,name:fe,origin:h.url(),bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:h.object({port:h.number().int().min(1).max(65535)}).strict().optional(),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),Obt=Ts.extend({previousSignature:br.optional()}).strict(),Dbt=h.object({name:fe,content:en,labels:nJ.optional(),version:h.number().int().positive().optional()}).strict(),P$=h.object({content:en,version:h.number().int().positive()}).strict(),sJ=h.object({id:E,reason:h.enum(["grantExpired"])}).strict(),Nbt=h.record(E,h.object({version:h.number().int().positive(),content:en}).strict()),aJ=h.object({id:E,name:fe,version:h.number().int().positive(),content:en,policy:ao}).strict(),cJ=h.object({registration:RL,stoppedAt:h.iso.datetime().nullable(),heartbeatAt:h.iso.datetime().nullable()}).strict(),uJ=h.object({lease:E,request:Yc,sources:h.array(en).max(100)}).strict().nullable(),b1e=h.object({lease:E}).strict(),zbt=b1e.extend({receipt:Oy}).strict(),Gy=h.object({id:E,resource_id:E,executor_id:E,expected_revision:h.number().int().positive(),state:h.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:h.string().regex(/^\d+$/),result:en.nullable()}),Mbt=h.object({id:E,resourceId:E,expectedRevision:h.number().int().positive()}).strict(),S1e=h.object({fence:h.string().regex(/^\d+$/)}).strict(),Ubt=S1e.extend({content:en}).strict(),Lbt=h.object({id:E,runId:E,stateDigest:gr,expiresAt:Ie}).strict(),k$=h.object({id:E,runId:E,context:h.string(),sealed:$o.nullable(),expiresAt:Ie,receivedAt:Ie.nullable()}).strict(),lJ=(t,e)=>"oauth-callback:"+t+":"+e;var tc=class extends Error{constructor(r,o){super(o);this.code=r}code},tj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},T$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||C(r)!==C(e))throw new tc("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Ts);return await wL(r),{...r,fingerprint:await Ql(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new tc("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},cJ);if(await Pf(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},Qr(oJ));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await wL(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},P$);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await Io(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=xL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&ao.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await ee(o)!==i.digest)throw new tc("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!n$(i.policy,o))throw new tc("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return If((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Qr(aJ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||C(i.content)!==C(n.content))throw new tc("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await $f(await If(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...Ef(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return ao.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await $f(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},Yr);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await $f(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},h.union([Yr,st]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Qr(sJ))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},Yr),a=await If(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ge.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Qr(Yr));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ge.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await Rf(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Ka.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],p=await this.sourceContents([...d,...n.sourceIds??[]]),f=await this.policy(e,ge.executionResult,[],{id:a});f.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let m={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await ee(s.manifest),operation:de[i.kind],operationDigest:await ee(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(p.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await ee(w.policy),...w.policy.contentType===ge.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:f.readers,...s.manifest.resultVersion?{resultApproval:await Rf(f,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await kf(s,m);let y=w=>w.policy.contentType===ge.clientCredential;for(let w of p)await od(w,y(w)&&m.operation!==de.connect&&m.operation!==de.revoke?{...m,operation:de.refresh}:m,y(w)?{}:{destination:l?.url});return X5(m,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},zr)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new tj(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},zr);if(C(o.intent)!==C(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await vL(e.requestSignature,e.intent.actor.signing,"run");if(C(r.intent)!==C(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new tc("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?o8(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(C(e.intent.actor)!==C(this.binding)||C(e.intent.executor)!==C(this.binding))throw new tc("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,ge.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await AL(e.intent,e.receipt.state,r,this.keys,await Rf(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},zr)}};import{lstat as x1e,mkdir as E1e,readFile as $1e,readdir as R1e}from"node:fs/promises";import{join as dJ}from"node:path";var pJ=h.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),cd=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:pJ.parse(e)})}async read(e){let r=this.context(e),o=dJ(this.directory,e+".json");try{let n=await x1e(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=h.string().max(32e6).parse(JSON.parse(await $1e(o,"utf8"))),s=await _y(i,await Yo(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(ks(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 write(e,r){let o=this.context(e),n={context:o,value:r},i=await ur(n,this.privateKeys.signing,"journal"),s=nt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new vf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Yo(this.binding.encryption,"ECDH-ES+A256KW"));await E1e(this.directory,{recursive:!0,mode:448}),await Cf(dJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await R1e(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>pJ.parse(o.name.slice(0,-5)))}};var C$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Cs(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await ee(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&C(r)!==C(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var dt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function F(t,e,r,o){throw new dt(t,e,r,o)}var O$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},uJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},zr)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},h.object({id:E}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},k$),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Gy),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Gy),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},en),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Gy),state:r=>e.json("/api/connections/"+r+"/operation",{},Gy.nullable())}}};import{randomBytes as Vde,randomUUID as tHe}from"node:crypto";function I1e(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[o.name]=n}return r}function D$(t,e){let r=I1e(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ha.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(p=>p.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,p)=>{if(!t.parameters.some(f=>f.name===p))throw new Error("Declare every function parameter.");return Object.hasOwn(r,p)?n(r[p]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,p])=>[d,i(p,l)])):u},s=new E$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Ga.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.");return{kind:"http",request:a}}function fJ(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var mJ=h.object({operation:Ka,save:h.record(h.string(),fe)}).strict();function N$(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function hJ(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=e$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name==="connection.connect"){let n=t$.parse(r.invocation.input),i=bt.parse(e.kind==="connect"?e.input:null);if(e.kind!=="connect"||i.flowId!==r.continuationId||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Use the reviewed connection and execution environment.");if(i.action==="start"&&(i.methodId!==n.methodId||i.name!==n.name||i.appId!==(n.appId??null)||await ee(i.method)!==n.methodDigest))throw new Error("Use the reviewed connection method and application.");if(!["start","exchange","commit"].includes(String(i.action)))throw new Error("Continue the reviewed connection.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=Ty.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await ee(N$(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(C(e.request)!==C(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(e)!==C(Ka.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&C(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==C(o.save))throw new Error("Use the reviewed output destinations.")}function Hy(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function Po(t,e){for(let r of Hy(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function rj(t,e,r){let o=Hy(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function Lf(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function su(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{lookup as A1e}from"node:dns/promises";import{isIP as vJ}from"node:net";import{request as P1e}from"node:https";import{brotliDecompressSync as k1e,gunzipSync as T1e,inflateSync as C1e}from"node:zlib";var M$=Vt(yJ(),1),O1e=M$.default.IPv6.parseCIDR("2000::/3"),D1e=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function wJ(t){if(!vJ(t)||t.includes("%"))return!1;let e=M$.default.parse(t);return D1e.has(e.range())&&(!(e instanceof M$.default.IPv6)||e.match(O1e))}function ud(t,e){let r;try{r=new URL(t)}catch{F(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&F(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||vJ(o)&&!wJ(o))&&F(400,"private_destination","Choose a public HTTPS destination."),r}var U$=class{constructor(e){this.origin=e}origin;async send(e){let r=ud(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&F(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&F(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await A1e(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!wJ(u.address)))&&F(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(f,m,y)=>{m.all?y(null,[a]):y(null,a.address,a.family)}},p=P1e(r,d,f=>{let m=[],y=0;f.on("data",w=>{y+=w.length,y>n?f.destroy(new dt(413,"body_limit","The response body is too large.")):m.push(w)}),f.on("error",l),f.on("end",()=>{try{let w=Buffer.concat(m),b=f.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?T1e:b==="deflate"?C1e:b==="br"?k1e:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,I]of Object.entries(f.headers))I!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(I)?I.join(", "):I);u({status:f.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&F(409,"cancelled","The operation was cancelled."),F(502,"service_unavailable","The service could not be reached. Try again.")}}};function jf(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{F(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&F(502,"invalid_response","The service returned an invalid response."),e}function zs(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function L$(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!P5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=nt(Lf(Po(JSON.parse(zs(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=zs(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}function N1e(t,e){return t.policy.contentType===ge.value?e.output===void 0:t.policy.contentType===ge.tokenSet&&e.output!==void 0}var ko=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},j$=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Tf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Tf(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await ee(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Tf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await Y5(r.request,this.binding,this.keys);await kf(this.environment,p.intent);let f=Ka.parse(p.operation);if(de[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await hJ(o,f),await this.validateOperation(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.executeOperation(f,o,r.sources,c);d=await Tf(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(p){if(p instanceof ko)throw p;p instanceof Af&&(p=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||!(p instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(p.code));d=await Tf(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof dt?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?D$(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async validateOperation(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await Io(c);let u=r.sources.find(p=>p.id===c.policy.id);if(!u||!await EL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await ee(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(de[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(ud(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=Hy(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");rj(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(Hy(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await Os(u.approval);if(C(l.policy.authorities.find(d=>d.id===l.authorityId))!==C(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==ge.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&C(d.executor)===C(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?D$(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!N1e(u,c))throw new Error("Use the input named in the signed request.");await od(u,r,{...n?{destination:n.url}:{}}),await Qc(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async executeOperation(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?D$(e.definition,e.arguments):e,a=[],c=new Map,u=async m=>{let y=o.find(b=>b.policy.id===m.id);if(y.policy.contentType===ge.value)return Qc(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(m.id)||c.set(m.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(m.id);if(!m.output||!Object.hasOwn(w,m.output))throw new Error("Choose an available connection output.");return nt(w[m.output])};if(s.kind==="command"){let m=await L$(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:m.environment,files:m.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new dt(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new dt(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new dt(422,"function_failed",su(y.stderr,m.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,su(y.stdout,m.sensitive))}return{...y,stdout:su(y.stdout,m.sensitive),stderr:su(y.stderr,m.sensitive)}}let l=structuredClone(i);for(let m of l.bindings){let y="";for(let w of m.parts)if(typeof w=="string")y+=w;else{let b=zs(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}rj(l,m.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let p=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(p.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,su(zs(p.body),a))}let f=e.kind==="http"?e.save:{};if(Object.keys(f).length){if(p.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let m={};for(let[y,w]of Object.entries(f)){let b=p.body;if(y!==""){let x=Po(JSON.parse(zs(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=nt(typeof x=="string"?x:JSON.stringify(x))}let S=await rd(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});m[w.name]=(await this.broker.capture(w.name,S)).id}return{status:p.status,saved:m}}return{status:p.status,headers:Object.fromEntries(Object.entries(p.headers).map(([m,y])=>[m,su(y,a)])),body:su(zs(p.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:_r.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:Po(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=nt(typeof c=="string"?c:JSON.stringify(c)),l=await rd(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};var hc=Vt(_V(),1);import{randomUUID as e3e}from"node:crypto";function nde(t){let e=UE.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&F(502,"invalid_response","The AWS account could not be verified."),e.data}function ode(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&wf(t.arn)===wf(e.arn)}function bV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&F(409,"reconnect_required","Reconnect with current AWS credentials.")}var ak=class{async obtain(e,r,o){let n=Va.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};bV(s?.expiration);let a=new hc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();bV(d.expiration),c=new hc.STSClient({region:n.region,credentials:d});let p=nde(await c.send(new hc.GetCallerIdentityCommand({}),{abortSignal:u}));r&&!ode(p,r.sourceIdentity)&&F(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,m=p;if(n.role){l=!0;let b=(await c.send(new hc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+e3e().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&F(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},bV(f.expiration),c.destroy(),c=new hc.STSClient({region:n.region,credentials:f}),m=nde(await c.send(new hc.GetCallerIdentityCommand({}),{abortSignal:u}));let S=n.role.arn.split(":");(m.accountId!==S[4]||m.arn.split(":")[1]!==S[1]||m.arn.split(":")[5]?.split("/").slice(0,2).join("/")!=="assumed-role/"+n.role.arn.split("/").at(-1))&&F(502,"account_changed","The requested AWS role could not be verified.")}return r&&!ode(m,r.identity)&&F(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:LE.parse({...n,sourceIdentity:p,identity:m}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&F(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&F(409,"reconnect_required","Reconnect with current AWS credentials."),l&&F(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),F(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};import{randomUUID as t3e}from"node:crypto";var ck=class{constructor(e){this.aws=e}aws;facts=zL;validate(e){e.aws||F(400,"aws_authentication_required","Choose AWS authentication for this executor.")}async start({input:e,signal:r}){let o=(await this.aws.obtain(e.aws,void 0,r)).state;return{kind:"ready",material:co.parse({format:2,methodId:e.methodId,method:e.method,generation:t3e(),appId:null,appGeneration:null,aws:o})}}needsRenewal(){return!1}async check(e,r){await this.outputs(e,null,r)}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};import{randomUUID as Q3e}from"node:crypto";var SV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(SV="oauth4webapi/v3.8.8");function e_(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Sa="ERR_INVALID_ARG_VALUE",xa="ERR_INVALID_ARG_TYPE";function $r(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var TV=Symbol(),r3e=Symbol(),n3e=Symbol(),CV=Symbol();var Jw=Symbol();var o3e=new TextEncoder,i3e=new TextDecoder;function xV(t){return typeof t=="string"?o3e.encode(t):i3e.decode(t)}var EV;Uint8Array.prototype.toBase64?EV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):EV=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var $V;Uint8Array.fromBase64?$V=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw $r("The input to be decoded is not correctly encoded.",Sa,e)}}:$V=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw $r("The input to be decoded is not correctly encoded.",Sa,e)}};function RV(t){return typeof t=="string"?$V(t):EV(t)}var uh=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=O3e,Error.captureStackTrace?.(this,this.constructor)}},Xw=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function Re(t,e,r){return new Xw(t,{code:e,cause:r})}function s3e(t){return t.toLowerCase().replace(/^application\//,"")}function Yw(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function OV(t){e_(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(SV&&!e.has("user-agent")&&e.set("user-agent",SV),e.has("authorization"))throw $r('"options.headers" must not include the "authorization" header name',Sa);return e}function a3e(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw $r('"options.signal" must return or be an instance of AbortSignal',xa);return e}}function uk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw $r(`${r} must be a number`,xa,n);if(t>0)return;if(e){if(t!==0)throw $r(`${r} must be a non-negative number`,Sa,n);return}throw $r(`${r} must be a positive number`,Sa,n)}catch(i){throw o?Re(i.message,o,n):i}}function fn(t,e,r,o){try{if(typeof t!="string")throw $r(`${e} must be a string`,xa,o);if(t.length===0)throw $r(`${e} must not be empty`,Sa,o)}catch(n){throw r?Re(n.message,r,o):n}}function ade(t){u3e(t,"application/json")}function c3e(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return Re(r,N3e,t)}function u3e(t,e){if(fde(t)!==e)throw c3e(t,e)}async function cde(t){return fn(t,"codeVerifier"),RV(await crypto.subtle.digest("SHA-256",xV(t)))}function DV(t){let e=t?.[r3e];return typeof e=="number"&&Number.isFinite(e)?e:0}function NV(t){let e=t?.[n3e];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function ude(){return Math.floor(Date.now()/1e3)}function Qu(t){if(typeof t!="object"||t===null)throw $r('"as" must be an object',xa);fn(t.issuer,'"as.issuer"')}function el(t){if(typeof t!="object"||t===null)throw $r('"client" must be an object',xa);fn(t.client_id,'"client.client_id"')}function ide(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function lde(t){return fn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function dde(t){return fn(t,'"clientSecret"'),(e,r,o,n)=>{let i=ide(r.client_id),s=ide(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function pde(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var l3e=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function d3e(t,e){if(e&&t.protocol!=="https:")throw Re("only requests to HTTPS are allowed",M3e,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Re("only HTTP and HTTPS requests are allowed",U3e,t)}function sde(t,e,r,o){let n;if(typeof t!="string"||!(n=l3e(t)))throw Re(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?L3e:j3e,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return d3e(n,o),n}function zV(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?sde(t.mtls_endpoint_aliases[e],e,r,o):sde(t[e],e,r,o)}var IV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=C3e,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Qw=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=D3e,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)}},AV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=T3e,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},lk="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",p3e="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",f3e='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',m3e="("+lk+")\\s*=\\s*"+f3e,h3e="("+lk+")\\s*=\\s*("+lk+")",g3e=new RegExp("^[,\\s]*("+lk+")"),y3e=new RegExp("^[,\\s]*"+m3e+"[,\\s]*(.*)"),v3e=new RegExp("^[,\\s]*"+h3e+"[,\\s]*(.*)"),w3e=new RegExp("^("+p3e+")(?:$|[,\\s])(.*)");function _3e(t){if(!e_(t,Response))throw $r('"response" must be an instance of Response',xa);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(g3e),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(y3e)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(v3e)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(w3e)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function b3e(t){if(t.status>399&&t.status<500){fk(t),ade(t);try{let e=await t.clone().json();if(Yw(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function MV(t,e,r){if(t.status!==e){x3e(t);let o;throw(o=await b3e(t))?(await t.body?.cancel(),new IV("server responded with an error in the response body",{cause:o,response:t})):Re(`"response" is not a conform ${r} response (unexpected HTTP status code)`,z3e,t)}}function S3e(t){if(!jV.has(t))throw $r('"options.DPoP" is not a valid DPoPHandle',Sa)}function fde(t){return t.headers.get("content-type")?.split(";")[0]}async function UV(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[CV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:a3e(o,s?.signal)})}async function LV(t,e,r,o,n,i){let s=zV(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[TV]!==!0);n.set("grant_type",o);let a=OV(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(S3e(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await UV(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function mde(t,e,r,o,n){Qu(t),el(e),fn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),LV(t,e,r,"refresh_token",i,n)}var hde=new WeakMap,gde=new WeakMap;function yde(t){if(!t.id_token)return;let e=hde.get(t);if(!e)throw $r('"ref" was already garbage collected or did not resolve from the proper sources',Sa);return e}async function mk(t,e,r,o,n,i){if(Qu(t),el(e),!e_(r,Response))throw $r('"response" must be an instance of Response',xa);await MV(r,200,"Token Endpoint"),fk(r);let s=await Mde(r);if(fn(s.access_token,'"response" body "access_token" property',St,{body:s}),fn(s.token_type,'"response" body "token_type" property',St,{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;uk(a,!0,'"response" body "expires_in" property',St,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&fn(s.refresh_token,'"response" body "refresh_token" property',St,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw Re('"response" body "scope" property must be a string',St,{body:s});if(s.id_token!==void 0){fn(s.id_token,'"response" body "id_token" property',St,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(uk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await R3e(t,e,s.id_token,a,n);A3e(e,c),I3e(c),gde.set(r,u),hde.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new uh("unsupported `token_type` value",{cause:{body:s}});return s}function x3e(t){let e;if(e=_3e(t))throw new AV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function vde(t,e,r,o){return mk(t,e,r,void 0,o?.[Jw],o?.recognizedTokenTypes)}function wde(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw Re('unexpected JWT "aud" (audience) claim value',lh,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw Re('unexpected JWT "aud" (audience) claim value',lh,{expected:t,claims:e.claims,claim:"aud"});return e}function _de(t,e){let r=t[G3e]?.(e)??t.issuer;if(e.claims.iss!==r)throw Re('unexpected JWT "iss" (issuer) claim value',lh,{expected:r,claims:e.claims,claim:"iss"});return e}var jV=new WeakSet;function E3e(t){return jV.add(t),t}var FV=Symbol();async function bde(t,e,r,o,n,i,s){if(Qu(t),el(e),!jV.has(o))throw $r('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Sa);fn(n,'"redirectUri"');let a=Gd(o,"code");if(!a)throw Re('no authorization code in "callbackParameters"',St);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==FV&&(fn(i,'"codeVerifier"'),c.set("code_verifier",i)),LV(t,e,r,"authorization_code",c,s)}var Sde={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function xde(t,e){for(let r of t)if(e.claims[r]===void 0)throw Re(`JWT "${r}" (${Sde[r]}) claim missing`,St,{claims:e.claims});return e}function $3e(t,e){if(typeof e.claims[t]!="string")throw Re(`unexpected JWT "${t}" (${Sde[t]}) claim type`,St,{claims:e.claims});return e}function R3e(t,e,r,o,n){return Dde(r,Nde.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),DV(e),NV(e),n).then(xde.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(_de.bind(void 0,t)).then(wde.bind(void 0,e.client_id)).then($3e.bind(void 0,"sub"))}function Ede(t,e){if(e===pk)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?pk:(uk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function I3e(t){t.auth_time!==void 0&&uk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',St,{claims:t})}function $de(t,e,r){if(r===pk)return;let o=ude()+DV(t),n=NV(t);if(e.auth_time+r<o-n)throw Re("too much time has elapsed since the last End-User authentication",kV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Rde(t,e){let r=e===dk?void 0:e;if(t.nonce!==r)throw Re('unexpected ID Token "nonce" claim value',lh,{expected:r,claims:t,claim:"nonce"})}function A3e(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw Re('ID Token "aud" (audience) claim includes additional untrusted audiences',lh,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw Re('unexpected ID Token "azp" (authorized party) claim value',lh,{expected:t.client_id,claims:e,claim:"azp"})}}var dk=Symbol(),pk=Symbol();async function Ide(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?P3e(t,e,r,o.expectedNonce,o.maxAge,o[Jw],o.recognizedTokenTypes):k3e(t,e,r,o?.maxAge,o?.[Jw],o?.recognizedTokenTypes)}async function P3e(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=dk;break;case dk:break;default:fn(o,'"expectedNonce" argument'),a.push("nonce")}n=Ede(e,n),n!==pk&&a.push("auth_time");let c=await mk(t,e,r,a,i,s);fn(c.id_token,'"response" body "id_token" property',St,{body:c});let u=yde(c);return $de(e,u,n),Rde(u,o),c}async function k3e(t,e,r,o,n,i){let s=await mk(t,e,r,void 0,n,i),a=yde(s);return a&&($de(e,a,Ede(e,o)),Rde(a,dk)),s}var T3e="OAUTH_WWW_AUTHENTICATE_CHALLENGE",C3e="OAUTH_RESPONSE_BODY_ERROR",O3e="OAUTH_UNSUPPORTED_OPERATION",D3e="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var PV="OAUTH_PARSE_ERROR",St="OAUTH_INVALID_RESPONSE";var N3e="OAUTH_RESPONSE_IS_NOT_JSON",z3e="OAUTH_RESPONSE_IS_NOT_CONFORM",M3e="OAUTH_HTTP_REQUEST_FORBIDDEN",U3e="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",kV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",lh="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var L3e="OAUTH_MISSING_SERVER_METADATA",j3e="OAUTH_INVALID_SERVER_METADATA";function F3e(t,e){if(typeof e.header.typ!="string"||s3e(e.header.typ)!==t)throw Re('unexpected JWT "typ" header parameter value',St,{header:e.header});return e}async function Ade(t,e,r,o,n){return Qu(t),el(e),LV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Pde(t,e,r,o){return mk(t,e,r,void 0,o?.[Jw],o?.recognizedTokenTypes)}async function kde(t,e,r,o,n){Qu(t),el(e),fn(o,'"token"');let i=zV(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[TV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=OV(n?.headers);return a.delete("accept"),UV(t,e,r,i,s,a,n)}async function Tde(t){if(!e_(t,Response))throw $r('"response" must be an instance of Response',xa);await MV(t,200,"Revocation Endpoint")}function fk(t){if(t.bodyUsed)throw $r('"response" body has been used already',Sa)}async function Cde(t,e,r,o,n){Qu(t),el(e),fn(o,'"token"');let i=zV(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[TV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=OV(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),UV(t,e,r,i,s,a,n)}async function Ode(t,e,r,o){if(Qu(t),el(e),!e_(r,Response))throw $r('"response" must be an instance of Response',xa);await MV(r,200,"Introspection Endpoint");let n;if(fde(r)==="application/token-introspection+jwt"){fk(r);let{claims:i,jwt:s}=await Dde(await r.text(),Nde.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),DV(e),NV(e),o?.[Jw]).then(F3e.bind(void 0,"token-introspection+jwt")).then(xde.bind(void 0,["aud","iat","iss"])).then(_de.bind(void 0,t)).then(wde.bind(void 0,e.client_id));if(gde.set(r,s),!Yw(i.token_introspection))throw Re('JWT "token_introspection" claim must be a JSON object',St,{claims:i});n=i.token_introspection}else fk(r),n=await Mde(r);if(typeof n.active!="boolean")throw Re('"response" body "active" property must be a boolean',St,{body:n});return n}async function Dde(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new uh("JWE decryption is not configured",{cause:t});if(a!==3)throw Re("Invalid JWT",St,t);let c;try{c=JSON.parse(xV(RV(i)))}catch(d){throw Re("failed to parse JWT Header body as base64url encoded JSON",PV,d)}if(!Yw(c))throw Re("JWT Header must be a top level object",St,t);if(e(c),c.crit!==void 0)throw new uh('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(xV(RV(s)))}catch(d){throw Re("failed to parse JWT Payload body as base64url encoded JSON",PV,d)}if(!Yw(u))throw Re("JWT Payload must be a top level object",St,t);let l=ude()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw Re('unexpected JWT "exp" (expiration time) claim type',St,{claims:u});if(u.exp<=l-o)throw Re('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',kV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw Re('unexpected JWT "iat" (issued at) claim type',St,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw Re('unexpected JWT "iss" (issuer) claim type',St,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw Re('unexpected JWT "nbf" (not before) claim type',St,{claims:u});if(u.nbf>l+o)throw Re('unexpected JWT "nbf" (not before) claim value',kV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw Re('unexpected JWT "aud" (audience) claim type',St,{claims:u});return{header:c,claims:u,jwt:t}}function Nde(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw Re('unexpected JWT "alg" header parameter',St,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw Re('unexpected JWT "alg" header parameter',St,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw Re('unexpected JWT "alg" header parameter',St,{header:o,expected:r,reason:"default value"});return}throw Re('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Gd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw Re(`"${e}" parameter must be provided only once`,St);return r}var q3e=Symbol(),V3e=Symbol();function zde(t,e,r,o){if(Qu(t),el(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw $r('"parameters" must be an instance of URLSearchParams, or URL',xa);if(Gd(r,"response"))throw Re('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',St,{parameters:r});let n=Gd(r,"iss"),i=Gd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw Re('response parameter "iss" (issuer) missing',St,{parameters:r});if(n&&n!==t.issuer)throw Re('unexpected "iss" (issuer) response parameter value',St,{expected:t.issuer,parameters:r});switch(o){case void 0:case V3e:if(i!==void 0)throw Re('unexpected "state" response parameter encountered',St,{expected:void 0,parameters:r});break;case q3e:break;default:if(fn(o,'"expectedState" argument'),i!==o)throw Re(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',St,{expected:o,parameters:r})}if(Gd(r,"error"))throw new Qw("authorization response from the server is an error",{cause:r});let a=Gd(r,"id_token"),c=Gd(r,"token");if(a!==void 0||c!==void 0)throw new uh("implicit and hybrid flows are not supported");return E3e(new URLSearchParams(r))}async function Mde(t,e=ade){let r;try{r=await t.json()}catch(o){throw e(t),Re('failed to parse "response" body as JSON',PV,o)}if(!Yw(r))throw Re('"response" body must be a top level object',St,{body:r});return r}var G3e=Symbol();import{createHash as H3e}from"node:crypto";function tl(t,e){try{return ud(new E$(t).expand(e)).href}catch{F(400,"invalid_service_url","Check the service URL and its required fields.")}}var hk=t=>H3e("sha256").update(t).digest("hex"),t_=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],gk=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&F(502,"invalid_response","The service returned an invalid expiry."),e};var Lde=Object.assign(Object.create(null),{dpop:()=>F(502,"invalid_response","The service returned an unsupported token.")}),B3e={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Lde,{"user access token":()=>{}}),refreshInspection:!0,async inspect(t){let{app:e,current:r}=t,{server:o,client:n}=t.configuration(),i=await Cde({...o,introspection_endpoint:o.token_endpoint+"/introspect"},n,t.authentication("basic"),r.accessToken,{...t.options(),additionalParameters:{token_type_hint:"access_token"}}),s;try{s=await Ode(o,n,Response.json(await t.json(i),{status:i.status}))}catch{F(409,"reconnect_required","Reconnect this service to renew access.")}return(s.active!==!0||s.client_id!==e.clientId||typeof s.sub!="string"||!s.sub||typeof s.exp!="number"||s.exp*1e3<=Date.now())&&F(409,"reconnect_required","Reconnect this service to renew access."),{...r,account:s.sub,accountName:typeof s.username=="string"?s.username:s.sub,scopes:t_(s.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(r.expiresAt??1/0,s.exp*1e3)}}},K3e={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&F(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key",allowAccountChange:!0,refreshInspection:!0,async inspect({transport:t,current:e}){let r=await t.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+e.accessToken}}),o=jf(r);(r.status!==200||!o.data||typeof o.data!="object")&&F(409,"reconnect_required","Reconnect this service to renew access.");let n=o.data;return{...e,account:hk(e.accessToken),accountName:typeof n.label=="string"?n.label:"OpenRouter",facts:n}}},Z3e={verifyIdentity({current:t,response:e}){e.headers["x-oauth-scopes"]!==void 0&&(t.scopes=t_(e.headers["x-oauth-scopes"].replaceAll(","," ")),t.scopesStatus="reported")}},W3e={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+Buffer.from(t.clientId+":"+(t.clientSecret??"")).toString("base64"),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},J3e={verifyIdentity({data:t}){t.email_verified!==!0&&F(502,"invalid_response","The service account could not be verified.")}},X3e=Object.assign(Object.create(null),{ebay:B3e,openrouter:K3e,github:Z3e,google:J3e}),Y3e=[{matches:t=>t.hostname.endsWith(".myshopify.com"),service(t,e){return{...e.pathname==="/admin/oauth/access_token"?{normalizeToken(r){r.token_type===void 0&&(r.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...t.grantType==="client_credentials"&&/^\/admin\/api\/[^/]+\/graphql\.json$/.test(e.pathname)?{identityRequest({spec:r,url:o,current:n}){return{url:o,method:r.identity.method,headers:{...r.identity.headers,"content-type":"application/json","X-Shopify-Access-Token":n.accessToken},body:JSON.stringify({query:"{ shop { id name myshopifyDomain } }"})}},verifyIdentity({app:r,data:o}){((Array.isArray(o.errors)?o.errors.length:o.errors)||Po(o,"/data/shop/myshopifyDomain")!==r.fields.shop+".myshopify.com")&&F(502,"invalid_response","The Shopify store could not be verified.")}}:{}}}},{matches:t=>t.hostname==="api.notion.com"&&t.pathname==="/v1/oauth/token",service:()=>({normalizeToken(t){t.refresh_token===null&&delete t.refresh_token}})}];function ho(t,e){let r=e?new URL(e):void 0,o=r?Y3e.find(i=>i.matches(r))?.service(t,r):void 0,n=t.adapter?X3e[t.adapter]:void 0;return t.adapter&&!n&&F(400,"invalid_input","Choose a supported service authentication adapter."),{recognizedTokenTypes:Lde,...o,...n,...t.revoke?.style==="github"?W3e:{},...o?.verifyIdentity||n?.verifyIdentity?{verifyIdentity(i){o?.verifyIdentity?.(i),n?.verifyIdentity?.(i)}}:{}}}var yk=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...$$(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof ji&&F(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&F(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(tl(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:ho(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await cde(n),c.code_challenge_method="S256"),ho(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(tl(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:tl(e.tokenUrl,this.appValues(e,r))};return e.issuer&&ud(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?pde():(e.clientSecret||F(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?dde(e.clientSecret):lde(e.clientSecret))}options(e="form"){return{[CV]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return jf({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&Po(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&F(409,"reconnect_required","Reconnect this service to renew access."),r===429&&F(503,"service_rate_limit","The service is busy. Try again later."),F(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&F(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,ho(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=gk(u.expires_in));try{let d=await(n?vde:e.grantType==="client_credentials"?Pde:Ide)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:ho(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;F(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[ho(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&F(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+gk(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&F(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?t_(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+gk(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&F(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=ho(e);if(l.exchange){let f=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>tl(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,f.status,jf(f))}else{let{server:f,client:m}=this.configuration(e,r),y;try{let w=zde(f,m,o.parameters,o.state);y=await bde(f,m,this.authentication(r,e.clientAuth),w,l.redirectUri?.(r,i)??i,e.pkce?n:FV,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(w){throw(w instanceof Xw||w instanceof Qw)&&F(400,"invalid_state","Start the connection again."),w}u=await this.tokenResponse(e,r,y)}let d=this.token(e,u,s,a);await c?.(d,u);let p=await this.inspect(e,r,d,u);return a&&p.account!==a.account&&!l.allowAccountChange&&F(409,"account_changed","Reconnect using the same service account."),p}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&F(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=ho(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Ade(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e.tokenFormat)),d=await this.tokenResponse(e,r,l),p={...this.token(e,d,o,n,!!n),requestedScopes:o};await i?.(p,d);let f=await this.inspect(e,r,p,d);return n&&f.account!==n.account&&F(409,"account_changed","Reconnect using the same service account."),f}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||F(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&F(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await mde(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return(e.identity?.url||ho(e).refreshInspection)&&(i=await this.inspect(e,r,i)),i.account!==o.account&&F(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{},s=ho(e);if(s.inspect)return s.inspect({spec:e,app:r,transport:this.transport,current:o,configuration:()=>this.configuration(e,r),authentication:l=>this.authentication(r,l),options:()=>this.options(),json:l=>this.json(l)});if(e.identity?.url){let l=tl(e.identity.url,{...this.appValues(e,r),...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),d=ho(e,l),p=await this.transport.send(d.identityRequest?.({spec:e,app:r,transport:this.transport,url:l,current:o})??{url:l,method:e.identity.method,headers:{...e.identity.headers,authorization:"Bearer "+o.accessToken}});i=jf(p),(p.status===401||p.status===403)&&F(409,"reconnect_required","Reconnect this service to renew access."),p.status>=400&&F(502,"invalid_response","The service account could not be verified."),d.verifyIdentity?.({spec:e,app:r,transport:this.transport,current:o,response:p,data:i})}else e.identity?.from==="app"&&(i=this.appValues(e,r));let a=l=>{for(let d of Array.isArray(l)?l:[l]){let p=Po(i,d);if(typeof p=="string"&&p||typeof p=="number")return String(p)}return""},c=e.identity?.id,u=c?Array.isArray(c)?c.map(l=>a(l)).filter(Boolean).join(":"):a(c):o.account||r.fields.domain||r.fields.shop||hk(o.accessToken);return(!u||u.length>1e3)&&F(502,"invalid_response","The service account could not be verified."),{...o,account:u,accountName:e.identity&&a(e.identity.name)||u,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||F(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=tl(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await kde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Tde(d)}catch{F(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64")),(await this.transport.send(ho(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&F(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,Lf(Po(n,s))]))}};function r_(t,e,r={}){try{return Mf(t,e,r)}catch(o){throw o instanceof ji&&F(400,o.code,o.message),o}}function gc(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function Hd(t){return t||F(409,"app_required","Choose an OAuth application."),t}function qV(t){let e=gc(t).scopes;return p$(e,t.scopes)}function jde(t,e,r){let o=ec(gc(t).fields,e.fields);return co.parse({format:2,methodId:t.methodId,method:t.method,generation:Q3e(),appId:t.appId,appGeneration:t.appId?e.generation:null,oauth:r,...Object.keys(o).length?{fields:o}:{}})}function Fde(t){return{token:ej.parse(t.token),response:bt.parse(t.response)}}var vk=class{constructor(e){this.transport=e}transport;facts=DL;oauth(e){return new yk({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}validate(e,r){let o=gc(e),n=Hd(r);ho(o),r_(o.fields,n.fields,o.defaults);for(let i of o.fields)i.secret===!1&&e.fields[i.name]&&n.fields[i.name]!==e.fields[i.name]&&F(409,"wrong_app","Choose an application with the approved service settings.");Ao(e.method).requiresApp&&o.clientAuth!=="none"&&!n.clientSecret&&F(409,"app_required","Add a client secret to this OAuth application.")}async start(e){let{input:r,signal:o}=e,n=gc(r),i=Hd(e.app);if(n.grantType!=="client_credentials")return{kind:"authorize",url:await this.oauth(o).authorize(n,i,e.state,e.verifier,r.redirectUri,qV(r))};await e.dispatch();let s=await this.oauth(o).clientCredentials(n,i,qV(r),void 0,(a,c)=>e.receive({token:a,response:c}));return{kind:"ready",material:jde(r,i,s)}}async exchange(e,r,o){let{input:n,signal:i}=e,s=gc(n),a=Hd(e.app),c=new URLSearchParams(r);(c.getAll("state").length!==1||c.get("state")!==e.state)&&F(400,"invalid_state","Start the connection again.");let u;if(o){let l=Fde(o);u=await this.oauth(i).inspect(s,a,l.token,l.response)}else await e.dispatch(),u=await this.oauth(i).exchange(s,a,{parameters:c,state:e.state},e.verifier,n.redirectUri,qV(n),void 0,(l,d)=>e.receive({token:l,response:d}));return jde(n,a,u)}needsRenewal(e){return e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=await this.oauth(e.signal).refresh(gc(e.material),Hd(e.app),e.material.oauth,(o,n)=>e.receive({token:o,response:n}));return co.parse({...e.material,oauth:r})}async recover(e,r,o){let n=Fde(o),i=await this.oauth().inspect(gc(e),Hd(r),n.token,n.response);return co.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(gc(e),Hd(r),e.oauth)}async revoke(e,r,o){await this.oauth(o).revoke(gc(e),Hd(r),e.oauth)}};import{randomUUID as eHe}from"node:crypto";function wk(t){if(t.method.kind!=="token")throw new Error("Use a token connection provider.");return t.method.config}var _k=class{facts=NL;validate(e){r_(wk(e).fields,e.fields)}async start({input:e}){return{kind:"ready",material:co.parse({format:2,methodId:e.methodId,method:e.method,generation:eHe(),appId:null,appGeneration:null,fields:r_(wk(e).fields,e.fields)})}}needsRenewal(){return!1}async outputs(e){let r=$$(wk(e).fields,e.fields);return Object.fromEntries(Object.entries(wk(e).outputs).map(([o,n])=>[o,Lf(Po(r,n))]))}};function qde(t,e){return{oauth:new vk(t),token:new _k,aws:new ck(e)}}var dh=class{constructor(e,r,o,n,i,s=new ak){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=qde(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers[Ao(e).family]}metadata(e){return I$(e,this.provider(e.method).facts(e))}labels(e){return A$(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||F(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=co.safeParse(JSON.parse(zs(await Qc(e,r,this.keys,{destination:o}))));n.success||F(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&F(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==de.revoke&&F(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,ge.clientCredential,n),s=iu.parse(JSON.parse(zs(await Qc(i,o,this.keys))));return s.methodId!==r&&F(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(Ao(e.method).application==="none")return null;if(!Ds(e.method))return iu.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===de.revoke?de.revoke:de.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&F(409,"app_changed","Reconnect this service with the current application."),e.method.kind==="oauth"&&Object.entries(e.fields??{}).some(([s,a])=>i.fields[s]!==a)&&F(409,"app_changed","Reconnect this service with the current application settings."),i}async flow(e,r){let o=await this.readFlow(e);return(!o||o.expiresAt<=Date.now()||C(o.actor)!==C(r.actor)||o.ownerId!==r.ownerId)&&F(409,"connection_expired","Start the connection again."),o}async readFlow(e){let r=await this.journal.read("connect_"+e);return r&&(!Vy.safeParse(r.input).success||r.material&&!co.safeParse(r.material).success)&&F(409,"connection_expired","Start the connection again."),r}writeFlow(e,r){return this.journal.write("connect_"+e,r)}async startApp(e,r,o){return Ao(e.method).application==="none"?null:e.appId?this.app(e.appId,e.methodId,r,o):iu.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}})}authorization(e,r,o){return{input:r.input,app:r.app,state:r.state,verifier:r.verifier,signal:o,dispatch:async()=>{r.phase="exchanging",await this.writeFlow(e,r)},receive:async n=>{r.checkpoint=n,r.phase="received",await this.writeFlow(e,r)}}}async validate(e,r,o){let n=Vy.parse(e),i=de[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&F(400,"wrong_operation","Use the approved connection operation."),n.action==="start"){if(Ds(n.method)&&!n.appId&&F(400,"app_required","Choose an OAuth application."),Ao(n.method).browserAuthorization){n.redirectUri||F(400,"invalid_redirect","Choose a callback URL.");let s=new URL(n.redirectUri);(s.username||s.password||s.hash||s.search||!(n.redirectUri===r.origin+"/oauth/callback"||s.protocol==="http:"&&["127.0.0.1","[::1]"].includes(s.hostname)))&&F(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.")}this.provider(n.method).validate(n,await this.startApp(n,r,o))}else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await Os(n.approval);(!s.material||n.authorizationDigest!==(await this.metadata(s.material)).authorizationDigest||a.policy.contentType!==ge.tokenSet||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||C(a.policy.authorities.find(c=>c.id===a.authorityId))!==C(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&C(c.executor)===C(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&F(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);C(a)!==C(s.app)&&F(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,ge.tokenSet,o),a=await this.material(s,r);await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=Vy.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&F(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o,n);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,ge.tokenSet,o),c=await this.material(a,r);if(i.action==="refresh"){await this.provider(c.method).check?.(c,n);let l=await this.refresh(a,c,r,o,n);return{kind:"refreshed",id:a.policy.id,...await this.metadata(l)}}let u=this.provider(c.method);return u.revoke||F(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await u.revoke(c,await this.connectionApp(c,r,o),n),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:{...await this.metadata(r.material),...this.labels(r.material)}}}async start(e,r,o,n){await this.readFlow(e.flowId)&&F(409,"flow_exists","Use a new connection request.");let i={actor:r.actor,ownerId:r.ownerId,input:e,app:await this.startApp(e,r,o),state:Vde(32).toString("base64url"),verifier:Vde(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:"authorize"};await this.writeFlow(e.flowId,i);let s=await this.provider(e.method).start(this.authorization(e.flowId,i,n));return s.kind==="ready"?(i.material=s.material,i.phase="review",await this.writeFlow(e.flowId,i),this.review(e.flowId,i)):(e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await ee(i.state),expiresAt:new Date(i.expiresAt).toISOString()}),{kind:"authorize",flowId:e.flowId,url:s.url})}async exchange(e,r,o){let n=await this.flow(e.flowId,r);if(n.phase==="review")return this.review(e.flowId,n);let i=this.provider(n.input.method);return(!i.exchange||!["authorize","received"].includes(n.phase))&&F(409,"connection_uncertain","Check the connection before authorizing it again."),n.material=await i.exchange(this.authorization(e.flowId,n,o),e.parameters,n.phase==="received"?n.checkpoint:void 0),n.phase="review",await this.writeFlow(e.flowId,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r);if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||F(409,"approval_required","Review this connection before saving."),o.content?(C(o.content.policy)!==C(e.approval.policy)||o.content.creationRunId!==r.id)&&F(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await rd(nt(C(o.material)),e.approval,r.id,this.binding,this.keys,await this.metadata(o.material)),o.phase="committing",await this.writeFlow(e.flowId,o));let n;try{n=await this.broker.capture(o.input.name,o.content,this.labels(o.material))}catch(i){throw i instanceof dt&&i.status<500?i:new ko}return o.phase="committed",await this.writeFlow(e.flowId,o),{kind:"connected",id:n.id}}async recover(e,r){let o=Vy.parse(e);if(o.action!=="commit")return null;let n=await this.readFlow(o.flowId);if(!n?.content||n.ownerId!==r.ownerId||C(n.actor)!==C(r.actor)||n.content.creationRunId!==r.id||C(n.content.policy)!==C(o.approval.policy)||!["committing","committed"].includes(n.phase))return null;try{await this.broker.capture(n.input.name,n.content,this.labels(n.material))}catch(i){if(i instanceof dt&&i.status<500)return null;throw new ko}return n.phase="committed",await this.writeFlow(o.flowId,n),{kind:"connected",id:n.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&F(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&F(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await J5(e.previous,nt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||F(409,"reconnect_required","Reconnect this service to renew access.");try{await od(e,{...o,operation:de.refresh},{destination:s})}catch{F(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=tHe(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let p=await a.renew({material:r,app:c,signal:i,receive:async f=>{d.checkpoint=f,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,p)}catch(p){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),p instanceof dt&&["connection_review","reconnect_required","account_changed"].includes(p.code))throw p;F(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};function Cn(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=VV(rHe(Wa()),"custody",r.id),i=new cd(VV(n,"client"),o,r,e),s=new T$(t,o,r,e,new C$(i)),a=new O$(t),c=new U$(o),u=new dh(r,e,a.connections(),new cd(VV(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Gde(t,e){let{custody:r,keys:o,binding:n,connections:i}=Cn(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await ee(n),operation:de.command,functionDigest:null,operationDigest:await ee(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await ee(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ge.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return L$(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===ge.value)return Qc(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return nt(d[u.output])})}import{mkdir as Hnt}from"node:fs/promises";import{join as J_}from"node:path";import{setTimeout as Bnt}from"node:timers/promises";import{spawn as nHe}from"node:child_process";import{constants as GV}from"node:fs";import{open as Hde,rm as oHe}from"node:fs/promises";async function Bde(t){if(process.platform!=="linux"){let r=await Hde(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await oHe(t,{force:!0})}}let e=await Hde(t,GV.O_CREAT|GV.O_WRONLY|GV.O_NOFOLLOW,384);try{let r=nHe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var mD=Vt(_V(),1),hD=Vt(R0e(),1);function I0e(t){return $L.safeParse(t).success?t:null}async function A0e(t=3e3){let e=new mD.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new mD.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=I0e(n.Arn);if(i)return i;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new hD.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new hD.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=I0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var UG=h.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),LG=UG.max(4096).startsWith("/"),P0e=h.object({command:h.array(UG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:LG.optional(),environment:h.record(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),UG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:h.string().max(1e6).default(""),timeoutSeconds:h.number().int().min(1).max(3600).default(60)}).strict(),yKt=P0e.extend({id:E.optional()}),k0e=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),T0e=h.object({exitCode:h.number().int().nullable(),signal:h.string().max(32).nullable(),stdout:h.string().max(1e6),stderr:h.string().max(1e6),timedOut:h.boolean(),truncated:h.boolean()}).strict(),vKt=h.object({state:k0e.exclude(["queued","running"]),result:T0e.nullable(),error:h.string().max(100).nullable()}).strict(),gD=P0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:LG,state:k0e,result:T0e.nullable(),error:h.string().nullable(),createdAt:Ie,startedAt:Ie.nullable(),finishedAt:Ie.nullable()}).strict(),wKt=gD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),_Kt=h.object({workingDirectory:LG}).strict(),C0e=h.object({lease:E,process:gD}).strict().nullable();var yD=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},C0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},gD)}},vD=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new ko}return!0}};var wD=h.object({format:h.literal(1),functionId:E,ownerId:E,revision:h.number().int().positive(),definition:Qo,author:or,executor:or,createdAt:Ie,signature:br}).strict();async function O0e(t,e){return wD.parse({...t,signature:await ur(t,e.signing,"function-publication")})}async function D0e(t,e){let r=wD.parse(t),{signature:o,...n}=r;if(await Cs(n.author),await Nr(n,o,n.author.signing,"function-publication"),e&&C(n.executor)!==C(e))throw new Error("This function is approved for another executor.");return r}var jG=h.object({functionId:E,publication:wD,contents:h.record(E,h.object({version:h.number().int().positive(),content:en}).strict())}).strict(),Cnt=h.object({name:fe,definition:Qo,authorization:jG}).strict(),TKt=Cnt.extend({version:h.number().int().positive()}),Ont=h.object({id:E.optional(),ownerId:E.optional(),arguments:bt.default({}),outputs:h.record(h.string().max(500),u$).default({})}).strict(),N0e=h.object({code:h.string().max(100),message:h.string().max(1e3)}).strict(),z0e=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,state:a$,result:_r.nullable(),error:N0e.nullable(),createdAt:Ie,startedAt:Ie.nullable(),finishedAt:Ie.nullable()}).strict(),Dnt=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,actor:or.nullable(),arguments:bt,outputs:Ont.shape.outputs,definitionDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:Ie,expiresAt:Ie}).strict(),M0e=h.object({id:E,requestDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),state:a$.exclude(["queued","running"]),result:_r.nullable(),error:N0e.nullable(),finishedAt:Ie,signature:br}).strict(),U0e=h.object({lease:E,request:Dnt,publication:wD,sources:h.array(en).max(100)}).strict().nullable();var _D=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/invocations/claim",{method:"POST",body:{}},U0e)}dispatch(e,r){return this.api.json("/api/runtime/functions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/runtime/functions/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean(),reason:h.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(e,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:e,completion:r}},z0e)}},bD=class{constructor(e,r,o,n=15e3){this.executor=e;this.broker=r;this.journal=o;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(e,r,o,n){let i={id:e.id,requestDigest:e.digest,state:r,result:o,error:n,finishedAt:new Date().toISOString()};e.completion=M0e.parse({...i,signature:await ur(i,this.executor.keys.signing,"function-result")}),e.phase="settled",await this.journal.write("invocation_"+e.id,e)}async deliver(e){await this.broker.finish(e.lease,e.completion),e.delivered=!0,await this.journal.write("invocation_"+e.id,e)}async reconcile(){let e=[];for(let r of await this.journal.keys("invocation_"))try{let o=await this.journal.read(r);if(!o||o.delivered||o.phase==="prepared")continue;o.completion||await this.complete(o,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(o)}catch{e.push(r.slice(11))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:o,publication:n,sources:i,lease:s}=r,a=await ee(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),p=!1,f=!1,m=setInterval(()=>{f||(f=!0,this.broker.renew(o.id,s).then(y=>{y.active||(p||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{f=!1}))},this.renewalMilliseconds);m.unref();try{if(await D0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await ee(n.definition)!==o.definitionDigest||Date.parse(o.expiresAt)<=Date.now())throw new Error("Run the current approved function in its configured environment.");let y="function_"+n.functionId,w=await this.journal.read(y),b=await ee(n);if(w&&(n.revision<w.revision||n.revision===w.revision&&w.digest!==b))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(y,{revision:n.revision,digest:b});let S=i8.parse({kind:"function",functionId:o.functionId,definition:n.definition,arguments:o.arguments,outputs:o.outputs}),x={format:2,id:o.id,origin:this.executor.environment.manifest.origin,ownerId:o.ownerId,actor:o.actor??this.executor.binding,executor:this.executor.binding,environmentId:n.definition.environmentId,environmentDigest:await ee(this.executor.environment.manifest),operation:de.function,operationDigest:await ee(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await ee(T.policy),materialRevision:T.materialRevision,...T.policy.contentType===ge.tokenSet&&typeof T.metadata.authorizationDigest=="string"?{authorizationDigest:T.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:o.createdAt,expiresAt:o.expiresAt};await kf(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let I=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(I)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",I,null)}catch(y){if(y instanceof ko)throw y;let w=u.phase==="dispatched",b=d.aborted&&p?"cancelled":w&&(d.aborted||!(y instanceof dt))?"uncertain":"failed";await this.complete(u,b,null,!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="uncertain"?"execution_uncertain":b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="uncertain"?"Check the result before invoking this function again.":b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(m)}try{await this.deliver(u)}catch{throw new ko}return!0}};import{spawn as Nnt,execFile as znt}from"node:child_process";import{chmod as Mnt,lstat as L0e,mkdir as FG,readFile as j0e,readdir as Unt,realpath as F0e,rename as Lnt,rm as jnt,symlink as Fnt,writeFile as q0e}from"node:fs/promises";import{join as ll}from"node:path";import{promisify as qnt}from"node:util";import{createConnection as Vnt}from"node:net";import{setTimeout as Gnt}from"node:timers/promises";var qG=qnt(znt),W_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',SD=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=ll(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await FG(this.options.directory,{recursive:!0,mode:448}),await FG(this.sessions,{recursive:!0,mode:448}),await FG(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await L0e(this.options.workspaceLink),await F0e(this.options.workspaceLink)!==await F0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await Fnt(this.options.workspace,this.options.workspaceLink)}let e=ll(this.options.directory,"host_ed25519");try{await L0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await qG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Li(),timeout:1e4})}await Mnt(e,384),this.hostKey=hy.parse((await qG("ssh-keygen",["-y","-f",e],{env:Li(),timeout:1e4})).stdout);let r=ll(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+W_(e),"PidFile "+W_(ll(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+W_(ll(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+W_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+W_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
|
|
130
|
+
`),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await l8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",f,...p.flatMap(([m,y])=>["--env",m+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(p=>{let f=u8(d[0],d.slice(1),{env:Li(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),m={stdout:new p8("utf8"),stderr:new p8("utf8")},y=0,w=!1,b=(T,M)=>{let J=Math.max(0,1e6-y);M.length>J&&(c.truncated=!0);let le=M.subarray(0,J);y+=le.length,c[T]+=m[T].write(le)};f.stdout.on("data",T=>b("stdout",T)),f.stderr.on("data",T=>b("stderr",T)),f.stdin.on("error",()=>{}),f.stdin.end(e.stdin??"");let S=()=>{u=!0;try{f.pid&&process.platform!=="win32"?process.kill(-f.pid,"SIGKILL"):f.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let I=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=m.stdout.end(),c.stderr+=m.stderr.end(),p())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),f.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",I()}),f.once("close",(T,M)=>{c.exitCode=T,c.signal=M,I()})}),c}finally{s&&u&&await new Promise(l=>{let d=u8("docker",["rm","-f",i],{env:Li(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await vDe(o,{recursive:!0,force:!0})}}};function IDe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var d$=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new RDe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function m8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await SDe(f8($De(),"foundation-"));await bDe(r,448);try{let o=Li(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=f8(r,i);await EDe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=_De(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=IDe(n),u=new d$(c,m=>process.stdout.write(m)),l=new d$(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,y)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(m??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await xDe(r,{recursive:!0,force:!0})}}import{dirname as rHe,join as VV}from"node:path";function Ao(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function p$(t,e){return[...new Set([...t.required??[],...e??t.default])]}function Ds(t){return Ao(t).requiresApp}var ADe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),h8=bt.refine(t=>Object.keys(t).every(e=>!ADe.has(e)),"Keep method-specific facts separate from common facts."),OL=h.object({accountId:h.string().max(2e3).nullable(),accountName:h.string().max(2e3),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),authorization:h8,details:h8}).strict();function DL(t){if(t.method.kind!=="oauth"||!t.oauth)throw new Error("Use OAuth connection material.");return OL.parse({accountId:t.oauth.account,accountName:t.oauth.accountName,accountVerified:t.oauth.accountVerified??!1,scopes:t.oauth.scopes,scopesStatus:t.oauth.scopesStatus??"unknown",authorization:{},details:{}})}function NL(t){if(t.method.kind!=="token"||!t.fields)throw new Error("Use token connection material.");return OL.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function zL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return OL.parse({accountId:wf(t.aws.identity.arn),accountName:t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1),accountVerified:!0,scopes:[],scopesStatus:"unknown",authorization:{aws:y5(t.aws)},details:{aws:v5(t.aws)}})}var PDe={oauth:DL,token:NL,aws:zL};function Of(t){return PDe[t.method.kind](t)}function g8(t,e=Of(t)){return e.accountVerified?e.accountId:null}function y8(t,e=Of(t)){return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...t.method.kind==="oauth"&&t.fields&&Object.keys(t.fields).length?{fields:t.fields}:{},...e.authorization,...t.state?{state:t.state}:{}}}var rJ=Vt(L8(),1);var Qa=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},eNe=class extends Qa{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},tNe=class extends Qa{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},rNe=class extends Qa{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},nNe=class extends Qa{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},oNe=class extends Qa{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},iNe=class extends Qa{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},sNe=class extends Qa{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},x$=class extends Qa{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},HL=class extends x${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},aNe=class extends x${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},cNe=class extends x${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},j8=class extends x${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},uNe=class extends Qa{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},lNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},dNe=class extends lNe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},pNe=["","+",".","/",";","?","&","#"],K8={"":{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}},fNe=new TextEncoder,F8="0123456789ABCDEF",q8=t=>ou(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),jy=(t,e)=>t[e]==="%"&&e+2<t.length&&q8(t[e+1])&&q8(t[e+2]);function BL(t,e){let r=t[e];return r==null?0:ou(Z8,W8,sd("_"))(r)?1:jy(t,e)?3:0}function mNe(t,e){if(jy(t,e))return 3;let{char:r,size:o}=Fy(t,e);return gNe(r)?o:0}function Fy(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var JL=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&jy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Fy(e,o);r+=ou(J8,s=>t&&hNe(s))(n)?n:X8(n),o+=i}return r};function zf(t){let e="";for(let r=0;r<t.length;){if(jy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Fy(t,r);e+=J8(o)?o:X8(o),r+=n}return e}function Uy(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(jy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Fy(t,n);r+=i,n+=s}return r}var Z8=t=>ou(En(65,90),En(97,122))(t.charCodeAt(0)),W8=t=>En(48,57)(t.charCodeAt(0)),J8=t=>ou(Z8,W8,e=>"-._~".includes(e))(t),hNe=t=>":/?#[]@!$&'()*+,;=".includes(t),gNe=t=>yNe(t.codePointAt(0)),yNe=t=>t!=null&&ou(sd(33),En(35,36),sd(38),En(40,59),sd(61),En(63,91),sd(93),sd(95),En(97,122),sd(126),vNe,wNe)(t);function vNe(t){if(t<65536)return ou(En(160,55295),En(63744,64975),En(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var wNe=t=>ou(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),X8=t=>Array.from(fNe.encode(t)).map(e=>`%${F8[e>>4]}${F8[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,sd=t=>e=>t===e,ou=(...t)=>e=>t.some(r=>r(e));function Y8(t,e,r){return t.map(o=>o.kind==="literal"?o.text:_Ne(o.vars,o.operator,e,r)).join("")}function _Ne(t,e,r,o){let n=K8[e],i=t.flatMap(s=>bNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function bNe(t,e,r,o){if(e==null)return[];if(PNe(e)){let n=$Ne(e,r.allowReserved);return n.length<1?[]:V8(t,"list",o)?xNe(t,n,r):[]}if(ANe(e)){let n=RNe(e,r.allowReserved);return n.length<1?[]:V8(t,"associative",o)?ENe(t,n,r):[]}return SNe(t,e,r)}function SNe(t,e,r){let o=String(e),n=t.prefix==null?o:Uy(o,t.prefix),i=JL(r.allowReserved)(n);return r.named?[Ly(zf(t.name),i,r)]:[i]}function xNe(t,e,r){let o=zf(t.name);if(t.explode)return r.named?e.map(i=>Ly(o,i,r)):[...e];let n=e.join(",");return r.named?[Ly(o,n,r)]:[n]}function ENe(t,e,r){if(t.explode)return e.map(([n,i])=>Ly(n,i,r));let o=e.flat(1).join(",");return r.named?[Ly(zf(t.name),o,r)]:[o]}var Ly=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,$Ne=(t,e)=>t.filter(r=>r!=null).map(String).map(JL(e)),RNe=(t,e)=>Object.entries(t).map(([r,o])=>[r,INe(o)]).filter(([,r])=>r!=null).map(r=>r.map(JL(e)));function INe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var ANe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),PNe=t=>Array.isArray(t);function V8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new dNe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function kNe(t,e,r){return KL(t,e,r,0,0,{})}function KL(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=n1e(i);return Y8(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?KL(t,e,r,o+1,n+s.text.length,i):null;for(let a of TNe(t,e,o,n)){let c=e.slice(n,a);for(let u of ONe(s.vars,s.operator,c)){let l=XL(i,u);if(l==null)continue;let d=KL(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*TNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*CNe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*CNe(t,e){for(let r=t;r>=e;r--)yield r}function*ONe(t,e,r){if(r===""){yield*DNe(t,e);return}let o=K8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?VNe(t,o,n):NNe(t,o,n)}var DNe=(t,e)=>(e===""||e==="+")&&t.length===1?[nu(t[0],"")]:[{}],NNe=(t,e,r)=>ZL(t,e,YL(r,e.sep),0,0);function*ZL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of zNe(i,e,r,n))for(let a of ZL(t,e,r,o+1,s.index)){let c=XL(s.bindings,a);c!=null&&(yield c)}yield*ZL(t,e,r,o+1,n)}function*zNe(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of MNe(t,e,s))yield{bindings:a,index:o+i}}}function*MNe(t,e,r){let o=Q8(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*UNe(t,e,r)),yield*o}function*UNe(t,e,r){let o=eJ(r,e.allowReserved);if(o==null)return;let n=LNe(r,e);n!=null&&(yield nu(t,n)),yield nu(t,o)}var LNe=(t,e)=>jNe(t.join(e.sep),e);function jNe(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=FNe(t,i,e.sep),a=Ya(t.slice(o,n),e.allowReserved),c=Ya(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function FNe(t,e,r){for(let o=e;o<t.length;o++)if(qNe(t,o,r))return o;return t.length}var qNe=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*Q8(t,e,r){let o=Ya(r,e.allowReserved);if(o==null)return;let n=nu(t,o);if(t.prefix!=null){yield n;return}let i=YL(r,",");if(i.length<2){yield n;return}let s=eJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?YNe(i,e.allowReserved):null;a!=null&&(yield nu(t,a)),yield nu(t,s),yield n}var VNe=(t,e,r)=>WL(t,e,YL(r,e.sep).map(XNe),0,0);function*WL(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of GNe(i,e,r,n,t))for(let a of WL(t,e,r,o+1,s.index)){let c=XL(s.bindings,a);c!=null&&(yield c)}yield*WL(t,e,r,o+1,n)}function*GNe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*BNe(t,e,r,o,n);return}yield*HNe(t,e,r,o)}}function*HNe(t,e,r,o){let n=r[o];if(n.name===zf(t.name))for(let i of Q8(t,e,n.value))yield{bindings:i,index:o+1}}function*BNe(t,e,r,o,n){yield*KNe(t,e,r,o),yield*WNe(t,e,r,o,n)}function*KNe(t,e,r,o){let n=[...ZNe(zf(t.name),e,r,o)];n.length>0&&(yield{bindings:nu(t,n),index:o+n.length})}function*ZNe(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Ya(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*WNe(t,e,r,o,n){let i=[...JNe(e,r,o,new Set(n.map(s=>zf(s.name))))];i.length>0&&(yield{bindings:nu(t,Object.fromEntries(i)),index:o+i.length})}function*JNe(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=Ya(i.name,t.allowReserved),a=Ya(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function XNe(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function YNe(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Ya(t[o],e),i=Ya(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function eJ(t,e){let r=[];for(let o of t){let n=Ya(o,e);if(n==null)return null;r.push(n)}return r}function Ya(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var nu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function XL(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=QNe(i,n);if(s==null)return null;r[o]=s}return r}var QNe=(t,e)=>S$(t)||S$(e)?e1e(t,e):t1e(t.value,e.value)?t:null;function e1e(t,e){let r=G8(t.value),o=G8(e.value);if(r==null||o==null)return null;let n=S$(t),i=S$(e);if(!n&&!i)return null;if(n&&!i)return Uy(o,t.prefix)===r?e:null;if(!n&&i)return Uy(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Uy(o,s)===r?e:null:Uy(r,a)===o?t:null}var S$=t=>t.prefix!=null,G8=t=>typeof t=="string"?t:null;function t1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):H8(t)?H8(e)&&r1e(Object.entries(t),Object.entries(e)):t===e}var r1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),H8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),n1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),YL=(t,e)=>e===""?[t]:t.split(e),o1e=["=",",","!","@","|"];function i1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new oNe(e,r));let n=t[0];if(u1e(n))return o(new iNe(e,r+1,n));if(!B8(n)&&BL(t,0)<1)return o(new sNe(e,r+1,n));let i=B8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:s1e(t,e,r+1,s)}}function s1e(t,e,r,o){if(o>=t.length)throw new HL(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new j8(e,r+i):new HL(e,r+i);let s=i,a=a1e(t,i);if(a===s)throw new HL(e,r+i);let c=t.slice(s,a);i=a;let u=c1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new uNe(e,r+i,t[i]):new aNe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new j8(e,r+i-1)}return n}function a1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=BL(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||BL(t,r+1)<1)break;r++,o=!0}return r}function c1e(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&l1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new cNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function B8(t){return pNe.includes(t)&&t!==""}function u1e(t){return o1e.includes(t)}function l1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function d1e(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new eNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new rNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(i1e(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new tNe(t,i)),n(s),i++;continue}let a=mNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Fy(t,i);r(new nNe(t,i,c)),n(c),i+=u}return o}var E$=class tJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=g1e(r),this.#e=p1e(d1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new tJ(e,r)}get tokens(){return this.#e}expand=e=>Y8(this.#e,e,this.#t);match=e=>kNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},p1e=t=>Object.freeze(t.map(f1e)),f1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(m1e))}),m1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),h1e=()=>{},g1e=({strict:t,report:e})=>(e??=h1e,t??=!0,e=t?y1e(e):e,{strict:t,report:e}),y1e=t=>e=>{throw t(e),e};var ji=class extends Error{constructor(r,o){super(o);this.code=r}code};function Mf(t,e,r={}){let o=(i,s)=>{throw new ji(i,s)},n={...r,...e};for(let i of t)i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,rJ.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.");return Object.keys(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function $$(t,e,r={}){let o=Mf(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new ji("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function R$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new ji("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new ji("encrypted_input_required","Supply private material directly with your encryption keys.")}return Mf(t.map(r=>({...r,required:!1})),e)}function ec(t,e){return R$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function Uf(t,e,r){R$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new ji("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}var ad=h.record(h.string().max(100),h.string().max(16384)),iu=h.object({format:h.literal(1),methodId:h.string().min(1),generation:E,clientId:h.string().max(1e3),clientSecret:h.string().max(16384).optional(),fields:ad}).strict(),ej=h.object({accessToken:h.string().min(1).max(16384),refreshToken:h.string().min(1).max(16384).optional(),expiresAt:h.number().nullable(),refreshExpiresAt:h.number().optional(),scopes:h.array(h.string()),requestedScopes:h.array(h.string()).optional(),account:h.string(),accountName:h.string(),accountVerified:h.boolean().optional(),scopesStatus:h.enum(["unknown","requested","reported"]).optional(),extra:ad,facts:bt}).strict(),QL={format:h.literal(2),methodId:h.string().min(1),method:Yl,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:h.literal("reconnect").optional()},qy=h.never().optional(),co=h.union([h.object({...QL,method:VE,oauth:ej,fields:ad.optional(),aws:qy}).strict(),h.object({...QL,method:GE,fields:ad,oauth:qy,aws:qy}).strict(),h.object({...QL,method:HE,aws:LE,oauth:qy,fields:qy}).strict()]).superRefine((t,e)=>{if(t.method.kind==="oauth"&&t.fields)try{R$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}t.method.kind==="oauth"&&Ds(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the OAuth application required by this connection."}),t.method.kind!=="oauth"&&t.appId!==null&&e.addIssue({code:"custom",message:"Only OAuth connections use an application."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),xbt=h.object({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),generation:E,fields:ad.optional()}).strict(),v1e=h.object({methodId:h.string().min(1).max(200),methodKind:lL,generation:E,authorizationDigest:gr,appId:E.nullable(),accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),outputs:h.array(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:h.enum(["ready","reconnect"]),fields:ad.optional(),aws:jE.optional()}).strict();async function I$(t,e=Of(t)){let r=Ao(t.method).outputs,o=t.method.kind!=="aws"&&t.fields?ec(t.method.config.fields,t.fields):{},n=await ee(y8(t,e));return v1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:n,appId:t.appId,accountId:g8(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...Object.keys(o).length?{fields:o}:{},...e.details})}var w1e=h.array(h.object({name:h.string(),label:h.string(),value:h.string()}).strict()),nJ=h.object({methodName:fe,account:h.string().max(2e3),settings:w1e.optional()}).strict();function A$(t,e=Of(t)){let r=Ao(t.method).fields,o=t.method.kind!=="aws"&&t.fields?ec(r,t.fields):{},n=r.filter(i=>o[i.name]).map(i=>({name:i.name,label:i.label,value:i.choices?.find(s=>s.value===o[i.name])?.label??o[i.name]}));return{methodName:t.method.name,account:e.accountName,...n.length?{settings:n}:{}}}var _1e=h.object({action:h.literal("start"),flowId:E,name:fe,methodId:h.string().min(1),method:Yl,appId:E.nullable(),fields:ad.default({}),scopes:h.array(h.string().max(1e3)).max(200).default([]),redirectUri:h.url().optional(),aws:Va.optional()}).strict().superRefine((t,e)=>{t.aws&&t.method.kind!=="aws"&&e.addIssue({code:"custom",message:"Choose one authentication configuration for this connection method."})}),Vy=h.discriminatedUnion("action",[_1e,h.object({action:h.literal("exchange"),flowId:E,parameters:h.string().max(16384)}).strict(),h.object({action:h.literal("commit"),flowId:E,authorizationDigest:gr,approval:td}).strict(),h.object({action:h.literal("refresh"),id:E}).strict(),h.object({action:h.literal("revoke"),id:E}).strict()]);var oJ=Ts.extend({name:fe}),Cbt=h.object({bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ts,token:h.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),iJ=h.object({id:E,executorId:E,ownerId:E,name:fe,origin:h.url(),bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:h.object({port:h.number().int().min(1).max(65535)}).strict().optional(),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),Obt=Ts.extend({previousSignature:br.optional()}).strict(),Dbt=h.object({name:fe,content:en,labels:nJ.optional(),version:h.number().int().positive().optional()}).strict(),P$=h.object({content:en,version:h.number().int().positive()}).strict(),sJ=h.object({id:E,reason:h.enum(["grantExpired"])}).strict(),Nbt=h.record(E,h.object({version:h.number().int().positive(),content:en}).strict()),aJ=h.object({id:E,name:fe,version:h.number().int().positive(),content:en,policy:ao}).strict(),cJ=h.object({registration:RL,stoppedAt:h.iso.datetime().nullable(),heartbeatAt:h.iso.datetime().nullable()}).strict(),uJ=h.object({lease:E,request:Yc,sources:h.array(en).max(100)}).strict().nullable(),b1e=h.object({lease:E}).strict(),zbt=b1e.extend({receipt:Oy}).strict(),Gy=h.object({id:E,resource_id:E,executor_id:E,expected_revision:h.number().int().positive(),state:h.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:h.string().regex(/^\d+$/),result:en.nullable()}),Mbt=h.object({id:E,resourceId:E,expectedRevision:h.number().int().positive()}).strict(),S1e=h.object({fence:h.string().regex(/^\d+$/)}).strict(),Ubt=S1e.extend({content:en}).strict(),Lbt=h.object({id:E,runId:E,stateDigest:gr,expiresAt:Ie}).strict(),k$=h.object({id:E,runId:E,context:h.string(),sealed:$o.nullable(),expiresAt:Ie,receivedAt:Ie.nullable()}).strict(),lJ=(t,e)=>"oauth-callback:"+t+":"+e;var tc=class extends Error{constructor(r,o){super(o);this.code=r}code},tj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},T$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;async trusted(e){let r=e.principalId===this.binding.principalId?this.binding:await this.trust.binding(e.principalId);if(!r||C(r)!==C(e))throw new tc("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Ts);return await wL(r),{...r,fingerprint:await Ql(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new tc("fingerprint_mismatch","The identity fingerprint does not match.");return await this.trust.rememberBinding(o.binding),o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},cJ);if(await Pf(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},Qr(oJ));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await wL(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},P$);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await Io(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=xL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&ao.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await ee(o)!==i.digest)throw new tc("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!n$(i.policy,o))throw new tc("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return If((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Qr(aJ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||C(i.content)!==C(n.content))throw new tc("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await $f(await If(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...Ef(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return ao.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await $f(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},Yr);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await $f(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},h.union([Yr,st]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Qr(sJ))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},Yr),a=await If(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ge.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Qr(Yr));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ge.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await Rf(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Ka.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],p=await this.sourceContents([...d,...n.sourceIds??[]]),f=await this.policy(e,ge.executionResult,[],{id:a});f.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let m={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await ee(s.manifest),operation:de[i.kind],operationDigest:await ee(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(p.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await ee(w.policy),...w.policy.contentType===ge.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:f.readers,...s.manifest.resultVersion?{resultApproval:await Rf(f,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await kf(s,m);let y=w=>w.policy.contentType===ge.clientCredential;for(let w of p)await od(w,y(w)&&m.operation!==de.connect&&m.operation!==de.revoke?{...m,operation:de.refresh}:m,y(w)?{}:{destination:l?.url});return X5(m,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},zr)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new tj(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},zr);if(C(o.intent)!==C(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await vL(e.requestSignature,e.intent.actor.signing,"run");if(C(r.intent)!==C(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new tc("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?o8(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(C(e.intent.actor)!==C(this.binding)||C(e.intent.executor)!==C(this.binding))throw new tc("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,ge.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await AL(e.intent,e.receipt.state,r,this.keys,await Rf(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},zr)}};import{lstat as x1e,mkdir as E1e,readFile as $1e,readdir as R1e}from"node:fs/promises";import{join as dJ}from"node:path";var pJ=h.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),cd=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:pJ.parse(e)})}async read(e){let r=this.context(e),o=dJ(this.directory,e+".json");try{let n=await x1e(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=h.string().max(32e6).parse(JSON.parse(await $1e(o,"utf8"))),s=await _y(i,await Yo(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(ks(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 write(e,r){let o=this.context(e),n={context:o,value:r},i=await ur(n,this.privateKeys.signing,"journal"),s=nt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new vf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Yo(this.binding.encryption,"ECDH-ES+A256KW"));await E1e(this.directory,{recursive:!0,mode:448}),await Cf(dJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await R1e(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>pJ.parse(o.name.slice(0,-5)))}};var C$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Cs(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await ee(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&C(r)!==C(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var dt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function F(t,e,r,o){throw new dt(t,e,r,o)}var O$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},uJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},zr)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},h.object({id:E}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},k$),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Gy),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Gy),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},en),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Gy),state:r=>e.json("/api/connections/"+r+"/operation",{},Gy.nullable())}}};import{randomBytes as Vde,randomUUID as tHe}from"node:crypto";function I1e(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[o.name]=n}return r}function D$(t,e){let r=I1e(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ha.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(p=>p.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,p)=>{if(!t.parameters.some(f=>f.name===p))throw new Error("Declare every function parameter.");return Object.hasOwn(r,p)?n(r[p]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,p])=>[d,i(p,l)])):u},s=new E$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Ga.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.");return{kind:"http",request:a}}function fJ(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var mJ=h.object({operation:Ka,save:h.record(h.string(),fe)}).strict();function N$(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function hJ(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=e$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name==="connection.connect"){let n=t$.parse(r.invocation.input),i=bt.parse(e.kind==="connect"?e.input:null);if(e.kind!=="connect"||i.flowId!==r.continuationId||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Use the reviewed connection and execution environment.");if(i.action==="start"&&(i.methodId!==n.methodId||i.name!==n.name||i.appId!==(n.appId??null)||await ee(i.method)!==n.methodDigest))throw new Error("Use the reviewed connection method and application.");if(i.action==="start"){let s=h.record(h.string(),h.string()).parse(i.fields??{});if(Object.entries(n.fields??{}).some(([a,c])=>c&&s[a]!==c))throw new Error("Use the reviewed service settings.")}if(!["start","exchange","commit"].includes(String(i.action)))throw new Error("Continue the reviewed connection.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=Ty.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await ee(N$(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(C(e.request)!==C(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(e)!==C(Ka.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&C(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==C(o.save))throw new Error("Use the reviewed output destinations.")}function Hy(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function Po(t,e){for(let r of Hy(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function rj(t,e,r){let o=Hy(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function Lf(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function su(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{lookup as A1e}from"node:dns/promises";import{isIP as vJ}from"node:net";import{request as P1e}from"node:https";import{brotliDecompressSync as k1e,gunzipSync as T1e,inflateSync as C1e}from"node:zlib";var M$=Vt(yJ(),1),O1e=M$.default.IPv6.parseCIDR("2000::/3"),D1e=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function wJ(t){if(!vJ(t)||t.includes("%"))return!1;let e=M$.default.parse(t);return D1e.has(e.range())&&(!(e instanceof M$.default.IPv6)||e.match(O1e))}function ud(t,e){let r;try{r=new URL(t)}catch{F(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&F(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||vJ(o)&&!wJ(o))&&F(400,"private_destination","Choose a public HTTPS destination."),r}var U$=class{constructor(e){this.origin=e}origin;async send(e){let r=ud(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&F(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&F(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await A1e(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!wJ(u.address)))&&F(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(f,m,y)=>{m.all?y(null,[a]):y(null,a.address,a.family)}},p=P1e(r,d,f=>{let m=[],y=0;f.on("data",w=>{y+=w.length,y>n?f.destroy(new dt(413,"body_limit","The response body is too large.")):m.push(w)}),f.on("error",l),f.on("end",()=>{try{let w=Buffer.concat(m),b=f.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?T1e:b==="deflate"?C1e:b==="br"?k1e:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,I]of Object.entries(f.headers))I!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(I)?I.join(", "):I);u({status:f.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&F(409,"cancelled","The operation was cancelled."),F(502,"service_unavailable","The service could not be reached. Try again.")}}};function jf(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{F(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&F(502,"invalid_response","The service returned an invalid response."),e}function zs(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function L$(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!P5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=nt(Lf(Po(JSON.parse(zs(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=zs(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}function N1e(t,e){return t.policy.contentType===ge.value?e.output===void 0:t.policy.contentType===ge.tokenSet&&e.output!==void 0}var ko=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},j$=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Tf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Tf(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await ee(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Tf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await Y5(r.request,this.binding,this.keys);await kf(this.environment,p.intent);let f=Ka.parse(p.operation);if(de[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await hJ(o,f),await this.validateOperation(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.executeOperation(f,o,r.sources,c);d=await Tf(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(p){if(p instanceof ko)throw p;p instanceof Af&&(p=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||!(p instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(p.code));d=await Tf(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof dt?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?D$(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async validateOperation(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await Io(c);let u=r.sources.find(p=>p.id===c.policy.id);if(!u||!await EL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await ee(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(de[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(ud(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=Hy(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");rj(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(Hy(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await Os(u.approval);if(C(l.policy.authorities.find(d=>d.id===l.authorityId))!==C(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==ge.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&C(d.executor)===C(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?D$(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!N1e(u,c))throw new Error("Use the input named in the signed request.");await od(u,r,{...n?{destination:n.url}:{}}),await Qc(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async executeOperation(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?D$(e.definition,e.arguments):e,a=[],c=new Map,u=async m=>{let y=o.find(b=>b.policy.id===m.id);if(y.policy.contentType===ge.value)return Qc(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(m.id)||c.set(m.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(m.id);if(!m.output||!Object.hasOwn(w,m.output))throw new Error("Choose an available connection output.");return nt(w[m.output])};if(s.kind==="command"){let m=await L$(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:m.environment,files:m.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new dt(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new dt(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new dt(422,"function_failed",su(y.stderr,m.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,su(y.stdout,m.sensitive))}return{...y,stdout:su(y.stdout,m.sensitive),stderr:su(y.stderr,m.sensitive)}}let l=structuredClone(i);for(let m of l.bindings){let y="";for(let w of m.parts)if(typeof w=="string")y+=w;else{let b=zs(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}rj(l,m.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let p=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(p.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,su(zs(p.body),a))}let f=e.kind==="http"?e.save:{};if(Object.keys(f).length){if(p.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let m={};for(let[y,w]of Object.entries(f)){let b=p.body;if(y!==""){let x=Po(JSON.parse(zs(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=nt(typeof x=="string"?x:JSON.stringify(x))}let S=await rd(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});m[w.name]=(await this.broker.capture(w.name,S)).id}return{status:p.status,saved:m}}return{status:p.status,headers:Object.fromEntries(Object.entries(p.headers).map(([m,y])=>[m,su(y,a)])),body:su(zs(p.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:_r.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:Po(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=nt(typeof c=="string"?c:JSON.stringify(c)),l=await rd(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};var hc=Vt(_V(),1);import{randomUUID as e3e}from"node:crypto";function nde(t){let e=UE.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&F(502,"invalid_response","The AWS account could not be verified."),e.data}function ode(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&wf(t.arn)===wf(e.arn)}function bV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&F(409,"reconnect_required","Reconnect with current AWS credentials.")}var ak=class{async obtain(e,r,o){let n=Va.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};bV(s?.expiration);let a=new hc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();bV(d.expiration),c=new hc.STSClient({region:n.region,credentials:d});let p=nde(await c.send(new hc.GetCallerIdentityCommand({}),{abortSignal:u}));r&&!ode(p,r.sourceIdentity)&&F(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,m=p;if(n.role){l=!0;let b=(await c.send(new hc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+e3e().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&F(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},bV(f.expiration),c.destroy(),c=new hc.STSClient({region:n.region,credentials:f}),m=nde(await c.send(new hc.GetCallerIdentityCommand({}),{abortSignal:u}));let S=n.role.arn.split(":");(m.accountId!==S[4]||m.arn.split(":")[1]!==S[1]||m.arn.split(":")[5]?.split("/").slice(0,2).join("/")!=="assumed-role/"+n.role.arn.split("/").at(-1))&&F(502,"account_changed","The requested AWS role could not be verified.")}return r&&!ode(m,r.identity)&&F(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:LE.parse({...n,sourceIdentity:p,identity:m}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&F(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&F(409,"reconnect_required","Reconnect with current AWS credentials."),l&&F(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),F(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};import{randomUUID as t3e}from"node:crypto";var ck=class{constructor(e){this.aws=e}aws;facts=zL;validate(e){e.aws||F(400,"aws_authentication_required","Choose AWS authentication for this executor.")}async start({input:e,signal:r}){let o=(await this.aws.obtain(e.aws,void 0,r)).state;return{kind:"ready",material:co.parse({format:2,methodId:e.methodId,method:e.method,generation:t3e(),appId:null,appGeneration:null,aws:o})}}needsRenewal(){return!1}async check(e,r){await this.outputs(e,null,r)}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};import{randomUUID as Q3e}from"node:crypto";var SV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(SV="oauth4webapi/v3.8.8");function e_(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Sa="ERR_INVALID_ARG_VALUE",xa="ERR_INVALID_ARG_TYPE";function $r(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var TV=Symbol(),r3e=Symbol(),n3e=Symbol(),CV=Symbol();var Jw=Symbol();var o3e=new TextEncoder,i3e=new TextDecoder;function xV(t){return typeof t=="string"?o3e.encode(t):i3e.decode(t)}var EV;Uint8Array.prototype.toBase64?EV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):EV=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var $V;Uint8Array.fromBase64?$V=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw $r("The input to be decoded is not correctly encoded.",Sa,e)}}:$V=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw $r("The input to be decoded is not correctly encoded.",Sa,e)}};function RV(t){return typeof t=="string"?$V(t):EV(t)}var uh=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=O3e,Error.captureStackTrace?.(this,this.constructor)}},Xw=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function Re(t,e,r){return new Xw(t,{code:e,cause:r})}function s3e(t){return t.toLowerCase().replace(/^application\//,"")}function Yw(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function OV(t){e_(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(SV&&!e.has("user-agent")&&e.set("user-agent",SV),e.has("authorization"))throw $r('"options.headers" must not include the "authorization" header name',Sa);return e}function a3e(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw $r('"options.signal" must return or be an instance of AbortSignal',xa);return e}}function uk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw $r(`${r} must be a number`,xa,n);if(t>0)return;if(e){if(t!==0)throw $r(`${r} must be a non-negative number`,Sa,n);return}throw $r(`${r} must be a positive number`,Sa,n)}catch(i){throw o?Re(i.message,o,n):i}}function fn(t,e,r,o){try{if(typeof t!="string")throw $r(`${e} must be a string`,xa,o);if(t.length===0)throw $r(`${e} must not be empty`,Sa,o)}catch(n){throw r?Re(n.message,r,o):n}}function ade(t){u3e(t,"application/json")}function c3e(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return Re(r,N3e,t)}function u3e(t,e){if(fde(t)!==e)throw c3e(t,e)}async function cde(t){return fn(t,"codeVerifier"),RV(await crypto.subtle.digest("SHA-256",xV(t)))}function DV(t){let e=t?.[r3e];return typeof e=="number"&&Number.isFinite(e)?e:0}function NV(t){let e=t?.[n3e];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function ude(){return Math.floor(Date.now()/1e3)}function Qu(t){if(typeof t!="object"||t===null)throw $r('"as" must be an object',xa);fn(t.issuer,'"as.issuer"')}function el(t){if(typeof t!="object"||t===null)throw $r('"client" must be an object',xa);fn(t.client_id,'"client.client_id"')}function ide(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function lde(t){return fn(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function dde(t){return fn(t,'"clientSecret"'),(e,r,o,n)=>{let i=ide(r.client_id),s=ide(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function pde(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var l3e=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function d3e(t,e){if(e&&t.protocol!=="https:")throw Re("only requests to HTTPS are allowed",M3e,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Re("only HTTP and HTTPS requests are allowed",U3e,t)}function sde(t,e,r,o){let n;if(typeof t!="string"||!(n=l3e(t)))throw Re(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?L3e:j3e,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return d3e(n,o),n}function zV(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?sde(t.mtls_endpoint_aliases[e],e,r,o):sde(t[e],e,r,o)}var IV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=C3e,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Qw=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=D3e,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)}},AV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=T3e,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},lk="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",p3e="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",f3e='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',m3e="("+lk+")\\s*=\\s*"+f3e,h3e="("+lk+")\\s*=\\s*("+lk+")",g3e=new RegExp("^[,\\s]*("+lk+")"),y3e=new RegExp("^[,\\s]*"+m3e+"[,\\s]*(.*)"),v3e=new RegExp("^[,\\s]*"+h3e+"[,\\s]*(.*)"),w3e=new RegExp("^("+p3e+")(?:$|[,\\s])(.*)");function _3e(t){if(!e_(t,Response))throw $r('"response" must be an instance of Response',xa);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(g3e),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(y3e)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(v3e)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(w3e)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function b3e(t){if(t.status>399&&t.status<500){fk(t),ade(t);try{let e=await t.clone().json();if(Yw(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function MV(t,e,r){if(t.status!==e){x3e(t);let o;throw(o=await b3e(t))?(await t.body?.cancel(),new IV("server responded with an error in the response body",{cause:o,response:t})):Re(`"response" is not a conform ${r} response (unexpected HTTP status code)`,z3e,t)}}function S3e(t){if(!jV.has(t))throw $r('"options.DPoP" is not a valid DPoPHandle',Sa)}function fde(t){return t.headers.get("content-type")?.split(";")[0]}async function UV(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[CV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:a3e(o,s?.signal)})}async function LV(t,e,r,o,n,i){let s=zV(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[TV]!==!0);n.set("grant_type",o);let a=OV(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(S3e(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await UV(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function mde(t,e,r,o,n){Qu(t),el(e),fn(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),LV(t,e,r,"refresh_token",i,n)}var hde=new WeakMap,gde=new WeakMap;function yde(t){if(!t.id_token)return;let e=hde.get(t);if(!e)throw $r('"ref" was already garbage collected or did not resolve from the proper sources',Sa);return e}async function mk(t,e,r,o,n,i){if(Qu(t),el(e),!e_(r,Response))throw $r('"response" must be an instance of Response',xa);await MV(r,200,"Token Endpoint"),fk(r);let s=await Mde(r);if(fn(s.access_token,'"response" body "access_token" property',St,{body:s}),fn(s.token_type,'"response" body "token_type" property',St,{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;uk(a,!0,'"response" body "expires_in" property',St,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&fn(s.refresh_token,'"response" body "refresh_token" property',St,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw Re('"response" body "scope" property must be a string',St,{body:s});if(s.id_token!==void 0){fn(s.id_token,'"response" body "id_token" property',St,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(uk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await R3e(t,e,s.id_token,a,n);A3e(e,c),I3e(c),gde.set(r,u),hde.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new uh("unsupported `token_type` value",{cause:{body:s}});return s}function x3e(t){let e;if(e=_3e(t))throw new AV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function vde(t,e,r,o){return mk(t,e,r,void 0,o?.[Jw],o?.recognizedTokenTypes)}function wde(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw Re('unexpected JWT "aud" (audience) claim value',lh,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw Re('unexpected JWT "aud" (audience) claim value',lh,{expected:t,claims:e.claims,claim:"aud"});return e}function _de(t,e){let r=t[G3e]?.(e)??t.issuer;if(e.claims.iss!==r)throw Re('unexpected JWT "iss" (issuer) claim value',lh,{expected:r,claims:e.claims,claim:"iss"});return e}var jV=new WeakSet;function E3e(t){return jV.add(t),t}var FV=Symbol();async function bde(t,e,r,o,n,i,s){if(Qu(t),el(e),!jV.has(o))throw $r('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Sa);fn(n,'"redirectUri"');let a=Gd(o,"code");if(!a)throw Re('no authorization code in "callbackParameters"',St);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==FV&&(fn(i,'"codeVerifier"'),c.set("code_verifier",i)),LV(t,e,r,"authorization_code",c,s)}var Sde={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function xde(t,e){for(let r of t)if(e.claims[r]===void 0)throw Re(`JWT "${r}" (${Sde[r]}) claim missing`,St,{claims:e.claims});return e}function $3e(t,e){if(typeof e.claims[t]!="string")throw Re(`unexpected JWT "${t}" (${Sde[t]}) claim type`,St,{claims:e.claims});return e}function R3e(t,e,r,o,n){return Dde(r,Nde.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),DV(e),NV(e),n).then(xde.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(_de.bind(void 0,t)).then(wde.bind(void 0,e.client_id)).then($3e.bind(void 0,"sub"))}function Ede(t,e){if(e===pk)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?pk:(uk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function I3e(t){t.auth_time!==void 0&&uk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',St,{claims:t})}function $de(t,e,r){if(r===pk)return;let o=ude()+DV(t),n=NV(t);if(e.auth_time+r<o-n)throw Re("too much time has elapsed since the last End-User authentication",kV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Rde(t,e){let r=e===dk?void 0:e;if(t.nonce!==r)throw Re('unexpected ID Token "nonce" claim value',lh,{expected:r,claims:t,claim:"nonce"})}function A3e(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw Re('ID Token "aud" (audience) claim includes additional untrusted audiences',lh,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw Re('unexpected ID Token "azp" (authorized party) claim value',lh,{expected:t.client_id,claims:e,claim:"azp"})}}var dk=Symbol(),pk=Symbol();async function Ide(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?P3e(t,e,r,o.expectedNonce,o.maxAge,o[Jw],o.recognizedTokenTypes):k3e(t,e,r,o?.maxAge,o?.[Jw],o?.recognizedTokenTypes)}async function P3e(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=dk;break;case dk:break;default:fn(o,'"expectedNonce" argument'),a.push("nonce")}n=Ede(e,n),n!==pk&&a.push("auth_time");let c=await mk(t,e,r,a,i,s);fn(c.id_token,'"response" body "id_token" property',St,{body:c});let u=yde(c);return $de(e,u,n),Rde(u,o),c}async function k3e(t,e,r,o,n,i){let s=await mk(t,e,r,void 0,n,i),a=yde(s);return a&&($de(e,a,Ede(e,o)),Rde(a,dk)),s}var T3e="OAUTH_WWW_AUTHENTICATE_CHALLENGE",C3e="OAUTH_RESPONSE_BODY_ERROR",O3e="OAUTH_UNSUPPORTED_OPERATION",D3e="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var PV="OAUTH_PARSE_ERROR",St="OAUTH_INVALID_RESPONSE";var N3e="OAUTH_RESPONSE_IS_NOT_JSON",z3e="OAUTH_RESPONSE_IS_NOT_CONFORM",M3e="OAUTH_HTTP_REQUEST_FORBIDDEN",U3e="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",kV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",lh="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var L3e="OAUTH_MISSING_SERVER_METADATA",j3e="OAUTH_INVALID_SERVER_METADATA";function F3e(t,e){if(typeof e.header.typ!="string"||s3e(e.header.typ)!==t)throw Re('unexpected JWT "typ" header parameter value',St,{header:e.header});return e}async function Ade(t,e,r,o,n){return Qu(t),el(e),LV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Pde(t,e,r,o){return mk(t,e,r,void 0,o?.[Jw],o?.recognizedTokenTypes)}async function kde(t,e,r,o,n){Qu(t),el(e),fn(o,'"token"');let i=zV(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[TV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=OV(n?.headers);return a.delete("accept"),UV(t,e,r,i,s,a,n)}async function Tde(t){if(!e_(t,Response))throw $r('"response" must be an instance of Response',xa);await MV(t,200,"Revocation Endpoint")}function fk(t){if(t.bodyUsed)throw $r('"response" body has been used already',Sa)}async function Cde(t,e,r,o,n){Qu(t),el(e),fn(o,'"token"');let i=zV(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[TV]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=OV(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),UV(t,e,r,i,s,a,n)}async function Ode(t,e,r,o){if(Qu(t),el(e),!e_(r,Response))throw $r('"response" must be an instance of Response',xa);await MV(r,200,"Introspection Endpoint");let n;if(fde(r)==="application/token-introspection+jwt"){fk(r);let{claims:i,jwt:s}=await Dde(await r.text(),Nde.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),DV(e),NV(e),o?.[Jw]).then(F3e.bind(void 0,"token-introspection+jwt")).then(xde.bind(void 0,["aud","iat","iss"])).then(_de.bind(void 0,t)).then(wde.bind(void 0,e.client_id));if(gde.set(r,s),!Yw(i.token_introspection))throw Re('JWT "token_introspection" claim must be a JSON object',St,{claims:i});n=i.token_introspection}else fk(r),n=await Mde(r);if(typeof n.active!="boolean")throw Re('"response" body "active" property must be a boolean',St,{body:n});return n}async function Dde(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new uh("JWE decryption is not configured",{cause:t});if(a!==3)throw Re("Invalid JWT",St,t);let c;try{c=JSON.parse(xV(RV(i)))}catch(d){throw Re("failed to parse JWT Header body as base64url encoded JSON",PV,d)}if(!Yw(c))throw Re("JWT Header must be a top level object",St,t);if(e(c),c.crit!==void 0)throw new uh('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(xV(RV(s)))}catch(d){throw Re("failed to parse JWT Payload body as base64url encoded JSON",PV,d)}if(!Yw(u))throw Re("JWT Payload must be a top level object",St,t);let l=ude()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw Re('unexpected JWT "exp" (expiration time) claim type',St,{claims:u});if(u.exp<=l-o)throw Re('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',kV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw Re('unexpected JWT "iat" (issued at) claim type',St,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw Re('unexpected JWT "iss" (issuer) claim type',St,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw Re('unexpected JWT "nbf" (not before) claim type',St,{claims:u});if(u.nbf>l+o)throw Re('unexpected JWT "nbf" (not before) claim value',kV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw Re('unexpected JWT "aud" (audience) claim type',St,{claims:u});return{header:c,claims:u,jwt:t}}function Nde(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw Re('unexpected JWT "alg" header parameter',St,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw Re('unexpected JWT "alg" header parameter',St,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw Re('unexpected JWT "alg" header parameter',St,{header:o,expected:r,reason:"default value"});return}throw Re('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Gd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw Re(`"${e}" parameter must be provided only once`,St);return r}var q3e=Symbol(),V3e=Symbol();function zde(t,e,r,o){if(Qu(t),el(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw $r('"parameters" must be an instance of URLSearchParams, or URL',xa);if(Gd(r,"response"))throw Re('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',St,{parameters:r});let n=Gd(r,"iss"),i=Gd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw Re('response parameter "iss" (issuer) missing',St,{parameters:r});if(n&&n!==t.issuer)throw Re('unexpected "iss" (issuer) response parameter value',St,{expected:t.issuer,parameters:r});switch(o){case void 0:case V3e:if(i!==void 0)throw Re('unexpected "state" response parameter encountered',St,{expected:void 0,parameters:r});break;case q3e:break;default:if(fn(o,'"expectedState" argument'),i!==o)throw Re(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',St,{expected:o,parameters:r})}if(Gd(r,"error"))throw new Qw("authorization response from the server is an error",{cause:r});let a=Gd(r,"id_token"),c=Gd(r,"token");if(a!==void 0||c!==void 0)throw new uh("implicit and hybrid flows are not supported");return E3e(new URLSearchParams(r))}async function Mde(t,e=ade){let r;try{r=await t.json()}catch(o){throw e(t),Re('failed to parse "response" body as JSON',PV,o)}if(!Yw(r))throw Re('"response" body must be a top level object',St,{body:r});return r}var G3e=Symbol();import{createHash as H3e}from"node:crypto";function tl(t,e){try{return ud(new E$(t).expand(e)).href}catch{F(400,"invalid_service_url","Check the service URL and its required fields.")}}var hk=t=>H3e("sha256").update(t).digest("hex"),t_=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],gk=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&F(502,"invalid_response","The service returned an invalid expiry."),e};var Lde=Object.assign(Object.create(null),{dpop:()=>F(502,"invalid_response","The service returned an unsupported token.")}),B3e={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Lde,{"user access token":()=>{}}),refreshInspection:!0,async inspect(t){let{app:e,current:r}=t,{server:o,client:n}=t.configuration(),i=await Cde({...o,introspection_endpoint:o.token_endpoint+"/introspect"},n,t.authentication("basic"),r.accessToken,{...t.options(),additionalParameters:{token_type_hint:"access_token"}}),s;try{s=await Ode(o,n,Response.json(await t.json(i),{status:i.status}))}catch{F(409,"reconnect_required","Reconnect this service to renew access.")}return(s.active!==!0||s.client_id!==e.clientId||typeof s.sub!="string"||!s.sub||typeof s.exp!="number"||s.exp*1e3<=Date.now())&&F(409,"reconnect_required","Reconnect this service to renew access."),{...r,account:s.sub,accountName:typeof s.username=="string"?s.username:s.sub,scopes:t_(s.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(r.expiresAt??1/0,s.exp*1e3)}}},K3e={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&F(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key",allowAccountChange:!0,refreshInspection:!0,async inspect({transport:t,current:e}){let r=await t.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+e.accessToken}}),o=jf(r);(r.status!==200||!o.data||typeof o.data!="object")&&F(409,"reconnect_required","Reconnect this service to renew access.");let n=o.data;return{...e,account:hk(e.accessToken),accountName:typeof n.label=="string"?n.label:"OpenRouter",facts:n}}},Z3e={verifyIdentity({current:t,response:e}){e.headers["x-oauth-scopes"]!==void 0&&(t.scopes=t_(e.headers["x-oauth-scopes"].replaceAll(","," ")),t.scopesStatus="reported")}},W3e={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+Buffer.from(t.clientId+":"+(t.clientSecret??"")).toString("base64"),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},J3e={verifyIdentity({data:t}){t.email_verified!==!0&&F(502,"invalid_response","The service account could not be verified.")}},X3e=Object.assign(Object.create(null),{ebay:B3e,openrouter:K3e,github:Z3e,google:J3e}),Y3e=[{matches:t=>t.hostname.endsWith(".myshopify.com"),service(t,e){return{...e.pathname==="/admin/oauth/access_token"?{normalizeToken(r){r.token_type===void 0&&(r.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...t.grantType==="client_credentials"&&/^\/admin\/api\/[^/]+\/graphql\.json$/.test(e.pathname)?{identityRequest({spec:r,url:o,current:n}){return{url:o,method:r.identity.method,headers:{...r.identity.headers,"content-type":"application/json","X-Shopify-Access-Token":n.accessToken},body:JSON.stringify({query:"{ shop { id name myshopifyDomain } }"})}},verifyIdentity({app:r,data:o}){((Array.isArray(o.errors)?o.errors.length:o.errors)||Po(o,"/data/shop/myshopifyDomain")!==r.fields.shop+".myshopify.com")&&F(502,"invalid_response","The Shopify store could not be verified.")}}:{}}}},{matches:t=>t.hostname==="api.notion.com"&&t.pathname==="/v1/oauth/token",service:()=>({normalizeToken(t){t.refresh_token===null&&delete t.refresh_token}})}];function ho(t,e){let r=e?new URL(e):void 0,o=r?Y3e.find(i=>i.matches(r))?.service(t,r):void 0,n=t.adapter?X3e[t.adapter]:void 0;return t.adapter&&!n&&F(400,"invalid_input","Choose a supported service authentication adapter."),{recognizedTokenTypes:Lde,...o,...n,...t.revoke?.style==="github"?W3e:{},...o?.verifyIdentity||n?.verifyIdentity?{verifyIdentity(i){o?.verifyIdentity?.(i),n?.verifyIdentity?.(i)}}:{}}}var yk=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...$$(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof ji&&F(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&F(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(tl(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:ho(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await cde(n),c.code_challenge_method="S256"),ho(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(tl(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:tl(e.tokenUrl,this.appValues(e,r))};return e.issuer&&ud(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?pde():(e.clientSecret||F(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?dde(e.clientSecret):lde(e.clientSecret))}options(e="form"){return{[CV]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return jf({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&Po(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&F(409,"reconnect_required","Reconnect this service to renew access."),r===429&&F(503,"service_rate_limit","The service is busy. Try again later."),F(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&F(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,ho(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=gk(u.expires_in));try{let d=await(n?vde:e.grantType==="client_credentials"?Pde:Ide)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:ho(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;F(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[ho(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&F(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+gk(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&F(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?t_(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+gk(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&F(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=ho(e);if(l.exchange){let f=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>tl(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,f.status,jf(f))}else{let{server:f,client:m}=this.configuration(e,r),y;try{let w=zde(f,m,o.parameters,o.state);y=await bde(f,m,this.authentication(r,e.clientAuth),w,l.redirectUri?.(r,i)??i,e.pkce?n:FV,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(w){throw(w instanceof Xw||w instanceof Qw)&&F(400,"invalid_state","Start the connection again."),w}u=await this.tokenResponse(e,r,y)}let d=this.token(e,u,s,a);await c?.(d,u);let p=await this.inspect(e,r,d,u);return a&&p.account!==a.account&&!l.allowAccountChange&&F(409,"account_changed","Reconnect using the same service account."),p}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&F(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=ho(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Ade(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e.tokenFormat)),d=await this.tokenResponse(e,r,l),p={...this.token(e,d,o,n,!!n),requestedScopes:o};await i?.(p,d);let f=await this.inspect(e,r,p,d);return n&&f.account!==n.account&&F(409,"account_changed","Reconnect using the same service account."),f}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||F(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&F(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await mde(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return(e.identity?.url||ho(e).refreshInspection)&&(i=await this.inspect(e,r,i)),i.account!==o.account&&F(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{},s=ho(e);if(s.inspect)return s.inspect({spec:e,app:r,transport:this.transport,current:o,configuration:()=>this.configuration(e,r),authentication:l=>this.authentication(r,l),options:()=>this.options(),json:l=>this.json(l)});if(e.identity?.url){let l=tl(e.identity.url,{...this.appValues(e,r),...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),d=ho(e,l),p=await this.transport.send(d.identityRequest?.({spec:e,app:r,transport:this.transport,url:l,current:o})??{url:l,method:e.identity.method,headers:{...e.identity.headers,authorization:"Bearer "+o.accessToken}});i=jf(p),(p.status===401||p.status===403)&&F(409,"reconnect_required","Reconnect this service to renew access."),p.status>=400&&F(502,"invalid_response","The service account could not be verified."),d.verifyIdentity?.({spec:e,app:r,transport:this.transport,current:o,response:p,data:i})}else e.identity?.from==="app"&&(i=this.appValues(e,r));let a=l=>{for(let d of Array.isArray(l)?l:[l]){let p=Po(i,d);if(typeof p=="string"&&p||typeof p=="number")return String(p)}return""},c=e.identity?.id,u=c?Array.isArray(c)?c.map(l=>a(l)).filter(Boolean).join(":"):a(c):o.account||r.fields.domain||r.fields.shop||hk(o.accessToken);return(!u||u.length>1e3)&&F(502,"invalid_response","The service account could not be verified."),{...o,account:u,accountName:e.identity&&a(e.identity.name)||u,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||F(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=tl(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await kde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Tde(d)}catch{F(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64")),(await this.transport.send(ho(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&F(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,Lf(Po(n,s))]))}};function r_(t,e,r={}){try{return Mf(t,e,r)}catch(o){throw o instanceof ji&&F(400,o.code,o.message),o}}function gc(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function Hd(t){return t||F(409,"app_required","Choose an OAuth application."),t}function qV(t){let e=gc(t).scopes;return p$(e,t.scopes)}function jde(t,e,r){let o=ec(gc(t).fields,e.fields);return co.parse({format:2,methodId:t.methodId,method:t.method,generation:Q3e(),appId:t.appId,appGeneration:t.appId?e.generation:null,oauth:r,...Object.keys(o).length?{fields:o}:{}})}function Fde(t){return{token:ej.parse(t.token),response:bt.parse(t.response)}}var vk=class{constructor(e){this.transport=e}transport;facts=DL;oauth(e){return new yk({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}validate(e,r){let o=gc(e),n=Hd(r);ho(o),r_(o.fields,n.fields,o.defaults);for(let i of o.fields)i.secret===!1&&e.fields[i.name]&&n.fields[i.name]!==e.fields[i.name]&&F(409,"wrong_app","Choose an application with the approved service settings.");Ao(e.method).requiresApp&&o.clientAuth!=="none"&&!n.clientSecret&&F(409,"app_required","Add a client secret to this OAuth application.")}async start(e){let{input:r,signal:o}=e,n=gc(r),i=Hd(e.app);if(n.grantType!=="client_credentials")return{kind:"authorize",url:await this.oauth(o).authorize(n,i,e.state,e.verifier,r.redirectUri,qV(r))};await e.dispatch();let s=await this.oauth(o).clientCredentials(n,i,qV(r),void 0,(a,c)=>e.receive({token:a,response:c}));return{kind:"ready",material:jde(r,i,s)}}async exchange(e,r,o){let{input:n,signal:i}=e,s=gc(n),a=Hd(e.app),c=new URLSearchParams(r);(c.getAll("state").length!==1||c.get("state")!==e.state)&&F(400,"invalid_state","Start the connection again.");let u;if(o){let l=Fde(o);u=await this.oauth(i).inspect(s,a,l.token,l.response)}else await e.dispatch(),u=await this.oauth(i).exchange(s,a,{parameters:c,state:e.state},e.verifier,n.redirectUri,qV(n),void 0,(l,d)=>e.receive({token:l,response:d}));return jde(n,a,u)}needsRenewal(e){return e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=await this.oauth(e.signal).refresh(gc(e.material),Hd(e.app),e.material.oauth,(o,n)=>e.receive({token:o,response:n}));return co.parse({...e.material,oauth:r})}async recover(e,r,o){let n=Fde(o),i=await this.oauth().inspect(gc(e),Hd(r),n.token,n.response);return co.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(gc(e),Hd(r),e.oauth)}async revoke(e,r,o){await this.oauth(o).revoke(gc(e),Hd(r),e.oauth)}};import{randomUUID as eHe}from"node:crypto";function wk(t){if(t.method.kind!=="token")throw new Error("Use a token connection provider.");return t.method.config}var _k=class{facts=NL;validate(e){r_(wk(e).fields,e.fields)}async start({input:e}){return{kind:"ready",material:co.parse({format:2,methodId:e.methodId,method:e.method,generation:eHe(),appId:null,appGeneration:null,fields:r_(wk(e).fields,e.fields)})}}needsRenewal(){return!1}async outputs(e){let r=$$(wk(e).fields,e.fields);return Object.fromEntries(Object.entries(wk(e).outputs).map(([o,n])=>[o,Lf(Po(r,n))]))}};function qde(t,e){return{oauth:new vk(t),token:new _k,aws:new ck(e)}}var dh=class{constructor(e,r,o,n,i,s=new ak){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=qde(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers[Ao(e).family]}metadata(e){return I$(e,this.provider(e.method).facts(e))}labels(e){return A$(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||F(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=co.safeParse(JSON.parse(zs(await Qc(e,r,this.keys,{destination:o}))));n.success||F(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&F(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==de.revoke&&F(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,ge.clientCredential,n),s=iu.parse(JSON.parse(zs(await Qc(i,o,this.keys))));return s.methodId!==r&&F(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(Ao(e.method).application==="none")return null;if(!Ds(e.method))return iu.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===de.revoke?de.revoke:de.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&F(409,"app_changed","Reconnect this service with the current application."),e.method.kind==="oauth"&&Object.entries(e.fields??{}).some(([s,a])=>i.fields[s]!==a)&&F(409,"app_changed","Reconnect this service with the current application settings."),i}async flow(e,r){let o=await this.readFlow(e);return(!o||o.expiresAt<=Date.now()||C(o.actor)!==C(r.actor)||o.ownerId!==r.ownerId)&&F(409,"connection_expired","Start the connection again."),o}async readFlow(e){let r=await this.journal.read("connect_"+e);return r&&(!Vy.safeParse(r.input).success||r.material&&!co.safeParse(r.material).success)&&F(409,"connection_expired","Start the connection again."),r}writeFlow(e,r){return this.journal.write("connect_"+e,r)}async startApp(e,r,o){return Ao(e.method).application==="none"?null:e.appId?this.app(e.appId,e.methodId,r,o):iu.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}})}authorization(e,r,o){return{input:r.input,app:r.app,state:r.state,verifier:r.verifier,signal:o,dispatch:async()=>{r.phase="exchanging",await this.writeFlow(e,r)},receive:async n=>{r.checkpoint=n,r.phase="received",await this.writeFlow(e,r)}}}async validate(e,r,o){let n=Vy.parse(e),i=de[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&F(400,"wrong_operation","Use the approved connection operation."),n.action==="start"){if(Ds(n.method)&&!n.appId&&F(400,"app_required","Choose an OAuth application."),Ao(n.method).browserAuthorization){n.redirectUri||F(400,"invalid_redirect","Choose a callback URL.");let s=new URL(n.redirectUri);(s.username||s.password||s.hash||s.search||!(n.redirectUri===r.origin+"/oauth/callback"||s.protocol==="http:"&&["127.0.0.1","[::1]"].includes(s.hostname)))&&F(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.")}this.provider(n.method).validate(n,await this.startApp(n,r,o))}else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await Os(n.approval);(!s.material||n.authorizationDigest!==(await this.metadata(s.material)).authorizationDigest||a.policy.contentType!==ge.tokenSet||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||C(a.policy.authorities.find(c=>c.id===a.authorityId))!==C(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&C(c.executor)===C(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&F(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);C(a)!==C(s.app)&&F(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,ge.tokenSet,o),a=await this.material(s,r);await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=Vy.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&F(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o,n);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,ge.tokenSet,o),c=await this.material(a,r);if(i.action==="refresh"){await this.provider(c.method).check?.(c,n);let l=await this.refresh(a,c,r,o,n);return{kind:"refreshed",id:a.policy.id,...await this.metadata(l)}}let u=this.provider(c.method);return u.revoke||F(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await u.revoke(c,await this.connectionApp(c,r,o),n),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:{...await this.metadata(r.material),...this.labels(r.material)}}}async start(e,r,o,n){await this.readFlow(e.flowId)&&F(409,"flow_exists","Use a new connection request.");let i={actor:r.actor,ownerId:r.ownerId,input:e,app:await this.startApp(e,r,o),state:Vde(32).toString("base64url"),verifier:Vde(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:"authorize"};await this.writeFlow(e.flowId,i);let s=await this.provider(e.method).start(this.authorization(e.flowId,i,n));return s.kind==="ready"?(i.material=s.material,i.phase="review",await this.writeFlow(e.flowId,i),this.review(e.flowId,i)):(e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await ee(i.state),expiresAt:new Date(i.expiresAt).toISOString()}),{kind:"authorize",flowId:e.flowId,url:s.url})}async exchange(e,r,o){let n=await this.flow(e.flowId,r);if(n.phase==="review")return this.review(e.flowId,n);let i=this.provider(n.input.method);return(!i.exchange||!["authorize","received"].includes(n.phase))&&F(409,"connection_uncertain","Check the connection before authorizing it again."),n.material=await i.exchange(this.authorization(e.flowId,n,o),e.parameters,n.phase==="received"?n.checkpoint:void 0),n.phase="review",await this.writeFlow(e.flowId,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r);if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||F(409,"approval_required","Review this connection before saving."),o.content?(C(o.content.policy)!==C(e.approval.policy)||o.content.creationRunId!==r.id)&&F(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await rd(nt(C(o.material)),e.approval,r.id,this.binding,this.keys,await this.metadata(o.material)),o.phase="committing",await this.writeFlow(e.flowId,o));let n;try{n=await this.broker.capture(o.input.name,o.content,this.labels(o.material))}catch(i){throw i instanceof dt&&i.status<500?i:new ko}return o.phase="committed",await this.writeFlow(e.flowId,o),{kind:"connected",id:n.id}}async recover(e,r){let o=Vy.parse(e);if(o.action!=="commit")return null;let n=await this.readFlow(o.flowId);if(!n?.content||n.ownerId!==r.ownerId||C(n.actor)!==C(r.actor)||n.content.creationRunId!==r.id||C(n.content.policy)!==C(o.approval.policy)||!["committing","committed"].includes(n.phase))return null;try{await this.broker.capture(n.input.name,n.content,this.labels(n.material))}catch(i){if(i instanceof dt&&i.status<500)return null;throw new ko}return n.phase="committed",await this.writeFlow(o.flowId,n),{kind:"connected",id:n.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&F(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&F(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await J5(e.previous,nt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||F(409,"reconnect_required","Reconnect this service to renew access.");try{await od(e,{...o,operation:de.refresh},{destination:s})}catch{F(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=tHe(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let p=await a.renew({material:r,app:c,signal:i,receive:async f=>{d.checkpoint=f,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,p)}catch(p){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),p instanceof dt&&["connection_review","reconnect_required","account_changed"].includes(p.code))throw p;F(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};function Cn(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=VV(rHe(Wa()),"custody",r.id),i=new cd(VV(n,"client"),o,r,e),s=new T$(t,o,r,e,new C$(i)),a=new O$(t),c=new U$(o),u=new dh(r,e,a.connections(),new cd(VV(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Gde(t,e){let{custody:r,keys:o,binding:n,connections:i}=Cn(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await ee(n),operation:de.command,functionDigest:null,operationDigest:await ee(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await ee(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===ge.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return L$(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===ge.value)return Qc(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return nt(d[u.output])})}import{mkdir as Hnt}from"node:fs/promises";import{join as J_}from"node:path";import{setTimeout as Bnt}from"node:timers/promises";import{spawn as nHe}from"node:child_process";import{constants as GV}from"node:fs";import{open as Hde,rm as oHe}from"node:fs/promises";async function Bde(t){if(process.platform!=="linux"){let r=await Hde(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await oHe(t,{force:!0})}}let e=await Hde(t,GV.O_CREAT|GV.O_WRONLY|GV.O_NOFOLLOW,384);try{let r=nHe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var mD=Vt(_V(),1),hD=Vt(R0e(),1);function I0e(t){return $L.safeParse(t).success?t:null}async function A0e(t=3e3){let e=new mD.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new mD.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=I0e(n.Arn);if(i)return i;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new hD.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new hD.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=I0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var UG=h.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),LG=UG.max(4096).startsWith("/"),P0e=h.object({command:h.array(UG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:LG.optional(),environment:h.record(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),UG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:h.string().max(1e6).default(""),timeoutSeconds:h.number().int().min(1).max(3600).default(60)}).strict(),yKt=P0e.extend({id:E.optional()}),k0e=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),T0e=h.object({exitCode:h.number().int().nullable(),signal:h.string().max(32).nullable(),stdout:h.string().max(1e6),stderr:h.string().max(1e6),timedOut:h.boolean(),truncated:h.boolean()}).strict(),vKt=h.object({state:k0e.exclude(["queued","running"]),result:T0e.nullable(),error:h.string().max(100).nullable()}).strict(),gD=P0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:LG,state:k0e,result:T0e.nullable(),error:h.string().nullable(),createdAt:Ie,startedAt:Ie.nullable(),finishedAt:Ie.nullable()}).strict(),wKt=gD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),_Kt=h.object({workingDirectory:LG}).strict(),C0e=h.object({lease:E,process:gD}).strict().nullable();var yD=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},C0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},gD)}},vD=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new ko}return!0}};var wD=h.object({format:h.literal(1),functionId:E,ownerId:E,revision:h.number().int().positive(),definition:Qo,author:or,executor:or,createdAt:Ie,signature:br}).strict();async function O0e(t,e){return wD.parse({...t,signature:await ur(t,e.signing,"function-publication")})}async function D0e(t,e){let r=wD.parse(t),{signature:o,...n}=r;if(await Cs(n.author),await Nr(n,o,n.author.signing,"function-publication"),e&&C(n.executor)!==C(e))throw new Error("This function is approved for another executor.");return r}var jG=h.object({functionId:E,publication:wD,contents:h.record(E,h.object({version:h.number().int().positive(),content:en}).strict())}).strict(),Cnt=h.object({name:fe,definition:Qo,authorization:jG}).strict(),TKt=Cnt.extend({version:h.number().int().positive()}),Ont=h.object({id:E.optional(),ownerId:E.optional(),arguments:bt.default({}),outputs:h.record(h.string().max(500),u$).default({})}).strict(),N0e=h.object({code:h.string().max(100),message:h.string().max(1e3)}).strict(),z0e=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,state:a$,result:_r.nullable(),error:N0e.nullable(),createdAt:Ie,startedAt:Ie.nullable(),finishedAt:Ie.nullable()}).strict(),Dnt=h.object({id:E,functionId:E,functionVersion:h.number().int().positive(),ownerId:E,actorId:E,actor:or.nullable(),arguments:bt,outputs:Ont.shape.outputs,definitionDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:Ie,expiresAt:Ie}).strict(),M0e=h.object({id:E,requestDigest:h.string().regex(/^[A-Za-z0-9_-]{43}$/),state:a$.exclude(["queued","running"]),result:_r.nullable(),error:N0e.nullable(),finishedAt:Ie,signature:br}).strict(),U0e=h.object({lease:E,request:Dnt,publication:wD,sources:h.array(en).max(100)}).strict().nullable();var _D=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/invocations/claim",{method:"POST",body:{}},U0e)}dispatch(e,r){return this.api.json("/api/runtime/functions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/runtime/functions/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean(),reason:h.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(e,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:e,completion:r}},z0e)}},bD=class{constructor(e,r,o,n=15e3){this.executor=e;this.broker=r;this.journal=o;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(e,r,o,n){let i={id:e.id,requestDigest:e.digest,state:r,result:o,error:n,finishedAt:new Date().toISOString()};e.completion=M0e.parse({...i,signature:await ur(i,this.executor.keys.signing,"function-result")}),e.phase="settled",await this.journal.write("invocation_"+e.id,e)}async deliver(e){await this.broker.finish(e.lease,e.completion),e.delivered=!0,await this.journal.write("invocation_"+e.id,e)}async reconcile(){let e=[];for(let r of await this.journal.keys("invocation_"))try{let o=await this.journal.read(r);if(!o||o.delivered||o.phase==="prepared")continue;o.completion||await this.complete(o,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(o)}catch{e.push(r.slice(11))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:o,publication:n,sources:i,lease:s}=r,a=await ee(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),p=!1,f=!1,m=setInterval(()=>{f||(f=!0,this.broker.renew(o.id,s).then(y=>{y.active||(p||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{f=!1}))},this.renewalMilliseconds);m.unref();try{if(await D0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await ee(n.definition)!==o.definitionDigest||Date.parse(o.expiresAt)<=Date.now())throw new Error("Run the current approved function in its configured environment.");let y="function_"+n.functionId,w=await this.journal.read(y),b=await ee(n);if(w&&(n.revision<w.revision||n.revision===w.revision&&w.digest!==b))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(y,{revision:n.revision,digest:b});let S=i8.parse({kind:"function",functionId:o.functionId,definition:n.definition,arguments:o.arguments,outputs:o.outputs}),x={format:2,id:o.id,origin:this.executor.environment.manifest.origin,ownerId:o.ownerId,actor:o.actor??this.executor.binding,executor:this.executor.binding,environmentId:n.definition.environmentId,environmentDigest:await ee(this.executor.environment.manifest),operation:de.function,operationDigest:await ee(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await ee(T.policy),materialRevision:T.materialRevision,...T.policy.contentType===ge.tokenSet&&typeof T.metadata.authorizationDigest=="string"?{authorizationDigest:T.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:o.createdAt,expiresAt:o.expiresAt};await kf(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let I=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(I)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",I,null)}catch(y){if(y instanceof ko)throw y;let w=u.phase==="dispatched",b=d.aborted&&p?"cancelled":w&&(d.aborted||!(y instanceof dt))?"uncertain":"failed";await this.complete(u,b,null,!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="uncertain"?"execution_uncertain":b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="uncertain"?"Check the result before invoking this function again.":b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(m)}try{await this.deliver(u)}catch{throw new ko}return!0}};import{spawn as Nnt,execFile as znt}from"node:child_process";import{chmod as Mnt,lstat as L0e,mkdir as FG,readFile as j0e,readdir as Unt,realpath as F0e,rename as Lnt,rm as jnt,symlink as Fnt,writeFile as q0e}from"node:fs/promises";import{join as ll}from"node:path";import{promisify as qnt}from"node:util";import{createConnection as Vnt}from"node:net";import{setTimeout as Gnt}from"node:timers/promises";var qG=qnt(znt),W_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',SD=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=ll(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await FG(this.options.directory,{recursive:!0,mode:448}),await FG(this.sessions,{recursive:!0,mode:448}),await FG(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await L0e(this.options.workspaceLink),await F0e(this.options.workspaceLink)!==await F0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await Fnt(this.options.workspace,this.options.workspaceLink)}let e=ll(this.options.directory,"host_ed25519");try{await L0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await qG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Li(),timeout:1e4})}await Mnt(e,384),this.hostKey=hy.parse((await qG("ssh-keygen",["-y","-f",e],{env:Li(),timeout:1e4})).stdout);let r=ll(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+W_(e),"PidFile "+W_(ll(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+W_(ll(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+W_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+W_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
|
|
131
131
|
`)+`
|
|
132
132
|
`;await q0e(r,o,{mode:384}),await this.sync(),await qG("/usr/sbin/sshd",["-t","-f",r],{env:Li(),timeout:1e4});let n=Nnt("/usr/sbin/sshd",["-D","-e","-f",r],{env:Li(),detached:!0,stdio:"ignore"});this.child=n;let i=null;n.once("error",s=>{i=s});try{for(let s=0;;s++){if(i||n.exitCode!==null||n.signalCode!==null||s>=100)throw i??new Error("The SSH server could not start.");if(await this.listening())break;await Gnt(50)}await this.sync(),this.timer=setInterval(()=>{!this.pending&&!this.closing&&(this.pending=this.sync().catch(()=>{process.stderr.write(JSON.stringify({event:"ssh_settings_pending"})+`
|
|
133
133
|
`)}).finally(()=>{this.pending=null}))},1e4),this.timer.unref()}catch(s){throw await this.stop(),s}}ensureRunning(){if(!this.child?.pid||this.child.exitCode!==null||this.child.signalCode!==null)throw new Error("The SSH server has stopped.")}listening(){return new Promise(e=>{let r=Vnt({host:this.options.listenAddress==="::1"?"::1":"127.0.0.1",port:this.options.port});r.setTimeout(500),r.once("connect",()=>{r.destroy(),e(!0)}),r.once("error",()=>{r.destroy(),e(!1)}),r.once("timeout",()=>{r.destroy(),e(!1)})})}async activeSessions(){let e=0;for(let r of await Unt(this.sessions)){if(!/^[1-9][0-9]*$/.test(r))continue;let o=ll(this.sessions,r);try{let[n,i]=await Promise.all([j0e(o,"utf8"),j0e("/proc/"+r+"/stat","utf8")]),s=a=>a.slice(a.lastIndexOf(")")+2).trim().split(/\s+/)[19];if(!s(n)||s(n)!==s(i))throw new Error("The SSH session has ended.");e++}catch{await jnt(o,{force:!0})}}return Math.min(e,1024)}async sync(){let{configuration:e}=pE.parse(await this.heartbeat({hostKey:this.hostKey,appliedRevision:this.child?.pid&&this.child.exitCode===null&&this.child.signalCode===null?this.appliedRevision:0,activeSessions:await this.activeSessions()}));if(!e||e.port!==this.options.port)throw new Error("The SSH settings belong to another listener.");if(this.appliedRevision!==e.revision){let r=ll(this.options.directory,"authorized_keys."+crypto.randomUUID());await q0e(r,e.authorizedKeys.join(`
|