@tomato414941/foundation 13.1.0 → 13.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -125,8 +125,8 @@ ${c}`:c:"",l=Function,d=`return (input) => {
|
|
|
125
125
|
${c}
|
|
126
126
|
}`,f;try{f=new l(...s,d)(...a)}catch(p){throw new Ke(`this schema (generated code failed to evaluate: ${p.message})`)}return e?.debug&&(f.code=u),f.definite=o.definite,f}function ye(t,e){for(let[o,n]of t.constants)if(n===e)return o;let r=`c${t.constantCounter++}`;return t.constants.set(r,e),r}function Vl(t,e){return t.definite=!1,ye(t,e)}function pe(t){return`v${t.varCounter++}`}function uTe(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return qn;let o=r;return o.issues.length===0?o.value:qn}function _n(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return rr(t,e,r,o,n)}catch(u){if(!(u instanceof Ke)||!u.islandable)throw u;if(t.content.length=i,e.constants.size>s){let l=Array.from(e.constants.keys()).slice(s);for(let d of l)e.constants.delete(d)}return e.constantCounter=a,e.varCounter=c,lTe(t,e,r,o)}}function lTe(t,e,r,o){e.definite=!1;let n=ye(e,r),i=ye(e,uTe),s=pe(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var dTe=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function pTe(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&&!dTe.has(a.check))throw new Ke('check with a custom "when" condition');switch(a.check){case"greater_than":fTe(t,e,a,i);break;case"less_than":mTe(t,e,a,i);break;case"multiple_of":hTe(t,e,a,i);break;case"number_format":Q9(t,a,i);break;case"min_length":{let c=Fl(a.minimum,"min_length"),u=Kz(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Fl(a.maximum,"max_length"),u=Kz(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Fl(a.length,"length_equals"),u=Kz(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 < ${Fl(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${Fl(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${Fl(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=eZ(t,e,a,i);break;case"custom":i=bTe(t,e,s,i);break;case"bigint_format":gTe(t,a,i);break;case"mime_type":yTe(t,e,a,i);break;case"property":wTe(t,e,a,i);break;case"properties":vTe(t,e,a,i);break;case"overwrite":{let c=pe(e);_Te(t,e,s,i,c),i=c;break}default:throw new Ke(`check type ${a.check}`)}}return i}function Kz(t,e,r,o){let n=ye(e,zl),i=pe(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function Fl(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Ke(`${e} bound of type ${typeof t}`);return`${t}`}function Y9(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Ke("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Ke("comparison check with Invalid Date bound");return ye(t,e)}throw new Ke(`comparison check bound of type ${typeof e}`)}function fTe(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${Y9(e,r.value)}) return INVALID;`)}function mTe(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${Y9(e,r.value)}) return INVALID;`)}function hTe(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Ke("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ye(e,og);t.write(`if (${n}(${o}, ${Fl(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Q9(t,e,r){let o=e.format;switch(o){case"safeint":t.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":t.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":t.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":t.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":t.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Ke(`number format ${o}`)}}function gTe(t,e,r){let o=e.format;if(o)switch(o){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Ke(`bigint format ${o}`)}}function yTe(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=ye(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function vTe(t,e,r,o){if(r.when)throw new Ke('check with a custom "when" condition');t.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?ye(e,i):jn(i),a=pe(e);t.write(`const ${a} = ${o}[${s}];`),_n(t,e,n[i],a,!1)}}function wTe(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;rr(t,e,r.schema,n)}function _Te(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Ke("overwrite check without a transform function");if(Gl(i))throw new Oi("z.compile: async overwrite transforms are not supported");let s=ye(e,i);t.write(`const ${n} = ${s}(${o});`)}function Zz(){throw new ao}function Xz(t){this.issues.push(t)}function bTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Gl(n.fn))throw new Oi("z.compile: async .refine() predicates are not supported");let i=Vl(e,n.fn),s=ye(e,Zz),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(Gl(r._zod.check))throw new Oi("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=Vl(e,u=>{let l={value:u,issues:[],addIssue:Xz};return i(l)instanceof Promise&&Zz(),l.issues.length===0?l.value:qn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Ke("custom check without a predicate or check function")}var STe=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 eZ(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ye(e,_g);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ye(e,QS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ye(e,sx),l=ye(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ye(e,wg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ye(e,WS);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ye(e,rx);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ye(e,ox);return t.write(`if (!${u}(${o})) return INVALID;`),o}let s=r;if(i==="url"||i==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=ye(e,DS),l=ye(e,r),d=pe(e),f=pe(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${f} = ${u}(${d}, ${l});`),t.write(`if (typeof ${f} === "number") return INVALID;`),s.hostname!==void 0){let y=ye(e,NS);t.write(`if (!${y}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let y=ye(e,zS);t.write(`if (!${y}(${f}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=pe(e),h=s.normalize?`${f}.href`:`${ye(e,vg)}(${d})`;return t.write(`const ${p} = ${h};`),p}let a=r.fn;if(a){if(Gl(a))throw new Ke(`async string format ${i}`);let u=ye(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(STe.has(i)&&r.pattern){let u=ye(e,r.pattern);return t.write(`${u}.lastIndex = 0;`),t.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new Ke("regex format without a pattern");case"lowercase":t.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":t.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":t.write(`if (!${o}.includes(${jn(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${jn(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${jn(u)}) return INVALID;`);break}default:throw new Ke(`string format ${c}`)}return o}function rr(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Ke(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=xTe(t,e,r,o,a);break;case"number":c=ETe(t,r,o);break;case"boolean":c=$Te(t,o);break;case"bigint":c=RTe(t,r,o);break;case"symbol":c=ITe(t,o);break;case"undefined":c=ATe(t,o);break;case"null":c=PTe(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=kTe(t,o);break;case"nan":c=TTe(t,o);break;case"date":c=CTe(t,o);break;case"object":c=OTe(t,e,r,o,a);break;case"optional":c=DTe(t,e,r,o,a);break;case"nullable":c=MTe(t,e,r,o,a);break;case"array":c=UTe(t,e,r,o,a);break;case"literal":c=LTe(t,e,r,o);break;case"enum":c=jTe(t,e,r,o);break;case"readonly":{let u=W9(t,e,r,o),l=pe(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":W9(t,e,r,o),c="true";break;case"default":case"prefault":c=FTe(t,e,r,o);break;case"nonoptional":c=qTe(t,e,r,o);break;case"tuple":c=VTe(t,e,r,o);break;case"union":c=GTe(t,e,r,o);break;case"intersection":c=KTe(t,e,r,o);break;case"record":c=ZTe(t,e,r,o);break;case"map":c=JTe(t,e,r,o);break;case"set":c=XTe(t,e,r,o);break;case"file":c=YTe(t,o);break;case"template_literal":c=QTe(t,e,r,o);break;case"lazy":c=eCe(t,e,r,o);break;case"pipe":c=tCe(t,e,r,o);break;case"custom":c=rCe(t,e,r,o);break;case"transform":c=iCe(t,e,r,o);break;case"catch":c=oCe(t,e,r,o);break;default:throw new Ke(`schema type ${s}`)}return c===null?null:pTe(t,e,r,c)}function xTe(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:eZ(t,e,i,o,n)}function ETe(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&&Q9(t,{format:o.format},r),r}function $Te(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function RTe(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 ITe(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function ATe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function PTe(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function kTe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function TTe(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function CTe(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function OTe(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let s=i.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=S=>typeof S=="symbol"?ye(e,S):jn(S),d=S=>typeof S=="symbol"?`[${l(S)}]`:jn(S),f=s;if(a.includes("__proto__"))throw new Ke('object shape key "__proto__"');let p=new Map;for(let S of u){let x=f[S],R=l(S),T=pe(e);if(t.write(`const ${T} = ${o}[${R}];`),x._zod.optin!==void 0){let M=pe(e);t.write(`let ${M} = (() => {`),t.indented(Z=>{let te=_n(Z,e,x,T);Z.write(`return ${te};`)}),t.write("})();"),x._zod.optout==="optional"?(t.write(`if (${M} === INVALID) {`),t.indented(Z=>{Z.write(`if (${R} in ${o}) return INVALID;`),Z.write(`${M} = undefined;`)}),t.write("}")):t.write(`if (${M} === INVALID) return INVALID;`),p.set(S,M)}else{zTe(x)&&t.write(`if (!(${R} in ${o})) return INVALID;`);let M=_n(t,e,x,T,n);M!==null&&p.set(S,M)}}let h=i.catchall,y="none";if(h){let S=h._zod.def.type;if(S==="never"){let x=a.map(R=>`k !== ${jn(R)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(R=>{R.write(`if (${x}) return INVALID;`)}),t.write("}")}else(S==="unknown"||S==="any")&&!h._zod.def.checks?.length?y="passthrough":y="schema"}let w=pe(e),b=u.some(S=>Z9(f[S])||Wz(f[S]));if(!n){if(y==="schema"){let S=a.length>0?ye(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`);let R=pe(e);x.write(`const ${R} = ${o}[k];`),_n(x,e,h,R,!1)}),t.write("}")}return null}if(b){t.write(`const ${w} = {};`);for(let S of u){let x=l(S),R=p.get(S);Wz(f[S])?t.write(`if (${x} in ${o}) ${w}[${x}] = ${R};`):Z9(f[S])?t.write(`if (${R} !== undefined || ${x} in ${o}) ${w}[${x}] = ${R};`):t.write(`${w}[${x}] = ${R};`)}}else{let S=u.map(x=>`${d(x)}: ${p.get(x)}`).join(", ");t.write(`const ${w} = { ${S} };`)}if(y!=="none"){let S=a.length>0?ye(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{if(x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`),y==="passthrough")x.write(`${w}[k] = ${o}[k];`);else{let R=pe(e);x.write(`const ${R} = ${o}[k];`);let T=_n(x,e,h,R);x.write(`${w}[k] = ${T};`)}}),t.write("}")}return w}function DTe(t,e,r,o,n=!0){let i=r._zod.def;if(NTe(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 NTe(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function zTe(t){return t._zod.optin===void 0&&ql(t)}function ql(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?ql(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?ql(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(ql):!0;case"intersection":return!e.left||!e.right?!0:ql(e.left)&&ql(e.right);case"pipe":return e.in?ql(e.in):!0;default:return!0}}function Wz(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function Z9(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&jp(t)}function jp(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?jp(e.innerType):!0;case"union":return e.options?e.options.some(jp):!0;case"intersection":return!e.left||!e.right||jp(e.left)||jp(e.right);case"pipe":return e.out?jp(e.out):!0;default:return!0}}function MTe(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 UTe(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 LTe(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=ye(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=ye(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${jn(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")t.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)t.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)t.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")t.write(`if (${o} !== ${s}n) return INVALID;`);else throw new Ke(`literal type ${typeof s}`);return o}function jTe(t,e,r,o){let n=r._zod.values;if(!n)throw new Ke("enum schema without enumerated values");let i=ye(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function W9(t,e,r,o){let n=r._zod.def;return rr(t,e,n.innerType,o)}function FTe(t,e,r,o){let n=r._zod.def,s=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!s)return rr(t,e,n.innerType,o);let c=ye(e,s),u=pe(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),rr(t,e,n.innerType,u)}let a=pe(e);if(s){let c=ye(e,s),u=ye(e,bp);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 qTe(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 VTe(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=J9(i,"optin"),c=J9(i,"optout");s?t.write(`if (${o}.length < ${a}) return INVALID;`):t.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=pe(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(f=>{f.write(`if (${l} < ${o}.length) {`),f.indented(p=>{let h=pe(e);p.write(`const ${h} = ${o}[${l}];`);let y=_n(p,e,d,h);p.write(`${u}[${l}] = ${y};`)}),f.write("} else {"),f.indented(p=>{if(Wz(d)){p.write(`${u}.length = ${l};`);return}let h=pe(e),y=pe(e);p.write(`const ${h} = undefined;`),p.write(`const ${y} = (() => {`),p.indented(w=>{let b=_n(w,e,d,h);w.write(`return ${b};`)}),p.write("})();"),p.write(`if (${y} === INVALID || ${y} === undefined) ${u}.length = ${l};`),p.write(`else ${u}[${l}] = ${y};`)}),f.write("}")}),t.write("}");else{let f=pe(e);t.write(`const ${f} = ${o}[${l}];`);let p=_n(t,e,d,f);t.write(`${u}[${l}] = ${p};`)}}if(s){let l=pe(e),d=pe(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(f=>{f.write(`const ${d} = ${o}[${l}];`);let p=_n(f,e,s,d);f.write(`${u}[${l}] = ${p};`)}),t.write("}")}return u}function J9(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 GTe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return HTe(t,e,n,o);if(n.inclusive===!1)throw new Ke("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return rr(t,e,i[0],o);if(i.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(i.flatMap(l=>l._zod.def.values)),u=ye(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=pe(e);t.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?t.write(`${a} = (() => {`):t.write(`if (${a} === INVALID) ${a} = (() => {`),t.indented(l=>{let d=rr(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function HTe(t,e,r,o){if(r.unionFallback)throw new Ke("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=pe(e),i=pe(e);t.write(`const ${n} = ${o}?.[${jn(r.discriminator)}];`),t.write(`let ${i};`);let s=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Ke("discriminated union option without static discriminator values");for(let f of u){if(a.has(f))throw new Ke(`duplicate discriminator value ${String(f)}`);a.add(f)}let l=Array.from(u,f=>BTe(e,n,f)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(f=>{let p=rr(f,e,c,o);f.write(`${i} = ${p};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function BTe(t,e,r){if(typeof r=="string")return`${e} === ${jn(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${e})`:`${e} === ${r}`;if(typeof r=="boolean")return`${e} === ${r}`;if(r===null)return`${e} === null`;if(r===void 0)return`${e} === undefined`;if(typeof r=="bigint")return`${e} === ${r}n`;if(typeof r=="symbol"){let o=ye(t,r);return`${e} === ${o}`}throw new Ke(`literal discriminator value ${String(r)}`)}function KTe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=_n(t,e,n.left,o),s=_n(t,e,n.right,o),a=ye(e,Cp),c=pe(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function ZTe(t,e,r,o){let n=r._zod.def,i=ye(e,Xo);t.write(`if (!${i}(${o})) return INVALID;`);let s=pe(e),a=pe(e),c=pe(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let y of l){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new Ke(`record key value ${String(y)}`);let w=typeof y=="number"?y.toString():y;if(w==="__proto__")throw new Ke('record key "__proto__"');p.push(w);let b=ye(e,y),S=rr(t,e,n.keyType,b),x=pe(e);t.write(`const ${x} = ${o}[${WTe(e,w)}];`);let R=_n(t,e,n.valueType,x);t.write(`${s}[${S}] = ${R};`)}let h=ye(e,new Set(p));return t.write(`for (const ${a} in ${o}) {`),t.indented(y=>{y.write(`if (${h}.has(${a})) continue;`),u.mode==="loose"?y.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):y.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let p=n.mode==="loose",h=r0(n.keyType);h.definite===!1&&(e.definite=!1);let y=ye(e,h),w=ye(e,qa),b=pe(e);return X9(t,e,o,a,S=>{S.write(`let ${b} = ${y}(${a});`),S.write(`if (${b} === INVALID && typeof ${a} === "string" && ${w}.test(${a})) ${b} = ${y}(Number(${a}));`),p?S.write(`if (${b} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):S.write(`if (${b} === INVALID) return INVALID;`),S.write(`if (${b} === "__proto__") continue;`);let x=pe(e);S.write(`const ${x} = ${o}[${a}];`);let R=_n(S,e,n.valueType,x);S.write(`${s}[${b}] = ${R};`)}),s}return X9(t,e,o,a,p=>{p.write(`const ${c} = ${o}[${a}];`);let h=_n(p,e,n.valueType,c);p.write(`${s}[${a}] = ${h};`)},"return INVALID;"),s}function X9(t,e,r,o,n,i){let s=ye(e,Object.prototype.propertyIsEnumerable),a=pe(e),c=pe(e),u=pe(e);t.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),t.write(`const ${c} = Object.getOwnPropertyNames(${r});`),t.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),t.write("}"),t.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),t.write("}")}function WTe(t,e){return typeof e=="string"?jn(e):ye(t,e)}function JTe(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 XTe(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 YTe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function QTe(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=ye(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function eCe(t,e,r,o){let n=r._zod.def,i=Vl(e,n.getter),s=ye(e,{parser:null});t.write(`if (!${s}.parser) {`),t.indented(c=>{c.write(`const inner = ${i}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),t.write("}");let a=pe(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function tCe(t,e,r,o){let n=r._zod.def,i=rr(t,e,n.in,o);if(n.transform){if(Gl(n.transform))throw new Oi("z.compile: async transforms in pipes are not supported");let s=n.transform,c=Vl(e,l=>{let d={value:l,issues:[],addIssue:Xz},f=s(l,d);return f instanceof Promise?qn:d.issues.length===0?f:qn}),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 Gl(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function rCe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Gl(n.fn))throw new Oi("z.compile: async custom predicates are not supported");let i=Vl(e,n.fn),s=ye(e,Zz),a=pe(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Ke("custom schema without a predicate function");return o}function nCe(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return qn;let n=o;return n.issues.length===0?n.value:e()}function oCe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[lS])throw new Ke("catch with a callback (only a constant catch value compiles)",!1);let i=pe(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=_n(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ye(e,n.innerType),a=Vl(e,n.catchValue),c=ye(e,nCe);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 iCe(t,e,r,o){let n=r._zod.def;if(n.transform){if(Gl(n.transform))throw new Oi("z.compile: async transforms are not supported");let i=n.transform,a=Vl(e,u=>{let l={value:u,issues:[],addIssue:Xz},d=i(u,l);return d instanceof Promise?qn:l.issues.length===0?d:qn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function n0(t){return t.checks&&(t.checks=[...t.checks]),t}function o0(t,e){return new t(n0({type:"string",...j(e)}))}function Yz(t,e){return new t(n0({type:"string",coerce:!0,...j(e)}))}function Tg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Cg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function Og(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Dg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Ng(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function zg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Fp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function Mg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Ug(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function Lg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function jg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function Fg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function qg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function Vg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function Gg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function Hg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function i0(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...j(e)})}function Bg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function Kg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function Zg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Wg(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function Jg(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function s0(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...j(e)})}function a0(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...j(e)})}function Xg(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}var Qz={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Yg(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function Qg(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function ey(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function ty(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function c0(t,e){return new t(n0({type:"number",checks:[],...j(e)}))}function eM(t,e){return new t(n0({type:"number",coerce:!0,checks:[],...j(e)}))}function u0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function l0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...j(e)})}function d0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...j(e)})}function p0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...j(e)})}function f0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...j(e)})}function m0(t,e){return new t({type:"boolean",...j(e)})}function tM(t,e){return new t({type:"boolean",coerce:!0,...j(e)})}function h0(t,e){return new t({type:"bigint",...j(e)})}function rM(t,e){return new t({type:"bigint",coerce:!0,...j(e)})}function g0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...j(e)})}function y0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...j(e)})}function v0(t,e){return new t({type:"symbol",...j(e)})}function w0(t,e){return new t({type:"undefined",...j(e)})}function _0(t,e){return new t({type:"null",...j(e)})}function b0(t){return new t({type:"any"})}function S0(t){return new t({type:"unknown"})}function x0(t,e){return new t({type:"never",...j(e)})}function E0(t,e){return new t({type:"void",...j(e)})}function $0(t,e){return new t({type:"date",...j(e)})}function nM(t,e){return new t({type:"date",coerce:!0,...j(e)})}function R0(t,e){return new t({type:"nan",...j(e)})}function Ps(t,e){return new ES({check:"less_than",...j(e),value:t,inclusive:!1})}function $o(t,e){return new ES({check:"less_than",...j(e),value:t,inclusive:!0})}function ks(t,e){return new $S({check:"greater_than",...j(e),value:t,inclusive:!1})}function Ro(t,e){return new $S({check:"greater_than",...j(e),value:t,inclusive:!0})}function I0(t){return ks(0,t)}function A0(t){return Ps(0,t)}function P0(t){return $o(0,t)}function k0(t){return Ro(0,t)}function jc(t,e){return new fz({check:"multiple_of",...j(e),value:t})}function Fc(t,e){return new gz({check:"max_size",...j(e),maximum:t})}function Ts(t,e){return new yz({check:"min_size",...j(e),minimum:t})}function Hl(t,e){return new vz({check:"size_equals",...j(e),size:t})}function Bl(t,e){return new wz({check:"max_length",...j(e),maximum:t})}function Va(t,e){return new _z({check:"min_length",...j(e),minimum:t})}function Kl(t,e){return new bz({check:"length_equals",...j(e),length:t})}function qp(t,e){return new Sz({check:"string_format",format:"regex",...j(e),pattern:t})}function Vp(t){return new xz({check:"string_format",format:"lowercase",...j(t)})}function Gp(t){return new Ez({check:"string_format",format:"uppercase",...j(t)})}function Hp(t,e){return new $z({check:"string_format",format:"includes",...j(e),includes:t})}function Bp(t,e){return new Rz({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Kp(t,e){return new Iz({check:"string_format",format:"ends_with",...j(e),suffix:t})}function T0(t,e,r){return new Az({check:"property",property:t,schema:e,...j(r)})}function Zp(t,e){return new Pz({check:"properties",shape:t,...j(e)})}function Wp(t,e){return new kz({check:"mime_type",mime:t,...j(e)})}function Di(t){return new Tz({check:"overwrite",tx:t})}function Jp(t){return Di(e=>e.normalize(t))}function Xp(){return Di(t=>t.trim())}function Yp(){return Di(t=>t.toLowerCase())}function Qp(){return Di(t=>t.toUpperCase())}function ef(){return Di(t=>m1(t))}function oM(t,e,r){return new t({type:"array",element:e,...j(r)})}function sCe(t,e,r){return new t({type:"union",options:e,...j(r)})}function aCe(t,e,r){return new t({type:"union",options:e,inclusive:!1,...j(r)})}function cCe(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...j(o)})}function uCe(t,e,r){return new t({type:"intersection",left:e,right:r})}function lCe(t,e,r,o){let n=r instanceof be,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...j(i)})}function dCe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...j(o)})}function pCe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...j(o)})}function fCe(t,e,r){return new t({type:"set",valueType:e,...j(r)})}function mCe(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 hCe(t,e,r){return new t({type:"enum",entries:e,...j(r)})}function gCe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...j(r)})}function C0(t,e){return new t({type:"file",...j(e)})}function yCe(t,e){return new t({type:"transform",transform:e})}function vCe(t,e){return new t({type:"optional",innerType:e})}function wCe(t,e){return new t({type:"nullable",innerType:e})}function _Ce(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():bp(r)}})}function bCe(t,e,r){return new t({type:"nonoptional",innerType:e,...j(r)})}function SCe(t,e){return new t({type:"success",innerType:e})}function xCe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:b1(r)})}function ECe(t,e,r){return new t({type:"pipe",in:e,out:r})}function $Ce(t,e){return new t({type:"readonly",innerType:e})}function RCe(t,e,r){return new t({type:"template_literal",parts:e,...j(r)})}function ICe(t,e){return new t({type:"lazy",getter:e})}function ACe(t,e){return new t({type:"promise",innerType:e})}function O0(t,e,r){let o=j(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function D0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function N0(t,e){let r=tZ(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Sp(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(Sp(i))}},t(o.value,o)),e);return r}function tZ(t,e){let r=new Pt({check:"custom",...j(e)});return r._zod.check=t,r}function z0(t){let e=new Pt({check:"describe"});return e._zod.onattach=[r=>{let o=Jr.get(r)??{};Jr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function M0(t){let e=new Pt({check:"meta"});return e._zod.onattach=[r=>{let o=Jr.get(r)??{};Jr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function U0(t,e){let r=j(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(p=>typeof p=="string"?p.toLowerCase():p),n=n.map(p=>typeof p=="string"?p.toLowerCase():p));let i=new Set(o),s=new Set(n),a=t.Codec??Np,c=t.Boolean??Op,u=t.String??Lc,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),f=new a({type:"pipe",in:l,out:d,transform:((p,h)=>{let y=p;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:s.has(y)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:h.value,inst:f,continue:!1}),{})}),reverseTransform:((p,h)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function qc(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 ry(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&Wr(t,o,r[o]);return t}function Vc(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??Jr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function Pr(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function Rt(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let f=s.schema,p=e.processors[n.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);p(t,e,f,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),Rt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&ry(s.schema,c),e.io==="input"&&Vn(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 rZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Gc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(h=>h);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${rZ(p)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+rZ(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 iZ(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;iZ(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 sZ=new Set(["type","properties","required","additionalProperties"]),nZ=["oneOf","anyOf"];function oZ(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function iM(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!sZ.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]??oZ(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:iM(a)??{allOf:a};Wr(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=oZ(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 PCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of sZ)if(n in t)return;let r=e.filter(n=>nZ.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=iM(e);else{let n=r[0],i=nZ.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=>iM([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,ry(t,o))}function Hc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):ry(u,h),ry(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(h.$ref&&p.def)for(let w in u)w==="$ref"||w==="allOf"||w in p.def&&JSON.stringify(u[w])===JSON.stringify(p.def[w])&&delete u[w]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}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())iZ(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)??[])PCe(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)}ry(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,Wr(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:tf(e,"input",t.processors),output:tf(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Vn(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 Vn(o.element,r);if(o.type==="set")return Vn(o.valueType,r);if(o.type==="lazy")return Vn(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 Vn(o.innerType,r);if(o.type==="intersection")return Vn(o.left,r)||Vn(o.right,r);if(o.type==="record"||o.type==="map")return Vn(o.keyType,r)||Vn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Vn(o.in,r)||Vn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Vn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Vn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Vn(n,r))return!0;return!!(o.rest&&Vn(o.rest,r))}return!1}var sM=(t,e={})=>r=>{let o=Vc({...r,processors:e});return Rt(t,o),Gc(o,t),Hc(o,t)},tf=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Vc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Gc(s,t),Hc(s,t)};var rf=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},nf=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},aZ=(t,e)=>{rf(t,"minimum",e),nf(t,"maximum",e)},dZ=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},pZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},fZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},mZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},cZ=(t,e)=>rf(t,"minimum",e.minimum),uZ=(t,e)=>nf(t,"maximum",e.maximum),lZ=t=>(e,r)=>{mZ(e,r.format);let[o,n]=t[r.format];rf(e,"minimum",o),nf(e,"maximum",n)},kCe={greater_than:(t,e)=>rf(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>nf(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>dZ(t,e.value),number_format:lZ(sg),bigint_format:lZ(ag),min_length:cZ,max_length:uZ,length_equals:(t,e)=>aZ(t,e.length),min_size:cZ,max_size:uZ,size_equals:(t,e)=>aZ(t,e.size),string_format:(t,e)=>{mZ(t,e.format),e.pattern&&pZ(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)=>fZ(t,e.mime)};function kr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)kCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&rf(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&rf(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&nf(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&nf(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&dZ(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&fZ(e,n.mime);for(let i of n.patterns??[])pZ(e,i);return e}var TCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},CCe=new Map([[XS,K1],[bg,Z1]]),hZ=t=>CCe.get(t)??t,uM=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=kr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=TCe[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(hZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},lM=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=kr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let h=new Set;for(let b of a)Number.isFinite(b)&&b!==0?h.add(Math.abs(b)):Pr(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=h;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},dM=(t,e,r,o)=>{r.type="boolean"},pM=(t,e,r,o)=>{Pr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},fM=(t,e,r,o)=>{Pr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},mM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},hM=(t,e,r,o)=>{Pr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},gM=(t,e,r,o)=>{Pr(t,e,r,o,"Void cannot be represented in JSON Schema")},yM=(t,e,r,o)=>{r.not={}},vM=(t,e,r,o)=>{},wM=(t,e,r,o)=>{},_M=(t,e,r,o)=>{Pr(t,e,r,o,"Date cannot be represented in JSON Schema")},bM=(t,e,r,o)=>{let n=t._zod.def,i=yp(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},SM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Pr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Pr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},xM=(t,e,r,o)=>{Pr(t,e,r,o,"NaN cannot be represented in JSON Schema")},EM=(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},$M=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=kr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},RM=(t,e,r,o)=>{r.type="boolean"},IM=(t,e,r,o)=>{Pr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},AM=(t,e,r,o)=>{Pr(t,e,r,o,"Function types cannot be represented in JSON Schema")},PM=(t,e,r,o)=>{Pr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},kM=(t,e,r,o)=>{Pr(t,e,r,o,"Map cannot be represented in JSON Schema")},TM=(t,e,r,o)=>{Pr(t,e,r,o,"Set cannot be represented in JSON Schema")},CM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=kr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function ny(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?ny(e.out):e.type==="catch"?ny(e.innerType):t._zod.optin}var OM=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Pr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Wr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?ny(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},j0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},DM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},NM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?ny(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:h}=kr(t);typeof p=="number"&&(n.minItems=p),typeof h=="number"&&(n.maxItems=h)};function aM(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let h=t.get(e)?.def;if(!h)return e;let y=aM(t,h,r);return y===h?e:y}for(let h of["anyOf","oneOf"]){let y=e[h];if(!Array.isArray(y))continue;let w=y.map(b=>aM(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[h]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(h=>typeof h=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(h=>typeof h=="number"?String(h):h):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?qa:mg).source)),p}var cM=new WeakMap;function OCe(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 cM.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=aM(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 zM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=kr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Wr(n.patternProperties,hZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=cM.get(e);l||(l=[],cM.set(e,l),e.deferred.push(()=>OCe(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&ny(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))}},MM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},UM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},LM=Symbol();function gZ(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Pr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),LM):JSON.parse(s)}var jM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=gZ(n.defaultValue,t,e,r,o);s!==LM&&(r.default=s)},FM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=gZ(n.defaultValue,t,e,r,o);s!==LM&&(r._prefault=s)},qM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Pr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},VM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},GM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},HM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},F0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},BM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},L0={string:uM,number:lM,boolean:dM,bigint:pM,symbol:fM,null:mM,undefined:hM,void:gM,never:yM,any:vM,unknown:wM,date:_M,enum:bM,literal:SM,nan:xM,template_literal:EM,file:$M,success:RM,custom:IM,function:AM,transform:PM,map:kM,set:TM,array:CM,object:OM,union:j0,intersection:DM,tuple:NM,record:zM,nullable:MM,nonoptional:UM,default:jM,prefault:FM,catch:qM,pipe:VM,readonly:GM,promise:HM,optional:F0,lazy:BM};function Zl(t,e){if("_idmap"in t){let o=t,n=Vc({...e,processors:L0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Gc(n,l),Wr(s,u,Hc(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=Vc({...e,processors:L0});return Rt(t,r),Gc(r,t),Hc(r,t)}var q0=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=Vc({processors:L0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Gc(this.ctx,e);let o=Hc(this.ctx,e),{"~standard":n,...i}=o;return i}};var yZ={};var pf={};Ht(pf,{ZodAny:()=>dU,ZodArray:()=>hU,ZodBase64:()=>aE,ZodBase64URL:()=>cE,ZodBigInt:()=>lf,ZodBigIntFormat:()=>dE,ZodBoolean:()=>uf,ZodCIDRv4:()=>iE,ZodCIDRv6:()=>sE,ZodCUID:()=>Y0,ZodCUID2:()=>Q0,ZodCatch:()=>DU,ZodCodec:()=>py,ZodCreditCard:()=>sU,ZodCustom:()=>fy,ZodCustomStringFormat:()=>Jl,ZodDate:()=>ay,ZodDefault:()=>AU,ZodDiscriminatedUnion:()=>yU,ZodE164:()=>uE,ZodEmail:()=>Z0,ZodEmoji:()=>J0,ZodEnum:()=>sf,ZodExactOptional:()=>mE,ZodFile:()=>EU,ZodFunction:()=>GU,ZodGUID:()=>W0,ZodIBAN:()=>aU,ZodIPv4:()=>nE,ZodIPv6:()=>oE,ZodISODate:()=>Kc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Wc,ZodISOTime:()=>Zc,ZodInstanceOf:()=>KU,ZodIntersection:()=>vU,ZodJWT:()=>lE,ZodKSUID:()=>rE,ZodLazy:()=>FU,ZodLiteral:()=>xU,ZodMAC:()=>iU,ZodMap:()=>bU,ZodNaN:()=>zU,ZodNanoID:()=>X0,ZodNever:()=>fU,ZodNonOptional:()=>hE,ZodNull:()=>lU,ZodNullable:()=>IU,ZodNumber:()=>cf,ZodNumberFormat:()=>Xl,ZodObject:()=>cy,ZodOptional:()=>Yl,ZodPipe:()=>dy,ZodPrefault:()=>kU,ZodPreprocess:()=>MU,ZodPromise:()=>VU,ZodReadonly:()=>UU,ZodRecord:()=>of,ZodSet:()=>SU,ZodString:()=>af,ZodStringFormat:()=>Tt,ZodSuccess:()=>OU,ZodSymbol:()=>cU,ZodTemplateLiteral:()=>jU,ZodTransform:()=>$U,ZodTuple:()=>wU,ZodType:()=>Ce,ZodULID:()=>eE,ZodURL:()=>iy,ZodUUID:()=>Cs,ZodUndefined:()=>uU,ZodUnion:()=>uy,ZodUnknown:()=>pU,ZodVoid:()=>mU,ZodXID:()=>tE,ZodXor:()=>gU,_ZodString:()=>K0,_default:()=>PU,_function:()=>$W,any:()=>sW,array:()=>qe,base64:()=>jZ,base64url:()=>FZ,bigint:()=>tW,boolean:()=>hr,catch:()=>NU,check:()=>RW,cidrv4:()=>UZ,cidrv6:()=>LZ,codec:()=>bW,creditCard:()=>VZ,cuid:()=>kZ,cuid2:()=>TZ,currencyCode:()=>WZ,custom:()=>gE,date:()=>cW,describe:()=>IW,discriminatedUnion:()=>ly,e164:()=>qZ,email:()=>_Z,emoji:()=>AZ,enum:()=>Yr,exactOptional:()=>RU,file:()=>yW,float32:()=>XZ,float64:()=>YZ,function:()=>$W,guid:()=>bZ,hash:()=>JZ,hex:()=>ZZ,hostname:()=>KZ,httpUrl:()=>IZ,iban:()=>GZ,instanceof:()=>PW,int:()=>H0,int32:()=>QZ,int64:()=>rW,intersection:()=>df,invertCodec:()=>SW,ipv4:()=>NZ,ipv6:()=>MZ,json:()=>TW,jwt:()=>HZ,keyof:()=>uW,ksuid:()=>DZ,lazy:()=>qU,literal:()=>ae,looseObject:()=>Xr,looseRecord:()=>fW,mac:()=>zZ,map:()=>mW,meta:()=>AW,nan:()=>_W,nanoid:()=>PZ,nativeEnum:()=>gW,never:()=>pE,nonoptional:()=>CU,null:()=>sy,nullable:()=>oy,nullish:()=>vW,number:()=>yt,object:()=>X,optional:()=>kt,partialRecord:()=>pW,pipe:()=>B0,prefault:()=>TU,preprocess:()=>my,promise:()=>EW,readonly:()=>LU,record:()=>Ct,refine:()=>HU,set:()=>hW,strictObject:()=>lW,string:()=>O,stringFormat:()=>BZ,stringbool:()=>kW,success:()=>wW,superRefine:()=>BU,symbol:()=>oW,templateLiteral:()=>xW,transform:()=>fE,tuple:()=>_U,uint32:()=>eW,uint64:()=>nW,ulid:()=>CZ,undefined:()=>iW,union:()=>It,unknown:()=>Ut,url:()=>RZ,uuid:()=>SZ,uuidv4:()=>xZ,uuidv6:()=>EZ,uuidv7:()=>$Z,void:()=>aW,xid:()=>OZ,xor:()=>dW});var V0={};Ht(V0,{endsWith:()=>Kp,gt:()=>ks,gte:()=>Ro,includes:()=>Hp,length:()=>Kl,lowercase:()=>Vp,lt:()=>Ps,lte:()=>$o,maxLength:()=>Bl,maxSize:()=>Fc,mime:()=>Wp,minLength:()=>Va,minSize:()=>Ts,multipleOf:()=>jc,negative:()=>A0,nonnegative:()=>k0,nonpositive:()=>P0,normalize:()=>Jp,overwrite:()=>Di,positive:()=>I0,properties:()=>Zp,property:()=>T0,regex:()=>qp,size:()=>Hl,slugify:()=>ef,startsWith:()=>Bp,toLowerCase:()=>Yp,toUpperCase:()=>Qp,trim:()=>Xp,uppercase:()=>Gp});var vZ=new WeakSet([Object.prototype,Error.prototype]);function G0(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 wZ=(t,e)=>{I1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);vZ.has(r)||(vZ.add(r),G0(r,"format",o=>n=>pg(o,n)),G0(r,"flatten",o=>n=>dg(o,n)),G0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,vp,2)}),G0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,vp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},NCe=$("ZodError",wZ),uo=$("ZodError",wZ,void 0,{Parent:Error});var KM=xp(uo),ZM=Ep(uo),WM=$p(uo),JM=Ip(uo),XM=pS(uo),YM=fS(uo),QM=mS(uo),eU=hS(uo),tU=gS(uo),rU=yS(uo),nU=vS(uo),oU=wS(uo);function MCe(){zr.localeError||cr(Jx())}function Wl(){zr.memoizer||cr({memoizer:Pg()})}var Ce=$("ZodType",(t,e)=>(MCe(),be.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(HU(t,e))},superRefine(t,e){return this.check(BU(t,e))},overwrite(t){return this.check(Di(t))},optional(){return kt(this)},exactOptional(){return RU(this)},nullable(){return oy(this)},nullish(){return kt(oy(this))},nonoptional(t){return CU(this,t)},array(){return qe(this)},or(t){return It([this,t])},and(t){return df(this,t)},transform(t){return B0(this,fE(t))},default(t){return PU(this,t)},prefault(t){return TU(this,t)},catch(t){return NU(this,t)},pipe(t){return B0(this,t)},readonly(){return LU(this)},describe(t){let e=this.clone();return Jr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Jr.get(this);let e=this.clone();return Jr.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",{...kS(this),jsonSchema:{input:tf(this,"input"),output:tf(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return KM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await ZM(this,e,r,{callee:t})},safeParse(t,e){return WM(this,t,e)},async safeParseAsync(t,e){return JM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Pp(this,t,e)},validateAsync(t,e){return kp(this,t,e)},encode:function t(e,r){return XM(this,e,r,{callee:t})},decode:function t(e,r){return YM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await QM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await eU(this,e,r,{callee:t})},safeEncode(t,e){return tU(this,t,e)},safeDecode(t,e){return rU(this,t,e)},async safeEncodeAsync(t,e){return nU(this,t,e)},async safeDecodeAsync(t,e){return oU(this,t,e)},toJSONSchema(t){return sM(this,{})(t)},get description(){return Jr.get(this)?.description},get _def(){return this._zod.def}}),K0=$("_ZodString",(t,e)=>{Lc.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n)},D.derived({format:t=>kr(t).format??null,minLength:t=>kr(t).minimum??null,maxLength:t=>kr(t).maximum??null},{regex(...t){return this.check(qp(...t))},includes(...t){return this.check(Hp(...t))},startsWith(...t){return this.check(Bp(...t))},endsWith(...t){return this.check(Kp(...t))},min(...t){return this.check(Va(...t))},max(...t){return this.check(Bl(...t))},length(...t){return this.check(Kl(...t))},nonempty(...t){return this.check(Va(1,...t))},lowercase(t){return this.check(Vp(t))},uppercase(t){return this.check(Gp(t))},trim(){return this.check(Xp())},normalize(...t){return this.check(Jp(...t))},toLowerCase(){return this.check(Yp())},toUpperCase(){return this.check(Qp())},slugify(){return this.check(ef())}})),af=$("ZodString",(t,e)=>{Lc.init(t,e),K0.init(t,e)},{email(t){return this.check(Tg(Z0,t))},url(t){return this.check(Fp(iy,t))},jwt(t){return this.check(Xg(lE,t))},emoji(t){return this.check(Mg(J0,t))},guid(t){return this.check(Cg(W0,t))},uuid(t){return this.check(Og(Cs,t))},uuidv4(t){return this.check(Dg(Cs,t))},uuidv6(t){return this.check(Ng(Cs,t))},uuidv7(t){return this.check(zg(Cs,t))},nanoid(t){return this.check(Ug(X0,t))},cuid(t){return this.check(Lg(Y0,t))},cuid2(t){return this.check(jg(Q0,t))},ulid(t){return this.check(Fg(eE,t))},base64(t){return this.check(Zg(aE,t))},base64url(t){return this.check(Wg(cE,t))},xid(t){return this.check(qg(tE,t))},ksuid(t){return this.check(Vg(rE,t))},ipv4(t){return this.check(Gg(nE,t))},ipv6(t){return this.check(Hg(oE,t))},cidrv4(t){return this.check(Bg(iE,t))},cidrv6(t){return this.check(Kg(sE,t))},e164(t){return this.check(Jg(uE,t))},datetime(t){return this.check(Yg(Bc,t))},date(t){return this.check(Qg(Kc,t))},time(t){return this.check(ey(Zc,t))},duration(t){return this.check(ty(Wc,t))}});function O(t){return o0(af,t)}var Tt=$("ZodStringFormat",(t,e)=>{St.init(t,e),K0.init(t,e)}),Bc=$("ZodISODateTime",(t,e)=>{zz.init(t,e),Tt.init(t,e)}),Kc=$("ZodISODate",(t,e)=>{Mz.init(t,e),Tt.init(t,e)}),Zc=$("ZodISOTime",(t,e)=>{Uz.init(t,e),Tt.init(t,e)}),Wc=$("ZodISODuration",(t,e)=>{Lz.init(t,e),Tt.init(t,e)}),Z0=$("ZodEmail",(t,e)=>{OS.init(t,e),Tt.init(t,e)});function _Z(t){return Tg(Z0,t)}var W0=$("ZodGUID",(t,e)=>{TS.init(t,e),Tt.init(t,e)});function bZ(t){return Cg(W0,t)}var Cs=$("ZodUUID",(t,e)=>{CS.init(t,e),Tt.init(t,e)});function SZ(t){return Og(Cs,t)}function xZ(t){return Dg(Cs,t)}function EZ(t){return Ng(Cs,t)}function $Z(t){return zg(Cs,t)}var iy=$("ZodURL",(t,e)=>{MS.init(t,e),Tt.init(t,e)});function RZ(t){return Fp(iy,t)}function IZ(t){return Fp(iy,{protocol:fg,hostname:J1,...D.normalizeParams(t)})}var J0=$("ZodEmoji",(t,e)=>{US.init(t,e),Tt.init(t,e)});function AZ(t){return Mg(J0,t)}var X0=$("ZodNanoID",(t,e)=>{LS.init(t,e),Tt.init(t,e)});function PZ(t){return Ug(X0,t)}var Y0=$("ZodCUID",(t,e)=>{jS.init(t,e),Tt.init(t,e)});function kZ(t){return Lg(Y0,t)}var Q0=$("ZodCUID2",(t,e)=>{FS.init(t,e),Tt.init(t,e)});function TZ(t){return jg(Q0,t)}var eE=$("ZodULID",(t,e)=>{qS.init(t,e),Tt.init(t,e)});function CZ(t){return Fg(eE,t)}var tE=$("ZodXID",(t,e)=>{VS.init(t,e),Tt.init(t,e)});function OZ(t){return qg(tE,t)}var rE=$("ZodKSUID",(t,e)=>{GS.init(t,e),Tt.init(t,e)});function DZ(t){return Vg(rE,t)}var nE=$("ZodIPv4",(t,e)=>{HS.init(t,e),Tt.init(t,e)});function NZ(t){return Gg(nE,t)}var iU=$("ZodMAC",(t,e)=>{KS.init(t,e),Tt.init(t,e)});function zZ(t){return i0(iU,t)}var oE=$("ZodIPv6",(t,e)=>{BS.init(t,e),Tt.init(t,e)});function MZ(t){return Hg(oE,t)}var iE=$("ZodCIDRv4",(t,e)=>{ZS.init(t,e),Tt.init(t,e)});function UZ(t){return Bg(iE,t)}var sE=$("ZodCIDRv6",(t,e)=>{JS.init(t,e),Tt.init(t,e)});function LZ(t){return Kg(sE,t)}var aE=$("ZodBase64",(t,e)=>{YS.init(t,e),Tt.init(t,e)});function jZ(t){return Zg(aE,t)}var cE=$("ZodBase64URL",(t,e)=>{ex.init(t,e),Tt.init(t,e)});function FZ(t){return Wg(cE,t)}var uE=$("ZodE164",(t,e)=>{tx.init(t,e),Tt.init(t,e)});function qZ(t){return Jg(uE,t)}var sU=$("ZodCreditCard",(t,e)=>{nx.init(t,e),Tt.init(t,e)});function VZ(t){return s0(sU,t)}var aU=$("ZodIBAN",(t,e)=>{ix.init(t,e),Tt.init(t,e)});function GZ(t){return a0(aU,t)}var lE=$("ZodJWT",(t,e)=>{ax.init(t,e),Tt.init(t,e)});function HZ(t){return Xg(lE,t)}var Jl=$("ZodCustomStringFormat",(t,e)=>{cx.init(t,e),Tt.init(t,e)});function BZ(t,e,r={}){return qc(Jl,t,e,r)}function KZ(t){return qc(Jl,"hostname",W1,t)}function ZZ(t){return qc(Jl,"hex",lz,t)}function WZ(t){return qc(Jl,"currency_code",Y1,t)}function JZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Eo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return qc(Jl,o,n,e)}var cf=$("ZodNumber",(t,e)=>{Sg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=kr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=kr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=kr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>kr(t).format??null},{gt(t,e){return this.check(ks(t,e))},gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},lt(t,e){return this.check(Ps(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},int(t){return this.check(H0(t))},safe(t){return this.check(H0(t))},positive(t){return this.check(ks(0,t))},nonnegative(t){return this.check(Ro(0,t))},negative(t){return this.check(Ps(0,t))},nonpositive(t){return this.check($o(0,t))},multipleOf(t,e){return this.check(jc(t,e))},step(t,e){return this.check(jc(t,e))},finite(){return this}}));function yt(t){return c0(cf,t)}var Xl=$("ZodNumberFormat",(t,e)=>{ux.init(t,e),cf.init(t,e)});function H0(t){return u0(Xl,t)}function XZ(t){return l0(Xl,t)}function YZ(t){return d0(Xl,t)}function QZ(t){return p0(Xl,t)}function eW(t){return f0(Xl,t)}var uf=$("ZodBoolean",(t,e)=>{Op.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n)});function hr(t){return m0(uf,t)}var lf=$("ZodBigInt",(t,e)=>{xg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pM(t,r,o,n)},D.derived({minValue:t=>kr(t).minimum??null,maxValue:t=>kr(t).maximum??null,format:t=>kr(t).format??null},{gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},gt(t,e){return this.check(ks(t,e))},lt(t,e){return this.check(Ps(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},positive(t){return this.check(ks(BigInt(0),t))},negative(t){return this.check(Ps(BigInt(0),t))},nonpositive(t){return this.check($o(BigInt(0),t))},nonnegative(t){return this.check(Ro(BigInt(0),t))},multipleOf(t,e){return this.check(jc(t,e))}}));function tW(t){return h0(lf,t)}var dE=$("ZodBigIntFormat",(t,e)=>{lx.init(t,e),lf.init(t,e)});function rW(t){return g0(dE,t)}function nW(t){return y0(dE,t)}var cU=$("ZodSymbol",(t,e)=>{dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fM(t,r,o,n)});function oW(t){return v0(cU,t)}var uU=$("ZodUndefined",(t,e)=>{px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n)});function iW(t){return w0(uU,t)}var lU=$("ZodNull",(t,e)=>{fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n)});function sy(t){return _0(lU,t)}var dU=$("ZodAny",(t,e)=>{mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n)});function sW(){return b0(dU)}var pU=$("ZodUnknown",(t,e)=>{hx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n)});function Ut(){return S0(pU)}var fU=$("ZodNever",(t,e)=>{gx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n)});function pE(t){return x0(fU,t)}var mU=$("ZodVoid",(t,e)=>{yx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n)});function aW(t){return E0(mU,t)}var ay=$("ZodDate",(t,e)=>{vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n),t.min=(r,o)=>t.check(Ro(r,o)),t.max=(r,o)=>t.check($o(r,o))},D.derived({minDate:t=>{let{minimum:e}=kr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=kr(t);return e?new Date(e):null}},{}));function cW(t){return $0(ay,t)}var hU=$("ZodArray",(t,e)=>{Wl(),wx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Va(t,e))},nonempty(t){return this.check(Va(1,t))},max(t,e){return this.check(Bl(t,e))},length(t,e){return this.check(Kl(t,e))},unwrap(){return this.element}});function qe(t,e){return oM(hU,t,e)}function uW(t){let e=t._zod.def.shape;return Yr(Object.keys(e))}var cy=$("ZodObject",(t,e)=>{Wl(),jz.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OM(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Yr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:pE()}))},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(Yl,this,t[0])},exactPartial(...t){return D.partial(mE,this,t[0],"exactPartial")},required(...t){return D.required(hE,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new cy(r)}function lW(t,e){return new cy({type:"object",shape:t,catchall:pE(),...D.normalizeParams(e)})}function Xr(t,e){return new cy({type:"object",shape:t,catchall:Ut(),...D.normalizeParams(e)})}var uy=$("ZodUnion",(t,e)=>{Dp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>j0(t,r,o,n),t.options=e.options});function It(t,e){return new uy({type:"union",options:t,...D.normalizeParams(e)})}var gU=$("ZodXor",(t,e)=>{uy.init(t,e),bx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>j0(t,r,o,n),t.options=e.options});function dW(t,e){return new gU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var yU=$("ZodDiscriminatedUnion",(t,e)=>{uy.init(t,e),Sx.init(t,e)});function ly(t,e,r){return new yU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var vU=$("ZodIntersection",(t,e)=>{xx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>DM(t,r,o,n)});function df(t,e){return new vU({type:"intersection",left:t,right:e})}var wU=$("ZodTuple",(t,e)=>{Wl(),Eg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>NM(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 Yl({type:"optional",innerType:e}))})}});function _U(t,e,r){let o=e instanceof be,n=o?r:e,i=o?e:null;return new wU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var of=$("ZodRecord",(t,e)=>{Wl(),Ex.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Ct(t,e,r){return!e||!e._zod?new of({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new of({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function pW(t,e,r){return new of({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function fW(t,e,r){return new of({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var bU=$("ZodMap",(t,e)=>{Wl(),$x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ts(...r)),t.nonempty=r=>t.check(Ts(1,r)),t.max=(...r)=>t.check(Fc(...r)),t.size=(...r)=>t.check(Hl(...r))});function mW(t,e,r){return new bU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var SU=$("ZodSet",(t,e)=>{Wl(),Rx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TM(t,r,o,n),t.min=(...r)=>t.check(Ts(...r)),t.nonempty=r=>t.check(Ts(1,r)),t.max=(...r)=>t.check(Fc(...r)),t.size=(...r)=>t.check(Hl(...r))});function hW(t,e){return new SU({type:"set",valueType:t,...D.normalizeParams(e)})}var sf=$("ZodEnum",(t,e)=>{Ix.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(o,n,i)=>bM(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 sf({...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 sf({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Yr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new sf({type:"enum",entries:r,...D.normalizeParams(e)})}function gW(t,e){return new sf({type:"enum",entries:t,...D.normalizeParams(e)})}var xU=$("ZodLiteral",(t,e)=>{Ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ae(t,e){return new xU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var EU=$("ZodFile",(t,e)=>{Px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$M(t,r,o,n),t.min=(r,o)=>t.check(Ts(r,o)),t.max=(r,o)=>t.check(Fc(r,o)),t.mime=(r,o)=>t.check(Wp(Array.isArray(r)?r:[r],o))});function yW(t){return C0(EU,t)}var $U=$("ZodTransform",(t,e)=>{Wl(),kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Uc(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 fE(t){return new $U({type:"transform",transform:t})}var Yl=$("ZodOptional",(t,e)=>{$g.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>F0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function kt(t){return new Yl({type:"optional",innerType:t})}var mE=$("ZodExactOptional",(t,e)=>{Tx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>F0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function RU(t){return new mE({type:"optional",innerType:t})}var IU=$("ZodNullable",(t,e)=>{Cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>MM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function oy(t){return new IU({type:"nullable",innerType:t})}function vW(t){return kt(oy(t))}var AU=$("ZodDefault",(t,e)=>{Ox.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>jM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function PU(t,e){return new AU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var kU=$("ZodPrefault",(t,e)=>{Dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>FM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function TU(t,e){return new kU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var hE=$("ZodNonOptional",(t,e)=>{Nx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>UM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function CU(t,e){return new hE({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var OU=$("ZodSuccess",(t,e)=>{zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wW(t){return new OU({type:"success",innerType:t})}var DU=$("ZodCatch",(t,e)=>{Mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function NU(t,e){return new DU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var zU=$("ZodNaN",(t,e)=>{Ux.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n)});function _W(t){return R0(zU,t)}var dy=$("ZodPipe",(t,e)=>{Rg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>VM(t,r,o,n),t.in=e.in,t.out=e.out});function B0(t,e){return new dy({type:"pipe",in:t,out:e})}var py=$("ZodCodec",(t,e)=>{dy.init(t,e),Np.init(t,e)});function bW(t,e,r){return new py({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function SW(t){let e=t._zod.def;return new py({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var MU=$("ZodPreprocess",(t,e)=>{dy.init(t,e),qz.init(t,e)}),UU=$("ZodReadonly",(t,e)=>{Lx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function LU(t){return new UU({type:"readonly",innerType:t})}var jU=$("ZodTemplateLiteral",(t,e)=>{jx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n)});function xW(t,e){return new jU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var FU=$("ZodLazy",(t,e)=>{zp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>BM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function qU(t){return new FU({type:"lazy",getter:t})}var VU=$("ZodPromise",(t,e)=>{qx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function EW(t){return new VU({type:"promise",innerType:t})}var GU=$("ZodFunction",(t,e)=>{Fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n)});function $W(t){return new GU({type:"function",input:Array.isArray(t?.input)?_U(t?.input):t?.input??qe(Ut()),output:t?.output??Ut()})}var fy=$("ZodCustom",(t,e)=>{Vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n)});function RW(t){let e=new Pt({check:"custom"});return e._zod.check=t,e}function gE(t,e){return O0(fy,t??(()=>!0),e)}function HU(t,e={}){return D0(fy,t,e)}function BU(t,e){return N0(t,e)}var IW=z0,AW=M0,KU=$("ZodInstanceOf",(t,e)=>{fy.init(t,e)},{properties(t,e){return this.check(Zp(t,e))}});function PW(t,e={}){let r=new KU({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 kW=(...t)=>U0({Codec:py,Boolean:uf,String:af},...t);function TW(t){let e=qU(()=>It([O(t),yt(),hr(),sy(),qe(e),Ct(O(),e)]));return e}function my(t,e){return new MU({type:"pipe",in:fE(t),out:e})}var UCe={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 LCe(t){cr({customError:t})}function jCe(){return cr().customError}var ZU;ZU||(ZU={});var Ql={};Ht(Ql,{ZodISODate:()=>Kc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Wc,ZodISOTime:()=>Zc,date:()=>qCe,datetime:()=>FCe,duration:()=>GCe,time:()=>VCe});function FCe(t){return Yg(Bc,t)}function qCe(t){return Qg(Kc,t)}function VCe(t){return ey(Zc,t)}function GCe(t){return ty(Wc,t)}var J={...pf,...V0,iso:Ql},HCe=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 BCe(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 CW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function KCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ZCe(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:KCe(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 WCe(t,e){return J.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 WU(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=WU(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=WU(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 JCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),XCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function hy(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(hy):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>JCe.has(e)?hy(r):!XCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(hy))}function OW(t){return t===1?"element":"elements"}function YCe(t,e){return J.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=WU(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 ${OW(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 ${OW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function DW(t,e){if(t!==!1)return t===void 0||t===!0?J.any():Gn(t,e)}var QCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function NW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return J.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 J.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=ZCe(n,e),s=Gn(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 J.null();if(n.length===0)return J.never();if(n.length===1)return J.literal(n[0]);if(n.every(s=>typeof s=="string"))return J.enum(n);let i=n.map(s=>J.literal(s));return i.length<2?i[0]:J.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return J.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return NW(s,e)});return n.length===0?J.never():n.length===1?n[0]:J.union(n)}if(!r)return J.any();let o;switch(r){case"string":{let n=J.string();if(t.format){let i=t.format;i==="email"?n=n.check(J.email()):i==="uri"||i==="uri-reference"?n=n.check(J.url()):i==="uuid"||i==="guid"?n=n.check(J.uuid()):i==="date-time"?n=n.check(J.iso.datetime({offset:!0})):i==="date"?n=n.check(J.iso.date()):i==="time"?n=n.check(J.regex(QCe)):i==="duration"?n=n.check(J.iso.duration()):i==="hostname"?n=n.check(J.hostname()):i==="ipv4"?n=n.check(J.ipv4()):i==="ipv6"?n=n.check(J.ipv6()):i==="mac"?n=n.check(J.mac()):i==="cidr"?n=n.check(J.cidrv4()):i==="cidr-v6"?n=n.check(J.cidrv6()):i==="base64"?n=n.check(J.base64()):i==="base64url"?n=n.check(J.base64url()):i==="e164"?n=n.check(J.e164()):i==="credit_card"?n=n.check(J.creditCard()):i==="iban"?n=n.check(J.iban()):i==="jwt"?n=n.check(J.jwt()):i==="emoji"?n=n.check(J.emoji()):i==="nanoid"?n=n.check(J.nanoid()):i==="cuid"?n=n.check(J.cuid()):i==="cuid2"?n=n.check(J.cuid2()):i==="ulid"?n=n.check(J.ulid()):i==="xid"?n=n.check(J.xid()):i==="ksuid"&&(n=n.check(J.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"?J.number().int():J.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=J.boolean();break}case"null":{o=J.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Gn(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=Gn(f,e);Wr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let y of f){let w=Gn(d[y],e),b=J.string().regex(new RegExp(y));p.push(J.looseRecord(b,w))}let h=[];if(Object.keys(n).length>0&&h.push(J.object(n).passthrough()),h.push(...p),h.length===0)o=J.object({}).passthrough();else if(h.length===1)o=h[0];else{let y=J.intersection(h[0],h[1]);for(let w=2;w<h.length;w++)y=J.intersection(y,h[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=f.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Xo(S.value))return;let x=[];for(let R of Object.keys(S.value))y.includes(R)||w.some(T=>T.test(R))||x.push(R);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=J.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=Gn(f,e)}o=WCe(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=>Gn(d,e)),c=CW(a,s),u=Array.isArray(i)?void 0:DW(i,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Gn(d,e)),c=CW(a,s),u=DW(t.additionalItems,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(i!==void 0){let s=Gn(i,e),a=J.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=J.array(J.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=YCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Gn(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 Gn(t,e){if(typeof t=="boolean")return t?J.any():J.never();let r=NW(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=>Gn(u,e)),c=J.union(a);r=o?J.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Gn(u,e)),c=J.xor(a);r=o?J.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:J.any();else{let a=o?r:Gn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=J.intersection(a,Gn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=J.nullable(r)),t.readOnly===!0&&(r=J.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&&!hy(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&&!hy(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))HCe.has(a)||Wr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function zW(t,e){if(typeof t=="boolean")return t?J.any():J.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=BCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Jr};return Gn(r,i)}var MW=Symbol("z.visit/resolving");function gy(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===MW)return new zp({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,MW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let h of l){let y=n(u[h]);y!==u[h]&&(d=!0),f[h]=y}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let h=n(p);h!==p&&(l=!0),d.push(h)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function UW(t){return gy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function eOe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Jo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function LW(t){return eOe(t.out,t.checks)}function tOe(t){return t.in._zod.traits.has("$ZodTransform")?LW(t):t.in}function jW(t){return gy(t,{pipe:e=>tOe(e._zod.def),default:(e,r)=>r?kt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function FW(t){return gy(t,{pipe:e=>LW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var JU={};Ht(JU,{bigint:()=>iOe,boolean:()=>oOe,date:()=>sOe,number:()=>nOe,string:()=>rOe});function rOe(t){return Yz(af,t)}function nOe(t){return eM(cf,t)}function oOe(t){return tM(uf,t)}function iOe(t){return rM(lf,t)}function sOe(t){return nM(ay,t)}var yy={name:"@tomato414941/foundation",version:"13.1.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&m.config({jitless:!0});function cOe(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 vy=m.string().trim().max(8192).refine(t=>cOe(t)!==null,"Use an OpenSSH public key from a .pub file."),wy=m.object({authorizedKeys:m.array(vy).max(32)}).strict(),Jgt=wy.extend({revision:m.number().int().positive().optional()}),XU=wy.extend({host:m.string().min(1).max(253).nullable(),port:m.number().int().min(1).max(65535),username:m.literal("root"),workingDirectory:m.literal("/workspace"),hostKey:vy.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),Xgt=XU.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])}),Ygt=m.object({hostKey:vy,appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),uOe=wy.extend({port:m.number().int().min(1).max(65535),revision:m.number().int().positive()}).strict(),yE=m.object({configuration:uOe.nullable()}).strict();var ff=new TextEncoder,mf=new TextDecoder,qW=new TextDecoder("utf-8",{fatal:!0}),vE=2**32;function Hn(...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 YU(t,e,r){if(e<0||e>=vE)throw new RangeError(`value must be >= 0 and <= ${vE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function QU(t){let e=Math.floor(t/vE),r=t%vE,o=new Uint8Array(8);return YU(o,e,0),YU(o,r,4),o}function wE(t){let e=new Uint8Array(4);return YU(e,t),e}var lOe=/[^\x00-\x7f]/;function Qr(t){if(typeof t=="string"&&t.length>=128){if(lOe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return ff.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 VW(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 GW(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 _E(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ga=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 ed=class extends Ga{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ot=class extends Ga{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Jc=class extends Ga{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends Ga{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Xt=class extends Ga{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var _y=class extends Ga{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var bE=class extends Ga{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var dOe="The input to be decoded is not correctly encoded.";function td(t){try{return GW(typeof t=="string"?t:mf.decode(t),!0)}catch(e){throw new TypeError(dOe,{cause:e})}}function nr(t){return VW(typeof t=="string"?ff.encode(t):t,!0)}function Io(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function vr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Xc(...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 Qo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function lo(t,e,r){try{return td(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function SE(t,e,r){try{return Qr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function hf(t,e,r){let o;try{o=JSON.parse(qW.decode(td(t)))}catch{throw new e(r)}if(!vr(o))throw new e(r);return o}var xE={__proto__:null,b64:!0},EE={__proto__:null};function by(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 Yc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ot(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function RE(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 rd(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!vr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var pOe=t=>t[Symbol.toStringTag],fOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function zi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(vr(e)){if(s=iL(e),typeof s.kty!="string")throw HW(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(fOe(t,s,r),s.kty==="oct")return td(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!rL(e))throw HW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${pOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Qc(e))return e;if(a=e,a.type==="secret")return a.export()}eL||=new WeakMap;let c=e,u=eL.get(c);if(u?.[o])return u[o];if(u||eL.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=mOe[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await yf(t,s)}var eL,mOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function AE(t){if(!Qc(t))throw new Error("CryptoKey instance expected")}var Qc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},tL=t=>t?.[Symbol.toStringTag]==="KeyObject",rL=t=>Qc(t)||tL(t);function BW(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 Ha=(t,...e)=>BW("Key must be ",t,...e);function HW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(BW(`Key for the ${t} algorithm must be `,e,...o))}var IE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function nL(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function gf(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 oL(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw IE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw IE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw IE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw IE(e.length,"algorithm.length");nL(t,r)}function PE(t){return{__proto__:null,...t}}function iL(t){let e=PE(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 kE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function yf(t,e,r){if(!t.kty.includes(e.kty))throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Mi(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),oL(t,e,r),t}var nd=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function TE(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 hOe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function KW(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function ZW(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Ha(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 WW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function gOe(t,e,r,o,n){let[i,s,a]=await ZW(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Hn(n,o,c,QU(n.length*8)),l=await WW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function yOe(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 vOe(t,e,r,o,n,i){let[s,a,c]=await ZW(t,e,"decrypt"),u=Hn(i,o,r,QU(i.length*8)),l=await WW(a,u,c);try{if(await yOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Jc}async function CE(t,e,r,o,n){if(!Qc(r)&&!(r instanceof Uint8Array))throw new TypeError(Ha(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?KW(t,o):o=hOe(t),r instanceof Uint8Array&&TE(r,t.cekBits),t.cbc)return gOe(t,e,r,o,n);let i=await Mi(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function OE(t,e,r,o,n,i){if(!Qc(e)&&!(e instanceof Uint8Array))throw new TypeError(Ha(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(KW(t,o),e instanceof Uint8Array&&TE(e,t.cekBits),t.cbc)return vOe(t,e,r,o,n,i);let s=await Mi(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Hn(r,n)))}catch{throw new Jc}}function Sy(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var wOe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],_Oe=[[],["deriveBits"]],zE=[[],[]];function DE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:wOe,ops:["wrapKey","unwrapKey"]}}function NE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:_Oe,ops:[void 0,"deriveBits"]}}function vf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:zE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function sL(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:zE,ops:["deriveBits","deriveBits"]}}var Ba=Sy({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:zE,ops:["encrypt","decrypt"]},"RSA-OAEP":DE(1),"RSA-OAEP-256":DE(256),"RSA-OAEP-384":DE(384),"RSA-OAEP-512":DE(512),"ECDH-ES":NE("direct-key-agreement"),"ECDH-ES+A128KW":NE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":NE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":NE("key-agreement-with-key-wrapping"),A128KW:vf(128),A192KW:vf(192),A256KW:vf(256),A128GCMKW:vf(128,!0),A192GCMKW:vf(192,!0),A256GCMKW:vf(256,!0),"PBES2-HS256+A128KW":sL(),"PBES2-HS384+A192KW":sL(),"PBES2-HS512+A256KW":sL()}),bOe=["encrypt","decrypt"];function wf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:zE,ops:bOe,cekBits:t,ivBits:e?128:96,cbc:e}}var SOe=Sy({A128GCM:wf(128),A192GCM:wf(192),A256GCM:wf(256),"A128CBC-HS256":wf(256,!0),"A192CBC-HS384":wf(384,!0),"A256CBC-HS512":wf(512,!0)});function JW(t,e){throw new Ot(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Ui(t){return(typeof t=="string"?Ba[t]:void 0)??JW("alg","Algorithm")}function Li(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function od(t){return(typeof t=="string"?SOe[t]:void 0)??JW("enc","Encryption Algorithm")}function XW(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");nL(t,e)}async function xOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function EOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function QW(t,e,r){oL(e,Ui(t).subtle,r),gf(t,e)}async function e5(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=Hn(Qr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Mi(o,Ui(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function aL(t){return Hn(wE(t.length),t)}async function $Oe(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 _E("sha256",Hn(wE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function t5(t,e,r,o,n=new Uint8Array,i=new Uint8Array){XW(t),XW(e,"deriveBits");let s=Hn(aL(Qr(r)),aL(n),aL(i),wE(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 $Oe(a,o,s)}function r5(t){AE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ot("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ME(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 lo(r,e,H)}}function n5(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 ROe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function YW(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function IOe(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 o5(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return YW(o),r;let c=a==="direct-key-agreement";switch(c?YW(o):ROe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!vr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(h=>Object.hasOwn(u,h)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');r5(r);let l=await yf(t,u),d=ME(n,"apu"),f=ME(n,"apv");n5(d,f);let p=await t5(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return AE(r),QW(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');IOe(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=lo(n.p2s,"p2s",H);r=await e5(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=lo(n.iv,"iv",H),l=lo(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 OE(od(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return EOe(s.slice(-6),r,o)}async function UE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Li(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await zi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??nd(e):void 0;l&&TE(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{r5(u);let{apu:p,apv:h}=i;p!==void 0&&Io(p,'"apu"'),h!==void 0&&Io(h,'"apv"');let y=p??ME(o,"apu"),w=h??ME(o,"apv");n5(y,w);let b;i.epk!==void 0?b=await zi(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:R,y:T,crv:M,kty:Z}=await S.exportKey("jwk",x),te=a==="direct-key-agreement",Ie=await t5(u,b,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),Te={x:R,crv:M,kty:Z};if(Z==="EC"&&(Te.y=T),f={epk:Te},p!==void 0&&(f.apu=nr(p)),h!==void 0&&(f.apv=nr(h)),te)return[Ie,void 0,f];u=Ie;break}case"RSA-OAEP":{AE(u),QW(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:h=crypto.getRandomValues(new Uint8Array(16))}=i;u=await e5(h,s,p,u),f={p2c:p,p2s:nr(h)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let h=await CE(od(s.slice(0,-2)),l,u,p,new Uint8Array);d=h.ciphertext,f={iv:nr(h.iv),tag:nr(h.tag)}}}if(d??=await xOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,f]}function LE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ot('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function i5(t){if(typeof globalThis[t]>"u")throw new Ot(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function s5(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 Hn(...n)}async function a5(t){return i5("CompressionStream"),s5(new CompressionStream("deflate-raw"),t)}async function c5(t,e){return i5("DecompressionStream"),s5(new DecompressionStream("deflate-raw"),t,e)}function u5(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&&!vr(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 l5(t){let e,r;try{let{header:o}=t;if(vr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function d5(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&&!vr(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 cL(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=hf(e,H,"JWE Protected Header is invalid")),[s,lo(r,"ciphertext",H),o!==void 0?lo(o,"iv",H):void 0,n!==void 0?lo(n,"tag",H):void 0,SE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function jE(t){return[t&&by("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&by("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function uL(t,e,r,o=cL(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Xc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,h,y,w,b]=e,{encrypted_key:S}=t;Yc(H,EE,y,n,f),LE(f,n);let{alg:x,enc:R}=f;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Ba[x];if(S===""&&(!T||!Li(T)))throw new H("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof R!="string"||!R))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new ed('"alg" (Algorithm) Header Parameter value not allowed');let Z;if(M){if(R!==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(h&&!h.has(R))throw new ed('"enc" (Encryption Algorithm) Header Parameter value not allowed');Z=od(R)}let te;if(S!==void 0)try{te=lo(S,"encrypted_key",H)}catch(Fe){if(!T||!Li(T))throw Fe;te=new Uint8Array}let Ie=!1;typeof r=="function"&&(r=await r(n,t),Ie=!0);let Te=T??Ui(x);Li(Te)&&te===void 0&&(te=new Uint8Array);let bt=await zi(Te.mode==="direct-encryption"?Z:Te,r,"decrypt"),me;if(Te.mode==="integrated-encryption")me=await Te.decrypt(bt,te,i,c,n,f);else{let Fe=Z,se;try{se=await o5(Te,Fe,bt,te,f,w),Li(Te)&&se instanceof Uint8Array&&se.byteLength<<3!==Fe.cekBits&&(se=nd(Fe))}catch(tr){if(tr instanceof TypeError||tr instanceof H||tr instanceof Ot)throw tr;se=nd(Fe)}me=await OE(Fe,se,i,s,a,c)}if(f.zip==="DEF"){let Fe=b??25e4;if(Fe===0)throw new Ot('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Fe!==1/0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");me=await c5(me,Fe).catch(se=>{throw se instanceof H?se:new H("Failed to decompress plaintext",{cause:se})})}return{plaintext:me,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:lo(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ie&&{key:bt}}}async function p5(t,e,r){if(t instanceof Uint8Array&&(t=mf.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 uL({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function xy(t,e,r){return p5(t,jE(r),e)}async function lL(t,e,r){if(!vr(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(vr))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=jE(r),s=u5(t),a=cL(s)}catch{throw new Jc}let c=n.map(u=>l5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Ba[l]:void 0;if(d&&!Li(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 d5(l),await uL(l,i,e,a)}catch{}throw new Jc}function FE(t,e,r){if(!Xc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function dL(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&&Io(s,"JWE Additional Authenticated Data"),a!==void 0&&Io(a,"JWE Content Encryption Key"),c!==void 0&&Io(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=rd(H,o)[0],t[1]=o),n!==void 0&&(n=rd(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=rd(H,i)[0],t[3]=i),u!==void 0&&!vr(u))throw new TypeError("JWE Key Management Parameters must be an object");FE(o,n,i);let d={...o,...n,...i};$E(H,o),Yc(H,EE,l,o,d),LE(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=Ba[f];if(h?.mode==="integrated-encryption"){if(p!==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 ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,h]}if(typeof p!="string"||!p)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,od(p),h]}async function pL(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,h]=t,y=a,w=c,b=i??Ui(o.alg),S,x,R;b.mode==="integrated-encryption"?R=await zi(b,r,"encrypt"):[R,S,x]=await UE(b,n,r,o,d,p),x&&(h?w=w?{...w,...x}:x:y=y?{...y,...x}:x,FE(y,w,u));let T=y?nr(JSON.stringify(y)):"",M=l?.byteLength?nr(l):void 0,Z=Qr(M?`${T}.${M}`:T),te=s;o.zip==="DEF"&&(te=await a5(te).catch(Fe=>{throw new H("Failed to compress plaintext",{cause:Fe})}));let Ie,Te,bt;b.mode==="integrated-encryption"?[S,Ie]=await b.encrypt(R,te,Z,y,o,p):{ciphertext:Ie,tag:Te,iv:bt}=await CE(n,te,R,f,Z);let me={ciphertext:nr(Ie)};return bt&&(me.iv=nr(bt)),Te&&(me.tag=nr(Te)),S?.byteLength&&(me.encrypted_key=nr(S)),M&&(me.aad=M),y&&(me.protected=T),u&&(me.unprotected=u),w&&(me.header=w),me}async function f5(t,e,r){return pL(t,dL(t,r),e)}function m5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var fL=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Qo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Qo(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}},Ey=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new fL(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Qo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Qo(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");Io(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let h of this.#t){let[y,w,b,S]=h.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],R=dL(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,R,b]);let[{alg:T,enc:M},,Z]=R;if(e&&Z&&!Li(Z))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[,h]of i)h[2]??=Ui(h[0].alg);let[s,a,c]=i[0],u=e?nd(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await pL(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let h=1;h<i.length;h++){let[y,[w,b,S],x]=i[h],R=y[2],[,T,M]=await UE(S,b,x,w,u,y[7]),Z={encrypted_key:nr(T)};if(R||M){let te={...R,...M};M&&FE(y[1],te,y[3]),Z.header=te}p.recipients.push(Z)}return p}};var $y=[["verify"],["sign"]];function mL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:$y}}function _f(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:$y,minRsaBits:2048}}function hL(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:$y}}function h5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:$y}}function gL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:$y}}var yL=Sy({HS256:mL(256),HS384:mL(384),HS512:mL(512),RS256:_f(256),RS384:_f(384),RS512:_f(512),PS256:_f(256,32),PS384:_f(384,48),PS512:_f(512,64),ES256:hL("P-256",256),ES384:hL("P-384",384),ES512:hL("P-521",512),EdDSA:h5(),Ed25519:h5(),"ML-DSA-44":gL(44),"ML-DSA-65":gL(65),"ML-DSA-87":gL(87)});function qE(t){let e=typeof t=="string"?yL[t]:void 0;if(!e)throw new Ot(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function g5(t){return[t&&by("algorithms",t.algorithms),t?.crit]}function AOe(t){return t===void 0?{}:hf(t,Xt,"JWS Protected Header is invalid")}function POe(t){try{return Qr(t)}catch{throw new Xt("JWS Compact Serialization payload must use only ASCII characters")}}async function kOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??AOe(i);if(!Xc(c,s))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=RE(c,Yc(Xt,xE,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 ed('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Xt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let h=qE(d),y=Hn(i!==void 0?Qr(i):new Uint8Array,Qr("."),typeof f=="string"?e[2]??=SE(f,"payload",Xt):f),w=lo(t.signature,"signature",Xt),b=await zi(h,r,"verify"),S=await Mi(b,h.subtle,"verify");h.minRsaBits&&gf(h.alg,S);let x=!1;try{x=await crypto.subtle.verify(h.signing,S,w,y)}catch{}if(!x)throw new bE;let R={payload:typeof f=="string"?lo(f,"payload",Xt):f};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),p?[{...R,key:b},l]:[R,l]}async function y5(t,e,r){if(t instanceof Uint8Array&&(t=mf.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 kOe({payload:n,protected:o,signature:i},e,r,POe)}async function vL(t,e,r){let[o]=await y5(t,g5(r),e);return o}var bf=class{#e;constructor(e){Io(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Qo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Qo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Qo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Qo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return m5(await f5([...this.#e],e,r))}};async function TOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=rd(Xt,n);n=b[0],a=nr(b[1])}if(i!==void 0&&(i=rd(Xt,i)[0]),!n&&!i)throw new Xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Xc(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=RE(n,Yc(Xt,xE,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=qE(l),f="",p=o,h;if(u){let b=t[4];b?(f=b[0]??=nr(o),p=b[1]??=Qr(f)):(f=nr(o),h=ff.encode(`${a}.${f}`))}h??=Hn(Qr(a),Qr("."),p);let y=await Mi(await zi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&gf(d.alg,y);let w={signature:nr(new Uint8Array(await crypto.subtle.sign(d.signing,y,h))),payload:f};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function v5(t,e,r,o,n){let[i]=await TOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Ry=class{#e;#t;constructor(e){Io(e,"payload"),this.#e=e}setProtectedHeader(e){return Qo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return v5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var wL='"alg" (Algorithm)';function _L(t='JWK "alg" (Algorithm) Parameter'){throw new Ot(`Invalid or unsupported ${t} value`)}function Iy(t,e){return(typeof t=="string"?yL[t]??Ba[t]:void 0)??_L(e)}async function eu(t){if(tL(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(!Qc(t))throw new TypeError(Ha(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 Ka=(t,e)=>{if(typeof t!="string"||!t)throw new _y(`${e} missing or invalid`)};async function bL(t,e){let r;if(vr(t)){if(r=PE(t),typeof r.kty!="string")throw new TypeError(Ha(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(rL(t))r=PE(await eu(t));else throw new TypeError(Ha(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":Ka(r.alg,'"alg" (Algorithm) Parameter'),Ka(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Ka(r.crv,'"crv" (Curve) Parameter'),Ka(r.x,'"x" (X Coordinate) Parameter'),Ka(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Ka(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Ka(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Ka(r.e,'"e" (Exponent) Parameter'),Ka(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 _y('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ot('"kty" (Key Type) Parameter missing or unsupported')}let n=Qr(JSON.stringify(o));return nr(await _E(e,n))}async function ei(t,e,r){if(!vr(t))throw new TypeError("JWK must be an object");let o=iL(t),n=kE(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 td(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 yf(Iy(e),o,n)}case"RSA":case"EC":case"OKP":return yf(Iy(e),o,n);default:throw new Ot('Unsupported "kty" (Key Type) Parameter value')}}function SL(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 hf(e,TypeError,r)}function COe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ot("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Ay(t,e){let r=kE(e?.extractable),o=Iy(t,wL);o.secret&&_L(wL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ot("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ot(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:COe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var S5=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),x5=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),w5=m.string().min(1).max(128),_5=m.string().min(1).max(16384),OOe=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:w5,secretAccessKey:_5}).strict(),m.object({kind:m.literal("session"),accessKeyId:w5,secretAccessKey:_5,sessionToken:m.string().min(1).max(16384),expiresAt:m.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),m.object({kind:m.literal("environment")}).strict()]),DOe=m.object({arn:x5,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Za=m.object({authentication:OOe,region:S5,role:DOe.optional()}).strict(),VE=m.object({accountId:m.string().regex(/^\d{12}$/),principalId:m.string().min(1).max(256),arn:m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),GE=Za.extend({sourceIdentity:VE.optional(),identity:VE.optional()}).strict();function Sf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function b5(t){return{...t,arn:Sf(t.arn)}}function E5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:b5(t.sourceIdentity)}:{},...t.identity?{identity:b5(t.identity)}:{}}}var HE=m.object({authentication:m.enum(["access_key","session","environment"]),region:S5,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:x5.optional(),expiresAt:m.number().int().positive().optional()}).strict();function $5(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var R5=m.object({method:m.enum(["GET","POST","PUT","DELETE","PATCH"]),path:m.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),Py=m.object({account:m.string().min(1),identities:m.array(m.string()),user:m.string().nullable(),description:m.string().nullable(),roles:m.array(m.string()).nullable(),credentialId:m.number().int().positive(),rules:m.array(R5),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function I5(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return R5.parse({method:r[1],path:r[2]})})}typeof window<"u"&&m.config({jitless:!0});var E=m.uuid(),fe=m.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Ae=m.iso.datetime(),wr=m.json(),Lt=m.record(m.string(),wr),A5=m.enum(["ja","en"]),P5=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var k5=m.enum(["variable","connection","service","method","app","object","environment","function"]),bn=m.object({kty:m.literal("EC"),crv:m.literal("P-256"),x:m.string().min(40).max(50),y:m.string().min(40).max(50)}).strict(),NOe=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:E}).strict(),WE=m.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 NOe.safeParse(SL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ao=m.object({protected:m.string().max(2048),iv:m.string().max(64),ciphertext:m.string().max(2e6),tag:m.string().max(64),aad:m.string().max(2048).optional(),recipients:m.array(m.object({encrypted_key:m.string().max(2048),header:m.object({kid:E,epk:bn.optional(),alg:m.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Dwt=m.object({id:E,name:fe,publicKey:bn}),tu=m.object({id:E,name:fe,owner:m.object({id:E,name:fe}).nullable(),createdAt:Ae,permissions:m.array(P5),createKinds:m.array(k5),publicKey:bn.nullable()}),T5=m.object({id:E,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:Ae,lastUsedAt:Ae.nullable(),expiresAt:Ae.nullable(),canOpen:m.boolean()}),C5=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),zOe=m.object({subjectId:E,relation:C5,objectId:E}).strict(),Nwt=zOe.extend({objectType:m.enum(["principal",...k5.options]),subjectName:fe,objectName:fe,createdAt:Ae}),zwt=m.object({error:m.object({code:m.string(),message:m.string(),details:wr.optional()})}),Mwt=m.object({ok:m.literal(!0)}),MOe=m.object({value:m.string().min(1).max(200),label:m.string().min(1).max(200),values:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).default({})}).strict(),JE=m.object({name:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:m.string(),secret:m.boolean().optional(),inputType:m.enum(["text","password"]).optional(),required:m.boolean().optional(),placeholder:m.string().optional(),note:m.string().optional(),pattern:m.string().optional(),choices:m.array(MOe).min(1).max(100).optional(),defaultValue:m.string().max(1e3).optional(),when:m.object({field:m.string(),values:m.array(m.string()).min(1)}).strict().optional(),visibility:m.enum(["application","connection"]).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."})}),XE=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),xL=m.object({values:m.array(m.object({id:m.string(),name:m.string(),description:m.string().optional()})).optional(),default:m.array(m.string()).default([]),required:m.array(m.string()).optional(),separator:m.string().default(" "),docs:m.url().optional()}),id=m.string().min(1).max(4096),KE=m.union([m.string(),m.array(m.string()).min(1)]),UOe=m.object({application:m.enum(["required","implicit"]).default("required"),grantType:m.enum(["authorization_code","client_credentials"]).optional(),issuer:m.url().optional(),registrationUrl:m.url().optional(),authorizeUrl:id.optional(),tokenUrl:id,identity:m.object({url:id.optional(),from:m.enum(["token","app"]).optional(),method:m.enum(["GET","POST"]).default("GET"),id:KE.default("/id"),name:KE.default("/name"),headers:m.record(m.string(),m.string()).default({})}).optional(),revoke:m.object({url:id,style:m.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:m.enum(["body","basic","none"]).optional()}).optional(),clientAuth:m.enum(["body","basic","none"]).default("body"),pkce:m.boolean().default(!0),tokenFormat:m.enum(["form","json"]).default("form"),okPointer:m.string().optional(),authorizeParams:m.record(m.string(),m.string()).default({}),tokenParams:m.record(m.string(),m.string()).default({}),defaults:m.record(m.string(),m.string()).default({}),scopes:xL.default({default:[],separator:" "}),fields:m.array(JE).default([]),outputs:XE.default({ACCESS_TOKEN:"/accessToken"}),adapter:m.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:m.array(m.string()).default([]),hint:m.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),LOe=m.object({fields:m.array(JE).min(1),outputs:XE,resolver:m.literal("vultr-role").optional(),bindFields:m.boolean().optional(),constants:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).optional(),identity:m.object({url:id,headers:m.record(m.string(),m.string()),id:KE,name:KE}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),EL=m.enum(["oauth","token","aws","ovh","approval"]),jOe=m.object({hint:m.string().optional()}).strict(),FOe=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:id,fields:m.array(JE).min(1),scopes:xL.default({default:[],separator:`
|
|
129
|
-
`}),outputs:XE,hint:m.string().optional()}).strict(),Cy={name:fe,docs:m.url().optional(),console:id.optional()},YE=m.object({...Cy,kind:m.literal("oauth"),config:UOe}).strict(),QE=m.object({...Cy,kind:m.literal("token"),config:LOe}).strict(),e$=m.object({...Cy,kind:m.literal("aws"),config:jOe}).strict(),t$=m.object({...Cy,kind:m.literal("ovh"),config:FOe}).strict(),r$=m.object({...Cy,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(JE).default([]),scopes:xL.default({default:[],separator:" "}),outputs:XE,hint:m.string().optional()}).strict()}).strict(),ru=m.discriminatedUnion("kind",[YE,QE,e$,t$,r$]),ky={id:m.string().min(1),builtin:m.boolean(),availability:m.enum(["ready","app-required","unavailable"]),defaultName:fe,registration:m.object({kind:m.enum(["input","authorization"]),device:m.enum(["browser","cli"]),browserExchange:m.enum(["available","unavailable","unknown"]),tokenAlternatives:m.array(m.string())}).strict()},Oy=m.discriminatedUnion("kind",[YE.extend(ky),QE.extend(ky),e$.extend(ky),t$.extend(ky),r$.extend(ky)]),Ty=m.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),$L=m.object({name:fe,logo:m.string().regex(/^[a-z0-9-]+$/).optional(),api:m.url().optional(),docs:m.url().optional(),console:m.url().optional(),targets:m.array(m.object({id:Ty,name:fe,api:m.url().optional(),methods:m.array(Ty).min(1)}).strict()).max(32).optional()}).strict(),qOe=$L.extend({methods:m.record(Ty,m.string().min(1))}).strict(),O5=$L.extend({methods:m.record(Ty,m.union([m.string().min(1),ru]))}).strict(),Uwt=$L.extend({id:m.string(),builtin:m.boolean(),methods:m.record(Ty,Oy)}),D5=m.object({id:E,output:m.string().min(1).max(100).optional()}).strict(),N5=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),RL=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:D5,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),VOe=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),D5])).min(1).max(32)}).strict(),Wa=m.object({url:m.string().max(4096),method:m.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:m.record(m.string(),m.string().max(8192)).default({}),body:m.string().max(1e6).optional(),json:wr.optional(),form:m.record(m.string(),m.string()).optional(),bindings:m.array(VOe).max(32).default([])}).strict(),Ja=m.object({command:m.array(m.string().max(8192)).min(1).max(100),stdin:m.string().max(1e6).optional(),timeoutSeconds:m.number().int().min(1).max(3600).default(60),inputs:m.array(RL).max(32).default([])}).strict(),z5=m.discriminatedUnion("kind",[Ja.omit({stdin:!0}).extend({kind:m.literal("command")}).strict(),m.object({kind:m.literal("http"),request:Wa}).strict()]),ti=m.object({description:m.string().max(2e3).default(""),environmentId:E,program:z5,parameters:m.array(m.object({name:m.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:m.string().max(100),type:m.enum(["string","number","boolean","json"]).default("string"),required:m.boolean().default(!0),default:wr.optional()}).strict()).max(32).default([]),result:m.enum(["text","json"]).default("json")}).strict(),nu={id:E,ownerId:E,name:fe,createdAt:Ae,updatedAt:Ae,version:m.number().int().positive(),permissions:m.array(P5)},GOe=m.enum(["starting","running","stopping","stopped","failed"]),HOe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),BOe=m.object({idleSeconds:m.number().int().min(60).max(86400).default(3600),maxSeconds:m.number().int().min(60).max(86400).default(3600)}).strict(),M5=m.object({image:m.string().min(1).max(300).optional(),size:m.enum(["small","medium","large"]).default("small"),lifetime:BOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:wy.optional()}).strict(),IL={recipients:m.array(E).default([]),executors:m.array(E).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},KOe=m.object({...nu,kind:m.literal("variable"),data:m.object({...IL,bytes:m.number().int().nonnegative()})}),ZOe=m.object({...nu,kind:m.literal("connection"),data:m.object({...IL,methodId:m.string(),fields:m.record(m.string(),m.string()).default({}),settings:m.array(m.object({name:m.string(),label:m.string(),value:m.string()})).default([]),methodName:m.string(),methodKind:EL,services:m.array(m.object({id:m.string(),name:fe})).default([]),account:m.string(),accountId:m.string().nullable().default(null),accountVerified:m.boolean().default(!1),scopes:m.array(m.string()),scopesStatus:m.enum(["unknown","requested","reported"]).default("unknown"),outputs:m.array(m.string()),state:m.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:m.string().optional(),aws:HE.optional(),ovh:Py.optional()})}),WOe=m.object({...nu,kind:m.literal("service"),data:qOe}),JOe=m.object({...nu,kind:m.literal("method"),data:ru}),XOe=m.object({...nu,kind:m.literal("app"),data:m.object({...IL,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:E.optional()})}),YOe=m.object({...nu,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),QOe=m.object({...nu,kind:m.literal("environment"),data:M5.extend({executorId:E.optional(),operatorId:E.optional(),driver:m.enum(["attached","managed"]).optional(),capabilities:m.array(m.string()).optional(),isolation:m.enum(["process","container"]).optional(),manifestDigest:m.string().optional(),processes:m.object({workingDirectory:m.string()}).optional(),ssh:XU.optional(),awsPrincipal:m.string().optional(),state:GOe,deletion:HOe.optional(),startedAt:Ae.nullable(),stoppedAt:Ae.nullable(),lastActiveAt:Ae,error:m.string().nullable()})}),n$=m.object({...nu,kind:m.literal("function"),data:ti.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:z5.optional()})}),_r=m.discriminatedUnion("kind",[KOe,ZOe,WOe,JOe,XOe,YOe,QOe,n$]),Lwt=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:fe,definition:O5}).strict(),m.object({kind:m.literal("method"),name:fe,definition:ru}).strict(),m.object({kind:m.literal("environment"),name:fe.optional(),options:M5}).strict()]),jwt=m.object({version:m.number().int().positive(),name:fe.optional(),definition:m.union([O5,ru]).optional()}).strict(),ji=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Lt}).strict(),o$=ji.extend({inputs:m.array(m.object({pointer:m.string(),label:m.string().min(1).max(100),secret:m.boolean().default(!1),multiline:m.boolean().default(!1),site:m.url().optional()}).strict()).max(16).default([])}),ZE=m.object({ja:m.string(),en:m.string()}).strict(),AL=o$.extend({title:ZE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:ZE.nullable()}).strict()}),U5=m.object({to:E.optional(),executionId:E.optional(),message:m.string().max(1e3).default(""),operations:m.array(o$).min(1).max(8).optional(),expiresInMinutes:m.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."})}),BE=m.object({id:E,name:fe}),L5=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:BE,relation:C5,object:BE}),m.object({kind:m.literal("transfer"),item:BE,to:BE})]),i$=m.object({id:E,executionId:E,from:tu.pick({id:!0,name:!0}),to:tu.pick({id:!0,name:!0}).nullable(),message:m.string(),purpose:m.enum(["input","approval"]),state:m.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:Ae,expiresAt:Ae,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),Fwt=m.object({id:E,name:fe,publicKey:bn,state:m.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:Ae,expiresAt:Ae}),qwt=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:tu.pick({id:!0,name:!0}).nullable()}),Vwt=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),Gwt=m.object({id:m.string(),actorId:E.nullable(),action:m.string(),targetId:E.nullable(),createdAt:Ae,details:Lt}),Hwt=m.object({returnUrl:m.url().optional(),refreshUrl:m.url().optional()}).strict(),Mr=t=>m.object({items:m.array(t),next:m.string().nullable().default(null)}),Bwt=m.object({id:E}),Kwt=m.object({owner:E}),eDe=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),Zwt=eDe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var tDe=m.object({email:m.boolean(),environments:m.boolean(),ssh:m.boolean(),objects:m.boolean(),payments:m.boolean()}),s$=m.object({principal:tu.nullable(),credentialId:E.nullable(),wrappedKey:WE.nullable(),requestId:E.nullable(),server:m.object({name:fe}),features:tDe,principals:m.array(tu)}),Ywt=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:A5.default("ja"),principalId:E.optional()}).strict(),Qwt=m.object({intent:m.enum(["register","authenticate"]),name:fe.optional(),principalId:E.optional(),returnTo:m.string().max(2048).optional()}).strict(),e_t=m.object({challengeId:E,credential:m.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:WE.optional()}).strict();var rDe=new TextEncoder,nDe=new TextDecoder,Dy="ECDH-ES+A256KW",PL="A256GCM",tt=t=>rDe.encode(t),Po=t=>nDe.decode(t);function Os(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 j5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function a$(){let t=await Ay(Dy,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await eu(t.publicKey)),privateKey:await eu(t.privateKey)}}async function Xa(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 Ey(t).setProtectedHeader({enc:PL}).setAdditionalAuthenticatedData(tt(r));for(let n of e)o.addRecipient(await ei(n.publicKey,Dy)).setUnprotectedHeader({alg:Dy,kid:n.id});return Ao.parse(await o.encrypt())}async function ko(t,e,r,o){if(t.aad!==Os(tt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await ei(e,Dy);return(await lL({...t,recipients:[n]},i,{keyManagementAlgorithms:[Dy],contentEncryptionAlgorithms:[PL]})).plaintext}async function oDe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:tt("Foundation"),info:tt("passkey encryption key")},e,256))}async function F5(t,e,r){let o=await xy(t,await oDe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[PL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Po(o.plaintext))}var br=m.string().regex(/^[A-Za-z0-9_-]{43}$/),Sr=m.string().min(100).max(4e6),q5=bn.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Ny=m.object({encryption:q5,signing:q5}).strict(),or=m.object({id:E,principalId:E,generation:m.number().int().positive(),previous:br.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function xf(t){return bL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function Q(t){return Os(new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t)))))}async function Ya(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function u$(){let[t,e]=await Promise.all([a$(),Ay("ES256",{crv:"P-256",extractable:!0})]),r=await eu(e.privateKey);return Ny.parse({encryption:t.privateKey,signing:r})}function c$(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function l$(t,e){return or.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:c$(e.encryption),signing:c$(e.signing)})}async function ur(t,e,r){let o=e instanceof CryptoKey?e:await ei(e,"ES256");return new Ry(tt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Ur(t,e,r,o){if(C(await kL(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function kL(t,e,r){let o=await vL(t,await ei(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 Ds=m.object({binding:or,signature:Sr}).strict();async function zy(t,e){if(await Ns(t),await xf(e.encryption)!==await xf(t.encryption)||await xf(e.signing)!==await xf(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 Ns(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 xf(e.encryption)===await xf(e.signing))throw new Error("Use separate encryption and signing keys.");await ei(e.encryption,"ECDH-ES+A256KW"),await ei(e.signing,"ES256")}async function d$(t){let{binding:e,signature:r}=Ds.parse(t);return await Ns(e),await Ur(e,r,e.signing,"key-binding"),e}var V5=m.object({ownerId:E,name:fe,resourceId:E.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(E).max(32).optional()}).strict(),G5=V5.extend({value:m.literal("").optional()}),TL=V5.extend({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}),Ef=m.object({ownerId:E,name:fe,definition:ti,resourceId:E.optional(),version:m.number().int().positive().optional()}).strict(),p$=m.object({ownerId:E,connectionId:E,environmentId:E}).strict(),H5=m.object({ownerId:E,connectionId:E,version:m.number().int().positive(),users:m.array(E).max(32),expiresAt:m.iso.datetime().optional()}).strict(),B5=m.object({ownerId:E,methodId:m.string().min(1).max(200),connectionId:E.optional(),name:fe.optional(),appId:E.optional(),redirectUri:m.url().optional(),users:m.array(E).max(32).optional(),scopes:m.array(m.string().min(1).max(1e3)).max(200).optional(),methodDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:m.string().max(1e3).optional(),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}).strict(),My=m.object({ownerId:E,environmentId:E.optional(),operation:m.union([m.object({kind:m.literal("http"),request:Wa}).strict(),Ja.extend({kind:m.literal("command")}),m.object({kind:m.enum(["http","command"]),programId:E,programDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:m.record(m.string(),fe).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),f$=m.object({name:ji.shape.name,title:ZE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:AL.shape.environment,input:Lt}).strict(),K5=m.object({id:E.optional(),operations:m.array(o$).min(1).max(8),responderId:E.optional(),message:m.string().max(1e3).default(""),expiresInMinutes:m.number().int().min(1).max(1440).default(1440)}).strict(),Z5=m.object({values:m.array(Lt).max(8).default([]),configuration:m.array(Lt).max(8).default([]),code:m.string().max(20).optional()}).strict(),$f=m.object({index:m.number().int().nonnegative(),invocation:ji,approval:m.object({id:E,index:m.number().int().nonnegative()}).strict().optional(),continuation:m.object({kind:m.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),Ze=m.object({id:E,actorId:E,ownerId:E,requests:m.array(E),steps:m.array(m.object({index:m.number().int().nonnegative(),name:ji.shape.name,state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:m.array(m.object({kind:m.enum(["run","function"]),id:E}).strict())}).strict()),creator:tu.pick({id:!0,name:!0}),operations:m.array(AL),approval:m.object({requestId:E.nullable(),proposal:L5.nullable()}).strict().nullable(),canContinue:m.boolean(),canCancel:m.boolean(),url:m.url(),code:m.string().optional(),error:m.object({code:m.string(),message:m.string()}).strict().nullable(),index:m.number().int().nonnegative(),state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:m.enum(["approval","input","execution"]).nullable(),waiting:$f.nullable(),results:m.array(wr.nullable()),createdAt:m.iso.datetime(),expiresAt:m.iso.datetime()}).strict(),W5=m.object({id:E,index:m.number().int().nonnegative(),invocation:ji,continuationId:E.optional()}).strict();var Rf=m.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"},iDe=m.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),X5=t=>t===ge.executionResult?14e5:1e6,ue={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},Uy=m.enum([ue.http,ue.command,ue.function,ue.connect,ue.refresh,ue.revoke]);var sDe={[ge.value]:[ue.http,ue.command,ue.function],[ge.tokenSet]:[ue.http,ue.command,ue.function,ue.refresh,ue.revoke],[ge.clientCredential]:[ue.connect,ue.refresh,ue.revoke],[ge.executionResult]:[]},ou=t=>sDe[t],Y5=t=>ou(t).filter(e=>e===ue.function||e===ue.refresh),CL=t=>t===ge.tokenSet,aDe=m.object({id:E,digest:br}).strict(),cDe=m.object({actor:or,executor:or,operations:m.array(Uy).min(1).max(6),functionDigests:m.array(br).max(100).default([]),origins:m.array(Rf).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:Ae}).strict(),uDe=m.object({function:aDe,executor:or,operations:m.array(Uy).min(1).max(6),expiresAt:Ae}).strict(),lDe=m.union([cDe,uDe]),en=m.object({format:m.literal(2),origin:Rf,id:E,ownerId:E,contentType:iDe,revision:m.number().int().positive(),authorities:m.array(or).min(1).max(100),readers:m.array(or).min(1).max(100),grants:m.array(lDe).max(100),observers:m.array(E).max(100).optional(),producers:m.array(m.object({executor:or,runId:E,expiresAt:Ae,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),J5=m.object({ownerId:E,authorities:m.array(or).min(1).max(100)}).strict(),Q5=m.object({origin:Rf,id:E,revision:m.number().int().positive(),from:J5,to:J5,policyDigest:br,previous:br.nullable(),signerId:E}).strict(),dDe=Q5.extend({signature:Sr}),OL=m.array(dDe).max(16),Ly=m.object({policy:en,authorityId:E,signature:Sr,lineage:OL.optional()}).strict(),tn=m.object({policy:en,authorityId:E,authorization:Sr,lineage:OL.optional(),materialRevision:m.number().int().positive(),updatedAt:Ae,creationRunId:E.nullable(),metadata:Lt,sealed:Ao,signerId:E,signature:Sr}).strict(),sd=t=>({ownerId:t.ownerId,authorities:t.authorities});async function e8(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 Q(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 Ur(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(sd(t)))throw new Error("Use the authorities approved by the latest handoff.")}function DL(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 m$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(sd(t));return r===C(sd(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function t8(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(sd(t.policy))!==C(sd(e))){if(await To(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=Q5.parse({origin:e.origin,id:e.id,revision:e.revision,from:sd(t.policy),to:sd(e),policyDigest:await Q(e),previous:n.length?await Q(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ur(i,o.signing,"authority-handoff")})}return n.length?{lineage:OL.parse(n)}:{}}async function h$(t){let e=en.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Ns(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=>!ou(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ue.function&&i!==ue.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ue.http||i===ue.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ue.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function g$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function iu(t,e){return C({purpose:"resource",policyDigest:await Q(t),materialRevision:e})}async function If(t,e,r,o,n,i,s){if(t.byteLength>X5(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await h$(e),c=await t8(s,a,o,n);if(!a.authorities.some(f=>C(f)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Xa(t,g$(a).map(f=>({id:f.id,publicKey:f.encryption})),await iu(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ur(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=tn.parse({...l,signature:await ur(l,n.signing,"resource")});return await To(d),d}async function To(t){let e=tn.parse(t),{signature:r,...o}=e;await h$(e.policy),await e8(e.policy,e.lineage);let n=DL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await Q(e.policy))throw new Error("The handoff approves a different access policy.");await Ur(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??(CL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ue.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Ur(o,r,s.signing,"resource");let a=g$(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!==Os(tt(await iu(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function r8(t,e,r,o,n=t.metadata){let i=await To(t);if(!CL(i.policy.contentType)||!(i.policy.authorities.some(f=>C(f)===C(r))||i.policy.grants.some(f=>C(f.executor)===C(r)&&f.operations.includes(ue.refresh)&&Date.parse(f.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Xa(e,g$(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await iu(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 To(d),d}async function y$(t,e,r,o){let n=await h$(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 t8(o,n,e,r),authorityId:e.id,signature:await ur(n,r.signing,"access-policy")};return await su(i),i}async function su(t){let e=Ly.parse(t);await h$(e.policy),await e8(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await Q(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 Ur(e.policy,e.signature,o.signing,"access-policy"),e}async function jy(t,e,r,o,n,i){let s=await su(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&C(f.executor)===C(o)&&(a.contentType===ge.executionResult||Date.parse(f.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>X5(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Xa(t,g$(a).map(f=>({id:f.id,publicKey:f.encryption})),await iu(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 To(d),d}async function ad(t,e,r){let o=await To(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return ko(o.sealed,r,e.id,await iu(o.policy,o.materialRevision))}var pDe=m.object({id:E,policyDigest:br,materialRevision:m.number().int().positive(),authorizationDigest:br.optional()}).strict();async function NL(t,e){return e.id===t.policy.id&&e.policyDigest===await Q(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||CL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var v$=m.object({format:m.literal(2),id:E,origin:Rf,ownerId:E,approval:m.object({id:E,index:m.number().int().min(0).max(7)}).strict().optional(),operationContext:W5.optional(),actor:or,environmentId:E,executor:or,environmentDigest:br,operation:Uy,functionDigest:br.nullable(),functionId:E.optional(),operationDigest:br,sources:m.array(pDe).max(100),resultRecipients:m.array(or).min(1).max(100),resultApproval:Ly.optional(),createdAt:Ae,expiresAt:Ae}).strict(),Af=m.object({intent:v$,signature:Sr,sealed:Ao}).strict();async function cd(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await Q(t)})}async function n8(t,e,r){if(v$.parse(t),await Q(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Xa(tt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await cd(t,"input"))};return Af.parse({...o,signature:await ur(o,r.signing,"run")})}async function fDe(t,e=Date.now()){let r=Af.parse(t),{signature:o,...n}=r;await Ur(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 su(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!==Os(tt(await cd(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function o8(t,e,r){let o=await fDe(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await ko(o.sealed,r.encryption,e.id,await cd(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await Q(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function ud(t,e,r={}){let o=await To(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await NL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ue.function||e.operation===ue.refresh:e.operation===ue.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ue.command&&e.operation!==ue.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function au(t,e,r,o={}){return await ud(t,e,o),ko(t.sealed,r.encryption,e.executor.id,await iu(t.policy,t.materialRevision))}var zL=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),i8=m.object({format:m.literal(3),id:E,origin:Rf,ownerId:E,name:fe,executor:or,operatorId:E,driver:m.enum(["attached","managed"]),capabilities:m.array(Uy).min(1).max(6),functionVersion:m.number().int().positive().optional(),resultVersion:m.literal(1).optional(),isolation:m.enum(["process","container"]),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:zL.optional(),revision:m.number().int().positive()}).strict(),ML=m.object({manifest:i8,signature:Sr}).strict();async function UL(t,e){let r=i8.parse(t),o={manifest:r,signature:await ur(r,e.signing,"environment")};return await kf(o),o}async function kf(t){let e=ML.parse(t),{manifest:r}=e;if(await Ns(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ue.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(ue.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Ur(r,e.signature,r.executor.signing,"environment"),e}async function Tf(t,e){let{manifest:r}=await kf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await Q(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ue.function&&r.functionVersion!==2)throw new Error("This environment does not authorize the requested execution.")}var w$=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),_$=m.object({ok:m.boolean(),result:wr.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),s8={id:E,intentDigest:br,executorId:E,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Ae},a8=m.object({...s8,sealed:Ao,signature:Sr}).strict(),c8=m.object({...s8,format:m.literal(2),accessDigest:br,proofDigest:br,approval:Ly,content:tn,previousDigest:br.optional(),previous:a8.optional(),signature:Sr}).strict(),Fy=m.union([a8,c8]),mDe=m.object({result:_$,proof:Sr}).strict(),u8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function LL(t,e,r,o,n,i){await su(n);let s={format:2,id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await Q(n),...i?{previousDigest:await Q(i)}:{}},a=await ur({...s,resultDigest:await Q(r)},o.signing,"execution-result"),c=tt(C({result:_$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Pf;let u=await jy(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await Q(a)},d=c8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ur(l,o.signing,"receipt")});return await jL(d,t),d}var Pf=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Cf(t,e,r,o){let n=_$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return LL(t,e,n,o,t.resultApproval);let i=tt(C(n));if(i.byteLength>14e5)throw new Pf;let s=await Xa(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await cd(t,"result")),a={id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Fy.parse({...a,signature:await ur(a,o.signing,"receipt")})}async function jL(t,e){let r=Fy.parse(t);if("content"in r){await Ur(u8(r),r.signature,e.executor.signing,"receipt");let i=await su(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.accessDigest!==await Q(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 Q(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await jL(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 To(r.content),!m$(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 Ur(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.sealed.aad!==Os(tt(await cd(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 l8(t,e,r,o){if(await jL(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 ko(t.content.sealed,o.encryption,r,await iu(t.content.policy,t.content.materialRevision)),a=mDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await Q(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=u8(t);if(await Ur({...u,resultDigest:await Q(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 ko(t.sealed,o.encryption,r,await cd(e,"result")),i=_$.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 hDe=m.enum(["http","command","function","connect","refresh","revoke"]),Bn=m.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:hDe,state:w$,intent:v$,requestSignature:Sr,receipt:Fy.nullable(),error:m.string().nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),b$=m.object({name:fe,approval:Ly}).strict(),d8=m.object({kind:m.literal("function"),functionId:E,definition:ti,arguments:Lt.default({}),outputs:m.record(m.string(),b$).default({})}).strict(),Qa=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:Wa,save:m.record(m.string(),b$).default({})}).strict(),m.object({kind:m.literal("command"),...Ja.shape}).strict(),m.object({kind:m.enum(["connect","refresh","revoke"]),input:wr}).strict()]);var cu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},ec=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=m.object({error:m.object({code:m.string(),message:m.string()})}).parse(await n.json())}catch{throw new cu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new cu(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",{},s$)}};import{chmod as gDe,lstat as yDe,mkdir as vDe,open as FL,readFile as f8,rename as wDe,rm as _De}from"node:fs/promises";import{dirname as bDe,join as qL,resolve as SDe}from"node:path";import{homedir as xDe}from"node:os";import{randomUUID as EDe}from"node:crypto";var VL=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:Ny.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."),m8=m.object({current:m.uuid(),identities:m.array(VL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function tc(){return qL(process.env.XDG_CONFIG_HOME||qL(xDe(),".config"),"foundation","identity.json")}function uu(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 S$(t){let e;try{let n=tc(),i=await yDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await gDe(n,384);let s=m8.parse(JSON.parse(await f8(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=uu(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==uu(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 VL.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!==uu(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 qy(t){let e=tc(),r;try{r=m8.parse(JSON.parse(await f8(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=VL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Of(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 iZ(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;iZ(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 sZ=new Set(["type","properties","required","additionalProperties"]),nZ=["oneOf","anyOf"];function oZ(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function iM(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!sZ.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]??oZ(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:iM(a)??{allOf:a};Wr(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=oZ(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 PCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of sZ)if(n in t)return;let r=e.filter(n=>nZ.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=iM(e);else{let n=r[0],i=nZ.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=>iM([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,ry(t,o))}function Hc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):ry(u,h),ry(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(h.$ref&&p.def)for(let w in u)w==="$ref"||w==="allOf"||w in p.def&&JSON.stringify(u[w])===JSON.stringify(p.def[w])&&delete u[w]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}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())iZ(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)??[])PCe(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)}ry(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,Wr(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:tf(e,"input",t.processors),output:tf(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Vn(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 Vn(o.element,r);if(o.type==="set")return Vn(o.valueType,r);if(o.type==="lazy")return Vn(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 Vn(o.innerType,r);if(o.type==="intersection")return Vn(o.left,r)||Vn(o.right,r);if(o.type==="record"||o.type==="map")return Vn(o.keyType,r)||Vn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Vn(o.in,r)||Vn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Vn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Vn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Vn(n,r))return!0;return!!(o.rest&&Vn(o.rest,r))}return!1}var sM=(t,e={})=>r=>{let o=Vc({...r,processors:e});return Rt(t,o),Gc(o,t),Hc(o,t)},tf=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Vc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Gc(s,t),Hc(s,t)};var rf=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},nf=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},aZ=(t,e)=>{rf(t,"minimum",e),nf(t,"maximum",e)},dZ=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},pZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},fZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},mZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},cZ=(t,e)=>rf(t,"minimum",e.minimum),uZ=(t,e)=>nf(t,"maximum",e.maximum),lZ=t=>(e,r)=>{mZ(e,r.format);let[o,n]=t[r.format];rf(e,"minimum",o),nf(e,"maximum",n)},kCe={greater_than:(t,e)=>rf(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>nf(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>dZ(t,e.value),number_format:lZ(sg),bigint_format:lZ(ag),min_length:cZ,max_length:uZ,length_equals:(t,e)=>aZ(t,e.length),min_size:cZ,max_size:uZ,size_equals:(t,e)=>aZ(t,e.size),string_format:(t,e)=>{mZ(t,e.format),e.pattern&&pZ(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)=>fZ(t,e.mime)};function kr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)kCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&rf(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&rf(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&nf(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&nf(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&dZ(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&fZ(e,n.mime);for(let i of n.patterns??[])pZ(e,i);return e}var TCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},CCe=new Map([[XS,K1],[bg,Z1]]),hZ=t=>CCe.get(t)??t,uM=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=kr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=TCe[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(hZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},lM=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=kr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let h=new Set;for(let b of a)Number.isFinite(b)&&b!==0?h.add(Math.abs(b)):Pr(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=h;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},dM=(t,e,r,o)=>{r.type="boolean"},pM=(t,e,r,o)=>{Pr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},fM=(t,e,r,o)=>{Pr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},mM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},hM=(t,e,r,o)=>{Pr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},gM=(t,e,r,o)=>{Pr(t,e,r,o,"Void cannot be represented in JSON Schema")},yM=(t,e,r,o)=>{r.not={}},vM=(t,e,r,o)=>{},wM=(t,e,r,o)=>{},_M=(t,e,r,o)=>{Pr(t,e,r,o,"Date cannot be represented in JSON Schema")},bM=(t,e,r,o)=>{let n=t._zod.def,i=yp(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},SM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Pr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Pr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},xM=(t,e,r,o)=>{Pr(t,e,r,o,"NaN cannot be represented in JSON Schema")},EM=(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},$M=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=kr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},RM=(t,e,r,o)=>{r.type="boolean"},IM=(t,e,r,o)=>{Pr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},AM=(t,e,r,o)=>{Pr(t,e,r,o,"Function types cannot be represented in JSON Schema")},PM=(t,e,r,o)=>{Pr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},kM=(t,e,r,o)=>{Pr(t,e,r,o,"Map cannot be represented in JSON Schema")},TM=(t,e,r,o)=>{Pr(t,e,r,o,"Set cannot be represented in JSON Schema")},CM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=kr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function ny(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?ny(e.out):e.type==="catch"?ny(e.innerType):t._zod.optin}var OM=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Pr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Wr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?ny(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},j0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},DM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},NM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?ny(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:h}=kr(t);typeof p=="number"&&(n.minItems=p),typeof h=="number"&&(n.maxItems=h)};function aM(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let h=t.get(e)?.def;if(!h)return e;let y=aM(t,h,r);return y===h?e:y}for(let h of["anyOf","oneOf"]){let y=e[h];if(!Array.isArray(y))continue;let w=y.map(b=>aM(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[h]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(h=>typeof h=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(h=>typeof h=="number"?String(h):h):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?qa:mg).source)),p}var cM=new WeakMap;function OCe(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 cM.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=aM(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 zM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=kr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Wr(n.patternProperties,hZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=cM.get(e);l||(l=[],cM.set(e,l),e.deferred.push(()=>OCe(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&ny(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))}},MM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},UM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},LM=Symbol();function gZ(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Pr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),LM):JSON.parse(s)}var jM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=gZ(n.defaultValue,t,e,r,o);s!==LM&&(r.default=s)},FM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=gZ(n.defaultValue,t,e,r,o);s!==LM&&(r._prefault=s)},qM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Pr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},VM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},GM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},HM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},F0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},BM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},L0={string:uM,number:lM,boolean:dM,bigint:pM,symbol:fM,null:mM,undefined:hM,void:gM,never:yM,any:vM,unknown:wM,date:_M,enum:bM,literal:SM,nan:xM,template_literal:EM,file:$M,success:RM,custom:IM,function:AM,transform:PM,map:kM,set:TM,array:CM,object:OM,union:j0,intersection:DM,tuple:NM,record:zM,nullable:MM,nonoptional:UM,default:jM,prefault:FM,catch:qM,pipe:VM,readonly:GM,promise:HM,optional:F0,lazy:BM};function Zl(t,e){if("_idmap"in t){let o=t,n=Vc({...e,processors:L0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Gc(n,l),Wr(s,u,Hc(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=Vc({...e,processors:L0});return Rt(t,r),Gc(r,t),Hc(r,t)}var q0=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=Vc({processors:L0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Gc(this.ctx,e);let o=Hc(this.ctx,e),{"~standard":n,...i}=o;return i}};var yZ={};var pf={};Ht(pf,{ZodAny:()=>dU,ZodArray:()=>hU,ZodBase64:()=>aE,ZodBase64URL:()=>cE,ZodBigInt:()=>lf,ZodBigIntFormat:()=>dE,ZodBoolean:()=>uf,ZodCIDRv4:()=>iE,ZodCIDRv6:()=>sE,ZodCUID:()=>Y0,ZodCUID2:()=>Q0,ZodCatch:()=>DU,ZodCodec:()=>py,ZodCreditCard:()=>sU,ZodCustom:()=>fy,ZodCustomStringFormat:()=>Jl,ZodDate:()=>ay,ZodDefault:()=>AU,ZodDiscriminatedUnion:()=>yU,ZodE164:()=>uE,ZodEmail:()=>Z0,ZodEmoji:()=>J0,ZodEnum:()=>sf,ZodExactOptional:()=>mE,ZodFile:()=>EU,ZodFunction:()=>GU,ZodGUID:()=>W0,ZodIBAN:()=>aU,ZodIPv4:()=>nE,ZodIPv6:()=>oE,ZodISODate:()=>Kc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Wc,ZodISOTime:()=>Zc,ZodInstanceOf:()=>KU,ZodIntersection:()=>vU,ZodJWT:()=>lE,ZodKSUID:()=>rE,ZodLazy:()=>FU,ZodLiteral:()=>xU,ZodMAC:()=>iU,ZodMap:()=>bU,ZodNaN:()=>zU,ZodNanoID:()=>X0,ZodNever:()=>fU,ZodNonOptional:()=>hE,ZodNull:()=>lU,ZodNullable:()=>IU,ZodNumber:()=>cf,ZodNumberFormat:()=>Xl,ZodObject:()=>cy,ZodOptional:()=>Yl,ZodPipe:()=>dy,ZodPrefault:()=>kU,ZodPreprocess:()=>MU,ZodPromise:()=>VU,ZodReadonly:()=>UU,ZodRecord:()=>of,ZodSet:()=>SU,ZodString:()=>af,ZodStringFormat:()=>Tt,ZodSuccess:()=>OU,ZodSymbol:()=>cU,ZodTemplateLiteral:()=>jU,ZodTransform:()=>$U,ZodTuple:()=>wU,ZodType:()=>Ce,ZodULID:()=>eE,ZodURL:()=>iy,ZodUUID:()=>Cs,ZodUndefined:()=>uU,ZodUnion:()=>uy,ZodUnknown:()=>pU,ZodVoid:()=>mU,ZodXID:()=>tE,ZodXor:()=>gU,_ZodString:()=>K0,_default:()=>PU,_function:()=>$W,any:()=>sW,array:()=>qe,base64:()=>jZ,base64url:()=>FZ,bigint:()=>tW,boolean:()=>hr,catch:()=>NU,check:()=>RW,cidrv4:()=>UZ,cidrv6:()=>LZ,codec:()=>bW,creditCard:()=>VZ,cuid:()=>kZ,cuid2:()=>TZ,currencyCode:()=>WZ,custom:()=>gE,date:()=>cW,describe:()=>IW,discriminatedUnion:()=>ly,e164:()=>qZ,email:()=>_Z,emoji:()=>AZ,enum:()=>Yr,exactOptional:()=>RU,file:()=>yW,float32:()=>XZ,float64:()=>YZ,function:()=>$W,guid:()=>bZ,hash:()=>JZ,hex:()=>ZZ,hostname:()=>KZ,httpUrl:()=>IZ,iban:()=>GZ,instanceof:()=>PW,int:()=>H0,int32:()=>QZ,int64:()=>rW,intersection:()=>df,invertCodec:()=>SW,ipv4:()=>NZ,ipv6:()=>MZ,json:()=>TW,jwt:()=>HZ,keyof:()=>uW,ksuid:()=>DZ,lazy:()=>qU,literal:()=>ae,looseObject:()=>Xr,looseRecord:()=>fW,mac:()=>zZ,map:()=>mW,meta:()=>AW,nan:()=>_W,nanoid:()=>PZ,nativeEnum:()=>gW,never:()=>pE,nonoptional:()=>CU,null:()=>sy,nullable:()=>oy,nullish:()=>vW,number:()=>yt,object:()=>X,optional:()=>kt,partialRecord:()=>pW,pipe:()=>B0,prefault:()=>TU,preprocess:()=>my,promise:()=>EW,readonly:()=>LU,record:()=>Ct,refine:()=>HU,set:()=>hW,strictObject:()=>lW,string:()=>O,stringFormat:()=>BZ,stringbool:()=>kW,success:()=>wW,superRefine:()=>BU,symbol:()=>oW,templateLiteral:()=>xW,transform:()=>fE,tuple:()=>_U,uint32:()=>eW,uint64:()=>nW,ulid:()=>CZ,undefined:()=>iW,union:()=>It,unknown:()=>Ut,url:()=>RZ,uuid:()=>SZ,uuidv4:()=>xZ,uuidv6:()=>EZ,uuidv7:()=>$Z,void:()=>aW,xid:()=>OZ,xor:()=>dW});var V0={};Ht(V0,{endsWith:()=>Kp,gt:()=>ks,gte:()=>Ro,includes:()=>Hp,length:()=>Kl,lowercase:()=>Vp,lt:()=>Ps,lte:()=>$o,maxLength:()=>Bl,maxSize:()=>Fc,mime:()=>Wp,minLength:()=>Va,minSize:()=>Ts,multipleOf:()=>jc,negative:()=>A0,nonnegative:()=>k0,nonpositive:()=>P0,normalize:()=>Jp,overwrite:()=>Di,positive:()=>I0,properties:()=>Zp,property:()=>T0,regex:()=>qp,size:()=>Hl,slugify:()=>ef,startsWith:()=>Bp,toLowerCase:()=>Yp,toUpperCase:()=>Qp,trim:()=>Xp,uppercase:()=>Gp});var vZ=new WeakSet([Object.prototype,Error.prototype]);function G0(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 wZ=(t,e)=>{I1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);vZ.has(r)||(vZ.add(r),G0(r,"format",o=>n=>pg(o,n)),G0(r,"flatten",o=>n=>dg(o,n)),G0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,vp,2)}),G0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,vp,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},NCe=$("ZodError",wZ),uo=$("ZodError",wZ,void 0,{Parent:Error});var KM=xp(uo),ZM=Ep(uo),WM=$p(uo),JM=Ip(uo),XM=pS(uo),YM=fS(uo),QM=mS(uo),eU=hS(uo),tU=gS(uo),rU=yS(uo),nU=vS(uo),oU=wS(uo);function MCe(){zr.localeError||cr(Jx())}function Wl(){zr.memoizer||cr({memoizer:Pg()})}var Ce=$("ZodType",(t,e)=>(MCe(),be.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(HU(t,e))},superRefine(t,e){return this.check(BU(t,e))},overwrite(t){return this.check(Di(t))},optional(){return kt(this)},exactOptional(){return RU(this)},nullable(){return oy(this)},nullish(){return kt(oy(this))},nonoptional(t){return CU(this,t)},array(){return qe(this)},or(t){return It([this,t])},and(t){return df(this,t)},transform(t){return B0(this,fE(t))},default(t){return PU(this,t)},prefault(t){return TU(this,t)},catch(t){return NU(this,t)},pipe(t){return B0(this,t)},readonly(){return LU(this)},describe(t){let e=this.clone();return Jr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Jr.get(this);let e=this.clone();return Jr.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",{...kS(this),jsonSchema:{input:tf(this,"input"),output:tf(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return KM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await ZM(this,e,r,{callee:t})},safeParse(t,e){return WM(this,t,e)},async safeParseAsync(t,e){return JM(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Pp(this,t,e)},validateAsync(t,e){return kp(this,t,e)},encode:function t(e,r){return XM(this,e,r,{callee:t})},decode:function t(e,r){return YM(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await QM(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await eU(this,e,r,{callee:t})},safeEncode(t,e){return tU(this,t,e)},safeDecode(t,e){return rU(this,t,e)},async safeEncodeAsync(t,e){return nU(this,t,e)},async safeDecodeAsync(t,e){return oU(this,t,e)},toJSONSchema(t){return sM(this,{})(t)},get description(){return Jr.get(this)?.description},get _def(){return this._zod.def}}),K0=$("_ZodString",(t,e)=>{Lc.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uM(t,r,o,n)},D.derived({format:t=>kr(t).format??null,minLength:t=>kr(t).minimum??null,maxLength:t=>kr(t).maximum??null},{regex(...t){return this.check(qp(...t))},includes(...t){return this.check(Hp(...t))},startsWith(...t){return this.check(Bp(...t))},endsWith(...t){return this.check(Kp(...t))},min(...t){return this.check(Va(...t))},max(...t){return this.check(Bl(...t))},length(...t){return this.check(Kl(...t))},nonempty(...t){return this.check(Va(1,...t))},lowercase(t){return this.check(Vp(t))},uppercase(t){return this.check(Gp(t))},trim(){return this.check(Xp())},normalize(...t){return this.check(Jp(...t))},toLowerCase(){return this.check(Yp())},toUpperCase(){return this.check(Qp())},slugify(){return this.check(ef())}})),af=$("ZodString",(t,e)=>{Lc.init(t,e),K0.init(t,e)},{email(t){return this.check(Tg(Z0,t))},url(t){return this.check(Fp(iy,t))},jwt(t){return this.check(Xg(lE,t))},emoji(t){return this.check(Mg(J0,t))},guid(t){return this.check(Cg(W0,t))},uuid(t){return this.check(Og(Cs,t))},uuidv4(t){return this.check(Dg(Cs,t))},uuidv6(t){return this.check(Ng(Cs,t))},uuidv7(t){return this.check(zg(Cs,t))},nanoid(t){return this.check(Ug(X0,t))},cuid(t){return this.check(Lg(Y0,t))},cuid2(t){return this.check(jg(Q0,t))},ulid(t){return this.check(Fg(eE,t))},base64(t){return this.check(Zg(aE,t))},base64url(t){return this.check(Wg(cE,t))},xid(t){return this.check(qg(tE,t))},ksuid(t){return this.check(Vg(rE,t))},ipv4(t){return this.check(Gg(nE,t))},ipv6(t){return this.check(Hg(oE,t))},cidrv4(t){return this.check(Bg(iE,t))},cidrv6(t){return this.check(Kg(sE,t))},e164(t){return this.check(Jg(uE,t))},datetime(t){return this.check(Yg(Bc,t))},date(t){return this.check(Qg(Kc,t))},time(t){return this.check(ey(Zc,t))},duration(t){return this.check(ty(Wc,t))}});function O(t){return o0(af,t)}var Tt=$("ZodStringFormat",(t,e)=>{St.init(t,e),K0.init(t,e)}),Bc=$("ZodISODateTime",(t,e)=>{zz.init(t,e),Tt.init(t,e)}),Kc=$("ZodISODate",(t,e)=>{Mz.init(t,e),Tt.init(t,e)}),Zc=$("ZodISOTime",(t,e)=>{Uz.init(t,e),Tt.init(t,e)}),Wc=$("ZodISODuration",(t,e)=>{Lz.init(t,e),Tt.init(t,e)}),Z0=$("ZodEmail",(t,e)=>{OS.init(t,e),Tt.init(t,e)});function _Z(t){return Tg(Z0,t)}var W0=$("ZodGUID",(t,e)=>{TS.init(t,e),Tt.init(t,e)});function bZ(t){return Cg(W0,t)}var Cs=$("ZodUUID",(t,e)=>{CS.init(t,e),Tt.init(t,e)});function SZ(t){return Og(Cs,t)}function xZ(t){return Dg(Cs,t)}function EZ(t){return Ng(Cs,t)}function $Z(t){return zg(Cs,t)}var iy=$("ZodURL",(t,e)=>{MS.init(t,e),Tt.init(t,e)});function RZ(t){return Fp(iy,t)}function IZ(t){return Fp(iy,{protocol:fg,hostname:J1,...D.normalizeParams(t)})}var J0=$("ZodEmoji",(t,e)=>{US.init(t,e),Tt.init(t,e)});function AZ(t){return Mg(J0,t)}var X0=$("ZodNanoID",(t,e)=>{LS.init(t,e),Tt.init(t,e)});function PZ(t){return Ug(X0,t)}var Y0=$("ZodCUID",(t,e)=>{jS.init(t,e),Tt.init(t,e)});function kZ(t){return Lg(Y0,t)}var Q0=$("ZodCUID2",(t,e)=>{FS.init(t,e),Tt.init(t,e)});function TZ(t){return jg(Q0,t)}var eE=$("ZodULID",(t,e)=>{qS.init(t,e),Tt.init(t,e)});function CZ(t){return Fg(eE,t)}var tE=$("ZodXID",(t,e)=>{VS.init(t,e),Tt.init(t,e)});function OZ(t){return qg(tE,t)}var rE=$("ZodKSUID",(t,e)=>{GS.init(t,e),Tt.init(t,e)});function DZ(t){return Vg(rE,t)}var nE=$("ZodIPv4",(t,e)=>{HS.init(t,e),Tt.init(t,e)});function NZ(t){return Gg(nE,t)}var iU=$("ZodMAC",(t,e)=>{KS.init(t,e),Tt.init(t,e)});function zZ(t){return i0(iU,t)}var oE=$("ZodIPv6",(t,e)=>{BS.init(t,e),Tt.init(t,e)});function MZ(t){return Hg(oE,t)}var iE=$("ZodCIDRv4",(t,e)=>{ZS.init(t,e),Tt.init(t,e)});function UZ(t){return Bg(iE,t)}var sE=$("ZodCIDRv6",(t,e)=>{JS.init(t,e),Tt.init(t,e)});function LZ(t){return Kg(sE,t)}var aE=$("ZodBase64",(t,e)=>{YS.init(t,e),Tt.init(t,e)});function jZ(t){return Zg(aE,t)}var cE=$("ZodBase64URL",(t,e)=>{ex.init(t,e),Tt.init(t,e)});function FZ(t){return Wg(cE,t)}var uE=$("ZodE164",(t,e)=>{tx.init(t,e),Tt.init(t,e)});function qZ(t){return Jg(uE,t)}var sU=$("ZodCreditCard",(t,e)=>{nx.init(t,e),Tt.init(t,e)});function VZ(t){return s0(sU,t)}var aU=$("ZodIBAN",(t,e)=>{ix.init(t,e),Tt.init(t,e)});function GZ(t){return a0(aU,t)}var lE=$("ZodJWT",(t,e)=>{ax.init(t,e),Tt.init(t,e)});function HZ(t){return Xg(lE,t)}var Jl=$("ZodCustomStringFormat",(t,e)=>{cx.init(t,e),Tt.init(t,e)});function BZ(t,e,r={}){return qc(Jl,t,e,r)}function KZ(t){return qc(Jl,"hostname",W1,t)}function ZZ(t){return qc(Jl,"hex",lz,t)}function WZ(t){return qc(Jl,"currency_code",Y1,t)}function JZ(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Eo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return qc(Jl,o,n,e)}var cf=$("ZodNumber",(t,e)=>{Sg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lM(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=kr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=kr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=kr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>kr(t).format??null},{gt(t,e){return this.check(ks(t,e))},gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},lt(t,e){return this.check(Ps(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},int(t){return this.check(H0(t))},safe(t){return this.check(H0(t))},positive(t){return this.check(ks(0,t))},nonnegative(t){return this.check(Ro(0,t))},negative(t){return this.check(Ps(0,t))},nonpositive(t){return this.check($o(0,t))},multipleOf(t,e){return this.check(jc(t,e))},step(t,e){return this.check(jc(t,e))},finite(){return this}}));function yt(t){return c0(cf,t)}var Xl=$("ZodNumberFormat",(t,e)=>{ux.init(t,e),cf.init(t,e)});function H0(t){return u0(Xl,t)}function XZ(t){return l0(Xl,t)}function YZ(t){return d0(Xl,t)}function QZ(t){return p0(Xl,t)}function eW(t){return f0(Xl,t)}var uf=$("ZodBoolean",(t,e)=>{Op.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dM(t,r,o,n)});function hr(t){return m0(uf,t)}var lf=$("ZodBigInt",(t,e)=>{xg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pM(t,r,o,n)},D.derived({minValue:t=>kr(t).minimum??null,maxValue:t=>kr(t).maximum??null,format:t=>kr(t).format??null},{gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},gt(t,e){return this.check(ks(t,e))},lt(t,e){return this.check(Ps(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},positive(t){return this.check(ks(BigInt(0),t))},negative(t){return this.check(Ps(BigInt(0),t))},nonpositive(t){return this.check($o(BigInt(0),t))},nonnegative(t){return this.check(Ro(BigInt(0),t))},multipleOf(t,e){return this.check(jc(t,e))}}));function tW(t){return h0(lf,t)}var dE=$("ZodBigIntFormat",(t,e)=>{lx.init(t,e),lf.init(t,e)});function rW(t){return g0(dE,t)}function nW(t){return y0(dE,t)}var cU=$("ZodSymbol",(t,e)=>{dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fM(t,r,o,n)});function oW(t){return v0(cU,t)}var uU=$("ZodUndefined",(t,e)=>{px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n)});function iW(t){return w0(uU,t)}var lU=$("ZodNull",(t,e)=>{fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n)});function sy(t){return _0(lU,t)}var dU=$("ZodAny",(t,e)=>{mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n)});function sW(){return b0(dU)}var pU=$("ZodUnknown",(t,e)=>{hx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n)});function Ut(){return S0(pU)}var fU=$("ZodNever",(t,e)=>{gx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n)});function pE(t){return x0(fU,t)}var mU=$("ZodVoid",(t,e)=>{yx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n)});function aW(t){return E0(mU,t)}var ay=$("ZodDate",(t,e)=>{vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n),t.min=(r,o)=>t.check(Ro(r,o)),t.max=(r,o)=>t.check($o(r,o))},D.derived({minDate:t=>{let{minimum:e}=kr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=kr(t);return e?new Date(e):null}},{}));function cW(t){return $0(ay,t)}var hU=$("ZodArray",(t,e)=>{Wl(),wx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Va(t,e))},nonempty(t){return this.check(Va(1,t))},max(t,e){return this.check(Bl(t,e))},length(t,e){return this.check(Kl(t,e))},unwrap(){return this.element}});function qe(t,e){return oM(hU,t,e)}function uW(t){let e=t._zod.def.shape;return Yr(Object.keys(e))}var cy=$("ZodObject",(t,e)=>{Wl(),jz.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OM(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Yr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:pE()}))},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(Yl,this,t[0])},exactPartial(...t){return D.partial(mE,this,t[0],"exactPartial")},required(...t){return D.required(hE,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new cy(r)}function lW(t,e){return new cy({type:"object",shape:t,catchall:pE(),...D.normalizeParams(e)})}function Xr(t,e){return new cy({type:"object",shape:t,catchall:Ut(),...D.normalizeParams(e)})}var uy=$("ZodUnion",(t,e)=>{Dp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>j0(t,r,o,n),t.options=e.options});function It(t,e){return new uy({type:"union",options:t,...D.normalizeParams(e)})}var gU=$("ZodXor",(t,e)=>{uy.init(t,e),bx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>j0(t,r,o,n),t.options=e.options});function dW(t,e){return new gU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var yU=$("ZodDiscriminatedUnion",(t,e)=>{uy.init(t,e),Sx.init(t,e)});function ly(t,e,r){return new yU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var vU=$("ZodIntersection",(t,e)=>{xx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>DM(t,r,o,n)});function df(t,e){return new vU({type:"intersection",left:t,right:e})}var wU=$("ZodTuple",(t,e)=>{Wl(),Eg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>NM(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 Yl({type:"optional",innerType:e}))})}});function _U(t,e,r){let o=e instanceof be,n=o?r:e,i=o?e:null;return new wU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var of=$("ZodRecord",(t,e)=>{Wl(),Ex.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Ct(t,e,r){return!e||!e._zod?new of({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new of({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function pW(t,e,r){return new of({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function fW(t,e,r){return new of({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var bU=$("ZodMap",(t,e)=>{Wl(),$x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ts(...r)),t.nonempty=r=>t.check(Ts(1,r)),t.max=(...r)=>t.check(Fc(...r)),t.size=(...r)=>t.check(Hl(...r))});function mW(t,e,r){return new bU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var SU=$("ZodSet",(t,e)=>{Wl(),Rx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TM(t,r,o,n),t.min=(...r)=>t.check(Ts(...r)),t.nonempty=r=>t.check(Ts(1,r)),t.max=(...r)=>t.check(Fc(...r)),t.size=(...r)=>t.check(Hl(...r))});function hW(t,e){return new SU({type:"set",valueType:t,...D.normalizeParams(e)})}var sf=$("ZodEnum",(t,e)=>{Ix.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(o,n,i)=>bM(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 sf({...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 sf({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Yr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new sf({type:"enum",entries:r,...D.normalizeParams(e)})}function gW(t,e){return new sf({type:"enum",entries:t,...D.normalizeParams(e)})}var xU=$("ZodLiteral",(t,e)=>{Ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ae(t,e){return new xU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var EU=$("ZodFile",(t,e)=>{Px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$M(t,r,o,n),t.min=(r,o)=>t.check(Ts(r,o)),t.max=(r,o)=>t.check(Fc(r,o)),t.mime=(r,o)=>t.check(Wp(Array.isArray(r)?r:[r],o))});function yW(t){return C0(EU,t)}var $U=$("ZodTransform",(t,e)=>{Wl(),kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Uc(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 fE(t){return new $U({type:"transform",transform:t})}var Yl=$("ZodOptional",(t,e)=>{$g.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>F0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function kt(t){return new Yl({type:"optional",innerType:t})}var mE=$("ZodExactOptional",(t,e)=>{Tx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>F0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function RU(t){return new mE({type:"optional",innerType:t})}var IU=$("ZodNullable",(t,e)=>{Cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>MM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function oy(t){return new IU({type:"nullable",innerType:t})}function vW(t){return kt(oy(t))}var AU=$("ZodDefault",(t,e)=>{Ox.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>jM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function PU(t,e){return new AU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var kU=$("ZodPrefault",(t,e)=>{Dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>FM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function TU(t,e){return new kU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var hE=$("ZodNonOptional",(t,e)=>{Nx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>UM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function CU(t,e){return new hE({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var OU=$("ZodSuccess",(t,e)=>{zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>RM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wW(t){return new OU({type:"success",innerType:t})}var DU=$("ZodCatch",(t,e)=>{Mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function NU(t,e){return new DU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var zU=$("ZodNaN",(t,e)=>{Ux.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n)});function _W(t){return R0(zU,t)}var dy=$("ZodPipe",(t,e)=>{Rg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>VM(t,r,o,n),t.in=e.in,t.out=e.out});function B0(t,e){return new dy({type:"pipe",in:t,out:e})}var py=$("ZodCodec",(t,e)=>{dy.init(t,e),Np.init(t,e)});function bW(t,e,r){return new py({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function SW(t){let e=t._zod.def;return new py({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var MU=$("ZodPreprocess",(t,e)=>{dy.init(t,e),qz.init(t,e)}),UU=$("ZodReadonly",(t,e)=>{Lx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function LU(t){return new UU({type:"readonly",innerType:t})}var jU=$("ZodTemplateLiteral",(t,e)=>{jx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n)});function xW(t,e){return new jU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var FU=$("ZodLazy",(t,e)=>{zp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>BM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function qU(t){return new FU({type:"lazy",getter:t})}var VU=$("ZodPromise",(t,e)=>{qx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function EW(t){return new VU({type:"promise",innerType:t})}var GU=$("ZodFunction",(t,e)=>{Fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n)});function $W(t){return new GU({type:"function",input:Array.isArray(t?.input)?_U(t?.input):t?.input??qe(Ut()),output:t?.output??Ut()})}var fy=$("ZodCustom",(t,e)=>{Vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n)});function RW(t){let e=new Pt({check:"custom"});return e._zod.check=t,e}function gE(t,e){return O0(fy,t??(()=>!0),e)}function HU(t,e={}){return D0(fy,t,e)}function BU(t,e){return N0(t,e)}var IW=z0,AW=M0,KU=$("ZodInstanceOf",(t,e)=>{fy.init(t,e)},{properties(t,e){return this.check(Zp(t,e))}});function PW(t,e={}){let r=new KU({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 kW=(...t)=>U0({Codec:py,Boolean:uf,String:af},...t);function TW(t){let e=qU(()=>It([O(t),yt(),hr(),sy(),qe(e),Ct(O(),e)]));return e}function my(t,e){return new MU({type:"pipe",in:fE(t),out:e})}var UCe={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 LCe(t){cr({customError:t})}function jCe(){return cr().customError}var ZU;ZU||(ZU={});var Ql={};Ht(Ql,{ZodISODate:()=>Kc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Wc,ZodISOTime:()=>Zc,date:()=>qCe,datetime:()=>FCe,duration:()=>GCe,time:()=>VCe});function FCe(t){return Yg(Bc,t)}function qCe(t){return Qg(Kc,t)}function VCe(t){return ey(Zc,t)}function GCe(t){return ty(Wc,t)}var J={...pf,...V0,iso:Ql},HCe=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 BCe(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 CW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function KCe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ZCe(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:KCe(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 WCe(t,e){return J.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 WU(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=WU(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=WU(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 JCe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),XCe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function hy(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(hy):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>JCe.has(e)?hy(r):!XCe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(hy))}function OW(t){return t===1?"element":"elements"}function YCe(t,e){return J.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=WU(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 ${OW(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 ${OW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function DW(t,e){if(t!==!1)return t===void 0||t===!0?J.any():Gn(t,e)}var QCe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function NW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return J.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 J.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=ZCe(n,e),s=Gn(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 J.null();if(n.length===0)return J.never();if(n.length===1)return J.literal(n[0]);if(n.every(s=>typeof s=="string"))return J.enum(n);let i=n.map(s=>J.literal(s));return i.length<2?i[0]:J.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return J.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return NW(s,e)});return n.length===0?J.never():n.length===1?n[0]:J.union(n)}if(!r)return J.any();let o;switch(r){case"string":{let n=J.string();if(t.format){let i=t.format;i==="email"?n=n.check(J.email()):i==="uri"||i==="uri-reference"?n=n.check(J.url()):i==="uuid"||i==="guid"?n=n.check(J.uuid()):i==="date-time"?n=n.check(J.iso.datetime({offset:!0})):i==="date"?n=n.check(J.iso.date()):i==="time"?n=n.check(J.regex(QCe)):i==="duration"?n=n.check(J.iso.duration()):i==="hostname"?n=n.check(J.hostname()):i==="ipv4"?n=n.check(J.ipv4()):i==="ipv6"?n=n.check(J.ipv6()):i==="mac"?n=n.check(J.mac()):i==="cidr"?n=n.check(J.cidrv4()):i==="cidr-v6"?n=n.check(J.cidrv6()):i==="base64"?n=n.check(J.base64()):i==="base64url"?n=n.check(J.base64url()):i==="e164"?n=n.check(J.e164()):i==="credit_card"?n=n.check(J.creditCard()):i==="iban"?n=n.check(J.iban()):i==="jwt"?n=n.check(J.jwt()):i==="emoji"?n=n.check(J.emoji()):i==="nanoid"?n=n.check(J.nanoid()):i==="cuid"?n=n.check(J.cuid()):i==="cuid2"?n=n.check(J.cuid2()):i==="ulid"?n=n.check(J.ulid()):i==="xid"?n=n.check(J.xid()):i==="ksuid"&&(n=n.check(J.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"?J.number().int():J.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=J.boolean();break}case"null":{o=J.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Gn(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=Gn(f,e);Wr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let y of f){let w=Gn(d[y],e),b=J.string().regex(new RegExp(y));p.push(J.looseRecord(b,w))}let h=[];if(Object.keys(n).length>0&&h.push(J.object(n).passthrough()),h.push(...p),h.length===0)o=J.object({}).passthrough();else if(h.length===1)o=h[0];else{let y=J.intersection(h[0],h[1]);for(let w=2;w<h.length;w++)y=J.intersection(y,h[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=f.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Xo(S.value))return;let x=[];for(let R of Object.keys(S.value))y.includes(R)||w.some(T=>T.test(R))||x.push(R);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=J.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let f=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=Gn(f,e)}o=WCe(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=>Gn(d,e)),c=CW(a,s),u=Array.isArray(i)?void 0:DW(i,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Gn(d,e)),c=CW(a,s),u=DW(t.additionalItems,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(i!==void 0){let s=Gn(i,e),a=J.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=J.array(J.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=YCe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Gn(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 Gn(t,e){if(typeof t=="boolean")return t?J.any():J.never();let r=NW(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=>Gn(u,e)),c=J.union(a);r=o?J.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Gn(u,e)),c=J.xor(a);r=o?J.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:J.any();else{let a=o?r:Gn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=J.intersection(a,Gn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=J.nullable(r)),t.readOnly===!0&&(r=J.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&&!hy(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&&!hy(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))HCe.has(a)||Wr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function zW(t,e){if(typeof t=="boolean")return t?J.any():J.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=BCe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Jr};return Gn(r,i)}var MW=Symbol("z.visit/resolving");function gy(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===MW)return new zp({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,MW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let h of l){let y=n(u[h]);y!==u[h]&&(d=!0),f[h]=y}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let h=n(p);h!==p&&(l=!0),d.push(h)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:f}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let f of u){let p=n(f);p!==f&&(l=!0),d.push(p)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function UW(t){return gy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function eOe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Jo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function LW(t){return eOe(t.out,t.checks)}function tOe(t){return t.in._zod.traits.has("$ZodTransform")?LW(t):t.in}function jW(t){return gy(t,{pipe:e=>tOe(e._zod.def),default:(e,r)=>r?kt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function FW(t){return gy(t,{pipe:e=>LW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var JU={};Ht(JU,{bigint:()=>iOe,boolean:()=>oOe,date:()=>sOe,number:()=>nOe,string:()=>rOe});function rOe(t){return Yz(af,t)}function nOe(t){return eM(cf,t)}function oOe(t){return tM(uf,t)}function iOe(t){return rM(lf,t)}function sOe(t){return nM(ay,t)}var yy={name:"@tomato414941/foundation",version:"13.1.1",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&m.config({jitless:!0});function cOe(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 vy=m.string().trim().max(8192).refine(t=>cOe(t)!==null,"Use an OpenSSH public key from a .pub file."),wy=m.object({authorizedKeys:m.array(vy).max(32)}).strict(),Jgt=wy.extend({revision:m.number().int().positive().optional()}),XU=wy.extend({host:m.string().min(1).max(253).nullable(),port:m.number().int().min(1).max(65535),username:m.literal("root"),workingDirectory:m.literal("/workspace"),hostKey:vy.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),Xgt=XU.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])}),Ygt=m.object({hostKey:vy,appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),uOe=wy.extend({port:m.number().int().min(1).max(65535),revision:m.number().int().positive()}).strict(),yE=m.object({configuration:uOe.nullable()}).strict();var ff=new TextEncoder,mf=new TextDecoder,qW=new TextDecoder("utf-8",{fatal:!0}),vE=2**32;function Hn(...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 YU(t,e,r){if(e<0||e>=vE)throw new RangeError(`value must be >= 0 and <= ${vE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function QU(t){let e=Math.floor(t/vE),r=t%vE,o=new Uint8Array(8);return YU(o,e,0),YU(o,r,4),o}function wE(t){let e=new Uint8Array(4);return YU(e,t),e}var lOe=/[^\x00-\x7f]/;function Qr(t){if(typeof t=="string"&&t.length>=128){if(lOe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return ff.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 VW(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 GW(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 _E(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ga=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 ed=class extends Ga{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ot=class extends Ga{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Jc=class extends Ga{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends Ga{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Xt=class extends Ga{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var _y=class extends Ga{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var bE=class extends Ga{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var dOe="The input to be decoded is not correctly encoded.";function td(t){try{return GW(typeof t=="string"?t:mf.decode(t),!0)}catch(e){throw new TypeError(dOe,{cause:e})}}function nr(t){return VW(typeof t=="string"?ff.encode(t):t,!0)}function Io(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function vr(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Xc(...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 Qo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function lo(t,e,r){try{return td(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function SE(t,e,r){try{return Qr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function hf(t,e,r){let o;try{o=JSON.parse(qW.decode(td(t)))}catch{throw new e(r)}if(!vr(o))throw new e(r);return o}var xE={__proto__:null,b64:!0},EE={__proto__:null};function by(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 Yc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ot(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function RE(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 rd(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!vr(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var pOe=t=>t[Symbol.toStringTag],fOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function zi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(vr(e)){if(s=iL(e),typeof s.kty!="string")throw HW(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(fOe(t,s,r),s.kty==="oct")return td(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!rL(e))throw HW(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${pOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Qc(e))return e;if(a=e,a.type==="secret")return a.export()}eL||=new WeakMap;let c=e,u=eL.get(c);if(u?.[o])return u[o];if(u||eL.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=mOe[a.asymmetricKeyDetails?.namedCurve],f=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(f,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await yf(t,s)}var eL,mOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function AE(t){if(!Qc(t))throw new Error("CryptoKey instance expected")}var Qc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},tL=t=>t?.[Symbol.toStringTag]==="KeyObject",rL=t=>Qc(t)||tL(t);function BW(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 Ha=(t,...e)=>BW("Key must be ",t,...e);function HW(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(BW(`Key for the ${t} algorithm must be `,e,...o))}var IE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function nL(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function gf(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 oL(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw IE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw IE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw IE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw IE(e.length,"algorithm.length");nL(t,r)}function PE(t){return{__proto__:null,...t}}function iL(t){let e=PE(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 kE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function yf(t,e,r){if(!t.kty.includes(e.kty))throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Mi(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),oL(t,e,r),t}var nd=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function TE(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 hOe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function KW(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function ZW(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Ha(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 WW(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function gOe(t,e,r,o,n){let[i,s,a]=await ZW(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Hn(n,o,c,QU(n.length*8)),l=await WW(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function yOe(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 vOe(t,e,r,o,n,i){let[s,a,c]=await ZW(t,e,"decrypt"),u=Hn(i,o,r,QU(i.length*8)),l=await WW(a,u,c);try{if(await yOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Jc}async function CE(t,e,r,o,n){if(!Qc(r)&&!(r instanceof Uint8Array))throw new TypeError(Ha(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?KW(t,o):o=hOe(t),r instanceof Uint8Array&&TE(r,t.cekBits),t.cbc)return gOe(t,e,r,o,n);let i=await Mi(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function OE(t,e,r,o,n,i){if(!Qc(e)&&!(e instanceof Uint8Array))throw new TypeError(Ha(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(KW(t,o),e instanceof Uint8Array&&TE(e,t.cekBits),t.cbc)return vOe(t,e,r,o,n,i);let s=await Mi(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Hn(r,n)))}catch{throw new Jc}}function Sy(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var wOe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],_Oe=[[],["deriveBits"]],zE=[[],[]];function DE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:wOe,ops:["wrapKey","unwrapKey"]}}function NE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:_Oe,ops:[void 0,"deriveBits"]}}function vf(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:zE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function sL(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:zE,ops:["deriveBits","deriveBits"]}}var Ba=Sy({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:zE,ops:["encrypt","decrypt"]},"RSA-OAEP":DE(1),"RSA-OAEP-256":DE(256),"RSA-OAEP-384":DE(384),"RSA-OAEP-512":DE(512),"ECDH-ES":NE("direct-key-agreement"),"ECDH-ES+A128KW":NE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":NE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":NE("key-agreement-with-key-wrapping"),A128KW:vf(128),A192KW:vf(192),A256KW:vf(256),A128GCMKW:vf(128,!0),A192GCMKW:vf(192,!0),A256GCMKW:vf(256,!0),"PBES2-HS256+A128KW":sL(),"PBES2-HS384+A192KW":sL(),"PBES2-HS512+A256KW":sL()}),bOe=["encrypt","decrypt"];function wf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:zE,ops:bOe,cekBits:t,ivBits:e?128:96,cbc:e}}var SOe=Sy({A128GCM:wf(128),A192GCM:wf(192),A256GCM:wf(256),"A128CBC-HS256":wf(256,!0),"A192CBC-HS384":wf(384,!0),"A256CBC-HS512":wf(512,!0)});function JW(t,e){throw new Ot(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Ui(t){return(typeof t=="string"?Ba[t]:void 0)??JW("alg","Algorithm")}function Li(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function od(t){return(typeof t=="string"?SOe[t]:void 0)??JW("enc","Encryption Algorithm")}function XW(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");nL(t,e)}async function xOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function EOe(t,e,r){let o=await Mi(e,Ui(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function QW(t,e,r){oL(e,Ui(t).subtle,r),gf(t,e)}async function e5(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=Hn(Qr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Mi(o,Ui(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function aL(t){return Hn(wE(t.length),t)}async function $Oe(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 _E("sha256",Hn(wE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function t5(t,e,r,o,n=new Uint8Array,i=new Uint8Array){XW(t),XW(e,"deriveBits");let s=Hn(aL(Qr(r)),aL(n),aL(i),wE(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 $Oe(a,o,s)}function r5(t){AE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ot("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ME(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 lo(r,e,H)}}function n5(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 ROe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function YW(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function IOe(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 o5(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return YW(o),r;let c=a==="direct-key-agreement";switch(c?YW(o):ROe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!vr(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(h=>Object.hasOwn(u,h)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');r5(r);let l=await yf(t,u),d=ME(n,"apu"),f=ME(n,"apv");n5(d,f);let p=await t5(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,f);if(c)return p;r=p;break}case"RSA-OAEP":return AE(r),QW(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');IOe(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=lo(n.p2s,"p2s",H);r=await e5(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=lo(n.iv,"iv",H),l=lo(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 OE(od(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return EOe(s.slice(-6),r,o)}async function UE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Li(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await zi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??nd(e):void 0;l&&TE(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{r5(u);let{apu:p,apv:h}=i;p!==void 0&&Io(p,'"apu"'),h!==void 0&&Io(h,'"apv"');let y=p??ME(o,"apu"),w=h??ME(o,"apv");n5(y,w);let b;i.epk!==void 0?b=await zi(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:R,y:T,crv:M,kty:Z}=await S.exportKey("jwk",x),te=a==="direct-key-agreement",Ie=await t5(u,b,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),Te={x:R,crv:M,kty:Z};if(Z==="EC"&&(Te.y=T),f={epk:Te},p!==void 0&&(f.apu=nr(p)),h!==void 0&&(f.apv=nr(h)),te)return[Ie,void 0,f];u=Ie;break}case"RSA-OAEP":{AE(u),QW(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:h=crypto.getRandomValues(new Uint8Array(16))}=i;u=await e5(h,s,p,u),f={p2c:p,p2s:nr(h)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let h=await CE(od(s.slice(0,-2)),l,u,p,new Uint8Array);d=h.ciphertext,f={iv:nr(h.iv),tag:nr(h.tag)}}}if(d??=await xOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,f]}function LE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ot('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function i5(t){if(typeof globalThis[t]>"u")throw new Ot(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function s5(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 Hn(...n)}async function a5(t){return i5("CompressionStream"),s5(new CompressionStream("deflate-raw"),t)}async function c5(t,e){return i5("DecompressionStream"),s5(new DecompressionStream("deflate-raw"),t,e)}function u5(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&&!vr(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 l5(t){let e,r;try{let{header:o}=t;if(vr(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function d5(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&&!vr(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 cL(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=hf(e,H,"JWE Protected Header is invalid")),[s,lo(r,"ciphertext",H),o!==void 0?lo(o,"iv",H):void 0,n!==void 0?lo(n,"tag",H):void 0,SE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function jE(t){return[t&&by("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&by("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function uL(t,e,r,o=cL(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Xc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,h,y,w,b]=e,{encrypted_key:S}=t;Yc(H,EE,y,n,f),LE(f,n);let{alg:x,enc:R}=f;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Ba[x];if(S===""&&(!T||!Li(T)))throw new H("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof R!="string"||!R))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(x)||!p&&x.startsWith("PBES2"))throw new ed('"alg" (Algorithm) Header Parameter value not allowed');let Z;if(M){if(R!==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(h&&!h.has(R))throw new ed('"enc" (Encryption Algorithm) Header Parameter value not allowed');Z=od(R)}let te;if(S!==void 0)try{te=lo(S,"encrypted_key",H)}catch(Fe){if(!T||!Li(T))throw Fe;te=new Uint8Array}let Ie=!1;typeof r=="function"&&(r=await r(n,t),Ie=!0);let Te=T??Ui(x);Li(Te)&&te===void 0&&(te=new Uint8Array);let bt=await zi(Te.mode==="direct-encryption"?Z:Te,r,"decrypt"),me;if(Te.mode==="integrated-encryption")me=await Te.decrypt(bt,te,i,c,n,f);else{let Fe=Z,se;try{se=await o5(Te,Fe,bt,te,f,w),Li(Te)&&se instanceof Uint8Array&&se.byteLength<<3!==Fe.cekBits&&(se=nd(Fe))}catch(tr){if(tr instanceof TypeError||tr instanceof H||tr instanceof Ot)throw tr;se=nd(Fe)}me=await OE(Fe,se,i,s,a,c)}if(f.zip==="DEF"){let Fe=b??25e4;if(Fe===0)throw new Ot('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Fe!==1/0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");me=await c5(me,Fe).catch(se=>{throw se instanceof H?se:new H("Failed to decompress plaintext",{cause:se})})}return{plaintext:me,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:lo(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ie&&{key:bt}}}async function p5(t,e,r){if(t instanceof Uint8Array&&(t=mf.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 uL({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function xy(t,e,r){return p5(t,jE(r),e)}async function lL(t,e,r){if(!vr(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(vr))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=jE(r),s=u5(t),a=cL(s)}catch{throw new Jc}let c=n.map(u=>l5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Ba[l]:void 0;if(d&&!Li(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 d5(l),await uL(l,i,e,a)}catch{}throw new Jc}function FE(t,e,r){if(!Xc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function dL(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&&Io(s,"JWE Additional Authenticated Data"),a!==void 0&&Io(a,"JWE Content Encryption Key"),c!==void 0&&Io(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=rd(H,o)[0],t[1]=o),n!==void 0&&(n=rd(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=rd(H,i)[0],t[3]=i),u!==void 0&&!vr(u))throw new TypeError("JWE Key Management Parameters must be an object");FE(o,n,i);let d={...o,...n,...i};$E(H,o),Yc(H,EE,l,o,d),LE(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=Ba[f];if(h?.mode==="integrated-encryption"){if(p!==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 ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,h]}if(typeof p!="string"||!p)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,od(p),h]}async function pL(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,h]=t,y=a,w=c,b=i??Ui(o.alg),S,x,R;b.mode==="integrated-encryption"?R=await zi(b,r,"encrypt"):[R,S,x]=await UE(b,n,r,o,d,p),x&&(h?w=w?{...w,...x}:x:y=y?{...y,...x}:x,FE(y,w,u));let T=y?nr(JSON.stringify(y)):"",M=l?.byteLength?nr(l):void 0,Z=Qr(M?`${T}.${M}`:T),te=s;o.zip==="DEF"&&(te=await a5(te).catch(Fe=>{throw new H("Failed to compress plaintext",{cause:Fe})}));let Ie,Te,bt;b.mode==="integrated-encryption"?[S,Ie]=await b.encrypt(R,te,Z,y,o,p):{ciphertext:Ie,tag:Te,iv:bt}=await CE(n,te,R,f,Z);let me={ciphertext:nr(Ie)};return bt&&(me.iv=nr(bt)),Te&&(me.tag=nr(Te)),S?.byteLength&&(me.encrypted_key=nr(S)),M&&(me.aad=M),y&&(me.protected=T),u&&(me.unprotected=u),w&&(me.header=w),me}async function f5(t,e,r){return pL(t,dL(t,r),e)}function m5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var fL=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Qo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Qo(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}},Ey=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new fL(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Qo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Qo(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");Io(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let h of this.#t){let[y,w,b,S]=h.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],R=dL(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,R,b]);let[{alg:T,enc:M},,Z]=R;if(e&&Z&&!Li(Z))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[,h]of i)h[2]??=Ui(h[0].alg);let[s,a,c]=i[0],u=e?nd(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await pL(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let h=1;h<i.length;h++){let[y,[w,b,S],x]=i[h],R=y[2],[,T,M]=await UE(S,b,x,w,u,y[7]),Z={encrypted_key:nr(T)};if(R||M){let te={...R,...M};M&&FE(y[1],te,y[3]),Z.header=te}p.recipients.push(Z)}return p}};var $y=[["verify"],["sign"]];function mL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:$y}}function _f(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:$y,minRsaBits:2048}}function hL(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:$y}}function h5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:$y}}function gL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:$y}}var yL=Sy({HS256:mL(256),HS384:mL(384),HS512:mL(512),RS256:_f(256),RS384:_f(384),RS512:_f(512),PS256:_f(256,32),PS384:_f(384,48),PS512:_f(512,64),ES256:hL("P-256",256),ES384:hL("P-384",384),ES512:hL("P-521",512),EdDSA:h5(),Ed25519:h5(),"ML-DSA-44":gL(44),"ML-DSA-65":gL(65),"ML-DSA-87":gL(87)});function qE(t){let e=typeof t=="string"?yL[t]:void 0;if(!e)throw new Ot(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function g5(t){return[t&&by("algorithms",t.algorithms),t?.crit]}function AOe(t){return t===void 0?{}:hf(t,Xt,"JWS Protected Header is invalid")}function POe(t){try{return Qr(t)}catch{throw new Xt("JWS Compact Serialization payload must use only ASCII characters")}}async function kOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??AOe(i);if(!Xc(c,s))throw new Xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=RE(c,Yc(Xt,xE,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 ed('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Xt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let h=qE(d),y=Hn(i!==void 0?Qr(i):new Uint8Array,Qr("."),typeof f=="string"?e[2]??=SE(f,"payload",Xt):f),w=lo(t.signature,"signature",Xt),b=await zi(h,r,"verify"),S=await Mi(b,h.subtle,"verify");h.minRsaBits&&gf(h.alg,S);let x=!1;try{x=await crypto.subtle.verify(h.signing,S,w,y)}catch{}if(!x)throw new bE;let R={payload:typeof f=="string"?lo(f,"payload",Xt):f};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),p?[{...R,key:b},l]:[R,l]}async function y5(t,e,r){if(t instanceof Uint8Array&&(t=mf.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 kOe({payload:n,protected:o,signature:i},e,r,POe)}async function vL(t,e,r){let[o]=await y5(t,g5(r),e);return o}var bf=class{#e;constructor(e){Io(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Qo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Qo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Qo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Qo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return m5(await f5([...this.#e],e,r))}};async function TOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=rd(Xt,n);n=b[0],a=nr(b[1])}if(i!==void 0&&(i=rd(Xt,i)[0]),!n&&!i)throw new Xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Xc(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=RE(n,Yc(Xt,xE,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=qE(l),f="",p=o,h;if(u){let b=t[4];b?(f=b[0]??=nr(o),p=b[1]??=Qr(f)):(f=nr(o),h=ff.encode(`${a}.${f}`))}h??=Hn(Qr(a),Qr("."),p);let y=await Mi(await zi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&gf(d.alg,y);let w={signature:nr(new Uint8Array(await crypto.subtle.sign(d.signing,y,h))),payload:f};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function v5(t,e,r,o,n){let[i]=await TOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Ry=class{#e;#t;constructor(e){Io(e,"payload"),this.#e=e}setProtectedHeader(e){return Qo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return v5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var wL='"alg" (Algorithm)';function _L(t='JWK "alg" (Algorithm) Parameter'){throw new Ot(`Invalid or unsupported ${t} value`)}function Iy(t,e){return(typeof t=="string"?yL[t]??Ba[t]:void 0)??_L(e)}async function eu(t){if(tL(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(!Qc(t))throw new TypeError(Ha(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 Ka=(t,e)=>{if(typeof t!="string"||!t)throw new _y(`${e} missing or invalid`)};async function bL(t,e){let r;if(vr(t)){if(r=PE(t),typeof r.kty!="string")throw new TypeError(Ha(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(rL(t))r=PE(await eu(t));else throw new TypeError(Ha(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":Ka(r.alg,'"alg" (Algorithm) Parameter'),Ka(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Ka(r.crv,'"crv" (Curve) Parameter'),Ka(r.x,'"x" (X Coordinate) Parameter'),Ka(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Ka(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Ka(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Ka(r.e,'"e" (Exponent) Parameter'),Ka(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 _y('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ot('"kty" (Key Type) Parameter missing or unsupported')}let n=Qr(JSON.stringify(o));return nr(await _E(e,n))}async function ei(t,e,r){if(!vr(t))throw new TypeError("JWK must be an object");let o=iL(t),n=kE(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 td(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 yf(Iy(e),o,n)}case"RSA":case"EC":case"OKP":return yf(Iy(e),o,n);default:throw new Ot('Unsupported "kty" (Key Type) Parameter value')}}function SL(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 hf(e,TypeError,r)}function COe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ot("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Ay(t,e){let r=kE(e?.extractable),o=Iy(t,wL);o.secret&&_L(wL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ot("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ot(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:COe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var S5=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),x5=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),w5=m.string().min(1).max(128),_5=m.string().min(1).max(16384),OOe=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:w5,secretAccessKey:_5}).strict(),m.object({kind:m.literal("session"),accessKeyId:w5,secretAccessKey:_5,sessionToken:m.string().min(1).max(16384),expiresAt:m.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),m.object({kind:m.literal("environment")}).strict()]),DOe=m.object({arn:x5,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Za=m.object({authentication:OOe,region:S5,role:DOe.optional()}).strict(),VE=m.object({accountId:m.string().regex(/^\d{12}$/),principalId:m.string().min(1).max(256),arn:m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),GE=Za.extend({sourceIdentity:VE.optional(),identity:VE.optional()}).strict();function Sf(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function b5(t){return{...t,arn:Sf(t.arn)}}function E5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:b5(t.sourceIdentity)}:{},...t.identity?{identity:b5(t.identity)}:{}}}var HE=m.object({authentication:m.enum(["access_key","session","environment"]),region:S5,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:x5.optional(),expiresAt:m.number().int().positive().optional()}).strict();function $5(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var R5=m.object({method:m.enum(["GET","POST","PUT","DELETE","PATCH"]),path:m.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),Py=m.object({account:m.string().min(1),identities:m.array(m.string()),user:m.string().nullable(),description:m.string().nullable(),roles:m.array(m.string()).nullable(),credentialId:m.number().int().positive(),rules:m.array(R5),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function I5(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return R5.parse({method:r[1],path:r[2]})})}typeof window<"u"&&m.config({jitless:!0});var E=m.uuid(),fe=m.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),Ae=m.iso.datetime(),wr=m.json(),Lt=m.record(m.string(),wr),A5=m.enum(["ja","en"]),P5=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var k5=m.enum(["variable","connection","service","method","app","object","environment","function"]),bn=m.object({kty:m.literal("EC"),crv:m.literal("P-256"),x:m.string().min(40).max(50),y:m.string().min(40).max(50)}).strict(),NOe=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:E}).strict(),WE=m.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 NOe.safeParse(SL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ao=m.object({protected:m.string().max(2048),iv:m.string().max(64),ciphertext:m.string().max(2e6),tag:m.string().max(64),aad:m.string().max(2048).optional(),recipients:m.array(m.object({encrypted_key:m.string().max(2048),header:m.object({kid:E,epk:bn.optional(),alg:m.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Dwt=m.object({id:E,name:fe,publicKey:bn}),tu=m.object({id:E,name:fe,owner:m.object({id:E,name:fe}).nullable(),createdAt:Ae,permissions:m.array(P5),createKinds:m.array(k5),publicKey:bn.nullable()}),T5=m.object({id:E,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:Ae,lastUsedAt:Ae.nullable(),expiresAt:Ae.nullable(),canOpen:m.boolean()}),C5=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),zOe=m.object({subjectId:E,relation:C5,objectId:E}).strict(),Nwt=zOe.extend({objectType:m.enum(["principal",...k5.options]),subjectName:fe,objectName:fe,createdAt:Ae}),zwt=m.object({error:m.object({code:m.string(),message:m.string(),details:wr.optional()})}),Mwt=m.object({ok:m.literal(!0)}),MOe=m.object({value:m.string().min(1).max(200),label:m.string().min(1).max(200),values:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).default({})}).strict(),JE=m.object({name:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:m.string(),secret:m.boolean().optional(),inputType:m.enum(["text","password"]).optional(),required:m.boolean().optional(),placeholder:m.string().optional(),note:m.string().optional(),pattern:m.string().optional(),choices:m.array(MOe).min(1).max(100).optional(),defaultValue:m.string().max(1e3).optional(),when:m.object({field:m.string(),values:m.array(m.string()).min(1)}).strict().optional(),visibility:m.enum(["application","connection"]).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."})}),XE=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),xL=m.object({values:m.array(m.object({id:m.string(),name:m.string(),description:m.string().optional()})).optional(),default:m.array(m.string()).default([]),required:m.array(m.string()).optional(),separator:m.string().default(" "),docs:m.url().optional()}),id=m.string().min(1).max(4096),KE=m.union([m.string(),m.array(m.string()).min(1)]),UOe=m.object({application:m.enum(["required","implicit"]).default("required"),grantType:m.enum(["authorization_code","client_credentials"]).optional(),issuer:m.url().optional(),registrationUrl:m.url().optional(),authorizeUrl:id.optional(),tokenUrl:id,identity:m.object({url:id.optional(),from:m.enum(["token","app"]).optional(),method:m.enum(["GET","POST"]).default("GET"),id:KE.default("/id"),name:KE.default("/name"),headers:m.record(m.string(),m.string()).default({})}).optional(),revoke:m.object({url:id,style:m.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:m.enum(["body","basic","none"]).optional()}).optional(),clientAuth:m.enum(["body","basic","none"]).default("body"),pkce:m.boolean().default(!0),tokenFormat:m.enum(["form","json"]).default("form"),okPointer:m.string().optional(),authorizeParams:m.record(m.string(),m.string()).default({}),tokenParams:m.record(m.string(),m.string()).default({}),defaults:m.record(m.string(),m.string()).default({}),scopes:xL.default({default:[],separator:" "}),fields:m.array(JE).default([]),outputs:XE.default({ACCESS_TOKEN:"/accessToken"}),adapter:m.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:m.array(m.string()).default([]),hint:m.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),LOe=m.object({fields:m.array(JE).min(1),outputs:XE,resolver:m.literal("vultr-role").optional(),bindFields:m.boolean().optional(),constants:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).optional(),identity:m.object({url:id,headers:m.record(m.string(),m.string()),id:KE,name:KE}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),EL=m.enum(["oauth","token","aws","ovh","approval"]),jOe=m.object({hint:m.string().optional()}).strict(),FOe=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:id,fields:m.array(JE).min(1),scopes:xL.default({default:[],separator:`
|
|
129
|
+
`}),outputs:XE,hint:m.string().optional()}).strict(),Cy={name:fe,docs:m.url().optional(),console:id.optional()},YE=m.object({...Cy,kind:m.literal("oauth"),config:UOe}).strict(),QE=m.object({...Cy,kind:m.literal("token"),config:LOe}).strict(),e$=m.object({...Cy,kind:m.literal("aws"),config:jOe}).strict(),t$=m.object({...Cy,kind:m.literal("ovh"),config:FOe}).strict(),r$=m.object({...Cy,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(JE).default([]),scopes:xL.default({default:[],separator:" "}),outputs:XE,hint:m.string().optional()}).strict()}).strict(),ru=m.discriminatedUnion("kind",[YE,QE,e$,t$,r$]),ky={id:m.string().min(1),builtin:m.boolean(),availability:m.enum(["ready","app-required","unavailable"]),defaultName:fe,registration:m.object({kind:m.enum(["input","authorization"]),device:m.enum(["browser","cli"]),browserExchange:m.enum(["available","unavailable","unknown"]),tokenAlternatives:m.array(m.string())}).strict()},Oy=m.discriminatedUnion("kind",[YE.extend(ky),QE.extend(ky),e$.extend(ky),t$.extend(ky),r$.extend(ky)]),Ty=m.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),$L=m.object({name:fe,logo:m.string().regex(/^[a-z0-9-]+$/).optional(),api:m.url().optional(),docs:m.url().optional(),console:m.url().optional(),targets:m.array(m.object({id:Ty,name:fe,api:m.url().optional(),methods:m.array(Ty).min(1)}).strict()).max(32).optional()}).strict(),qOe=$L.extend({methods:m.record(Ty,m.string().min(1))}).strict(),O5=$L.extend({methods:m.record(Ty,m.union([m.string().min(1),ru]))}).strict(),Uwt=$L.extend({id:m.string(),builtin:m.boolean(),methods:m.record(Ty,Oy)}),D5=m.object({id:E,output:m.string().min(1).max(100).optional()}).strict(),N5=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),RL=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:D5,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),VOe=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),D5])).min(1).max(32)}).strict(),Wa=m.object({url:m.string().max(4096),method:m.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:m.record(m.string(),m.string().max(8192)).default({}),body:m.string().max(1e6).optional(),json:wr.optional(),form:m.record(m.string(),m.string()).optional(),bindings:m.array(VOe).max(32).default([])}).strict(),Ja=m.object({command:m.array(m.string().max(8192)).min(1).max(100),stdin:m.string().max(1e6).optional(),timeoutSeconds:m.number().int().min(1).max(3600).default(60),inputs:m.array(RL).max(32).default([])}).strict(),z5=m.discriminatedUnion("kind",[Ja.omit({stdin:!0}).extend({kind:m.literal("command")}).strict(),m.object({kind:m.literal("http"),request:Wa}).strict()]),ti=m.object({description:m.string().max(2e3).default(""),environmentId:E,program:z5,parameters:m.array(m.object({name:m.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:m.string().max(100),type:m.enum(["string","number","boolean","json"]).default("string"),required:m.boolean().default(!0),default:wr.optional()}).strict()).max(32).default([]),result:m.enum(["text","json"]).default("json")}).strict(),nu={id:E,ownerId:E,name:fe,createdAt:Ae,updatedAt:Ae,version:m.number().int().positive(),permissions:m.array(P5)},GOe=m.enum(["starting","running","stopping","stopped","failed"]),HOe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),BOe=m.object({idleSeconds:m.number().int().min(60).max(86400).default(3600),maxSeconds:m.number().int().min(60).max(86400).default(3600)}).strict(),M5=m.object({image:m.string().min(1).max(300).optional(),size:m.enum(["small","medium","large"]).default("small"),lifetime:BOe.default({idleSeconds:3600,maxSeconds:3600}),ssh:wy.optional()}).strict(),IL={recipients:m.array(E).default([]),executors:m.array(E).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},KOe=m.object({...nu,kind:m.literal("variable"),data:m.object({...IL,bytes:m.number().int().nonnegative()})}),ZOe=m.object({...nu,kind:m.literal("connection"),data:m.object({...IL,methodId:m.string(),fields:m.record(m.string(),m.string()).default({}),settings:m.array(m.object({name:m.string(),label:m.string(),value:m.string()})).default([]),methodName:m.string(),methodKind:EL,services:m.array(m.object({id:m.string(),name:fe})).default([]),account:m.string(),accountId:m.string().nullable().default(null),accountVerified:m.boolean().default(!1),scopes:m.array(m.string()),scopesStatus:m.enum(["unknown","requested","reported"]).default("unknown"),outputs:m.array(m.string()),state:m.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:m.string().optional(),aws:HE.optional(),ovh:Py.optional()})}),WOe=m.object({...nu,kind:m.literal("service"),data:qOe}),JOe=m.object({...nu,kind:m.literal("method"),data:ru}),XOe=m.object({...nu,kind:m.literal("app"),data:m.object({...IL,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:E.optional()})}),YOe=m.object({...nu,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),QOe=m.object({...nu,kind:m.literal("environment"),data:M5.extend({executorId:E.optional(),operatorId:E.optional(),driver:m.enum(["attached","managed"]).optional(),capabilities:m.array(m.string()).optional(),isolation:m.enum(["process","container"]).optional(),manifestDigest:m.string().optional(),processes:m.object({workingDirectory:m.string()}).optional(),ssh:XU.optional(),awsPrincipal:m.string().optional(),state:GOe,connected:m.boolean(),deletion:HOe.optional(),startedAt:Ae.nullable(),stoppedAt:Ae.nullable(),lastActiveAt:Ae,error:m.string().nullable()})}),n$=m.object({...nu,kind:m.literal("function"),data:ti.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:z5.optional()})}),_r=m.discriminatedUnion("kind",[KOe,ZOe,WOe,JOe,XOe,YOe,QOe,n$]),Lwt=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:fe,definition:O5}).strict(),m.object({kind:m.literal("method"),name:fe,definition:ru}).strict(),m.object({kind:m.literal("environment"),name:fe.optional(),options:M5}).strict()]),jwt=m.object({version:m.number().int().positive(),name:fe.optional(),definition:m.union([O5,ru]).optional()}).strict(),ji=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Lt}).strict(),o$=ji.extend({inputs:m.array(m.object({pointer:m.string(),label:m.string().min(1).max(100),secret:m.boolean().default(!1),multiline:m.boolean().default(!1),site:m.url().optional()}).strict()).max(16).default([])}),ZE=m.object({ja:m.string(),en:m.string()}).strict(),AL=o$.extend({title:ZE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:ZE.nullable()}).strict()}),U5=m.object({to:E.optional(),executionId:E.optional(),message:m.string().max(1e3).default(""),operations:m.array(o$).min(1).max(8).optional(),expiresInMinutes:m.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."})}),BE=m.object({id:E,name:fe}),L5=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:BE,relation:C5,object:BE}),m.object({kind:m.literal("transfer"),item:BE,to:BE})]),i$=m.object({id:E,executionId:E,from:tu.pick({id:!0,name:!0}),to:tu.pick({id:!0,name:!0}).nullable(),message:m.string(),purpose:m.enum(["input","approval"]),state:m.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:Ae,expiresAt:Ae,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),Fwt=m.object({id:E,name:fe,publicKey:bn,state:m.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:Ae,expiresAt:Ae}),qwt=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:tu.pick({id:!0,name:!0}).nullable()}),Vwt=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),Gwt=m.object({id:m.string(),actorId:E.nullable(),action:m.string(),targetId:E.nullable(),createdAt:Ae,details:Lt}),Hwt=m.object({returnUrl:m.url().optional(),refreshUrl:m.url().optional()}).strict(),Mr=t=>m.object({items:m.array(t),next:m.string().nullable().default(null)}),Bwt=m.object({id:E}),Kwt=m.object({owner:E}),eDe=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),Zwt=eDe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var tDe=m.object({email:m.boolean(),environments:m.boolean(),ssh:m.boolean(),objects:m.boolean(),payments:m.boolean()}),s$=m.object({principal:tu.nullable(),credentialId:E.nullable(),wrappedKey:WE.nullable(),requestId:E.nullable(),server:m.object({name:fe}),features:tDe,principals:m.array(tu)}),Ywt=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:A5.default("ja"),principalId:E.optional()}).strict(),Qwt=m.object({intent:m.enum(["register","authenticate"]),name:fe.optional(),principalId:E.optional(),returnTo:m.string().max(2048).optional()}).strict(),e_t=m.object({challengeId:E,credential:m.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:WE.optional()}).strict();var rDe=new TextEncoder,nDe=new TextDecoder,Dy="ECDH-ES+A256KW",PL="A256GCM",tt=t=>rDe.encode(t),Po=t=>nDe.decode(t);function Os(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 j5(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function a$(){let t=await Ay(Dy,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await eu(t.publicKey)),privateKey:await eu(t.privateKey)}}async function Xa(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 Ey(t).setProtectedHeader({enc:PL}).setAdditionalAuthenticatedData(tt(r));for(let n of e)o.addRecipient(await ei(n.publicKey,Dy)).setUnprotectedHeader({alg:Dy,kid:n.id});return Ao.parse(await o.encrypt())}async function ko(t,e,r,o){if(t.aad!==Os(tt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await ei(e,Dy);return(await lL({...t,recipients:[n]},i,{keyManagementAlgorithms:[Dy],contentEncryptionAlgorithms:[PL]})).plaintext}async function oDe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:tt("Foundation"),info:tt("passkey encryption key")},e,256))}async function F5(t,e,r){let o=await xy(t,await oDe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[PL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Po(o.plaintext))}var br=m.string().regex(/^[A-Za-z0-9_-]{43}$/),Sr=m.string().min(100).max(4e6),q5=bn.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Ny=m.object({encryption:q5,signing:q5}).strict(),or=m.object({id:E,principalId:E,generation:m.number().int().positive(),previous:br.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function xf(t){return bL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function Q(t){return Os(new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t)))))}async function Ya(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function u$(){let[t,e]=await Promise.all([a$(),Ay("ES256",{crv:"P-256",extractable:!0})]),r=await eu(e.privateKey);return Ny.parse({encryption:t.privateKey,signing:r})}function c$(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function l$(t,e){return or.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:c$(e.encryption),signing:c$(e.signing)})}async function ur(t,e,r){let o=e instanceof CryptoKey?e:await ei(e,"ES256");return new Ry(tt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Ur(t,e,r,o){if(C(await kL(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function kL(t,e,r){let o=await vL(t,await ei(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 Ds=m.object({binding:or,signature:Sr}).strict();async function zy(t,e){if(await Ns(t),await xf(e.encryption)!==await xf(t.encryption)||await xf(e.signing)!==await xf(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 Ns(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 xf(e.encryption)===await xf(e.signing))throw new Error("Use separate encryption and signing keys.");await ei(e.encryption,"ECDH-ES+A256KW"),await ei(e.signing,"ES256")}async function d$(t){let{binding:e,signature:r}=Ds.parse(t);return await Ns(e),await Ur(e,r,e.signing,"key-binding"),e}var V5=m.object({ownerId:E,name:fe,resourceId:E.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(E).max(32).optional()}).strict(),G5=V5.extend({value:m.literal("").optional()}),TL=V5.extend({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}),Ef=m.object({ownerId:E,name:fe,definition:ti,resourceId:E.optional(),version:m.number().int().positive().optional()}).strict(),p$=m.object({ownerId:E,connectionId:E,environmentId:E}).strict(),H5=m.object({ownerId:E,connectionId:E,version:m.number().int().positive(),users:m.array(E).max(32),expiresAt:m.iso.datetime().optional()}).strict(),B5=m.object({ownerId:E,methodId:m.string().min(1).max(200),connectionId:E.optional(),name:fe.optional(),appId:E.optional(),redirectUri:m.url().optional(),users:m.array(E).max(32).optional(),scopes:m.array(m.string().min(1).max(1e3)).max(200).optional(),methodDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:m.string().max(1e3).optional(),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}).strict(),My=m.object({ownerId:E,environmentId:E.optional(),operation:m.union([m.object({kind:m.literal("http"),request:Wa}).strict(),Ja.extend({kind:m.literal("command")}),m.object({kind:m.enum(["http","command"]),programId:E,programDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:m.record(m.string(),fe).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),f$=m.object({name:ji.shape.name,title:ZE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:AL.shape.environment,input:Lt}).strict(),K5=m.object({id:E.optional(),operations:m.array(o$).min(1).max(8),responderId:E.optional(),message:m.string().max(1e3).default(""),expiresInMinutes:m.number().int().min(1).max(1440).default(1440)}).strict(),Z5=m.object({values:m.array(Lt).max(8).default([]),configuration:m.array(Lt).max(8).default([]),code:m.string().max(20).optional()}).strict(),$f=m.object({index:m.number().int().nonnegative(),invocation:ji,approval:m.object({id:E,index:m.number().int().nonnegative()}).strict().optional(),continuation:m.object({kind:m.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),Ze=m.object({id:E,actorId:E,ownerId:E,requests:m.array(E),steps:m.array(m.object({index:m.number().int().nonnegative(),name:ji.shape.name,state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:m.array(m.object({kind:m.enum(["run","function"]),id:E}).strict())}).strict()),creator:tu.pick({id:!0,name:!0}),operations:m.array(AL),approval:m.object({requestId:E.nullable(),proposal:L5.nullable()}).strict().nullable(),canContinue:m.boolean(),canCancel:m.boolean(),url:m.url(),code:m.string().optional(),error:m.object({code:m.string(),message:m.string()}).strict().nullable(),index:m.number().int().nonnegative(),state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:m.enum(["approval","input","execution"]).nullable(),waiting:$f.nullable(),results:m.array(wr.nullable()),createdAt:m.iso.datetime(),expiresAt:m.iso.datetime()}).strict(),W5=m.object({id:E,index:m.number().int().nonnegative(),invocation:ji,continuationId:E.optional()}).strict();var Rf=m.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"},iDe=m.enum([ge.value,ge.tokenSet,ge.clientCredential,ge.executionResult]),X5=t=>t===ge.executionResult?14e5:1e6,ue={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},Uy=m.enum([ue.http,ue.command,ue.function,ue.connect,ue.refresh,ue.revoke]);var sDe={[ge.value]:[ue.http,ue.command,ue.function],[ge.tokenSet]:[ue.http,ue.command,ue.function,ue.refresh,ue.revoke],[ge.clientCredential]:[ue.connect,ue.refresh,ue.revoke],[ge.executionResult]:[]},ou=t=>sDe[t],Y5=t=>ou(t).filter(e=>e===ue.function||e===ue.refresh),CL=t=>t===ge.tokenSet,aDe=m.object({id:E,digest:br}).strict(),cDe=m.object({actor:or,executor:or,operations:m.array(Uy).min(1).max(6),functionDigests:m.array(br).max(100).default([]),origins:m.array(Rf).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:Ae}).strict(),uDe=m.object({function:aDe,executor:or,operations:m.array(Uy).min(1).max(6),expiresAt:Ae}).strict(),lDe=m.union([cDe,uDe]),en=m.object({format:m.literal(2),origin:Rf,id:E,ownerId:E,contentType:iDe,revision:m.number().int().positive(),authorities:m.array(or).min(1).max(100),readers:m.array(or).min(1).max(100),grants:m.array(lDe).max(100),observers:m.array(E).max(100).optional(),producers:m.array(m.object({executor:or,runId:E,expiresAt:Ae,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),J5=m.object({ownerId:E,authorities:m.array(or).min(1).max(100)}).strict(),Q5=m.object({origin:Rf,id:E,revision:m.number().int().positive(),from:J5,to:J5,policyDigest:br,previous:br.nullable(),signerId:E}).strict(),dDe=Q5.extend({signature:Sr}),OL=m.array(dDe).max(16),Ly=m.object({policy:en,authorityId:E,signature:Sr,lineage:OL.optional()}).strict(),tn=m.object({policy:en,authorityId:E,authorization:Sr,lineage:OL.optional(),materialRevision:m.number().int().positive(),updatedAt:Ae,creationRunId:E.nullable(),metadata:Lt,sealed:Ao,signerId:E,signature:Sr}).strict(),sd=t=>({ownerId:t.ownerId,authorities:t.authorities});async function e8(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 Q(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 Ur(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(sd(t)))throw new Error("Use the authorities approved by the latest handoff.")}function DL(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 m$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(sd(t));return r===C(sd(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function t8(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(sd(t.policy))!==C(sd(e))){if(await To(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=Q5.parse({origin:e.origin,id:e.id,revision:e.revision,from:sd(t.policy),to:sd(e),policyDigest:await Q(e),previous:n.length?await Q(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ur(i,o.signing,"authority-handoff")})}return n.length?{lineage:OL.parse(n)}:{}}async function h$(t){let e=en.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Ns(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=>!ou(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ue.function&&i!==ue.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ue.http||i===ue.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ue.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function g$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function iu(t,e){return C({purpose:"resource",policyDigest:await Q(t),materialRevision:e})}async function If(t,e,r,o,n,i,s){if(t.byteLength>X5(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await h$(e),c=await t8(s,a,o,n);if(!a.authorities.some(f=>C(f)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Xa(t,g$(a).map(f=>({id:f.id,publicKey:f.encryption})),await iu(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ur(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===ge.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=tn.parse({...l,signature:await ur(l,n.signing,"resource")});return await To(d),d}async function To(t){let e=tn.parse(t),{signature:r,...o}=e;await h$(e.policy),await e8(e.policy,e.lineage);let n=DL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await Q(e.policy))throw new Error("The handoff approves a different access policy.");await Ur(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??(CL(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ue.refresh)&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Ur(o,r,s.signing,"resource");let a=g$(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!==Os(tt(await iu(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function r8(t,e,r,o,n=t.metadata){let i=await To(t);if(!CL(i.policy.contentType)||!(i.policy.authorities.some(f=>C(f)===C(r))||i.policy.grants.some(f=>C(f.executor)===C(r)&&f.operations.includes(ue.refresh)&&Date.parse(f.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Xa(e,g$(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await iu(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 To(d),d}async function y$(t,e,r,o){let n=await h$(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 t8(o,n,e,r),authorityId:e.id,signature:await ur(n,r.signing,"access-policy")};return await su(i),i}async function su(t){let e=Ly.parse(t);await h$(e.policy),await e8(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await Q(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 Ur(e.policy,e.signature,o.signing,"access-policy"),e}async function jy(t,e,r,o,n,i){let s=await su(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&C(f.executor)===C(o)&&(a.contentType===ge.executionResult||Date.parse(f.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>X5(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Xa(t,g$(a).map(f=>({id:f.id,publicKey:f.encryption})),await iu(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 To(d),d}async function ad(t,e,r){let o=await To(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return ko(o.sealed,r,e.id,await iu(o.policy,o.materialRevision))}var pDe=m.object({id:E,policyDigest:br,materialRevision:m.number().int().positive(),authorizationDigest:br.optional()}).strict();async function NL(t,e){return e.id===t.policy.id&&e.policyDigest===await Q(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||CL(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var v$=m.object({format:m.literal(2),id:E,origin:Rf,ownerId:E,approval:m.object({id:E,index:m.number().int().min(0).max(7)}).strict().optional(),operationContext:W5.optional(),actor:or,environmentId:E,executor:or,environmentDigest:br,operation:Uy,functionDigest:br.nullable(),functionId:E.optional(),operationDigest:br,sources:m.array(pDe).max(100),resultRecipients:m.array(or).min(1).max(100),resultApproval:Ly.optional(),createdAt:Ae,expiresAt:Ae}).strict(),Af=m.object({intent:v$,signature:Sr,sealed:Ao}).strict();async function cd(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await Q(t)})}async function n8(t,e,r){if(v$.parse(t),await Q(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Xa(tt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await cd(t,"input"))};return Af.parse({...o,signature:await ur(o,r.signing,"run")})}async function fDe(t,e=Date.now()){let r=Af.parse(t),{signature:o,...n}=r;await Ur(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 su(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!==Os(tt(await cd(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function o8(t,e,r){let o=await fDe(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await ko(o.sealed,r.encryption,e.id,await cd(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await Q(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function ud(t,e,r={}){let o=await To(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await NL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Date.parse(c.expiresAt)>(r.now??Date.now())&&Date.parse(c.expiresAt)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ue.function||e.operation===ue.refresh:e.operation===ue.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ue.command&&e.operation!==ue.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function au(t,e,r,o={}){return await ud(t,e,o),ko(t.sealed,r.encryption,e.executor.id,await iu(t.policy,t.materialRevision))}var zL=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),i8=m.object({format:m.literal(3),id:E,origin:Rf,ownerId:E,name:fe,executor:or,operatorId:E,driver:m.enum(["attached","managed"]),capabilities:m.array(Uy).min(1).max(6),functionVersion:m.number().int().positive().optional(),resultVersion:m.literal(1).optional(),isolation:m.enum(["process","container"]),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:zL.optional(),revision:m.number().int().positive()}).strict(),ML=m.object({manifest:i8,signature:Sr}).strict();async function UL(t,e){let r=i8.parse(t),o={manifest:r,signature:await ur(r,e.signing,"environment")};return await kf(o),o}async function kf(t){let e=ML.parse(t),{manifest:r}=e;if(await Ns(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ue.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(ue.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Ur(r,e.signature,r.executor.signing,"environment"),e}async function Tf(t,e){let{manifest:r}=await kf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await Q(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ue.function&&r.functionVersion!==2)throw new Error("This environment does not authorize the requested execution.")}var w$=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),_$=m.object({ok:m.boolean(),result:wr.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),s8={id:E,intentDigest:br,executorId:E,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:Ae},a8=m.object({...s8,sealed:Ao,signature:Sr}).strict(),c8=m.object({...s8,format:m.literal(2),accessDigest:br,proofDigest:br,approval:Ly,content:tn,previousDigest:br.optional(),previous:a8.optional(),signature:Sr}).strict(),Fy=m.union([a8,c8]),mDe=m.object({result:_$,proof:Sr}).strict(),u8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function LL(t,e,r,o,n,i){await su(n);let s={format:2,id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await Q(n),...i?{previousDigest:await Q(i)}:{}},a=await ur({...s,resultDigest:await Q(r)},o.signing,"execution-result"),c=tt(C({result:_$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Pf;let u=await jy(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await Q(a)},d=c8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ur(l,o.signing,"receipt")});return await jL(d,t),d}var Pf=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Cf(t,e,r,o){let n=_$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return LL(t,e,n,o,t.resultApproval);let i=tt(C(n));if(i.byteLength>14e5)throw new Pf;let s=await Xa(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await cd(t,"result")),a={id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Fy.parse({...a,signature:await ur(a,o.signing,"receipt")})}async function jL(t,e){let r=Fy.parse(t);if("content"in r){await Ur(u8(r),r.signature,e.executor.signing,"receipt");let i=await su(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.accessDigest!==await Q(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 Q(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await jL(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 To(r.content),!m$(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 Ur(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.sealed.aad!==Os(tt(await cd(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 l8(t,e,r,o){if(await jL(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 ko(t.content.sealed,o.encryption,r,await iu(t.content.policy,t.content.materialRevision)),a=mDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await Q(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=u8(t);if(await Ur({...u,resultDigest:await Q(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 ko(t.sealed,o.encryption,r,await cd(e,"result")),i=_$.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 hDe=m.enum(["http","command","function","connect","refresh","revoke"]),Bn=m.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:hDe,state:w$,intent:v$,requestSignature:Sr,receipt:Fy.nullable(),error:m.string().nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),b$=m.object({name:fe,approval:Ly}).strict(),d8=m.object({kind:m.literal("function"),functionId:E,definition:ti,arguments:Lt.default({}),outputs:m.record(m.string(),b$).default({})}).strict(),Qa=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:Wa,save:m.record(m.string(),b$).default({})}).strict(),m.object({kind:m.literal("command"),...Ja.shape}).strict(),m.object({kind:m.enum(["connect","refresh","revoke"]),input:wr}).strict()]);var cu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},ec=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=m.object({error:m.object({code:m.string(),message:m.string()})}).parse(await n.json())}catch{throw new cu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new cu(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",{},s$)}};import{chmod as gDe,lstat as yDe,mkdir as vDe,open as FL,readFile as f8,rename as wDe,rm as _De}from"node:fs/promises";import{dirname as bDe,join as qL,resolve as SDe}from"node:path";import{homedir as xDe}from"node:os";import{randomUUID as EDe}from"node:crypto";var VL=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:Ny.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."),m8=m.object({current:m.uuid(),identities:m.array(VL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function tc(){return qL(process.env.XDG_CONFIG_HOME||qL(xDe(),".config"),"foundation","identity.json")}function uu(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 S$(t){let e;try{let n=tc(),i=await yDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await gDe(n,384);let s=m8.parse(JSON.parse(await f8(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=uu(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==uu(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 VL.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!==uu(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 qy(t){let e=tc(),r;try{r=m8.parse(JSON.parse(await f8(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=VL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Of(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
130
130
|
`,!!r)}async function p8(t){if(process.platform==="win32")return;let e=await FL(t,"r");try{await e.sync()}finally{await e.close()}}async function Of(t,e,r){let o=SDe(t),n=bDe(o);if(await vDe(n,{recursive:!0,mode:448}),!r){let s=await FL(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await p8(n);return}let i=qL(n,".foundation-"+EDe());try{let s=await FL(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await wDe(i,o),await p8(n)}finally{await _De(i,{force:!0})}}import{spawn as ADe}from"node:child_process";import{chmod as PDe,mkdtemp as kDe,rm as TDe,writeFile as CDe}from"node:fs/promises";import{tmpdir as ODe}from"node:os";import{join as w8}from"node:path";import{StringDecoder as DDe}from"node:string_decoder";import{spawn as h8}from"node:child_process";import{mkdir as g8,mkdtemp as $De,rm as RDe,writeFile as y8}from"node:fs/promises";import{tmpdir as IDe}from"node:os";import{join as Vy}from"node:path";import{StringDecoder as v8}from"node:string_decoder";function Fi(t={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...t}}var Gy=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 $De(Vy(IDe(),"foundation-job-")),n=Vy(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 g8(n,{mode:448});let l={...e.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[f,p]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(f))throw new Error("Use valid file variable names.");await y8(Vy(n,f),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),l[f]=s?"/run/foundation/"+f:Vy(n,f)}let d=e.command;if(s){if(Object.entries(l).some(([h,y])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)||y.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let f=Object.entries(l).filter(([,h])=>/[\r\n]/.test(h)),p=Vy(o,"environment");await y8(p,Object.entries(l).filter(([,h])=>!/[\r\n]/.test(h)).map(([h,y])=>h+"="+y).join(`
|
|
131
131
|
`),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await g8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",p,...f.flatMap(([h,y])=>["--env",h+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(f=>{let p=h8(d[0],d.slice(1),{env:Fi(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),h={stdout:new v8("utf8"),stderr:new v8("utf8")},y=0,w=!1,b=(T,M)=>{let Z=Math.max(0,1e6-y);M.length>Z&&(c.truncated=!0);let te=M.subarray(0,Z);y+=te.length,c[T]+=h[T].write(te)};p.stdout.on("data",T=>b("stdout",T)),p.stderr.on("data",T=>b("stderr",T)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let S=()=>{u=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let R=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=h.stdout.end(),c.stderr+=h.stderr.end(),f())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),p.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",R()}),p.once("close",(T,M)=>{c.exitCode=T,c.signal=M,R()})}),c}finally{s&&u&&await new Promise(l=>{let d=h8("docker",["rm","-f",i],{env:Fi(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await RDe(o,{recursive:!0,force:!0})}}};function NDe(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 x$=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 DDe("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 _8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await kDe(w8(ODe(),"foundation-"));await PDe(r,448);try{let o=Fi(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=w8(r,i);await CDe(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=ADe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=NDe(n),u=new x$(c,h=>process.stdout.write(h)),l=new x$(c,h=>process.stderr.write(h));a.stdout.on("data",h=>u.write(h)),a.stderr.on("data",h=>l.write(h));let d=h=>{if(a.pid)try{process.platform==="win32"?a.kill(h):process.kill(-a.pid,h)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(h,y)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(h??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await TDe(r,{recursive:!0,force:!0})}}import{dirname as fHe,join as JV}from"node:path";function xr(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"ovh":{let r=t.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,fields:t.config.fields,outputs:Object.keys(t.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function qi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function lu(t){return xr(t).requiresApp}var zDe=new Set(["airtable.com","dash.cloudflare.com","api.ebay.com","accounts.secure.freee.co.jp","github.com","id.heroku.com","api.hubapi.com","api.netlify.com","api.notion.com","api.render.com","login.salesforce.com","cloud.digitalocean.com","api.vultr.com","api.x.com","zoom.us"]);function b8(t){if(t.kind==="approval")return"unavailable";if(!xr(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth")return"available";try{let e=new URL(t.config.tokenUrl).hostname;return zDe.has(e)||e==="login.microsoftonline.com"&&t.config.clientAuth!=="none"?"unavailable":t.config.tokenUrl.includes("{")?"unknown":"available"}catch{return"unknown"}}var MDe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),S8=Lt.refine(t=>Object.keys(t).every(e=>!MDe.has(e)),"Keep method-specific facts separate from common facts."),du=m.object({accountId:m.string().max(2e3).nullable(),accountName:m.string().max(2e3),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),authorization:S8,details:S8}).strict();function GL(t){if(t.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let e="requestedScopes"in t?t.requestedScopes:void 0;return du.parse({accountId:t.oauth?.account??"",accountName:t.oauth?.accountName??"",accountVerified:t.oauth?.accountVerified??!1,scopes:e??t.oauth?.scopes??[],scopesStatus:e?"requested":t.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function Df(t){if(t.method.kind!=="token"&&t.method.kind!=="approval"||!t.fields)throw new Error("Use input credential material.");return"facts"in t&&t.facts?du.parse(t.facts):du.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function HL(t){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let e="ovh"in t?t.ovh:void 0;if(!e){let r="requestedScopes"in t?t.requestedScopes:void 0;return du.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return du.parse({accountId:e.user?e.account+"/"+e.user:e.account,accountName:e.account+(e.user?" / "+e.user:""),accountVerified:!0,scopes:e.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:e},details:{ovh:e}})}function BL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return du.parse({accountId:t.aws.identity?Sf(t.aws.identity.arn):null,accountName:t.aws.identity?t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1):"",accountVerified:!!t.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:E5(t.aws)},details:{aws:$5(t.aws)}})}var UDe={oauth:GL,token:Df,aws:BL,ovh:HL,approval:Df};function Hy(t){return UDe[t.method.kind](t)}var aJ=Vt(G8(),1);var ic=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"}},uNe=class extends ic{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"}},lNe=class extends ic{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},dNe=class extends ic{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"}},pNe=class extends ic{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"}},fNe=class extends ic{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},mNe=class extends ic{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"}},hNe=class extends ic{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"}},D$=class extends ic{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},tj=class extends D${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"}},gNe=class extends D${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"}},yNe=class extends D${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"}},H8=class extends D${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},vNe=class extends ic{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"}},wNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},_Ne=class extends wNe{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"}},bNe=["","+",".","/",";","?","&","#"],Y8={"":{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}},SNe=new TextEncoder,B8="0123456789ABCDEF",K8=t=>mu(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),Wy=(t,e)=>t[e]==="%"&&e+2<t.length&&K8(t[e+1])&&K8(t[e+2]);function rj(t,e){let r=t[e];return r==null?0:mu(Q8,eJ,dd("_"))(r)?1:Wy(t,e)?3:0}function xNe(t,e){if(Wy(t,e))return 3;let{char:r,size:o}=Jy(t,e);return $Ne(r)?o:0}function Jy(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 sj=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Wy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=Jy(e,o);r+=mu(tJ,s=>t&&ENe(s))(n)?n:rJ(n),o+=i}return r};function Mf(t){let e="";for(let r=0;r<t.length;){if(Wy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=Jy(t,r);e+=tJ(o)?o:rJ(o),r+=n}return e}function Ky(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Wy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=Jy(t,n);r+=i,n+=s}return r}var Q8=t=>mu(En(65,90),En(97,122))(t.charCodeAt(0)),eJ=t=>En(48,57)(t.charCodeAt(0)),tJ=t=>mu(Q8,eJ,e=>"-._~".includes(e))(t),ENe=t=>":/?#[]@!$&'()*+,;=".includes(t),$Ne=t=>RNe(t.codePointAt(0)),RNe=t=>t!=null&&mu(dd(33),En(35,36),dd(38),En(40,59),dd(61),En(63,91),dd(93),dd(95),En(97,122),dd(126),INe,ANe)(t);function INe(t){if(t<65536)return mu(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 ANe=t=>mu(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),rJ=t=>Array.from(SNe.encode(t)).map(e=>`%${B8[e>>4]}${B8[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,dd=t=>e=>t===e,mu=(...t)=>e=>t.some(r=>r(e));function nJ(t,e,r){return t.map(o=>o.kind==="literal"?o.text:PNe(o.vars,o.operator,e,r)).join("")}function PNe(t,e,r,o){let n=Y8[e],i=t.flatMap(s=>kNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function kNe(t,e,r,o){if(e==null)return[];if(UNe(e)){let n=DNe(e,r.allowReserved);return n.length<1?[]:Z8(t,"list",o)?CNe(t,n,r):[]}if(MNe(e)){let n=NNe(e,r.allowReserved);return n.length<1?[]:Z8(t,"associative",o)?ONe(t,n,r):[]}return TNe(t,e,r)}function TNe(t,e,r){let o=String(e),n=t.prefix==null?o:Ky(o,t.prefix),i=sj(r.allowReserved)(n);return r.named?[Zy(Mf(t.name),i,r)]:[i]}function CNe(t,e,r){let o=Mf(t.name);if(t.explode)return r.named?e.map(i=>Zy(o,i,r)):[...e];let n=e.join(",");return r.named?[Zy(o,n,r)]:[n]}function ONe(t,e,r){if(t.explode)return e.map(([n,i])=>Zy(n,i,r));let o=e.flat(1).join(",");return r.named?[Zy(Mf(t.name),o,r)]:[o]}var Zy=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,DNe=(t,e)=>t.filter(r=>r!=null).map(String).map(sj(e)),NNe=(t,e)=>Object.entries(t).map(([r,o])=>[r,zNe(o)]).filter(([,r])=>r!=null).map(r=>r.map(sj(e)));function zNe(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 MNe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),UNe=t=>Array.isArray(t);function Z8(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new _Ne(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function LNe(t,e,r){return nj(t,e,r,0,0,{})}function nj(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=p1e(i);return nJ(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?nj(t,e,r,o+1,n+s.text.length,i):null;for(let a of jNe(t,e,o,n)){let c=e.slice(n,a);for(let u of qNe(s.vars,s.operator,c)){let l=aj(i,u);if(l==null)continue;let d=nj(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*jNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*FNe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*FNe(t,e){for(let r=t;r>=e;r--)yield r}function*qNe(t,e,r){if(r===""){yield*VNe(t,e);return}let o=Y8[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?YNe(t,o,n):GNe(t,o,n)}var VNe=(t,e)=>(e===""||e==="+")&&t.length===1?[fu(t[0],"")]:[{}],GNe=(t,e,r)=>oj(t,e,cj(r,e.sep),0,0);function*oj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of HNe(i,e,r,n))for(let a of oj(t,e,r,o+1,s.index)){let c=aj(s.bindings,a);c!=null&&(yield c)}yield*oj(t,e,r,o+1,n)}function*HNe(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 BNe(t,e,s))yield{bindings:a,index:o+i}}}function*BNe(t,e,r){let o=oJ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*KNe(t,e,r)),yield*o}function*KNe(t,e,r){let o=iJ(r,e.allowReserved);if(o==null)return;let n=ZNe(r,e);n!=null&&(yield fu(t,n)),yield fu(t,o)}var ZNe=(t,e)=>WNe(t.join(e.sep),e);function WNe(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=JNe(t,i,e.sep),a=oc(t.slice(o,n),e.allowReserved),c=oc(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 JNe(t,e,r){for(let o=e;o<t.length;o++)if(XNe(t,o,r))return o;return t.length}var XNe=(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*oJ(t,e,r){let o=oc(r,e.allowReserved);if(o==null)return;let n=fu(t,o);if(t.prefix!=null){yield n;return}let i=cj(r,",");if(i.length<2){yield n;return}let s=iJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?a1e(i,e.allowReserved):null;a!=null&&(yield fu(t,a)),yield fu(t,s),yield n}var YNe=(t,e,r)=>ij(t,e,cj(r,e.sep).map(s1e),0,0);function*ij(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of QNe(i,e,r,n,t))for(let a of ij(t,e,r,o+1,s.index)){let c=aj(s.bindings,a);c!=null&&(yield c)}yield*ij(t,e,r,o+1,n)}function*QNe(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*t1e(t,e,r,o,n);return}yield*e1e(t,e,r,o)}}function*e1e(t,e,r,o){let n=r[o];if(n.name===Mf(t.name))for(let i of oJ(t,e,n.value))yield{bindings:i,index:o+1}}function*t1e(t,e,r,o,n){yield*r1e(t,e,r,o),yield*o1e(t,e,r,o,n)}function*r1e(t,e,r,o){let n=[...n1e(Mf(t.name),e,r,o)];n.length>0&&(yield{bindings:fu(t,n),index:o+n.length})}function*n1e(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=oc(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*o1e(t,e,r,o,n){let i=[...i1e(e,r,o,new Set(n.map(s=>Mf(s.name))))];i.length>0&&(yield{bindings:fu(t,Object.fromEntries(i)),index:o+i.length})}function*i1e(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=oc(i.name,t.allowReserved),a=oc(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function s1e(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function a1e(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=oc(t[o],e),i=oc(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function iJ(t,e){let r=[];for(let o of t){let n=oc(o,e);if(n==null)return null;r.push(n)}return r}function oc(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var fu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function aj(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=c1e(i,n);if(s==null)return null;r[o]=s}return r}var c1e=(t,e)=>O$(t)||O$(e)?u1e(t,e):l1e(t.value,e.value)?t:null;function u1e(t,e){let r=W8(t.value),o=W8(e.value);if(r==null||o==null)return null;let n=O$(t),i=O$(e);if(!n&&!i)return null;if(n&&!i)return Ky(o,t.prefix)===r?e:null;if(!n&&i)return Ky(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Ky(o,s)===r?e:null:Ky(r,a)===o?t:null}var O$=t=>t.prefix!=null,W8=t=>typeof t=="string"?t:null;function l1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):J8(t)?J8(e)&&d1e(Object.entries(t),Object.entries(e)):t===e}var d1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),J8=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),p1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),cj=(t,e)=>e===""?[t]:t.split(e),f1e=["=",",","!","@","|"];function m1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new fNe(e,r));let n=t[0];if(v1e(n))return o(new mNe(e,r+1,n));if(!X8(n)&&rj(t,0)<1)return o(new hNe(e,r+1,n));let i=X8(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:h1e(t,e,r+1,s)}}function h1e(t,e,r,o){if(o>=t.length)throw new tj(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new H8(e,r+i):new tj(e,r+i);let s=i,a=g1e(t,i);if(a===s)throw new tj(e,r+i);let c=t.slice(s,a);i=a;let u=y1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new vNe(e,r+i,t[i]):new gNe(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 H8(e,r+i-1)}return n}function g1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=rj(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||rj(t,r+1)<1)break;r++,o=!0}return r}function y1e(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&&w1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new yNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function X8(t){return bNe.includes(t)&&t!==""}function v1e(t){return f1e.includes(t)}function w1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function _1e(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 uNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new dNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(m1e(f,t,i))}catch(p){r(p instanceof Error?p:new Error(String(p))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new lNe(t,i)),n(s),i++;continue}let a=xNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=Jy(t,i);r(new pNe(t,i,c)),n(c),i+=u}return o}var N$=class sJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=$1e(r),this.#e=b1e(_1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new sJ(e,r)}get tokens(){return this.#e}expand=e=>nJ(this.#e,e,this.#t);match=e=>LNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},b1e=t=>Object.freeze(t.map(S1e)),S1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(x1e))}),x1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),E1e=()=>{},$1e=({strict:t,report:e})=>(e??=E1e,t??=!0,e=t?R1e(e):e,{strict:t,report:e}),R1e=t=>e=>{throw t(e),e};var sc=class extends Error{constructor(r,o){super(o);this.code=r}code};function I1e(t,e){return!t.when||e[t.when.field]===void 0||t.when.values.includes(e[t.when.field])}function z$(t,e,r={}){let o=(i,s)=>{throw new sc(i,s)},n={...r,...e};for(let i of t)n[i.name]===void 0&&i.defaultValue!==void 0&&(n[i.name]=i.defaultValue);for(let i of t){if(!I1e(i,n)){delete n[i.name];continue}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,aJ.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 Ms(t,e,r={}){let o=z$(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 sc("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function M$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new sc("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new sc("encrypted_input_required","Supply private material directly with your encryption keys.")}return z$(t.map(r=>({...r,required:!1,defaultValue:void 0})),e)}function po(t,e){return M$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function Uf(t,e,r){M$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new sc("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}function cJ(t,e=Hy(t)){return e.accountVerified?e.accountId:null}function uJ(t,e=Hy(t)){let o=(t.method.kind==="oauth"||t.method.kind==="ovh"||t.method.kind==="token"&&!!(t.method.config.identity||t.method.config.resolver||t.method.config.bindFields))&&t.method.kind!=="aws"?po(t.method.config.fields,t.fields??{}):{};return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,..."implicitApp"in t&&t.implicitApp?{implicitApp:{clientId:t.implicitApp.clientId,generation:t.implicitApp.generation,fields:t.implicitApp.fields}}:{},account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...Object.keys(o).length?{fields:o}:{},...e.authorization,...t.state?{state:t.state}:{}}}var hu=m.record(m.string().max(100),m.string().max(16384)),Kn=m.object({format:m.literal(1),methodId:m.string().min(1),generation:E,clientId:m.string().max(1e3),clientSecret:m.string().max(16384).optional(),fields:hu}).strict(),uj=m.object({accessToken:m.string().min(1).max(16384),refreshToken:m.string().min(1).max(16384).optional(),expiresAt:m.number().nullable(),refreshExpiresAt:m.number().optional(),scopes:m.array(m.string()),requestedScopes:m.array(m.string()).optional(),account:m.string(),accountName:m.string(),accountVerified:m.boolean().optional(),scopesStatus:m.enum(["unknown","requested","reported"]).optional(),extra:hu,facts:Lt}).strict(),Xy={format:m.literal(2),methodId:m.string().min(1),method:ru,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:m.literal("reconnect").optional()},ac=m.never().optional(),$n=m.union([m.object({...Xy,method:YE,oauth:uj.optional(),requestedScopes:m.array(m.string()).optional(),implicitApp:Kn.optional(),fields:hu.optional(),aws:ac}).strict(),m.object({...Xy,method:QE,fields:hu,facts:du.optional(),oauth:ac,aws:ac}).strict(),m.object({...Xy,method:r$,fields:hu,oauth:ac,aws:ac}).strict(),m.object({...Xy,method:t$,fields:hu,ovh:Py.optional(),requestedScopes:m.array(m.string()).optional(),oauth:ac,aws:ac}).strict(),m.object({...Xy,method:e$,aws:GE,oauth:ac,fields:ac}).strict()]).superRefine((t,e)=>{if("implicitApp"in t&&t.implicitApp&&(t.method.kind!=="oauth"||t.method.config.application!=="implicit"||t.implicitApp.methodId!==t.methodId)&&e.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),t.method.kind==="oauth"&&t.fields)try{M$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}lu(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the application required by this connection."}),!lu(t.method)&&t.appId!==null&&e.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!("requestedScopes"in t&&t.requestedScopes)&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),Fbt=m.object({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),generation:E,fields:hu.optional()}).strict(),A1e=m.object({methodId:m.string().min(1).max(200),methodKind:EL,generation:E,authorizationDigest:br,appId:E.nullable(),accountId:m.string().max(2e3).nullable(),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),outputs:m.array(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:m.enum(["ready","reconnect"]),fields:hu.optional(),aws:HE.optional(),ovh:Py.optional()}).strict();async function Lf(t,e=Hy(t)){let r=xr(t.method).outputs,o=t.method.kind!=="aws"&&t.fields?po(t.method.config.fields,t.fields):{},n=await Q(uJ(t,e));return A1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:n,appId:t.appId,accountId:cJ(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 P1e=m.array(m.object({name:m.string(),label:m.string(),value:m.string()}).strict()),lJ=m.object({methodName:fe,account:m.string().max(2e3),settings:P1e.optional()}).strict();function U$(t){let e=xr(t.method).fields,r=t.method.kind!=="aws"&&t.fields?po(e,t.fields):{},o=e.filter(n=>r[n.name]).map(n=>({name:n.name,label:n.label,value:n.choices?.find(i=>i.value===r[n.name])?.label??r[n.name]}));return{methodName:t.method.name,account:"",...o.length?{settings:o}:{}}}var lj=m.discriminatedUnion("action",[m.object({action:m.literal("refresh"),id:E}).strict(),m.object({action:m.literal("revoke"),id:E}).strict()]);var dj=Ds.extend({name:fe}),Jbt=m.object({bootstrap:m.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ds,token:m.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),dJ=m.object({id:E,executorId:E,ownerId:E,name:fe,origin:m.url(),bootstrap:m.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:m.object({port:m.number().int().min(1).max(65535)}).strict().optional(),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),Xbt=Ds.extend({previousSignature:Sr.optional()}).strict(),pJ=m.object({name:fe,content:tn,labels:lJ.optional(),version:m.number().int().positive().optional()}).strict(),L$=m.object({content:tn,version:m.number().int().positive()}).strict(),fJ=m.object({id:E,reason:m.enum(["grantExpired","recipients"])}).strict(),Ybt=m.record(E,m.object({version:m.number().int().positive(),content:tn}).strict()),mJ=m.object({id:E,name:fe,version:m.number().int().positive(),content:tn,policy:en}).strict(),hJ=m.object({registration:ML,stoppedAt:m.iso.datetime().nullable(),heartbeatAt:m.iso.datetime().nullable()}).strict(),gJ=m.object({lease:E,request:Af,sources:m.array(tn).max(100)}).strict().nullable(),k1e=m.object({lease:E}).strict(),Qbt=k1e.extend({receipt:Fy}).strict(),Yy=m.object({id:E,resource_id:E,executor_id:E,expected_revision:m.number().int().positive(),state:m.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:m.string().regex(/^\d+$/),result:tn.nullable()}),eSt=m.object({id:E,resourceId:E,expectedRevision:m.number().int().positive()}).strict(),T1e=m.object({fence:m.string().regex(/^\d+$/)}).strict(),tSt=T1e.extend({content:tn}).strict(),rSt=m.object({id:E,executionId:E,index:m.number().int().nonnegative(),stateDigest:br,expiresAt:Ae}).strict(),pj=m.object({id:E,executionId:E,context:m.string(),sealed:Ao.nullable(),expiresAt:Ae,receivedAt:Ae.nullable()}).strict(),yJ=(t,e)=>"oauth-callback:"+t+":"+e;var Us=class extends Error{constructor(r,o){super(o);this.code=r}code},fj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},j$=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 Us("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",{},Ds);return await d$(r),{...r,fingerprint:await Ya(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new Us("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",{},hJ);if(await kf(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",{},Mr(dj));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:i,...s}of r)await d$(s),await this.trusted(s.binding);let o=await this.api.json("/api/principals/"+E.parse(e)+"/bound-agents",{},Mr(dj)),n=[];for(let{name:i,...s}of o.items){await d$(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof Us&&a.code==="identity_untrusted"))throw a}}return[...r.map(i=>i.binding),...n]}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},L$);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await To(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=DL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&en.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await Q(o)!==i.digest)throw new Us("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!m$(i.policy,o))throw new Us("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return ad((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Mr(mJ))).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 Us("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 If(await ad(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:[...ou(r)],origins:[],functionDigests:[],callerProgram:r!==ge.clientCredential,expiresAt:s});return en.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await If(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},_r);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await If(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}},m.union([_r,Ze]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Mr(fJ))).items}async reprotect(e,r="grantExpired"){let o=await this.read(e),{policy:n}=o.content,i=Date.now(),s=n.grants.filter(l=>Date.parse(l.expiresAt)>i),a=r==="recipients"?(await this.recipients(n.ownerId)).filter(l=>!n.readers.some(d=>d.id===l.id)):[];if(s.length===n.grants.length&&!a.length||n.producers.some(l=>Date.parse(l.expiresAt)>i))return null;let c=await this.api.json("/api/resources/"+n.id,{},_r),u=await ad(o.content,this.binding,this.keys.encryption);return this.save(c.name,u,{...n,revision:n.revision+1,grants:s,producers:[],readers:[...n.readers,...a],authorities:[...n.authorities,...a.filter(l=>!n.authorities.some(d=>d.id===l.id))]},{metadata:o.content.metadata,previous:o})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id,o.reason)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===ge.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Mr(_r));s=d.items.find(f=>f.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,ge.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await y$(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=Qa.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],f=await this.sourceContents([...d,...n.sourceIds??[]]);for(let w=0;w<f.length;w++){let b=f[w],S=b.policy.contentType===ge.clientCredential,x=S&&i.kind!=="revoke"?ue.refresh:ue[i.kind],R=S?void 0:l?new URL(l.url).origin:void 0;if(b.policy.grants.some(me=>"actor"in me&&C(me.actor)===C(this.binding)&&C(me.executor)===C(s.manifest.executor)&&me.operations.includes(x)&&Date.parse(me.expiresAt)>=Date.parse(c)&&(!R||!me.origins.length||me.origins.includes(R))&&(S||me.callerProgram))||!b.policy.authorities.some(me=>C(me)===C(this.binding)))continue;let M=await this.read(b.policy.id),Z=await this.api.json("/api/resources/"+b.policy.id,{},_r),te={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===ge.tokenSet?[ue.refresh]:[]])],origins:R?[R]:[],functionDigests:[],callerProgram:!S,expiresAt:c},Ie=me=>C({...me,expiresAt:null}),Te=M.content.policy.grants.filter(me=>Ie(me)===Ie(te)),bt=en.parse({...M.content.policy,revision:M.content.policy.revision+1,grants:[...M.content.policy.grants.filter(me=>Date.parse(me.expiresAt)>Date.now()&&Ie(me)!==Ie(te)),{...te,expiresAt:new Date(Math.max(Date.parse(c),...Te.map(me=>Date.parse(me.expiresAt)))).toISOString()}]});await this.save(Z.name,await ad(M.content,this.binding,this.keys.encryption),bt,{previous:M,metadata:M.content.metadata}),f[w]=(await this.read(b.policy.id)).content}let p=await this.policy(e,ge.executionResult,[],{id:a});p.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let h={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await Q(s.manifest),operation:ue[i.kind],operationDigest:await Q(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(f.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await Q(w.policy),...w.policy.contentType===ge.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:p.readers,...s.manifest.resultVersion?{resultApproval:await y$(p,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await Tf(s,h);let y=w=>w.policy.contentType===ge.clientCredential;for(let w of f)await ud(w,y(w)&&h.operation!==ue.connect&&h.operation!==ue.revoke?{...h,operation:ue.refresh}:h,y(w)?{}:{destination:l?.url});return n8(h,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},Bn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new fj(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,{},Bn);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 kL(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 Us("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?l8(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 Us("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 LL(e.intent,e.receipt.state,r,this.keys,await y$(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},Bn)}};import{lstat as C1e,mkdir as O1e,readFile as D1e,readdir as N1e}from"node:fs/promises";import{join as vJ}from"node:path";var wJ=m.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),pd=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:wJ.parse(e)})}async read(e){let r=this.context(e),o=vJ(this.directory,e+".json");try{let n=await C1e(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=m.string().max(32e6).parse(JSON.parse(await D1e(o,"utf8"))),s=await xy(i,await ei(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(Po(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await Ur({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await ur(n,this.privateKeys.signing,"journal"),s=tt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new bf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await ei(this.binding.encryption,"ECDH-ES+A256KW"));await O1e(this.directory,{recursive:!0,mode:448}),await Of(vJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await N1e(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=>wJ.parse(o.name.slice(0,-5)))}};var F$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Ns(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 Q(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 q(t,e,r,o){throw new dt(t,e,r,o)}var q$=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:{}},gJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.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}},Bn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},m.object({id:E}))}connections(){let e=this.api;return{prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Yy),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Yy),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},tn),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},Yy),state:r=>e.json("/api/connections/"+r+"/operation",{},Yy.nullable())}}};import{randomUUID as aHe}from"node:crypto";var bc=Vt(TV(),1);import{randomUUID as eGe}from"node:crypto";function nde(t){let e=VE.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)&&q(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&&Sf(t.arn)===Sf(e.arn)}function CV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&q(409,"reconnect_required","Reconnect with current AWS credentials.")}var uk=class{async obtain(e,r,o){let n=Za.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)}:{}};CV(s?.expiration);let a=new bc.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();CV(d.expiration),c=new bc.STSClient({region:n.region,credentials:d});let f=r?.sourceIdentity?nde(await c.send(new bc.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&f&&!ode(f,r.sourceIdentity)&&q(409,"account_changed","Reconnect to approve the current AWS authentication source.");let p=d,h=f;if(n.role){l=!0;let b=(await c.send(new bc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+eGe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&q(502,"invalid_response","AWS did not return credentials."),p={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},CV(p.expiration),r?.identity&&(c.destroy(),c=new bc.STSClient({region:n.region,credentials:p}),h=nde(await c.send(new bc.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&h&&!ode(h,r.identity)&&q(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:GE.parse({...n,sourceIdentity:f,identity:h}),credentials:{AWS_ACCESS_KEY_ID:p.accessKeyId,AWS_SECRET_ACCESS_KEY:p.secretAccessKey,AWS_SESSION_TOKEN:p.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&q(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&q(409,"reconnect_required","Reconnect with current AWS credentials."),l&&q(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),q(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var lk=class{constructor(e){this.aws=e}aws;facts=BL;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var OV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(OV="oauth4webapi/v3.8.8");function yk(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 Ea="ERR_INVALID_ARG_VALUE",Sc="ERR_INVALID_ARG_TYPE";function Or(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var ade=Symbol(),tGe=Symbol(),rGe=Symbol(),qV=Symbol();var dk=Symbol();var nGe=new TextEncoder,oGe=new TextDecoder;function DV(t){return typeof t=="string"?nGe.encode(t):oGe.decode(t)}var NV;Uint8Array.prototype.toBase64?NV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):NV=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 zV;Uint8Array.fromBase64?zV=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Or("The input to be decoded is not correctly encoded.",Ea,e)}}:zV=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw Or("The input to be decoded is not correctly encoded.",Ea,e)}};function MV(t){return typeof t=="string"?zV(t):NV(t)}var ch=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=zGe,Error.captureStackTrace?.(this,this.constructor)}},n_=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function De(t,e,r){return new n_(t,{code:e,cause:r})}function pk(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function cde(t){yk(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(OV&&!e.has("user-agent")&&e.set("user-agent",OV),e.has("authorization"))throw Or('"options.headers" must not include the "authorization" header name',Ea);return e}function iGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Or('"options.signal" must return or be an instance of AbortSignal',Sc);return e}}function fk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Or(`${r} must be a number`,Sc,n);if(t>0)return;if(e){if(t!==0)throw Or(`${r} must be a non-negative number`,Ea,n);return}throw Or(`${r} must be a positive number`,Ea,n)}catch(i){throw o?De(i.message,o,n):i}}function On(t,e,r,o){try{if(typeof t!="string")throw Or(`${e} must be a string`,Sc,o);if(t.length===0)throw Or(`${e} must not be empty`,Ea,o)}catch(n){throw r?De(n.message,r,o):n}}function ude(t){aGe(t,"application/json")}function sGe(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return De(r,UGe,t)}function aGe(t,e){if(bGe(t)!==e)throw sGe(t,e)}async function lde(t){return On(t,"codeVerifier"),MV(await crypto.subtle.digest("SHA-256",DV(t)))}function dde(t){let e=t?.[tGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function pde(t){let e=t?.[rGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function fde(){return Math.floor(Date.now()/1e3)}function lh(t){if(typeof t!="object"||t===null)throw Or('"as" must be an object',Sc);On(t.issuer,'"as.issuer"')}function dh(t){if(typeof t!="object"||t===null)throw Or('"client" must be an object',Sc);On(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 mde(t){return On(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function hde(t){return On(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 gde(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var cGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function uGe(t,e){if(e&&t.protocol!=="https:")throw De("only requests to HTTPS are allowed",jGe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw De("only HTTP and HTTPS requests are allowed",FGe,t)}function sde(t,e,r,o){let n;if(typeof t!="string"||!(n=cGe(t)))throw De(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?qGe:VGe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return uGe(n,o),n}function yde(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 UV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=NGe,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)}},o_=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=MGe,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)}},LV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=DGe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},mk="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",lGe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",dGe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',pGe="("+mk+")\\s*=\\s*"+dGe,fGe="("+mk+")\\s*=\\s*("+mk+")",mGe=new RegExp("^[,\\s]*("+mk+")"),hGe=new RegExp("^[,\\s]*"+pGe+"[,\\s]*(.*)"),gGe=new RegExp("^[,\\s]*"+fGe+"[,\\s]*(.*)"),yGe=new RegExp("^("+lGe+")(?:$|[,\\s])(.*)");function vGe(t){if(!yk(t,Response))throw Or('"response" must be an instance of Response',Sc);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(mGe),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let f,p;if(n=o.match(hGe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(gGe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(yGe)){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 wGe(t){if(t.status>399&&t.status<500){Dde(t),ude(t);try{let e=await t.clone().json();if(pk(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function vde(t,e,r){if(t.status!==e){xGe(t);let o;throw(o=await wGe(t))?(await t.body?.cancel(),new UV("server responded with an error in the response body",{cause:o,response:t})):De(`"response" is not a conform ${r} response (unexpected HTTP status code)`,LGe,t)}}function _Ge(t){if(!GV.has(t))throw Or('"options.DPoP" is not a valid DPoPHandle',Ea)}function bGe(t){return t.headers.get("content-type")?.split(";")[0]}async function wde(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?.[qV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:iGe(o,s?.signal)})}async function VV(t,e,r,o,n,i){let s=yde(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[ade]!==!0);n.set("grant_type",o);let a=cde(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(_Ge(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await wde(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function _de(t,e,r,o,n){lh(t),dh(e),On(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),VV(t,e,r,"refresh_token",i,n)}var bde=new WeakMap,SGe=new WeakMap;function Sde(t){if(!t.id_token)return;let e=bde.get(t);if(!e)throw Or('"ref" was already garbage collected or did not resolve from the proper sources',Ea);return e}async function vk(t,e,r,o,n,i){if(lh(t),dh(e),!yk(r,Response))throw Or('"response" must be an instance of Response',Sc);await vde(r,200,"Token Endpoint"),Dde(r);let s=await ZGe(r);if(On(s.access_token,'"response" body "access_token" property',Mt,{body:s}),On(s.token_type,'"response" body "token_type" property',Mt,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;fk(a,!0,'"response" body "expires_in" property',Mt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&On(s.refresh_token,'"response" body "refresh_token" property',Mt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw De('"response" body "scope" property must be a string',Mt,{body:s});if(s.id_token!==void 0){On(s.id_token,'"response" body "id_token" property',Mt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(fk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await PGe(t,e,s.id_token,a,n);TGe(e,c),kGe(c),SGe.set(r,u),bde.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 ch("unsupported `token_type` value",{cause:{body:s}});return s}function xGe(t){let e;if(e=vGe(t))throw new LV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function xde(t,e,r,o){return vk(t,e,r,void 0,o?.[dk],o?.recognizedTokenTypes)}function EGe(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw De('unexpected JWT "aud" (audience) claim value',uh,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw De('unexpected JWT "aud" (audience) claim value',uh,{expected:t,claims:e.claims,claim:"aud"});return e}function $Ge(t,e){let r=t[WGe]?.(e)??t.issuer;if(e.claims.iss!==r)throw De('unexpected JWT "iss" (issuer) claim value',uh,{expected:r,claims:e.claims,claim:"iss"});return e}var GV=new WeakSet;function RGe(t){return GV.add(t),t}var HV=Symbol();async function Ede(t,e,r,o,n,i,s){if(lh(t),dh(e),!GV.has(o))throw Or('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ea);On(n,'"redirectUri"');let a=Kd(o,"code");if(!a)throw De('no authorization code in "callbackParameters"',Mt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==HV&&(On(i,'"codeVerifier"'),c.set("code_verifier",i)),VV(t,e,r,"authorization_code",c,s)}var $de={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 IGe(t,e){for(let r of t)if(e.claims[r]===void 0)throw De(`JWT "${r}" (${$de[r]}) claim missing`,Mt,{claims:e.claims});return e}function AGe(t,e){if(typeof e.claims[t]!="string")throw De(`unexpected JWT "${t}" (${$de[t]}) claim type`,Mt,{claims:e.claims});return e}function PGe(t,e,r,o,n){return GGe(r,HGe.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),dde(e),pde(e),n).then(IGe.bind(void 0,["aud","exp","iat","iss","sub",...o])).then($Ge.bind(void 0,t)).then(EGe.bind(void 0,e.client_id)).then(AGe.bind(void 0,"sub"))}function Rde(t,e){if(e===gk)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?gk:(fk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function kGe(t){t.auth_time!==void 0&&fk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Mt,{claims:t})}function Ide(t,e,r){if(r===gk)return;let o=fde()+dde(t),n=pde(t);if(e.auth_time+r<o-n)throw De("too much time has elapsed since the last End-User authentication",FV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Ade(t,e){let r=e===hk?void 0:e;if(t.nonce!==r)throw De('unexpected ID Token "nonce" claim value',uh,{expected:r,claims:t,claim:"nonce"})}function TGe(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw De('ID Token "aud" (audience) claim includes additional untrusted audiences',uh,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw De('unexpected ID Token "azp" (authorized party) claim value',uh,{expected:t.client_id,claims:e,claim:"azp"})}}var hk=Symbol(),gk=Symbol();async function Pde(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?CGe(t,e,r,o.expectedNonce,o.maxAge,o[dk],o.recognizedTokenTypes):OGe(t,e,r,o?.maxAge,o?.[dk],o?.recognizedTokenTypes)}async function CGe(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=hk;break;case hk:break;default:On(o,'"expectedNonce" argument'),a.push("nonce")}n=Rde(e,n),n!==gk&&a.push("auth_time");let c=await vk(t,e,r,a,i,s);On(c.id_token,'"response" body "id_token" property',Mt,{body:c});let u=Sde(c);return Ide(e,u,n),Ade(u,o),c}async function OGe(t,e,r,o,n,i){let s=await vk(t,e,r,void 0,n,i),a=Sde(s);return a&&(Ide(e,a,Rde(e,o)),Ade(a,hk)),s}var DGe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",NGe="OAUTH_RESPONSE_BODY_ERROR",zGe="OAUTH_UNSUPPORTED_OPERATION",MGe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var jV="OAUTH_PARSE_ERROR",Mt="OAUTH_INVALID_RESPONSE";var UGe="OAUTH_RESPONSE_IS_NOT_JSON",LGe="OAUTH_RESPONSE_IS_NOT_CONFORM",jGe="OAUTH_HTTP_REQUEST_FORBIDDEN",FGe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",FV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",uh="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var qGe="OAUTH_MISSING_SERVER_METADATA",VGe="OAUTH_INVALID_SERVER_METADATA";async function kde(t,e,r,o,n){return lh(t),dh(e),VV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function Tde(t,e,r,o){return vk(t,e,r,void 0,o?.[dk],o?.recognizedTokenTypes)}async function Cde(t,e,r,o,n){lh(t),dh(e),On(o,'"token"');let i=yde(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[ade]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=cde(n?.headers);return a.delete("accept"),wde(t,e,r,i,s,a,n)}async function Ode(t){if(!yk(t,Response))throw Or('"response" must be an instance of Response',Sc);await vde(t,200,"Revocation Endpoint")}function Dde(t){if(t.bodyUsed)throw Or('"response" body has been used already',Ea)}async function GGe(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 ch("JWE decryption is not configured",{cause:t});if(a!==3)throw De("Invalid JWT",Mt,t);let c;try{c=JSON.parse(DV(MV(i)))}catch(d){throw De("failed to parse JWT Header body as base64url encoded JSON",jV,d)}if(!pk(c))throw De("JWT Header must be a top level object",Mt,t);if(e(c),c.crit!==void 0)throw new ch('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(DV(MV(s)))}catch(d){throw De("failed to parse JWT Payload body as base64url encoded JSON",jV,d)}if(!pk(u))throw De("JWT Payload must be a top level object",Mt,t);let l=fde()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw De('unexpected JWT "exp" (expiration time) claim type',Mt,{claims:u});if(u.exp<=l-o)throw De('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',FV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw De('unexpected JWT "iat" (issued at) claim type',Mt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw De('unexpected JWT "iss" (issuer) claim type',Mt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw De('unexpected JWT "nbf" (not before) claim type',Mt,{claims:u});if(u.nbf>l+o)throw De('unexpected JWT "nbf" (not before) claim value',FV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw De('unexpected JWT "aud" (audience) claim type',Mt,{claims:u});return{header:c,claims:u,jwt:t}}function HGe(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:r,reason:"default value"});return}throw De('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Kd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw De(`"${e}" parameter must be provided only once`,Mt);return r}var BGe=Symbol(),KGe=Symbol();function Nde(t,e,r,o){if(lh(t),dh(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Or('"parameters" must be an instance of URLSearchParams, or URL',Sc);if(Kd(r,"response"))throw De('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Mt,{parameters:r});let n=Kd(r,"iss"),i=Kd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw De('response parameter "iss" (issuer) missing',Mt,{parameters:r});if(n&&n!==t.issuer)throw De('unexpected "iss" (issuer) response parameter value',Mt,{expected:t.issuer,parameters:r});switch(o){case void 0:case KGe:if(i!==void 0)throw De('unexpected "state" response parameter encountered',Mt,{expected:void 0,parameters:r});break;case BGe:break;default:if(On(o,'"expectedState" argument'),i!==o)throw De(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Mt,{expected:o,parameters:r})}if(Kd(r,"error"))throw new o_("authorization response from the server is an error",{cause:r});let a=Kd(r,"id_token"),c=Kd(r,"token");if(a!==void 0||c!==void 0)throw new ch("implicit and hybrid flows are not supported");return RGe(new URLSearchParams(r))}async function ZGe(t,e=ude){let r;try{r=await t.json()}catch(o){throw e(t),De('failed to parse "response" body as JSON',jV,o)}if(!pk(r))throw De('"response" body must be a top level object',Mt,{body:r});return r}var WGe=Symbol();function i_(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 vo(t,e){for(let r of i_(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function BV(t,e,r){let o=i_(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 $a(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 cl(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}var ph=Vt(Mde(),1);var XGe=ph.default.IPv6.parseCIDR("2000::/3"),YGe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function bk(t){if(!ph.default.isValid(t)||t.includes("%"))return!1;let e=ph.default.parse(t);return YGe.has(e.range())&&(!(e instanceof ph.default.IPv6)||e.match(XGe))}function Ho(t,e){let r;try{r=new URL(t)}catch{q(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)&&q(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||ph.default.isValid(o)&&!bk(o))&&q(400,"private_destination","Choose a public HTTPS destination."),r}function gs(t){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.body))}catch{q(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&q(502,"invalid_response","The service returned an invalid response."),e}var _k=class{constructor(e){this.origin=e}origin;async send(e){let r=Ho(e.url,this.origin),o=e.maxBytes??1048576;e.body&&(typeof e.body=="string"?new TextEncoder().encode(e.body).length:e.body.length)>o&&q(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:e.method??"GET",headers:e.headers,body:typeof e.body=="string"?e.body:e.body?new Uint8Array(e.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]])})}catch{e.signal?.aborted&&q(409,"cancelled","The operation was cancelled."),q(409,"browser_exchange_unavailable","Restart authorization using the CLI on this device.")}let i=n.body?.getReader(),s=[],a=0;if(i)try{for(;;){let l=await i.read();if(l.done)break;a+=l.value.length,a>o&&q(413,"body_limit","The response body is too large."),s.push(l.value)}}finally{await i.cancel()}let c=new Uint8Array(a),u=0;for(let l of s)c.set(l,u),u+=l.length;return{status:n.status,headers:Object.fromEntries(n.headers),body:c}}};function KV(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Ude=Object.assign(Object.create(null),{dpop:()=>q(502,"invalid_response","The service returned an unsupported token.")}),QGe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Ude,{"user access token":()=>{}})},eHe={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"))&&q(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"},tHe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+KV(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},rHe={tokenParameters(t){let e=t.get("redirect_uri");e!==null&&(t.set("redirect_url",e),t.delete("redirect_uri"))}};function Ra(t,e){let r=e?new URL(e):void 0;return{recognizedTokenTypes:Ude,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...t.adapter==="ebay"?QGe:t.adapter==="openrouter"?eHe:t.adapter==="vultr"?rHe:{},...t.revoke?.style==="github"?tHe:{}}}function xc(t,e){try{return Ho(new N$(t).expand(e)).href}catch{q(400,"invalid_service_url","Check the service URL and its required fields.")}}var Lde=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],Sk=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&q(502,"invalid_response","The service returned an invalid expiry."),e};var Zd=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...Ms(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof sc&&q(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&q(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(xc(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:Ra(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await lde(n),c.code_challenge_method="S256"),Ra(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(xc(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:xc(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Ho(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?gde():(e.clientSecret||q(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?hde(e.clientSecret):mde(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[qV]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);e&&Ra(e).tokenParameters?.(c);let u=await this.transport.send({url:o,method:s,headers:r==="json"?{...i,"content-type":"application/json"}:i,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(e){return gs({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&vo(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&q(409,"reconnect_required","Reconnect this service to renew access."),r===429&&q(503,"service_rate_limit","The service is busy. Try again later."),q(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&q(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,Ra(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=Sk(u.expires_in));try{let d=await(n?xde:e.grantType==="client_credentials"?Tde:Pde)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:Ra(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;q(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[Ra(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&q(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+Sk(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&q(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?Lde(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()+Sk(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"&&q(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=Ra(e);if(l.exchange){let f=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>xc(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,f.status,gs(f))}else{let{server:f,client:p}=this.configuration(e,r),h;try{let y=Nde(f,p,o.parameters,o.state);h=await Ede(f,p,this.authentication(r,e.clientAuth),y,l.redirectUri?.(r,i)??i,e.pkce?n:HV,{...this.options(e),additionalParameters:e.tokenParams})}catch(y){throw(y instanceof n_||y instanceof o_)&&q(400,"invalid_state","Start the connection again."),y}u=await this.tokenResponse(e,r,h)}let d=this.token(e,u,s,a);return await c?.(d,u),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&q(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=Ra(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await kde(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e)),d=await this.tokenResponse(e,r,l),f={...this.token(e,d,o,n,!!n),requestedScopes:o};return await i?.(f,d),f}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||q(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())&&q(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await _de(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return i}async revoke(e,r,o){e.revoke||q(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=xc(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 Cde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Ode(d)}catch{q(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 "+KV(r.clientId,r.clientSecret??"")),(await this.transport.send(Ra(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&&q(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,$a(vo(n,s))]))}};function ZV(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function WV(t){return t||q(409,"app_required","Choose an OAuth application."),t}function nHe(t){return{token:uj.parse(t.token),response:Lt.parse(t.response)}}var xk=class{constructor(e){this.transport=e}transport;facts=GL;oauth(e){return new Zd({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(e){return!e.oauth||e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=e.material,o=ZV(r),n=WV(e.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>e.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(e.signal).clientCredentials(o,n,i??qi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return $n.parse({...e.material,oauth:a})}async recover(e,r,o){let i=nHe(o).token;return $n.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(ZV(e),WV(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(ZV(e),WV(r),e.oauth)}};function jde(t){if(t.method.kind!=="token"&&t.method.kind!=="approval")throw new Error("Use an input credential provider.");return t.method.config}var s_=class{facts=Df;needsRenewal(){return!1}async outputs(e){let r=jde(e),o=Ms(r.fields,e.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(jde(e).outputs).map(([n,i])=>[n,$a(vo(o,i))]))}};function Ek(t){if(t.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return t.method.config}var $k=class{facts=HL;values(e,r){let o=Ek(e),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&q(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:e.fields;return Ms(o.fields,i)}credentials(e,r){if(Ek(e).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:e.fields.consumerKey};let o=this.values(e,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(e,r){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o="ovh"in e?e.ovh:void 0;o&&o.expiresAt!==null&&o.expiresAt<=Date.now()&&q(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=Ek(e).authorization==="consumer_key"?{...this.values(e,r),...this.credentials(e,r)}:this.values(e,r);return Object.fromEntries(Object.entries(Ek(e).outputs).map(([i,s])=>[i,$a(vo(n,s))]))}};import{readFile as oHe}from"node:fs/promises";var iHe=m.object({accessToken:m.string().min(1).max(16384).regex(/^\S+$/),expiresAt:m.number().int().positive()}).strict();async function sHe(t,e){if(t==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await oHe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!i||i.length>16384)&&q(409,"authentication_required","Provide the current OIDC token to this executor."),i.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([e,AbortSignal.timeout(3e3)])});r.ok||q(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let o=(await r.text()).trim();return(!o||o.length>16384)&&q(502,"invalid_response","The instance did not return a valid identity token."),o}function Fde(t){if(t.method.kind!=="token"||t.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return t.method.config}var Rk=class{constructor(e,r=sHe){this.transport=e;this.identityToken=r}transport;identityToken;facts=Df;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(e,r){let o=Ms(Fde(e).fields,e.fields),n=o.authentication;["api_key","oidc","instance"].includes(n)||q(400,"invalid_field","Choose a Vultr authentication source.");let i=n==="api_key"?o.token:o.credential||await this.identityToken(n,r);(!i||i.length>16384||/\s/.test(i))&&q(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(o.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&q(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+i},signal:r,body:JSON.stringify({role_id:o.roleId,session_name:o.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:o.userId}:{},...n==="oidc"?{oidc_issuer_id:o.issuerId}:{}})});a.status>=400&&q(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=gs(a);(c.role_id!==void 0&&c.role_id!==o.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==o.userId)&&q(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=iHe.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&q(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(e,r,o){let n=Fde(e);o.throwIfAborted();let i=await Q(e),s=this.sessions.get(i);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(i);a||(a=this.obtain(e,o),this.pending.set(i,a));try{s=await a,this.sessions.set(i,s)}finally{this.pending.get(i)===a&&this.pending.delete(i)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,$a(vo(s,c))]))}};function qde(t,e){let r={oauth:new xk(t),token:new s_,aws:new lk(e),approval:new s_,ovh:new $k},o=new Rk(t);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?o:r[n.kind]}function Ia(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Ik(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!N5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=tt($a(vo(JSON.parse(Ia(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Ia(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var fh=class{constructor(e,r,o,n,i,s=new uk){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(e)}metadata(e){return Lf(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||q(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=$n.safeParse(JSON.parse(Ia(await au(e,r,this.keys,{destination:o}))));n.success||q(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&q(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==ue.revoke&&q(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=Kn.parse(JSON.parse(Ia(await au(i,o,this.keys))));return s.methodId!==r&&q(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(xr(e.method).application==="none")return null;if(!lu(e.method))return"implicitApp"in e&&e.implicitApp?e.implicitApp:Kn.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===ue.revoke?ue.revoke:ue.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&q(409,"app_changed","Reconnect this service with the current application."),xr(e.method).requiresApp&&e.method.kind!=="aws"&&Object.entries(po(e.method.config.fields,e.fields??{})).some(([s,a])=>i.fields[s]!==a)&&q(409,"app_changed","Reconnect this service with the current application settings."),i}async validate(e,r,o){let n=lj.parse(e);r.operation!==ue[n.action]&&q(400,"wrong_operation","Use the approved connection operation.");let i=await this.material(this.source(n.id,ge.tokenSet,o),r);await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=lj.parse(e);this.active.has(i.id)&&q(409,"connection_busy","Another operation is updating this connection."),this.active.add(i.id);try{n.throwIfAborted();let s=this.source(i.id,ge.tokenSet,o),a=await this.material(s,r);if(i.action==="refresh"){let u=await this.refresh(s,a,r,o,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(u)}}let c=this.provider(a.method);return c.revoke||q(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await c.revoke(a,await this.connectionApp(a,r,o),n),{kind:"revoked",id:s.policy.id}}finally{this.active.delete(i.id)}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&q(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&&q(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await r8(e.previous,tt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||q(409,"reconnect_required","Reconnect this service to renew access.");try{await ud(e,{...o,operation:ue.refresh},{destination:s})}catch{q(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=aHe(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let f=await a.renew({material:r,app:c,signal:i,receive:async p=>{d.checkpoint=p,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,f)}catch(f){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),f instanceof dt&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(f.code))throw f;q(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};import{lookup as cHe}from"node:dns/promises";import{request as uHe}from"node:https";import{brotliDecompressSync as lHe,gunzipSync as dHe,inflateSync as pHe}from"node:zlib";var mh=class{constructor(e){this.origin=e}origin;async send(e){let r=Ho(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&q(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))&&q(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await cHe(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!bk(u.address)))&&q(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,h,y)=>{h.all?y(null,[a]):y(null,a.address,a.family)}},f=uHe(r,d,p=>{let h=[],y=0;p.on("data",w=>{y+=w.length,y>n?p.destroy(new dt(413,"body_limit","The response body is too large.")):h.push(w)}),p.on("error",l),p.on("end",()=>{try{let w=Buffer.concat(h),b=p.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?dHe:b==="deflate"?pHe:b==="br"?lHe:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,R]of Object.entries(p.headers))R!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(R)?R.join(", "):R);u({status:p.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&q(409,"cancelled","The operation was cancelled."),q(502,"service_unavailable","The service could not be reached. Try again.")}}};function Dn(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=JV(fHe(tc()),"custody",r.id),i=new pd(JV(n,"client"),o,r,e),s=new j$(t,o,r,e,new F$(i)),a=new q$(t),c=new mh(o),u=new fh(r,e,a.connections(),new pd(JV(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 Vde(t,e){let{custody:r,keys:o,binding:n,connections:i}=Dn(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 Q(n),operation:ue.command,functionDigest:null,operationDigest:await Q(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await Q(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 Ik(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(l.policy.contentType===ge.value)return au(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return tt(d[u.output])})}import{mkdir as oot}from"node:fs/promises";import{join as eb}from"node:path";import{setTimeout as iot}from"node:timers/promises";function mHe(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 Ak(t,e){let r=mHe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Ja.parse({...l,stdin:JSON.stringify(r)})}}let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(f=>f.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,f)=>{if(!t.parameters.some(p=>p.name===f))throw new Error("Declare every function parameter.");return Object.hasOwn(r,f)?n(r[f]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,f])=>[d,i(f,l)])):u},s=new N$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Wa.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 Gde(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 Hde=m.object({operation:Qa,save:m.record(m.string(),fe)}).strict();function Pk(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function Bde(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=p$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=My.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 Q(Pk(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(Qa.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 hHe(t,e){return t.policy.contentType===ge.value?e.output===void 0:t.policy.contentType===ge.tokenSet&&e.output!==void 0}var Aa=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},kk=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 Cf(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Cf(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 Q(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let f=await Cf(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:f,delivered:!1}),await this.broker.finish(r.lease,f),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(f=>{f.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let f=await o8(r.request,this.binding,this.keys);await Tf(this.environment,f.intent);let p=Qa.parse(f.operation);if(ue[p.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await Bde(o,p),await this.validateOperation(p,o,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let h=await this.executeOperation(p,o,r.sources,c);d=await Cf(o,"succeeded",{ok:!0,result:h,error:null},this.keys)}catch(f){if(f instanceof Aa)throw f;f instanceof Pf&&(f=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let p=l&&(c.aborted||!(f instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(f.code));d=await Cf(o,p?"uncertain":"failed",{ok:!1,result:null,error:f instanceof dt?{code:f.code,message:f.message}:{code:p?"execution_uncertain":"invalid_execution",message:p?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?Ak(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 To(c);let u=r.sources.find(f=>f.id===c.policy.id);if(!u||!await NL(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 Q(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(ue[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Ho(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=i_(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.");BV(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(i_(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await su(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"?Ak(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||!hHe(u,c))throw new Error("Use the input named in the signed request.");await ud(u,r,{...n?{destination:n.url}:{}}),await au(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"?Ak(e.definition,e.arguments):e,a=[],c=new Map,u=async h=>{let y=o.find(b=>b.policy.id===h.id);if(y.policy.contentType===ge.value)return au(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(h.id)||c.set(h.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(h.id);if(!h.output||!Object.hasOwn(w,h.output))throw new Error("Choose an available connection output.");return tt(w[h.output])};if(s.kind==="command"){let h=await Ik(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:h.environment,files:h.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",cl(y.stderr,h.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,cl(y.stdout,h.sensitive))}return{...y,stdout:cl(y.stdout,h.sensitive),stderr:cl(y.stderr,h.sensitive)}}let l=structuredClone(i);for(let h of l.bindings){let y="";for(let w of h.parts)if(typeof w=="string")y+=w;else{let b=Ia(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}BV(l,h.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let f=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(f.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");return this.functionResult(e,r,cl(Ia(f.body),a))}let p=e.kind==="http"?e.save:{};if(Object.keys(p).length){if(f.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let h={};for(let[y,w]of Object.entries(p)){let b=f.body;if(y!==""){let x=vo(JSON.parse(Ia(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=tt(typeof x=="string"?x:JSON.stringify(x))}let S=await jy(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});h[w.name]=(await this.broker.capture(w.name,S)).id}return{status:f.status,saved:h}}return{status:f.status,headers:Object.fromEntries(Object.entries(f.headers).map(([h,y])=>[h,cl(y,a)])),body:cl(Ia(f.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:wr.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:vo(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=tt(typeof c=="string"?c:JSON.stringify(c)),l=await jy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};import{spawn as gHe}from"node:child_process";import{constants as XV}from"node:fs";import{open as Kde,rm as yHe}from"node:fs/promises";async function Zde(t){if(process.platform!=="linux"){let r=await Kde(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 yHe(t,{force:!0})}}let e=await Kde(t,XV.O_CREAT|XV.O_WRONLY|XV.O_NOFOLLOW,384);try{let r=gHe("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 ED=Vt(TV(),1),$D=Vt(A0e(),1);function P0e(t){return zL.safeParse(t).success?t:null}async function k0e(t=3e3){let e=new ED.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 ED.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=P0e(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 $D.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new $D.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=P0e(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 H3=m.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),B3=H3.max(4096).startsWith("/"),T0e=m.object({command:m.array(H3.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:B3.optional(),environment:m.record(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),H3.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:m.string().max(1e6).default(""),timeoutSeconds:m.number().int().min(1).max(3600).default(60)}).strict(),LKt=T0e.extend({id:E.optional()}),C0e=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),O0e=m.object({exitCode:m.number().int().nullable(),signal:m.string().max(32).nullable(),stdout:m.string().max(1e6),stderr:m.string().max(1e6),timedOut:m.boolean(),truncated:m.boolean()}).strict(),jKt=m.object({state:C0e.exclude(["queued","running"]),result:O0e.nullable(),error:m.string().max(100).nullable()}).strict(),RD=T0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:B3,state:C0e,result:O0e.nullable(),error:m.string().nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),FKt=RD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),qKt=m.object({workingDirectory:B3}).strict(),D0e=m.object({lease:E,process:RD}).strict().nullable();var ID=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},D0e)}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}},m.object({active:m.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},RD)}},AD=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 Aa}return!0}};var PD=m.object({format:m.literal(1),functionId:E,ownerId:E,revision:m.number().int().positive(),definition:ti,author:or,executor:or,createdAt:Ae,signature:Sr}).strict();async function N0e(t,e){return PD.parse({...t,signature:await ur(t,e.signing,"function-publication")})}async function z0e(t,e){let r=PD.parse(t),{signature:o,...n}=r;if(await Ns(n.author),await Ur(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 K3=m.object({functionId:E,publication:PD,contents:m.record(E,m.object({version:m.number().int().positive(),content:tn}).strict())}).strict(),Hnt=m.object({name:fe,definition:ti,authorization:K3}).strict(),QKt=Hnt.extend({version:m.number().int().positive()}),Bnt=m.object({id:E.optional(),ownerId:E.optional(),arguments:Lt.default({}),outputs:m.record(m.string().max(500),b$).default({})}).strict(),M0e=m.object({code:m.string().max(100),message:m.string().max(1e3)}).strict(),U0e=m.object({id:E,functionId:E,functionVersion:m.number().int().positive(),ownerId:E,actorId:E,state:w$,result:wr.nullable(),error:M0e.nullable(),createdAt:Ae,startedAt:Ae.nullable(),finishedAt:Ae.nullable()}).strict(),Knt=m.object({id:E,functionId:E,functionVersion:m.number().int().positive(),ownerId:E,actorId:E,actor:or.nullable(),arguments:Lt,outputs:Bnt.shape.outputs,definitionDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:Ae,expiresAt:Ae}).strict(),L0e=m.object({id:E,requestDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/),state:w$.exclude(["queued","running"]),result:wr.nullable(),error:M0e.nullable(),finishedAt:Ae,signature:Sr}).strict(),j0e=m.object({lease:E,request:Knt,publication:PD,sources:m.array(tn).max(100)}).strict().nullable();var kD=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:{}},j0e)}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}},m.object({active:m.boolean(),reason:m.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}},U0e)}},TD=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=L0e.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 Q(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),f=!1,p=!1,h=setInterval(()=>{p||(p=!0,this.broker.renew(o.id,s).then(y=>{y.active||(f||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{p=!1}))},this.renewalMilliseconds);h.unref();try{if(await z0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await Q(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 Q(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=d8.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 Q(this.executor.environment.manifest),operation:ue.function,operationDigest:await Q(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await Q(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 Tf(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let R=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(R)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",R,null)}catch(y){if(y instanceof Aa)throw y;let w=u.phase==="dispatched",b=d.aborted&&f?"cancelled":w&&(d.aborted||!(y instanceof dt))?"uncertain":"failed";await this.complete(u,b,null,!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="uncertain"?"execution_uncertain":b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="uncertain"?"Check the result before invoking this function again.":b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(h)}try{await this.deliver(u)}catch{throw new Aa}return!0}};import{spawn as Znt,execFile as Wnt}from"node:child_process";import{chmod as Jnt,lstat as F0e,mkdir as Z3,readFile as q0e,readdir as Xnt,realpath as V0e,rename as Ynt,rm as Qnt,symlink as eot,writeFile as G0e}from"node:fs/promises";import{join as yl}from"node:path";import{promisify as tot}from"node:util";import{createConnection as rot}from"node:net";import{setTimeout as not}from"node:timers/promises";var W3=tot(Wnt),Q_=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',CD=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=yl(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await Z3(this.options.directory,{recursive:!0,mode:448}),await Z3(this.sessions,{recursive:!0,mode:448}),await Z3(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await F0e(this.options.workspaceLink),await V0e(this.options.workspaceLink)!==await V0e(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 eot(this.options.workspace,this.options.workspaceLink)}let e=yl(this.options.directory,"host_ed25519");try{await F0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await W3("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:Fi(),timeout:1e4})}await Jnt(e,384),this.hostKey=vy.parse((await W3("ssh-keygen",["-y","-f",e],{env:Fi(),timeout:1e4})).stdout);let r=yl(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+Q_(e),"PidFile "+Q_(yl(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+Q_(yl(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 "+Q_("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+Q_("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
|
|
132
132
|
`)+`
|