@tomato414941/foundation 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.mjs +2 -2
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -125,7 +125,7 @@ ${c}`:c:"",l=Function,d=`return (input) => {
125
125
  ${c}
126
126
  }`,f;try{f=new l(...s,d)(...a)}catch(p){throw new Re(`this schema (generated code failed to evaluate: ${p.message})`)}return e?.debug&&(f.code=u),f.definite=o.definite,f}function ne(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 ou(t,e){return t.definite=!1,ne(t,e)}function ee(t){return`v${t.varCounter++}`}function ple(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return Gr;let o=r;return o.issues.length===0?o.value:Gr}function Cr(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return $t(t,e,r,o,n)}catch(u){if(!(u instanceof Re)||!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,mle(t,e,r,o)}}function mle(t,e,r,o){e.definite=!1;let n=ne(e,r),i=ne(e,ple),s=ee(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var hle=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function gle(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&&!hle.has(a.check))throw new Re('check with a custom "when" condition');switch(a.check){case"greater_than":yle(t,e,a,i);break;case"less_than":vle(t,e,a,i);break;case"multiple_of":wle(t,e,a,i);break;case"number_format":xF(t,a,i);break;case"min_length":{let c=ru(a.minimum,"min_length"),u=EP(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=ru(a.maximum,"max_length"),u=EP(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=ru(a.length,"length_equals"),u=EP(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 < ${ru(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${ru(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${ru(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=EF(t,e,a,i);break;case"custom":i=kle(t,e,s,i);break;case"bigint_format":ble(t,a,i);break;case"mime_type":_le(t,e,a,i);break;case"property":xle(t,e,a,i);break;case"properties":Sle(t,e,a,i);break;case"overwrite":{let c=ee(e);Ele(t,e,s,i,c),i=c;break}default:throw new Re(`check type ${a.check}`)}}return i}function EP(t,e,r,o){let n=ne(e,Xc),i=ee(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function ru(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Re(`${e} bound of type ${typeof t}`);return`${t}`}function SF(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Re("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Re("comparison check with Invalid Date bound");return ne(t,e)}throw new Re(`comparison check bound of type ${typeof e}`)}function yle(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${SF(e,r.value)}) return INVALID;`)}function vle(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${SF(e,r.value)}) return INVALID;`)}function wle(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Re("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ne(e,ym);t.write(`if (${n}(${o}, ${ru(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function xF(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 Re(`number format ${o}`)}}function ble(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 Re(`bigint format ${o}`)}}function _le(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=ne(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function Sle(t,e,r,o){if(r.when)throw new Re('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"?ne(e,i):Wr(i),a=ee(e);t.write(`const ${a} = ${o}[${s}];`),Cr(t,e,n[i],a,!1)}}function xle(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;$t(t,e,r.schema,n)}function Ele(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Re("overwrite check without a transform function");if(iu(i))throw new No("z.compile: async overwrite transforms are not supported");let s=ne(e,i);t.write(`const ${n} = ${s}(${o});`)}function kP(){throw new pn}function AP(t){this.issues.push(t)}function kle(t,e,r,o){let n=r._zod.def;if(n.fn){if(iu(n.fn))throw new No("z.compile: async .refine() predicates are not supported");let i=ou(e,n.fn),s=ne(e,kP),a=ee(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(iu(r._zod.check))throw new No("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=ou(e,u=>{let l={value:u,issues:[],addIssue:AP};return i(l)instanceof Promise&&kP(),l.issues.length===0?l.value:Gr}),c=ee(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Re("custom check without a predicate or check function")}var $le=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 EF(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ne(e,Om);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ne(e,cb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ne(e,hb),l=ne(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ne(e,Cm);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ne(e,ob);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ne(e,db);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ne(e,pb);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=ne(e,Bw),l=ne(e,r),d=ee(e),f=ee(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 g=ne(e,Hw);t.write(`if (!${g}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let g=ne(e,qw);t.write(`if (!${g}(${f}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let p=ee(e),m=s.normalize?`${f}.href`:`${ne(e,Rm)}(${d})`;return t.write(`const ${p} = ${m};`),p}let a=r.fn;if(a){if(iu(a))throw new Re(`async string format ${i}`);let u=ne(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if($le.has(i)&&r.pattern){let u=ne(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 Re("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(${Wr(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${Wr(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${Wr(u)}) return INVALID;`);break}default:throw new Re(`string format ${c}`)}return o}function $t(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Re(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=Ile(t,e,r,o,a);break;case"number":c=Ale(t,r,o);break;case"boolean":c=Tle(t,o);break;case"bigint":c=Ple(t,r,o);break;case"symbol":c=Rle(t,o);break;case"undefined":c=Cle(t,o);break;case"null":c=Ole(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=Nle(t,o);break;case"nan":c=Dle(t,o);break;case"date":c=zle(t,o);break;case"object":c=jle(t,e,r,o,a);break;case"optional":c=Mle(t,e,r,o,a);break;case"nullable":c=Fle(t,e,r,o,a);break;case"array":c=Vle(t,e,r,o,a);break;case"literal":c=Ble(t,e,r,o);break;case"enum":c=Hle(t,e,r,o);break;case"readonly":{let u=wF(t,e,r,o),l=ee(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":wF(t,e,r,o),c="true";break;case"default":case"prefault":c=qle(t,e,r,o);break;case"nonoptional":c=Zle(t,e,r,o);break;case"tuple":c=Kle(t,e,r,o);break;case"union":c=Wle(t,e,r,o);break;case"intersection":c=Xle(t,e,r,o);break;case"record":c=Yle(t,e,r,o);break;case"map":c=ede(t,e,r,o);break;case"set":c=tde(t,e,r,o);break;case"file":c=rde(t,o);break;case"template_literal":c=nde(t,e,r,o);break;case"lazy":c=ode(t,e,r,o);break;case"pipe":c=ide(t,e,r,o);break;case"custom":c=sde(t,e,r,o);break;case"transform":c=ude(t,e,r,o);break;case"catch":c=cde(t,e,r,o);break;default:throw new Re(`schema type ${s}`)}return c===null?null:gle(t,e,r,c)}function Ile(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:EF(t,e,i,o,n)}function Ale(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&&xF(t,{format:o.format},r),r}function Tle(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function Ple(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 Rle(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function Cle(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Ole(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function Nle(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Dle(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function zle(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function jle(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=b=>typeof b=="symbol"?ne(e,b):Wr(b),d=b=>typeof b=="symbol"?`[${l(b)}]`:Wr(b),f=s;if(a.includes("__proto__"))throw new Re('object shape key "__proto__"');let p=new Map;for(let b of u){let _=f[b],E=l(b),A=ee(e);if(t.write(`const ${A} = ${o}[${E}];`),_._zod.optin!==void 0){let z=ee(e);t.write(`let ${z} = (() => {`),t.indented(H=>{let te=Cr(H,e,_,A);H.write(`return ${te};`)}),t.write("})();"),_._zod.optout==="optional"?(t.write(`if (${z} === INVALID) {`),t.indented(H=>{H.write(`if (${E} in ${o}) return INVALID;`),H.write(`${z} = undefined;`)}),t.write("}")):t.write(`if (${z} === INVALID) return INVALID;`),p.set(b,z)}else{Lle(_)&&t.write(`if (!(${E} in ${o})) return INVALID;`);let z=Cr(t,e,_,A,n);z!==null&&p.set(b,z)}}let m=i.catchall,g="none";if(m){let b=m._zod.def.type;if(b==="never"){let _=a.map(E=>`k !== ${Wr(E)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(E=>{E.write(`if (${_}) return INVALID;`)}),t.write("}")}else(b==="unknown"||b==="any")&&!m._zod.def.checks?.length?g="passthrough":g="schema"}let v=ee(e),w=u.some(b=>vF(f[b])||$P(f[b]));if(!n){if(g==="schema"){let b=a.length>0?ne(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(_=>{_.write('if (k === "__proto__") continue;'),b&&_.write(`if (${b}.has(k)) continue;`);let E=ee(e);_.write(`const ${E} = ${o}[k];`),Cr(_,e,m,E,!1)}),t.write("}")}return null}if(w){t.write(`const ${v} = {};`);for(let b of u){let _=l(b),E=p.get(b);$P(f[b])?t.write(`if (${_} in ${o}) ${v}[${_}] = ${E};`):vF(f[b])?t.write(`if (${E} !== undefined || ${_} in ${o}) ${v}[${_}] = ${E};`):t.write(`${v}[${_}] = ${E};`)}}else{let b=u.map(_=>`${d(_)}: ${p.get(_)}`).join(", ");t.write(`const ${v} = { ${b} };`)}if(g!=="none"){let b=a.length>0?ne(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(_=>{if(_.write('if (k === "__proto__") continue;'),b&&_.write(`if (${b}.has(k)) continue;`),g==="passthrough")_.write(`${v}[k] = ${o}[k];`);else{let E=ee(e);_.write(`const ${E} = ${o}[k];`);let A=Cr(_,e,m,E);_.write(`${v}[k] = ${A};`)}}),t.write("}")}return v}function Mle(t,e,r,o,n=!0){let i=r._zod.def;if(Ule(r))return $t(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=ee(e),c=ee(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=$t(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=$t(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?ee(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=$t(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Ule(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function Lle(t){return t._zod.optin===void 0&&nu(t)}function nu(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?nu(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?nu(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(nu):!0;case"intersection":return!e.left||!e.right?!0:nu(e.left)&&nu(e.right);case"pipe":return e.in?nu(e.in):!0;default:return!0}}function $P(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function vF(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&od(t)}function od(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?od(e.innerType):!0;case"union":return e.options?e.options.some(od):!0;case"intersection":return!e.left||!e.right||od(e.left)||od(e.right);case"pipe":return e.out?od(e.out):!0;default:return!0}}function Fle(t,e,r,o,n=!0){let i=r._zod.def,s=n?ee(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=$t(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Vle(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?ee(e):null,a=ee(e),c=ee(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=Cr(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function Ble(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=ne(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=ne(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${Wr(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 Re(`literal type ${typeof s}`);return o}function Hle(t,e,r,o){let n=r._zod.values;if(!n)throw new Re("enum schema without enumerated values");let i=ne(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function wF(t,e,r,o){let n=r._zod.def;return $t(t,e,n.innerType,o)}function qle(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 $t(t,e,n.innerType,o);let c=ne(e,s),u=ee(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),$t(t,e,n.innerType,u)}let a=ee(e);if(s){let c=ne(e,s),u=ne(e,Ul);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=$t(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=$t(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function Zle(t,e,r,o){let n=r._zod.def,i=$t(t,e,n.innerType,o),s=ee(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function Kle(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=bF(i,"optin"),c=bF(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=ee(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(f=>{f.write(`if (${l} < ${o}.length) {`),f.indented(p=>{let m=ee(e);p.write(`const ${m} = ${o}[${l}];`);let g=Cr(p,e,d,m);p.write(`${u}[${l}] = ${g};`)}),f.write("} else {"),f.indented(p=>{if($P(d)){p.write(`${u}.length = ${l};`);return}let m=ee(e),g=ee(e);p.write(`const ${m} = undefined;`),p.write(`const ${g} = (() => {`),p.indented(v=>{let w=Cr(v,e,d,m);v.write(`return ${w};`)}),p.write("})();"),p.write(`if (${g} === INVALID || ${g} === undefined) ${u}.length = ${l};`),p.write(`else ${u}[${l}] = ${g};`)}),f.write("}")}),t.write("}");else{let f=ee(e);t.write(`const ${f} = ${o}[${l}];`);let p=Cr(t,e,d,f);t.write(`${u}[${l}] = ${p};`)}}if(s){let l=ee(e),d=ee(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(f=>{f.write(`const ${d} = ${o}[${l}];`);let p=Cr(f,e,s,d);f.write(`${u}[${l}] = ${p};`)}),t.write("}")}return u}function bF(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 Wle(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return Jle(t,e,n,o);if(n.inclusive===!1)throw new Re("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return $t(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=ne(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=ee(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=$t(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function Jle(t,e,r,o){if(r.unionFallback)throw new Re("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=ee(e),i=ee(e);t.write(`const ${n} = ${o}?.[${Wr(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 Re("discriminated union option without static discriminator values");for(let f of u){if(a.has(f))throw new Re(`duplicate discriminator value ${String(f)}`);a.add(f)}let l=Array.from(u,f=>Gle(e,n,f)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(f=>{let p=$t(f,e,c,o);f.write(`${i} = ${p};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function Gle(t,e,r){if(typeof r=="string")return`${e} === ${Wr(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=ne(t,r);return`${e} === ${o}`}throw new Re(`literal discriminator value ${String(r)}`)}function Xle(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=Cr(t,e,n.left,o),s=Cr(t,e,n.right,o),a=ne(e,Gl),c=ee(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function Yle(t,e,r,o){let n=r._zod.def,i=ne(e,Gn);t.write(`if (!${i}(${o})) return INVALID;`);let s=ee(e),a=ee(e),c=ee(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let p=[];for(let g of l){if(!(typeof g=="string"||typeof g=="number"||typeof g=="symbol"))throw new Re(`record key value ${String(g)}`);let v=typeof g=="number"?g.toString():g;if(v==="__proto__")throw new Re('record key "__proto__"');p.push(v);let w=ne(e,g),b=$t(t,e,n.keyType,w),_=ee(e);t.write(`const ${_} = ${o}[${Qle(e,v)}];`);let E=Cr(t,e,n.valueType,_);t.write(`${s}[${b}] = ${E};`)}let m=ne(e,new Set(p));return t.write(`for (const ${a} in ${o}) {`),t.indented(g=>{g.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?g.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):g.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let p=n.mode==="loose",m=d_(n.keyType);m.definite===!1&&(e.definite=!1);let g=ne(e,m),v=ne(e,Os),w=ee(e);return _F(t,e,o,a,b=>{b.write(`let ${w} = ${g}(${a});`),b.write(`if (${w} === INVALID && typeof ${a} === "string" && ${v}.test(${a})) ${w} = ${g}(Number(${a}));`),p?b.write(`if (${w} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):b.write(`if (${w} === INVALID) return INVALID;`),b.write(`if (${w} === "__proto__") continue;`);let _=ee(e);b.write(`const ${_} = ${o}[${a}];`);let E=Cr(b,e,n.valueType,_);b.write(`${s}[${w}] = ${E};`)}),s}return _F(t,e,o,a,p=>{p.write(`const ${c} = ${o}[${a}];`);let m=Cr(p,e,n.valueType,c);p.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function _F(t,e,r,o,n,i){let s=ne(e,Object.prototype.propertyIsEnumerable),a=ee(e),c=ee(e),u=ee(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 Qle(t,e){return typeof e=="string"?Wr(e):ne(t,e)}function ede(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=ee(e),s=ee(e),a=ee(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=$t(c,e,n.keyType,s),l=$t(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function tde(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=ee(e),s=ee(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=$t(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function rde(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function nde(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=ne(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function ode(t,e,r,o){let n=r._zod.def,i=ou(e,n.getter),s=ne(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=ee(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function ide(t,e,r,o){let n=r._zod.def,i=$t(t,e,n.in,o);if(n.transform){if(iu(n.transform))throw new No("z.compile: async transforms in pipes are not supported");let s=n.transform,c=ou(e,l=>{let d={value:l,issues:[],addIssue:AP},f=s(l,d);return f instanceof Promise?Gr:d.issues.length===0?f:Gr}),u=ee(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),$t(t,e,n.out,u)}else return $t(t,e,n.out,i)}function iu(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function sde(t,e,r,o){let n=r._zod.def;if(n.fn){if(iu(n.fn))throw new No("z.compile: async custom predicates are not supported");let i=ou(e,n.fn),s=ne(e,kP),a=ee(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Re("custom schema without a predicate function");return o}function ade(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return Gr;let n=o;return n.issues.length===0?n.value:e()}function cde(t,e,r,o){let n=r._zod.def;if(!n.catchValue[ww])throw new Re("catch with a callback (only a constant catch value compiles)",!1);let i=ee(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=Cr(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ne(e,n.innerType),a=ou(e,n.catchValue),c=ne(e,ade);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 ude(t,e,r,o){let n=r._zod.def;if(n.transform){if(iu(n.transform))throw new No("z.compile: async transforms are not supported");let i=n.transform,a=ou(e,u=>{let l={value:u,issues:[],addIssue:AP},d=i(u,l);return d instanceof Promise?Gr:l.issues.length===0?d:Gr}),c=ee(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function f_(t){return t.checks&&(t.checks=[...t.checks]),t}function p_(t,e){return new t(f_({type:"string",...N(e)}))}function TP(t,e){return new t(f_({type:"string",coerce:!0,...N(e)}))}function Hm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function qm(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function Zm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function Km(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function Wm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function Jm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function id(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function Gm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function Xm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function Ym(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function Qm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function eh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function th(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function rh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function nh(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function oh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function m_(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...N(e)})}function ih(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function sh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function ah(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function ch(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function uh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function h_(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...N(e)})}function g_(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...N(e)})}function lh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}var PP={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function dh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function fh(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function ph(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function mh(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function y_(t,e){return new t(f_({type:"number",checks:[],...N(e)}))}function RP(t,e){return new t(f_({type:"number",coerce:!0,checks:[],...N(e)}))}function v_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function w_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...N(e)})}function b_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...N(e)})}function __(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...N(e)})}function S_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...N(e)})}function x_(t,e){return new t({type:"boolean",...N(e)})}function CP(t,e){return new t({type:"boolean",coerce:!0,...N(e)})}function E_(t,e){return new t({type:"bigint",...N(e)})}function OP(t,e){return new t({type:"bigint",coerce:!0,...N(e)})}function k_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...N(e)})}function $_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...N(e)})}function I_(t,e){return new t({type:"symbol",...N(e)})}function A_(t,e){return new t({type:"undefined",...N(e)})}function T_(t,e){return new t({type:"null",...N(e)})}function P_(t){return new t({type:"any"})}function R_(t){return new t({type:"unknown"})}function C_(t,e){return new t({type:"never",...N(e)})}function O_(t,e){return new t({type:"void",...N(e)})}function N_(t,e){return new t({type:"date",...N(e)})}function NP(t,e){return new t({type:"date",coerce:!0,...N(e)})}function D_(t,e){return new t({type:"nan",...N(e)})}function $i(t,e){return new Ow({check:"less_than",...N(e),value:t,inclusive:!1})}function Pn(t,e){return new Ow({check:"less_than",...N(e),value:t,inclusive:!0})}function Ii(t,e){return new Nw({check:"greater_than",...N(e),value:t,inclusive:!1})}function Rn(t,e){return new Nw({check:"greater_than",...N(e),value:t,inclusive:!0})}function z_(t){return Ii(0,t)}function j_(t){return $i(0,t)}function M_(t){return Pn(0,t)}function U_(t){return Rn(0,t)}function ga(t,e){return new HT({check:"multiple_of",...N(e),value:t})}function ya(t,e){return new KT({check:"max_size",...N(e),maximum:t})}function Ai(t,e){return new WT({check:"min_size",...N(e),minimum:t})}function su(t,e){return new JT({check:"size_equals",...N(e),size:t})}function au(t,e){return new GT({check:"max_length",...N(e),maximum:t})}function Ns(t,e){return new XT({check:"min_length",...N(e),minimum:t})}function cu(t,e){return new YT({check:"length_equals",...N(e),length:t})}function sd(t,e){return new QT({check:"string_format",format:"regex",...N(e),pattern:t})}function ad(t){return new eP({check:"string_format",format:"lowercase",...N(t)})}function cd(t){return new tP({check:"string_format",format:"uppercase",...N(t)})}function ud(t,e){return new rP({check:"string_format",format:"includes",...N(e),includes:t})}function ld(t,e){return new nP({check:"string_format",format:"starts_with",...N(e),prefix:t})}function dd(t,e){return new oP({check:"string_format",format:"ends_with",...N(e),suffix:t})}function L_(t,e,r){return new iP({check:"property",property:t,schema:e,...N(r)})}function fd(t,e){return new sP({check:"properties",shape:t,...N(e)})}function pd(t,e){return new aP({check:"mime_type",mime:t,...N(e)})}function Do(t){return new cP({check:"overwrite",tx:t})}function md(t){return Do(e=>e.normalize(t))}function hd(){return Do(t=>t.trim())}function gd(){return Do(t=>t.toLowerCase())}function yd(){return Do(t=>t.toUpperCase())}function vd(){return Do(t=>qA(t))}function DP(t,e,r){return new t({type:"array",element:e,...N(r)})}function lde(t,e,r){return new t({type:"union",options:e,...N(r)})}function dde(t,e,r){return new t({type:"union",options:e,inclusive:!1,...N(r)})}function fde(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...N(o)})}function pde(t,e,r){return new t({type:"intersection",left:e,right:r})}function mde(t,e,r,o){let n=r instanceof ae,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...N(i)})}function hde(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...N(o)})}function gde(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...N(o)})}function yde(t,e,r){return new t({type:"set",valueType:e,...N(r)})}function vde(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...N(r)})}function wde(t,e,r){return new t({type:"enum",entries:e,...N(r)})}function bde(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...N(r)})}function F_(t,e){return new t({type:"file",...N(e)})}function _de(t,e){return new t({type:"transform",transform:e})}function Sde(t,e){return new t({type:"optional",innerType:e})}function xde(t,e){return new t({type:"nullable",innerType:e})}function Ede(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():Ul(r)}})}function kde(t,e,r){return new t({type:"nonoptional",innerType:e,...N(r)})}function $de(t,e){return new t({type:"success",innerType:e})}function Ide(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:YA(r)})}function Ade(t,e,r){return new t({type:"pipe",in:e,out:r})}function Tde(t,e){return new t({type:"readonly",innerType:e})}function Pde(t,e,r){return new t({type:"template_literal",parts:e,...N(r)})}function Rde(t,e){return new t({type:"lazy",getter:e})}function Cde(t,e){return new t({type:"promise",innerType:e})}function V_(t,e,r){let o=N(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function B_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...N(r)})}function H_(t,e){let r=kF(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Ll(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(Ll(i))}},t(o.value,o)),e);return r}function kF(t,e){let r=new nt({check:"custom",...N(e)});return r._zod.check=t,r}function q_(t){let e=new nt({check:"describe"});return e._zod.onattach=[r=>{let o=ur.get(r)??{};ur.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function Z_(t){let e=new nt({check:"meta"});return e._zod.onattach=[r=>{let o=ur.get(r)??{};ur.add(r,{...o,...t})}],e._zod.check=()=>{},e}function K_(t,e){let r=N(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??Ql,c=t.Boolean??Xl,u=t.String??ha,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),f=new a({type:"pipe",in:l,out:d,transform:((p,m)=>{let g=p;return r.case!=="sensitive"&&(g=g.toLowerCase()),i.has(g)?!0:s.has(g)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:f,continue:!1}),{})}),reverseTransform:((p,m)=>p===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function va(t,e,r,o={}){let n=N(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 hh(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&cr(t,o,r[o]);return t}function wa(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??ur,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 Kt(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 et(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),et(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&hh(s.schema,c),e.io==="input"&&Xr(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 $F(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ba(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(m=>m);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${$F(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+$F(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 TF(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;TF(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 PF=new Set(["type","properties","required","additionalProperties"]),IF=["oneOf","anyOf"];function AF(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function zP(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!PF.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]??AF(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:zP(a)??{allOf:a};cr(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=AF(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 Ode(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of PF)if(n in t)return;let r=e.filter(n=>IF.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=zP(e);else{let n=r[0],i=IF.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=>zP([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,hh(t,o))}function _a(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):hh(u,m),hh(u,l),a._zod.parent===d)for(let v in u)v==="$ref"||v==="allOf"||v in l||delete u[v];if(m.$ref&&p.def)for(let v in u)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(u[v])===JSON.stringify(p.def[v])&&delete u[v]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())TF(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)??[])Ode(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)}hh(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,cr(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:wd(e,"input",t.processors),output:wd(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Xr(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 Xr(o.element,r);if(o.type==="set")return Xr(o.valueType,r);if(o.type==="lazy")return Xr(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 Xr(o.innerType,r);if(o.type==="intersection")return Xr(o.left,r)||Xr(o.right,r);if(o.type==="record"||o.type==="map")return Xr(o.keyType,r)||Xr(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Xr(o.in,r)||Xr(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Xr(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Xr(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Xr(n,r))return!0;return!!(o.rest&&Xr(o.rest,r))}return!1}var jP=(t,e={})=>r=>{let o=wa({...r,processors:e});return et(t,o),ba(o,t),_a(o,t)},wd=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=wa({...n??{},target:i,io:e,processors:r});return et(t,s),ba(s,t),_a(s,t)};var bd=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},_d=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},RF=(t,e)=>{bd(t,"minimum",e),_d(t,"maximum",e)},DF=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},zF=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},jF=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},MF=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},CF=(t,e)=>bd(t,"minimum",e.minimum),OF=(t,e)=>_d(t,"maximum",e.maximum),NF=t=>(e,r)=>{MF(e,r.format);let[o,n]=t[r.format];bd(e,"minimum",o),_d(e,"maximum",n)},Nde={greater_than:(t,e)=>bd(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>_d(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>DF(t,e.value),number_format:NF(wm),bigint_format:NF(bm),min_length:CF,max_length:OF,length_equals:(t,e)=>RF(t,e.length),min_size:CF,max_size:OF,size_equals:(t,e)=>RF(t,e.size),string_format:(t,e)=>{MF(t,e.format),e.pattern&&zF(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)=>jF(t,e.mime)};function Wt(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)Nde[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&bd(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&bd(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&_d(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&_d(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&DF(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&jF(e,n.mime);for(let i of n.patterns??[])zF(e,i);return e}var Dde={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},zde=new Map([[sb,ET],[Nm,kT]]),UF=t=>zde.get(t)??t,LP=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Wt(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=Dde[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(UF);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}))])}},FP=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Wt(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let w of a)Number.isFinite(w)&&w!==0?m.add(Math.abs(w)):Kt(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[g,...v]=m;g!==void 0&&(n.multipleOf=g),v.length&&(n.allOf=[...n.allOf??[],...v.map(w=>({multipleOf:w}))])}},VP=(t,e,r,o)=>{r.type="boolean"},BP=(t,e,r,o)=>{Kt(t,e,r,o,"BigInt cannot be represented in JSON Schema")},HP=(t,e,r,o)=>{Kt(t,e,r,o,"Symbols cannot be represented in JSON Schema")},qP=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},ZP=(t,e,r,o)=>{Kt(t,e,r,o,"Undefined cannot be represented in JSON Schema")},KP=(t,e,r,o)=>{Kt(t,e,r,o,"Void cannot be represented in JSON Schema")},WP=(t,e,r,o)=>{r.not={}},JP=(t,e,r,o)=>{},GP=(t,e,r,o)=>{},XP=(t,e,r,o)=>{Kt(t,e,r,o,"Date cannot be represented in JSON Schema")},YP=(t,e,r,o)=>{let n=t._zod.def,i=Dl(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},QP=(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(Kt(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Kt(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},eR=(t,e,r,o)=>{Kt(t,e,r,o,"NaN cannot be represented in JSON Schema")},tR=(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},rR=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Wt(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})))},nR=(t,e,r,o)=>{r.type="boolean"},oR=(t,e,r,o)=>{Kt(t,e,r,o,"Custom types cannot be represented in JSON Schema")},iR=(t,e,r,o)=>{Kt(t,e,r,o,"Function types cannot be represented in JSON Schema")},sR=(t,e,r,o)=>{Kt(t,e,r,o,"Transforms cannot be represented in JSON Schema")},aR=(t,e,r,o)=>{Kt(t,e,r,o,"Map cannot be represented in JSON Schema")},cR=(t,e,r,o)=>{Kt(t,e,r,o,"Set cannot be represented in JSON Schema")},uR=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Wt(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=et(i.element,e,{...o,path:[...o.path,"items"]})};function gh(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?gh(e.out):e.type==="catch"?gh(e.innerType):t._zod.optin}var lR=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Kt(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)cr(n.properties,u,et(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"?gh(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=et(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},J_=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>et(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},dR=(t,e,r,o)=>{let n=t._zod.def,i=et(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=et(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)},fR=(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((g,v)=>et(g,e,{...o,path:[...o.path,s,v]})),u=i.rest?et(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 g=i.items[l-1];if(!(e.io==="input"?gh(g)!==void 0:g._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:m}=Wt(t);typeof p=="number"&&(n.minItems=p),typeof m=="number"&&(n.maxItems=m)};function MP(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let g=MP(t,m,r);return g===m?e:g}for(let m of["anyOf","oneOf"]){let g=e[m];if(!Array.isArray(g))continue;let v=g.map(w=>MP(t,w,r));v.some((w,b)=>w!==g[b])&&(e={...e,[m]:v})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Os:Im).source)),p}var UP=new WeakMap;function jde(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 UP.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=MP(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 pR=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Wt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=et(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)cr(n.patternProperties,UF(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=et(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=UP.get(e);l||(l=[],UP.set(e,l),e.deferred.push(()=>jde(e))),l.push(t)}n.additionalProperties=et(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&gh(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))}},mR=(t,e,r,o)=>{let n=t._zod.def,i=et(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"}]},hR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},gR=Symbol();function LF(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Kt(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),gR):JSON.parse(s)}var yR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=LF(n.defaultValue,t,e,r,o);s!==gR&&(r.default=s)},vR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=LF(n.defaultValue,t,e,r,o);s!==gR&&(r._prefault=s)},wR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Kt(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},bR=(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;et(s,e,o);let a=e.seen.get(t);a.ref=s},_R=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},SR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},G_=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},xR=(t,e,r,o)=>{let n=t._zod.innerType;et(n,e,o);let i=e.seen.get(t);i.ref=n},W_={string:LP,number:FP,boolean:VP,bigint:BP,symbol:HP,null:qP,undefined:ZP,void:KP,never:WP,any:JP,unknown:GP,date:XP,enum:YP,literal:QP,nan:eR,template_literal:tR,file:rR,success:nR,custom:oR,function:iR,transform:sR,map:aR,set:cR,array:uR,object:lR,union:J_,intersection:dR,tuple:fR,record:pR,nullable:mR,nonoptional:hR,default:yR,prefault:vR,catch:wR,pipe:bR,readonly:_R,promise:SR,optional:G_,lazy:xR};function uu(t,e){if("_idmap"in t){let o=t,n=wa({...e,processors:W_}),i={};for(let c of o._idmap.entries()){let[u,l]=c;et(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;ba(n,l),cr(s,u,_a(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=wa({...e,processors:W_});return et(t,r),ba(r,t),_a(r,t)}var X_=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=wa({processors:W_,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 et(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,ba(this.ctx,e);let o=_a(this.ctx,e),{"~standard":n,...i}=o;return i}};var FF={};var Td={};gt(Td,{ZodAny:()=>VR,ZodArray:()=>ZR,ZodBase64:()=>gS,ZodBase64URL:()=>yS,ZodBigInt:()=>Id,ZodBigIntFormat:()=>bS,ZodBoolean:()=>$d,ZodCIDRv4:()=>mS,ZodCIDRv6:()=>hS,ZodCUID:()=>aS,ZodCUID2:()=>cS,ZodCatch:()=>dC,ZodCodec:()=>kh,ZodCreditCard:()=>jR,ZodCustom:()=>$h,ZodCustomStringFormat:()=>du,ZodDate:()=>bh,ZodDefault:()=>iC,ZodDiscriminatedUnion:()=>WR,ZodE164:()=>vS,ZodEmail:()=>nS,ZodEmoji:()=>iS,ZodEnum:()=>xd,ZodExactOptional:()=>xS,ZodFile:()=>tC,ZodFunction:()=>_C,ZodGUID:()=>oS,ZodIBAN:()=>MR,ZodIPv4:()=>fS,ZodIPv6:()=>pS,ZodISODate:()=>xa,ZodISODateTime:()=>Sa,ZodISODuration:()=>ka,ZodISOTime:()=>Ea,ZodInstanceOf:()=>EC,ZodIntersection:()=>JR,ZodJWT:()=>wS,ZodKSUID:()=>dS,ZodLazy:()=>vC,ZodLiteral:()=>eC,ZodMAC:()=>zR,ZodMap:()=>YR,ZodNaN:()=>pC,ZodNanoID:()=>sS,ZodNever:()=>HR,ZodNonOptional:()=>ES,ZodNull:()=>FR,ZodNullable:()=>oC,ZodNumber:()=>kd,ZodNumberFormat:()=>fu,ZodObject:()=>_h,ZodOptional:()=>pu,ZodPipe:()=>Eh,ZodPrefault:()=>aC,ZodPreprocess:()=>mC,ZodPromise:()=>bC,ZodReadonly:()=>hC,ZodRecord:()=>Sd,ZodSet:()=>QR,ZodString:()=>Ed,ZodStringFormat:()=>it,ZodSuccess:()=>lC,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>yC,ZodTransform:()=>rC,ZodTuple:()=>GR,ZodType:()=>ve,ZodULID:()=>uS,ZodURL:()=>vh,ZodUUID:()=>Ti,ZodUndefined:()=>LR,ZodUnion:()=>Sh,ZodUnknown:()=>BR,ZodVoid:()=>qR,ZodXID:()=>lS,ZodXor:()=>KR,_ZodString:()=>rS,_default:()=>sC,_function:()=>JV,any:()=>PV,array:()=>Ae,base64:()=>lV,base64url:()=>dV,bigint:()=>kV,boolean:()=>Mt,catch:()=>fC,check:()=>GV,cidrv4:()=>cV,cidrv6:()=>uV,codec:()=>qV,creditCard:()=>pV,cuid:()=>eV,cuid2:()=>tV,currencyCode:()=>wV,custom:()=>kS,date:()=>CV,describe:()=>XV,discriminatedUnion:()=>xh,e164:()=>fV,email:()=>HF,emoji:()=>YF,enum:()=>dr,exactOptional:()=>nC,file:()=>FV,float32:()=>_V,float64:()=>SV,function:()=>JV,guid:()=>qF,hash:()=>bV,hex:()=>vV,hostname:()=>yV,httpUrl:()=>XF,iban:()=>mV,instanceof:()=>QV,int:()=>eS,int32:()=>xV,int64:()=>$V,intersection:()=>Ad,invertCodec:()=>ZV,ipv4:()=>iV,ipv6:()=>aV,json:()=>tB,jwt:()=>hV,keyof:()=>OV,ksuid:()=>oV,lazy:()=>wC,literal:()=>G,looseObject:()=>lr,looseRecord:()=>jV,mac:()=>sV,map:()=>MV,meta:()=>YV,nan:()=>HV,nanoid:()=>QF,nativeEnum:()=>LV,never:()=>_S,nonoptional:()=>uC,null:()=>wh,nullable:()=>yh,nullish:()=>VV,number:()=>qe,object:()=>V,optional:()=>ot,partialRecord:()=>zV,pipe:()=>tS,prefault:()=>cC,preprocess:()=>Ih,promise:()=>WV,readonly:()=>gC,record:()=>st,refine:()=>SC,set:()=>UV,strictObject:()=>NV,string:()=>$,stringFormat:()=>gV,stringbool:()=>eB,success:()=>BV,superRefine:()=>xC,symbol:()=>AV,templateLiteral:()=>KV,transform:()=>SS,tuple:()=>XR,uint32:()=>EV,uint64:()=>IV,ulid:()=>rV,undefined:()=>TV,union:()=>tt,unknown:()=>ut,url:()=>GF,uuid:()=>ZF,uuidv4:()=>KF,uuidv6:()=>WF,uuidv7:()=>JF,void:()=>RV,xid:()=>nV,xor:()=>DV});var Y_={};gt(Y_,{endsWith:()=>dd,gt:()=>Ii,gte:()=>Rn,includes:()=>ud,length:()=>cu,lowercase:()=>ad,lt:()=>$i,lte:()=>Pn,maxLength:()=>au,maxSize:()=>ya,mime:()=>pd,minLength:()=>Ns,minSize:()=>Ai,multipleOf:()=>ga,negative:()=>j_,nonnegative:()=>U_,nonpositive:()=>M_,normalize:()=>md,overwrite:()=>Do,positive:()=>z_,properties:()=>fd,property:()=>L_,regex:()=>sd,size:()=>su,slugify:()=>vd,startsWith:()=>ld,toLowerCase:()=>gd,toUpperCase:()=>yd,trim:()=>hd,uppercase:()=>cd});var VF=new WeakSet([Object.prototype,Error.prototype]);function Q_(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 BF=(t,e)=>{oT.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);VF.has(r)||(VF.add(r),Q_(r,"format",o=>n=>km(o,n)),Q_(r,"flatten",o=>n=>Em(o,n)),Q_(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,zl,2)}),Q_(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,zl,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Ude=S("ZodError",BF),hn=S("ZodError",BF,void 0,{Parent:Error});var ER=Fl(hn),kR=Vl(hn),$R=Bl(hn),IR=ql(hn),AR=_w(hn),TR=Sw(hn),PR=xw(hn),RR=Ew(hn),CR=kw(hn),OR=$w(hn),NR=Iw(hn),DR=Aw(hn);function Fde(){Yt.localeError||Ct(i_())}function lu(){Yt.memoizer||Ct({memoizer:Vm()})}var ve=S("ZodType",(t,e)=>(Fde(),ae.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(I.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 He(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(SC(t,e))},superRefine(t,e){return this.check(xC(t,e))},overwrite(t){return this.check(Do(t))},optional(){return ot(this)},exactOptional(){return nC(this)},nullable(){return yh(this)},nullish(){return ot(yh(this))},nonoptional(t){return uC(this,t)},array(){return Ae(this)},or(t){return tt([this,t])},and(t){return Ad(this,t)},transform(t){return tS(this,SS(t))},default(t){return sC(this,t)},prefault(t){return cC(this,t)},catch(t){return fC(this,t)},pipe(t){return tS(this,t)},readonly(){return gC(this)},describe(t){let e=this.clone();return ur.add(e,{description:t}),e},meta(...t){if(t.length===0)return ur.get(this);let e=this.clone();return ur.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 I.hide(this,"~standard",{...Uw(this),jsonSchema:{input:wd(this,"input"),output:wd(this,"output")}})},set"~standard"(t){I.own(this,"~standard",t)},parse:function t(e,r){return ER(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await kR(this,e,r,{callee:t})},safeParse(t,e){return $R(this,t,e)},async safeParseAsync(t,e){return IR(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){I.own(this,"spa",t)},validate(t,e){return Kl(this,t,e)},validateAsync(t,e){return Wl(this,t,e)},encode:function t(e,r){return AR(this,e,r,{callee:t})},decode:function t(e,r){return TR(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await PR(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await RR(this,e,r,{callee:t})},safeEncode(t,e){return CR(this,t,e)},safeDecode(t,e){return OR(this,t,e)},async safeEncodeAsync(t,e){return NR(this,t,e)},async safeDecodeAsync(t,e){return DR(this,t,e)},toJSONSchema(t){return jP(this,{})(t)},get description(){return ur.get(this)?.description},get _def(){return this._zod.def}}),rS=S("_ZodString",(t,e)=>{ha.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>LP(t,r,o,n)},I.derived({format:t=>Wt(t).format??null,minLength:t=>Wt(t).minimum??null,maxLength:t=>Wt(t).maximum??null},{regex(...t){return this.check(sd(...t))},includes(...t){return this.check(ud(...t))},startsWith(...t){return this.check(ld(...t))},endsWith(...t){return this.check(dd(...t))},min(...t){return this.check(Ns(...t))},max(...t){return this.check(au(...t))},length(...t){return this.check(cu(...t))},nonempty(...t){return this.check(Ns(1,...t))},lowercase(t){return this.check(ad(t))},uppercase(t){return this.check(cd(t))},trim(){return this.check(hd())},normalize(...t){return this.check(md(...t))},toLowerCase(){return this.check(gd())},toUpperCase(){return this.check(yd())},slugify(){return this.check(vd())}})),Ed=S("ZodString",(t,e)=>{ha.init(t,e),rS.init(t,e)},{email(t){return this.check(Hm(nS,t))},url(t){return this.check(id(vh,t))},jwt(t){return this.check(lh(wS,t))},emoji(t){return this.check(Gm(iS,t))},guid(t){return this.check(qm(oS,t))},uuid(t){return this.check(Zm(Ti,t))},uuidv4(t){return this.check(Km(Ti,t))},uuidv6(t){return this.check(Wm(Ti,t))},uuidv7(t){return this.check(Jm(Ti,t))},nanoid(t){return this.check(Xm(sS,t))},cuid(t){return this.check(Ym(aS,t))},cuid2(t){return this.check(Qm(cS,t))},ulid(t){return this.check(eh(uS,t))},base64(t){return this.check(ah(gS,t))},base64url(t){return this.check(ch(yS,t))},xid(t){return this.check(th(lS,t))},ksuid(t){return this.check(rh(dS,t))},ipv4(t){return this.check(nh(fS,t))},ipv6(t){return this.check(oh(pS,t))},cidrv4(t){return this.check(ih(mS,t))},cidrv6(t){return this.check(sh(hS,t))},e164(t){return this.check(uh(vS,t))},datetime(t){return this.check(dh(Sa,t))},date(t){return this.check(fh(xa,t))},time(t){return this.check(ph(Ea,t))},duration(t){return this.check(mh(ka,t))}});function $(t){return p_(Ed,t)}var it=S("ZodStringFormat",(t,e)=>{We.init(t,e),rS.init(t,e)}),Sa=S("ZodISODateTime",(t,e)=>{pP.init(t,e),it.init(t,e)}),xa=S("ZodISODate",(t,e)=>{mP.init(t,e),it.init(t,e)}),Ea=S("ZodISOTime",(t,e)=>{hP.init(t,e),it.init(t,e)}),ka=S("ZodISODuration",(t,e)=>{gP.init(t,e),it.init(t,e)}),nS=S("ZodEmail",(t,e)=>{Vw.init(t,e),it.init(t,e)});function HF(t){return Hm(nS,t)}var oS=S("ZodGUID",(t,e)=>{Lw.init(t,e),it.init(t,e)});function qF(t){return qm(oS,t)}var Ti=S("ZodUUID",(t,e)=>{Fw.init(t,e),it.init(t,e)});function ZF(t){return Zm(Ti,t)}function KF(t){return Km(Ti,t)}function WF(t){return Wm(Ti,t)}function JF(t){return Jm(Ti,t)}var vh=S("ZodURL",(t,e)=>{Zw.init(t,e),it.init(t,e)});function GF(t){return id(vh,t)}function XF(t){return id(vh,{protocol:$m,hostname:IT,...I.normalizeParams(t)})}var iS=S("ZodEmoji",(t,e)=>{Kw.init(t,e),it.init(t,e)});function YF(t){return Gm(iS,t)}var sS=S("ZodNanoID",(t,e)=>{Ww.init(t,e),it.init(t,e)});function QF(t){return Xm(sS,t)}var aS=S("ZodCUID",(t,e)=>{Jw.init(t,e),it.init(t,e)});function eV(t){return Ym(aS,t)}var cS=S("ZodCUID2",(t,e)=>{Gw.init(t,e),it.init(t,e)});function tV(t){return Qm(cS,t)}var uS=S("ZodULID",(t,e)=>{Xw.init(t,e),it.init(t,e)});function rV(t){return eh(uS,t)}var lS=S("ZodXID",(t,e)=>{Yw.init(t,e),it.init(t,e)});function nV(t){return th(lS,t)}var dS=S("ZodKSUID",(t,e)=>{Qw.init(t,e),it.init(t,e)});function oV(t){return rh(dS,t)}var fS=S("ZodIPv4",(t,e)=>{eb.init(t,e),it.init(t,e)});function iV(t){return nh(fS,t)}var zR=S("ZodMAC",(t,e)=>{rb.init(t,e),it.init(t,e)});function sV(t){return m_(zR,t)}var pS=S("ZodIPv6",(t,e)=>{tb.init(t,e),it.init(t,e)});function aV(t){return oh(pS,t)}var mS=S("ZodCIDRv4",(t,e)=>{nb.init(t,e),it.init(t,e)});function cV(t){return ih(mS,t)}var hS=S("ZodCIDRv6",(t,e)=>{ib.init(t,e),it.init(t,e)});function uV(t){return sh(hS,t)}var gS=S("ZodBase64",(t,e)=>{ab.init(t,e),it.init(t,e)});function lV(t){return ah(gS,t)}var yS=S("ZodBase64URL",(t,e)=>{ub.init(t,e),it.init(t,e)});function dV(t){return ch(yS,t)}var vS=S("ZodE164",(t,e)=>{lb.init(t,e),it.init(t,e)});function fV(t){return uh(vS,t)}var jR=S("ZodCreditCard",(t,e)=>{fb.init(t,e),it.init(t,e)});function pV(t){return h_(jR,t)}var MR=S("ZodIBAN",(t,e)=>{mb.init(t,e),it.init(t,e)});function mV(t){return g_(MR,t)}var wS=S("ZodJWT",(t,e)=>{gb.init(t,e),it.init(t,e)});function hV(t){return lh(wS,t)}var du=S("ZodCustomStringFormat",(t,e)=>{yb.init(t,e),it.init(t,e)});function gV(t,e,r={}){return va(du,t,e,r)}function yV(t){return va(du,"hostname",$T,t)}function vV(t){return va(du,"hex",FT,t)}function wV(t){return va(du,"currency_code",TT,t)}function bV(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Tn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return va(du,o,n,e)}var kd=S("ZodNumber",(t,e)=>{Dm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>FP(t,r,o,n),t.isFinite=!0},I.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Wt(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Wt(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Wt(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Wt(t).format??null},{gt(t,e){return this.check(Ii(t,e))},gte(t,e){return this.check(Rn(t,e))},min(t,e){return this.check(Rn(t,e))},lt(t,e){return this.check($i(t,e))},lte(t,e){return this.check(Pn(t,e))},max(t,e){return this.check(Pn(t,e))},int(t){return this.check(eS(t))},safe(t){return this.check(eS(t))},positive(t){return this.check(Ii(0,t))},nonnegative(t){return this.check(Rn(0,t))},negative(t){return this.check($i(0,t))},nonpositive(t){return this.check(Pn(0,t))},multipleOf(t,e){return this.check(ga(t,e))},step(t,e){return this.check(ga(t,e))},finite(){return this}}));function qe(t){return y_(kd,t)}var fu=S("ZodNumberFormat",(t,e)=>{vb.init(t,e),kd.init(t,e)});function eS(t){return v_(fu,t)}function _V(t){return w_(fu,t)}function SV(t){return b_(fu,t)}function xV(t){return __(fu,t)}function EV(t){return S_(fu,t)}var $d=S("ZodBoolean",(t,e)=>{Xl.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>VP(t,r,o,n)});function Mt(t){return x_($d,t)}var Id=S("ZodBigInt",(t,e)=>{zm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>BP(t,r,o,n)},I.derived({minValue:t=>Wt(t).minimum??null,maxValue:t=>Wt(t).maximum??null,format:t=>Wt(t).format??null},{gte(t,e){return this.check(Rn(t,e))},min(t,e){return this.check(Rn(t,e))},gt(t,e){return this.check(Ii(t,e))},lt(t,e){return this.check($i(t,e))},lte(t,e){return this.check(Pn(t,e))},max(t,e){return this.check(Pn(t,e))},positive(t){return this.check(Ii(BigInt(0),t))},negative(t){return this.check($i(BigInt(0),t))},nonpositive(t){return this.check(Pn(BigInt(0),t))},nonnegative(t){return this.check(Rn(BigInt(0),t))},multipleOf(t,e){return this.check(ga(t,e))}}));function kV(t){return E_(Id,t)}var bS=S("ZodBigIntFormat",(t,e)=>{wb.init(t,e),Id.init(t,e)});function $V(t){return k_(bS,t)}function IV(t){return $_(bS,t)}var UR=S("ZodSymbol",(t,e)=>{bb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HP(t,r,o,n)});function AV(t){return I_(UR,t)}var LR=S("ZodUndefined",(t,e)=>{_b.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ZP(t,r,o,n)});function TV(t){return A_(LR,t)}var FR=S("ZodNull",(t,e)=>{Sb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qP(t,r,o,n)});function wh(t){return T_(FR,t)}var VR=S("ZodAny",(t,e)=>{xb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JP(t,r,o,n)});function PV(){return P_(VR)}var BR=S("ZodUnknown",(t,e)=>{Eb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GP(t,r,o,n)});function ut(){return R_(BR)}var HR=S("ZodNever",(t,e)=>{kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WP(t,r,o,n)});function _S(t){return C_(HR,t)}var qR=S("ZodVoid",(t,e)=>{$b.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>KP(t,r,o,n)});function RV(t){return O_(qR,t)}var bh=S("ZodDate",(t,e)=>{Ib.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XP(t,r,o,n),t.min=(r,o)=>t.check(Rn(r,o)),t.max=(r,o)=>t.check(Pn(r,o))},I.derived({minDate:t=>{let{minimum:e}=Wt(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Wt(t);return e?new Date(e):null}},{}));function CV(t){return N_(bh,t)}var ZR=S("ZodArray",(t,e)=>{lu(),Ab.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uR(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ns(t,e))},nonempty(t){return this.check(Ns(1,t))},max(t,e){return this.check(au(t,e))},length(t,e){return this.check(cu(t,e))},unwrap(){return this.element}});function Ae(t,e){return DP(ZR,t,e)}function OV(t){let e=t._zod.def.shape;return dr(Object.keys(e))}var _h=S("ZodObject",(t,e)=>{lu(),yP.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lR(t,r,o,n),I.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return dr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(I.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(I.mergeDefs(this._zod.def,{catchall:ut()}))},loose(){return this.clone(I.mergeDefs(this._zod.def,{catchall:ut()}))},strict(){return this.clone(I.mergeDefs(this._zod.def,{catchall:_S()}))},strip(){return this.clone(I.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return I.extend(this,t)},safeExtend(t){return I.safeExtend(this,t)},merge(t){return I.merge(this,t)},pick(t){return I.pick(this,t)},omit(t){return I.omit(this,t)},partial(...t){return I.partial(pu,this,t[0])},exactPartial(...t){return I.partial(xS,this,t[0],"exactPartial")},required(...t){return I.required(ES,this,t[0])}});function V(t,e){let r={type:"object",shape:t??{},...I.normalizeParams(e)};return new _h(r)}function NV(t,e){return new _h({type:"object",shape:t,catchall:_S(),...I.normalizeParams(e)})}function lr(t,e){return new _h({type:"object",shape:t,catchall:ut(),...I.normalizeParams(e)})}var Sh=S("ZodUnion",(t,e)=>{Yl.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>J_(t,r,o,n),t.options=e.options});function tt(t,e){return new Sh({type:"union",options:t,...I.normalizeParams(e)})}var KR=S("ZodXor",(t,e)=>{Sh.init(t,e),Pb.init(t,e),t._zod.processJSONSchema=(r,o,n)=>J_(t,r,o,n),t.options=e.options});function DV(t,e){return new KR({type:"union",options:t,inclusive:!1,...I.normalizeParams(e)})}var WR=S("ZodDiscriminatedUnion",(t,e)=>{Sh.init(t,e),Rb.init(t,e)});function xh(t,e,r){return new WR({type:"union",options:e,discriminator:t,...I.normalizeParams(r)})}var JR=S("ZodIntersection",(t,e)=>{Cb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dR(t,r,o,n)});function Ad(t,e){return new JR({type:"intersection",left:t,right:e})}var GR=S("ZodTuple",(t,e)=>{lu(),jm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fR(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 pu({type:"optional",innerType:e}))})}});function XR(t,e,r){let o=e instanceof ae,n=o?r:e,i=o?e:null;return new GR({type:"tuple",items:t,rest:i,...I.normalizeParams(n)})}var Sd=S("ZodRecord",(t,e)=>{lu(),Ob.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function st(t,e,r){return!e||!e._zod?new Sd({type:"record",keyType:$(),valueType:t,...I.normalizeParams(e)}):new Sd({type:"record",keyType:t,valueType:e,...I.normalizeParams(r)})}function zV(t,e,r){return new Sd({type:"record",keyType:t,valueType:e,...I.normalizeParams(r),partial:!0})}function jV(t,e,r){return new Sd({type:"record",keyType:t,valueType:e,mode:"loose",...I.normalizeParams(r)})}var YR=S("ZodMap",(t,e)=>{lu(),Nb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ai(...r)),t.nonempty=r=>t.check(Ai(1,r)),t.max=(...r)=>t.check(ya(...r)),t.size=(...r)=>t.check(su(...r))});function MV(t,e,r){return new YR({type:"map",keyType:t,valueType:e,...I.normalizeParams(r)})}var QR=S("ZodSet",(t,e)=>{lu(),Db.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cR(t,r,o,n),t.min=(...r)=>t.check(Ai(...r)),t.nonempty=r=>t.check(Ai(1,r)),t.max=(...r)=>t.check(ya(...r)),t.size=(...r)=>t.check(su(...r))});function UV(t,e){return new QR({type:"set",valueType:t,...I.normalizeParams(e)})}var xd=S("ZodEnum",(t,e)=>{zb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(o,n,i)=>YP(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 xd({...e,checks:[],...I.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 xd({...e,checks:[],...I.normalizeParams(n),entries:i})}});function dr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new xd({type:"enum",entries:r,...I.normalizeParams(e)})}function LV(t,e){return new xd({type:"enum",entries:t,...I.normalizeParams(e)})}var eC=S("ZodLiteral",(t,e)=>{jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QP(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 G(t,e){return new eC({type:"literal",values:Array.isArray(t)?t:[t],...I.normalizeParams(e)})}var tC=S("ZodFile",(t,e)=>{Mb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rR(t,r,o,n),t.min=(r,o)=>t.check(Ai(r,o)),t.max=(r,o)=>t.check(ya(r,o)),t.mime=(r,o)=>t.check(pd(Array.isArray(r)?r:[r],o))});function FV(t){return F_(tC,t)}var rC=S("ZodTransform",(t,e)=>{lu(),Ub.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sR(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new ma(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(I.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(I.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 SS(t){return new rC({type:"transform",transform:t})}var pu=S("ZodOptional",(t,e)=>{Mm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ot(t){return new pu({type:"optional",innerType:t})}var xS=S("ZodExactOptional",(t,e)=>{Lb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function nC(t){return new xS({type:"optional",innerType:t})}var oC=S("ZodNullable",(t,e)=>{Fb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yh(t){return new oC({type:"nullable",innerType:t})}function VV(t){return ot(yh(t))}var iC=S("ZodDefault",(t,e)=>{Vb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function sC(t,e){return new iC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():I.shallowClone(e)}})}var aC=S("ZodPrefault",(t,e)=>{Bb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function cC(t,e){return new aC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():I.shallowClone(e)}})}var ES=S("ZodNonOptional",(t,e)=>{Hb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function uC(t,e){return new ES({type:"nonoptional",innerType:t,...I.normalizeParams(e)})}var lC=S("ZodSuccess",(t,e)=>{qb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function BV(t){return new lC({type:"success",innerType:t})}var dC=S("ZodCatch",(t,e)=>{Zb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function fC(t,e){return new dC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:I.constantCatch(e)})}var pC=S("ZodNaN",(t,e)=>{Kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eR(t,r,o,n)});function HV(t){return D_(pC,t)}var Eh=S("ZodPipe",(t,e)=>{Um.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bR(t,r,o,n),t.in=e.in,t.out=e.out});function tS(t,e){return new Eh({type:"pipe",in:t,out:e})}var kh=S("ZodCodec",(t,e)=>{Eh.init(t,e),Ql.init(t,e)});function qV(t,e,r){return new kh({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function ZV(t){let e=t._zod.def;return new kh({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var mC=S("ZodPreprocess",(t,e)=>{Eh.init(t,e),wP.init(t,e)}),hC=S("ZodReadonly",(t,e)=>{Wb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function gC(t){return new hC({type:"readonly",innerType:t})}var yC=S("ZodTemplateLiteral",(t,e)=>{Jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tR(t,r,o,n)});function KV(t,e){return new yC({type:"template_literal",parts:t,...I.normalizeParams(e)})}var vC=S("ZodLazy",(t,e)=>{ed.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xR(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function wC(t){return new vC({type:"lazy",getter:t})}var bC=S("ZodPromise",(t,e)=>{Xb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function WV(t){return new bC({type:"promise",innerType:t})}var _C=S("ZodFunction",(t,e)=>{Gb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iR(t,r,o,n)});function JV(t){return new _C({type:"function",input:Array.isArray(t?.input)?XR(t?.input):t?.input??Ae(ut()),output:t?.output??ut()})}var $h=S("ZodCustom",(t,e)=>{Yb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oR(t,r,o,n)});function GV(t){let e=new nt({check:"custom"});return e._zod.check=t,e}function kS(t,e){return V_($h,t??(()=>!0),e)}function SC(t,e={}){return B_($h,t,e)}function xC(t,e){return H_(t,e)}var XV=q_,YV=Z_,EC=S("ZodInstanceOf",(t,e)=>{$h.init(t,e)},{properties(t,e){return this.check(fd(t,e))}});function QV(t,e={}){let r=new EC({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...I.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 eB=(...t)=>K_({Codec:kh,Boolean:$d,String:Ed},...t);function tB(t){let e=wC(()=>tt([$(t),qe(),Mt(),wh(),Ae(e),st($(),e)]));return e}function Ih(t,e){return new mC({type:"pipe",in:SS(t),out:e})}var Vde={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 Bde(t){Ct({customError:t})}function Hde(){return Ct().customError}var kC;kC||(kC={});var mu={};gt(mu,{ZodISODate:()=>xa,ZodISODateTime:()=>Sa,ZodISODuration:()=>ka,ZodISOTime:()=>Ea,date:()=>Zde,datetime:()=>qde,duration:()=>Wde,time:()=>Kde});function qde(t){return dh(Sa,t)}function Zde(t){return fh(xa,t)}function Kde(t){return ph(Ea,t)}function Wde(t){return mh(ka,t)}var F={...Td,...Y_,iso:mu},Jde=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 Gde(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 rB(t,e){return t.map((r,o)=>o<e?r:r.optional())}function Xde(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Yde(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:Xde(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 Qde(t,e){return F.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 $C(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=$C(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=$C(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 efe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),tfe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Ah(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(Ah):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>efe.has(e)?Ah(r):!tfe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(Ah))}function nB(t){return t===1?"element":"elements"}function rfe(t,e){return F.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=$C(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 ${nB(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 ${nB(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function oB(t,e){if(t!==!1)return t===void 0||t===!0?F.any():Yr(t,e)}var nfe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function iB(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return F.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 F.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=Yde(n,e),s=Yr(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 F.null();if(n.length===0)return F.never();if(n.length===1)return F.literal(n[0]);if(n.every(s=>typeof s=="string"))return F.enum(n);let i=n.map(s=>F.literal(s));return i.length<2?i[0]:F.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return F.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return iB(s,e)});return n.length===0?F.never():n.length===1?n[0]:F.union(n)}if(!r)return F.any();let o;switch(r){case"string":{let n=F.string();if(t.format){let i=t.format;i==="email"?n=n.check(F.email()):i==="uri"||i==="uri-reference"?n=n.check(F.url()):i==="uuid"||i==="guid"?n=n.check(F.uuid()):i==="date-time"?n=n.check(F.iso.datetime({offset:!0})):i==="date"?n=n.check(F.iso.date()):i==="time"?n=n.check(F.regex(nfe)):i==="duration"?n=n.check(F.iso.duration()):i==="hostname"?n=n.check(F.hostname()):i==="ipv4"?n=n.check(F.ipv4()):i==="ipv6"?n=n.check(F.ipv6()):i==="mac"?n=n.check(F.mac()):i==="cidr"?n=n.check(F.cidrv4()):i==="cidr-v6"?n=n.check(F.cidrv6()):i==="base64"?n=n.check(F.base64()):i==="base64url"?n=n.check(F.base64url()):i==="e164"?n=n.check(F.e164()):i==="credit_card"?n=n.check(F.creditCard()):i==="iban"?n=n.check(F.iban()):i==="jwt"?n=n.check(F.jwt()):i==="emoji"?n=n.check(F.emoji()):i==="nanoid"?n=n.check(F.nanoid()):i==="cuid"?n=n.check(F.cuid()):i==="cuid2"?n=n.check(F.cuid2()):i==="ulid"?n=n.check(F.ulid()):i==="xid"?n=n.check(F.xid()):i==="ksuid"&&(n=n.check(F.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"?F.number().int():F.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=F.boolean();break}case"null":{o=F.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Yr(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=Yr(f,e);cr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let g of f){let v=Yr(d[g],e),w=F.string().regex(new RegExp(g));p.push(F.looseRecord(w,v))}let m=[];if(Object.keys(n).length>0&&m.push(F.object(n).passthrough()),m.push(...p),m.length===0)o=F.object({}).passthrough();else if(m.length===1)o=m[0];else{let g=F.intersection(m[0],m[1]);for(let v=2;v<m.length;v++)g=F.intersection(g,m[v]);o=g}if(t.additionalProperties===!1){let g=Object.keys(n),v=f.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!Gn(b.value))return;let _=[];for(let E of Object.keys(b.value))g.includes(E)||v.some(A=>A.test(E))||_.push(E);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=F.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=Yr(f,e)}o=Qde(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=>Yr(d,e)),c=rB(a,s),u=Array.isArray(i)?void 0:oB(i,e),l=F.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(F.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(F.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Yr(d,e)),c=rB(a,s),u=oB(t.additionalItems,e),l=F.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(F.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(F.maxLength(t.maxItems)))}else if(i!==void 0){let s=Yr(i,e),a=F.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=F.array(F.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=rfe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Yr(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 Yr(t,e){if(typeof t=="boolean")return t?F.any():F.never();let r=iB(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=>Yr(u,e)),c=F.union(a);r=o?F.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Yr(u,e)),c=F.xor(a);r=o?F.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:F.any();else{let a=o?r:Yr(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=F.intersection(a,Yr(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=F.nullable(r)),t.readOnly===!0&&(r=F.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&&!Ah(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&&!Ah(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))Jde.has(a)||cr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function sB(t,e){if(typeof t=="boolean")return t?F.any():F.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=Gde(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??ur};return Yr(r,i)}var aB=Symbol("z.visit/resolving");function Th(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===aB)return new ed({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,aB);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let m of l){let g=n(u[m]);g!==u[m]&&(d=!0),f[m]=g}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?He(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:He(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let m=n(p);m!==p&&(l=!0),d.push(m)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?He(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:He(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:He(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?He(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:He(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:He(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:He(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:He(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return He(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 cB(t){return Th(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:tt(r.options)}})}function ofe(t,e){if(!e?.length)return t;let r=t._zod.def;return He(t,Jn(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function uB(t){return ofe(t.out,t.checks)}function ife(t){return t.in._zod.traits.has("$ZodTransform")?uB(t):t.in}function lB(t){return Th(t,{pipe:e=>ife(e._zod.def),default:(e,r)=>r?ot(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function dB(t){return Th(t,{pipe:e=>uB(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var IC={};gt(IC,{bigint:()=>ufe,boolean:()=>cfe,date:()=>lfe,number:()=>afe,string:()=>sfe});function sfe(t){return TP(Ed,t)}function afe(t){return RP(kd,t)}function cfe(t){return CP($d,t)}function ufe(t){return OP(Id,t)}function lfe(t){return NP(bh,t)}var Ph={name:"@tomato414941/foundation",version:"1.3.0",description:"Manage Foundation resources and deliver encrypted inputs to commands.",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"};var Pd=new TextEncoder,Rd=new TextDecoder,fB=new TextDecoder("utf-8",{fatal:!0}),$S=2**32;function Qr(...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 AC(t,e,r){if(e<0||e>=$S)throw new RangeError(`value must be >= 0 and <= ${$S-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function TC(t){let e=Math.floor(t/$S),r=t%$S,o=new Uint8Array(8);return AC(o,e,0),AC(o,r,4),o}function IS(t){let e=new Uint8Array(4);return AC(e,t),e}var ffe=/[^\x00-\x7f]/;function fr(t){if(typeof t=="string"&&t.length>=128){if(ffe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return Pd.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 pB(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 mB(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 AS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ds=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 hu=class extends Ds{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},at=class extends Ds{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},$a=class extends Ds{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},M=class extends Ds{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},bt=class extends Ds{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var Rh=class extends Ds{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var TS=class extends Ds{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var pfe="The input to be decoded is not correctly encoded.";function gu(t){try{return mB(typeof t=="string"?t:Rd.decode(t),!0)}catch(e){throw new TypeError(pfe,{cause:e})}}function It(t){return pB(typeof t=="string"?Pd.encode(t):t,!0)}function Cn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Ft(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 Ia(...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 Yn(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function gn(t,e,r){try{return gu(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function PS(t,e,r){try{return fr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function Cd(t,e,r){let o;try{o=JSON.parse(fB.decode(gu(t)))}catch{throw new e(r)}if(!Ft(o))throw new e(r);return o}var RS={__proto__:null,b64:!0},CS={__proto__:null};function Ch(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 OS(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 Aa(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 at(`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 NS(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new bt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function yu(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(!Ft(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var mfe=t=>t[Symbol.toStringTag],hfe=(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 jo(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(Ft(e)){if(s=DC(e),typeof s.kty!="string")throw hB(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(hfe(t,s,r),s.kty==="oct")return gu(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!CC(e))throw hB(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${mfe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Ta(e))return e;if(a=e,a.type==="secret")return a.export()}PC||=new WeakMap;let c=e,u=PC.get(c);if(u?.[o])return u[o];if(u||PC.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=gfe[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 Nd(t,s)}var PC,gfe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function zS(t){if(!Ta(t))throw new Error("CryptoKey instance expected")}var Ta=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},RC=t=>t?.[Symbol.toStringTag]==="KeyObject",CC=t=>Ta(t)||RC(t);function gB(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 zs=(t,...e)=>gB("Key must be ",t,...e);function hB(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(gB(`Key for the ${t} algorithm must be `,e,...o))}var DS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function OC(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Od(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 NC(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw DS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw DS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw DS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw DS(e.length,"algorithm.length");OC(t,r)}function jS(t){return{__proto__:null,...t}}function DC(t){let e=jS(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 MS(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function Nd(t,e,r){if(!t.kty.includes(e.kty))throw new at('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 Mo(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),NC(t,e,r),t}var vu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function US(t,e){let r=t.byteLength<<3;if(r!==e)throw new M(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var yfe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function yB(t,e){if(e.length<<3!==t.ivBits)throw new M("Invalid Initialization Vector length")}async function vB(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(zs(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 wB(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vfe(t,e,r,o,n){let[i,s,a]=await vB(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Qr(n,o,c,TC(n.length*8)),l=await wB(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function wfe(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 bfe(t,e,r,o,n,i){let[s,a,c]=await vB(t,e,"decrypt"),u=Qr(i,o,r,TC(i.length*8)),l=await wB(a,u,c);try{if(await wfe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new $a}async function LS(t,e,r,o,n){if(!Ta(r)&&!(r instanceof Uint8Array))throw new TypeError(zs(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?yB(t,o):o=yfe(t),r instanceof Uint8Array&&US(r,t.cekBits),t.cbc)return vfe(t,e,r,o,n);let i=await Mo(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 FS(t,e,r,o,n,i){if(!Ta(e)&&!(e instanceof Uint8Array))throw new TypeError(zs(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new M("JWE Initialization Vector missing");if(!n)throw new M("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new M("Invalid Authentication Tag length");if(yB(t,o),e instanceof Uint8Array&&US(e,t.cekBits),t.cbc)return bfe(t,e,r,o,n,i);let s=await Mo(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Qr(r,n)))}catch{throw new $a}}function Oh(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var _fe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Sfe=[[],["deriveBits"]],HS=[[],[]];function VS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:_fe,ops:["wrapKey","unwrapKey"]}}function BS(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 at('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Sfe,ops:[void 0,"deriveBits"]}}function Dd(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:HS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function zC(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:HS,ops:["deriveBits","deriveBits"]}}var js=Oh({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:HS,ops:["encrypt","decrypt"]},"RSA-OAEP":VS(1),"RSA-OAEP-256":VS(256),"RSA-OAEP-384":VS(384),"RSA-OAEP-512":VS(512),"ECDH-ES":BS("direct-key-agreement"),"ECDH-ES+A128KW":BS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":BS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":BS("key-agreement-with-key-wrapping"),A128KW:Dd(128),A192KW:Dd(192),A256KW:Dd(256),A128GCMKW:Dd(128,!0),A192GCMKW:Dd(192,!0),A256GCMKW:Dd(256,!0),"PBES2-HS256+A128KW":zC(),"PBES2-HS384+A192KW":zC(),"PBES2-HS512+A256KW":zC()}),xfe=["encrypt","decrypt"];function zd(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:HS,ops:xfe,cekBits:t,ivBits:e?128:96,cbc:e}}var Efe=Oh({A128GCM:zd(128),A192GCM:zd(192),A256GCM:zd(256),"A128CBC-HS256":zd(256,!0),"A192CBC-HS384":zd(384,!0),"A256CBC-HS512":zd(512,!0)});function bB(t,e){throw new at(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Uo(t){return(typeof t=="string"?js[t]:void 0)??bB("alg","Algorithm")}function Lo(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function wu(t){return(typeof t=="string"?Efe[t]:void 0)??bB("enc","Encryption Algorithm")}function _B(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");OC(t,e)}async function kfe(t,e,r){let o=await Mo(e,Uo(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 $fe(t,e,r){let o=await Mo(e,Uo(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 xB(t,e,r){NC(e,Uo(t).subtle,r),Od(t,e)}async function EB(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new M("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new M("PBES2 Count Input must be a positive integer");let n=Qr(fr(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 Mo(o,Uo(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function jC(t){return Qr(IS(t.length),t)}async function Ife(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 AS("sha256",Qr(IS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function kB(t,e,r,o,n=new Uint8Array,i=new Uint8Array){_B(t),_B(e,"deriveBits");let s=Qr(jC(fr(r)),jC(n),jC(i),IS(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 Ife(a,o,s)}function $B(t){zS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new at("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function qS(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new M(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return gn(r,e,M)}}function IB(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 M('JOSE Header "apu" and "apv" values must be distinct')}}function Afe(t){if(t===void 0)throw new M("JWE Encrypted Key missing")}function SB(t){if(t!==void 0)throw new M("Encountered unexpected JWE Encrypted Key")}function Tfe(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 AB(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return SB(o),r;let c=a==="direct-key-agreement";switch(c?SB(o):Afe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Ft(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new M('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');$B(r);let l=await Nd(t,u),d=qS(n,"apu"),f=qS(n,"apv");IB(d,f);let p=await kB(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 zS(r),xB(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new M('JOSE Header "p2c" (PBES2 Count) missing or invalid');Tfe(i);let u=i??1e4;if(n.p2c>u)throw new M('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new M('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=gn(n.p2s,"p2s",M);r=await EB(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new M('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new M('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=gn(n.iv,"iv",M),l=gn(n.tag,"tag",M);if(u.byteLength!==12)throw new M("Invalid Initialization Vector length");if(l.byteLength!==16)throw new M("Invalid Authentication Tag length");return FS(wu(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return $fe(s.slice(-6),r,o)}async function ZS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Lo(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await jo(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??vu(e):void 0;l&&US(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{$B(u);let{apu:p,apv:m}=i;p!==void 0&&Cn(p,'"apu"'),m!==void 0&&Cn(m,'"apv"');let g=p??qS(o,"apu"),v=m??qS(o,"apv");IB(g,v);let w;i.epk!==void 0?w=await jo(t,i.epk,"decrypt"):w=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,_=w;if(!_.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');_=await b.getPublicKey(w,[])}let{x:E,y:A,crv:z,kty:H}=await b.exportKey("jwk",_),te=a==="direct-key-agreement",$e=await kB(u,w,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),g,v),xe={x:E,crv:z,kty:H};if(H==="EC"&&(xe.y=A),f={epk:xe},p!==void 0&&(f.apu=It(p)),m!==void 0&&(f.apv=It(m)),te)return[$e,void 0,f];u=$e;break}case"RSA-OAEP":{zS(u),xB(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await EB(m,s,p,u),f={p2c:p,p2s:It(m)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await LS(wu(s.slice(0,-2)),l,u,p,new Uint8Array);d=m.ciphertext,f={iv:It(m.iv),tag:It(m.tag)}}}if(d??=await kfe(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 KS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new at('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new M('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function TB(t){if(typeof globalThis[t]>"u")throw new at(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function PB(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 M("Decompressed plaintext exceeded the configured limit")}return Qr(...n)}async function RB(t){return TB("CompressionStream"),PB(new CompressionStream("deflate-raw"),t)}async function CB(t,e){return TB("DecompressionStream"),PB(new DecompressionStream("deflate-raw"),t,e)}function OB(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 M("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new M("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new M("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new M("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new M("JWE AAD incorrect type");if(s!==void 0&&!Ft(s))throw new M("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 NB(t){let e,r;try{let{header:o}=t;if(Ft(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 DB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new M("JWE Encrypted Key incorrect type");if(r!==void 0&&!Ft(r))throw new M("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new M("JOSE Header missing")}function MC(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=Cd(e,M,"JWE Protected Header is invalid")),[s,gn(r,"ciphertext",M),o!==void 0?gn(o,"iv",M):void 0,n!==void 0?gn(n,"tag",M):void 0,PS((e??"")+(i!==void 0?`.${i}`:""),"aad",M)]}function WS(t){return[t&&Ch("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&Ch("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function UC(t,e,r,o=MC(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Ia(n,u,l))throw new M("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,m,g,v,w]=e,{encrypted_key:b}=t;Aa(M,CS,g,n,f),KS(f,n);let{alg:_,enc:E}=f;if(typeof _!="string"||!_)throw new M("missing JWE Algorithm (alg) in JWE Header");let A=js[_];if(b===""&&(!A||!Lo(A)))throw new M("JWE Encrypted Key incorrect type");let z=A?.mode==="integrated-encryption";if(!z&&(typeof E!="string"||!E))throw new M("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(_)||!p&&_.startsWith("PBES2"))throw new hu('"alg" (Algorithm) Header Parameter value not allowed');let H;if(z){if(E!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new M("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new M("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(E))throw new hu('"enc" (Encryption Algorithm) Header Parameter value not allowed');H=wu(E)}let te;if(b!==void 0)try{te=gn(b,"encrypted_key",M)}catch(Ie){if(!A||!Lo(A))throw Ie;te=new Uint8Array}let $e=!1;typeof r=="function"&&(r=await r(n,t),$e=!0);let xe=A??Uo(_);Lo(xe)&&te===void 0&&(te=new Uint8Array);let Qe=await jo(xe.mode==="direct-encryption"?H:xe,r,"decrypt"),Le;if(xe.mode==="integrated-encryption")Le=await xe.decrypt(Qe,te,i,c,n,f);else{let Ie=H,J;try{J=await AB(xe,Ie,Qe,te,f,v),Lo(xe)&&J instanceof Uint8Array&&J.byteLength<<3!==Ie.cekBits&&(J=vu(Ie))}catch(Et){if(Et instanceof TypeError||Et instanceof M||Et instanceof at)throw Et;J=vu(Ie)}Le=await FS(Ie,J,i,s,a,c)}if(f.zip==="DEF"){let Ie=w??25e4;if(Ie===0)throw new at('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ie!==1/0&&(!Number.isSafeInteger(Ie)||Ie<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");Le=await CB(Le,Ie).catch(J=>{throw J instanceof M?J:new M("Failed to decompress plaintext",{cause:J})})}return{plaintext:Le,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:gn(d,"aad",M)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...$e&&{key:Qe}}}async function zB(t,e,r){if(t instanceof Uint8Array&&(t=Rd.decode(t)),typeof t!="string")throw new M("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 M("Invalid Compact JWE");return UC({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Nh(t,e,r){return zB(t,WS(r),e)}async function LC(t,e,r){if(!Ft(t))throw new M("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new M("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Ft))throw new M("JWE Recipients missing or incorrect type");if(!n.length)throw new M("JWE Recipients has no members");let i,s,a;try{i=WS(r),s=OB(t),a=MC(s)}catch{throw new $a}let c=n.map(u=>NB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?js[l]:void 0;if(d&&!Lo(d))throw new M(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return DB(l),await UC(l,i,e,a)}catch{}throw new $a}function JS(t,e,r){if(!Ia(t,e,r))throw new M("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function FC(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new M("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&&Cn(s,"JWE Additional Authenticated Data"),a!==void 0&&Cn(a,"JWE Content Encryption Key"),c!==void 0&&Cn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=yu(M,o)[0],t[1]=o),n!==void 0&&(n=yu(M,n)[0],t[2]=n),!r&&i!==void 0&&(i=yu(M,i)[0],t[3]=i),u!==void 0&&!Ft(u))throw new TypeError("JWE Key Management Parameters must be an object");JS(o,n,i);let d={...o,...n,...i};OS(M,o),Aa(M,CS,l,o,d),KS(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new M('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=js[f];if(m?.mode==="integrated-encryption"){if(p!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!="string"||!p)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,wu(p),m]}async function VC(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,m]=t,g=a,v=c,w=i??Uo(o.alg),b,_,E;w.mode==="integrated-encryption"?E=await jo(w,r,"encrypt"):[E,b,_]=await ZS(w,n,r,o,d,p),_&&(m?v=v?{...v,..._}:_:g=g?{...g,..._}:_,JS(g,v,u));let A=g?It(JSON.stringify(g)):"",z=l?.byteLength?It(l):void 0,H=fr(z?`${A}.${z}`:A),te=s;o.zip==="DEF"&&(te=await RB(te).catch(Ie=>{throw new M("Failed to compress plaintext",{cause:Ie})}));let $e,xe,Qe;w.mode==="integrated-encryption"?[b,$e]=await w.encrypt(E,te,H,g,o,p):{ciphertext:$e,tag:xe,iv:Qe}=await LS(n,te,E,f,H);let Le={ciphertext:It($e)};return Qe&&(Le.iv=It(Qe)),xe&&(Le.tag=It(xe)),b?.byteLength&&(Le.encrypted_key=It(b)),z&&(Le.aad=z),g&&(Le.protected=A),u&&(Le.unprotected=u),v&&(Le.header=v),Le}async function jB(t,e,r){return VC(t,FC(t,r),e)}function MB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var BC=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Yn(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Yn(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}},Dh=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new BC(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Yn(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Yn(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new M("at least one recipient must be added");Cn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[g,v,w,b]=m.state,_=[this.#e,o,g,n,this.#o,void 0,void 0,v,b,e],E=FC(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,E,w]);let[{alg:A,enc:z},,H]=E;if(e&&H&&!Lo(H))throw new M(`"${A}" alg may only have a single recipient`);if(!r)r=z;else if(r!==z)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Uo(m[0].alg);let[s,a,c]=i[0],u=e?vu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await VC(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let m=1;m<i.length;m++){let[g,[v,w,b],_]=i[m],E=g[2],[,A,z]=await ZS(b,w,_,v,u,g[7]),H={encrypted_key:It(A)};if(E||z){let te={...E,...z};z&&JS(g[1],te,g[3]),H.header=te}p.recipients.push(H)}return p}};var zh=[["verify"],["sign"]];function HC(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:zh}}function jd(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:zh,minRsaBits:2048}}function qC(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:zh}}function UB(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:zh}}function ZC(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:zh}}var KC=Oh({HS256:HC(256),HS384:HC(384),HS512:HC(512),RS256:jd(256),RS384:jd(384),RS512:jd(512),PS256:jd(256,32),PS384:jd(384,48),PS512:jd(512,64),ES256:qC("P-256",256),ES384:qC("P-384",384),ES512:qC("P-521",512),EdDSA:UB(),Ed25519:UB(),"ML-DSA-44":ZC(44),"ML-DSA-65":ZC(65),"ML-DSA-87":ZC(87)});function GS(t){let e=typeof t=="string"?KC[t]:void 0;if(!e)throw new at(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function LB(t){return[t&&Ch("algorithms",t.algorithms),t?.crit]}function Pfe(t){return t===void 0?{}:Cd(t,bt,"JWS Protected Header is invalid")}function Rfe(t){try{return fr(t)}catch{throw new bt("JWS Compact Serialization payload must use only ASCII characters")}}async function Cfe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Pfe(i);if(!Ia(c,s))throw new bt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=NS(c,Aa(bt,RS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new bt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new hu('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new bt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new bt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let m=GS(d),g=Qr(i!==void 0?fr(i):new Uint8Array,fr("."),typeof f=="string"?e[2]??=PS(f,"payload",bt):f),v=gn(t.signature,"signature",bt),w=await jo(m,r,"verify"),b=await Mo(w,m.subtle,"verify");m.minRsaBits&&Od(m.alg,b);let _=!1;try{_=await crypto.subtle.verify(m.signing,b,v,g)}catch{}if(!_)throw new TS;let E={payload:typeof f=="string"?gn(f,"payload",bt):f};return i!==void 0&&(E.protectedHeader=c),s!==void 0&&(E.unprotectedHeader=s),p?[{...E,key:w},l]:[E,l]}async function FB(t,e,r){if(t instanceof Uint8Array&&(t=Rd.decode(t)),typeof t!="string")throw new bt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new bt("Invalid Compact JWS");return Cfe({payload:n,protected:o,signature:i},e,r,Rfe)}async function WC(t,e,r){let[o]=await FB(t,LB(r),e);return o}var Md=class{#e;constructor(e){Cn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Yn(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Yn(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Yn(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Yn(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return MB(await jB([...this.#e],e,r))}};async function Ofe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=yu(bt,n);n=w[0],a=It(w[1])}if(i!==void 0&&(i=yu(bt,i)[0]),!n&&!i)throw new bt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ia(n,i))throw new bt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};OS(bt,n);let u=NS(n,Aa(bt,RS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new bt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=GS(l),f="",p=o,m;if(u){let w=t[4];w?(f=w[0]??=It(o),p=w[1]??=fr(f)):(f=It(o),m=Pd.encode(`${a}.${f}`))}m??=Qr(fr(a),fr("."),p);let g=await Mo(await jo(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&Od(d.alg,g);let v={signature:It(new Uint8Array(await crypto.subtle.sign(d.signing,g,m))),payload:f};return n&&(v.protected=a),i&&(v.header=i),[v,u]}async function VB(t,e,r,o,n){let[i]=await Ofe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var jh=class{#e;#t;constructor(e){Cn(e,"payload"),this.#e=e}setProtectedHeader(e){return Yn(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return VB(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var JC='"alg" (Algorithm)';function GC(t='JWK "alg" (Algorithm) Parameter'){throw new at(`Invalid or unsupported ${t} value`)}function Mh(t,e){return(typeof t=="string"?KC[t]??js[t]:void 0)??GC(e)}async function Pa(t){if(RC(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:It(t)};if(!Ta(t))throw new TypeError(zs(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 Ms=(t,e)=>{if(typeof t!="string"||!t)throw new Rh(`${e} missing or invalid`)};async function XC(t,e){let r;if(Ft(t)){if(r=jS(t),typeof r.kty!="string")throw new TypeError(zs(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(CC(t))r=jS(await Pa(t));else throw new TypeError(zs(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":Ms(r.alg,'"alg" (Algorithm) Parameter'),Ms(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Ms(r.crv,'"crv" (Curve) Parameter'),Ms(r.x,'"x" (X Coordinate) Parameter'),Ms(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Ms(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Ms(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Ms(r.e,'"e" (Exponent) Parameter'),Ms(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 Rh('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new at('"kty" (Key Type) Parameter missing or unsupported')}let n=fr(JSON.stringify(o));return It(await AS(e,n))}async function Qn(t,e,r){if(!Ft(t))throw new TypeError("JWK must be an object");let o=DC(t),n=MS(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 gu(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 Nd(Mh(e),o,n)}case"RSA":case"EC":case"OKP":return Nd(Mh(e),o,n);default:throw new at('Unsupported "kty" (Key Type) Parameter value')}}function YC(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 Cd(e,TypeError,r)}function Nfe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new at("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Uh(t,e){let r=MS(e?.extractable),o=Mh(t,JC);o.secret&&GC(JC);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new at("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 at(`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:Nfe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}typeof window<"u"&&h.config({jitless:!0});var k=h.uuid(),fe=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),rt=h.iso.datetime(),eo=h.json(),bu=h.record(h.string(),eo),HB=h.enum(["ja","en"]),eO=h.enum(["read","create","update","delete","share","transfer","reveal","use","execute","credentials","billing","export"]),Dfe=h.enum(["secret","connection","service","method","app","object","environment","function"]),Or=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),zfe=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:k}).strict(),YS=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return zfe.safeParse(YC(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Fo=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:k,epk:Or.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),c2e=h.object({id:k,name:fe,publicKey:Or}),Ud=h.object({id:k,name:fe,createdAt:rt,permissions:h.array(eO),createKinds:h.array(Dfe),publicKey:Or.nullable()}),qB=h.object({id:k,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:rt,lastUsedAt:rt.nullable(),expiresAt:rt.nullable()}),jfe=h.object({subjectId:k,relation:h.enum(["agent","member","payer"]),principalId:k}).strict(),u2e=jfe.extend({id:k,createdAt:rt,subjectName:fe,principalName:fe}).extend({relation:h.enum(["owner","agent","member","payer"])}),l2e=h.object({principalId:k,actions:h.array(eO).min(1),principalName:fe.optional()}),d2e=h.object({error:h.object({code:h.string(),message:h.string(),details:eo.optional()})}),f2e=h.object({ok:h.literal(!0)}),ZB=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional()}),KB=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),Mfe=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),separator:h.string().default(" "),docs:h.url().optional()}),XS=h.string().min(1).max(4096),BB=h.union([h.string(),h.array(h.string()).min(1)]),WB=h.object({issuer:h.url().optional(),authorizeUrl:XS,tokenUrl:XS,identity:h.object({url:XS.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:BB.default("/id"),name:BB.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),revoke:h.object({url:XS,style:h.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:h.enum(["body","basic","none"]).optional()}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:Mfe.default({default:[],separator:" "}),fields:h.array(ZB).default([]),outputs:KB.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.enum(["google","github","ebay","openrouter","cloudflare","slack"]).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}),JB=h.object({fields:h.array(ZB).min(1),outputs:KB,console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}),tO=h.enum(["oauth","token","role"]),GB=h.object({kind:h.literal("aws"),hint:h.string().optional()}),rO={name:fe,docs:h.url().optional(),console:h.url().optional()},XB=h.object({...rO,kind:h.literal("oauth"),config:WB}).strict(),YB=h.object({...rO,kind:h.literal("token"),config:JB}).strict(),QB=h.object({...rO,kind:h.literal("role"),config:GB}).strict(),_u=h.discriminatedUnion("kind",[XB,YB,QB]),QC={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"])},nO=h.discriminatedUnion("kind",[XB.extend(QC),YB.extend(QC),QB.extend(QC)]),oO=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),QS=h.object({name:fe,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional()}).strict(),Ufe=QS.extend({auth:h.object({oauth:WB.optional(),token:JB.optional(),role:GB.optional()}).strict()}).strict(),Lfe=QS.extend({methods:h.record(oO,h.string().min(1))}).strict(),Ffe=QS.extend({methods:h.record(oO,h.union([h.string().min(1),_u]))}).strict(),eH=h.union([Ffe,Ufe]),p2e=QS.extend({id:h.string(),builtin:h.boolean(),methods:h.record(oO,nO)}),tH=h.discriminatedUnion("kind",[h.object({kind:h.literal("secret"),id:k}).strict(),h.object({kind:h.literal("connection"),id:k,output:h.string().min(1).max(100)}).strict()]),iO=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:tH,format:h.enum(["text","file","json"]).default("text"),pointer:h.string().optional()}).strict(),Vfe=h.object({pointer:h.string().max(500),parts:h.array(h.union([h.string().max(8192),tH])).min(1).max(32)}).strict(),Su=h.object({url:h.string().max(4096),method:h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:h.record(h.string(),h.string().max(8192)).default({}),body:h.string().max(1e6).optional(),json:eo.optional(),form:h.record(h.string(),h.string()).optional(),bindings:h.array(Vfe).max(32).default([])}).strict(),Lh=h.object({description:h.string().max(2e3).default(""),request:Su,parameters:h.array(h.object({name:h.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:h.string().max(100),required:h.boolean().default(!0),default:h.string().optional()})).max(32).default([]),save:h.record(h.string(),fe).default({}),outputOwnerId:k.optional()}).strict(),Ra={id:k,ownerId:k,name:fe,createdAt:rt,updatedAt:rt,version:h.number().int().positive(),permissions:h.array(eO)},Bfe=h.enum(["starting","running","stopping","stopped","failed"]),Hfe=h.object({idleSeconds:h.number().int().min(60).max(86400).default(3600),maxSeconds:h.number().int().min(60).max(86400).default(3600)}).strict(),rH=h.object({image:h.string().min(1).max(300).optional(),size:h.enum(["small","medium","large"]).default("small"),lifetime:Hfe.default({idleSeconds:3600,maxSeconds:3600}),callerIds:h.array(k).min(1).max(100).optional()}).strict(),sO={recipients:h.array(k).default([]),executors:h.array(k).default([]),custodyRevision:h.number().int().positive().nullable().default(null)},qfe=h.object({...Ra,kind:h.literal("secret"),data:h.object({...sO,bytes:h.number().int().nonnegative()})}),Zfe=h.object({...Ra,kind:h.literal("connection"),data:h.object({...sO,methodId:h.string(),methodName:h.string(),methodKind:tO,services:h.array(h.object({id:h.string(),name:fe})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:k.nullable(),generation:k.optional(),authorizationDigest:h.string().optional()})}),Kfe=h.object({...Ra,kind:h.literal("service"),data:Lfe}),Wfe=h.object({...Ra,kind:h.literal("method"),data:_u}),Jfe=h.object({...Ra,kind:h.literal("app"),data:h.object({...sO,methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:k.optional()})}),Gfe=h.object({...Ra,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),Xfe=h.object({...Ra,kind:h.literal("environment"),data:rH.extend({executorId:k.optional(),operatorId:k.optional(),driver:h.enum(["attached","managed"]).optional(),capabilities:h.array(h.string()).optional(),isolation:h.enum(["process","container"]).optional(),manifestDigest:h.string().optional(),state:Bfe,startedAt:rt.nullable(),stoppedAt:rt.nullable(),lastActiveAt:rt,error:h.string().nullable()})}),Yfe=h.object({...Ra,kind:h.literal("function"),data:Lh}),Pi=h.discriminatedUnion("kind",[qfe,Zfe,Kfe,Wfe,Jfe,Gfe,Xfe,Yfe]),m2e=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:fe,definition:eH}).strict(),h.object({kind:h.literal("method"),name:fe,definition:_u}).strict(),h.object({kind:h.literal("environment"),name:fe.optional(),options:rH}).strict(),h.object({kind:h.literal("function"),name:fe,definition:Lh}).strict()]),h2e=h.object({version:h.number().int().positive(),name:fe.optional(),definition:h.union([eH,_u,Lh]).optional()}).strict(),ex=h.object({command:h.array(h.string().max(8192)).min(1).max(100),stdin:h.string().max(1e6).optional(),timeoutSeconds:h.number().int().min(1).max(3600).default(60),inputs:h.array(iO).max(32).default([])}).strict(),nH=h.object({method:h.enum(["GET","POST","PUT","PATCH","DELETE","CONNECT"]),path:h.string().startsWith("/api/").max(2048),body:eo.optional(),inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()})).max(16).default([])}).strict(),Qfe=h.object({ja:h.string(),en:h.string()}).strict(),oH=h.object({ownerId:h.union([k,h.literal("$approver")]),methodId:h.string().min(1).max(200),connectionId:k.optional(),environmentId:k.optional(),name:fe.optional()}).strict(),iH=h.object({to:k.optional(),message:h.string().max(1e3).default(""),operations:h.array(nH).min(1).max(8),expiresInMinutes:h.number().int().min(1).max(1440).default(30)}).strict(),Ld=h.object({id:k,from:Ud.pick({id:!0,name:!0}),to:Ud.pick({id:!0,name:!0}).nullable(),message:h.string(),operations:h.array(nH.extend({title:Qfe})),state:h.enum(["pending","running","approved","declined","cancelled","expired"]),results:h.array(eo.nullable()),createdAt:rt,expiresAt:rt,url:h.url(),code:h.string().optional(),continueUrl:h.url().nullable(),returnUrl:h.url().nullable(),refreshUrl:h.url().nullable(),canRespond:h.boolean()}),g2e=h.object({id:k,name:fe,publicKey:Or,state:h.enum(["pending","approving","approved"]),principalId:k.nullable(),createdAt:rt,expiresAt:rt}),y2e=h.object({available:h.boolean(),required:h.boolean(),active:h.boolean(),payer:Ud.pick({id:!0,name:!0}).nullable()}),v2e=h.object({storageBytes:h.number().nonnegative(),storageLimit:h.number().positive(),computeSeconds:h.number().nonnegative(),computeLimit:h.number().positive(),month:h.string()}),w2e=h.object({id:h.string(),actorId:k.nullable(),action:h.string(),targetId:k.nullable(),createdAt:rt,details:bu}),b2e=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional(),webhookUrl:h.url().optional()}).strict(),xu=t=>h.object({items:h.array(t),next:h.string().nullable().default(null)}),_2e=h.object({id:k}),S2e=h.object({owner:k}),x2e=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()});var epe=h.object({email:h.boolean(),environments:h.boolean(),objects:h.boolean(),payments:h.boolean()}),tx=h.object({principal:Ud.nullable(),credentialId:k.nullable(),wrappedKey:YS.nullable(),requestId:k.nullable(),server:h.object({name:fe,commit:h.string().nullable()}),features:epe,principals:h.array(Ud)}),I2e=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:HB.default("ja"),principalId:k.optional()}).strict(),A2e=h.object({intent:h.enum(["register","authenticate"]),name:fe.optional(),principalId:k.optional(),returnTo:h.string().max(2048).optional()}).strict(),T2e=h.object({challengeId:k,credential:h.json(),publicKey:Or.optional(),existingPublicKey:Or.optional(),wrappedKey:YS.optional()}).strict();var tpe=new TextEncoder,rpe=new TextDecoder,Fh="ECDH-ES+A256KW",aO="A256GCM",lt=t=>tpe.encode(t),Eu=t=>rpe.decode(t);function Ca(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 sH(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function rx(){let t=await Uh(Fh,{crv:"P-256",extractable:!0});return{publicKey:Or.parse(await Pa(t.publicKey)),privateKey:await Pa(t.privateKey)}}async function ku(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 Dh(t).setProtectedHeader({enc:aO}).setAdditionalAuthenticatedData(lt(r));for(let n of e)o.addRecipient(await Qn(n.publicKey,Fh)).setUnprotectedHeader({alg:Fh,kid:n.id});return Fo.parse(await o.encrypt())}async function Ri(t,e,r,o){if(t.aad!==Ca(lt(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 Qn(e,Fh);return(await LC({...t,recipients:[n]},i,{keyManagementAlgorithms:[Fh],contentEncryptionAlgorithms:[aO]})).plaintext}async function npe(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:lt("Foundation"),info:lt("passkey encryption key")},e,256))}async function aH(t,e,r){let o=await Nh(t,await npe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[aO]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Eu(o.plaintext))}var pr=h.string().regex(/^[A-Za-z0-9_-]{43}$/),On=h.string().min(100).max(4e6),cH=Or.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Vh=h.object({encryption:cH,signing:cH}).strict(),Vt=h.object({id:k,principalId:k,generation:h.number().int().positive(),previous:pr.nullable(),encryption:Or,signing:Or}).strict();function R(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,R).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)+":"+R(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Fd(t){return XC(Or.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ge(t){return Ca(new Uint8Array(await crypto.subtle.digest("SHA-256",lt(R(t)))))}async function ox(){let[t,e]=await Promise.all([rx(),Uh("ES256",{crv:"P-256",extractable:!0})]),r=await Pa(e.privateKey);return Vh.parse({encryption:t.privateKey,signing:r})}function nx(t){return Or.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function ix(t,e){return Vt.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:nx(e.encryption),signing:nx(e.signing)})}async function yn(t,e,r){let o=e instanceof CryptoKey?e:await Qn(e,"ES256");return new jh(lt(R(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function to(t,e,r,o){if(R(await cO(e,r,o))!==R(t))throw new Error("The signature does not authorize this content.")}async function cO(t,e,r){let o=await WC(t,await Qn(Or.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(R(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Ci=h.object({binding:Vt,signature:On}).strict();async function Bh(t,e){if(await Us(t),await Fd(e.encryption)!==await Fd(t.encryption)||await Fd(e.signing)!==await Fd(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await yn(t,e.signing,"key-binding")}}async function Us(t){let e=Vt.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Fd(e.encryption)===await Fd(e.signing))throw new Error("Use separate encryption and signing keys.");await Qn(e.encryption,"ECDH-ES+A256KW"),await Qn(e.signing,"ES256")}async function uO(t){let{binding:e,signature:r}=Ci.parse(t);return await Us(e),await to(e,r,e.signing,"key-binding"),e}var Vd=h.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),lO=h.enum(["secret","connection","app"]),Hh=h.enum(["http","command","function","connect","refresh","revoke"]),ope=h.object({actor:Vt,executor:Vt,operations:h.array(Hh).min(1).max(6),functionDigests:h.array(pr).max(100).default([]),origins:h.array(Vd).max(100).default([]),callerProgram:h.boolean().default(!1),expiresAt:rt}).strict(),Ls=h.object({format:h.literal(1),origin:Vd,id:k,ownerId:k,kind:lO,revision:h.number().int().positive(),authorities:h.array(Vt).min(1).max(100),readers:h.array(Vt).min(1).max(100),grants:h.array(ope).max(100),observers:h.array(k).max(100).optional(),producers:h.array(h.object({executor:Vt,runId:k,expiresAt:rt,materialRevision:h.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),uH=h.object({ownerId:k,authorities:h.array(Vt).min(1).max(100)}).strict(),lH=h.object({origin:Vd,id:k,kind:lO,revision:h.number().int().positive(),from:uH,to:uH,policyDigest:pr,previous:pr.nullable(),signerId:k}).strict(),ipe=lH.extend({signature:On}),dO=h.array(ipe).max(16),qh=h.object({policy:Ls,authorityId:k,signature:On,lineage:dO.optional()}).strict(),ro=h.object({policy:Ls,authorityId:k,authorization:On,lineage:dO.optional(),materialRevision:h.number().int().positive(),updatedAt:rt,creationRunId:k.nullable(),metadata:bu,sealed:Fo,signerId:k,signature:On}).strict(),$u=t=>({ownerId:t.ownerId,authorities:t.authorities});async function dH(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.kind!==t.kind||o.revision>t.revision||r&&(o.revision<=r.revision||R(r.to)!==R(o.from))||o.previous!==(r?await ge(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 to(i,n,s.signing,"authority-handoff"),r=o}if(r&&R(r.to)!==R($u(t)))throw new Error("Use the authorities approved by the latest handoff.")}function fO(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 fH(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.kind!==e.policy.kind)return!1;let r=R($u(t));return r===R($u(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&R(o.from)===r)}async function pH(t,e,r,o){let n=[...t?.lineage??[]];if(t&&R($u(t.policy))!==R($u(e))){if(await Vo(t),!t.policy.authorities.some(s=>R(s)===R(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.kind!==e.kind||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=lH.parse({origin:e.origin,id:e.id,kind:e.kind,revision:e.revision,from:$u(t.policy),to:$u(e),policyDigest:await ge(e),previous:n.length?await ge(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await yn(i,o.signing,"authority-handoff")})}return n.length?{lineage:dO.parse(n)}:{}}async function sx(t){let e=Ls.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>[n.actor,n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Us(n);let i=R(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(n.operations.some(i=>["http","command"].includes(i))&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes("function")&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function ax(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Bd(t,e){return R({purpose:"resource",origin:t.origin,id:t.id,ownerId:t.ownerId,kind:t.kind,policyDigest:await ge(t),materialRevision:e})}async function mH(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await sx(e),c=await pH(s,a,o,n);if(!a.authorities.some(f=>R(f)===R(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await ku(t,ax(a).map(f=>({id:f.id,publicKey:f.encryption})),await Bd(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await yn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.kind==="secret"?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=ro.parse({...l,signature:await yn(l,n.signing,"resource")});return await Vo(d),d}async function Vo(t){let e=ro.parse(t),{signature:r,...o}=e;await sx(e.policy),await dH(e.policy,e.lineage);let n=fO(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ge(e.policy))throw new Error("The handoff approves a different access policy.");await to(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&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor??(e.policy.kind==="connection"?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes("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 to(o,r,s.signing,"resource");let a=ax(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(R(a)!==R(c)||e.sealed.aad!==Ca(lt(await Bd(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function hH(t,e,r,o,n=t.metadata){let i=await Vo(t);if(i.policy.kind!=="connection"||!(i.policy.authorities.some(f=>R(f)===R(r))||i.policy.grants.some(f=>R(f.executor)===R(r)&&f.operations.includes("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 ku(e,ax(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await Bd(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 yn(l,o.signing,"resource")};return await Vo(d),d}async function cx(t,e,r,o){let n=await sx(t);if(!n.authorities.some(s=>R(s)===R(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await pH(o,n,e,r),authorityId:e.id,signature:await yn(n,r.signing,"access-policy")};return await Hd(i),i}async function Hd(t){let e=qh.parse(t);await sx(e.policy),await dH(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ge(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 to(e.policy,e.signature,o.signing,"access-policy"),e}async function ux(t,e,r,o,n,i){let s=await Hd(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&R(f.executor)===R(o)&&Date.parse(f.expiresAt)>Date.now());if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let u=await ku(t,ax(a).map(f=>({id:f.id,publicKey:f.encryption})),await Bd(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 yn(l,n.signing,"resource")};return await Vo(d),d}async function lx(t,e,r){let o=await Vo(t);if(!o.policy.readers.some(n=>R(n)===R(e)))throw new Error("This identity cannot reveal the content.");return Ri(o.sealed,r,e.id,await Bd(o.policy,o.materialRevision))}var spe=h.object({id:k,kind:lO,policyDigest:pr,materialRevision:h.number().int().positive(),authorizationDigest:pr.optional()}).strict();async function pO(t,e){return e.id===t.policy.id&&e.kind===t.policy.kind&&e.policyDigest===await ge(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||e.kind==="connection"&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var dx=h.object({format:h.literal(1),id:k,origin:Vd,ownerId:k,approval:h.object({id:k,index:h.number().int().min(0).max(7)}).strict().optional(),actor:Vt,environmentId:k,executor:Vt,environmentDigest:pr,operation:Hh,functionDigest:pr.nullable(),operationDigest:pr,sources:h.array(spe).max(100),resultRecipients:h.array(Vt).min(1).max(100),createdAt:rt,expiresAt:rt}).strict(),fx=h.object({intent:dx,signature:On,sealed:Fo}).strict();async function Iu(t,e){return R({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ge(t)})}async function gH(t,e,r){if(dx.parse(t),await ge(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await ku(lt(R(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Iu(t,"input"))};return fx.parse({...o,signature:await yn(o,r.signing,"run")})}async function ape(t,e=Date.now()){let r=fx.parse(t),{signature:o,...n}=r;await to(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(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Ca(lt(await Iu(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function yH(t,e,r){let o=await ape(t);if(R(o.intent.executor)!==R(e))throw new Error("This operation belongs to another executor.");let n=await Ri(o.sealed,r.encryption,e.id,await Iu(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(R(s)!==i||await ge(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function Au(t,e,r={}){let o=await Vo(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await pO(o,i))throw new Error("The input changed after this execution was authorized.");if(R(e.actor)===R(e.executor)&&n.readers.some(c=>R(c)===R(e.actor)))return o;if(!n.grants.filter(c=>R(c.actor)===R(e.actor)&&R(c.executor)===R(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=>e.operation==="function"&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:!["command","http"].includes(e.operation)||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function qd(t,e,r,o={}){return await Au(t,e,o),Ri(t.sealed,r.encryption,e.executor.id,await Bd(t.policy,t.materialRevision))}var wH=h.object({format:h.literal(1),id:k,origin:Vd,ownerId:k,name:fe,executor:Vt,operatorId:k,driver:h.enum(["attached","managed"]),capabilities:h.array(Hh).min(1).max(6),callers:h.array(Vt).min(1).max(100),isolation:h.enum(["process","container"]),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),revision:h.number().int().positive()}).strict(),mO=h.object({manifest:wH,signature:On}).strict();async function bH(t,e){let r=wH.parse(t),o={manifest:r,signature:await yn(r,e.signing,"environment")};return await Zd(o),o}async function Zd(t){let e=mO.parse(t),{manifest:r}=e;await Us(r.executor);for(let o of r.callers)await Us(o);if(new Set(r.callers.map(o=>o.id)).size!==r.callers.length||new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct callers and execution capabilities.");if(r.capabilities.includes("command")&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes("command")&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await to(r,e.signature,r.executor.signing,"environment"),e}async function px(t,e){let{manifest:r}=await Zd(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ge(r)||R(e.executor)!==R(r.executor)||!r.callers.some(o=>R(o)===R(e.actor))||!r.capabilities.includes(e.operation))throw new Error("This environment does not authorize the requested execution.")}var cpe=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),_H=h.object({ok:h.boolean(),result:eo.nullable(),error:h.object({code:h.string().max(100),message:h.string().max(1e3)}).nullable()}).strict(),Kh=h.object({id:k,intentDigest:pr,executorId:k,state:h.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:rt,sealed:Fo,signature:On}).strict(),Zh=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Kd(t,e,r,o){let n=_H.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=lt(R(n));if(i.byteLength>14e5)throw new Zh;let s=await ku(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Iu(t,"result")),a={id:t.id,intentDigest:await ge(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Kh.parse({...a,signature:await yn(a,o.signing,"receipt")})}async function upe(t,e){let r=Kh.parse(t),{signature:o,...n}=r;if(await to(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ge(e)||r.executorId!==e.executor.id||r.sealed.aad!==Ca(lt(await Iu(e,"result")))||R(r.sealed.recipients.map(i=>i.header.kid).sort())!==R(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function SH(t,e,r,o){await upe(t,e);let n=await Ri(t.sealed,o.encryption,r,await Iu(e,"result")),i=_H.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 Nn=h.object({id:k,ownerId:k,actorId:k,environmentId:k,kind:Hh,state:cpe,intent:dx,requestSignature:On,receipt:Kh.nullable(),error:h.string().nullable(),createdAt:rt,startedAt:rt.nullable(),finishedAt:rt.nullable()}).strict(),vH=h.object({name:fe,approval:qh}).strict(),Wd=h.discriminatedUnion("kind",[h.object({kind:h.literal("http"),request:Su,save:h.record(h.string(),vH).default({})}).strict(),h.object({kind:h.literal("command"),...ex.shape}).strict(),h.object({kind:h.literal("function"),definition:Lh,arguments:h.record(h.string(),h.string()).default({}),outputs:h.record(h.string(),vH).default({})}).strict(),h.object({kind:h.enum(["connect","refresh","revoke"]),input:eo}).strict()]);var Oa=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Na=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string()})}).parse(await n.json())}catch{throw new Oa("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new Oa(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await(await this.response(e,r)).json();return o?o.parse(n):n}async session(){return this.json("/api/session",{},tx)}};import{chmod as lpe,lstat as dpe,mkdir as fpe,open as hO,readFile as EH,rename as ppe,rm as mpe}from"node:fs/promises";import{dirname as hpe,join as gO,resolve as gpe}from"node:path";import{homedir as ype}from"node:os";import{randomUUID as vpe}from"node:crypto";var yO=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:Vh.nullable(),binding:Vt.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),kH=h.object({current:h.uuid(),identities:h.array(yO).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Fs(){return gO(process.env.XDG_CONFIG_HOME||gO(ype(),".config"),"foundation","identity.json")}function Da(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 mx(t){let e;try{let n=Fs(),i=await dpe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await lpe(n,384);let s=kH.parse(JSON.parse(await EH(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=Da(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Da(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 yO.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!==Da(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 Wh(t){let e=Fs(),r;try{r=kH.parse(JSON.parse(await EH(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=yO.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Jd(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 TF(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;TF(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 PF=new Set(["type","properties","required","additionalProperties"]),IF=["oneOf","anyOf"];function AF(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function zP(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!PF.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]??AF(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:zP(a)??{allOf:a};cr(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=AF(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 Ode(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of PF)if(n in t)return;let r=e.filter(n=>IF.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=zP(e);else{let n=r[0],i=IF.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=>zP([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,hh(t,o))}function _a(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):hh(u,m),hh(u,l),a._zod.parent===d)for(let v in u)v==="$ref"||v==="allOf"||v in l||delete u[v];if(m.$ref&&p.def)for(let v in u)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(u[v])===JSON.stringify(p.def[v])&&delete u[v]}let f=a._zod.parent;if(f&&f!==d){o(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())TF(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)??[])Ode(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)}hh(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,cr(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:wd(e,"input",t.processors),output:wd(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Xr(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 Xr(o.element,r);if(o.type==="set")return Xr(o.valueType,r);if(o.type==="lazy")return Xr(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 Xr(o.innerType,r);if(o.type==="intersection")return Xr(o.left,r)||Xr(o.right,r);if(o.type==="record"||o.type==="map")return Xr(o.keyType,r)||Xr(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Xr(o.in,r)||Xr(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Xr(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Xr(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Xr(n,r))return!0;return!!(o.rest&&Xr(o.rest,r))}return!1}var jP=(t,e={})=>r=>{let o=wa({...r,processors:e});return et(t,o),ba(o,t),_a(o,t)},wd=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=wa({...n??{},target:i,io:e,processors:r});return et(t,s),ba(s,t),_a(s,t)};var bd=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},_d=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},RF=(t,e)=>{bd(t,"minimum",e),_d(t,"maximum",e)},DF=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},zF=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},jF=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},MF=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},CF=(t,e)=>bd(t,"minimum",e.minimum),OF=(t,e)=>_d(t,"maximum",e.maximum),NF=t=>(e,r)=>{MF(e,r.format);let[o,n]=t[r.format];bd(e,"minimum",o),_d(e,"maximum",n)},Nde={greater_than:(t,e)=>bd(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>_d(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>DF(t,e.value),number_format:NF(wm),bigint_format:NF(bm),min_length:CF,max_length:OF,length_equals:(t,e)=>RF(t,e.length),min_size:CF,max_size:OF,size_equals:(t,e)=>RF(t,e.size),string_format:(t,e)=>{MF(t,e.format),e.pattern&&zF(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)=>jF(t,e.mime)};function Wt(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)Nde[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&bd(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&bd(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&_d(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&_d(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&DF(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&jF(e,n.mime);for(let i of n.patterns??[])zF(e,i);return e}var Dde={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},zde=new Map([[sb,ET],[Nm,kT]]),UF=t=>zde.get(t)??t,LP=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Wt(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=Dde[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(UF);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}))])}},FP=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Wt(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";if(d?p?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),f?p?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let w of a)Number.isFinite(w)&&w!==0?m.add(Math.abs(w)):Kt(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[g,...v]=m;g!==void 0&&(n.multipleOf=g),v.length&&(n.allOf=[...n.allOf??[],...v.map(w=>({multipleOf:w}))])}},VP=(t,e,r,o)=>{r.type="boolean"},BP=(t,e,r,o)=>{Kt(t,e,r,o,"BigInt cannot be represented in JSON Schema")},HP=(t,e,r,o)=>{Kt(t,e,r,o,"Symbols cannot be represented in JSON Schema")},qP=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},ZP=(t,e,r,o)=>{Kt(t,e,r,o,"Undefined cannot be represented in JSON Schema")},KP=(t,e,r,o)=>{Kt(t,e,r,o,"Void cannot be represented in JSON Schema")},WP=(t,e,r,o)=>{r.not={}},JP=(t,e,r,o)=>{},GP=(t,e,r,o)=>{},XP=(t,e,r,o)=>{Kt(t,e,r,o,"Date cannot be represented in JSON Schema")},YP=(t,e,r,o)=>{let n=t._zod.def,i=Dl(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},QP=(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(Kt(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Kt(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},eR=(t,e,r,o)=>{Kt(t,e,r,o,"NaN cannot be represented in JSON Schema")},tR=(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},rR=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Wt(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})))},nR=(t,e,r,o)=>{r.type="boolean"},oR=(t,e,r,o)=>{Kt(t,e,r,o,"Custom types cannot be represented in JSON Schema")},iR=(t,e,r,o)=>{Kt(t,e,r,o,"Function types cannot be represented in JSON Schema")},sR=(t,e,r,o)=>{Kt(t,e,r,o,"Transforms cannot be represented in JSON Schema")},aR=(t,e,r,o)=>{Kt(t,e,r,o,"Map cannot be represented in JSON Schema")},cR=(t,e,r,o)=>{Kt(t,e,r,o,"Set cannot be represented in JSON Schema")},uR=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Wt(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=et(i.element,e,{...o,path:[...o.path,"items"]})};function gh(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?gh(e.out):e.type==="catch"?gh(e.innerType):t._zod.optin}var lR=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Kt(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)cr(n.properties,u,et(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"?gh(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=et(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},J_=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>et(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},dR=(t,e,r,o)=>{let n=t._zod.def,i=et(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=et(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)},fR=(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((g,v)=>et(g,e,{...o,path:[...o.path,s,v]})),u=i.rest?et(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 g=i.items[l-1];if(!(e.io==="input"?gh(g)!==void 0:g._zod.optout==="optional"))break;l--}let d=i.items.length,f=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,f?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),f&&(n.maxItems=d)):(n.items=c,f?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),f&&(n.maxItems=d));let{minimum:p,maximum:m}=Wt(t);typeof p=="number"&&(n.minItems=p),typeof m=="number"&&(n.maxItems=m)};function MP(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let m=t.get(e)?.def;if(!m)return e;let g=MP(t,m,r);return g===m?e:g}for(let m of["anyOf","oneOf"]){let g=e[m];if(!Array.isArray(g))continue;let v=g.map(w=>MP(t,w,r));v.some((w,b)=>w!==g[b])&&(e={...e,[m]:v})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:f,...p}=e;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),n&&(p.type="string",i||(p.pattern=(o.includes("number")?Os:Im).source)),p}var UP=new WeakMap;function jde(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 UP.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=MP(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 pR=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Wt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=et(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)cr(n.patternProperties,UF(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=et(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=UP.get(e);l||(l=[],UP.set(e,l),e.deferred.push(()=>jde(e))),l.push(t)}n.additionalProperties=et(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&gh(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))}},mR=(t,e,r,o)=>{let n=t._zod.def,i=et(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"}]},hR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},gR=Symbol();function LF(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Kt(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),gR):JSON.parse(s)}var yR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=LF(n.defaultValue,t,e,r,o);s!==gR&&(r.default=s)},vR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=LF(n.defaultValue,t,e,r,o);s!==gR&&(r._prefault=s)},wR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Kt(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},bR=(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;et(s,e,o);let a=e.seen.get(t);a.ref=s},_R=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},SR=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},G_=(t,e,r,o)=>{let n=t._zod.def;et(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},xR=(t,e,r,o)=>{let n=t._zod.innerType;et(n,e,o);let i=e.seen.get(t);i.ref=n},W_={string:LP,number:FP,boolean:VP,bigint:BP,symbol:HP,null:qP,undefined:ZP,void:KP,never:WP,any:JP,unknown:GP,date:XP,enum:YP,literal:QP,nan:eR,template_literal:tR,file:rR,success:nR,custom:oR,function:iR,transform:sR,map:aR,set:cR,array:uR,object:lR,union:J_,intersection:dR,tuple:fR,record:pR,nullable:mR,nonoptional:hR,default:yR,prefault:vR,catch:wR,pipe:bR,readonly:_R,promise:SR,optional:G_,lazy:xR};function uu(t,e){if("_idmap"in t){let o=t,n=wa({...e,processors:W_}),i={};for(let c of o._idmap.entries()){let[u,l]=c;et(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;ba(n,l),cr(s,u,_a(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=wa({...e,processors:W_});return et(t,r),ba(r,t),_a(r,t)}var X_=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=wa({processors:W_,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 et(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,ba(this.ctx,e);let o=_a(this.ctx,e),{"~standard":n,...i}=o;return i}};var FF={};var Td={};gt(Td,{ZodAny:()=>VR,ZodArray:()=>ZR,ZodBase64:()=>gS,ZodBase64URL:()=>yS,ZodBigInt:()=>Id,ZodBigIntFormat:()=>bS,ZodBoolean:()=>$d,ZodCIDRv4:()=>mS,ZodCIDRv6:()=>hS,ZodCUID:()=>aS,ZodCUID2:()=>cS,ZodCatch:()=>dC,ZodCodec:()=>kh,ZodCreditCard:()=>jR,ZodCustom:()=>$h,ZodCustomStringFormat:()=>du,ZodDate:()=>bh,ZodDefault:()=>iC,ZodDiscriminatedUnion:()=>WR,ZodE164:()=>vS,ZodEmail:()=>nS,ZodEmoji:()=>iS,ZodEnum:()=>xd,ZodExactOptional:()=>xS,ZodFile:()=>tC,ZodFunction:()=>_C,ZodGUID:()=>oS,ZodIBAN:()=>MR,ZodIPv4:()=>fS,ZodIPv6:()=>pS,ZodISODate:()=>xa,ZodISODateTime:()=>Sa,ZodISODuration:()=>ka,ZodISOTime:()=>Ea,ZodInstanceOf:()=>EC,ZodIntersection:()=>JR,ZodJWT:()=>wS,ZodKSUID:()=>dS,ZodLazy:()=>vC,ZodLiteral:()=>eC,ZodMAC:()=>zR,ZodMap:()=>YR,ZodNaN:()=>pC,ZodNanoID:()=>sS,ZodNever:()=>HR,ZodNonOptional:()=>ES,ZodNull:()=>FR,ZodNullable:()=>oC,ZodNumber:()=>kd,ZodNumberFormat:()=>fu,ZodObject:()=>_h,ZodOptional:()=>pu,ZodPipe:()=>Eh,ZodPrefault:()=>aC,ZodPreprocess:()=>mC,ZodPromise:()=>bC,ZodReadonly:()=>hC,ZodRecord:()=>Sd,ZodSet:()=>QR,ZodString:()=>Ed,ZodStringFormat:()=>it,ZodSuccess:()=>lC,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>yC,ZodTransform:()=>rC,ZodTuple:()=>GR,ZodType:()=>ve,ZodULID:()=>uS,ZodURL:()=>vh,ZodUUID:()=>Ti,ZodUndefined:()=>LR,ZodUnion:()=>Sh,ZodUnknown:()=>BR,ZodVoid:()=>qR,ZodXID:()=>lS,ZodXor:()=>KR,_ZodString:()=>rS,_default:()=>sC,_function:()=>JV,any:()=>PV,array:()=>Ae,base64:()=>lV,base64url:()=>dV,bigint:()=>kV,boolean:()=>Mt,catch:()=>fC,check:()=>GV,cidrv4:()=>cV,cidrv6:()=>uV,codec:()=>qV,creditCard:()=>pV,cuid:()=>eV,cuid2:()=>tV,currencyCode:()=>wV,custom:()=>kS,date:()=>CV,describe:()=>XV,discriminatedUnion:()=>xh,e164:()=>fV,email:()=>HF,emoji:()=>YF,enum:()=>dr,exactOptional:()=>nC,file:()=>FV,float32:()=>_V,float64:()=>SV,function:()=>JV,guid:()=>qF,hash:()=>bV,hex:()=>vV,hostname:()=>yV,httpUrl:()=>XF,iban:()=>mV,instanceof:()=>QV,int:()=>eS,int32:()=>xV,int64:()=>$V,intersection:()=>Ad,invertCodec:()=>ZV,ipv4:()=>iV,ipv6:()=>aV,json:()=>tB,jwt:()=>hV,keyof:()=>OV,ksuid:()=>oV,lazy:()=>wC,literal:()=>G,looseObject:()=>lr,looseRecord:()=>jV,mac:()=>sV,map:()=>MV,meta:()=>YV,nan:()=>HV,nanoid:()=>QF,nativeEnum:()=>LV,never:()=>_S,nonoptional:()=>uC,null:()=>wh,nullable:()=>yh,nullish:()=>VV,number:()=>qe,object:()=>V,optional:()=>ot,partialRecord:()=>zV,pipe:()=>tS,prefault:()=>cC,preprocess:()=>Ih,promise:()=>WV,readonly:()=>gC,record:()=>st,refine:()=>SC,set:()=>UV,strictObject:()=>NV,string:()=>$,stringFormat:()=>gV,stringbool:()=>eB,success:()=>BV,superRefine:()=>xC,symbol:()=>AV,templateLiteral:()=>KV,transform:()=>SS,tuple:()=>XR,uint32:()=>EV,uint64:()=>IV,ulid:()=>rV,undefined:()=>TV,union:()=>tt,unknown:()=>ut,url:()=>GF,uuid:()=>ZF,uuidv4:()=>KF,uuidv6:()=>WF,uuidv7:()=>JF,void:()=>RV,xid:()=>nV,xor:()=>DV});var Y_={};gt(Y_,{endsWith:()=>dd,gt:()=>Ii,gte:()=>Rn,includes:()=>ud,length:()=>cu,lowercase:()=>ad,lt:()=>$i,lte:()=>Pn,maxLength:()=>au,maxSize:()=>ya,mime:()=>pd,minLength:()=>Ns,minSize:()=>Ai,multipleOf:()=>ga,negative:()=>j_,nonnegative:()=>U_,nonpositive:()=>M_,normalize:()=>md,overwrite:()=>Do,positive:()=>z_,properties:()=>fd,property:()=>L_,regex:()=>sd,size:()=>su,slugify:()=>vd,startsWith:()=>ld,toLowerCase:()=>gd,toUpperCase:()=>yd,trim:()=>hd,uppercase:()=>cd});var VF=new WeakSet([Object.prototype,Error.prototype]);function Q_(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 BF=(t,e)=>{oT.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);VF.has(r)||(VF.add(r),Q_(r,"format",o=>n=>km(o,n)),Q_(r,"flatten",o=>n=>Em(o,n)),Q_(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,zl,2)}),Q_(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,zl,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Ude=S("ZodError",BF),hn=S("ZodError",BF,void 0,{Parent:Error});var ER=Fl(hn),kR=Vl(hn),$R=Bl(hn),IR=ql(hn),AR=_w(hn),TR=Sw(hn),PR=xw(hn),RR=Ew(hn),CR=kw(hn),OR=$w(hn),NR=Iw(hn),DR=Aw(hn);function Fde(){Yt.localeError||Ct(i_())}function lu(){Yt.memoizer||Ct({memoizer:Vm()})}var ve=S("ZodType",(t,e)=>(Fde(),ae.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(I.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 He(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(SC(t,e))},superRefine(t,e){return this.check(xC(t,e))},overwrite(t){return this.check(Do(t))},optional(){return ot(this)},exactOptional(){return nC(this)},nullable(){return yh(this)},nullish(){return ot(yh(this))},nonoptional(t){return uC(this,t)},array(){return Ae(this)},or(t){return tt([this,t])},and(t){return Ad(this,t)},transform(t){return tS(this,SS(t))},default(t){return sC(this,t)},prefault(t){return cC(this,t)},catch(t){return fC(this,t)},pipe(t){return tS(this,t)},readonly(){return gC(this)},describe(t){let e=this.clone();return ur.add(e,{description:t}),e},meta(...t){if(t.length===0)return ur.get(this);let e=this.clone();return ur.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 I.hide(this,"~standard",{...Uw(this),jsonSchema:{input:wd(this,"input"),output:wd(this,"output")}})},set"~standard"(t){I.own(this,"~standard",t)},parse:function t(e,r){return ER(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await kR(this,e,r,{callee:t})},safeParse(t,e){return $R(this,t,e)},async safeParseAsync(t,e){return IR(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){I.own(this,"spa",t)},validate(t,e){return Kl(this,t,e)},validateAsync(t,e){return Wl(this,t,e)},encode:function t(e,r){return AR(this,e,r,{callee:t})},decode:function t(e,r){return TR(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await PR(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await RR(this,e,r,{callee:t})},safeEncode(t,e){return CR(this,t,e)},safeDecode(t,e){return OR(this,t,e)},async safeEncodeAsync(t,e){return NR(this,t,e)},async safeDecodeAsync(t,e){return DR(this,t,e)},toJSONSchema(t){return jP(this,{})(t)},get description(){return ur.get(this)?.description},get _def(){return this._zod.def}}),rS=S("_ZodString",(t,e)=>{ha.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>LP(t,r,o,n)},I.derived({format:t=>Wt(t).format??null,minLength:t=>Wt(t).minimum??null,maxLength:t=>Wt(t).maximum??null},{regex(...t){return this.check(sd(...t))},includes(...t){return this.check(ud(...t))},startsWith(...t){return this.check(ld(...t))},endsWith(...t){return this.check(dd(...t))},min(...t){return this.check(Ns(...t))},max(...t){return this.check(au(...t))},length(...t){return this.check(cu(...t))},nonempty(...t){return this.check(Ns(1,...t))},lowercase(t){return this.check(ad(t))},uppercase(t){return this.check(cd(t))},trim(){return this.check(hd())},normalize(...t){return this.check(md(...t))},toLowerCase(){return this.check(gd())},toUpperCase(){return this.check(yd())},slugify(){return this.check(vd())}})),Ed=S("ZodString",(t,e)=>{ha.init(t,e),rS.init(t,e)},{email(t){return this.check(Hm(nS,t))},url(t){return this.check(id(vh,t))},jwt(t){return this.check(lh(wS,t))},emoji(t){return this.check(Gm(iS,t))},guid(t){return this.check(qm(oS,t))},uuid(t){return this.check(Zm(Ti,t))},uuidv4(t){return this.check(Km(Ti,t))},uuidv6(t){return this.check(Wm(Ti,t))},uuidv7(t){return this.check(Jm(Ti,t))},nanoid(t){return this.check(Xm(sS,t))},cuid(t){return this.check(Ym(aS,t))},cuid2(t){return this.check(Qm(cS,t))},ulid(t){return this.check(eh(uS,t))},base64(t){return this.check(ah(gS,t))},base64url(t){return this.check(ch(yS,t))},xid(t){return this.check(th(lS,t))},ksuid(t){return this.check(rh(dS,t))},ipv4(t){return this.check(nh(fS,t))},ipv6(t){return this.check(oh(pS,t))},cidrv4(t){return this.check(ih(mS,t))},cidrv6(t){return this.check(sh(hS,t))},e164(t){return this.check(uh(vS,t))},datetime(t){return this.check(dh(Sa,t))},date(t){return this.check(fh(xa,t))},time(t){return this.check(ph(Ea,t))},duration(t){return this.check(mh(ka,t))}});function $(t){return p_(Ed,t)}var it=S("ZodStringFormat",(t,e)=>{We.init(t,e),rS.init(t,e)}),Sa=S("ZodISODateTime",(t,e)=>{pP.init(t,e),it.init(t,e)}),xa=S("ZodISODate",(t,e)=>{mP.init(t,e),it.init(t,e)}),Ea=S("ZodISOTime",(t,e)=>{hP.init(t,e),it.init(t,e)}),ka=S("ZodISODuration",(t,e)=>{gP.init(t,e),it.init(t,e)}),nS=S("ZodEmail",(t,e)=>{Vw.init(t,e),it.init(t,e)});function HF(t){return Hm(nS,t)}var oS=S("ZodGUID",(t,e)=>{Lw.init(t,e),it.init(t,e)});function qF(t){return qm(oS,t)}var Ti=S("ZodUUID",(t,e)=>{Fw.init(t,e),it.init(t,e)});function ZF(t){return Zm(Ti,t)}function KF(t){return Km(Ti,t)}function WF(t){return Wm(Ti,t)}function JF(t){return Jm(Ti,t)}var vh=S("ZodURL",(t,e)=>{Zw.init(t,e),it.init(t,e)});function GF(t){return id(vh,t)}function XF(t){return id(vh,{protocol:$m,hostname:IT,...I.normalizeParams(t)})}var iS=S("ZodEmoji",(t,e)=>{Kw.init(t,e),it.init(t,e)});function YF(t){return Gm(iS,t)}var sS=S("ZodNanoID",(t,e)=>{Ww.init(t,e),it.init(t,e)});function QF(t){return Xm(sS,t)}var aS=S("ZodCUID",(t,e)=>{Jw.init(t,e),it.init(t,e)});function eV(t){return Ym(aS,t)}var cS=S("ZodCUID2",(t,e)=>{Gw.init(t,e),it.init(t,e)});function tV(t){return Qm(cS,t)}var uS=S("ZodULID",(t,e)=>{Xw.init(t,e),it.init(t,e)});function rV(t){return eh(uS,t)}var lS=S("ZodXID",(t,e)=>{Yw.init(t,e),it.init(t,e)});function nV(t){return th(lS,t)}var dS=S("ZodKSUID",(t,e)=>{Qw.init(t,e),it.init(t,e)});function oV(t){return rh(dS,t)}var fS=S("ZodIPv4",(t,e)=>{eb.init(t,e),it.init(t,e)});function iV(t){return nh(fS,t)}var zR=S("ZodMAC",(t,e)=>{rb.init(t,e),it.init(t,e)});function sV(t){return m_(zR,t)}var pS=S("ZodIPv6",(t,e)=>{tb.init(t,e),it.init(t,e)});function aV(t){return oh(pS,t)}var mS=S("ZodCIDRv4",(t,e)=>{nb.init(t,e),it.init(t,e)});function cV(t){return ih(mS,t)}var hS=S("ZodCIDRv6",(t,e)=>{ib.init(t,e),it.init(t,e)});function uV(t){return sh(hS,t)}var gS=S("ZodBase64",(t,e)=>{ab.init(t,e),it.init(t,e)});function lV(t){return ah(gS,t)}var yS=S("ZodBase64URL",(t,e)=>{ub.init(t,e),it.init(t,e)});function dV(t){return ch(yS,t)}var vS=S("ZodE164",(t,e)=>{lb.init(t,e),it.init(t,e)});function fV(t){return uh(vS,t)}var jR=S("ZodCreditCard",(t,e)=>{fb.init(t,e),it.init(t,e)});function pV(t){return h_(jR,t)}var MR=S("ZodIBAN",(t,e)=>{mb.init(t,e),it.init(t,e)});function mV(t){return g_(MR,t)}var wS=S("ZodJWT",(t,e)=>{gb.init(t,e),it.init(t,e)});function hV(t){return lh(wS,t)}var du=S("ZodCustomStringFormat",(t,e)=>{yb.init(t,e),it.init(t,e)});function gV(t,e,r={}){return va(du,t,e,r)}function yV(t){return va(du,"hostname",$T,t)}function vV(t){return va(du,"hex",FT,t)}function wV(t){return va(du,"currency_code",TT,t)}function bV(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Tn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return va(du,o,n,e)}var kd=S("ZodNumber",(t,e)=>{Dm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>FP(t,r,o,n),t.isFinite=!0},I.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Wt(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Wt(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Wt(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Wt(t).format??null},{gt(t,e){return this.check(Ii(t,e))},gte(t,e){return this.check(Rn(t,e))},min(t,e){return this.check(Rn(t,e))},lt(t,e){return this.check($i(t,e))},lte(t,e){return this.check(Pn(t,e))},max(t,e){return this.check(Pn(t,e))},int(t){return this.check(eS(t))},safe(t){return this.check(eS(t))},positive(t){return this.check(Ii(0,t))},nonnegative(t){return this.check(Rn(0,t))},negative(t){return this.check($i(0,t))},nonpositive(t){return this.check(Pn(0,t))},multipleOf(t,e){return this.check(ga(t,e))},step(t,e){return this.check(ga(t,e))},finite(){return this}}));function qe(t){return y_(kd,t)}var fu=S("ZodNumberFormat",(t,e)=>{vb.init(t,e),kd.init(t,e)});function eS(t){return v_(fu,t)}function _V(t){return w_(fu,t)}function SV(t){return b_(fu,t)}function xV(t){return __(fu,t)}function EV(t){return S_(fu,t)}var $d=S("ZodBoolean",(t,e)=>{Xl.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>VP(t,r,o,n)});function Mt(t){return x_($d,t)}var Id=S("ZodBigInt",(t,e)=>{zm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>BP(t,r,o,n)},I.derived({minValue:t=>Wt(t).minimum??null,maxValue:t=>Wt(t).maximum??null,format:t=>Wt(t).format??null},{gte(t,e){return this.check(Rn(t,e))},min(t,e){return this.check(Rn(t,e))},gt(t,e){return this.check(Ii(t,e))},lt(t,e){return this.check($i(t,e))},lte(t,e){return this.check(Pn(t,e))},max(t,e){return this.check(Pn(t,e))},positive(t){return this.check(Ii(BigInt(0),t))},negative(t){return this.check($i(BigInt(0),t))},nonpositive(t){return this.check(Pn(BigInt(0),t))},nonnegative(t){return this.check(Rn(BigInt(0),t))},multipleOf(t,e){return this.check(ga(t,e))}}));function kV(t){return E_(Id,t)}var bS=S("ZodBigIntFormat",(t,e)=>{wb.init(t,e),Id.init(t,e)});function $V(t){return k_(bS,t)}function IV(t){return $_(bS,t)}var UR=S("ZodSymbol",(t,e)=>{bb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HP(t,r,o,n)});function AV(t){return I_(UR,t)}var LR=S("ZodUndefined",(t,e)=>{_b.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ZP(t,r,o,n)});function TV(t){return A_(LR,t)}var FR=S("ZodNull",(t,e)=>{Sb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qP(t,r,o,n)});function wh(t){return T_(FR,t)}var VR=S("ZodAny",(t,e)=>{xb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JP(t,r,o,n)});function PV(){return P_(VR)}var BR=S("ZodUnknown",(t,e)=>{Eb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GP(t,r,o,n)});function ut(){return R_(BR)}var HR=S("ZodNever",(t,e)=>{kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WP(t,r,o,n)});function _S(t){return C_(HR,t)}var qR=S("ZodVoid",(t,e)=>{$b.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>KP(t,r,o,n)});function RV(t){return O_(qR,t)}var bh=S("ZodDate",(t,e)=>{Ib.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XP(t,r,o,n),t.min=(r,o)=>t.check(Rn(r,o)),t.max=(r,o)=>t.check(Pn(r,o))},I.derived({minDate:t=>{let{minimum:e}=Wt(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Wt(t);return e?new Date(e):null}},{}));function CV(t){return N_(bh,t)}var ZR=S("ZodArray",(t,e)=>{lu(),Ab.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uR(t,r,o,n),t.element=e.element},{min(t,e){return this.check(Ns(t,e))},nonempty(t){return this.check(Ns(1,t))},max(t,e){return this.check(au(t,e))},length(t,e){return this.check(cu(t,e))},unwrap(){return this.element}});function Ae(t,e){return DP(ZR,t,e)}function OV(t){let e=t._zod.def.shape;return dr(Object.keys(e))}var _h=S("ZodObject",(t,e)=>{lu(),yP.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lR(t,r,o,n),I.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return dr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(I.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(I.mergeDefs(this._zod.def,{catchall:ut()}))},loose(){return this.clone(I.mergeDefs(this._zod.def,{catchall:ut()}))},strict(){return this.clone(I.mergeDefs(this._zod.def,{catchall:_S()}))},strip(){return this.clone(I.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return I.extend(this,t)},safeExtend(t){return I.safeExtend(this,t)},merge(t){return I.merge(this,t)},pick(t){return I.pick(this,t)},omit(t){return I.omit(this,t)},partial(...t){return I.partial(pu,this,t[0])},exactPartial(...t){return I.partial(xS,this,t[0],"exactPartial")},required(...t){return I.required(ES,this,t[0])}});function V(t,e){let r={type:"object",shape:t??{},...I.normalizeParams(e)};return new _h(r)}function NV(t,e){return new _h({type:"object",shape:t,catchall:_S(),...I.normalizeParams(e)})}function lr(t,e){return new _h({type:"object",shape:t,catchall:ut(),...I.normalizeParams(e)})}var Sh=S("ZodUnion",(t,e)=>{Yl.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>J_(t,r,o,n),t.options=e.options});function tt(t,e){return new Sh({type:"union",options:t,...I.normalizeParams(e)})}var KR=S("ZodXor",(t,e)=>{Sh.init(t,e),Pb.init(t,e),t._zod.processJSONSchema=(r,o,n)=>J_(t,r,o,n),t.options=e.options});function DV(t,e){return new KR({type:"union",options:t,inclusive:!1,...I.normalizeParams(e)})}var WR=S("ZodDiscriminatedUnion",(t,e)=>{Sh.init(t,e),Rb.init(t,e)});function xh(t,e,r){return new WR({type:"union",options:e,discriminator:t,...I.normalizeParams(r)})}var JR=S("ZodIntersection",(t,e)=>{Cb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dR(t,r,o,n)});function Ad(t,e){return new JR({type:"intersection",left:t,right:e})}var GR=S("ZodTuple",(t,e)=>{lu(),jm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fR(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 pu({type:"optional",innerType:e}))})}});function XR(t,e,r){let o=e instanceof ae,n=o?r:e,i=o?e:null;return new GR({type:"tuple",items:t,rest:i,...I.normalizeParams(n)})}var Sd=S("ZodRecord",(t,e)=>{lu(),Ob.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function st(t,e,r){return!e||!e._zod?new Sd({type:"record",keyType:$(),valueType:t,...I.normalizeParams(e)}):new Sd({type:"record",keyType:t,valueType:e,...I.normalizeParams(r)})}function zV(t,e,r){return new Sd({type:"record",keyType:t,valueType:e,...I.normalizeParams(r),partial:!0})}function jV(t,e,r){return new Sd({type:"record",keyType:t,valueType:e,mode:"loose",...I.normalizeParams(r)})}var YR=S("ZodMap",(t,e)=>{lu(),Nb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ai(...r)),t.nonempty=r=>t.check(Ai(1,r)),t.max=(...r)=>t.check(ya(...r)),t.size=(...r)=>t.check(su(...r))});function MV(t,e,r){return new YR({type:"map",keyType:t,valueType:e,...I.normalizeParams(r)})}var QR=S("ZodSet",(t,e)=>{lu(),Db.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cR(t,r,o,n),t.min=(...r)=>t.check(Ai(...r)),t.nonempty=r=>t.check(Ai(1,r)),t.max=(...r)=>t.check(ya(...r)),t.size=(...r)=>t.check(su(...r))});function UV(t,e){return new QR({type:"set",valueType:t,...I.normalizeParams(e)})}var xd=S("ZodEnum",(t,e)=>{zb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(o,n,i)=>YP(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 xd({...e,checks:[],...I.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 xd({...e,checks:[],...I.normalizeParams(n),entries:i})}});function dr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new xd({type:"enum",entries:r,...I.normalizeParams(e)})}function LV(t,e){return new xd({type:"enum",entries:t,...I.normalizeParams(e)})}var eC=S("ZodLiteral",(t,e)=>{jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QP(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 G(t,e){return new eC({type:"literal",values:Array.isArray(t)?t:[t],...I.normalizeParams(e)})}var tC=S("ZodFile",(t,e)=>{Mb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>rR(t,r,o,n),t.min=(r,o)=>t.check(Ai(r,o)),t.max=(r,o)=>t.check(ya(r,o)),t.mime=(r,o)=>t.check(pd(Array.isArray(r)?r:[r],o))});function FV(t){return F_(tC,t)}var rC=S("ZodTransform",(t,e)=>{lu(),Ub.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sR(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new ma(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(I.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(I.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 SS(t){return new rC({type:"transform",transform:t})}var pu=S("ZodOptional",(t,e)=>{Mm.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ot(t){return new pu({type:"optional",innerType:t})}var xS=S("ZodExactOptional",(t,e)=>{Lb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function nC(t){return new xS({type:"optional",innerType:t})}var oC=S("ZodNullable",(t,e)=>{Fb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function yh(t){return new oC({type:"nullable",innerType:t})}function VV(t){return ot(yh(t))}var iC=S("ZodDefault",(t,e)=>{Vb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function sC(t,e){return new iC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():I.shallowClone(e)}})}var aC=S("ZodPrefault",(t,e)=>{Bb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function cC(t,e){return new aC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():I.shallowClone(e)}})}var ES=S("ZodNonOptional",(t,e)=>{Hb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function uC(t,e){return new ES({type:"nonoptional",innerType:t,...I.normalizeParams(e)})}var lC=S("ZodSuccess",(t,e)=>{qb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function BV(t){return new lC({type:"success",innerType:t})}var dC=S("ZodCatch",(t,e)=>{Zb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function fC(t,e){return new dC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:I.constantCatch(e)})}var pC=S("ZodNaN",(t,e)=>{Kb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eR(t,r,o,n)});function HV(t){return D_(pC,t)}var Eh=S("ZodPipe",(t,e)=>{Um.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bR(t,r,o,n),t.in=e.in,t.out=e.out});function tS(t,e){return new Eh({type:"pipe",in:t,out:e})}var kh=S("ZodCodec",(t,e)=>{Eh.init(t,e),Ql.init(t,e)});function qV(t,e,r){return new kh({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function ZV(t){let e=t._zod.def;return new kh({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var mC=S("ZodPreprocess",(t,e)=>{Eh.init(t,e),wP.init(t,e)}),hC=S("ZodReadonly",(t,e)=>{Wb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function gC(t){return new hC({type:"readonly",innerType:t})}var yC=S("ZodTemplateLiteral",(t,e)=>{Jb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tR(t,r,o,n)});function KV(t,e){return new yC({type:"template_literal",parts:t,...I.normalizeParams(e)})}var vC=S("ZodLazy",(t,e)=>{ed.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xR(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function wC(t){return new vC({type:"lazy",getter:t})}var bC=S("ZodPromise",(t,e)=>{Xb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function WV(t){return new bC({type:"promise",innerType:t})}var _C=S("ZodFunction",(t,e)=>{Gb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iR(t,r,o,n)});function JV(t){return new _C({type:"function",input:Array.isArray(t?.input)?XR(t?.input):t?.input??Ae(ut()),output:t?.output??ut()})}var $h=S("ZodCustom",(t,e)=>{Yb.init(t,e),ve.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oR(t,r,o,n)});function GV(t){let e=new nt({check:"custom"});return e._zod.check=t,e}function kS(t,e){return V_($h,t??(()=>!0),e)}function SC(t,e={}){return B_($h,t,e)}function xC(t,e){return H_(t,e)}var XV=q_,YV=Z_,EC=S("ZodInstanceOf",(t,e)=>{$h.init(t,e)},{properties(t,e){return this.check(fd(t,e))}});function QV(t,e={}){let r=new EC({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...I.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 eB=(...t)=>K_({Codec:kh,Boolean:$d,String:Ed},...t);function tB(t){let e=wC(()=>tt([$(t),qe(),Mt(),wh(),Ae(e),st($(),e)]));return e}function Ih(t,e){return new mC({type:"pipe",in:SS(t),out:e})}var Vde={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 Bde(t){Ct({customError:t})}function Hde(){return Ct().customError}var kC;kC||(kC={});var mu={};gt(mu,{ZodISODate:()=>xa,ZodISODateTime:()=>Sa,ZodISODuration:()=>ka,ZodISOTime:()=>Ea,date:()=>Zde,datetime:()=>qde,duration:()=>Wde,time:()=>Kde});function qde(t){return dh(Sa,t)}function Zde(t){return fh(xa,t)}function Kde(t){return ph(Ea,t)}function Wde(t){return mh(ka,t)}var F={...Td,...Y_,iso:mu},Jde=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 Gde(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 rB(t,e){return t.map((r,o)=>o<e?r:r.optional())}function Xde(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Yde(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:Xde(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 Qde(t,e){return F.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 $C(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=$C(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=$C(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 efe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),tfe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Ah(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(Ah):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>efe.has(e)?Ah(r):!tfe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(Ah))}function nB(t){return t===1?"element":"elements"}function rfe(t,e){return F.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=$C(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 ${nB(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 ${nB(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function oB(t,e){if(t!==!1)return t===void 0||t===!0?F.any():Yr(t,e)}var nfe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function iB(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return F.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 F.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=Yde(n,e),s=Yr(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 F.null();if(n.length===0)return F.never();if(n.length===1)return F.literal(n[0]);if(n.every(s=>typeof s=="string"))return F.enum(n);let i=n.map(s=>F.literal(s));return i.length<2?i[0]:F.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return F.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return iB(s,e)});return n.length===0?F.never():n.length===1?n[0]:F.union(n)}if(!r)return F.any();let o;switch(r){case"string":{let n=F.string();if(t.format){let i=t.format;i==="email"?n=n.check(F.email()):i==="uri"||i==="uri-reference"?n=n.check(F.url()):i==="uuid"||i==="guid"?n=n.check(F.uuid()):i==="date-time"?n=n.check(F.iso.datetime({offset:!0})):i==="date"?n=n.check(F.iso.date()):i==="time"?n=n.check(F.regex(nfe)):i==="duration"?n=n.check(F.iso.duration()):i==="hostname"?n=n.check(F.hostname()):i==="ipv4"?n=n.check(F.ipv4()):i==="ipv6"?n=n.check(F.ipv6()):i==="mac"?n=n.check(F.mac()):i==="cidr"?n=n.check(F.cidrv4()):i==="cidr-v6"?n=n.check(F.cidrv6()):i==="base64"?n=n.check(F.base64()):i==="base64url"?n=n.check(F.base64url()):i==="e164"?n=n.check(F.e164()):i==="credit_card"?n=n.check(F.creditCard()):i==="iban"?n=n.check(F.iban()):i==="jwt"?n=n.check(F.jwt()):i==="emoji"?n=n.check(F.emoji()):i==="nanoid"?n=n.check(F.nanoid()):i==="cuid"?n=n.check(F.cuid()):i==="cuid2"?n=n.check(F.cuid2()):i==="ulid"?n=n.check(F.ulid()):i==="xid"?n=n.check(F.xid()):i==="ksuid"&&(n=n.check(F.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"?F.number().int():F.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=F.boolean();break}case"null":{o=F.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Yr(t.additionalProperties,e):void 0;for(let[d,f]of Object.entries(i)){let p=Yr(f,e);cr(n,d,s.has(d)?p:p.optional())}if(t.patternProperties){let d=t.patternProperties,f=Object.keys(d),p=[];for(let g of f){let v=Yr(d[g],e),w=F.string().regex(new RegExp(g));p.push(F.looseRecord(w,v))}let m=[];if(Object.keys(n).length>0&&m.push(F.object(n).passthrough()),m.push(...p),m.length===0)o=F.object({}).passthrough();else if(m.length===1)o=m[0];else{let g=F.intersection(m[0],m[1]);for(let v=2;v<m.length;v++)g=F.intersection(g,m[v]);o=g}if(t.additionalProperties===!1){let g=Object.keys(n),v=f.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!Gn(b.value))return;let _=[];for(let E of Object.keys(b.value))g.includes(E)||v.some(A=>A.test(E))||_.push(E);_.length&&b.issues.push({code:"unrecognized_keys",keys:_,input:b.value,inst:w})})}}else{let d=F.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=Yr(f,e)}o=Qde(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=>Yr(d,e)),c=rB(a,s),u=Array.isArray(i)?void 0:oB(i,e),l=F.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(F.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(F.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Yr(d,e)),c=rB(a,s),u=oB(t.additionalItems,e),l=F.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(F.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(F.maxLength(t.maxItems)))}else if(i!==void 0){let s=Yr(i,e),a=F.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=F.array(F.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=rfe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Yr(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 Yr(t,e){if(typeof t=="boolean")return t?F.any():F.never();let r=iB(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=>Yr(u,e)),c=F.union(a);r=o?F.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Yr(u,e)),c=F.xor(a);r=o?F.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:F.any();else{let a=o?r:Yr(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=F.intersection(a,Yr(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=F.nullable(r)),t.readOnly===!0&&(r=F.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&&!Ah(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&&!Ah(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))Jde.has(a)||cr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function sB(t,e){if(typeof t=="boolean")return t?F.any():F.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=Gde(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??ur};return Yr(r,i)}var aB=Symbol("z.visit/resolving");function Th(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===aB)return new ed({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,aB);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,f={};for(let m of l){let g=n(u[m]);g!==u[m]&&(d=!0),f[m]=g}let p=a.catchall;return a.catchall&&(p=n(a.catchall),p!==a.catchall&&(d=!0)),d?He(s,{...a,shape:f,catchall:p}):s}case"array":{let u=n(a.element);return u===a.element?s:He(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let p of u){let m=n(p);m!==p&&(l=!0),d.push(m)}let f=a.rest;return a.rest&&(f=n(a.rest),f!==a.rest&&(l=!0)),l?He(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:He(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:He(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?He(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:He(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:He(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:He(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:He(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return He(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 cB(t){return Th(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:tt(r.options)}})}function ofe(t,e){if(!e?.length)return t;let r=t._zod.def;return He(t,Jn(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function uB(t){return ofe(t.out,t.checks)}function ife(t){return t.in._zod.traits.has("$ZodTransform")?uB(t):t.in}function lB(t){return Th(t,{pipe:e=>ife(e._zod.def),default:(e,r)=>r?ot(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function dB(t){return Th(t,{pipe:e=>uB(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var IC={};gt(IC,{bigint:()=>ufe,boolean:()=>cfe,date:()=>lfe,number:()=>afe,string:()=>sfe});function sfe(t){return TP(Ed,t)}function afe(t){return RP(kd,t)}function cfe(t){return CP($d,t)}function ufe(t){return OP(Id,t)}function lfe(t){return NP(bh,t)}var Ph={name:"@tomato414941/foundation",version:"1.3.1",description:"Manage Foundation resources and deliver encrypted inputs to commands.",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"};var Pd=new TextEncoder,Rd=new TextDecoder,fB=new TextDecoder("utf-8",{fatal:!0}),$S=2**32;function Qr(...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 AC(t,e,r){if(e<0||e>=$S)throw new RangeError(`value must be >= 0 and <= ${$S-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function TC(t){let e=Math.floor(t/$S),r=t%$S,o=new Uint8Array(8);return AC(o,e,0),AC(o,r,4),o}function IS(t){let e=new Uint8Array(4);return AC(e,t),e}var ffe=/[^\x00-\x7f]/;function fr(t){if(typeof t=="string"&&t.length>=128){if(ffe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return Pd.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 pB(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 mB(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 AS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ds=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 hu=class extends Ds{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},at=class extends Ds{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},$a=class extends Ds{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},M=class extends Ds{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},bt=class extends Ds{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var Rh=class extends Ds{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var TS=class extends Ds{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var pfe="The input to be decoded is not correctly encoded.";function gu(t){try{return mB(typeof t=="string"?t:Rd.decode(t),!0)}catch(e){throw new TypeError(pfe,{cause:e})}}function It(t){return pB(typeof t=="string"?Pd.encode(t):t,!0)}function Cn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Ft(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 Ia(...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 Yn(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function gn(t,e,r){try{return gu(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function PS(t,e,r){try{return fr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function Cd(t,e,r){let o;try{o=JSON.parse(fB.decode(gu(t)))}catch{throw new e(r)}if(!Ft(o))throw new e(r);return o}var RS={__proto__:null,b64:!0},CS={__proto__:null};function Ch(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 OS(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 Aa(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 at(`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 NS(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new bt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function yu(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(!Ft(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var mfe=t=>t[Symbol.toStringTag],hfe=(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 jo(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(Ft(e)){if(s=DC(e),typeof s.kty!="string")throw hB(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(hfe(t,s,r),s.kty==="oct")return gu(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!CC(e))throw hB(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${mfe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Ta(e))return e;if(a=e,a.type==="secret")return a.export()}PC||=new WeakMap;let c=e,u=PC.get(c);if(u?.[o])return u[o];if(u||PC.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=gfe[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 Nd(t,s)}var PC,gfe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function zS(t){if(!Ta(t))throw new Error("CryptoKey instance expected")}var Ta=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},RC=t=>t?.[Symbol.toStringTag]==="KeyObject",CC=t=>Ta(t)||RC(t);function gB(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 zs=(t,...e)=>gB("Key must be ",t,...e);function hB(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(gB(`Key for the ${t} algorithm must be `,e,...o))}var DS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function OC(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Od(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 NC(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw DS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw DS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw DS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw DS(e.length,"algorithm.length");OC(t,r)}function jS(t){return{__proto__:null,...t}}function DC(t){let e=jS(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 MS(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function Nd(t,e,r){if(!t.kty.includes(e.kty))throw new at('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 Mo(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),NC(t,e,r),t}var vu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function US(t,e){let r=t.byteLength<<3;if(r!==e)throw new M(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var yfe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function yB(t,e){if(e.length<<3!==t.ivBits)throw new M("Invalid Initialization Vector length")}async function vB(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(zs(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 wB(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vfe(t,e,r,o,n){let[i,s,a]=await vB(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Qr(n,o,c,TC(n.length*8)),l=await wB(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function wfe(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 bfe(t,e,r,o,n,i){let[s,a,c]=await vB(t,e,"decrypt"),u=Qr(i,o,r,TC(i.length*8)),l=await wB(a,u,c);try{if(await wfe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new $a}async function LS(t,e,r,o,n){if(!Ta(r)&&!(r instanceof Uint8Array))throw new TypeError(zs(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?yB(t,o):o=yfe(t),r instanceof Uint8Array&&US(r,t.cekBits),t.cbc)return vfe(t,e,r,o,n);let i=await Mo(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 FS(t,e,r,o,n,i){if(!Ta(e)&&!(e instanceof Uint8Array))throw new TypeError(zs(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new M("JWE Initialization Vector missing");if(!n)throw new M("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new M("Invalid Authentication Tag length");if(yB(t,o),e instanceof Uint8Array&&US(e,t.cekBits),t.cbc)return bfe(t,e,r,o,n,i);let s=await Mo(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Qr(r,n)))}catch{throw new $a}}function Oh(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var _fe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Sfe=[[],["deriveBits"]],HS=[[],[]];function VS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:_fe,ops:["wrapKey","unwrapKey"]}}function BS(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 at('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Sfe,ops:[void 0,"deriveBits"]}}function Dd(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:HS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function zC(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:HS,ops:["deriveBits","deriveBits"]}}var js=Oh({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:HS,ops:["encrypt","decrypt"]},"RSA-OAEP":VS(1),"RSA-OAEP-256":VS(256),"RSA-OAEP-384":VS(384),"RSA-OAEP-512":VS(512),"ECDH-ES":BS("direct-key-agreement"),"ECDH-ES+A128KW":BS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":BS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":BS("key-agreement-with-key-wrapping"),A128KW:Dd(128),A192KW:Dd(192),A256KW:Dd(256),A128GCMKW:Dd(128,!0),A192GCMKW:Dd(192,!0),A256GCMKW:Dd(256,!0),"PBES2-HS256+A128KW":zC(),"PBES2-HS384+A192KW":zC(),"PBES2-HS512+A256KW":zC()}),xfe=["encrypt","decrypt"];function zd(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:HS,ops:xfe,cekBits:t,ivBits:e?128:96,cbc:e}}var Efe=Oh({A128GCM:zd(128),A192GCM:zd(192),A256GCM:zd(256),"A128CBC-HS256":zd(256,!0),"A192CBC-HS384":zd(384,!0),"A256CBC-HS512":zd(512,!0)});function bB(t,e){throw new at(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Uo(t){return(typeof t=="string"?js[t]:void 0)??bB("alg","Algorithm")}function Lo(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function wu(t){return(typeof t=="string"?Efe[t]:void 0)??bB("enc","Encryption Algorithm")}function _B(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");OC(t,e)}async function kfe(t,e,r){let o=await Mo(e,Uo(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 $fe(t,e,r){let o=await Mo(e,Uo(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 xB(t,e,r){NC(e,Uo(t).subtle,r),Od(t,e)}async function EB(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new M("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new M("PBES2 Count Input must be a positive integer");let n=Qr(fr(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 Mo(o,Uo(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function jC(t){return Qr(IS(t.length),t)}async function Ife(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 AS("sha256",Qr(IS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function kB(t,e,r,o,n=new Uint8Array,i=new Uint8Array){_B(t),_B(e,"deriveBits");let s=Qr(jC(fr(r)),jC(n),jC(i),IS(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 Ife(a,o,s)}function $B(t){zS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new at("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function qS(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new M(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return gn(r,e,M)}}function IB(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 M('JOSE Header "apu" and "apv" values must be distinct')}}function Afe(t){if(t===void 0)throw new M("JWE Encrypted Key missing")}function SB(t){if(t!==void 0)throw new M("Encountered unexpected JWE Encrypted Key")}function Tfe(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 AB(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return SB(o),r;let c=a==="direct-key-agreement";switch(c?SB(o):Afe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Ft(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(m=>Object.hasOwn(u,m)))throw new M('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');$B(r);let l=await Nd(t,u),d=qS(n,"apu"),f=qS(n,"apv");IB(d,f);let p=await kB(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 zS(r),xB(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new M('JOSE Header "p2c" (PBES2 Count) missing or invalid');Tfe(i);let u=i??1e4;if(n.p2c>u)throw new M('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new M('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=gn(n.p2s,"p2s",M);r=await EB(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new M('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new M('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=gn(n.iv,"iv",M),l=gn(n.tag,"tag",M);if(u.byteLength!==12)throw new M("Invalid Initialization Vector length");if(l.byteLength!==16)throw new M("Invalid Authentication Tag length");return FS(wu(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return $fe(s.slice(-6),r,o)}async function ZS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Lo(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await jo(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??vu(e):void 0;l&&US(l,e.cekBits);let d,f;switch(t.subtle.name){case"ECDH":{$B(u);let{apu:p,apv:m}=i;p!==void 0&&Cn(p,'"apu"'),m!==void 0&&Cn(m,'"apv"');let g=p??qS(o,"apu"),v=m??qS(o,"apv");IB(g,v);let w;i.epk!==void 0?w=await jo(t,i.epk,"decrypt"):w=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let b=crypto.subtle,_=w;if(!_.extractable){if(typeof b.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');_=await b.getPublicKey(w,[])}let{x:E,y:A,crv:z,kty:H}=await b.exportKey("jwk",_),te=a==="direct-key-agreement",$e=await kB(u,w,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),g,v),xe={x:E,crv:z,kty:H};if(H==="EC"&&(xe.y=A),f={epk:xe},p!==void 0&&(f.apu=It(p)),m!==void 0&&(f.apv=It(m)),te)return[$e,void 0,f];u=$e;break}case"RSA-OAEP":{zS(u),xB(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:p=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await EB(m,s,p,u),f={p2c:p,p2s:It(m)};break}case"AES-GCM":{let p=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(p instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await LS(wu(s.slice(0,-2)),l,u,p,new Uint8Array);d=m.ciphertext,f={iv:It(m.iv),tag:It(m.tag)}}}if(d??=await kfe(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 KS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new at('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new M('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function TB(t){if(typeof globalThis[t]>"u")throw new at(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function PB(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 M("Decompressed plaintext exceeded the configured limit")}return Qr(...n)}async function RB(t){return TB("CompressionStream"),PB(new CompressionStream("deflate-raw"),t)}async function CB(t,e){return TB("DecompressionStream"),PB(new DecompressionStream("deflate-raw"),t,e)}function OB(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 M("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new M("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new M("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new M("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new M("JWE AAD incorrect type");if(s!==void 0&&!Ft(s))throw new M("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 NB(t){let e,r;try{let{header:o}=t;if(Ft(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 DB(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new M("JWE Encrypted Key incorrect type");if(r!==void 0&&!Ft(r))throw new M("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new M("JOSE Header missing")}function MC(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=Cd(e,M,"JWE Protected Header is invalid")),[s,gn(r,"ciphertext",M),o!==void 0?gn(o,"iv",M):void 0,n!==void 0?gn(n,"tag",M):void 0,PS((e??"")+(i!==void 0?`.${i}`:""),"aad",M)]}function WS(t){return[t&&Ch("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&Ch("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function UC(t,e,r,o=MC(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,f;if(u!==void 0||l!==void 0){if(!Ia(n,u,l))throw new M("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");f={...n,...u,...l}}else f=n??{};let[p,m,g,v,w]=e,{encrypted_key:b}=t;Aa(M,CS,g,n,f),KS(f,n);let{alg:_,enc:E}=f;if(typeof _!="string"||!_)throw new M("missing JWE Algorithm (alg) in JWE Header");let A=js[_];if(b===""&&(!A||!Lo(A)))throw new M("JWE Encrypted Key incorrect type");let z=A?.mode==="integrated-encryption";if(!z&&(typeof E!="string"||!E))throw new M("missing JWE Encryption Algorithm (enc) in JWE Header");if(p&&!p.has(_)||!p&&_.startsWith("PBES2"))throw new hu('"alg" (Algorithm) Header Parameter value not allowed');let H;if(z){if(E!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new M("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new M("JWE Authentication Tag must be empty for integrated encryption")}else{if(m&&!m.has(E))throw new hu('"enc" (Encryption Algorithm) Header Parameter value not allowed');H=wu(E)}let te;if(b!==void 0)try{te=gn(b,"encrypted_key",M)}catch(Ie){if(!A||!Lo(A))throw Ie;te=new Uint8Array}let $e=!1;typeof r=="function"&&(r=await r(n,t),$e=!0);let xe=A??Uo(_);Lo(xe)&&te===void 0&&(te=new Uint8Array);let Qe=await jo(xe.mode==="direct-encryption"?H:xe,r,"decrypt"),Le;if(xe.mode==="integrated-encryption")Le=await xe.decrypt(Qe,te,i,c,n,f);else{let Ie=H,J;try{J=await AB(xe,Ie,Qe,te,f,v),Lo(xe)&&J instanceof Uint8Array&&J.byteLength<<3!==Ie.cekBits&&(J=vu(Ie))}catch(Et){if(Et instanceof TypeError||Et instanceof M||Et instanceof at)throw Et;J=vu(Ie)}Le=await FS(Ie,J,i,s,a,c)}if(f.zip==="DEF"){let Ie=w??25e4;if(Ie===0)throw new at('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ie!==1/0&&(!Number.isSafeInteger(Ie)||Ie<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");Le=await CB(Le,Ie).catch(J=>{throw J instanceof M?J:new M("Failed to decompress plaintext",{cause:J})})}return{plaintext:Le,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:gn(d,"aad",M)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...$e&&{key:Qe}}}async function zB(t,e,r){if(t instanceof Uint8Array&&(t=Rd.decode(t)),typeof t!="string")throw new M("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 M("Invalid Compact JWE");return UC({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Nh(t,e,r){return zB(t,WS(r),e)}async function LC(t,e,r){if(!Ft(t))throw new M("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new M("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(Ft))throw new M("JWE Recipients missing or incorrect type");if(!n.length)throw new M("JWE Recipients has no members");let i,s,a;try{i=WS(r),s=OB(t),a=MC(s)}catch{throw new $a}let c=n.map(u=>NB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?js[l]:void 0;if(d&&!Lo(d))throw new M(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return DB(l),await UC(l,i,e,a)}catch{}throw new $a}function JS(t,e,r){if(!Ia(t,e,r))throw new M("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function FC(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new M("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&&Cn(s,"JWE Additional Authenticated Data"),a!==void 0&&Cn(a,"JWE Content Encryption Key"),c!==void 0&&Cn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=yu(M,o)[0],t[1]=o),n!==void 0&&(n=yu(M,n)[0],t[2]=n),!r&&i!==void 0&&(i=yu(M,i)[0],t[3]=i),u!==void 0&&!Ft(u))throw new TypeError("JWE Key Management Parameters must be an object");JS(o,n,i);let d={...o,...n,...i};OS(M,o),Aa(M,CS,l,o,d),KS(d,o);let{alg:f,enc:p}=d;if(typeof f!="string"||!f)throw new M('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=js[f];if(m?.mode==="integrated-encryption"){if(p!==void 0)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!="string"||!p)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,wu(p),m]}async function VC(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,f,p,,m]=t,g=a,v=c,w=i??Uo(o.alg),b,_,E;w.mode==="integrated-encryption"?E=await jo(w,r,"encrypt"):[E,b,_]=await ZS(w,n,r,o,d,p),_&&(m?v=v?{...v,..._}:_:g=g?{...g,..._}:_,JS(g,v,u));let A=g?It(JSON.stringify(g)):"",z=l?.byteLength?It(l):void 0,H=fr(z?`${A}.${z}`:A),te=s;o.zip==="DEF"&&(te=await RB(te).catch(Ie=>{throw new M("Failed to compress plaintext",{cause:Ie})}));let $e,xe,Qe;w.mode==="integrated-encryption"?[b,$e]=await w.encrypt(E,te,H,g,o,p):{ciphertext:$e,tag:xe,iv:Qe}=await LS(n,te,E,f,H);let Le={ciphertext:It($e)};return Qe&&(Le.iv=It(Qe)),xe&&(Le.tag=It(xe)),b?.byteLength&&(Le.encrypted_key=It(b)),z&&(Le.aad=z),g&&(Le.protected=A),u&&(Le.unprotected=u),v&&(Le.header=v),Le}async function jB(t,e,r){return VC(t,FC(t,r),e)}function MB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var BC=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Yn(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Yn(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}},Dh=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new BC(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Yn(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Yn(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new M("at least one recipient must be added");Cn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[g,v,w,b]=m.state,_=[this.#e,o,g,n,this.#o,void 0,void 0,v,b,e],E=FC(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,E,w]);let[{alg:A,enc:z},,H]=E;if(e&&H&&!Lo(H))throw new M(`"${A}" alg may only have a single recipient`);if(!r)r=z;else if(r!==z)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Uo(m[0].alg);let[s,a,c]=i[0],u=e?vu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...f}=await VC(s,a,c),p={...f,recipients:[{}]};l&&(p.recipients[0].encrypted_key=l),d&&(p.recipients[0].header=d);for(let m=1;m<i.length;m++){let[g,[v,w,b],_]=i[m],E=g[2],[,A,z]=await ZS(b,w,_,v,u,g[7]),H={encrypted_key:It(A)};if(E||z){let te={...E,...z};z&&JS(g[1],te,g[3]),H.header=te}p.recipients.push(H)}return p}};var zh=[["verify"],["sign"]];function HC(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:zh}}function jd(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:zh,minRsaBits:2048}}function qC(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:zh}}function UB(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:zh}}function ZC(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:zh}}var KC=Oh({HS256:HC(256),HS384:HC(384),HS512:HC(512),RS256:jd(256),RS384:jd(384),RS512:jd(512),PS256:jd(256,32),PS384:jd(384,48),PS512:jd(512,64),ES256:qC("P-256",256),ES384:qC("P-384",384),ES512:qC("P-521",512),EdDSA:UB(),Ed25519:UB(),"ML-DSA-44":ZC(44),"ML-DSA-65":ZC(65),"ML-DSA-87":ZC(87)});function GS(t){let e=typeof t=="string"?KC[t]:void 0;if(!e)throw new at(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function LB(t){return[t&&Ch("algorithms",t.algorithms),t?.crit]}function Pfe(t){return t===void 0?{}:Cd(t,bt,"JWS Protected Header is invalid")}function Rfe(t){try{return fr(t)}catch{throw new bt("JWS Compact Serialization payload must use only ASCII characters")}}async function Cfe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Pfe(i);if(!Ia(c,s))throw new bt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=NS(c,Aa(bt,RS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new bt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new hu('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new bt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new bt("JWS Payload must be a string or an Uint8Array instance");let f=l||typeof a!="string"?a:o(a),p=!1;typeof r=="function"&&(r=await r(c,t),p=!0);let m=GS(d),g=Qr(i!==void 0?fr(i):new Uint8Array,fr("."),typeof f=="string"?e[2]??=PS(f,"payload",bt):f),v=gn(t.signature,"signature",bt),w=await jo(m,r,"verify"),b=await Mo(w,m.subtle,"verify");m.minRsaBits&&Od(m.alg,b);let _=!1;try{_=await crypto.subtle.verify(m.signing,b,v,g)}catch{}if(!_)throw new TS;let E={payload:typeof f=="string"?gn(f,"payload",bt):f};return i!==void 0&&(E.protectedHeader=c),s!==void 0&&(E.unprotectedHeader=s),p?[{...E,key:w},l]:[E,l]}async function FB(t,e,r){if(t instanceof Uint8Array&&(t=Rd.decode(t)),typeof t!="string")throw new bt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new bt("Invalid Compact JWS");return Cfe({payload:n,protected:o,signature:i},e,r,Rfe)}async function WC(t,e,r){let[o]=await FB(t,LB(r),e);return o}var Md=class{#e;constructor(e){Cn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Yn(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Yn(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Yn(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Yn(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return MB(await jB([...this.#e],e,r))}};async function Ofe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=yu(bt,n);n=w[0],a=It(w[1])}if(i!==void 0&&(i=yu(bt,i)[0]),!n&&!i)throw new bt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ia(n,i))throw new bt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};OS(bt,n);let u=NS(n,Aa(bt,RS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new bt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=GS(l),f="",p=o,m;if(u){let w=t[4];w?(f=w[0]??=It(o),p=w[1]??=fr(f)):(f=It(o),m=Pd.encode(`${a}.${f}`))}m??=Qr(fr(a),fr("."),p);let g=await Mo(await jo(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&Od(d.alg,g);let v={signature:It(new Uint8Array(await crypto.subtle.sign(d.signing,g,m))),payload:f};return n&&(v.protected=a),i&&(v.header=i),[v,u]}async function VB(t,e,r,o,n){let[i]=await Ofe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var jh=class{#e;#t;constructor(e){Cn(e,"payload"),this.#e=e}setProtectedHeader(e){return Yn(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return VB(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var JC='"alg" (Algorithm)';function GC(t='JWK "alg" (Algorithm) Parameter'){throw new at(`Invalid or unsupported ${t} value`)}function Mh(t,e){return(typeof t=="string"?KC[t]??js[t]:void 0)??GC(e)}async function Pa(t){if(RC(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:It(t)};if(!Ta(t))throw new TypeError(zs(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 Ms=(t,e)=>{if(typeof t!="string"||!t)throw new Rh(`${e} missing or invalid`)};async function XC(t,e){let r;if(Ft(t)){if(r=jS(t),typeof r.kty!="string")throw new TypeError(zs(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(CC(t))r=jS(await Pa(t));else throw new TypeError(zs(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":Ms(r.alg,'"alg" (Algorithm) Parameter'),Ms(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Ms(r.crv,'"crv" (Curve) Parameter'),Ms(r.x,'"x" (X Coordinate) Parameter'),Ms(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Ms(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Ms(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Ms(r.e,'"e" (Exponent) Parameter'),Ms(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 Rh('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new at('"kty" (Key Type) Parameter missing or unsupported')}let n=fr(JSON.stringify(o));return It(await AS(e,n))}async function Qn(t,e,r){if(!Ft(t))throw new TypeError("JWK must be an object");let o=DC(t),n=MS(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 gu(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 Nd(Mh(e),o,n)}case"RSA":case"EC":case"OKP":return Nd(Mh(e),o,n);default:throw new at('Unsupported "kty" (Key Type) Parameter value')}}function YC(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 Cd(e,TypeError,r)}function Nfe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new at("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Uh(t,e){let r=MS(e?.extractable),o=Mh(t,JC);o.secret&&GC(JC);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new at("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 at(`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:Nfe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}typeof window<"u"&&h.config({jitless:!0});var k=h.uuid(),fe=h.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),rt=h.iso.datetime(),eo=h.json(),bu=h.record(h.string(),eo),HB=h.enum(["ja","en"]),eO=h.enum(["read","create","update","delete","share","transfer","reveal","use","execute","credentials","billing","export"]),Dfe=h.enum(["secret","connection","service","method","app","object","environment","function"]),Or=h.object({kty:h.literal("EC"),crv:h.literal("P-256"),x:h.string().min(40).max(50),y:h.string().min(40).max(50)}).strict(),zfe=h.object({alg:h.literal("dir"),enc:h.literal("A256GCM"),sub:k}).strict(),YS=h.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return zfe.safeParse(YC(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Fo=h.object({protected:h.string().max(2048),iv:h.string().max(64),ciphertext:h.string().max(2e6),tag:h.string().max(64),aad:h.string().max(2048).optional(),recipients:h.array(h.object({encrypted_key:h.string().max(2048),header:h.object({kid:k,epk:Or.optional(),alg:h.string().optional()}).passthrough()})).min(1).max(100)}).strict(),c2e=h.object({id:k,name:fe,publicKey:Or}),Ud=h.object({id:k,name:fe,createdAt:rt,permissions:h.array(eO),createKinds:h.array(Dfe),publicKey:Or.nullable()}),qB=h.object({id:k,kind:h.enum(["passkey","email","key"]),name:h.string(),createdAt:rt,lastUsedAt:rt.nullable(),expiresAt:rt.nullable()}),jfe=h.object({subjectId:k,relation:h.enum(["agent","member","payer"]),principalId:k}).strict(),u2e=jfe.extend({id:k,createdAt:rt,subjectName:fe,principalName:fe}).extend({relation:h.enum(["owner","agent","member","payer"])}),l2e=h.object({principalId:k,actions:h.array(eO).min(1),principalName:fe.optional()}),d2e=h.object({error:h.object({code:h.string(),message:h.string(),details:eo.optional()})}),f2e=h.object({ok:h.literal(!0)}),ZB=h.object({name:h.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:h.string(),secret:h.boolean().optional(),required:h.boolean().optional(),placeholder:h.string().optional(),note:h.string().optional(),pattern:h.string().optional()}),KB=h.record(h.string().regex(/^[A-Z_][A-Z0-9_]*$/),h.string()),Mfe=h.object({values:h.array(h.object({id:h.string(),name:h.string(),description:h.string().optional()})).optional(),default:h.array(h.string()).default([]),separator:h.string().default(" "),docs:h.url().optional()}),XS=h.string().min(1).max(4096),BB=h.union([h.string(),h.array(h.string()).min(1)]),WB=h.object({issuer:h.url().optional(),authorizeUrl:XS,tokenUrl:XS,identity:h.object({url:XS.optional(),from:h.enum(["token","app"]).optional(),method:h.enum(["GET","POST"]).default("GET"),id:BB.default("/id"),name:BB.default("/name"),headers:h.record(h.string(),h.string()).default({})}).optional(),revoke:h.object({url:XS,style:h.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:h.enum(["body","basic","none"]).optional()}).optional(),clientAuth:h.enum(["body","basic","none"]).default("body"),pkce:h.boolean().default(!0),tokenFormat:h.enum(["form","json"]).default("form"),okPointer:h.string().optional(),authorizeParams:h.record(h.string(),h.string()).default({}),tokenParams:h.record(h.string(),h.string()).default({}),defaults:h.record(h.string(),h.string()).default({}),scopes:Mfe.default({default:[],separator:" "}),fields:h.array(ZB).default([]),outputs:KB.default({ACCESS_TOKEN:"/accessToken"}),adapter:h.enum(["google","github","ebay","openrouter","cloudflare","slack"]).optional(),keep:h.array(h.string()).default([]),hint:h.string().optional()}),JB=h.object({fields:h.array(ZB).min(1),outputs:KB,console:h.url().optional(),instructions:h.string().optional(),hint:h.string().optional()}),tO=h.enum(["oauth","token","role"]),GB=h.object({kind:h.literal("aws"),hint:h.string().optional()}),rO={name:fe,docs:h.url().optional(),console:h.url().optional()},XB=h.object({...rO,kind:h.literal("oauth"),config:WB}).strict(),YB=h.object({...rO,kind:h.literal("token"),config:JB}).strict(),QB=h.object({...rO,kind:h.literal("role"),config:GB}).strict(),_u=h.discriminatedUnion("kind",[XB,YB,QB]),QC={id:h.string().min(1),builtin:h.boolean(),availability:h.enum(["ready","app-required","unavailable"])},nO=h.discriminatedUnion("kind",[XB.extend(QC),YB.extend(QC),QB.extend(QC)]),oO=h.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),QS=h.object({name:fe,logo:h.string().regex(/^[a-z0-9-]+$/).optional(),api:h.url().optional(),docs:h.url().optional(),console:h.url().optional()}).strict(),Ufe=QS.extend({auth:h.object({oauth:WB.optional(),token:JB.optional(),role:GB.optional()}).strict()}).strict(),Lfe=QS.extend({methods:h.record(oO,h.string().min(1))}).strict(),Ffe=QS.extend({methods:h.record(oO,h.union([h.string().min(1),_u]))}).strict(),eH=h.union([Ffe,Ufe]),p2e=QS.extend({id:h.string(),builtin:h.boolean(),methods:h.record(oO,nO)}),tH=h.discriminatedUnion("kind",[h.object({kind:h.literal("secret"),id:k}).strict(),h.object({kind:h.literal("connection"),id:k,output:h.string().min(1).max(100)}).strict()]),iO=h.object({name:h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:tH,format:h.enum(["text","file","json"]).default("text"),pointer:h.string().optional()}).strict(),Vfe=h.object({pointer:h.string().max(500),parts:h.array(h.union([h.string().max(8192),tH])).min(1).max(32)}).strict(),Su=h.object({url:h.string().max(4096),method:h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:h.record(h.string(),h.string().max(8192)).default({}),body:h.string().max(1e6).optional(),json:eo.optional(),form:h.record(h.string(),h.string()).optional(),bindings:h.array(Vfe).max(32).default([])}).strict(),Lh=h.object({description:h.string().max(2e3).default(""),request:Su,parameters:h.array(h.object({name:h.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:h.string().max(100),required:h.boolean().default(!0),default:h.string().optional()})).max(32).default([]),save:h.record(h.string(),fe).default({}),outputOwnerId:k.optional()}).strict(),Ra={id:k,ownerId:k,name:fe,createdAt:rt,updatedAt:rt,version:h.number().int().positive(),permissions:h.array(eO)},Bfe=h.enum(["starting","running","stopping","stopped","failed"]),Hfe=h.object({idleSeconds:h.number().int().min(60).max(86400).default(3600),maxSeconds:h.number().int().min(60).max(86400).default(3600)}).strict(),rH=h.object({image:h.string().min(1).max(300).optional(),size:h.enum(["small","medium","large"]).default("small"),lifetime:Hfe.default({idleSeconds:3600,maxSeconds:3600}),callerIds:h.array(k).min(1).max(100).optional()}).strict(),sO={recipients:h.array(k).default([]),executors:h.array(k).default([]),custodyRevision:h.number().int().positive().nullable().default(null)},qfe=h.object({...Ra,kind:h.literal("secret"),data:h.object({...sO,bytes:h.number().int().nonnegative()})}),Zfe=h.object({...Ra,kind:h.literal("connection"),data:h.object({...sO,methodId:h.string(),methodName:h.string(),methodKind:tO,services:h.array(h.object({id:h.string(),name:fe})).default([]),account:h.string(),accountId:h.string().nullable().default(null),accountVerified:h.boolean().default(!1),scopes:h.array(h.string()),scopesStatus:h.enum(["unknown","requested","reported"]).default("unknown"),outputs:h.array(h.string()),state:h.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:k.nullable(),generation:k.optional(),authorizationDigest:h.string().optional()})}),Kfe=h.object({...Ra,kind:h.literal("service"),data:Lfe}),Wfe=h.object({...Ra,kind:h.literal("method"),data:_u}),Jfe=h.object({...Ra,kind:h.literal("app"),data:h.object({...sO,methodId:h.string(),clientId:h.string(),fields:h.record(h.string(),h.string()).default({}),generation:k.optional()})}),Gfe=h.object({...Ra,kind:h.literal("object"),data:h.object({size:h.number().int().nonnegative(),contentType:h.string()})}),Xfe=h.object({...Ra,kind:h.literal("environment"),data:rH.extend({executorId:k.optional(),operatorId:k.optional(),driver:h.enum(["attached","managed"]).optional(),capabilities:h.array(h.string()).optional(),isolation:h.enum(["process","container"]).optional(),manifestDigest:h.string().optional(),state:Bfe,startedAt:rt.nullable(),stoppedAt:rt.nullable(),lastActiveAt:rt,error:h.string().nullable()})}),Yfe=h.object({...Ra,kind:h.literal("function"),data:Lh}),Pi=h.discriminatedUnion("kind",[qfe,Zfe,Kfe,Wfe,Jfe,Gfe,Xfe,Yfe]),m2e=h.discriminatedUnion("kind",[h.object({kind:h.literal("service"),name:fe,definition:eH}).strict(),h.object({kind:h.literal("method"),name:fe,definition:_u}).strict(),h.object({kind:h.literal("environment"),name:fe.optional(),options:rH}).strict(),h.object({kind:h.literal("function"),name:fe,definition:Lh}).strict()]),h2e=h.object({version:h.number().int().positive(),name:fe.optional(),definition:h.union([eH,_u,Lh]).optional()}).strict(),ex=h.object({command:h.array(h.string().max(8192)).min(1).max(100),stdin:h.string().max(1e6).optional(),timeoutSeconds:h.number().int().min(1).max(3600).default(60),inputs:h.array(iO).max(32).default([])}).strict(),nH=h.object({method:h.enum(["GET","POST","PUT","PATCH","DELETE","CONNECT"]),path:h.string().startsWith("/api/").max(2048),body:eo.optional(),inputs:h.array(h.object({pointer:h.string(),label:h.string().min(1).max(100),secret:h.boolean().default(!1),multiline:h.boolean().default(!1),site:h.url().optional()})).max(16).default([])}).strict(),Qfe=h.object({ja:h.string(),en:h.string()}).strict(),oH=h.object({ownerId:h.union([k,h.literal("$approver")]),methodId:h.string().min(1).max(200),connectionId:k.optional(),environmentId:k.optional(),name:fe.optional()}).strict(),iH=h.object({to:k.optional(),message:h.string().max(1e3).default(""),operations:h.array(nH).min(1).max(8),expiresInMinutes:h.number().int().min(1).max(1440).default(30)}).strict(),Ld=h.object({id:k,from:Ud.pick({id:!0,name:!0}),to:Ud.pick({id:!0,name:!0}).nullable(),message:h.string(),operations:h.array(nH.extend({title:Qfe})),state:h.enum(["pending","running","approved","declined","cancelled","expired"]),results:h.array(eo.nullable()),createdAt:rt,expiresAt:rt,url:h.url(),code:h.string().optional(),continueUrl:h.url().nullable(),returnUrl:h.url().nullable(),refreshUrl:h.url().nullable(),canRespond:h.boolean()}),g2e=h.object({id:k,name:fe,publicKey:Or,state:h.enum(["pending","approving","approved"]),principalId:k.nullable(),createdAt:rt,expiresAt:rt}),y2e=h.object({available:h.boolean(),required:h.boolean(),active:h.boolean(),payer:Ud.pick({id:!0,name:!0}).nullable()}),v2e=h.object({storageBytes:h.number().nonnegative(),storageLimit:h.number().positive(),computeSeconds:h.number().nonnegative(),computeLimit:h.number().positive(),month:h.string()}),w2e=h.object({id:h.string(),actorId:k.nullable(),action:h.string(),targetId:k.nullable(),createdAt:rt,details:bu}),b2e=h.object({returnUrl:h.url().optional(),refreshUrl:h.url().optional()}).strict(),xu=t=>h.object({items:h.array(t),next:h.string().nullable().default(null)}),_2e=h.object({id:k}),S2e=h.object({owner:k}),x2e=h.object({limit:h.coerce.number().int().min(1).max(200).default(100),after:h.string().optional()});var epe=h.object({email:h.boolean(),environments:h.boolean(),objects:h.boolean(),payments:h.boolean()}),tx=h.object({principal:Ud.nullable(),credentialId:k.nullable(),wrappedKey:YS.nullable(),requestId:k.nullable(),server:h.object({name:fe,commit:h.string().nullable()}),features:epe,principals:h.array(Ud)}),I2e=h.object({email:h.email().max(254),returnTo:h.string().max(2048).optional(),locale:HB.default("ja"),principalId:k.optional()}).strict(),A2e=h.object({intent:h.enum(["register","authenticate"]),name:fe.optional(),principalId:k.optional(),returnTo:h.string().max(2048).optional()}).strict(),T2e=h.object({challengeId:k,credential:h.json(),publicKey:Or.optional(),existingPublicKey:Or.optional(),wrappedKey:YS.optional()}).strict();var tpe=new TextEncoder,rpe=new TextDecoder,Fh="ECDH-ES+A256KW",aO="A256GCM",lt=t=>tpe.encode(t),Eu=t=>rpe.decode(t);function Ca(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 sH(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function rx(){let t=await Uh(Fh,{crv:"P-256",extractable:!0});return{publicKey:Or.parse(await Pa(t.publicKey)),privateKey:await Pa(t.privateKey)}}async function ku(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 Dh(t).setProtectedHeader({enc:aO}).setAdditionalAuthenticatedData(lt(r));for(let n of e)o.addRecipient(await Qn(n.publicKey,Fh)).setUnprotectedHeader({alg:Fh,kid:n.id});return Fo.parse(await o.encrypt())}async function Ri(t,e,r,o){if(t.aad!==Ca(lt(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 Qn(e,Fh);return(await LC({...t,recipients:[n]},i,{keyManagementAlgorithms:[Fh],contentEncryptionAlgorithms:[aO]})).plaintext}async function npe(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:lt("Foundation"),info:lt("passkey encryption key")},e,256))}async function aH(t,e,r){let o=await Nh(t,await npe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[aO]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Eu(o.plaintext))}var pr=h.string().regex(/^[A-Za-z0-9_-]{43}$/),On=h.string().min(100).max(4e6),cH=Or.extend({d:h.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Vh=h.object({encryption:cH,signing:cH}).strict(),Vt=h.object({id:k,principalId:k,generation:h.number().int().positive(),previous:pr.nullable(),encryption:Or,signing:Or}).strict();function R(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,R).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)+":"+R(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function Fd(t){return XC(Or.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ge(t){return Ca(new Uint8Array(await crypto.subtle.digest("SHA-256",lt(R(t)))))}async function ox(){let[t,e]=await Promise.all([rx(),Uh("ES256",{crv:"P-256",extractable:!0})]),r=await Pa(e.privateKey);return Vh.parse({encryption:t.privateKey,signing:r})}function nx(t){return Or.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function ix(t,e){return Vt.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:nx(e.encryption),signing:nx(e.signing)})}async function yn(t,e,r){let o=e instanceof CryptoKey?e:await Qn(e,"ES256");return new jh(lt(R(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function to(t,e,r,o){if(R(await cO(e,r,o))!==R(t))throw new Error("The signature does not authorize this content.")}async function cO(t,e,r){let o=await WC(t,await Qn(Or.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(R(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Ci=h.object({binding:Vt,signature:On}).strict();async function Bh(t,e){if(await Us(t),await Fd(e.encryption)!==await Fd(t.encryption)||await Fd(e.signing)!==await Fd(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await yn(t,e.signing,"key-binding")}}async function Us(t){let e=Vt.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Fd(e.encryption)===await Fd(e.signing))throw new Error("Use separate encryption and signing keys.");await Qn(e.encryption,"ECDH-ES+A256KW"),await Qn(e.signing,"ES256")}async function uO(t){let{binding:e,signature:r}=Ci.parse(t);return await Us(e),await to(e,r,e.signing,"key-binding"),e}var Vd=h.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),lO=h.enum(["secret","connection","app"]),Hh=h.enum(["http","command","function","connect","refresh","revoke"]),ope=h.object({actor:Vt,executor:Vt,operations:h.array(Hh).min(1).max(6),functionDigests:h.array(pr).max(100).default([]),origins:h.array(Vd).max(100).default([]),callerProgram:h.boolean().default(!1),expiresAt:rt}).strict(),Ls=h.object({format:h.literal(1),origin:Vd,id:k,ownerId:k,kind:lO,revision:h.number().int().positive(),authorities:h.array(Vt).min(1).max(100),readers:h.array(Vt).min(1).max(100),grants:h.array(ope).max(100),observers:h.array(k).max(100).optional(),producers:h.array(h.object({executor:Vt,runId:k,expiresAt:rt,materialRevision:h.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),uH=h.object({ownerId:k,authorities:h.array(Vt).min(1).max(100)}).strict(),lH=h.object({origin:Vd,id:k,kind:lO,revision:h.number().int().positive(),from:uH,to:uH,policyDigest:pr,previous:pr.nullable(),signerId:k}).strict(),ipe=lH.extend({signature:On}),dO=h.array(ipe).max(16),qh=h.object({policy:Ls,authorityId:k,signature:On,lineage:dO.optional()}).strict(),ro=h.object({policy:Ls,authorityId:k,authorization:On,lineage:dO.optional(),materialRevision:h.number().int().positive(),updatedAt:rt,creationRunId:k.nullable(),metadata:bu,sealed:Fo,signerId:k,signature:On}).strict(),$u=t=>({ownerId:t.ownerId,authorities:t.authorities});async function dH(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.kind!==t.kind||o.revision>t.revision||r&&(o.revision<=r.revision||R(r.to)!==R(o.from))||o.previous!==(r?await ge(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 to(i,n,s.signing,"authority-handoff"),r=o}if(r&&R(r.to)!==R($u(t)))throw new Error("Use the authorities approved by the latest handoff.")}function fO(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 fH(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.kind!==e.policy.kind)return!1;let r=R($u(t));return r===R($u(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&R(o.from)===r)}async function pH(t,e,r,o){let n=[...t?.lineage??[]];if(t&&R($u(t.policy))!==R($u(e))){if(await Vo(t),!t.policy.authorities.some(s=>R(s)===R(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.kind!==e.kind||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=lH.parse({origin:e.origin,id:e.id,kind:e.kind,revision:e.revision,from:$u(t.policy),to:$u(e),policyDigest:await ge(e),previous:n.length?await ge(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await yn(i,o.signing,"authority-handoff")})}return n.length?{lineage:dO.parse(n)}:{}}async function sx(t){let e=Ls.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>[n.actor,n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await Us(n);let i=R(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(n.operations.some(i=>["http","command"].includes(i))&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes("function")&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function ax(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Bd(t,e){return R({purpose:"resource",origin:t.origin,id:t.id,ownerId:t.ownerId,kind:t.kind,policyDigest:await ge(t),materialRevision:e})}async function mH(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await sx(e),c=await pH(s,a,o,n);if(!a.authorities.some(f=>R(f)===R(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await ku(t,ax(a).map(f=>({id:f.id,publicKey:f.encryption})),await Bd(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await yn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.kind==="secret"?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=ro.parse({...l,signature:await yn(l,n.signing,"resource")});return await Vo(d),d}async function Vo(t){let e=ro.parse(t),{signature:r,...o}=e;await sx(e.policy),await dH(e.policy,e.lineage);let n=fO(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ge(e.policy))throw new Error("The handoff approves a different access policy.");await to(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&&Date.parse(u.expiresAt)>Date.parse(e.updatedAt))?.executor??(e.policy.kind==="connection"?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes("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 to(o,r,s.signing,"resource");let a=ax(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(R(a)!==R(c)||e.sealed.aad!==Ca(lt(await Bd(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function hH(t,e,r,o,n=t.metadata){let i=await Vo(t);if(i.policy.kind!=="connection"||!(i.policy.authorities.some(f=>R(f)===R(r))||i.policy.grants.some(f=>R(f.executor)===R(r)&&f.operations.includes("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 ku(e,ax(i.policy).map(f=>({id:f.id,publicKey:f.encryption})),await Bd(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 yn(l,o.signing,"resource")};return await Vo(d),d}async function cx(t,e,r,o){let n=await sx(t);if(!n.authorities.some(s=>R(s)===R(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await pH(o,n,e,r),authorityId:e.id,signature:await yn(n,r.signing,"access-policy")};return await Hd(i),i}async function Hd(t){let e=qh.parse(t);await sx(e.policy),await dH(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ge(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 to(e.policy,e.signature,o.signing,"access-policy"),e}async function ux(t,e,r,o,n,i){let s=await Hd(e),{policy:a}=s,c=a.producers.find(f=>f.runId===r&&R(f.executor)===R(o)&&Date.parse(f.expiresAt)>Date.now());if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let u=await ku(t,ax(a).map(f=>({id:f.id,publicKey:f.encryption})),await Bd(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 yn(l,n.signing,"resource")};return await Vo(d),d}async function lx(t,e,r){let o=await Vo(t);if(!o.policy.readers.some(n=>R(n)===R(e)))throw new Error("This identity cannot reveal the content.");return Ri(o.sealed,r,e.id,await Bd(o.policy,o.materialRevision))}var spe=h.object({id:k,kind:lO,policyDigest:pr,materialRevision:h.number().int().positive(),authorizationDigest:pr.optional()}).strict();async function pO(t,e){return e.id===t.policy.id&&e.kind===t.policy.kind&&e.policyDigest===await ge(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||e.kind==="connection"&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var dx=h.object({format:h.literal(1),id:k,origin:Vd,ownerId:k,approval:h.object({id:k,index:h.number().int().min(0).max(7)}).strict().optional(),actor:Vt,environmentId:k,executor:Vt,environmentDigest:pr,operation:Hh,functionDigest:pr.nullable(),operationDigest:pr,sources:h.array(spe).max(100),resultRecipients:h.array(Vt).min(1).max(100),createdAt:rt,expiresAt:rt}).strict(),fx=h.object({intent:dx,signature:On,sealed:Fo}).strict();async function Iu(t,e){return R({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ge(t)})}async function gH(t,e,r){if(dx.parse(t),await ge(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await ku(lt(R(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Iu(t,"input"))};return fx.parse({...o,signature:await yn(o,r.signing,"run")})}async function ape(t,e=Date.now()){let r=fx.parse(t),{signature:o,...n}=r;await to(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(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Ca(lt(await Iu(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function yH(t,e,r){let o=await ape(t);if(R(o.intent.executor)!==R(e))throw new Error("This operation belongs to another executor.");let n=await Ri(o.sealed,r.encryption,e.id,await Iu(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(R(s)!==i||await ge(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function Au(t,e,r={}){let o=await Vo(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await pO(o,i))throw new Error("The input changed after this execution was authorized.");if(R(e.actor)===R(e.executor)&&n.readers.some(c=>R(c)===R(e.actor)))return o;if(!n.grants.filter(c=>R(c.actor)===R(e.actor)&&R(c.executor)===R(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=>e.operation==="function"&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:!["command","http"].includes(e.operation)||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function qd(t,e,r,o={}){return await Au(t,e,o),Ri(t.sealed,r.encryption,e.executor.id,await Bd(t.policy,t.materialRevision))}var wH=h.object({format:h.literal(1),id:k,origin:Vd,ownerId:k,name:fe,executor:Vt,operatorId:k,driver:h.enum(["attached","managed"]),capabilities:h.array(Hh).min(1).max(6),callers:h.array(Vt).min(1).max(100),isolation:h.enum(["process","container"]),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),revision:h.number().int().positive()}).strict(),mO=h.object({manifest:wH,signature:On}).strict();async function bH(t,e){let r=wH.parse(t),o={manifest:r,signature:await yn(r,e.signing,"environment")};return await Zd(o),o}async function Zd(t){let e=mO.parse(t),{manifest:r}=e;await Us(r.executor);for(let o of r.callers)await Us(o);if(new Set(r.callers.map(o=>o.id)).size!==r.callers.length||new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct callers and execution capabilities.");if(r.capabilities.includes("command")&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes("command")&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await to(r,e.signature,r.executor.signing,"environment"),e}async function px(t,e){let{manifest:r}=await Zd(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ge(r)||R(e.executor)!==R(r.executor)||!r.callers.some(o=>R(o)===R(e.actor))||!r.capabilities.includes(e.operation))throw new Error("This environment does not authorize the requested execution.")}var cpe=h.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),_H=h.object({ok:h.boolean(),result:eo.nullable(),error:h.object({code:h.string().max(100),message:h.string().max(1e3)}).nullable()}).strict(),Kh=h.object({id:k,intentDigest:pr,executorId:k,state:h.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:rt,sealed:Fo,signature:On}).strict(),Zh=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Kd(t,e,r,o){let n=_H.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=lt(R(n));if(i.byteLength>14e5)throw new Zh;let s=await ku(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Iu(t,"result")),a={id:t.id,intentDigest:await ge(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Kh.parse({...a,signature:await yn(a,o.signing,"receipt")})}async function upe(t,e){let r=Kh.parse(t),{signature:o,...n}=r;if(await to(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ge(e)||r.executorId!==e.executor.id||r.sealed.aad!==Ca(lt(await Iu(e,"result")))||R(r.sealed.recipients.map(i=>i.header.kid).sort())!==R(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function SH(t,e,r,o){await upe(t,e);let n=await Ri(t.sealed,o.encryption,r,await Iu(e,"result")),i=_H.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 Nn=h.object({id:k,ownerId:k,actorId:k,environmentId:k,kind:Hh,state:cpe,intent:dx,requestSignature:On,receipt:Kh.nullable(),error:h.string().nullable(),createdAt:rt,startedAt:rt.nullable(),finishedAt:rt.nullable()}).strict(),vH=h.object({name:fe,approval:qh}).strict(),Wd=h.discriminatedUnion("kind",[h.object({kind:h.literal("http"),request:Su,save:h.record(h.string(),vH).default({})}).strict(),h.object({kind:h.literal("command"),...ex.shape}).strict(),h.object({kind:h.literal("function"),definition:Lh,arguments:h.record(h.string(),h.string()).default({}),outputs:h.record(h.string(),vH).default({})}).strict(),h.object({kind:h.enum(["connect","refresh","revoke"]),input:eo}).strict()]);var Oa=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Na=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=h.object({error:h.object({code:h.string(),message:h.string()})}).parse(await n.json())}catch{throw new Oa("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new Oa(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await(await this.response(e,r)).json();return o?o.parse(n):n}async session(){return this.json("/api/session",{},tx)}};import{chmod as lpe,lstat as dpe,mkdir as fpe,open as hO,readFile as EH,rename as ppe,rm as mpe}from"node:fs/promises";import{dirname as hpe,join as gO,resolve as gpe}from"node:path";import{homedir as ype}from"node:os";import{randomUUID as vpe}from"node:crypto";var yO=h.object({origin:h.url(),principalId:h.uuid(),token:h.string().min(20),keys:Vh.nullable(),binding:Vt.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),kH=h.object({current:h.uuid(),identities:h.array(yO).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Fs(){return gO(process.env.XDG_CONFIG_HOME||gO(ype(),".config"),"foundation","identity.json")}function Da(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 mx(t){let e;try{let n=Fs(),i=await dpe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await lpe(n,384);let s=kH.parse(JSON.parse(await EH(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=Da(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Da(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 yO.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!==Da(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 Wh(t){let e=Fs(),r;try{r=kH.parse(JSON.parse(await EH(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=yO.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Jd(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
129
129
  `,!!r)}async function xH(t){if(process.platform==="win32")return;let e=await hO(t,"r");try{await e.sync()}finally{await e.close()}}async function Jd(t,e,r){let o=gpe(t),n=hpe(o);if(await fpe(n,{recursive:!0,mode:448}),!r){let s=await hO(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await xH(n);return}let i=gO(n,".foundation-"+vpe());try{let s=await hO(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await ppe(i,o),await xH(n)}finally{await mpe(i,{force:!0})}}import{spawn as xpe}from"node:child_process";import{chmod as Epe,mkdtemp as kpe,rm as $pe,writeFile as Ipe}from"node:fs/promises";import{tmpdir as Ape}from"node:os";import{join as TH}from"node:path";import{StringDecoder as Tpe}from"node:string_decoder";import{spawn as $H}from"node:child_process";import{mkdir as wpe,mkdtemp as bpe,rm as _pe,writeFile as IH}from"node:fs/promises";import{tmpdir as Spe}from"node:os";import{join as Jh}from"node:path";import{StringDecoder as AH}from"node:string_decoder";function hx(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 gx=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 bpe(Jh(Spe(),"foundation-job-")),n=Jh(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a={exitCode:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},c=!1;try{await wpe(n,{mode:448});let u={...e.environment};for(let[d,f]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d))throw new Error("Use valid file variable names.");await IH(Jh(n,d),Buffer.from(f,"base64"),{mode:384,flag:"wx"}),u[d]=s?"/run/foundation/"+d:Jh(n,d)}let l=e.command;if(s){if(Object.entries(u).some(([f,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(f)||/[\r\n\0]/.test(p)))throw new Error("Use file inputs for multiline container values.");let d=Jh(o,"environment");await IH(d,Object.entries(u).map(([f,p])=>f+"="+p).join(`
130
130
  `),{mode:384,flag:"wx"}),l=["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",d,"-i",this.options.image,...e.command]}return await new Promise(d=>{let f=$H(l[0],l.slice(1),{env:hx(s?{}:u),cwd:this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),p={stdout:new AH("utf8"),stderr:new AH("utf8")},m=0,g=!1,v=(E,A)=>{let z=Math.max(0,1e6-m);A.length>z&&(a.truncated=!0);let H=A.subarray(0,z);m+=H.length,a[E]+=p[E].write(H)};f.stdout.on("data",E=>v("stdout",E)),f.stderr.on("data",E=>v("stderr",E)),f.stdin.on("error",()=>{}),f.stdin.end(e.stdin??"");let w=()=>{c=!0;try{f.pid&&process.platform!=="win32"?process.kill(-f.pid,"SIGKILL"):f.kill("SIGKILL")}catch{}},b=setTimeout(()=>{a.timedOut=!0,w()},e.timeoutSeconds*1e3);b.unref();let _=()=>{g||(g=!0,clearTimeout(b),r.removeEventListener("abort",w),a.stdout+=p.stdout.end(),a.stderr+=p.stderr.end(),d())};r.addEventListener("abort",w,{once:!0}),r.aborted&&w(),f.once("error",()=>{a.exitCode=127,a.stderr="The command could not be started.",_()}),f.once("close",E=>{a.exitCode=E,_()})}),a}finally{s&&c&&await new Promise(u=>{let l=$H("docker",["rm","-f",i],{env:hx(),stdio:"ignore"});l.once("close",()=>u()),l.once("error",()=>u()),setTimeout(()=>{l.kill("SIGKILL"),u()},1e4).unref()}),await _pe(o,{recursive:!0,force:!0})}}};function Ppe(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 yx=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 Tpe("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 PH(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await kpe(TH(Ape(),"foundation-"));await Epe(r,448);try{let o=hx(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=TH(r,i);await Ipe(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=xpe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=Ppe(n),u=new yx(c,m=>process.stdout.write(m)),l=new yx(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},f=()=>d("SIGINT"),p=()=>d("SIGTERM");process.on("SIGINT",f),process.on("SIGTERM",p),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,g)=>{process.off("SIGINT",f),process.off("SIGTERM",p),u.end(),l.end(),i(m??(g==="SIGINT"?130:g==="SIGTERM"?143:1))})})}finally{await $pe(r,{recursive:!0,force:!0})}}import{dirname as HIe,join as yU}from"node:path";var RH=Ci.extend({name:fe}),CH=h.object({id:k,index:h.number().int().min(0).max(7),input:oH.extend({ownerId:k})}).strict(),E6e=h.object({bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ci,token:h.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),OH=h.object({id:k,executorId:k,ownerId:k,name:fe,origin:h.url(),bootstrap:h.string().regex(/^[A-Za-z0-9_-]{43}$/),commandImage:h.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/),callers:h.array(Vt).min(1).max(100)}).strict(),k6e=Ci.extend({previousSignature:On.optional()}).strict(),$6e=h.object({name:fe,content:ro,version:h.number().int().positive().optional()}).strict(),NH=h.object({content:ro,version:h.number().int().positive()}).strict(),I6e=h.record(k,h.object({version:h.number().int().positive(),content:ro}).strict()),A6e=h.object({id:k,name:fe,version:h.number().int().positive(),content:ro,policy:Ls}).strict(),DH=h.object({registration:mO,stoppedAt:h.iso.datetime().nullable(),heartbeatAt:h.iso.datetime().nullable()}).strict(),zH=h.object({lease:k,request:fx,sources:h.array(ro).max(100)}).strict().nullable(),Rpe=h.object({lease:k}).strict(),T6e=Rpe.extend({receipt:Kh}).strict(),Gh=h.object({id:k,resource_id:k,executor_id:k,expected_revision:h.number().int().positive(),state:h.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:h.string().regex(/^\d+$/),result:ro.nullable()}),P6e=h.object({id:k,resourceId:k,expectedRevision:h.number().int().positive()}).strict(),Cpe=h.object({fence:h.string().regex(/^\d+$/)}).strict(),R6e=Cpe.extend({content:ro}).strict(),C6e=h.object({id:k,runId:k,stateDigest:pr,expiresAt:rt}).strict(),vx=h.object({id:k,runId:k,context:h.string(),sealed:Fo.nullable(),expiresAt:rt,receivedAt:rt.nullable()}).strict(),jH=(t,e)=>"oauth-callback:"+t+":"+e;var Bs=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"}},Ope=class extends Bs{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"}},Npe=class extends Bs{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},Dpe=class extends Bs{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"}},zpe=class extends Bs{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"}},jpe=class extends Bs{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},Mpe=class extends Bs{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"}},Upe=class extends Bs{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"}},bx=class extends Bs{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},vO=class extends bx{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"}},Lpe=class extends bx{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"}},Fpe=class extends bx{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"}},MH=class extends bx{constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},Vpe=class extends Bs{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"}},Bpe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},Hpe=class extends Bpe{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"}},qpe=["","+",".","/",";","?","&","#"],qH={"":{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}},Zpe=new TextEncoder,UH="0123456789ABCDEF",LH=t=>ja(Nr(48,57),Nr(65,70),Nr(97,102))(t.charCodeAt(0)),Qh=(t,e)=>t[e]==="%"&&e+2<t.length&&LH(t[e+1])&&LH(t[e+2]);function wO(t,e){let r=t[e];return r==null?0:ja(ZH,KH,Tu("_"))(r)?1:Qh(t,e)?3:0}function Kpe(t,e){if(Qh(t,e))return 3;let{char:r,size:o}=eg(t,e);return Jpe(r)?o:0}function eg(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 xO=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Qh(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=eg(e,o);r+=ja(WH,s=>t&&Wpe(s))(n)?n:JH(n),o+=i}return r};function Gd(t){let e="";for(let r=0;r<t.length;){if(Qh(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=eg(t,r);e+=WH(o)?o:JH(o),r+=n}return e}function Xh(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Qh(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=eg(t,n);r+=i,n+=s}return r}var ZH=t=>ja(Nr(65,90),Nr(97,122))(t.charCodeAt(0)),KH=t=>Nr(48,57)(t.charCodeAt(0)),WH=t=>ja(ZH,KH,e=>"-._~".includes(e))(t),Wpe=t=>":/?#[]@!$&'()*+,;=".includes(t),Jpe=t=>Gpe(t.codePointAt(0)),Gpe=t=>t!=null&&ja(Tu(33),Nr(35,36),Tu(38),Nr(40,59),Tu(61),Nr(63,91),Tu(93),Tu(95),Nr(97,122),Tu(126),Xpe,Ype)(t);function Xpe(t){if(t<65536)return ja(Nr(160,55295),Nr(63744,64975),Nr(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var Ype=t=>ja(Nr(57344,63743),Nr(983040,1048573),Nr(1048576,1114109))(t),JH=t=>Array.from(Zpe.encode(t)).map(e=>`%${UH[e>>4]}${UH[e&15]}`).join(""),Nr=(t,e)=>r=>t<=r&&r<=e,Tu=t=>e=>t===e,ja=(...t)=>e=>t.some(r=>r(e));function GH(t,e,r){return t.map(o=>o.kind==="literal"?o.text:Qpe(o.vars,o.operator,e,r)).join("")}function Qpe(t,e,r,o){let n=qH[e],i=t.flatMap(s=>eme(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function eme(t,e,r,o){if(e==null)return[];if(cme(e)){let n=ome(e,r.allowReserved);return n.length<1?[]:FH(t,"list",o)?rme(t,n,r):[]}if(ame(e)){let n=ime(e,r.allowReserved);return n.length<1?[]:FH(t,"associative",o)?nme(t,n,r):[]}return tme(t,e,r)}function tme(t,e,r){let o=String(e),n=t.prefix==null?o:Xh(o,t.prefix),i=xO(r.allowReserved)(n);return r.named?[Yh(Gd(t.name),i,r)]:[i]}function rme(t,e,r){let o=Gd(t.name);if(t.explode)return r.named?e.map(i=>Yh(o,i,r)):[...e];let n=e.join(",");return r.named?[Yh(o,n,r)]:[n]}function nme(t,e,r){if(t.explode)return e.map(([n,i])=>Yh(n,i,r));let o=e.flat(1).join(",");return r.named?[Yh(Gd(t.name),o,r)]:[o]}var Yh=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,ome=(t,e)=>t.filter(r=>r!=null).map(String).map(xO(e)),ime=(t,e)=>Object.entries(t).map(([r,o])=>[r,sme(o)]).filter(([,r])=>r!=null).map(r=>r.map(xO(e)));function sme(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 ame=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cme=t=>Array.isArray(t);function FH(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new Hpe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function ume(t,e,r){return bO(t,e,r,0,0,{})}function bO(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=zme(i);return GH(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?bO(t,e,r,o+1,n+s.text.length,i):null;for(let a of lme(t,e,o,n)){let c=e.slice(n,a);for(let u of fme(s.vars,s.operator,c)){let l=EO(i,u);if(l==null)continue;let d=bO(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*lme(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*dme(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*dme(t,e){for(let r=t;r>=e;r--)yield r}function*fme(t,e,r){if(r===""){yield*pme(t,e);return}let o=qH[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?Sme(t,o,n):mme(t,o,n)}var pme=(t,e)=>(e===""||e==="+")&&t.length===1?[za(t[0],"")]:[{}],mme=(t,e,r)=>_O(t,e,kO(r,e.sep),0,0);function*_O(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of hme(i,e,r,n))for(let a of _O(t,e,r,o+1,s.index)){let c=EO(s.bindings,a);c!=null&&(yield c)}yield*_O(t,e,r,o+1,n)}function*hme(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 gme(t,e,s))yield{bindings:a,index:o+i}}}function*gme(t,e,r){let o=XH(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*yme(t,e,r)),yield*o}function*yme(t,e,r){let o=YH(r,e.allowReserved);if(o==null)return;let n=vme(r,e);n!=null&&(yield za(t,n)),yield za(t,o)}var vme=(t,e)=>wme(t.join(e.sep),e);function wme(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=bme(t,i,e.sep),a=Vs(t.slice(o,n),e.allowReserved),c=Vs(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 bme(t,e,r){for(let o=e;o<t.length;o++)if(_me(t,o,r))return o;return t.length}var _me=(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*XH(t,e,r){let o=Vs(r,e.allowReserved);if(o==null)return;let n=za(t,o);if(t.prefix!=null){yield n;return}let i=kO(r,",");if(i.length<2){yield n;return}let s=YH(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?Rme(i,e.allowReserved):null;a!=null&&(yield za(t,a)),yield za(t,s),yield n}var Sme=(t,e,r)=>SO(t,e,kO(r,e.sep).map(Pme),0,0);function*SO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of xme(i,e,r,n,t))for(let a of SO(t,e,r,o+1,s.index)){let c=EO(s.bindings,a);c!=null&&(yield c)}yield*SO(t,e,r,o+1,n)}function*xme(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*kme(t,e,r,o,n);return}yield*Eme(t,e,r,o)}}function*Eme(t,e,r,o){let n=r[o];if(n.name===Gd(t.name))for(let i of XH(t,e,n.value))yield{bindings:i,index:o+1}}function*kme(t,e,r,o,n){yield*$me(t,e,r,o),yield*Ame(t,e,r,o,n)}function*$me(t,e,r,o){let n=[...Ime(Gd(t.name),e,r,o)];n.length>0&&(yield{bindings:za(t,n),index:o+n.length})}function*Ime(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Vs(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*Ame(t,e,r,o,n){let i=[...Tme(e,r,o,new Set(n.map(s=>Gd(s.name))))];i.length>0&&(yield{bindings:za(t,Object.fromEntries(i)),index:o+i.length})}function*Tme(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=Vs(i.name,t.allowReserved),a=Vs(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function Pme(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function Rme(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Vs(t[o],e),i=Vs(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function YH(t,e){let r=[];for(let o of t){let n=Vs(o,e);if(n==null)return null;r.push(n)}return r}function Vs(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var za=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function EO(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=Cme(i,n);if(s==null)return null;r[o]=s}return r}var Cme=(t,e)=>wx(t)||wx(e)?Ome(t,e):Nme(t.value,e.value)?t:null;function Ome(t,e){let r=VH(t.value),o=VH(e.value);if(r==null||o==null)return null;let n=wx(t),i=wx(e);if(!n&&!i)return null;if(n&&!i)return Xh(o,t.prefix)===r?e:null;if(!n&&i)return Xh(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Xh(o,s)===r?e:null:Xh(r,a)===o?t:null}var wx=t=>t.prefix!=null,VH=t=>typeof t=="string"?t:null;function Nme(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):BH(t)?BH(e)&&Dme(Object.entries(t),Object.entries(e)):t===e}var Dme=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),BH=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),zme=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),kO=(t,e)=>e===""?[t]:t.split(e),jme=["=",",","!","@","|"];function Mme(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new jpe(e,r));let n=t[0];if(Vme(n))return o(new Mpe(e,r+1,n));if(!HH(n)&&wO(t,0)<1)return o(new Upe(e,r+1,n));let i=HH(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:Ume(t,e,r+1,s)}}function Ume(t,e,r,o){if(o>=t.length)throw new vO(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new MH(e,r+i):new vO(e,r+i);let s=i,a=Lme(t,i);if(a===s)throw new vO(e,r+i);let c=t.slice(s,a);i=a;let u=Fme(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new Vpe(e,r+i,t[i]):new Lpe(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 MH(e,r+i-1)}return n}function Lme(t,e){let r=e,o=!0;for(;r<t.length;){let n=wO(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||wO(t,r+1)<1)break;r++,o=!0}return r}function Fme(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&&Bme(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new Fpe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function HH(t){return qpe.includes(t)&&t!==""}function Vme(t){return jme.includes(t)}function Bme(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function Hme(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 Ope(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new Dpe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let f=t.slice(i+1,l);try{o.push(Mme(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 Npe(t,i)),n(s),i++;continue}let a=Kpe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=eg(t,i);r(new zpe(t,i,c)),n(c),i+=u}return o}var _x=class QH{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=Jme(r),this.#e=qme(Hme(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new QH(e,r)}get tokens(){return this.#e}expand=e=>GH(this.#e,e,this.#t);match=e=>ume(this.#e,e,this.#t);toString=()=>this.uriTemplate},qme=t=>Object.freeze(t.map(Zme)),Zme=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(Kme))}),Kme=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),Wme=()=>{},Jme=({strict:t,report:e})=>(e??=Wme,t??=!0,e=t?Gme(e):e,{strict:t,report:e}),Gme=t=>e=>{throw t(e),e};function Sx(t,e){let r={};if(Object.keys(e).some(a=>!t.parameters.some(c=>c.name===a)))throw new Error("Use the parameters this function declares.");for(let a of t.parameters){let c=e[a.name]??a.default??"";if(a.required&&!c)throw new Error("Complete the required function parameters.");if(c.length>8192)throw new Error("The function argument is too long.");r[a.name]=c}let o=a=>typeof a=="string"?a.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(c,u)=>{if(!Object.hasOwn(r,u))throw new Error("Declare every function parameter.");return r[u]}):Array.isArray(a)?a.map(o):a&&typeof a=="object"?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,o(u)])):a,n=new _x(t.request.url).expand(r),i=Su.parse({...o(t.request),url:n,bindings:t.request.bindings}),s=new URL(t.request.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(n).origin!==s.origin)throw new Error("The function must have a fixed destination host.");return i}var xx=class extends Error{constructor(r,o){super(o);this.code=r}code},$O=class extends Error{constructor(r){super("The execution request is saved locally. Check execution "+r+" before starting another operation.");this.id=r}id},Ex=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||R(r)!==R(e))throw new xx("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/"+k.parse(e)+"/binding",{},Ci);return await uO(r),{...r,fingerprint:await ge(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new xx("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/"+k.parse(e)+"/registration",{},DH);if(await Zd(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/"+k.parse(e)+"/bound-recipients",{},xu(RH));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:o,...n}of r)await uO(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/resources/"+k.parse(e)+"/custody",{},NH);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await Vo(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=fO(o);await this.trusted(n);let i=await this.trust.checkpoint(r);if(i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&R(o.policy)!==R(i.policy)||o.materialRevision===i.materialRevision&&await ge(o)!==i.digest)throw new Error("The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!fH(i.policy,o))throw new Error("An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return lx((await this.read(e)).content,this.binding,this.keys.encryption)}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=>R(c)===R(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=>c.actor.id!==this.binding.id):[];for(let c of o){if(await this.trusted(c.manifest.executor),!c.manifest.callers.some(u=>R(u)===R(this.binding)))throw new Error("This execution environment has not accepted your identity.");a.push({actor:this.binding,executor:c.manifest.executor,operations:r==="app"?["connect","refresh","revoke"]:["http","command","function","refresh","revoke"],origins:[],functionDigests:[],callerProgram:r!=="app",expiresAt:s})}return Ls.parse({format:1,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,kind: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&&R(o)===R({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await mH(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:s,...i?{version:i.version}:{}}},Pi);return await this.trust.rememberContent(s),a}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.kind==="connection"&&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:"secret",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},xu(Pi));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,"secret");return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await cx(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=await this.environment(r),s=Wd.parse(o),a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=s.kind==="http"?s.request:s.kind==="function"?Sx(s.definition,s.arguments):null;if(s.kind==="http"||s.kind==="function"){let p=s.kind==="function"?s.definition.save:n.save??{};if(s.kind==="function"&&Object.keys(p).length&&s.definition.outputOwnerId!==e)throw new Error("Run this function for its approved output owner.");let m=Object.fromEntries(await Promise.all(Object.entries(p).map(async([g,v])=>[g,await this.output(e,v,a,i,c)])));s.kind==="http"?s.save=m:s.outputs=m}let l=s.kind==="command"?s.inputs.map(p=>p.source.id):u?u.bindings.flatMap(p=>p.parts.flatMap(m=>typeof m=="string"?[]:[m.id])):[],d=await this.sourceContents([...l,...n.sourceIds??[]]),f={format:1,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:i.manifest.executor,environmentDigest:await ge(i.manifest),operation:s.kind,operationDigest:await ge(s),...n.approval?{approval:n.approval}:{},functionDigest:s.kind==="function"?await ge(s.definition):null,sources:await Promise.all(d.map(async p=>({id:p.policy.id,kind:p.policy.kind,materialRevision:p.materialRevision,policyDigest:await ge(p.policy),...p.policy.kind==="connection"&&typeof p.metadata.authorizationDigest=="string"?{authorizationDigest:p.metadata.authorizationDigest}:{}}))),resultRecipients:[this.binding],createdAt:new Date().toISOString(),expiresAt:c};await px(i,f);for(let p of d)await Au(p,p.policy.kind==="app"&&!["connect","revoke"].includes(f.operation)?{...f,operation:"refresh"}:f,p.policy.kind==="app"?{}:{destination:u?.url});return gH(f,s,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/executions",{method:"POST",body:e},Nn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new $O(e.intent.id)}}async resume(e){let r=await this.trust.run(k.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(R(r.intent.actor)!==R(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");return this.submitPrepared(r)}async result(e){if(R(e.intent.actor)!==R(this.binding)||e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another requester.");let r=await cO(e.requestSignature,this.binding.signing,"run");if(R(r.intent)!==R(e.intent))throw new Error("The result belongs to a different signed request.");return await this.trusted(e.intent.executor),e.receipt?SH(e.receipt,e.intent,this.binding.id,this.keys):null}};import{lstat as Xme,mkdir as Yme,readFile as Qme,readdir as ehe}from"node:fs/promises";import{join as eq}from"node:path";var tq=h.string().regex(/^(run|oauth|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),Pu=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 R({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:tq.parse(e)})}async read(e){let r=this.context(e),o=eq(this.directory,e+".json");try{let n=await Xme(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=h.string().max(32e6).parse(JSON.parse(await Qme(o,"utf8"))),s=await Nh(i,await Qn(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(Eu(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await to({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 yn(n,this.privateKeys.signing,"journal"),s=lt(R({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new Md(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Qn(this.binding.encryption,"ECDH-ES+A256KW"));await Yme(this.directory,{recursive:!0,mode:448}),await Jd(eq(this.directory,e+".json"),R(a),!0)}async keys(e){let r;try{r=await ehe(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=>tq.parse(o.name.slice(0,-5)))}};var kx=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Us(e),await this.journal.write("identity_"+e.principalId,e)}checkpoint(e){return this.journal.read("checkpoint_"+e)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await ge(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&R(r)!==R(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var Pt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function B(t,e,r,o){throw new Pt(t,e,r,o)}var $x=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 Pt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},zH)}renew(e,r){return this.api.json("/api/executions/"+e+"/renew",{method:"POST",body:{lease:r}},h.object({active:h.boolean()}))}dispatch(e,r){return this.api.json("/api/executions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/executions/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},Nn)}capture(e,r){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r}},h.object({id:k}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},vx),capture:(r,o)=>this.capture(r,o),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Gh),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Gh),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},ro),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}},Gh),state:r=>e.json("/api/connections/"+r+"/operation",{},Gh.nullable())}}};var ene=kt(xq(),1);import{randomBytes as Qre,randomUUID as hU}from"node:crypto";var zx=h.record(h.string().max(100),h.string().max(16384)),Ua=h.object({format:h.literal(1),methodId:h.string().min(1),generation:k,clientId:h.string().max(1e3),clientSecret:h.string().max(16384).optional(),fields:zx}).strict();function Cu(t){return t.kind==="oauth"&&t.config.adapter!=="openrouter"}var khe=h.object({accessToken:h.string().min(1).max(16384),refreshToken:h.string().min(1).max(16384).optional(),expiresAt:h.number().nullable(),refreshExpiresAt:h.number().optional(),scopes:h.array(h.string()),account:h.string(),accountName:h.string(),accountVerified:h.boolean().optional(),scopesStatus:h.enum(["unknown","requested","reported"]).optional(),extra:zx,facts:bu}).strict(),La=h.object({format:h.literal(1),methodId:h.string().min(1),method:_u,generation:k,appId:k.nullable(),appGeneration:k.nullable(),oauth:khe.optional(),fields:zx.optional(),role:h.object({arn:h.string().regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),externalId:h.string().min(16).max(1e3),region:h.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/)}).strict().optional()}).strict().superRefine((t,e)=>{(t.method.kind==="oauth"&&(!t.oauth||Cu(t.method)&&(!t.appId||!t.appGeneration))||t.method.kind==="token"&&!t.fields||t.method.kind==="role"&&!t.role)&&e.addIssue({code:"custom",message:"Supply the material required by this connection method."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."})}),MFe=h.object({methodId:h.string().min(1).max(200),clientId:h.string().max(1e3),generation:k}).strict(),$he=h.object({methodId:h.string().min(1).max(200),methodName:fe,methodKind:tO,generation:k,authorizationDigest:pr,appId:k.nullable(),account:h.string().max(2e3),accountId:h.string().max(2e3).nullable(),accountVerified:h.boolean(),scopes:h.array(h.string().max(1e3)).max(200),scopesStatus:h.enum(["unknown","requested","reported"]),outputs:h.array(h.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:h.literal("ready")}).strict();async function Ou(t){let e=t.method.kind==="role"?["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION"]:Object.keys(t.method.config.outputs),r=await ge({generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,account:t.oauth?.account??t.role?.arn??null,accountVerified:t.oauth?.accountVerified??!1,scopes:[...t.oauth?.scopes??[]].sort(),role:t.role??null});return $he.parse({methodId:t.methodId,methodName:t.method.name,methodKind:t.method.kind,generation:t.generation,authorizationDigest:r,appId:t.appId,account:t.oauth?.accountName??t.role?.arn??t.method.name,accountId:t.role?.arn??(t.oauth?.accountVerified?t.oauth.account:null),accountVerified:!!(t.role||t.oauth?.accountVerified),scopes:t.oauth?.scopes??[],scopesStatus:t.oauth?.scopesStatus??"unknown",outputs:e,state:"ready"})}var Ihe=h.object({action:h.literal("start"),flowId:k,name:fe,methodId:h.string().min(1),method:_u,appId:k.nullable(),fields:zx.default({}),scopes:h.array(h.string().max(1e3)).max(200).default([]),redirectUri:h.url().optional(),role:La.shape.role}).strict(),jx=h.discriminatedUnion("action",[Ihe,h.object({action:h.literal("exchange"),flowId:k,parameters:h.string().max(16384)}).strict(),h.object({action:h.literal("commit"),flowId:k,authorizationDigest:pr,approval:qh}).strict(),h.object({action:h.literal("refresh"),id:k}).strict(),h.object({action:h.literal("revoke"),id:k}).strict()]);function rg(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 Ni(t,e){for(let r of rg(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function DO(t,e,r){let o=rg(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 Qd(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 ng(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}import{createHash as xge}from"node:crypto";var zO;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(zO="oauth4webapi/v3.8.8");function ag(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 Di="ERR_INVALID_ARG_VALUE",zi="ERR_INVALID_ARG_TYPE";function Bt(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var qO=Symbol(),Ahe=Symbol(),The=Symbol(),ZO=Symbol();var Mx=Symbol();var Phe=new TextEncoder,Rhe=new TextDecoder;function jO(t){return typeof t=="string"?Phe.encode(t):Rhe.decode(t)}var MO;Uint8Array.prototype.toBase64?MO=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):MO=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 UO;Uint8Array.fromBase64?UO=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Bt("The input to be decoded is not correctly encoded.",Di,e)}}:UO=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 Bt("The input to be decoded is not correctly encoded.",Di,e)}};function LO(t){return typeof t=="string"?UO(t):MO(t)}var ef=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=ige,Error.captureStackTrace?.(this,this.constructor)}},og=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 me(t,e,r){return new og(t,{code:e,cause:r})}function Che(t){return t.toLowerCase().replace(/^application\//,"")}function ig(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function KO(t){ag(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(zO&&!e.has("user-agent")&&e.set("user-agent",zO),e.has("authorization"))throw Bt('"options.headers" must not include the "authorization" header name',Di);return e}function Ohe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Bt('"options.signal" must return or be an instance of AbortSignal',zi);return e}}function Ux(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Bt(`${r} must be a number`,zi,n);if(t>0)return;if(e){if(t!==0)throw Bt(`${r} must be a non-negative number`,Di,n);return}throw Bt(`${r} must be a positive number`,Di,n)}catch(i){throw o?me(i.message,o,n):i}}function hr(t,e,r,o){try{if(typeof t!="string")throw Bt(`${e} must be a string`,zi,o);if(t.length===0)throw Bt(`${e} must not be empty`,Di,o)}catch(n){throw r?me(n.message,r,o):n}}function $q(t){Dhe(t,"application/json")}function Nhe(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 me(r,age,t)}function Dhe(t,e){if(Cq(t)!==e)throw Nhe(t,e)}async function Iq(t){return hr(t,"codeVerifier"),LO(await crypto.subtle.digest("SHA-256",jO(t)))}function WO(t){let e=t?.[Ahe];return typeof e=="number"&&Number.isFinite(e)?e:0}function JO(t){let e=t?.[The];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Aq(){return Math.floor(Date.now()/1e3)}function Du(t){if(typeof t!="object"||t===null)throw Bt('"as" must be an object',zi);hr(t.issuer,'"as.issuer"')}function zu(t){if(typeof t!="object"||t===null)throw Bt('"client" must be an object',zi);hr(t.client_id,'"client.client_id"')}function Eq(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 Tq(t){return hr(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Pq(t){return hr(t,'"clientSecret"'),(e,r,o,n)=>{let i=Eq(r.client_id),s=Eq(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function Rq(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var zhe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function jhe(t,e){if(e&&t.protocol!=="https:")throw me("only requests to HTTPS are allowed",uge,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw me("only HTTP and HTTPS requests are allowed",lge,t)}function kq(t,e,r,o){let n;if(typeof t!="string"||!(n=zhe(t)))throw me(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?dge:fge,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return jhe(n,o),n}function GO(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?kq(t.mtls_endpoint_aliases[e],e,r,o):kq(t[e],e,r,o)}var FO=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=oge,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)}},sg=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=sge,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)}},VO=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=nge,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Lx="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Mhe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Uhe='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Lhe="("+Lx+")\\s*=\\s*"+Uhe,Fhe="("+Lx+")\\s*=\\s*("+Lx+")",Vhe=new RegExp("^[,\\s]*("+Lx+")"),Bhe=new RegExp("^[,\\s]*"+Lhe+"[,\\s]*(.*)"),Hhe=new RegExp("^[,\\s]*"+Fhe+"[,\\s]*(.*)"),qhe=new RegExp("^("+Mhe+")(?:$|[,\\s])(.*)");function Zhe(t){if(!ag(t,Response))throw Bt('"response" must be an instance of Response',zi);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(Vhe),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(Bhe)){[,f,p,o]=n,p.includes("\\")&&(p=p.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=p;continue}if(n=o.match(Hhe)){[,f,p,o]=n,u[f.toLowerCase()]=p;continue}if(n=o.match(qhe)){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 Khe(t){if(t.status>399&&t.status<500){Bx(t),$q(t);try{let e=await t.clone().json();if(ig(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function XO(t,e,r){if(t.status!==e){Jhe(t);let o;throw(o=await Khe(t))?(await t.body?.cancel(),new FO("server responded with an error in the response body",{cause:o,response:t})):me(`"response" is not a conform ${r} response (unexpected HTTP status code)`,cge,t)}}function Whe(t){if(!eN.has(t))throw Bt('"options.DPoP" is not a valid DPoPHandle',Di)}function Cq(t){return t.headers.get("content-type")?.split(";")[0]}async function YO(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?.[ZO]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Ohe(o,s?.signal)})}async function Oq(t,e,r,o,n,i){let s=GO(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[qO]!==!0);n.set("grant_type",o);let a=KO(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(Whe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await YO(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Nq(t,e,r,o,n){Du(t),zu(e),hr(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),Oq(t,e,r,"refresh_token",i,n)}var Dq=new WeakMap,zq=new WeakMap;function jq(t){if(!t.id_token)return;let e=Dq.get(t);if(!e)throw Bt('"ref" was already garbage collected or did not resolve from the proper sources',Di);return e}async function QO(t,e,r,o,n,i){if(Du(t),zu(e),!ag(r,Response))throw Bt('"response" must be an instance of Response',zi);await XO(r,200,"Token Endpoint"),Bx(r);let s=await tZ(r);if(hr(s.access_token,'"response" body "access_token" property',Ke,{body:s}),hr(s.token_type,'"response" body "token_type" property',Ke,{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;Ux(a,!0,'"response" body "expires_in" property',Ke,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&hr(s.refresh_token,'"response" body "refresh_token" property',Ke,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw me('"response" body "scope" property must be a string',Ke,{body:s});if(s.id_token!==void 0){hr(s.id_token,'"response" body "id_token" property',Ke,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Ux(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await Yhe(t,e,s.id_token,a,n);ege(e,c),Qhe(c),zq.set(r,u),Dq.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 ef("unsupported `token_type` value",{cause:{body:s}});return s}function Jhe(t){let e;if(e=Zhe(t))throw new VO("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Mq(t,e,r,o){return QO(t,e,r,void 0,o?.[Mx],o?.recognizedTokenTypes)}function Uq(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw me('unexpected JWT "aud" (audience) claim value',tf,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw me('unexpected JWT "aud" (audience) claim value',tf,{expected:t,claims:e.claims,claim:"aud"});return e}function Lq(t,e){let r=t[gge]?.(e)??t.issuer;if(e.claims.iss!==r)throw me('unexpected JWT "iss" (issuer) claim value',tf,{expected:r,claims:e.claims,claim:"iss"});return e}var eN=new WeakSet;function Ghe(t){return eN.add(t),t}var tN=Symbol();async function Fq(t,e,r,o,n,i,s){if(Du(t),zu(e),!eN.has(o))throw Bt('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Di);hr(n,'"redirectUri"');let a=Nu(o,"code");if(!a)throw me('no authorization code in "callbackParameters"',Ke);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==tN&&(hr(i,'"codeVerifier"'),c.set("code_verifier",i)),Oq(t,e,r,"authorization_code",c,s)}var Vq={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 Bq(t,e){for(let r of t)if(e.claims[r]===void 0)throw me(`JWT "${r}" (${Vq[r]}) claim missing`,Ke,{claims:e.claims});return e}function Xhe(t,e){if(typeof e.claims[t]!="string")throw me(`unexpected JWT "${t}" (${Vq[t]}) claim type`,Ke,{claims:e.claims});return e}function Yhe(t,e,r,o,n){return Yq(r,Qq.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),WO(e),JO(e),n).then(Bq.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(Lq.bind(void 0,t)).then(Uq.bind(void 0,e.client_id)).then(Xhe.bind(void 0,"sub"))}function Hq(t,e){if(e===Vx)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?Vx:(Ux(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function Qhe(t){t.auth_time!==void 0&&Ux(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Ke,{claims:t})}function qq(t,e,r){if(r===Vx)return;let o=Aq()+WO(t),n=JO(t);if(e.auth_time+r<o-n)throw me("too much time has elapsed since the last End-User authentication",HO,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Zq(t,e){let r=e===Fx?void 0:e;if(t.nonce!==r)throw me('unexpected ID Token "nonce" claim value',tf,{expected:r,claims:t,claim:"nonce"})}function ege(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw me('ID Token "aud" (audience) claim includes additional untrusted audiences',tf,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw me('unexpected ID Token "azp" (authorized party) claim value',tf,{expected:t.client_id,claims:e,claim:"azp"})}}var Fx=Symbol(),Vx=Symbol();async function Kq(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?tge(t,e,r,o.expectedNonce,o.maxAge,o[Mx],o.recognizedTokenTypes):rge(t,e,r,o?.maxAge,o?.[Mx],o?.recognizedTokenTypes)}async function tge(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=Fx;break;case Fx:break;default:hr(o,'"expectedNonce" argument'),a.push("nonce")}n=Hq(e,n),n!==Vx&&a.push("auth_time");let c=await QO(t,e,r,a,i,s);hr(c.id_token,'"response" body "id_token" property',Ke,{body:c});let u=jq(c);return qq(e,u,n),Zq(u,o),c}async function rge(t,e,r,o,n,i){let s=await QO(t,e,r,void 0,n,i),a=jq(s);return a&&(qq(e,a,Hq(e,o)),Zq(a,Fx)),s}var nge="OAUTH_WWW_AUTHENTICATE_CHALLENGE",oge="OAUTH_RESPONSE_BODY_ERROR",ige="OAUTH_UNSUPPORTED_OPERATION",sge="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var BO="OAUTH_PARSE_ERROR",Ke="OAUTH_INVALID_RESPONSE";var age="OAUTH_RESPONSE_IS_NOT_JSON",cge="OAUTH_RESPONSE_IS_NOT_CONFORM",uge="OAUTH_HTTP_REQUEST_FORBIDDEN",lge="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",HO="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",tf="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var dge="OAUTH_MISSING_SERVER_METADATA",fge="OAUTH_INVALID_SERVER_METADATA";function pge(t,e){if(typeof e.header.typ!="string"||Che(e.header.typ)!==t)throw me('unexpected JWT "typ" header parameter value',Ke,{header:e.header});return e}async function Wq(t,e,r,o,n){Du(t),zu(e),hr(o,'"token"');let i=GO(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[qO]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=KO(n?.headers);return a.delete("accept"),YO(t,e,r,i,s,a,n)}async function Jq(t){if(!ag(t,Response))throw Bt('"response" must be an instance of Response',zi);await XO(t,200,"Revocation Endpoint")}function Bx(t){if(t.bodyUsed)throw Bt('"response" body has been used already',Di)}async function Gq(t,e,r,o,n){Du(t),zu(e),hr(o,'"token"');let i=GO(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[qO]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=KO(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),YO(t,e,r,i,s,a,n)}async function Xq(t,e,r,o){if(Du(t),zu(e),!ag(r,Response))throw Bt('"response" must be an instance of Response',zi);await XO(r,200,"Introspection Endpoint");let n;if(Cq(r)==="application/token-introspection+jwt"){Bx(r);let{claims:i,jwt:s}=await Yq(await r.text(),Qq.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),WO(e),JO(e),o?.[Mx]).then(pge.bind(void 0,"token-introspection+jwt")).then(Bq.bind(void 0,["aud","iat","iss"])).then(Lq.bind(void 0,t)).then(Uq.bind(void 0,e.client_id));if(zq.set(r,s),!ig(i.token_introspection))throw me('JWT "token_introspection" claim must be a JSON object',Ke,{claims:i});n=i.token_introspection}else Bx(r),n=await tZ(r);if(typeof n.active!="boolean")throw me('"response" body "active" property must be a boolean',Ke,{body:n});return n}async function Yq(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 ef("JWE decryption is not configured",{cause:t});if(a!==3)throw me("Invalid JWT",Ke,t);let c;try{c=JSON.parse(jO(LO(i)))}catch(d){throw me("failed to parse JWT Header body as base64url encoded JSON",BO,d)}if(!ig(c))throw me("JWT Header must be a top level object",Ke,t);if(e(c),c.crit!==void 0)throw new ef('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(jO(LO(s)))}catch(d){throw me("failed to parse JWT Payload body as base64url encoded JSON",BO,d)}if(!ig(u))throw me("JWT Payload must be a top level object",Ke,t);let l=Aq()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw me('unexpected JWT "exp" (expiration time) claim type',Ke,{claims:u});if(u.exp<=l-o)throw me('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',HO,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw me('unexpected JWT "iat" (issued at) claim type',Ke,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw me('unexpected JWT "iss" (issuer) claim type',Ke,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw me('unexpected JWT "nbf" (not before) claim type',Ke,{claims:u});if(u.nbf>l+o)throw me('unexpected JWT "nbf" (not before) claim value',HO,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw me('unexpected JWT "aud" (audience) claim type',Ke,{claims:u});return{header:c,claims:u,jwt:t}}function Qq(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw me('unexpected JWT "alg" header parameter',Ke,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw me('unexpected JWT "alg" header parameter',Ke,{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 me('unexpected JWT "alg" header parameter',Ke,{header:o,expected:r,reason:"default value"});return}throw me('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Nu(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw me(`"${e}" parameter must be provided only once`,Ke);return r}var mge=Symbol(),hge=Symbol();function eZ(t,e,r,o){if(Du(t),zu(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Bt('"parameters" must be an instance of URLSearchParams, or URL',zi);if(Nu(r,"response"))throw me('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Ke,{parameters:r});let n=Nu(r,"iss"),i=Nu(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw me('response parameter "iss" (issuer) missing',Ke,{parameters:r});if(n&&n!==t.issuer)throw me('unexpected "iss" (issuer) response parameter value',Ke,{expected:t.issuer,parameters:r});switch(o){case void 0:case hge:if(i!==void 0)throw me('unexpected "state" response parameter encountered',Ke,{expected:void 0,parameters:r});break;case mge:break;default:if(hr(o,'"expectedState" argument'),i!==o)throw me(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Ke,{expected:o,parameters:r})}if(Nu(r,"error"))throw new sg("authorization response from the server is an error",{cause:r});let a=Nu(r,"id_token"),c=Nu(r,"token");if(a!==void 0||c!==void 0)throw new ef("implicit and hybrid flows are not supported");return Ghe(new URLSearchParams(r))}async function tZ(t,e=$q){let r;try{r=await t.json()}catch(o){throw e(t),me('failed to parse "response" body as JSON',BO,o)}if(!ig(r))throw me('"response" body must be a top level object',Ke,{body:r});return r}var gge=Symbol();import{lookup as vge}from"node:dns/promises";import{isIP as rZ,BlockList as nZ}from"node:net";import{request as wge}from"node:https";import{brotliDecompressSync as bge,gunzipSync as _ge,inflateSync as Sge}from"node:zlib";var Hx=new nZ;for(let[t,e]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])Hx.addSubnet(t,e,"ipv4");var oZ=new nZ;oZ.addSubnet("2000::",3,"ipv6");for(let[t,e]of[["2001::",32],["2001:db8::",32],["2002::",16]])Hx.addSubnet(t,e,"ipv6");function iZ(t){let e=rZ(t);return e===4?!Hx.check(t,"ipv4"):e===6&&oZ.check(t,"ipv6")&&!Hx.check(t,"ipv6")}function rf(t,e){let r;try{r=new URL(t)}catch{B(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)&&B(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||rZ(o)&&!iZ(o))&&B(400,"private_destination","Choose a public HTTPS destination."),r}var qx=class{constructor(e){this.origin=e}origin;async send(e){let r=rf(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&B(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))&&B(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await vge(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!iZ(u.address)))&&B(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(p,m,g)=>{m.all?g(null,[a]):g(null,a.address,a.family)}},f=wge(r,d,p=>{let m=[],g=0;p.on("data",v=>{g+=v.length,g>n?p.destroy(new Pt(413,"body_limit","The response body is too large.")):m.push(v)}),p.on("error",l),p.on("end",()=>{try{let v=Buffer.concat(m),w=p.headers["content-encoding"];if(w&&w!=="identity"){let _=w==="gzip"?_ge:w==="deflate"?Sge:w==="br"?bge:null;if(!_)throw new Pt(502,"invalid_response","The service returned an unsupported response.");v=_(v,{maxOutputLength:n})}let b={};for(let[_,E]of Object.entries(p.headers))E!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(_)&&(b[_]=Array.isArray(E)?E.join(", "):E);u({status:p.statusCode??502,headers:b,body:new Uint8Array(v)})}catch(v){l(v)}})});f.on("error",l),f.end(e.body)})}catch(s){if(s instanceof Pt)throw s;e.signal?.aborted&&B(409,"cancelled","The operation was cancelled."),B(502,"service_unavailable","The service could not be reached. Try again.")}}};function cg(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{B(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&B(502,"invalid_response","The service returned an invalid response."),e}var sZ=t=>xge("sha256").update(t).digest("hex");function nf(t,e){try{return rf(new _x(t).expand(e)).href}catch{B(400,"invalid_service_url","Check the service URL and its required fields.")}}var rN=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],nN=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&B(502,"invalid_response","The service returned an invalid expiry."),e},aZ=Object.assign(Object.create(null),{dpop:()=>B(502,"invalid_response","The service returned an unsupported token.")}),Ege=Object.assign(Object.create(null),aZ,{"user access token":()=>{}}),Zx=class{constructor(e){this.transport=e}transport;async authorize(e,r,o,n,i,s){let a=new URL(nf(e.authorizeUrl,r.fields)),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:e.adapter==="ebay"?r.fields.ruName:i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await Iq(n),c.code_challenge_method="S256"),e.adapter==="openrouter"&&(delete c.response_type,delete c.client_id,delete c.redirect_uri,c.callback_url=i,c.key_label="Foundation");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(nf(e.authorizeUrl,r.fields)).origin,token_endpoint:nf(e.tokenUrl,r.fields)};return e.issuer&&rf(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?Rq():(e.clientSecret||B(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Pq(e.clientSecret):Tq(e.clientSecret))}options(e="form"){return{[ZO]:async(r,{body:o,headers:n,method:i,signal:s})=>{let a=await this.transport.send({url:r,method:i,headers:e==="json"?{...n,"content-type":"application/json"}:n,body:e==="json"?JSON.stringify(Object.fromEntries(o)):o.toString(),signal:s});return new Response([204,205,304].includes(a.status)?null:new Uint8Array(a.body),{status:a.status,headers:a.headers})}}}async json(e){return cg({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&Ni(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&B(409,"reconnect_required","Reconnect this service to renew access."),r===429&&B(503,"service_rate_limit","The service is busy. Try again later."),B(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&B(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,c.hostname.endsWith(".myshopify.com")&&c.pathname==="/admin/oauth/access_token"&&u.token_type===void 0&&(u.token_type="bearer"),c.hostname==="api.notion.com"&&c.pathname==="/v1/oauth/token"&&u.refresh_token===null&&delete u.refresh_token,u.expires_in!==void 0&&(u.expires_in=nN(u.expires_in));try{let d=await(n?Mq:Kq)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:e.adapter==="ebay"?Ege:aZ});return{...i,...d}}catch(l){if(l instanceof Pt)throw l;B(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=e.adapter==="openrouter"?r.key:r.access_token;(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&B(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+nN(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&B(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?rN(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()+nN(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){let u;if(e.adapter==="openrouter"){let f=o.parameters;(f.getAll("state").length!==1||f.get("state")!==o.state||f.getAll("code").length!==1||!f.get("code"))&&B(400,"invalid_state","Start the connection again.");let p=await this.transport.send({url:nf(e.tokenUrl,r.fields),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:f.get("code"),code_verifier:n,code_challenge_method:"S256"})});u=this.checkResponse(e,p.status,cg(p))}else{let{server:f,client:p}=this.configuration(e,r),m;try{let g=eZ(f,p,o.parameters,o.state);m=await Fq(f,p,this.authentication(r,e.clientAuth),g,e.adapter==="ebay"?r.fields.ruName:i,e.pkce?n:tN,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(g){throw(g instanceof og||g instanceof sg)&&B(400,"invalid_state","Start the connection again."),g}u=await this.tokenResponse(e,r,m)}let l=this.token(e,u,s,a);await c?.(l,u);let d=await this.inspect(e,r,l,u);return a&&d.account!==a.account&&e.adapter!=="openrouter"&&B(409,"account_changed","Reconnect using the same service account."),d}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&B(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Nq(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return(e.identity?.url||e.adapter==="ebay"||e.adapter==="openrouter")&&(i=await this.inspect(e,r,i)),i.account!==o.account&&B(409,"account_changed","Reconnect using the same service account."),i}async inspect(e,r,o,n){let i=n??{};if(e.adapter==="ebay"){let{server:u,client:l}=this.configuration(e,r),d=await Gq({...u,introspection_endpoint:u.token_endpoint+"/introspect"},l,this.authentication(r,"basic"),o.accessToken,{...this.options(),additionalParameters:{token_type_hint:"access_token"}});try{i=await Xq(u,l,Response.json(await this.json(d),{status:d.status}))}catch{B(409,"reconnect_required","Reconnect this service to renew access.")}return(i.active!==!0||i.client_id!==r.clientId||typeof i.sub!="string"||!i.sub||typeof i.exp!="number"||i.exp*1e3<=Date.now())&&B(409,"reconnect_required","Reconnect this service to renew access."),{...o,account:i.sub,accountName:typeof i.username=="string"?i.username:i.sub,scopes:rN(i.scope),scopesStatus:"reported",accountVerified:!0,expiresAt:Math.min(o.expiresAt??1/0,i.exp*1e3)}}if(e.adapter==="openrouter"){let u=await this.transport.send({url:"https://openrouter.ai/api/v1/key",headers:{authorization:"Bearer "+o.accessToken}});i=cg(u),(u.status!==200||!i.data||typeof i.data!="object")&&B(409,"reconnect_required","Reconnect this service to renew access.");let l=i.data;return{...o,account:sZ(o.accessToken),accountName:typeof l.label=="string"?l.label:"OpenRouter",facts:l}}if(e.identity?.url){let u=await this.transport.send({url:nf(e.identity.url,{...r.fields,...o.extra,accessToken:o.accessToken,refreshToken:o.refreshToken??""}),method:e.identity.method,headers:{...e.identity.headers,authorization:"Bearer "+o.accessToken}});i=cg(u),(u.status===401||u.status===403)&&B(409,"reconnect_required","Reconnect this service to renew access."),u.status>=400&&B(502,"invalid_response","The service account could not be verified."),e.adapter==="github"&&u.headers["x-oauth-scopes"]!==void 0&&(o.scopes=rN(u.headers["x-oauth-scopes"].replaceAll(","," ")),o.scopesStatus="reported"),e.adapter==="google"&&i.email_verified!==!0&&B(502,"invalid_response","The service account could not be verified.")}else e.identity?.from==="app"&&(i=r.fields);let s=u=>{for(let l of Array.isArray(u)?u:[u]){let d=Ni(i,l);if(typeof d=="string"&&d||typeof d=="number")return String(d)}return""},a=e.identity?.id,c=a?Array.isArray(a)?a.map(u=>s(u)).filter(Boolean).join(":"):s(a):o.account||r.fields.domain||r.fields.shop||sZ(o.accessToken);return(!c||c.length>1e3)&&B(502,"invalid_response","The service account could not be verified."),{...o,account:c,accountName:e.identity&&s(e.identity.name)||c,accountVerified:!!(e.identity?.url||e.identity?.from==="token"&&n)}}async revoke(e,r,o){e.revoke||B(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=nf(e.revoke.url,{...r.fields,clientId:r.clientId,accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:u,client:l}=this.configuration(e,r),d=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),f=await Wq({...u,revocation_endpoint:n},l,d,o.refreshToken??o.accessToken,this.options());try{await Jq(f)}catch{B(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"||e.revoke.style==="github")&&(i.authorization="Basic "+Buffer.from(r.clientId+":"+(r.clientSecret??"")).toString("base64"));let a;e.revoke.style==="github"&&(i["content-type"]="application/json",a=JSON.stringify({access_token:o.accessToken})),(await this.transport.send({url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i,...a?{body:a}:{}})).status>=300&&B(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...r.fields,...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,Qd(Ni(n,s))]))}};function Zs(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Kx(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(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=lt(Qd(Ni(JSON.parse(Zs(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Zs(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var Fa=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},Wx=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 Kd(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Kd(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 ge(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 Kd(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 yH(r.request,this.binding,this.keys);await px(this.environment,f.intent);let p=Wd.parse(f.operation);if(p.kind!==o.operation)throw new Error("Use the operation authorized by this intent.");await this.preflight(p,o,r.sources),c.throwIfAborted(),s.operation=p,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.execute(p,o,r.sources,c);d=await Kd(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(f){if(f instanceof Fa)throw f;f instanceof Zh&&(f=new Pt(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 Pt)||["service_unavailable","connection_uncertain","lease_lost"].includes(f.code));d=await Kd(o,p?"uncertain":"failed",{ok:!1,result:null,error:f instanceof Pt?{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){return e.kind==="http"?e.request:e.kind==="function"?Sx(e.definition,e.arguments):null}async preflight(e,r,o){if(new Set(o.map(s=>s.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let s of o){await Vo(s);let a=r.sources.find(u=>u.id===s.policy.id);if(!a||!await pO(s,a))throw new Error("An execution input changed.");let c=await this.journal.read("checkpoint_"+s.policy.id);if(c&&(s.policy.revision<c.policy||s.materialRevision<c.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write("checkpoint_"+s.policy.id,{policy:s.policy.revision,material:s.materialRevision})}if(e.kind==="function"&&await ge(e.definition)!==r.functionDigest)throw new Error("Run the exact function authorized by this intent.");let n=this.request(e);if(n){if(rf(n.url,r.origin),[n.body,n.json,n.form].filter(a=>a!==void 0).length>1)throw new Error("Choose one request body format.");for(let a of n.bindings){let c=rg(a.pointer);if(!c.length||!["headers","body","json","form"].includes(c[0])||c[0]==="body"&&c.length!==1||["headers","form"].includes(c[0])&&c.length!==2)throw new Error("Bind credentials to request headers or the body.");DO(structuredClone(n),a.pointer,"validation")}let s=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(e.kind==="function"&&(Object.keys(s).length!==Object.keys(e.definition.save).length||Object.entries(e.definition.save).some(([a,c])=>s[a]?.name!==c)))throw new Error("Use the output destinations declared by this function.");for(let[a,c]of Object.entries(s)){if(rg(a),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let u=await Hd(c.approval);if(R(u.policy.authorities.find(l=>l.id===u.authorityId))!==R(r.actor)||u.policy.origin!==r.origin||u.policy.kind!=="secret"||u.policy.ownerId!==r.ownerId||e.kind==="function"&&e.definition.outputOwnerId!==u.policy.ownerId||!u.policy.producers.some(l=>l.runId===r.id&&R(l.executor)===R(this.binding)&&Date.parse(l.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}}let i=e.kind==="command"?e.inputs.map(s=>s.source):n?n.bindings.flatMap(s=>s.parts.filter(a=>typeof a!="string")):[];for(let s of i){let a=o.find(c=>c.policy.id===s.id);if(!a||a.policy.kind!==s.kind)throw new Error("Use the input named in the signed request.");await Au(a,r,{...n?{destination:n.url}:{}}),await qd(a,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 execute(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=[],a=new Map,c=async p=>{let m=o.find(v=>v.policy.id===p.id);if(p.kind==="secret")return qd(m,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");a.has(p.id)||a.set(p.id,this.extension.outputs(m,r,o,n,i?.url));let g=await a.get(p.id);if(!Object.hasOwn(g,p.output))throw new Error("Choose an available connection output.");return lt(g[p.output])};if(e.kind==="command"){let p=await Kx(e.inputs,c),m=await this.commands.execute({command:e.command,timeoutSeconds:e.timeoutSeconds,...e.stdin===void 0?{}:{stdin:e.stdin},environment:p.environment,files:p.files},n);return{...m,stdout:ng(m.stdout,p.sensitive),stderr:ng(m.stderr,p.sensitive)}}let u=structuredClone(i);for(let p of u.bindings){let m="";for(let g of p.parts)if(typeof g=="string")m+=g;else{let v=Zs(await c(g));s.push(v,Buffer.from(v).toString("base64"),Buffer.from(v).toString("base64url")),m+=v}DO(u,p.pointer,m)}let l=u.body;u.json!==void 0&&(l=JSON.stringify(u.json),u.headers["content-type"]="application/json"),u.form!==void 0&&(l=new URLSearchParams(u.form).toString(),u.headers["content-type"]="application/x-www-form-urlencoded");let d=await this.transport.send({url:u.url,method:u.method,headers:u.headers,...l===void 0?{}:{body:l},signal:n}),f=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(Object.keys(f).length){if(d.status>=400)throw new Pt(502,"service_response","The service returned an unsuccessful response.");let p={};for(let[m,g]of Object.entries(f)){let v=d.body;if(m!==""){let b=Ni(JSON.parse(Zs(v)),m);if(b===void 0)throw new Pt(400,"invalid_pointer","The response value was not found.");v=lt(typeof b=="string"?b:JSON.stringify(b))}let w=await ux(v,g.approval,r.id,this.binding,this.keys,{bytes:v.length});p[g.name]=(await this.broker.capture(g.name,w)).id}return{status:d.status,saved:p}}return{status:d.status,headers:Object.fromEntries(Object.entries(d.headers).map(([p,m])=>[p,ng(m,s)])),body:ng(Zs(d.body),s)}}};var yl=kt(Yre(),1);import{randomUUID as BIe}from"node:crypto";var hI=class{async obtain(e,r,o){let n=new yl.STSClient({region:o});try{let s=(await n.send(new yl.AssumeRoleCommand({RoleArn:e,RoleSessionName:"foundation-"+BIe().slice(0,8),ExternalId:r,DurationSeconds:3600}))).Credentials;(!s?.AccessKeyId||!s.SecretAccessKey||!s.SessionToken)&&B(502,"invalid_response","AWS did not return credentials.");let a=new yl.STSClient({region:o,credentials:{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken}});try{(await a.send(new yl.GetCallerIdentityCommand({}))).Account!==e.split(":")[4]&&B(502,"account_changed","The AWS account could not be verified.")}finally{a.destroy()}return{AWS_ACCESS_KEY_ID:s.AccessKeyId,AWS_SECRET_ACCESS_KEY:s.SecretAccessKey,AWS_SESSION_TOKEN:s.SessionToken,AWS_DEFAULT_REGION:o}}catch(i){if(i instanceof Pt)throw i;B(502,"role_denied","Check the IAM role and its trust policy for this executor.")}finally{n.destroy()}}};function gU(t,e){if(t.kind==="role")return{};let r=t.config.fields,o={...t.kind==="oauth"?t.config.defaults:{},...e};for(let n of r)n.required!==!1&&!o[n.name]&&B(400,"missing_field","Complete the required service fields."),o[n.name]?.includes("\0")&&B(400,"invalid_field","Check the service fields."),n.pattern&&(n.pattern.length>200||!(0,ene.default)(n.pattern))&&B(400,"invalid_pattern","Use a simple field validation pattern."),n.pattern&&o[n.name]&&!new RegExp(n.pattern,"u").test(o[n.name].slice(0,1e3))&&B(400,"invalid_field","Check the service fields.");return Object.keys(e).some(n=>!r.some(i=>i.name===n))&&B(400,"invalid_field","Remove unrecognized service fields."),o}var Ap=class{constructor(e,r,o,n,i,s=new hI){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.roles=s}binding;keys;broker;journal;transport;roles;active=new Set;oauth(e){return new Zx({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.kind===r);return n||B(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=La.parse(JSON.parse(Zs(await qd(e,r,this.keys,{destination:o}))));return(await Ou(n)).authorizationDigest!==e.metadata.authorizationDigest&&B(409,"connection_changed","Approve the current service account and permissions before using this connection."),n}async app(e,r,o,n){let i=this.source(e,"app",n),s=Ua.parse(JSON.parse(Zs(await qd(i,o,this.keys))));return s.methodId!==r&&B(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(!Cu(e.method))return Ua.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation==="revoke"?"revoke":"refresh",i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&B(409,"app_changed","Reconnect this service with the current application."),i}async flow(e,r){let o=await this.journal.read("oauth_"+e);return(!o||o.expiresAt<=Date.now()||R(o.actor)!==R(r.actor)||o.ownerId!==r.ownerId)&&B(409,"connection_expired","Start the connection again."),o}async validate(e,r,o){let n=jx.parse(e),i=n.action==="refresh"||n.action==="revoke"?n.action:"connect";if(r.operation!==i&&B(400,"wrong_operation","Use the approved connection operation."),n.action==="start")if(n.method.kind==="oauth"){(Cu(n.method)&&!n.appId||!n.redirectUri)&&B(400,"app_required","Choose an OAuth application and callback URL.");let s=new URL(n.redirectUri);(s.username||s.password||s.hash||s.search||!(n.redirectUri===r.origin+"/oauth/callback"||s.protocol==="http:"&&["127.0.0.1","[::1]"].includes(s.hostname)))&&B(400,"invalid_redirect","Use the Foundation callback or a callback on this computer.");let a=n.appId?await this.app(n.appId,n.methodId,r,o):Ua.parse({format:1,methodId:n.methodId,generation:n.flowId,clientId:"",fields:{}});gU(n.method,a.fields),Cu(n.method)&&n.method.config.clientAuth!=="none"&&!a.clientSecret&&B(409,"app_required","Add a client secret to this OAuth application.")}else n.method.kind==="token"?gU(n.method,n.fields):n.role||B(400,"role_required","Choose a role trusted for this executor.");else if(n.action==="commit"){let s=await this.flow(n.flowId,r),a=await Hd(n.approval);(!s.material||n.authorizationDigest!==(await Ou(s.material)).authorizationDigest||a.policy.kind!=="connection"||a.policy.ownerId!==r.ownerId||a.policy.origin!==r.origin||R(a.policy.authorities.find(c=>c.id===a.authorityId))!==R(r.actor)||!a.policy.producers.some(c=>c.runId===r.id&&R(c.executor)===R(this.binding)&&Date.parse(c.expiresAt)>Date.now()))&&B(403,"approval_required","Review the connection and approve its recipients before saving.")}else if(n.action==="exchange"){let s=await this.flow(n.flowId,r);if(s.app&&s.input.appId){let a=await this.app(s.input.appId,s.input.methodId,r,o);R(a)!==R(s.app)&&B(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,"connection",o),a=await this.material(s,r);a.method.kind==="oauth"&&await this.connectionApp(a,r,o)}}async execute(e,r,o,n){let i=jx.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&B(409,"connection_busy","Another operation is updating this connection."),this.active.add(s);try{if(n.throwIfAborted(),i.action==="start")return await this.start(i,r,o);if(i.action==="exchange")return await this.exchange(i,r,n);if(i.action==="commit")return await this.commit(i,r);let a=this.source(i.id,"connection",o),c=await this.material(a,r);if(i.action==="refresh"){let u=c.method.kind==="oauth"?await this.refresh(a,c,r,o,n):c;return{kind:"refreshed",id:a.policy.id,...await Ou(u)}}return c.method.kind!=="oauth"&&B(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await this.oauth(n).revoke(c.method.config,await this.connectionApp(c,r,o),c.oauth),{kind:"revoked",id:a.policy.id}}finally{this.active.delete(s)}}async review(e,r){return{kind:"review",flowId:e,name:r.input.name,metadata:await Ou(r.material)}}async start(e,r,o){let n="oauth_"+e.flowId;await this.journal.read(n)&&B(409,"flow_exists","Use a new connection request.");let i={actor:r.actor,ownerId:r.ownerId,input:e,app:e.method.kind!=="oauth"?null:e.appId?await this.app(e.appId,e.methodId,r,o):Ua.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}}),state:Qre(32).toString("base64url"),verifier:Qre(32).toString("base64url"),expiresAt:Math.min(Date.now()+6e5,Date.parse(r.expiresAt)),phase:e.method.kind==="oauth"?"authorize":"review"};if(e.method.kind!=="oauth"&&(e.method.kind==="role"&&await this.roles.obtain(e.role.arn,e.role.externalId,e.role.region),i.material=La.parse({format:1,methodId:e.methodId,method:e.method,generation:hU(),appId:null,appGeneration:null,...e.method.kind==="role"?{role:e.role}:{fields:gU(e.method,e.fields)}})),await this.journal.write(n,i),e.method.kind!=="oauth")return this.review(e.flowId,i);e.redirectUri===r.origin+"/oauth/callback"&&await this.broker.relay?.({id:e.flowId,runId:r.id,stateDigest:await ge(i.state),expiresAt:new Date(i.expiresAt).toISOString()});let s=[...new Set([...e.method.config.scopes.default,...e.scopes])];return{kind:"authorize",flowId:e.flowId,url:await this.oauth().authorize(e.method.config,i.app,i.state,i.verifier,e.redirectUri,s)}}async exchange(e,r,o){let n=await this.flow(e.flowId,r),i="oauth_"+e.flowId;if(n.phase==="review")return this.review(e.flowId,n);(n.input.method.kind!=="oauth"||!n.app||!["authorize","received"].includes(n.phase))&&B(409,"connection_uncertain","Check the connection before authorizing it again.");let s=this.oauth(o),a=n.input.method.config,c=new URLSearchParams(e.parameters);(c.getAll("state").length!==1||c.get("state")!==n.state)&&B(400,"invalid_state","Start the connection again.");let u;return n.phase==="received"?u=await s.inspect(a,n.app,n.checkpoint.token,n.checkpoint.response):(n.phase="exchanging",await this.journal.write(i,n),u=await s.exchange(a,n.app,{parameters:c,state:n.state},n.verifier,n.input.redirectUri,[...new Set([...a.scopes.default,...n.input.scopes])],void 0,async(l,d)=>{n.checkpoint={token:l,response:d},n.phase="received",await this.journal.write(i,n)})),n.material=La.parse({format:1,methodId:n.input.methodId,method:n.input.method,generation:hU(),appId:n.input.appId,appGeneration:n.input.appId?n.app.generation:null,oauth:u}),n.phase="review",await this.journal.write(i,n),this.review(e.flowId,n)}async commit(e,r){let o=await this.flow(e.flowId,r),n="oauth_"+e.flowId;if(o.phase==="committed")return{kind:"connected",id:o.content.policy.id};["review","committing"].includes(o.phase)||B(409,"approval_required","Review this connection before saving."),o.content?(R(o.content.policy)!==R(e.approval.policy)||o.content.creationRunId!==r.id)&&B(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await ux(lt(R(o.material)),e.approval,r.id,this.binding,this.keys,await Ou(o.material)),o.phase="committing",await this.journal.write(n,o));let i;try{i=await this.broker.capture(o.input.name,o.content)}catch(s){throw s instanceof Pt&&s.status<500?s:new Fa}return o.phase="committed",await this.journal.write(n,o),{kind:"connected",id:i.id}}async recover(e,r){let o=jx.parse(e);if(o.action!=="commit")return null;let n="oauth_"+o.flowId,i=await this.journal.read(n);if(!i?.content||i.ownerId!==r.ownerId||R(i.actor)!==R(r.actor)||i.content.creationRunId!==r.id||R(i.content.policy)!==R(o.approval.policy)||!["committing","committed"].includes(i.phase))return null;try{await this.broker.capture(i.input.name,i.content)}catch(s){if(s instanceof Pt&&s.status<500)return null;throw new Fa}return i.phase="committed",await this.journal.write(n,i),{kind:"connected",id:i.content.policy.id}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);if(s.method.kind==="token")return Object.fromEntries(Object.entries(s.method.config.outputs).map(([a,c])=>[a,Qd(Ni(s.fields,c))]));if(s.method.kind==="role")return this.roles.obtain(s.role.arn,s.role.externalId,s.role.region);if(await this.broker.state(e.policy.id)&&B(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),s.method.kind!=="oauth")throw new Error("Use an OAuth connection.");return this.oauth(n).outputs(s.method.config,await this.connectionApp(s,r,o),s.oauth)}async refreshed(e,r){let o=La.parse({...e.material,oauth:r}),n=await Ou(o);return n.authorizationDigest!==e.previous.metadata.authorizationDigest&&B(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=o,e.content=await hH(e.previous,lt(R(o)),this.binding,this.keys,n),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),o}async refresh(e,r,o,n,i,s){if(r.method.kind!=="oauth"||r.oauth.expiresAt===null||r.oauth.expiresAt>=Date.now()+6e4)return r;try{await Au(e,{...o,operation:"refresh"},{destination:s})}catch{B(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let a=await this.connectionApp(r,o,n),c=hU(),u=await this.broker.prepare(c,e.policy.id,e.materialRevision),l={operation:u,previous:e,material:r,app:a,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+c,l);try{i.throwIfAborted(),l.phase="dispatched",await this.journal.write("refresh_"+c,l),await this.broker.dispatch(c,u.fence),i.throwIfAborted();let d=await this.oauth(i).refresh(r.method.config,a,r.oauth,async(f,p)=>{l.checkpoint={token:f,response:p},l.phase="received",await this.journal.write("refresh_"+c,l)});return await this.refreshed(l,d)}catch(d){if(l.phase==="prepared"?await this.broker.abort(c,u.fence):await this.broker.uncertain(c,u.fence).catch(()=>{}),d instanceof Pt&&["connection_review","reconnect_required","account_changed"].includes(d.code))throw d;B(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&&o.material.method.kind==="oauth"){let i=await this.oauth().inspect(o.material.method.config,o.app,o.checkpoint.token,o.checkpoint.response);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};function $r(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=yU(HIe(Fs()),"custody",r.id),i=new Pu(yU(n,"client"),o,r,e),s=new Ex(t,o,r,e,new kx(i)),a=new $x(t),c=new qx(o),u=new Ap(r,e,a.connections(),new Pu(yU(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 tne(t,e){let{custody:r,keys:o,binding:n,connections:i}=$r(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:1,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await ge(n),operation:"command",functionDigest:null,operationDigest:await ge(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,kind:u.policy.kind,policyDigest:await ge(u.policy),materialRevision:u.materialRevision,...u.policy.kind==="connection"?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Kx(e,async u=>{let l=s.find(f=>f.policy.id===u.id);if(u.kind==="secret")return lx(l,n,o.encryption);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return lt(d[u.output])})}import{mkdir as KIe}from"node:fs/promises";import{join as one}from"node:path";import{setTimeout as WIe}from"node:timers/promises";import{spawn as qIe}from"node:child_process";import{constants as vU}from"node:fs";import{open as rne,rm as ZIe}from"node:fs/promises";async function nne(t){if(process.platform!=="linux"){let r=await rne(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 ZIe(t,{force:!0})}}let e=await rne(t,vU.O_CREAT|vU.O_WRONLY|vU.O_NOFOLLOW,384);try{let r=qIe("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()}async function gI(t,e){let{custody:r,directory:o,keys:n,binding:i,broker:s,transport:a}=$r(t),c=k.parse(e.id??crypto.randomUUID()),u=one(o,"executors",c);await KIe(u,{recursive:!0,mode:448});let l=await nne(one(u,"process.lock")),d=new AbortController,f=()=>d.abort();process.on("SIGINT",f),process.on("SIGTERM",f);try{let p=new Pu(u,t.identity.origin,i,n),m=await p.read("environment_"+c);if(m){if(await Zd(m),m.manifest.ownerId!==e.ownerId||R(m.manifest.executor)!==R(i))throw new Error("Use the owner and identity originally registered for this executor.")}else{let w=[];for(let b of new Set(e.callers.length?e.callers:[i.principalId])){let _=b===i.principalId?i:(await r.inspectIdentity(b)).binding;await r.trusted(_),w.push(_)}m=await bH({format:1,id:c,origin:t.identity.origin,ownerId:e.ownerId,name:e.name,executor:i,operatorId:i.principalId,driver:e.managed?"managed":"attached",capabilities:["http","command","function","connect","refresh","revoke"],callers:w,isolation:e.isolation,...e.image?{commandImage:e.image}:{},revision:1},n),await p.write("environment_"+c,m)}await t.json("/api/environments/"+c+"/registration",{method:"PUT",body:m}),process.stdout.write(JSON.stringify({environmentId:c,identityId:i.principalId,fingerprint:await ge(i),isolation:m.manifest.isolation,...m.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
131
131
  `);let g=new Ap(i,n,s.connections(),p,a),v=new Wx(m,n,s,p,a,new gx({isolation:m.manifest.isolation,image:m.manifest.commandImage}),g);do{let w=[...await g.reconcile(),...await v.reconcile()];w.length&&process.stderr.write(JSON.stringify({event:"reconciliation_pending",ids:w})+`
@@ -206,6 +206,6 @@ The last two values are base64url-encoded JSON; omit both for metadata-only acce
206
206
  `)}function Rr(t,e){if(!t)throw new Error(e);return t}async function Dae(t=22e5){let e=[],r=0;for await(let o of process.stdin){let n=Buffer.from(o);if(r+=n.length,r>t)throw new Error("The input is too large.");e.push(n)}return Buffer.concat(e)}async function LA(t){return t==="@-"?(await Dae()).toString("utf8"):t.startsWith("@")?await n2(t.slice(1),"utf8"):t}async function Ei(t,e={}){if(!t)return e;let r=await LA(t);try{return JSON.parse(r)}catch{throw new Error("Invalid JSON. Supply JSON text, @FILE, or @-.")}}function hm(t,e,r=86400){if(t===void 0)return e;let o=Number(t);if(!Number.isInteger(o)||o<1||o>r)throw new Error("Choose a time limit between 1 and "+r+" seconds.");return o}async function Ps(t,e){let r=JSON.stringify(t,null,2)+`
207
207
  `;e.values.output?await Jd(e.values.output,r,!!e.values.force):process.stdout.write(r)}async function Pae(t,e,r){if(!t.body)throw new Error("Foundation returned an empty response.");let o=Cae(e),n=r?jze(zze(o),".foundation-"+Mze()):o,i=await Oze(n,"wx",384),s=!1;try{await Nae(Oae.fromWeb(t.body),i.createWriteStream()),r&&await Nze(n,o),s=!0}finally{await i.close().catch(()=>{}),s||await Dze(n,{force:!0})}}async function Rae(t,e){let r=e.trim().split(".");if(r.length!==2||!/^[A-Za-z0-9_-]+$/.test(r[0])||!/^[A-Za-z0-9_-]{43}$/.test(r[1]))throw new Error("Use a sign-in key containing an authentication token and a separate encryption unlock code.");let[o,n]=r,i;try{i=await fetch(t+"/api/session",{headers:{authorization:"Bearer "+o},redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!i.ok)throw new Error("Sign-in failed (HTTP "+i.status+").");let s=tx.parse(await i.json());if(!s.principal)throw new Error("The key was not accepted.");if(!s.wrappedKey)throw new Error("This key does not carry an encryption key. Issue it from a browser that can open secrets.");let a=Vh.parse(await aH(s.wrappedKey,sH(n),s.principal.id).catch(()=>{throw new Error("The encryption key could not be unlocked with this key.")})),c=new Na({origin:t,principalId:s.principal.id,token:o,keys:null,binding:null}),{binding:u}=await c.json("/api/identities/"+s.principal.id+"/binding",{},Ci);await Bh(u,a),await Wh({origin:t,principalId:s.principal.id,token:o,keys:a,binding:u}),pw({principal:{id:s.principal.id,name:s.principal.name},origin:t,identity:Fs(),fingerprint:await ge(u)})}async function Vze(t){let e=Da(t.values.origin);if(t.values.key)return Rae(e,await LA(t.values.key));let r=fe.parse(t.values.name||UA()),o=await rx(),n;try{n=await fetch(e+"/api/auth/devices",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:r,publicKey:o.publicKey}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!n.ok)throw new Error("Sign-in could not start (HTTP "+n.status+").");let i=h.object({id:k,code:h.string(),poll:h.string(),url:h.url(),expiresAt:h.string()}).parse(await n.json());process.stderr.write(`Open ${i.url}
208
208
  and enter the code ${i.code.slice(0,4)}-${i.code.slice(4)} to sign in as yourself.
209
- `);let s=new Date(i.expiresAt).getTime();for(;;){if(Date.now()>=s)throw new Error("The sign-in was not approved in time. Run foundation login again.");await o2(2e3);let a=await fetch(`${e}/api/auth/devices/${i.id}?poll=${encodeURIComponent(i.poll)}`,{redirect:"error",signal:AbortSignal.timeout(3e4)}).catch(()=>null);if(!a)continue;if(a.status===404)throw new Error("The sign-in was not approved in time. Run foundation login again.");if(!a.ok)throw new Error("Sign-in failed (HTTP "+a.status+").");let c=h.object({state:h.string(),sealed:Fo.nullable()}).parse(await a.json());if(c.state!=="approved"||!c.sealed)continue;let u=new TextDecoder().decode(await Ri(c.sealed,o.privateKey,i.id,"device:"+i.id));return Rae(e,u)}}async function Bze(t){let e=Fs(),r=Da(t.values.origin);if(t.values.key)throw new Error("Use foundation login --key to sign in with a key.");let o=fe.parse(t.values.name||UA()),n=await ox(),i;try{i=await fetch(r+"/api/auth/enroll",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:o,publicKey:nx(n.encryption)}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!i.ok)throw new Error("Registration failed (HTTP "+i.status+").");let s=h.object({principal:h.object({id:k,name:fe}),credential:qB,token:h.string()}).parse(await i.json()),a=ix(s.principal.id,n),c={origin:r,principalId:s.principal.id,token:s.token,keys:n,binding:a};await Wh(c),await new Na(c).json("/api/principals/"+s.principal.id+"/binding",{method:"PUT",body:await Bh(a,n)},Ci),pw({principal:s.principal,origin:r,identity:e,fingerprint:await ge(a)})}async function MA(t,e,r){let o=Date.now()+r*1e3;for(;;){let n=await t();if(!["pending","running","queued"].includes(e(n)))return n;if(Date.now()>=o)throw new Error("The operation is still pending. Run the wait command again to continue.");await o2(1500)}}async function Hze(t,e,r){let o=fe.parse(Rr(e.positionals[0],"Supply the secret name."));if(!!e.values.file==!!e.values.stdin)throw new Error("Choose exactly one of --file or --stdin.");let n=e.values.file?await n2(e.values.file):await Dae(1e6);if(n.length>1e6)throw new Error("A secret must be at most 1,000,000 bytes.");let i=null,s;do{let f=new URLSearchParams({kind:"secret",query:o,limit:"200",...i?{after:i}:{}}),p=await t.json("/api/principals/"+r+"/resources?"+f,{},xu(Pi));s=p.items.find(m=>m.kind==="secret"&&m.name===o),i=p.next}while(i&&!s);let{custody:a}=$r(t),c=s?await a.read(s.id):void 0,u=await Promise.all((e.values.for??[]).map(f=>a.environment(k.parse(f)))),l=c&&!e.values.for?c.content.policy:await a.policy(r,"secret",u,{previous:c?.content.policy}),d=await a.save(o,n,l,{previous:c});await Ps(d,e)}async function r2(t,e,r){let o=await $r(t).custody.result(e);await Ps({id:e.id,state:e.state,environmentId:e.environmentId,result:o?.result??null,error:o?.error??e.error},r)}async function qze(t){let e=t.indexOf("--"),r=e<0?[]:t.slice(e+1),o=e<0?t:t.slice(0,e);if(o.length===0||o.includes("--help"))return process.stdout.write(Uze),0;if(o.includes("--version"))return process.stdout.write(Ph.version+`
209
+ `);let s=new Date(i.expiresAt).getTime();for(;;){if(Date.now()>=s)throw new Error("The sign-in was not approved in time. Run foundation login again.");await o2(2e3);let a=await fetch(`${e}/api/auth/devices/${i.id}?poll=${encodeURIComponent(i.poll)}`,{redirect:"error",signal:AbortSignal.timeout(3e4)}).catch(()=>null);if(!a)continue;if(a.status===404)throw new Error("The sign-in was not approved in time. Run foundation login again.");if(a.status>=500)continue;if(!a.ok)throw new Error("Sign-in failed (HTTP "+a.status+").");let c=h.object({state:h.string(),sealed:Fo.nullable()}).parse(await a.json());if(c.state!=="approved"||!c.sealed)continue;let u=new TextDecoder().decode(await Ri(c.sealed,o.privateKey,i.id,"device:"+i.id));return Rae(e,u)}}async function Bze(t){let e=Fs(),r=Da(t.values.origin);if(t.values.key)throw new Error("Use foundation login --key to sign in with a key.");let o=fe.parse(t.values.name||UA()),n=await ox(),i;try{i=await fetch(r+"/api/auth/enroll",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:o,publicKey:nx(n.encryption)}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!i.ok)throw new Error("Registration failed (HTTP "+i.status+").");let s=h.object({principal:h.object({id:k,name:fe}),credential:qB,token:h.string()}).parse(await i.json()),a=ix(s.principal.id,n),c={origin:r,principalId:s.principal.id,token:s.token,keys:n,binding:a};await Wh(c),await new Na(c).json("/api/principals/"+s.principal.id+"/binding",{method:"PUT",body:await Bh(a,n)},Ci),pw({principal:s.principal,origin:r,identity:e,fingerprint:await ge(a)})}async function MA(t,e,r){let o=Date.now()+r*1e3;for(;;){let n=await t();if(!["pending","running","queued"].includes(e(n)))return n;if(Date.now()>=o)throw new Error("The operation is still pending. Run the wait command again to continue.");await o2(1500)}}async function Hze(t,e,r){let o=fe.parse(Rr(e.positionals[0],"Supply the secret name."));if(!!e.values.file==!!e.values.stdin)throw new Error("Choose exactly one of --file or --stdin.");let n=e.values.file?await n2(e.values.file):await Dae(1e6);if(n.length>1e6)throw new Error("A secret must be at most 1,000,000 bytes.");let i=null,s;do{let f=new URLSearchParams({kind:"secret",query:o,limit:"200",...i?{after:i}:{}}),p=await t.json("/api/principals/"+r+"/resources?"+f,{},xu(Pi));s=p.items.find(m=>m.kind==="secret"&&m.name===o),i=p.next}while(i&&!s);let{custody:a}=$r(t),c=s?await a.read(s.id):void 0,u=await Promise.all((e.values.for??[]).map(f=>a.environment(k.parse(f)))),l=c&&!e.values.for?c.content.policy:await a.policy(r,"secret",u,{previous:c?.content.policy}),d=await a.save(o,n,l,{previous:c});await Ps(d,e)}async function r2(t,e,r){let o=await $r(t).custody.result(e);await Ps({id:e.id,state:e.state,environmentId:e.environmentId,result:o?.result??null,error:o?.error??e.error},r)}async function qze(t){let e=t.indexOf("--"),r=e<0?[]:t.slice(e+1),o=e<0?t:t.slice(0,e);if(o.length===0||o.includes("--help"))return process.stdout.write(Uze),0;if(o.includes("--version"))return process.stdout.write(Ph.version+`
210
210
  `),0;let n=o[0],i=Fze(o.slice(1));if(n==="init")return await Bze(i),0;if(n==="login")return await Vze(i),0;if(n==="agent"&&i.positionals[0]==="managed")return ine();let s=new Na(await mx(i.values.origin)),a=await s.session();if(!a.principal)throw new Error("The machine identity is no longer valid.");let c=k.parse(i.values.owner??a.principal.id);if(n==="mcp")return Eae(s);if(n==="status"){let{wrappedKey:u,...l}=a;return await Ps(l,i),0}if(n==="trust"){let{custody:u}=$r(s),l=k.parse(Rr(i.positionals[0],"Supply an identity ID."));if(i.values.fingerprint){let d=await u.trustIdentity(l,i.values.fingerprint);await Ps({identityId:l,fingerprint:d.fingerprint,trusted:!0},i)}else{let d=await u.inspectIdentity(l);await Ps({identityId:l,fingerprint:d.fingerprint,next:"Verify this fingerprint with the identity holder, then repeat with --fingerprint."},i)}return 0}if(n==="agent"){if(i.positionals[0]!=="start")throw new Error("Use foundation agent start.");return gI(s,{id:i.values.id?k.parse(i.values.id):void 0,ownerId:c,name:fe.parse(i.values.name??UA()),callers:(i.values.caller??[]).map(u=>k.parse(u)),isolation:h.enum(["process","container"]).parse(i.values.isolation??"process"),image:i.values.image,managed:i.values.managed,once:i.values.once})}if(n==="app"){let u=await Iae(s,{ownerId:c,name:Rr(i.positionals[0],"Supply an application name."),id:i.values.id,methodId:Rr(i.values.method,"Choose --method ID."),clientId:i.values["client-id"]??"",clientSecret:i.values["client-secret"]===void 0?void 0:await LA(i.values["client-secret"]),fields:await Ei(i.values.fields,{}),environments:i.values.for});return await Ps(u,i),0}if(n==="connect"){let u=t2(s),l=i.positionals[0]??"start",d;if(l==="start")d=await Aae(s,{ownerId:c,environmentId:Rr(i.values.environment,"Choose --environment ID."),methodId:Rr(i.values.method,"Choose --method ID."),name:i.values.name,appId:i.values.app,connectionId:i.values.connection,fields:await Ei(i.values.fields,{}),scopes:await Ei(i.values.scopes,[]),role:i.values.role?await Ei(i.values.role):void 0,environments:i.values.for,redirectUri:i.values["redirect-uri"]});else{let f=k.parse(Rr(i.positionals[1],"Supply a connection request ID."));if(l==="accept")d=await u.accept(f);else if(l==="cancel")d=await u.cancel(f);else if(l==="complete"){let p=await LA(Rr(i.values.parameters,"Supply the authorization response with --parameters."));d=await u.complete(f,p.includes("://")?new URL(p).search.slice(1):p.replace(/^\?/,""))}else if(l==="status"||l==="wait")d=await u.progress(f);else throw new Error("Choose connect start, status, wait, complete, accept, or cancel.")}if(i.values.wait||l==="wait"){let f=Date.now()+hm(i.values.timeout,600)*1e3;for(;(d.kind==="pending"||l==="wait"&&d.kind==="authorize")&&!(Date.now()>=f);)await o2(1e3),d=await u.progress(d.flow.id)}return await Ps(Tae(d),i),["failed","cancelled"].includes(d.kind)?1:0}if(n==="retry"){let u=k.parse(Rr(i.positionals[0],"Supply a saved execution ID."));return await r2(s,await $r(s).custody.resume(u),i),0}if(n==="api"||n==="schema"){let u=n==="schema"?"GET":Rr(i.positionals[0],"Supply an HTTP method.").toUpperCase();if(!["GET","HEAD","POST","PUT","PATCH","DELETE"].includes(u))throw new Error("Choose GET, HEAD, POST, PUT, PATCH, or DELETE.");let l=n==="schema"?"/api/openapi.json":Rr(i.positionals[1],"Supply an API path beginning with /api/.");if(i.values.body&&i.values.upload)throw new Error("Choose --body or --upload.");let d=await s.response(l,{method:u,...i.values.body?{body:await Ei(i.values.body)}:{},...i.values.upload?{raw:await n2(i.values.upload)}:{}});if(i.values.output)await Pae(d,i.values.output,!!i.values.force);else if(u==="HEAD"||d.status===204)pw({status:d.status});else if(d.headers.get("content-type")?.includes("json"))pw(await d.json());else{if(!d.body)throw new Error("Foundation returned an empty response.");await Nae(Oae.fromWeb(d.body),process.stdout)}return 0}if(n==="keep")return await Hze(s,i,c),0;if(n==="read"){let u=k.parse(Rr(i.positionals[0],"Supply the resource ID.")),l=await $r(s).custody.reveal(u);return i.values.output?await Jd(i.values.output,l,!!i.values.force):process.stdout.write(l),0}if(n==="exec"){let u=h.array(iO).max(32).parse(await Ei(i.values.inputs,[]));return PH(await tne(s,u),r)}if(n==="run"){let u=k.parse(Rr(i.values.environment,"Choose an explicit execution environment with --environment ID."));if([i.values.request,i.values.function,!!r.length].filter(Boolean).length!==1)throw new Error("Choose --request, --function, or a command after --.");let d=i.values.function?await s.json("/api/resources/"+k.parse(i.values.function),{},Pi):null;if(d&&d.kind!=="function")throw new Error("Choose a saved function.");let f=i.values.request?{kind:"http",request:await Ei(i.values.request)}:d?.kind==="function"?{kind:"function",definition:d.data,arguments:await Ei(i.values.arguments,{})}:{kind:"command",command:r,timeoutSeconds:hm(i.values.timeout,60,3600),inputs:await Ei(i.values.inputs,[])},p=await $r(s).custody.submit(c,u,Wd.parse(f),{save:h.record(h.string(),fe).parse(await Ei(i.values.save,{}))}),m=i.values.wait?await MA(()=>s.json("/api/executions/"+p.id,{},Nn),g=>g.state,hm(i.values.timeout,3600)):p;return await r2(s,m,i),["failed","cancelled","uncertain"].includes(m.state)?1:0}if(n==="wait"){let u=k.parse(Rr(i.positionals[0],"Supply a run ID.")),l=await MA(()=>s.json("/api/executions/"+u,{},Nn),d=>d.state,hm(i.values.timeout,3600));return await r2(s,l,i),l.state==="succeeded"?0:1}if(n==="join"||n==="request"){if(n==="request"&&i.positionals[0]==="wait"){let d=k.parse(Rr(i.positionals[1],"Supply a request ID.")),f=await MA(()=>s.json("/api/requests/"+d,{},Ld),p=>p.state,hm(i.values.timeout,1800));return await Ps(f,i),f.state==="approved"?0:1}let u=n==="join"?{to:i.values.to,message:i.values.message??UA(),operations:[{method:"POST",path:"/api/relations",body:{subjectId:a.principal.id,relation:"agent",principalId:"$approver"}}]}:await Ei(Rr(i.values.body,"Supply the request as --body JSON.")),l=await s.json("/api/requests",{method:"POST",body:iH.parse(u)},Ld);if(await Ps(l,i),i.values.wait){let d=await MA(()=>s.json("/api/requests/"+l.id,{},Ld),f=>f.state,hm(i.values.timeout,1800));return await Ps(d,{...i,values:{...i.values,force:!0}}),d.state==="approved"?0:1}return 0}if(n==="export"){let u=Rr(i.values.output,"Choose an export file with --output FILE.");return await Pae(await s.response("/api/principals/"+c+"/export"),u,!!i.values.force),pw({path:Cae(u)}),0}throw new Error("Unknown command: "+n+". Run foundation --help.")}try{process.exitCode=await qze(process.argv.slice(2))}catch(t){let e=t instanceof Oa?t.code+": "+t.message:t instanceof h.ZodError?"Check the command inputs against foundation schema.":t instanceof Error?t.message:"The command failed.";process.stderr.write("foundation: "+e+`
211
211
  `),process.exitCode=1}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomato414941/foundation",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Manage Foundation resources and deliver encrypted inputs to commands.",
5
5
  "type": "module",
6
6
  "engines": {