@tomato414941/foundation 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +1 -1
- 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
|
}`,p;try{p=new l(...s,d)(...a)}catch(f){throw new Ce(`this schema (generated code failed to evaluate: ${f.message})`)}return e?.debug&&(p.code=u),p.definite=o.definite,p}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 lu(t,e){return t.definite=!1,ne(t,e)}function ee(t){return`v${t.varCounter++}`}function Ele(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return Yr;let o=r;return o.issues.length===0?o.value:Yr}function Or(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return At(t,e,r,o,n)}catch(u){if(!(u instanceof Ce)||!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,$le(t,e,r,o)}}function $le(t,e,r,o){e.definite=!1;let n=ne(e,r),i=ne(e,Ele),s=ee(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var Ile=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function kle(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&&!Ile.has(a.check))throw new Ce('check with a custom "when" condition');switch(a.check){case"greater_than":Ale(t,e,a,i);break;case"less_than":Tle(t,e,a,i);break;case"multiple_of":Ple(t,e,a,i);break;case"number_format":PF(t,a,i);break;case"min_length":{let c=cu(a.minimum,"min_length"),u=AP(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=cu(a.maximum,"max_length"),u=AP(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=cu(a.length,"length_equals"),u=AP(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 < ${cu(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${cu(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${cu(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=RF(t,e,a,i);break;case"custom":i=zle(t,e,s,i);break;case"bigint_format":Rle(t,a,i);break;case"mime_type":Cle(t,e,a,i);break;case"property":Nle(t,e,a,i);break;case"properties":Ole(t,e,a,i);break;case"overwrite":{let c=ee(e);Dle(t,e,s,i,c),i=c;break}default:throw new Ce(`check type ${a.check}`)}}return i}function AP(t,e,r,o){let n=ne(e,nu),i=ee(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function cu(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Ce(`${e} bound of type ${typeof t}`);return`${t}`}function TF(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Ce("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Ce("comparison check with Invalid Date bound");return ne(t,e)}throw new Ce(`comparison check bound of type ${typeof e}`)}function Ale(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${TF(e,r.value)}) return INVALID;`)}function Tle(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${TF(e,r.value)}) return INVALID;`)}function Ple(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Ce("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ne(e,wm);t.write(`if (${n}(${o}, ${cu(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function PF(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 Ce(`number format ${o}`)}}function Rle(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 Ce(`bigint format ${o}`)}}function Cle(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 Ole(t,e,r,o){if(r.when)throw new Ce('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):Gr(i),a=ee(e);t.write(`const ${a} = ${o}[${s}];`),Or(t,e,n[i],a,!1)}}function Nle(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;At(t,e,r.schema,n)}function Dle(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Ce("overwrite check without a transform function");if(du(i))throw new jo("z.compile: async overwrite transforms are not supported");let s=ne(e,i);t.write(`const ${n} = ${s}(${o});`)}function TP(){throw new hn}function CP(t){this.issues.push(t)}function zle(t,e,r,o){let n=r._zod.def;if(n.fn){if(du(n.fn))throw new jo("z.compile: async .refine() predicates are not supported");let i=lu(e,n.fn),s=ne(e,TP),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(du(r._zod.check))throw new jo("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=lu(e,u=>{let l={value:u,issues:[],addIssue:CP};return i(l)instanceof Promise&&TP(),l.issues.length===0?l.value:Yr}),c=ee(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Ce("custom check without a predicate or check function")}var jle=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 RF(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ne(e,Dm);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ne(e,ub);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ne(e,gb),l=ne(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ne(e,Nm);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ne(e,ib);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ne(e,fb);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ne(e,mb);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,Hw),l=ne(e,r),d=ee(e),p=ee(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${p} = ${u}(${d}, ${l});`),t.write(`if (typeof ${p} === "number") return INVALID;`),s.hostname!==void 0){let h=ne(e,qw);t.write(`if (!${h}(${p}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let h=ne(e,Zw);t.write(`if (!${h}(${p}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let f=ee(e),m=s.normalize?`${p}.href`:`${ne(e,Om)}(${d})`;return t.write(`const ${f} = ${m};`),f}let a=r.fn;if(a){if(du(a))throw new Ce(`async string format ${i}`);let u=ne(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(jle.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 Ce("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(${Gr(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${Gr(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${Gr(u)}) return INVALID;`);break}default:throw new Ce(`string format ${c}`)}return o}function At(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Ce(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=Mle(t,e,r,o,a);break;case"number":c=Ule(t,r,o);break;case"boolean":c=Lle(t,o);break;case"bigint":c=Fle(t,r,o);break;case"symbol":c=Vle(t,o);break;case"undefined":c=Ble(t,o);break;case"null":c=Hle(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=qle(t,o);break;case"nan":c=Zle(t,o);break;case"date":c=Kle(t,o);break;case"object":c=Wle(t,e,r,o,a);break;case"optional":c=Jle(t,e,r,o,a);break;case"nullable":c=Yle(t,e,r,o,a);break;case"array":c=Qle(t,e,r,o,a);break;case"literal":c=ede(t,e,r,o);break;case"enum":c=tde(t,e,r,o);break;case"readonly":{let u=IF(t,e,r,o),l=ee(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":IF(t,e,r,o),c="true";break;case"default":case"prefault":c=rde(t,e,r,o);break;case"nonoptional":c=nde(t,e,r,o);break;case"tuple":c=ode(t,e,r,o);break;case"union":c=ide(t,e,r,o);break;case"intersection":c=cde(t,e,r,o);break;case"record":c=ude(t,e,r,o);break;case"map":c=dde(t,e,r,o);break;case"set":c=fde(t,e,r,o);break;case"file":c=pde(t,o);break;case"template_literal":c=mde(t,e,r,o);break;case"lazy":c=hde(t,e,r,o);break;case"pipe":c=gde(t,e,r,o);break;case"custom":c=yde(t,e,r,o);break;case"transform":c=bde(t,e,r,o);break;case"catch":c=wde(t,e,r,o);break;default:throw new Ce(`schema type ${s}`)}return c===null?null:kle(t,e,r,c)}function Mle(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:RF(t,e,i,o,n)}function Ule(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&&PF(t,{format:o.format},r),r}function Lle(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function Fle(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 Vle(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function Ble(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Hle(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function qle(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function Zle(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function Kle(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function Wle(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):Gr(b),d=b=>typeof b=="symbol"?`[${l(b)}]`:Gr(b),p=s;if(a.includes("__proto__"))throw new Ce('object shape key "__proto__"');let f=new Map;for(let b of u){let _=p[b],E=l(b),k=ee(e);if(t.write(`const ${k} = ${o}[${E}];`),_._zod.optin!==void 0){let O=ee(e);t.write(`let ${O} = (() => {`),t.indented(H=>{let te=Or(H,e,_,k);H.write(`return ${te};`)}),t.write("})();"),_._zod.optout==="optional"?(t.write(`if (${O} === INVALID) {`),t.indented(H=>{H.write(`if (${E} in ${o}) return INVALID;`),H.write(`${O} = undefined;`)}),t.write("}")):t.write(`if (${O} === INVALID) return INVALID;`),f.set(b,O)}else{Xle(_)&&t.write(`if (!(${E} in ${o})) return INVALID;`);let O=Or(t,e,_,k,n);O!==null&&f.set(b,O)}}let m=i.catchall,h="none";if(m){let b=m._zod.def.type;if(b==="never"){let _=a.map(E=>`k !== ${Gr(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?h="passthrough":h="schema"}let y=ee(e),w=u.some(b=>$F(p[b])||PP(p[b]));if(!n){if(h==="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];`),Or(_,e,m,E,!1)}),t.write("}")}return null}if(w){t.write(`const ${y} = {};`);for(let b of u){let _=l(b),E=f.get(b);PP(p[b])?t.write(`if (${_} in ${o}) ${y}[${_}] = ${E};`):$F(p[b])?t.write(`if (${E} !== undefined || ${_} in ${o}) ${y}[${_}] = ${E};`):t.write(`${y}[${_}] = ${E};`)}}else{let b=u.map(_=>`${d(_)}: ${f.get(_)}`).join(", ");t.write(`const ${y} = { ${b} };`)}if(h!=="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;`),h==="passthrough")_.write(`${y}[k] = ${o}[k];`);else{let E=ee(e);_.write(`const ${E} = ${o}[k];`);let k=Or(_,e,m,E);_.write(`${y}[k] = ${k};`)}}),t.write("}")}return y}function Jle(t,e,r,o,n=!0){let i=r._zod.def;if(Gle(r))return At(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=At(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=At(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=At(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Gle(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function Xle(t){return t._zod.optin===void 0&&uu(t)}function uu(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?uu(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?uu(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(uu):!0;case"intersection":return!e.left||!e.right?!0:uu(e.left)&&uu(e.right);case"pipe":return e.in?uu(e.in):!0;default:return!0}}function PP(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function $F(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&cd(t)}function cd(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?cd(e.innerType):!0;case"union":return e.options?e.options.some(cd):!0;case"intersection":return!e.left||!e.right||cd(e.left)||cd(e.right);case"pipe":return e.out?cd(e.out):!0;default:return!0}}function Yle(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=At(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function Qle(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=Or(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function ede(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} !== ${Gr(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 Ce(`literal type ${typeof s}`);return o}function tde(t,e,r,o){let n=r._zod.values;if(!n)throw new Ce("enum schema without enumerated values");let i=ne(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function IF(t,e,r,o){let n=r._zod.def;return At(t,e,n.innerType,o)}function rde(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 At(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}();`),At(t,e,n.innerType,u)}let a=ee(e);if(s){let c=ne(e,s),u=ne(e,Bl);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=At(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=At(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function nde(t,e,r,o){let n=r._zod.def,i=At(t,e,n.innerType,o),s=ee(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function ode(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=kF(i,"optin"),c=kF(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(p=>{p.write(`if (${l} < ${o}.length) {`),p.indented(f=>{let m=ee(e);f.write(`const ${m} = ${o}[${l}];`);let h=Or(f,e,d,m);f.write(`${u}[${l}] = ${h};`)}),p.write("} else {"),p.indented(f=>{if(PP(d)){f.write(`${u}.length = ${l};`);return}let m=ee(e),h=ee(e);f.write(`const ${m} = undefined;`),f.write(`const ${h} = (() => {`),f.indented(y=>{let w=Or(y,e,d,m);y.write(`return ${w};`)}),f.write("})();"),f.write(`if (${h} === INVALID || ${h} === undefined) ${u}.length = ${l};`),f.write(`else ${u}[${l}] = ${h};`)}),p.write("}")}),t.write("}");else{let p=ee(e);t.write(`const ${p} = ${o}[${l}];`);let f=Or(t,e,d,p);t.write(`${u}[${l}] = ${f};`)}}if(s){let l=ee(e),d=ee(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(p=>{p.write(`const ${d} = ${o}[${l}];`);let f=Or(p,e,s,d);p.write(`${u}[${l}] = ${f};`)}),t.write("}")}return u}function kF(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 ide(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return sde(t,e,n,o);if(n.inclusive===!1)throw new Ce("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return At(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=At(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function sde(t,e,r,o){if(r.unionFallback)throw new Ce("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}?.[${Gr(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 Ce("discriminated union option without static discriminator values");for(let p of u){if(a.has(p))throw new Ce(`duplicate discriminator value ${String(p)}`);a.add(p)}let l=Array.from(u,p=>ade(e,n,p)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(p=>{let f=At(p,e,c,o);p.write(`${i} = ${f};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function ade(t,e,r){if(typeof r=="string")return`${e} === ${Gr(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 Ce(`literal discriminator value ${String(r)}`)}function cde(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=Or(t,e,n.left,o),s=Or(t,e,n.right,o),a=ne(e,ed),c=ee(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function ude(t,e,r,o){let n=r._zod.def,i=ne(e,Yn);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 f=[];for(let h of l){if(!(typeof h=="string"||typeof h=="number"||typeof h=="symbol"))throw new Ce(`record key value ${String(h)}`);let y=typeof h=="number"?h.toString():h;if(y==="__proto__")throw new Ce('record key "__proto__"');f.push(y);let w=ne(e,h),b=At(t,e,n.keyType,w),_=ee(e);t.write(`const ${_} = ${o}[${lde(e,y)}];`);let E=Or(t,e,n.valueType,_);t.write(`${s}[${b}] = ${E};`)}let m=ne(e,new Set(f));return t.write(`for (const ${a} in ${o}) {`),t.indented(h=>{h.write(`if (${m}.has(${a})) continue;`),u.mode==="loose"?h.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):h.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let f=n.mode==="loose",m=f_(n.keyType);m.definite===!1&&(e.definite=!1);let h=ne(e,m),y=ne(e,zs),w=ee(e);return AF(t,e,o,a,b=>{b.write(`let ${w} = ${h}(${a});`),b.write(`if (${w} === INVALID && typeof ${a} === "string" && ${y}.test(${a})) ${w} = ${h}(Number(${a}));`),f?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=Or(b,e,n.valueType,_);b.write(`${s}[${w}] = ${E};`)}),s}return AF(t,e,o,a,f=>{f.write(`const ${c} = ${o}[${a}];`);let m=Or(f,e,n.valueType,c);f.write(`${s}[${a}] = ${m};`)},"return INVALID;"),s}function AF(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 lde(t,e){return typeof e=="string"?Gr(e):ne(t,e)}function dde(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=At(c,e,n.keyType,s),l=At(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function fde(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=At(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function pde(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function mde(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 hde(t,e,r,o){let n=r._zod.def,i=lu(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 gde(t,e,r,o){let n=r._zod.def,i=At(t,e,n.in,o);if(n.transform){if(du(n.transform))throw new jo("z.compile: async transforms in pipes are not supported");let s=n.transform,c=lu(e,l=>{let d={value:l,issues:[],addIssue:CP},p=s(l,d);return p instanceof Promise?Yr:d.issues.length===0?p:Yr}),u=ee(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),At(t,e,n.out,u)}else return At(t,e,n.out,i)}function du(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function yde(t,e,r,o){let n=r._zod.def;if(n.fn){if(du(n.fn))throw new jo("z.compile: async custom predicates are not supported");let i=lu(e,n.fn),s=ne(e,TP),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 Ce("custom schema without a predicate function");return o}function vde(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return Yr;let n=o;return n.issues.length===0?n.value:e()}function wde(t,e,r,o){let n=r._zod.def;if(!n.catchValue[bw])throw new Ce("catch with a callback (only a constant catch value compiles)",!1);let i=ee(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=Or(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ne(e,n.innerType),a=lu(e,n.catchValue),c=ne(e,vde);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 bde(t,e,r,o){let n=r._zod.def;if(n.transform){if(du(n.transform))throw new jo("z.compile: async transforms are not supported");let i=n.transform,a=lu(e,u=>{let l={value:u,issues:[],addIssue:CP},d=i(u,l);return d instanceof Promise?Yr:l.issues.length===0?d:Yr}),c=ee(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function p_(t){return t.checks&&(t.checks=[...t.checks]),t}function m_(t,e){return new t(p_({type:"string",...D(e)}))}function OP(t,e){return new t(p_({type:"string",coerce:!0,...D(e)}))}function Zm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...D(e)})}function Km(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...D(e)})}function Wm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...D(e)})}function Jm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(e)})}function Gm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(e)})}function Xm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(e)})}function ud(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...D(e)})}function Ym(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...D(e)})}function Qm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(e)})}function eh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...D(e)})}function th(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(e)})}function rh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...D(e)})}function nh(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...D(e)})}function oh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(e)})}function ih(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(e)})}function sh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(e)})}function h_(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...D(e)})}function ah(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(e)})}function ch(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(e)})}function uh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...D(e)})}function lh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...D(e)})}function dh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...D(e)})}function g_(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...D(e)})}function y_(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...D(e)})}function fh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...D(e)})}var NP={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function ph(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(e)})}function mh(t,e){return new t({type:"string",format:"date",check:"string_format",...D(e)})}function hh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...D(e)})}function gh(t,e){return new t({type:"string",format:"duration",check:"string_format",...D(e)})}function v_(t,e){return new t(p_({type:"number",checks:[],...D(e)}))}function DP(t,e){return new t(p_({type:"number",coerce:!0,checks:[],...D(e)}))}function w_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...D(e)})}function b_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...D(e)})}function __(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...D(e)})}function S_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...D(e)})}function x_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...D(e)})}function E_(t,e){return new t({type:"boolean",...D(e)})}function zP(t,e){return new t({type:"boolean",coerce:!0,...D(e)})}function $_(t,e){return new t({type:"bigint",...D(e)})}function jP(t,e){return new t({type:"bigint",coerce:!0,...D(e)})}function I_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...D(e)})}function k_(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...D(e)})}function A_(t,e){return new t({type:"symbol",...D(e)})}function T_(t,e){return new t({type:"undefined",...D(e)})}function P_(t,e){return new t({type:"null",...D(e)})}function R_(t){return new t({type:"any"})}function C_(t){return new t({type:"unknown"})}function O_(t,e){return new t({type:"never",...D(e)})}function N_(t,e){return new t({type:"void",...D(e)})}function D_(t,e){return new t({type:"date",...D(e)})}function MP(t,e){return new t({type:"date",coerce:!0,...D(e)})}function z_(t,e){return new t({type:"nan",...D(e)})}function Ti(t,e){return new Nw({check:"less_than",...D(e),value:t,inclusive:!1})}function Cn(t,e){return new Nw({check:"less_than",...D(e),value:t,inclusive:!0})}function Pi(t,e){return new Dw({check:"greater_than",...D(e),value:t,inclusive:!1})}function On(t,e){return new Dw({check:"greater_than",...D(e),value:t,inclusive:!0})}function j_(t){return Pi(0,t)}function M_(t){return Ti(0,t)}function U_(t){return Cn(0,t)}function L_(t){return On(0,t)}function wa(t,e){return new WT({check:"multiple_of",...D(e),value:t})}function ba(t,e){return new XT({check:"max_size",...D(e),maximum:t})}function Ri(t,e){return new YT({check:"min_size",...D(e),minimum:t})}function fu(t,e){return new QT({check:"size_equals",...D(e),size:t})}function pu(t,e){return new eP({check:"max_length",...D(e),maximum:t})}function js(t,e){return new tP({check:"min_length",...D(e),minimum:t})}function mu(t,e){return new rP({check:"length_equals",...D(e),length:t})}function ld(t,e){return new nP({check:"string_format",format:"regex",...D(e),pattern:t})}function dd(t){return new oP({check:"string_format",format:"lowercase",...D(t)})}function fd(t){return new iP({check:"string_format",format:"uppercase",...D(t)})}function pd(t,e){return new sP({check:"string_format",format:"includes",...D(e),includes:t})}function md(t,e){return new aP({check:"string_format",format:"starts_with",...D(e),prefix:t})}function hd(t,e){return new cP({check:"string_format",format:"ends_with",...D(e),suffix:t})}function F_(t,e,r){return new uP({check:"property",property:t,schema:e,...D(r)})}function gd(t,e){return new lP({check:"properties",shape:t,...D(e)})}function yd(t,e){return new dP({check:"mime_type",mime:t,...D(e)})}function Mo(t){return new fP({check:"overwrite",tx:t})}function vd(t){return Mo(e=>e.normalize(t))}function wd(){return Mo(t=>t.trim())}function bd(){return Mo(t=>t.toLowerCase())}function _d(){return Mo(t=>t.toUpperCase())}function Sd(){return Mo(t=>JA(t))}function UP(t,e,r){return new t({type:"array",element:e,...D(r)})}function _de(t,e,r){return new t({type:"union",options:e,...D(r)})}function Sde(t,e,r){return new t({type:"union",options:e,inclusive:!1,...D(r)})}function xde(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...D(o)})}function Ede(t,e,r){return new t({type:"intersection",left:e,right:r})}function $de(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,...D(i)})}function Ide(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...D(o)})}function kde(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...D(o)})}function Ade(t,e,r){return new t({type:"set",valueType:e,...D(r)})}function Tde(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...D(r)})}function Pde(t,e,r){return new t({type:"enum",entries:e,...D(r)})}function Rde(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...D(r)})}function V_(t,e){return new t({type:"file",...D(e)})}function Cde(t,e){return new t({type:"transform",transform:e})}function Ode(t,e){return new t({type:"optional",innerType:e})}function Nde(t,e){return new t({type:"nullable",innerType:e})}function Dde(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():Bl(r)}})}function zde(t,e,r){return new t({type:"nonoptional",innerType:e,...D(r)})}function jde(t,e){return new t({type:"success",innerType:e})}function Mde(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:rT(r)})}function Ude(t,e,r){return new t({type:"pipe",in:e,out:r})}function Lde(t,e){return new t({type:"readonly",innerType:e})}function Fde(t,e,r){return new t({type:"template_literal",parts:e,...D(r)})}function Vde(t,e){return new t({type:"lazy",getter:e})}function Bde(t,e){return new t({type:"promise",innerType:e})}function B_(t,e,r){let o=D(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function H_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...D(r)})}function q_(t,e){let r=CF(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Hl(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(Hl(i))}},t(o.value,o)),e);return r}function CF(t,e){let r=new it({check:"custom",...D(e)});return r._zod.check=t,r}function Z_(t){let e=new it({check:"describe"});return e._zod.onattach=[r=>{let o=lr.get(r)??{};lr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function K_(t){let e=new it({check:"meta"});return e._zod.onattach=[r=>{let o=lr.get(r)??{};lr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function W_(t,e){let r=D(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),s=new Set(n),a=t.Codec??nd,c=t.Boolean??td,u=t.String??va,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new a({type:"pipe",in:l,out:d,transform:((f,m)=>{let h=f;return r.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:s.has(h)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:p,continue:!1}),{})}),reverseTransform:((f,m)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return p._zod.bag.truthy=o,p._zod.bag.falsy=n,p._zod.bag.case=r.case??"insensitive",p}function _a(t,e,r,o={}){let n=D(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 yh(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&ur(t,o,r[o]);return t}function Sa(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??lr,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 Wt(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function rt(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let p=s.schema,f=e.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),rt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&yh(s.schema,c),e.io==="input"&&Qr(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 OF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function xa(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${OF(f)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+OF(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 zF(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;zF(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 jF=new Set(["type","properties","required","additionalProperties"]),NF=["oneOf","anyOf"];function DF(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function LP(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!jF.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]??DF(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:LP(a)??{allOf:a};ur(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=DF(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 Hde(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of jF)if(n in t)return;let r=e.filter(n=>NF.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=LP(e);else{let n=r[0],i=NF.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=>LP([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,yh(t,o))}function Ea(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):yh(u,m),yh(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(m.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())zF(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)??[])Hde(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)}yh(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,ur(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:xd(e,"input",t.processors),output:xd(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Qr(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 Qr(o.element,r);if(o.type==="set")return Qr(o.valueType,r);if(o.type==="lazy")return Qr(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 Qr(o.innerType,r);if(o.type==="intersection")return Qr(o.left,r)||Qr(o.right,r);if(o.type==="record"||o.type==="map")return Qr(o.keyType,r)||Qr(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Qr(o.in,r)||Qr(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Qr(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Qr(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Qr(n,r))return!0;return!!(o.rest&&Qr(o.rest,r))}return!1}var FP=(t,e={})=>r=>{let o=Sa({...r,processors:e});return rt(t,o),xa(o,t),Ea(o,t)},xd=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Sa({...n??{},target:i,io:e,processors:r});return rt(t,s),xa(s,t),Ea(s,t)};var Ed=(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)},MF=(t,e)=>{Ed(t,"minimum",e),$d(t,"maximum",e)},VF=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},BF=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},HF=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},qF=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},UF=(t,e)=>Ed(t,"minimum",e.minimum),LF=(t,e)=>$d(t,"maximum",e.maximum),FF=t=>(e,r)=>{qF(e,r.format);let[o,n]=t[r.format];Ed(e,"minimum",o),$d(e,"maximum",n)},qde={greater_than:(t,e)=>Ed(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>$d(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>VF(t,e.value),number_format:FF(_m),bigint_format:FF(Sm),min_length:UF,max_length:LF,length_equals:(t,e)=>MF(t,e.length),min_size:UF,max_size:LF,size_equals:(t,e)=>MF(t,e.size),string_format:(t,e)=>{qF(t,e.format),e.pattern&&BF(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)=>HF(t,e.mime)};function Jt(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)qde[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Ed(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Ed(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&&VF(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&HF(e,n.mime);for(let i of n.patterns??[])BF(e,i);return e}var Zde={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Kde=new Map([[ab,AT],[zm,TT]]),ZF=t=>Kde.get(t)??t,HP=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Jt(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=Zde[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(ZF);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},qP=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Jt(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let w of a)Number.isFinite(w)&&w!==0?m.add(Math.abs(w)):Wt(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...y]=m;h!==void 0&&(n.multipleOf=h),y.length&&(n.allOf=[...n.allOf??[],...y.map(w=>({multipleOf:w}))])}},ZP=(t,e,r,o)=>{r.type="boolean"},KP=(t,e,r,o)=>{Wt(t,e,r,o,"BigInt cannot be represented in JSON Schema")},WP=(t,e,r,o)=>{Wt(t,e,r,o,"Symbols cannot be represented in JSON Schema")},JP=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},GP=(t,e,r,o)=>{Wt(t,e,r,o,"Undefined cannot be represented in JSON Schema")},XP=(t,e,r,o)=>{Wt(t,e,r,o,"Void cannot be represented in JSON Schema")},YP=(t,e,r,o)=>{r.not={}},QP=(t,e,r,o)=>{},eR=(t,e,r,o)=>{},tR=(t,e,r,o)=>{Wt(t,e,r,o,"Date cannot be represented in JSON Schema")},rR=(t,e,r,o)=>{let n=t._zod.def,i=Ul(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},nR=(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(Wt(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Wt(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},oR=(t,e,r,o)=>{Wt(t,e,r,o,"NaN cannot be represented in JSON Schema")},iR=(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},sR=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Jt(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})))},aR=(t,e,r,o)=>{r.type="boolean"},cR=(t,e,r,o)=>{Wt(t,e,r,o,"Custom types cannot be represented in JSON Schema")},uR=(t,e,r,o)=>{Wt(t,e,r,o,"Function types cannot be represented in JSON Schema")},lR=(t,e,r,o)=>{Wt(t,e,r,o,"Transforms cannot be represented in JSON Schema")},dR=(t,e,r,o)=>{Wt(t,e,r,o,"Map cannot be represented in JSON Schema")},fR=(t,e,r,o)=>{Wt(t,e,r,o,"Set cannot be represented in JSON Schema")},pR=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Jt(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=rt(i.element,e,{...o,path:[...o.path,"items"]})};function vh(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?vh(e.out):e.type==="catch"?vh(e.innerType):t._zod.optin}var mR=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Wt(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)ur(n.properties,u,rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?vh(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},G_=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},hR=(t,e,r,o)=>{let n=t._zod.def,i=rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},gR=(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((h,y)=>rt(h,e,{...o,path:[...o.path,s,y]})),u=i.rest?rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let h=i.items[l-1];if(!(e.io==="input"?vh(h)!==void 0:h._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=Jt(t);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function VP(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 h=VP(t,m,r);return h===m?e:h}for(let m of["anyOf","oneOf"]){let h=e[m];if(!Array.isArray(h))continue;let y=h.map(w=>VP(t,w,r));y.some((w,b)=>w!==h[b])&&(e={...e,[m]:y})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?zs:Tm).source)),f}var BP=new WeakMap;function Wde(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 BP.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=VP(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 yR=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Jt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)ur(n.patternProperties,ZF(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=BP.get(e);l||(l=[],BP.set(e,l),e.deferred.push(()=>Wde(e))),l.push(t)}n.additionalProperties=rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&vh(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))}},vR=(t,e,r,o)=>{let n=t._zod.def,i=rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},wR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},bR=Symbol();function KF(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Wt(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),bR):JSON.parse(s)}var _R=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=KF(n.defaultValue,t,e,r,o);s!==bR&&(r.default=s)},SR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=KF(n.defaultValue,t,e,r,o);s!==bR&&(r._prefault=s)},xR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Wt(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},ER=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;rt(s,e,o);let a=e.seen.get(t);a.ref=s},$R=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},IR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},X_=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},kR=(t,e,r,o)=>{let n=t._zod.innerType;rt(n,e,o);let i=e.seen.get(t);i.ref=n},J_={string:HP,number:qP,boolean:ZP,bigint:KP,symbol:WP,null:JP,undefined:GP,void:XP,never:YP,any:QP,unknown:eR,date:tR,enum:rR,literal:nR,nan:oR,template_literal:iR,file:sR,success:aR,custom:cR,function:uR,transform:lR,map:dR,set:fR,array:pR,object:mR,union:G_,intersection:hR,tuple:gR,record:yR,nullable:vR,nonoptional:wR,default:_R,prefault:SR,catch:xR,pipe:ER,readonly:$R,promise:IR,optional:X_,lazy:kR};function hu(t,e){if("_idmap"in t){let o=t,n=Sa({...e,processors:J_}),i={};for(let c of o._idmap.entries()){let[u,l]=c;rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;xa(n,l),ur(s,u,Ea(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=Sa({...e,processors:J_});return rt(t,r),xa(r,t),Ea(r,t)}var Y_=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=Sa({processors:J_,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,xa(this.ctx,e);let o=Ea(this.ctx,e),{"~standard":n,...i}=o;return i}};var WF={};var Od={};vt(Od,{ZodAny:()=>ZR,ZodArray:()=>GR,ZodBase64:()=>yS,ZodBase64URL:()=>vS,ZodBigInt:()=>Rd,ZodBigIntFormat:()=>_S,ZodBoolean:()=>Pd,ZodCIDRv4:()=>hS,ZodCIDRv6:()=>gS,ZodCUID:()=>cS,ZodCUID2:()=>uS,ZodCatch:()=>hC,ZodCodec:()=>kh,ZodCreditCard:()=>FR,ZodCustom:()=>Ah,ZodCustomStringFormat:()=>yu,ZodDate:()=>Sh,ZodDefault:()=>uC,ZodDiscriminatedUnion:()=>YR,ZodE164:()=>wS,ZodEmail:()=>oS,ZodEmoji:()=>sS,ZodEnum:()=>kd,ZodExactOptional:()=>ES,ZodFile:()=>iC,ZodFunction:()=>$C,ZodGUID:()=>iS,ZodIBAN:()=>VR,ZodIPv4:()=>pS,ZodIPv6:()=>mS,ZodISODate:()=>Ia,ZodISODateTime:()=>$a,ZodISODuration:()=>Aa,ZodISOTime:()=>ka,ZodInstanceOf:()=>AC,ZodIntersection:()=>QR,ZodJWT:()=>bS,ZodKSUID:()=>fS,ZodLazy:()=>SC,ZodLiteral:()=>oC,ZodMAC:()=>LR,ZodMap:()=>rC,ZodNaN:()=>yC,ZodNanoID:()=>aS,ZodNever:()=>WR,ZodNonOptional:()=>$S,ZodNull:()=>qR,ZodNullable:()=>cC,ZodNumber:()=>Td,ZodNumberFormat:()=>vu,ZodObject:()=>xh,ZodOptional:()=>wu,ZodPipe:()=>Ih,ZodPrefault:()=>dC,ZodPreprocess:()=>vC,ZodPromise:()=>EC,ZodReadonly:()=>wC,ZodRecord:()=>Id,ZodSet:()=>nC,ZodString:()=>Ad,ZodStringFormat:()=>at,ZodSuccess:()=>mC,ZodSymbol:()=>BR,ZodTemplateLiteral:()=>_C,ZodTransform:()=>sC,ZodTuple:()=>eC,ZodType:()=>we,ZodULID:()=>lS,ZodURL:()=>bh,ZodUUID:()=>Ci,ZodUndefined:()=>HR,ZodUnion:()=>Eh,ZodUnknown:()=>KR,ZodVoid:()=>JR,ZodXID:()=>dS,ZodXor:()=>XR,_ZodString:()=>nS,_default:()=>lC,_function:()=>rB,any:()=>jV,array:()=>Te,base64:()=>yV,base64url:()=>vV,bigint:()=>CV,boolean:()=>Lt,catch:()=>gC,check:()=>nB,cidrv4:()=>hV,cidrv6:()=>gV,codec:()=>YV,creditCard:()=>bV,cuid:()=>aV,cuid2:()=>cV,currencyCode:()=>IV,custom:()=>IS,date:()=>UV,describe:()=>oB,discriminatedUnion:()=>$h,e164:()=>wV,email:()=>XF,emoji:()=>iV,enum:()=>fr,exactOptional:()=>aC,file:()=>WV,float32:()=>AV,float64:()=>TV,function:()=>rB,guid:()=>YF,hash:()=>kV,hex:()=>$V,hostname:()=>EV,httpUrl:()=>oV,iban:()=>_V,instanceof:()=>sB,int:()=>tS,int32:()=>PV,int64:()=>OV,intersection:()=>Cd,invertCodec:()=>QV,ipv4:()=>fV,ipv6:()=>mV,json:()=>cB,jwt:()=>SV,keyof:()=>LV,ksuid:()=>dV,lazy:()=>xC,literal:()=>G,looseObject:()=>dr,looseRecord:()=>HV,mac:()=>pV,map:()=>qV,meta:()=>iB,nan:()=>XV,nanoid:()=>sV,nativeEnum:()=>KV,never:()=>SS,nonoptional:()=>pC,null:()=>_h,nullable:()=>wh,nullish:()=>JV,number:()=>Ke,object:()=>B,optional:()=>st,partialRecord:()=>BV,pipe:()=>rS,prefault:()=>fC,preprocess:()=>Th,promise:()=>tB,readonly:()=>bC,record:()=>ct,refine:()=>IC,set:()=>ZV,strictObject:()=>FV,string:()=>I,stringFormat:()=>xV,stringbool:()=>aB,success:()=>GV,superRefine:()=>kC,symbol:()=>DV,templateLiteral:()=>eB,transform:()=>xS,tuple:()=>tC,uint32:()=>RV,uint64:()=>NV,ulid:()=>uV,undefined:()=>zV,union:()=>nt,unknown:()=>dt,url:()=>nV,uuid:()=>QF,uuidv4:()=>eV,uuidv6:()=>tV,uuidv7:()=>rV,void:()=>MV,xid:()=>lV,xor:()=>VV});var Q_={};vt(Q_,{endsWith:()=>hd,gt:()=>Pi,gte:()=>On,includes:()=>pd,length:()=>mu,lowercase:()=>dd,lt:()=>Ti,lte:()=>Cn,maxLength:()=>pu,maxSize:()=>ba,mime:()=>yd,minLength:()=>js,minSize:()=>Ri,multipleOf:()=>wa,negative:()=>M_,nonnegative:()=>L_,nonpositive:()=>U_,normalize:()=>vd,overwrite:()=>Mo,positive:()=>j_,properties:()=>gd,property:()=>F_,regex:()=>ld,size:()=>fu,slugify:()=>Sd,startsWith:()=>md,toLowerCase:()=>bd,toUpperCase:()=>_d,trim:()=>wd,uppercase:()=>fd});var JF=new WeakSet([Object.prototype,Error.prototype]);function eS(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 GF=(t,e)=>{cT.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);JF.has(r)||(JF.add(r),eS(r,"format",o=>n=>km(o,n)),eS(r,"flatten",o=>n=>Im(o,n)),eS(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Ll,2)}),eS(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Ll,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Gde=S("ZodError",GF),yn=S("ZodError",GF,void 0,{Parent:Error});var AR=ql(yn),TR=Zl(yn),PR=Kl(yn),RR=Jl(yn),CR=Sw(yn),OR=xw(yn),NR=Ew(yn),DR=$w(yn),zR=Iw(yn),jR=kw(yn),MR=Aw(yn),UR=Tw(yn);function Yde(){Qt.localeError||Nt(s_())}function gu(){Qt.memoizer||Nt({memoizer:Hm()})}var we=S("ZodType",(t,e)=>(Yde(),ae.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(A.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 Ze(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(IC(t,e))},superRefine(t,e){return this.check(kC(t,e))},overwrite(t){return this.check(Mo(t))},optional(){return st(this)},exactOptional(){return aC(this)},nullable(){return wh(this)},nullish(){return st(wh(this))},nonoptional(t){return pC(this,t)},array(){return Te(this)},or(t){return nt([this,t])},and(t){return Cd(this,t)},transform(t){return rS(this,xS(t))},default(t){return lC(this,t)},prefault(t){return fC(this,t)},catch(t){return gC(this,t)},pipe(t){return rS(this,t)},readonly(){return bC(this)},describe(t){let e=this.clone();return lr.add(e,{description:t}),e},meta(...t){if(t.length===0)return lr.get(this);let e=this.clone();return lr.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 A.hide(this,"~standard",{...Lw(this),jsonSchema:{input:xd(this,"input"),output:xd(this,"output")}})},set"~standard"(t){A.own(this,"~standard",t)},parse:function t(e,r){return AR(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await TR(this,e,r,{callee:t})},safeParse(t,e){return PR(this,t,e)},async safeParseAsync(t,e){return RR(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){A.own(this,"spa",t)},validate(t,e){return Xl(this,t,e)},validateAsync(t,e){return Yl(this,t,e)},encode:function t(e,r){return CR(this,e,r,{callee:t})},decode:function t(e,r){return OR(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await NR(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await DR(this,e,r,{callee:t})},safeEncode(t,e){return zR(this,t,e)},safeDecode(t,e){return jR(this,t,e)},async safeEncodeAsync(t,e){return MR(this,t,e)},async safeDecodeAsync(t,e){return UR(this,t,e)},toJSONSchema(t){return FP(this,{})(t)},get description(){return lr.get(this)?.description},get _def(){return this._zod.def}}),nS=S("_ZodString",(t,e)=>{va.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HP(t,r,o,n)},A.derived({format:t=>Jt(t).format??null,minLength:t=>Jt(t).minimum??null,maxLength:t=>Jt(t).maximum??null},{regex(...t){return this.check(ld(...t))},includes(...t){return this.check(pd(...t))},startsWith(...t){return this.check(md(...t))},endsWith(...t){return this.check(hd(...t))},min(...t){return this.check(js(...t))},max(...t){return this.check(pu(...t))},length(...t){return this.check(mu(...t))},nonempty(...t){return this.check(js(1,...t))},lowercase(t){return this.check(dd(t))},uppercase(t){return this.check(fd(t))},trim(){return this.check(wd())},normalize(...t){return this.check(vd(...t))},toLowerCase(){return this.check(bd())},toUpperCase(){return this.check(_d())},slugify(){return this.check(Sd())}})),Ad=S("ZodString",(t,e)=>{va.init(t,e),nS.init(t,e)},{email(t){return this.check(Zm(oS,t))},url(t){return this.check(ud(bh,t))},jwt(t){return this.check(fh(bS,t))},emoji(t){return this.check(Ym(sS,t))},guid(t){return this.check(Km(iS,t))},uuid(t){return this.check(Wm(Ci,t))},uuidv4(t){return this.check(Jm(Ci,t))},uuidv6(t){return this.check(Gm(Ci,t))},uuidv7(t){return this.check(Xm(Ci,t))},nanoid(t){return this.check(Qm(aS,t))},cuid(t){return this.check(eh(cS,t))},cuid2(t){return this.check(th(uS,t))},ulid(t){return this.check(rh(lS,t))},base64(t){return this.check(uh(yS,t))},base64url(t){return this.check(lh(vS,t))},xid(t){return this.check(nh(dS,t))},ksuid(t){return this.check(oh(fS,t))},ipv4(t){return this.check(ih(pS,t))},ipv6(t){return this.check(sh(mS,t))},cidrv4(t){return this.check(ah(hS,t))},cidrv6(t){return this.check(ch(gS,t))},e164(t){return this.check(dh(wS,t))},datetime(t){return this.check(ph($a,t))},date(t){return this.check(mh(Ia,t))},time(t){return this.check(hh(ka,t))},duration(t){return this.check(gh(Aa,t))}});function I(t){return m_(Ad,t)}var at=S("ZodStringFormat",(t,e)=>{Ge.init(t,e),nS.init(t,e)}),$a=S("ZodISODateTime",(t,e)=>{yP.init(t,e),at.init(t,e)}),Ia=S("ZodISODate",(t,e)=>{vP.init(t,e),at.init(t,e)}),ka=S("ZodISOTime",(t,e)=>{wP.init(t,e),at.init(t,e)}),Aa=S("ZodISODuration",(t,e)=>{bP.init(t,e),at.init(t,e)}),oS=S("ZodEmail",(t,e)=>{Bw.init(t,e),at.init(t,e)});function XF(t){return Zm(oS,t)}var iS=S("ZodGUID",(t,e)=>{Fw.init(t,e),at.init(t,e)});function YF(t){return Km(iS,t)}var Ci=S("ZodUUID",(t,e)=>{Vw.init(t,e),at.init(t,e)});function QF(t){return Wm(Ci,t)}function eV(t){return Jm(Ci,t)}function tV(t){return Gm(Ci,t)}function rV(t){return Xm(Ci,t)}var bh=S("ZodURL",(t,e)=>{Kw.init(t,e),at.init(t,e)});function nV(t){return ud(bh,t)}function oV(t){return ud(bh,{protocol:Am,hostname:RT,...A.normalizeParams(t)})}var sS=S("ZodEmoji",(t,e)=>{Ww.init(t,e),at.init(t,e)});function iV(t){return Ym(sS,t)}var aS=S("ZodNanoID",(t,e)=>{Jw.init(t,e),at.init(t,e)});function sV(t){return Qm(aS,t)}var cS=S("ZodCUID",(t,e)=>{Gw.init(t,e),at.init(t,e)});function aV(t){return eh(cS,t)}var uS=S("ZodCUID2",(t,e)=>{Xw.init(t,e),at.init(t,e)});function cV(t){return th(uS,t)}var lS=S("ZodULID",(t,e)=>{Yw.init(t,e),at.init(t,e)});function uV(t){return rh(lS,t)}var dS=S("ZodXID",(t,e)=>{Qw.init(t,e),at.init(t,e)});function lV(t){return nh(dS,t)}var fS=S("ZodKSUID",(t,e)=>{eb.init(t,e),at.init(t,e)});function dV(t){return oh(fS,t)}var pS=S("ZodIPv4",(t,e)=>{tb.init(t,e),at.init(t,e)});function fV(t){return ih(pS,t)}var LR=S("ZodMAC",(t,e)=>{nb.init(t,e),at.init(t,e)});function pV(t){return h_(LR,t)}var mS=S("ZodIPv6",(t,e)=>{rb.init(t,e),at.init(t,e)});function mV(t){return sh(mS,t)}var hS=S("ZodCIDRv4",(t,e)=>{ob.init(t,e),at.init(t,e)});function hV(t){return ah(hS,t)}var gS=S("ZodCIDRv6",(t,e)=>{sb.init(t,e),at.init(t,e)});function gV(t){return ch(gS,t)}var yS=S("ZodBase64",(t,e)=>{cb.init(t,e),at.init(t,e)});function yV(t){return uh(yS,t)}var vS=S("ZodBase64URL",(t,e)=>{lb.init(t,e),at.init(t,e)});function vV(t){return lh(vS,t)}var wS=S("ZodE164",(t,e)=>{db.init(t,e),at.init(t,e)});function wV(t){return dh(wS,t)}var FR=S("ZodCreditCard",(t,e)=>{pb.init(t,e),at.init(t,e)});function bV(t){return g_(FR,t)}var VR=S("ZodIBAN",(t,e)=>{hb.init(t,e),at.init(t,e)});function _V(t){return y_(VR,t)}var bS=S("ZodJWT",(t,e)=>{yb.init(t,e),at.init(t,e)});function SV(t){return fh(bS,t)}var yu=S("ZodCustomStringFormat",(t,e)=>{vb.init(t,e),at.init(t,e)});function xV(t,e,r={}){return _a(yu,t,e,r)}function EV(t){return _a(yu,"hostname",PT,t)}function $V(t){return _a(yu,"hex",qT,t)}function IV(t){return _a(yu,"currency_code",OT,t)}function kV(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Rn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return _a(yu,o,n,e)}var Td=S("ZodNumber",(t,e)=>{jm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qP(t,r,o,n),t.isFinite=!0},A.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Jt(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Jt(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Jt(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Jt(t).format??null},{gt(t,e){return this.check(Pi(t,e))},gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},lt(t,e){return this.check(Ti(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},int(t){return this.check(tS(t))},safe(t){return this.check(tS(t))},positive(t){return this.check(Pi(0,t))},nonnegative(t){return this.check(On(0,t))},negative(t){return this.check(Ti(0,t))},nonpositive(t){return this.check(Cn(0,t))},multipleOf(t,e){return this.check(wa(t,e))},step(t,e){return this.check(wa(t,e))},finite(){return this}}));function Ke(t){return v_(Td,t)}var vu=S("ZodNumberFormat",(t,e)=>{wb.init(t,e),Td.init(t,e)});function tS(t){return w_(vu,t)}function AV(t){return b_(vu,t)}function TV(t){return __(vu,t)}function PV(t){return S_(vu,t)}function RV(t){return x_(vu,t)}var Pd=S("ZodBoolean",(t,e)=>{td.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ZP(t,r,o,n)});function Lt(t){return E_(Pd,t)}var Rd=S("ZodBigInt",(t,e)=>{Mm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>KP(t,r,o,n)},A.derived({minValue:t=>Jt(t).minimum??null,maxValue:t=>Jt(t).maximum??null,format:t=>Jt(t).format??null},{gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},gt(t,e){return this.check(Pi(t,e))},lt(t,e){return this.check(Ti(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},positive(t){return this.check(Pi(BigInt(0),t))},negative(t){return this.check(Ti(BigInt(0),t))},nonpositive(t){return this.check(Cn(BigInt(0),t))},nonnegative(t){return this.check(On(BigInt(0),t))},multipleOf(t,e){return this.check(wa(t,e))}}));function CV(t){return $_(Rd,t)}var _S=S("ZodBigIntFormat",(t,e)=>{bb.init(t,e),Rd.init(t,e)});function OV(t){return I_(_S,t)}function NV(t){return k_(_S,t)}var BR=S("ZodSymbol",(t,e)=>{_b.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WP(t,r,o,n)});function DV(t){return A_(BR,t)}var HR=S("ZodUndefined",(t,e)=>{Sb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GP(t,r,o,n)});function zV(t){return T_(HR,t)}var qR=S("ZodNull",(t,e)=>{xb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JP(t,r,o,n)});function _h(t){return P_(qR,t)}var ZR=S("ZodAny",(t,e)=>{Eb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QP(t,r,o,n)});function jV(){return R_(ZR)}var KR=S("ZodUnknown",(t,e)=>{$b.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eR(t,r,o,n)});function dt(){return C_(KR)}var WR=S("ZodNever",(t,e)=>{Ib.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YP(t,r,o,n)});function SS(t){return O_(WR,t)}var JR=S("ZodVoid",(t,e)=>{kb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XP(t,r,o,n)});function MV(t){return N_(JR,t)}var Sh=S("ZodDate",(t,e)=>{Ab.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tR(t,r,o,n),t.min=(r,o)=>t.check(On(r,o)),t.max=(r,o)=>t.check(Cn(r,o))},A.derived({minDate:t=>{let{minimum:e}=Jt(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Jt(t);return e?new Date(e):null}},{}));function UV(t){return D_(Sh,t)}var GR=S("ZodArray",(t,e)=>{gu(),Tb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pR(t,r,o,n),t.element=e.element},{min(t,e){return this.check(js(t,e))},nonempty(t){return this.check(js(1,t))},max(t,e){return this.check(pu(t,e))},length(t,e){return this.check(mu(t,e))},unwrap(){return this.element}});function Te(t,e){return UP(GR,t,e)}function LV(t){let e=t._zod.def.shape;return fr(Object.keys(e))}var xh=S("ZodObject",(t,e)=>{gu(),_P.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mR(t,r,o,n),A.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return fr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(A.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(A.mergeDefs(this._zod.def,{catchall:dt()}))},loose(){return this.clone(A.mergeDefs(this._zod.def,{catchall:dt()}))},strict(){return this.clone(A.mergeDefs(this._zod.def,{catchall:SS()}))},strip(){return this.clone(A.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return A.extend(this,t)},safeExtend(t){return A.safeExtend(this,t)},merge(t){return A.merge(this,t)},pick(t){return A.pick(this,t)},omit(t){return A.omit(this,t)},partial(...t){return A.partial(wu,this,t[0])},exactPartial(...t){return A.partial(ES,this,t[0],"exactPartial")},required(...t){return A.required($S,this,t[0])}});function B(t,e){let r={type:"object",shape:t??{},...A.normalizeParams(e)};return new xh(r)}function FV(t,e){return new xh({type:"object",shape:t,catchall:SS(),...A.normalizeParams(e)})}function dr(t,e){return new xh({type:"object",shape:t,catchall:dt(),...A.normalizeParams(e)})}var Eh=S("ZodUnion",(t,e)=>{rd.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.options=e.options});function nt(t,e){return new Eh({type:"union",options:t,...A.normalizeParams(e)})}var XR=S("ZodXor",(t,e)=>{Eh.init(t,e),Rb.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.options=e.options});function VV(t,e){return new XR({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var YR=S("ZodDiscriminatedUnion",(t,e)=>{Eh.init(t,e),Cb.init(t,e)});function $h(t,e,r){return new YR({type:"union",options:e,discriminator:t,...A.normalizeParams(r)})}var QR=S("ZodIntersection",(t,e)=>{Ob.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hR(t,r,o,n)});function Cd(t,e){return new QR({type:"intersection",left:t,right:e})}var eC=S("ZodTuple",(t,e)=>{gu(),Um.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gR(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 wu({type:"optional",innerType:e}))})}});function tC(t,e,r){let o=e instanceof ae,n=o?r:e,i=o?e:null;return new eC({type:"tuple",items:t,rest:i,...A.normalizeParams(n)})}var Id=S("ZodRecord",(t,e)=>{gu(),Nb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function ct(t,e,r){return!e||!e._zod?new Id({type:"record",keyType:I(),valueType:t,...A.normalizeParams(e)}):new Id({type:"record",keyType:t,valueType:e,...A.normalizeParams(r)})}function BV(t,e,r){return new Id({type:"record",keyType:t,valueType:e,...A.normalizeParams(r),partial:!0})}function HV(t,e,r){return new Id({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(r)})}var rC=S("ZodMap",(t,e)=>{gu(),Db.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ri(...r)),t.nonempty=r=>t.check(Ri(1,r)),t.max=(...r)=>t.check(ba(...r)),t.size=(...r)=>t.check(fu(...r))});function qV(t,e,r){return new rC({type:"map",keyType:t,valueType:e,...A.normalizeParams(r)})}var nC=S("ZodSet",(t,e)=>{gu(),zb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fR(t,r,o,n),t.min=(...r)=>t.check(Ri(...r)),t.nonempty=r=>t.check(Ri(1,r)),t.max=(...r)=>t.check(ba(...r)),t.size=(...r)=>t.check(fu(...r))});function ZV(t,e){return new nC({type:"set",valueType:t,...A.normalizeParams(e)})}var kd=S("ZodEnum",(t,e)=>{jb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(o,n,i)=>rR(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 kd({...e,checks:[],...A.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 kd({...e,checks:[],...A.normalizeParams(n),entries:i})}});function fr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new kd({type:"enum",entries:r,...A.normalizeParams(e)})}function KV(t,e){return new kd({type:"enum",entries:t,...A.normalizeParams(e)})}var oC=S("ZodLiteral",(t,e)=>{Mb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nR(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 oC({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var iC=S("ZodFile",(t,e)=>{Ub.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sR(t,r,o,n),t.min=(r,o)=>t.check(Ri(r,o)),t.max=(r,o)=>t.check(ba(r,o)),t.mime=(r,o)=>t.check(yd(Array.isArray(r)?r:[r],o))});function WV(t){return V_(iC,t)}var sC=S("ZodTransform",(t,e)=>{gu(),Lb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lR(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new ya(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A.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(A.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 xS(t){return new sC({type:"transform",transform:t})}var wu=S("ZodOptional",(t,e)=>{Lm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>X_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function st(t){return new wu({type:"optional",innerType:t})}var ES=S("ZodExactOptional",(t,e)=>{Fb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>X_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function aC(t){return new ES({type:"optional",innerType:t})}var cC=S("ZodNullable",(t,e)=>{Vb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wh(t){return new cC({type:"nullable",innerType:t})}function JV(t){return st(wh(t))}var uC=S("ZodDefault",(t,e)=>{Bb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function lC(t,e){return new uC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var dC=S("ZodPrefault",(t,e)=>{Hb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function fC(t,e){return new dC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var $S=S("ZodNonOptional",(t,e)=>{qb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pC(t,e){return new $S({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var mC=S("ZodSuccess",(t,e)=>{Zb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function GV(t){return new mC({type:"success",innerType:t})}var hC=S("ZodCatch",(t,e)=>{Kb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function gC(t,e){return new hC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:A.constantCatch(e)})}var yC=S("ZodNaN",(t,e)=>{Wb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oR(t,r,o,n)});function XV(t){return z_(yC,t)}var Ih=S("ZodPipe",(t,e)=>{Fm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ER(t,r,o,n),t.in=e.in,t.out=e.out});function rS(t,e){return new Ih({type:"pipe",in:t,out:e})}var kh=S("ZodCodec",(t,e)=>{Ih.init(t,e),nd.init(t,e)});function YV(t,e,r){return new kh({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function QV(t){let e=t._zod.def;return new kh({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var vC=S("ZodPreprocess",(t,e)=>{Ih.init(t,e),xP.init(t,e)}),wC=S("ZodReadonly",(t,e)=>{Jb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function bC(t){return new wC({type:"readonly",innerType:t})}var _C=S("ZodTemplateLiteral",(t,e)=>{Gb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iR(t,r,o,n)});function eB(t,e){return new _C({type:"template_literal",parts:t,...A.normalizeParams(e)})}var SC=S("ZodLazy",(t,e)=>{od.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kR(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function xC(t){return new SC({type:"lazy",getter:t})}var EC=S("ZodPromise",(t,e)=>{Yb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function tB(t){return new EC({type:"promise",innerType:t})}var $C=S("ZodFunction",(t,e)=>{Xb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uR(t,r,o,n)});function rB(t){return new $C({type:"function",input:Array.isArray(t?.input)?tC(t?.input):t?.input??Te(dt()),output:t?.output??dt()})}var Ah=S("ZodCustom",(t,e)=>{Qb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cR(t,r,o,n)});function nB(t){let e=new it({check:"custom"});return e._zod.check=t,e}function IS(t,e){return B_(Ah,t??(()=>!0),e)}function IC(t,e={}){return H_(Ah,t,e)}function kC(t,e){return q_(t,e)}var oB=Z_,iB=K_,AC=S("ZodInstanceOf",(t,e)=>{Ah.init(t,e)},{properties(t,e){return this.check(gd(t,e))}});function sB(t,e={}){let r=new AC({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...A.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 aB=(...t)=>W_({Codec:kh,Boolean:Pd,String:Ad},...t);function cB(t){let e=xC(()=>nt([I(t),Ke(),Lt(),_h(),Te(e),ct(I(),e)]));return e}function Th(t,e){return new vC({type:"pipe",in:xS(t),out:e})}var Qde={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 efe(t){Nt({customError:t})}function tfe(){return Nt().customError}var TC;TC||(TC={});var bu={};vt(bu,{ZodISODate:()=>Ia,ZodISODateTime:()=>$a,ZodISODuration:()=>Aa,ZodISOTime:()=>ka,date:()=>nfe,datetime:()=>rfe,duration:()=>ife,time:()=>ofe});function rfe(t){return ph($a,t)}function nfe(t){return mh(Ia,t)}function ofe(t){return hh(ka,t)}function ife(t){return gh(Aa,t)}var F={...Od,...Q_,iso:bu},sfe=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 afe(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 uB(t,e){return t.map((r,o)=>o<e?r:r.optional())}function cfe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ufe(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:cfe(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 lfe(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 PC(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=PC(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=PC(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 dfe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),ffe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Ph(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(Ph):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>dfe.has(e)?Ph(r):!ffe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(Ph))}function lB(t){return t===1?"element":"elements"}function pfe(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=PC(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 ${lB(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 ${lB(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function dB(t,e){if(t!==!1)return t===void 0||t===!0?F.any():en(t,e)}var mfe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function fB(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=ufe(n,e),s=en(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 fB(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(mfe)):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"?en(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=en(p,e);ur(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let h of p){let y=en(d[h],e),w=F.string().regex(new RegExp(h));f.push(F.looseRecord(w,y))}let m=[];if(Object.keys(n).length>0&&m.push(F.object(n).passthrough()),m.push(...f),m.length===0)o=F.object({}).passthrough();else if(m.length===1)o=m[0];else{let h=F.intersection(m[0],m[1]);for(let y=2;y<m.length;y++)h=F.intersection(h,m[y]);o=h}if(t.additionalProperties===!1){let h=Object.keys(n),y=p.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!Yn(b.value))return;let _=[];for(let E of Object.keys(b.value))h.includes(E)||y.some(k=>k.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 p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=en(p,e)}o=lfe(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=>en(d,e)),c=uB(a,s),u=Array.isArray(i)?void 0:dB(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=>en(d,e)),c=uB(a,s),u=dB(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=en(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=pfe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?en(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 en(t,e){if(typeof t=="boolean")return t?F.any():F.never();let r=fB(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=>en(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=>en(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:en(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=F.intersection(a,en(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&&!Ph(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&&!Ph(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))sfe.has(a)||ur(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function pB(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=afe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??lr};return en(r,i)}var mB=Symbol("z.visit/resolving");function Rh(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===mB)return new od({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,mB);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let h=n(u[m]);h!==u[m]&&(d=!0),p[m]=h}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?Ze(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:Ze(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?Ze(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:Ze(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:Ze(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?Ze(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:Ze(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:Ze(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:Ze(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:Ze(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return Ze(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 hB(t){return Rh(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:nt(r.options)}})}function hfe(t,e){if(!e?.length)return t;let r=t._zod.def;return Ze(t,Xn(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function gB(t){return hfe(t.out,t.checks)}function gfe(t){return t.in._zod.traits.has("$ZodTransform")?gB(t):t.in}function yB(t){return Rh(t,{pipe:e=>gfe(e._zod.def),default:(e,r)=>r?st(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function vB(t){return Rh(t,{pipe:e=>gB(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var RC={};vt(RC,{bigint:()=>bfe,boolean:()=>wfe,date:()=>_fe,number:()=>vfe,string:()=>yfe});function yfe(t){return OP(Ad,t)}function vfe(t){return DP(Td,t)}function wfe(t){return zP(Pd,t)}function bfe(t){return jP(Rd,t)}function _fe(t){return MP(Sh,t)}var Ch={name:"@tomato414941/foundation",version:"2.1.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 Nd=new TextEncoder,Dd=new TextDecoder,wB=new TextDecoder("utf-8",{fatal:!0}),kS=2**32;function tn(...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 CC(t,e,r){if(e<0||e>=kS)throw new RangeError(`value must be >= 0 and <= ${kS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OC(t){let e=Math.floor(t/kS),r=t%kS,o=new Uint8Array(8);return CC(o,e,0),CC(o,r,4),o}function AS(t){let e=new Uint8Array(4);return CC(e,t),e}var xfe=/[^\x00-\x7f]/;function pr(t){if(typeof t=="string"&&t.length>=128){if(xfe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return Nd.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 bB(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 _B(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 TS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ms=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 _u=class extends Ms{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},ut=class extends Ms{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ta=class extends Ms{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},M=class extends Ms{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},xt=class extends Ms{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var Oh=class extends Ms{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var PS=class extends Ms{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var Efe="The input to be decoded is not correctly encoded.";function Su(t){try{return _B(typeof t=="string"?t:Dd.decode(t),!0)}catch(e){throw new TypeError(Efe,{cause:e})}}function Tt(t){return bB(typeof t=="string"?Nd.encode(t):t,!0)}function Nn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Bt(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 Pa(...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 eo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function vn(t,e,r){try{return Su(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function RS(t,e,r){try{return pr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function zd(t,e,r){let o;try{o=JSON.parse(wB.decode(Su(t)))}catch{throw new e(r)}if(!Bt(o))throw new e(r);return o}var CS={__proto__:null,b64:!0},OS={__proto__:null};function Nh(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 NS(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 Ra(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 ut(`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 DS(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function xu(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(!Bt(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var $fe=t=>t[Symbol.toStringTag],Ife=(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 Lo(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(Bt(e)){if(s=UC(e),typeof s.kty!="string")throw SB(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(Ife(t,s,r),s.kty==="oct")return Su(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!zC(e))throw SB(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${$fe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Ca(e))return e;if(a=e,a.type==="secret")return a.export()}NC||=new WeakMap;let c=e,u=NC.get(c);if(u?.[o])return u[o];if(u||NC.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=kfe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await Md(t,s)}var NC,kfe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function jS(t){if(!Ca(t))throw new Error("CryptoKey instance expected")}var Ca=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},DC=t=>t?.[Symbol.toStringTag]==="KeyObject",zC=t=>Ca(t)||DC(t);function xB(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 Us=(t,...e)=>xB("Key must be ",t,...e);function SB(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(xB(`Key for the ${t} algorithm must be `,e,...o))}var zS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function jC(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function jd(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 MC(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw zS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw zS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw zS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw zS(e.length,"algorithm.length");jC(t,r)}function MS(t){return{__proto__:null,...t}}function UC(t){let e=MS(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 US(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function Md(t,e,r){if(!t.kty.includes(e.kty))throw new ut('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 Fo(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),MC(t,e,r),t}var Eu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function LS(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 Afe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function EB(t,e){if(e.length<<3!==t.ivBits)throw new M("Invalid Initialization Vector length")}async function $B(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Us(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 IB(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Tfe(t,e,r,o,n){let[i,s,a]=await $B(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=tn(n,o,c,OC(n.length*8)),l=await IB(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Pfe(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 Rfe(t,e,r,o,n,i){let[s,a,c]=await $B(t,e,"decrypt"),u=tn(i,o,r,OC(i.length*8)),l=await IB(a,u,c);try{if(await Pfe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Ta}async function FS(t,e,r,o,n){if(!Ca(r)&&!(r instanceof Uint8Array))throw new TypeError(Us(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?EB(t,o):o=Afe(t),r instanceof Uint8Array&&LS(r,t.cekBits),t.cbc)return Tfe(t,e,r,o,n);let i=await Fo(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 VS(t,e,r,o,n,i){if(!Ca(e)&&!(e instanceof Uint8Array))throw new TypeError(Us(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(EB(t,o),e instanceof Uint8Array&&LS(e,t.cekBits),t.cbc)return Rfe(t,e,r,o,n,i);let s=await Fo(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,tn(r,n)))}catch{throw new Ta}}function Dh(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var Cfe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Ofe=[[],["deriveBits"]],qS=[[],[]];function BS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:Cfe,ops:["wrapKey","unwrapKey"]}}function HS(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 ut('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Ofe,ops:[void 0,"deriveBits"]}}function Ud(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:qS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function LC(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:qS,ops:["deriveBits","deriveBits"]}}var Ls=Dh({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:qS,ops:["encrypt","decrypt"]},"RSA-OAEP":BS(1),"RSA-OAEP-256":BS(256),"RSA-OAEP-384":BS(384),"RSA-OAEP-512":BS(512),"ECDH-ES":HS("direct-key-agreement"),"ECDH-ES+A128KW":HS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":HS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":HS("key-agreement-with-key-wrapping"),A128KW:Ud(128),A192KW:Ud(192),A256KW:Ud(256),A128GCMKW:Ud(128,!0),A192GCMKW:Ud(192,!0),A256GCMKW:Ud(256,!0),"PBES2-HS256+A128KW":LC(),"PBES2-HS384+A192KW":LC(),"PBES2-HS512+A256KW":LC()}),Nfe=["encrypt","decrypt"];function Ld(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:qS,ops:Nfe,cekBits:t,ivBits:e?128:96,cbc:e}}var Dfe=Dh({A128GCM:Ld(128),A192GCM:Ld(192),A256GCM:Ld(256),"A128CBC-HS256":Ld(256,!0),"A192CBC-HS384":Ld(384,!0),"A256CBC-HS512":Ld(512,!0)});function kB(t,e){throw new ut(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Vo(t){return(typeof t=="string"?Ls[t]:void 0)??kB("alg","Algorithm")}function Bo(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function $u(t){return(typeof t=="string"?Dfe[t]:void 0)??kB("enc","Encryption Algorithm")}function AB(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");jC(t,e)}async function zfe(t,e,r){let o=await Fo(e,Vo(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 jfe(t,e,r){let o=await Fo(e,Vo(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 PB(t,e,r){MC(e,Vo(t).subtle,r),jd(t,e)}async function RB(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=tn(pr(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 Fo(o,Vo(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function FC(t){return tn(AS(t.length),t)}async function Mfe(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 TS("sha256",tn(AS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function CB(t,e,r,o,n=new Uint8Array,i=new Uint8Array){AB(t),AB(e,"deriveBits");let s=tn(FC(pr(r)),FC(n),FC(i),AS(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 Mfe(a,o,s)}function OB(t){jS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new ut("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ZS(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 vn(r,e,M)}}function NB(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 Ufe(t){if(t===void 0)throw new M("JWE Encrypted Key missing")}function TB(t){if(t!==void 0)throw new M("Encountered unexpected JWE Encrypted Key")}function Lfe(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 DB(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return TB(o),r;let c=a==="direct-key-agreement";switch(c?TB(o):Ufe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Bt(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');OB(r);let l=await Md(t,u),d=ZS(n,"apu"),p=ZS(n,"apv");NB(d,p);let f=await CB(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return jS(r),PB(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');Lfe(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=vn(n.p2s,"p2s",M);r=await RB(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=vn(n.iv,"iv",M),l=vn(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 VS($u(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return jfe(s.slice(-6),r,o)}async function KS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Bo(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Lo(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Eu(e):void 0;l&&LS(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{OB(u);let{apu:f,apv:m}=i;f!==void 0&&Nn(f,'"apu"'),m!==void 0&&Nn(m,'"apv"');let h=f??ZS(o,"apu"),y=m??ZS(o,"apv");NB(h,y);let w;i.epk!==void 0?w=await Lo(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:k,crv:O,kty:H}=await b.exportKey("jwk",_),te=a==="direct-key-agreement",ke=await CB(u,w,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),h,y),Ee={x:E,crv:O,kty:H};if(H==="EC"&&(Ee.y=k),p={epk:Ee},f!==void 0&&(p.apu=Tt(f)),m!==void 0&&(p.apv=Tt(m)),te)return[ke,void 0,p];u=ke;break}case"RSA-OAEP":{jS(u),PB(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await RB(m,s,f,u),p={p2c:f,p2s:Tt(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await FS($u(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:Tt(m.iv),tag:Tt(m.tag)}}}if(d??=await zfe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function WS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new ut('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 zB(t){if(typeof globalThis[t]>"u")throw new ut(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function jB(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 tn(...n)}async function MB(t){return zB("CompressionStream"),jB(new CompressionStream("deflate-raw"),t)}async function UB(t,e){return zB("DecompressionStream"),jB(new DecompressionStream("deflate-raw"),t,e)}function LB(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&&!Bt(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 FB(t){let e,r;try{let{header:o}=t;if(Bt(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 VB(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&&!Bt(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 VC(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=zd(e,M,"JWE Protected Header is invalid")),[s,vn(r,"ciphertext",M),o!==void 0?vn(o,"iv",M):void 0,n!==void 0?vn(n,"tag",M):void 0,RS((e??"")+(i!==void 0?`.${i}`:""),"aad",M)]}function JS(t){return[t&&Nh("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&Nh("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function BC(t,e,r,o=VC(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Pa(n,u,l))throw new M("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,h,y,w]=e,{encrypted_key:b}=t;Ra(M,OS,h,n,p),WS(p,n);let{alg:_,enc:E}=p;if(typeof _!="string"||!_)throw new M("missing JWE Algorithm (alg) in JWE Header");let k=Ls[_];if(b===""&&(!k||!Bo(k)))throw new M("JWE Encrypted Key incorrect type");let O=k?.mode==="integrated-encryption";if(!O&&(typeof E!="string"||!E))throw new M("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(_)||!f&&_.startsWith("PBES2"))throw new _u('"alg" (Algorithm) Header Parameter value not allowed');let H;if(O){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 _u('"enc" (Encryption Algorithm) Header Parameter value not allowed');H=$u(E)}let te;if(b!==void 0)try{te=vn(b,"encrypted_key",M)}catch(Ae){if(!k||!Bo(k))throw Ae;te=new Uint8Array}let ke=!1;typeof r=="function"&&(r=await r(n,t),ke=!0);let Ee=k??Vo(_);Bo(Ee)&&te===void 0&&(te=new Uint8Array);let tt=await Lo(Ee.mode==="direct-encryption"?H:Ee,r,"decrypt"),Ve;if(Ee.mode==="integrated-encryption")Ve=await Ee.decrypt(tt,te,i,c,n,p);else{let Ae=H,J;try{J=await DB(Ee,Ae,tt,te,p,y),Bo(Ee)&&J instanceof Uint8Array&&J.byteLength<<3!==Ae.cekBits&&(J=Eu(Ae))}catch(kt){if(kt instanceof TypeError||kt instanceof M||kt instanceof ut)throw kt;J=Eu(Ae)}Ve=await VS(Ae,J,i,s,a,c)}if(p.zip==="DEF"){let Ae=w??25e4;if(Ae===0)throw new ut('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ae!==1/0&&(!Number.isSafeInteger(Ae)||Ae<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");Ve=await UB(Ve,Ae).catch(J=>{throw J instanceof M?J:new M("Failed to decompress plaintext",{cause:J})})}return{plaintext:Ve,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:vn(d,"aad",M)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...ke&&{key:tt}}}async function BB(t,e,r){if(t instanceof Uint8Array&&(t=Dd.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 BC({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function zh(t,e,r){return BB(t,JS(r),e)}async function HC(t,e,r){if(!Bt(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(Bt))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=JS(r),s=LB(t),a=VC(s)}catch{throw new Ta}let c=n.map(u=>FB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Ls[l]:void 0;if(d&&!Bo(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 VB(l),await BC(l,i,e,a)}catch{}throw new Ta}function GS(t,e,r){if(!Pa(t,e,r))throw new M("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function qC(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&&Nn(s,"JWE Additional Authenticated Data"),a!==void 0&&Nn(a,"JWE Content Encryption Key"),c!==void 0&&Nn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=xu(M,o)[0],t[1]=o),n!==void 0&&(n=xu(M,n)[0],t[2]=n),!r&&i!==void 0&&(i=xu(M,i)[0],t[3]=i),u!==void 0&&!Bt(u))throw new TypeError("JWE Key Management Parameters must be an object");GS(o,n,i);let d={...o,...n,...i};NS(M,o),Ra(M,OS,l,o,d),WS(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new M('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Ls[p];if(m?.mode==="integrated-encryption"){if(f!==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 ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,$u(f),m]}async function ZC(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,m]=t,h=a,y=c,w=i??Vo(o.alg),b,_,E;w.mode==="integrated-encryption"?E=await Lo(w,r,"encrypt"):[E,b,_]=await KS(w,n,r,o,d,f),_&&(m?y=y?{...y,..._}:_:h=h?{...h,..._}:_,GS(h,y,u));let k=h?Tt(JSON.stringify(h)):"",O=l?.byteLength?Tt(l):void 0,H=pr(O?`${k}.${O}`:k),te=s;o.zip==="DEF"&&(te=await MB(te).catch(Ae=>{throw new M("Failed to compress plaintext",{cause:Ae})}));let ke,Ee,tt;w.mode==="integrated-encryption"?[b,ke]=await w.encrypt(E,te,H,h,o,f):{ciphertext:ke,tag:Ee,iv:tt}=await FS(n,te,E,p,H);let Ve={ciphertext:Tt(ke)};return tt&&(Ve.iv=Tt(tt)),Ee&&(Ve.tag=Tt(Ee)),b?.byteLength&&(Ve.encrypted_key=Tt(b)),O&&(Ve.aad=O),h&&(Ve.protected=k),u&&(Ve.unprotected=u),y&&(Ve.header=y),Ve}async function HB(t,e,r){return ZC(t,qC(t,r),e)}function qB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var KC=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return eo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return eo(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}},jh=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new KC(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return eo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return eo(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");Nn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[h,y,w,b]=m.state,_=[this.#e,o,h,n,this.#o,void 0,void 0,y,b,e],E=qC(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,E,w]);let[{alg:k,enc:O},,H]=E;if(e&&H&&!Bo(H))throw new M(`"${k}" alg may only have a single recipient`);if(!r)r=O;else if(r!==O)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Vo(m[0].alg);let[s,a,c]=i[0],u=e?Eu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await ZC(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[h,[y,w,b],_]=i[m],E=h[2],[,k,O]=await KS(b,w,_,y,u,h[7]),H={encrypted_key:Tt(k)};if(E||O){let te={...E,...O};O&&GS(h[1],te,h[3]),H.header=te}f.recipients.push(H)}return f}};var Mh=[["verify"],["sign"]];function WC(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Mh}}function Fd(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:Mh,minRsaBits:2048}}function JC(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Mh}}function ZB(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Mh}}function GC(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Mh}}var XC=Dh({HS256:WC(256),HS384:WC(384),HS512:WC(512),RS256:Fd(256),RS384:Fd(384),RS512:Fd(512),PS256:Fd(256,32),PS384:Fd(384,48),PS512:Fd(512,64),ES256:JC("P-256",256),ES384:JC("P-384",384),ES512:JC("P-521",512),EdDSA:ZB(),Ed25519:ZB(),"ML-DSA-44":GC(44),"ML-DSA-65":GC(65),"ML-DSA-87":GC(87)});function XS(t){let e=typeof t=="string"?XC[t]:void 0;if(!e)throw new ut(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function KB(t){return[t&&Nh("algorithms",t.algorithms),t?.crit]}function Ffe(t){return t===void 0?{}:zd(t,xt,"JWS Protected Header is invalid")}function Vfe(t){try{return pr(t)}catch{throw new xt("JWS Compact Serialization payload must use only ASCII characters")}}async function Bfe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Ffe(i);if(!Pa(c,s))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=DS(c,Ra(xt,CS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new _u('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new xt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let m=XS(d),h=tn(i!==void 0?pr(i):new Uint8Array,pr("."),typeof p=="string"?e[2]??=RS(p,"payload",xt):p),y=vn(t.signature,"signature",xt),w=await Lo(m,r,"verify"),b=await Fo(w,m.subtle,"verify");m.minRsaBits&&jd(m.alg,b);let _=!1;try{_=await crypto.subtle.verify(m.signing,b,y,h)}catch{}if(!_)throw new PS;let E={payload:typeof p=="string"?vn(p,"payload",xt):p};return i!==void 0&&(E.protectedHeader=c),s!==void 0&&(E.unprotectedHeader=s),f?[{...E,key:w},l]:[E,l]}async function WB(t,e,r){if(t instanceof Uint8Array&&(t=Dd.decode(t)),typeof t!="string")throw new xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new xt("Invalid Compact JWS");return Bfe({payload:n,protected:o,signature:i},e,r,Vfe)}async function YC(t,e,r){let[o]=await WB(t,KB(r),e);return o}var Vd=class{#e;constructor(e){Nn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return eo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return eo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return eo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return eo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return qB(await HB([...this.#e],e,r))}};async function Hfe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=xu(xt,n);n=w[0],a=Tt(w[1])}if(i!==void 0&&(i=xu(xt,i)[0]),!n&&!i)throw new xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Pa(n,i))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};NS(xt,n);let u=DS(n,Ra(xt,CS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=XS(l),p="",f=o,m;if(u){let w=t[4];w?(p=w[0]??=Tt(o),f=w[1]??=pr(p)):(p=Tt(o),m=Nd.encode(`${a}.${p}`))}m??=tn(pr(a),pr("."),f);let h=await Fo(await Lo(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&jd(d.alg,h);let y={signature:Tt(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:p};return n&&(y.protected=a),i&&(y.header=i),[y,u]}async function JB(t,e,r,o,n){let[i]=await Hfe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Uh=class{#e;#t;constructor(e){Nn(e,"payload"),this.#e=e}setProtectedHeader(e){return eo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return JB(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var QC='"alg" (Algorithm)';function eO(t='JWK "alg" (Algorithm) Parameter'){throw new ut(`Invalid or unsupported ${t} value`)}function Lh(t,e){return(typeof t=="string"?XC[t]??Ls[t]:void 0)??eO(e)}async function Oa(t){if(DC(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Tt(t)};if(!Ca(t))throw new TypeError(Us(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 Fs=(t,e)=>{if(typeof t!="string"||!t)throw new Oh(`${e} missing or invalid`)};async function tO(t,e){let r;if(Bt(t)){if(r=MS(t),typeof r.kty!="string")throw new TypeError(Us(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(zC(t))r=MS(await Oa(t));else throw new TypeError(Us(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":Fs(r.alg,'"alg" (Algorithm) Parameter'),Fs(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Fs(r.crv,'"crv" (Curve) Parameter'),Fs(r.x,'"x" (X Coordinate) Parameter'),Fs(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Fs(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Fs(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Fs(r.e,'"e" (Exponent) Parameter'),Fs(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 Oh('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new ut('"kty" (Key Type) Parameter missing or unsupported')}let n=pr(JSON.stringify(o));return Tt(await TS(e,n))}async function to(t,e,r){if(!Bt(t))throw new TypeError("JWK must be an object");let o=UC(t),n=US(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 Su(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 Md(Lh(e),o,n)}case"RSA":case"EC":case"OKP":return Md(Lh(e),o,n);default:throw new ut('Unsupported "kty" (Key Type) Parameter value')}}function rO(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 zd(e,TypeError,r)}function qfe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new ut("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Fh(t,e){let r=US(e?.extractable),o=Lh(t,QC);o.secret&&eO(QC);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new ut("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 ut(`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:qfe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}typeof window<"u"&&g.config({jitless:!0});var $=g.uuid(),le=g.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),ot=g.iso.datetime(),ro=g.json(),Iu=g.record(g.string(),ro),XB=g.enum(["ja","en"]),YB=g.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var QB=g.enum(["variable","connection","service","method","app","object","environment","function"]),Nr=g.object({kty:g.literal("EC"),crv:g.literal("P-256"),x:g.string().min(40).max(50),y:g.string().min(40).max(50)}).strict(),Zfe=g.object({alg:g.literal("dir"),enc:g.literal("A256GCM"),sub:$}).strict(),ex=g.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(rO(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ho=g.object({protected:g.string().max(2048),iv:g.string().max(64),ciphertext:g.string().max(2e6),tag:g.string().max(64),aad:g.string().max(2048).optional(),recipients:g.array(g.object({encrypted_key:g.string().max(2048),header:g.object({kid:$,epk:Nr.optional(),alg:g.string().optional()}).passthrough()})).min(1).max(100)}).strict(),T2e=g.object({id:$,name:le,publicKey:Nr}),Bd=g.object({id:$,name:le,owner:g.object({id:$,name:le}).nullable(),createdAt:ot,permissions:g.array(YB),createKinds:g.array(QB),publicKey:Nr.nullable()}),eH=g.object({id:$,kind:g.enum(["passkey","email","key"]),name:g.string(),createdAt:ot,lastUsedAt:ot.nullable(),expiresAt:ot.nullable(),canOpen:g.boolean()}),tH=g.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),Kfe=g.object({subjectId:$,relation:tH,objectId:$}).strict(),P2e=Kfe.extend({objectType:g.enum(["principal",...QB.options]),subjectName:le,objectName:le,createdAt:ot}),R2e=g.object({error:g.object({code:g.string(),message:g.string(),details:ro.optional()})}),C2e=g.object({ok:g.literal(!0)}),rH=g.object({name:g.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:g.string(),secret:g.boolean().optional(),required:g.boolean().optional(),placeholder:g.string().optional(),note:g.string().optional(),pattern:g.string().optional()}),nH=g.record(g.string().regex(/^[A-Z_][A-Z0-9_]*$/),g.string()),Wfe=g.object({values:g.array(g.object({id:g.string(),name:g.string(),description:g.string().optional()})).optional(),default:g.array(g.string()).default([]),separator:g.string().default(" "),docs:g.url().optional()}),YS=g.string().min(1).max(4096),GB=g.union([g.string(),g.array(g.string()).min(1)]),oH=g.object({issuer:g.url().optional(),authorizeUrl:YS,tokenUrl:YS,identity:g.object({url:YS.optional(),from:g.enum(["token","app"]).optional(),method:g.enum(["GET","POST"]).default("GET"),id:GB.default("/id"),name:GB.default("/name"),headers:g.record(g.string(),g.string()).default({})}).optional(),revoke:g.object({url:YS,style:g.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:g.enum(["body","basic","none"]).optional()}).optional(),clientAuth:g.enum(["body","basic","none"]).default("body"),pkce:g.boolean().default(!0),tokenFormat:g.enum(["form","json"]).default("form"),okPointer:g.string().optional(),authorizeParams:g.record(g.string(),g.string()).default({}),tokenParams:g.record(g.string(),g.string()).default({}),defaults:g.record(g.string(),g.string()).default({}),scopes:Wfe.default({default:[],separator:" "}),fields:g.array(rH).default([]),outputs:nH.default({ACCESS_TOKEN:"/accessToken"}),adapter:g.enum(["google","github","ebay","openrouter","cloudflare","slack"]).optional(),keep:g.array(g.string()).default([]),hint:g.string().optional()}),iH=g.object({fields:g.array(rH).min(1),outputs:nH,console:g.url().optional(),instructions:g.string().optional(),hint:g.string().optional()}),oO=g.enum(["oauth","token","role"]),sH=g.object({kind:g.literal("aws"),hint:g.string().optional()}),iO={name:le,docs:g.url().optional(),console:g.url().optional()},aH=g.object({...iO,kind:g.literal("oauth"),config:oH}).strict(),cH=g.object({...iO,kind:g.literal("token"),config:iH}).strict(),uH=g.object({...iO,kind:g.literal("role"),config:sH}).strict(),ku=g.discriminatedUnion("kind",[aH,cH,uH]),nO={id:g.string().min(1),builtin:g.boolean(),availability:g.enum(["ready","app-required","unavailable"])},sO=g.discriminatedUnion("kind",[aH.extend(nO),cH.extend(nO),uH.extend(nO)]),aO=g.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),tx=g.object({name:le,logo:g.string().regex(/^[a-z0-9-]+$/).optional(),api:g.url().optional(),docs:g.url().optional(),console:g.url().optional()}).strict(),Jfe=tx.extend({auth:g.object({oauth:oH.optional(),token:iH.optional(),role:sH.optional()}).strict()}).strict(),Gfe=tx.extend({methods:g.record(aO,g.string().min(1))}).strict(),Xfe=tx.extend({methods:g.record(aO,g.union([g.string().min(1),ku]))}).strict(),lH=g.union([Xfe,Jfe]),O2e=tx.extend({id:g.string(),builtin:g.boolean(),methods:g.record(aO,sO)}),dH=g.object({id:$,output:g.string().min(1).max(100).optional()}).strict(),cO=g.object({name:g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:dH,format:g.enum(["text","file","json"]).default("text"),pointer:g.string().optional()}).strict(),Yfe=g.object({pointer:g.string().max(500),parts:g.array(g.union([g.string().max(8192),dH])).min(1).max(32)}).strict(),Au=g.object({url:g.string().max(4096),method:g.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:g.record(g.string(),g.string().max(8192)).default({}),body:g.string().max(1e6).optional(),json:ro.optional(),form:g.record(g.string(),g.string()).optional(),bindings:g.array(Yfe).max(32).default([])}).strict(),Vh=g.object({description:g.string().max(2e3).default(""),request:Au,parameters:g.array(g.object({name:g.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:g.string().max(100),required:g.boolean().default(!0),default:g.string().optional()})).max(32).default([]),save:g.record(g.string(),le).default({}),outputOwnerId:$.optional()}).strict(),Na={id:$,ownerId:$,name:le,createdAt:ot,updatedAt:ot,version:g.number().int().positive(),permissions:g.array(YB)},Qfe=g.enum(["starting","running","stopping","stopped","failed"]),epe=g.object({state:g.enum(["pending","failed","complete"]),error:g.string().nullable()}),tpe=g.object({idleSeconds:g.number().int().min(60).max(86400).default(3600),maxSeconds:g.number().int().min(60).max(86400).default(3600)}).strict(),fH=g.object({image:g.string().min(1).max(300).optional(),size:g.enum(["small","medium","large"]).default("small"),lifetime:tpe.default({idleSeconds:3600,maxSeconds:3600})}).strict(),uO={recipients:g.array($).default([]),executors:g.array($).default([]),custodyRevision:g.number().int().positive().nullable().default(null)},rpe=g.object({...Na,kind:g.literal("variable"),data:g.object({...uO,bytes:g.number().int().nonnegative()})}),npe=g.object({...Na,kind:g.literal("connection"),data:g.object({...uO,methodId:g.string(),methodName:g.string(),methodKind:oO,services:g.array(g.object({id:g.string(),name:le})).default([]),account:g.string(),accountId:g.string().nullable().default(null),accountVerified:g.boolean().default(!1),scopes:g.array(g.string()),scopesStatus:g.enum(["unknown","requested","reported"]).default("unknown"),outputs:g.array(g.string()),state:g.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:$.nullable(),generation:$.optional(),authorizationDigest:g.string().optional()})}),ope=g.object({...Na,kind:g.literal("service"),data:Gfe}),ipe=g.object({...Na,kind:g.literal("method"),data:ku}),spe=g.object({...Na,kind:g.literal("app"),data:g.object({...uO,methodId:g.string(),clientId:g.string(),fields:g.record(g.string(),g.string()).default({}),generation:$.optional()})}),ape=g.object({...Na,kind:g.literal("object"),data:g.object({size:g.number().int().nonnegative(),contentType:g.string()})}),cpe=g.object({...Na,kind:g.literal("environment"),data:fH.extend({executorId:$.optional(),operatorId:$.optional(),driver:g.enum(["attached","managed"]).optional(),capabilities:g.array(g.string()).optional(),isolation:g.enum(["process","container"]).optional(),manifestDigest:g.string().optional(),awsPrincipal:g.string().optional(),state:Qfe,deletion:epe.optional(),startedAt:ot.nullable(),stoppedAt:ot.nullable(),lastActiveAt:ot,error:g.string().nullable()})}),upe=g.object({...Na,kind:g.literal("function"),data:Vh}),no=g.discriminatedUnion("kind",[rpe,npe,ope,ipe,spe,ape,cpe,upe]),N2e=g.discriminatedUnion("kind",[g.object({kind:g.literal("service"),name:le,definition:lH}).strict(),g.object({kind:g.literal("method"),name:le,definition:ku}).strict(),g.object({kind:g.literal("environment"),name:le.optional(),options:fH}).strict(),g.object({kind:g.literal("function"),name:le,definition:Vh}).strict()]),D2e=g.object({version:g.number().int().positive(),name:le.optional(),definition:g.union([lH,ku,Vh]).optional()}).strict(),rx=g.object({command:g.array(g.string().max(8192)).min(1).max(100),stdin:g.string().max(1e6).optional(),timeoutSeconds:g.number().int().min(1).max(3600).default(60),inputs:g.array(cO).max(32).default([])}).strict(),pH=g.object({method:g.enum(["GET","POST","PUT","PATCH","DELETE","CONNECT"]),path:g.string().startsWith("/api/").max(2048),body:ro.optional(),inputs:g.array(g.object({pointer:g.string(),label:g.string().min(1).max(100),secret:g.boolean().default(!1),multiline:g.boolean().default(!1),site:g.url().optional()})).max(16).default([])}).strict(),lpe=g.object({ja:g.string(),en:g.string()}).strict(),mH=g.object({ownerId:g.union([$,g.literal("$approver")]),methodId:g.string().min(1).max(200),connectionId:$.optional(),environmentId:$.optional(),name:le.optional()}).strict(),hH=g.object({to:$.optional(),message:g.string().max(1e3).default(""),operations:g.array(pH).min(1).max(8),expiresInMinutes:g.number().int().min(1).max(1440).default(30)}).strict(),QS=g.object({id:$,name:le}),dpe=g.discriminatedUnion("kind",[g.object({kind:g.literal("line"),subject:QS,relation:tH,object:QS}),g.object({kind:g.literal("transfer"),item:QS,to:QS})]),Da=g.object({id:$,from:Bd.pick({id:!0,name:!0}),to:Bd.pick({id:!0,name:!0}).nullable(),message:g.string(),proposal:dpe.nullable(),operations:g.array(pH.extend({title:lpe})),state:g.enum(["pending","running","approved","declined","cancelled","expired"]),results:g.array(ro.nullable()),createdAt:ot,expiresAt:ot,url:g.url(),code:g.string().optional(),continueUrl:g.url().nullable(),returnUrl:g.url().nullable(),refreshUrl:g.url().nullable(),canRespond:g.boolean()}),z2e=g.object({id:$,name:le,publicKey:Nr,state:g.enum(["pending","approving","approved"]),principalId:$.nullable(),createdAt:ot,expiresAt:ot}),j2e=g.object({available:g.boolean(),required:g.boolean(),active:g.boolean(),payer:Bd.pick({id:!0,name:!0}).nullable()}),M2e=g.object({storageBytes:g.number().nonnegative(),storageLimit:g.number().positive(),computeSeconds:g.number().nonnegative(),computeLimit:g.number().positive(),month:g.string()}),U2e=g.object({id:g.string(),actorId:$.nullable(),action:g.string(),targetId:$.nullable(),createdAt:ot,details:Iu}),L2e=g.object({returnUrl:g.url().optional(),refreshUrl:g.url().optional()}).strict(),za=t=>g.object({items:g.array(t),next:g.string().nullable().default(null)}),F2e=g.object({id:$}),V2e=g.object({owner:$}),fpe=g.object({limit:g.coerce.number().int().min(1).max(200).default(100),after:g.string().optional()}),B2e=fpe.extend({object:$.optional(),subject:$.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var ppe=new TextEncoder,mpe=new TextDecoder,Bh="ECDH-ES+A256KW",lO="A256GCM",ft=t=>ppe.encode(t),Tu=t=>mpe.decode(t);function ja(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 gH(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function nx(){let t=await Fh(Bh,{crv:"P-256",extractable:!0});return{publicKey:Nr.parse(await Oa(t.publicKey)),privateKey:await Oa(t.privateKey)}}async function Pu(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 jh(t).setProtectedHeader({enc:lO}).setAdditionalAuthenticatedData(ft(r));for(let n of e)o.addRecipient(await to(n.publicKey,Bh)).setUnprotectedHeader({alg:Bh,kid:n.id});return Ho.parse(await o.encrypt())}async function Oi(t,e,r,o){if(t.aad!==ja(ft(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 to(e,Bh);return(await HC({...t,recipients:[n]},i,{keyManagementAlgorithms:[Bh],contentEncryptionAlgorithms:[lO]})).plaintext}async function hpe(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:ft("Foundation"),info:ft("passkey encryption key")},e,256))}async function yH(t,e,r){let o=await zh(t,await hpe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[lO]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Tu(o.plaintext))}var mr=g.string().regex(/^[A-Za-z0-9_-]{43}$/),Dn=g.string().min(100).max(4e6),vH=Nr.extend({d:g.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Hh=g.object({encryption:vH,signing:vH}).strict(),hr=g.object({id:$,principalId:$,generation:g.number().int().positive(),previous:mr.nullable(),encryption:Nr,signing:Nr}).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 Hd(t){return tO(Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ye(t){return ja(new Uint8Array(await crypto.subtle.digest("SHA-256",ft(R(t)))))}async function ix(){let[t,e]=await Promise.all([nx(),Fh("ES256",{crv:"P-256",extractable:!0})]),r=await Oa(e.privateKey);return Hh.parse({encryption:t.privateKey,signing:r})}function ox(t){return Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function sx(t,e){return hr.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:ox(e.encryption),signing:ox(e.signing)})}async function wn(t,e,r){let o=e instanceof CryptoKey?e:await to(e,"ES256");return new Uh(ft(R(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function oo(t,e,r,o){if(R(await dO(e,r,o))!==R(t))throw new Error("The signature does not authorize this content.")}async function dO(t,e,r){let o=await YC(t,await to(Nr.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 Ni=g.object({binding:hr,signature:Dn}).strict();async function qh(t,e){if(await Ma(t),await Hd(e.encryption)!==await Hd(t.encryption)||await Hd(e.signing)!==await Hd(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await wn(t,e.signing,"key-binding")}}async function Ma(t){let e=hr.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Hd(e.encryption)===await Hd(e.signing))throw new Error("Use separate encryption and signing keys.");await to(e.encryption,"ECDH-ES+A256KW"),await to(e.signing,"ES256")}async function fO(t){let{binding:e,signature:r}=Ni.parse(t);return await Ma(e),await oo(e,r,e.signing,"key-binding"),e}var qd=g.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."),Me={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632"},gpe=g.enum([Me.value,Me.tokenSet,Me.clientCredential]),pe={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},ax=g.enum([pe.http,pe.command,pe.function,pe.connect,pe.refresh,pe.revoke]);var ype={[Me.value]:[pe.http,pe.command,pe.function],[Me.tokenSet]:[pe.http,pe.command,pe.function,pe.refresh,pe.revoke],[Me.clientCredential]:[pe.connect,pe.refresh,pe.revoke]},pO=t=>ype[t],mO=t=>t===Me.tokenSet,vpe=g.object({actor:hr,executor:hr,operations:g.array(ax).min(1).max(6),functionDigests:g.array(mr).max(100).default([]),origins:g.array(qd).max(100).default([]),callerProgram:g.boolean().default(!1),expiresAt:ot}).strict(),Di=g.object({format:g.literal(2),origin:qd,id:$,ownerId:$,contentType:gpe,revision:g.number().int().positive(),authorities:g.array(hr).min(1).max(100),readers:g.array(hr).min(1).max(100),grants:g.array(vpe).max(100),observers:g.array($).max(100).optional(),producers:g.array(g.object({executor:hr,runId:$,expiresAt:ot,materialRevision:g.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),wH=g.object({ownerId:$,authorities:g.array(hr).min(1).max(100)}).strict(),bH=g.object({origin:qd,id:$,revision:g.number().int().positive(),from:wH,to:wH,policyDigest:mr,previous:mr.nullable(),signerId:$}).strict(),wpe=bH.extend({signature:Dn}),hO=g.array(wpe).max(16),Zh=g.object({policy:Di,authorityId:$,signature:Dn,lineage:hO.optional()}).strict(),io=g.object({policy:Di,authorityId:$,authorization:Dn,lineage:hO.optional(),materialRevision:g.number().int().positive(),updatedAt:ot,creationRunId:$.nullable(),metadata:Iu,sealed:Ho,signerId:$,signature:Dn}).strict(),Ru=t=>({ownerId:t.ownerId,authorities:t.authorities});async function _H(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||R(r.to)!==R(o.from))||o.previous!==(r?await ye(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 oo(i,n,s.signing,"authority-handoff"),r=o}if(r&&R(r.to)!==R(Ru(t)))throw new Error("Use the authorities approved by the latest handoff.")}function gO(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 SH(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=R(Ru(t));return r===R(Ru(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&R(o.from)===r)}async function xH(t,e,r,o){let n=[...t?.lineage??[]];if(t&&R(Ru(t.policy))!==R(Ru(e))){if(await qo(t),!t.policy.authorities.some(s=>R(s)===R(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=bH.parse({origin:e.origin,id:e.id,revision:e.revision,from:Ru(t.policy),to:Ru(e),policyDigest:await ye(e),previous:n.length?await ye(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await wn(i,o.signing,"authority-handoff")})}return n.length?{lineage:hO.parse(n)}:{}}async function cx(t){let e=Di.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 Ma(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(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!pO(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if(n.operations.some(i=>i===pe.http||i===pe.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(pe.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function ux(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Zd(t,e){return R({purpose:"resource",policyDigest:await ye(t),materialRevision:e})}async function yO(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await cx(e),c=await xH(s,a,o,n);if(!a.authorities.some(p=>R(p)===R(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Pu(t,ux(a).map(p=>({id:p.id,publicKey:p.encryption})),await Zd(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await wn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===Me.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=io.parse({...l,signature:await wn(l,n.signing,"resource")});return await qo(d),d}async function qo(t){let e=io.parse(t),{signature:r,...o}=e;await cx(e.policy),await _H(e.policy,e.lineage);let n=gO(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ye(e.policy))throw new Error("The handoff approves a different access policy.");await oo(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??(mO(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(pe.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 oo(o,r,s.signing,"resource");let a=ux(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!==ja(ft(await Zd(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function EH(t,e,r,o,n=t.metadata){let i=await qo(t);if(!mO(i.policy.contentType)||!(i.policy.authorities.some(p=>R(p)===R(r))||i.policy.grants.some(p=>R(p.executor)===R(r)&&p.operations.includes(pe.refresh)&&Date.parse(p.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Pu(e,ux(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await Zd(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 wn(l,o.signing,"resource")};return await qo(d),d}async function lx(t,e,r,o){let n=await cx(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 xH(o,n,e,r),authorityId:e.id,signature:await wn(n,r.signing,"access-policy")};return await Kd(i),i}async function Kd(t){let e=Zh.parse(t);await cx(e.policy),await _H(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ye(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 oo(e.policy,e.signature,o.signing,"access-policy"),e}async function dx(t,e,r,o,n,i){let s=await Kd(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&R(p.executor)===R(o)&&Date.parse(p.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 Pu(t,ux(a).map(p=>({id:p.id,publicKey:p.encryption})),await Zd(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 wn(l,n.signing,"resource")};return await qo(d),d}async function vO(t,e,r){let o=await qo(t);if(!o.policy.readers.some(n=>R(n)===R(e)))throw new Error("This identity cannot reveal the content.");return Oi(o.sealed,r,e.id,await Zd(o.policy,o.materialRevision))}var bpe=g.object({id:$,policyDigest:mr,materialRevision:g.number().int().positive(),authorizationDigest:mr.optional()}).strict();async function wO(t,e){return e.id===t.policy.id&&e.policyDigest===await ye(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||mO(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var fx=g.object({format:g.literal(2),id:$,origin:qd,ownerId:$,approval:g.object({id:$,index:g.number().int().min(0).max(7)}).strict().optional(),actor:hr,environmentId:$,executor:hr,environmentDigest:mr,operation:ax,functionDigest:mr.nullable(),operationDigest:mr,sources:g.array(bpe).max(100),resultRecipients:g.array(hr).min(1).max(100),createdAt:ot,expiresAt:ot}).strict(),px=g.object({intent:fx,signature:Dn,sealed:Ho}).strict();async function Cu(t,e){return R({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ye(t)})}async function $H(t,e,r){if(fx.parse(t),await ye(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Pu(ft(R(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Cu(t,"input"))};return px.parse({...o,signature:await wn(o,r.signing,"run")})}async function _pe(t,e=Date.now()){let r=px.parse(t),{signature:o,...n}=r;await oo(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!==ja(ft(await Cu(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function IH(t,e,r){let o=await _pe(t);if(R(o.intent.executor)!==R(e))throw new Error("This operation belongs to another executor.");let n=await Oi(o.sealed,r.encryption,e.id,await Cu(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(R(s)!==i||await ye(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function Ou(t,e,r={}){let o=await qo(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await wO(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===pe.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==pe.command&&e.operation!==pe.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function Ua(t,e,r,o={}){return await Ou(t,e,o),Oi(t.sealed,r.encryption,e.executor.id,await Zd(t.policy,t.materialRevision))}var Spe=g.object({email:g.boolean(),environments:g.boolean(),objects:g.boolean(),payments:g.boolean()}),mx=g.object({principal:Bd.nullable(),credentialId:$.nullable(),wrappedKey:ex.nullable(),requestId:$.nullable(),server:g.object({name:le,commit:g.string().nullable()}),features:Spe,principals:g.array(Bd)}),s6e=g.object({email:g.email().max(254),returnTo:g.string().max(2048).optional(),locale:XB.default("ja"),principalId:$.optional()}).strict(),a6e=g.object({intent:g.enum(["register","authenticate"]),name:le.optional(),principalId:$.optional(),returnTo:g.string().max(2048).optional()}).strict(),c6e=g.object({challengeId:$,credential:g.json(),publicKey:Nr.optional(),existingPublicKey:Nr.optional(),wrappedKey:ex.optional()}).strict();var xpe=g.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/[\w+=,.@/-]{1,200}$/),AH=g.object({format:g.literal(3),id:$,origin:qd,ownerId:$,name:le,executor:hr,operatorId:$,driver:g.enum(["attached","managed"]),capabilities:g.array(ax).min(1).max(6),isolation:g.enum(["process","container"]),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:xpe.optional(),revision:g.number().int().positive()}).strict(),bO=g.object({manifest:AH,signature:Dn}).strict();async function _O(t,e){let r=AH.parse(t),o={manifest:r,signature:await wn(r,e.signing,"environment")};return await Wd(o),o}async function Wd(t){let e=bO.parse(t),{manifest:r}=e;if(await Ma(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(pe.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(pe.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await oo(r,e.signature,r.executor.signing,"environment"),e}async function hx(t,e){let{manifest:r}=await Wd(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ye(r)||R(e.executor)!==R(r.executor)||!r.capabilities.includes(e.operation))throw new Error("This environment does not authorize the requested execution.")}var Epe=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),TH=g.object({ok:g.boolean(),result:ro.nullable(),error:g.object({code:g.string().max(100),message:g.string().max(1e3)}).nullable()}).strict(),Wh=g.object({id:$,intentDigest:mr,executorId:$,state:g.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ot,sealed:Ho,signature:Dn}).strict(),Kh=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Jd(t,e,r,o){let n=TH.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=ft(R(n));if(i.byteLength>14e5)throw new Kh;let s=await Pu(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Cu(t,"result")),a={id:t.id,intentDigest:await ye(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Wh.parse({...a,signature:await wn(a,o.signing,"receipt")})}async function $pe(t,e){let r=Wh.parse(t),{signature:o,...n}=r;if(await oo(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ye(e)||r.executorId!==e.executor.id||r.sealed.aad!==ja(ft(await Cu(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 PH(t,e,r,o){await $pe(t,e);let n=await Oi(t.sealed,o.encryption,r,await Cu(e,"result")),i=TH.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 Ipe=g.enum(["http","command","function","connect","refresh","revoke"]),zn=g.object({id:$,ownerId:$,actorId:$,environmentId:$,kind:Ipe,state:Epe,intent:fx,requestSignature:Dn,receipt:Wh.nullable(),error:g.string().nullable(),createdAt:ot,startedAt:ot.nullable(),finishedAt:ot.nullable()}).strict(),kH=g.object({name:le,approval:Zh}).strict(),Gd=g.discriminatedUnion("kind",[g.object({kind:g.literal("http"),request:Au,save:g.record(g.string(),kH).default({})}).strict(),g.object({kind:g.literal("command"),...rx.shape}).strict(),g.object({kind:g.literal("function"),definition:Vh,arguments:g.record(g.string(),g.string()).default({}),outputs:g.record(g.string(),kH).default({})}).strict(),g.object({kind:g.enum(["connect","refresh","revoke"]),input:ro}).strict()]);var La=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Vs=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=g.object({error:g.object({code:g.string(),message:g.string()})}).parse(await n.json())}catch{throw new La("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new La(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",{},mx)}};import{chmod as kpe,lstat as Ape,mkdir as Tpe,open as SO,readFile as CH,rename as Ppe,rm as Rpe}from"node:fs/promises";import{dirname as Cpe,join as xO,resolve as Ope}from"node:path";import{homedir as Npe}from"node:os";import{randomUUID as Dpe}from"node:crypto";var EO=g.object({origin:g.url(),principalId:g.uuid(),token:g.string().min(20),keys:Hh.nullable(),binding:hr.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),OH=g.object({current:g.uuid(),identities:g.array(EO).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Bs(){return xO(process.env.XDG_CONFIG_HOME||xO(Npe(),".config"),"foundation","identity.json")}function Fa(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 gx(t){let e;try{let n=Bs(),i=await Ape(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await kpe(n,384);let s=OH.parse(JSON.parse(await CH(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=Fa(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Fa(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 EO.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!==Fa(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 Jh(t){let e=Bs(),r;try{r=OH.parse(JSON.parse(await CH(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=EO.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Xd(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 zF(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;zF(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 jF=new Set(["type","properties","required","additionalProperties"]),NF=["oneOf","anyOf"];function DF(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function LP(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!jF.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]??DF(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:LP(a)??{allOf:a};ur(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=DF(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 Hde(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of jF)if(n in t)return;let r=e.filter(n=>NF.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=LP(e);else{let n=r[0],i=NF.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=>LP([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,yh(t,o))}function Ea(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):yh(u,m),yh(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(m.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())zF(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)??[])Hde(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)}yh(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,ur(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:xd(e,"input",t.processors),output:xd(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Qr(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 Qr(o.element,r);if(o.type==="set")return Qr(o.valueType,r);if(o.type==="lazy")return Qr(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 Qr(o.innerType,r);if(o.type==="intersection")return Qr(o.left,r)||Qr(o.right,r);if(o.type==="record"||o.type==="map")return Qr(o.keyType,r)||Qr(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Qr(o.in,r)||Qr(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Qr(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Qr(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Qr(n,r))return!0;return!!(o.rest&&Qr(o.rest,r))}return!1}var FP=(t,e={})=>r=>{let o=Sa({...r,processors:e});return rt(t,o),xa(o,t),Ea(o,t)},xd=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Sa({...n??{},target:i,io:e,processors:r});return rt(t,s),xa(s,t),Ea(s,t)};var Ed=(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)},MF=(t,e)=>{Ed(t,"minimum",e),$d(t,"maximum",e)},VF=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},BF=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},HF=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},qF=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},UF=(t,e)=>Ed(t,"minimum",e.minimum),LF=(t,e)=>$d(t,"maximum",e.maximum),FF=t=>(e,r)=>{qF(e,r.format);let[o,n]=t[r.format];Ed(e,"minimum",o),$d(e,"maximum",n)},qde={greater_than:(t,e)=>Ed(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>$d(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>VF(t,e.value),number_format:FF(_m),bigint_format:FF(Sm),min_length:UF,max_length:LF,length_equals:(t,e)=>MF(t,e.length),min_size:UF,max_size:LF,size_equals:(t,e)=>MF(t,e.size),string_format:(t,e)=>{qF(t,e.format),e.pattern&&BF(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)=>HF(t,e.mime)};function Jt(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)qde[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&Ed(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Ed(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&&VF(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&HF(e,n.mime);for(let i of n.patterns??[])BF(e,i);return e}var Zde={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Kde=new Map([[ab,AT],[zm,TT]]),ZF=t=>Kde.get(t)??t,HP=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=Jt(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=Zde[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(ZF);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},qP=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=Jt(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let m=new Set;for(let w of a)Number.isFinite(w)&&w!==0?m.add(Math.abs(w)):Wt(t,e,n,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...y]=m;h!==void 0&&(n.multipleOf=h),y.length&&(n.allOf=[...n.allOf??[],...y.map(w=>({multipleOf:w}))])}},ZP=(t,e,r,o)=>{r.type="boolean"},KP=(t,e,r,o)=>{Wt(t,e,r,o,"BigInt cannot be represented in JSON Schema")},WP=(t,e,r,o)=>{Wt(t,e,r,o,"Symbols cannot be represented in JSON Schema")},JP=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},GP=(t,e,r,o)=>{Wt(t,e,r,o,"Undefined cannot be represented in JSON Schema")},XP=(t,e,r,o)=>{Wt(t,e,r,o,"Void cannot be represented in JSON Schema")},YP=(t,e,r,o)=>{r.not={}},QP=(t,e,r,o)=>{},eR=(t,e,r,o)=>{},tR=(t,e,r,o)=>{Wt(t,e,r,o,"Date cannot be represented in JSON Schema")},rR=(t,e,r,o)=>{let n=t._zod.def,i=Ul(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},nR=(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(Wt(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Wt(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},oR=(t,e,r,o)=>{Wt(t,e,r,o,"NaN cannot be represented in JSON Schema")},iR=(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},sR=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=Jt(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})))},aR=(t,e,r,o)=>{r.type="boolean"},cR=(t,e,r,o)=>{Wt(t,e,r,o,"Custom types cannot be represented in JSON Schema")},uR=(t,e,r,o)=>{Wt(t,e,r,o,"Function types cannot be represented in JSON Schema")},lR=(t,e,r,o)=>{Wt(t,e,r,o,"Transforms cannot be represented in JSON Schema")},dR=(t,e,r,o)=>{Wt(t,e,r,o,"Map cannot be represented in JSON Schema")},fR=(t,e,r,o)=>{Wt(t,e,r,o,"Set cannot be represented in JSON Schema")},pR=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=Jt(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=rt(i.element,e,{...o,path:[...o.path,"items"]})};function vh(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?vh(e.out):e.type==="catch"?vh(e.innerType):t._zod.optin}var mR=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Wt(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)ur(n.properties,u,rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?vh(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},G_=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},hR=(t,e,r,o)=>{let n=t._zod.def,i=rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},gR=(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((h,y)=>rt(h,e,{...o,path:[...o.path,s,y]})),u=i.rest?rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let h=i.items[l-1];if(!(e.io==="input"?vh(h)!==void 0:h._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:m}=Jt(t);typeof f=="number"&&(n.minItems=f),typeof m=="number"&&(n.maxItems=m)};function VP(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 h=VP(t,m,r);return h===m?e:h}for(let m of["anyOf","oneOf"]){let h=e[m];if(!Array.isArray(h))continue;let y=h.map(w=>VP(t,w,r));y.some((w,b)=>w!==h[b])&&(e={...e,[m]:y})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(m=>m==="number"||m==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(m=>typeof m=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(m=>typeof m=="number"?String(m):m):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?zs:Tm).source)),f}var BP=new WeakMap;function Wde(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 BP.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=VP(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 yR=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=Jt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)ur(n.patternProperties,ZF(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=BP.get(e);l||(l=[],BP.set(e,l),e.deferred.push(()=>Wde(e))),l.push(t)}n.additionalProperties=rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&vh(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))}},vR=(t,e,r,o)=>{let n=t._zod.def,i=rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},wR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},bR=Symbol();function KF(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Wt(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),bR):JSON.parse(s)}var _R=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=KF(n.defaultValue,t,e,r,o);s!==bR&&(r.default=s)},SR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=KF(n.defaultValue,t,e,r,o);s!==bR&&(r._prefault=s)},xR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Wt(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},ER=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;rt(s,e,o);let a=e.seen.get(t);a.ref=s},$R=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},IR=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},X_=(t,e,r,o)=>{let n=t._zod.def;rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},kR=(t,e,r,o)=>{let n=t._zod.innerType;rt(n,e,o);let i=e.seen.get(t);i.ref=n},J_={string:HP,number:qP,boolean:ZP,bigint:KP,symbol:WP,null:JP,undefined:GP,void:XP,never:YP,any:QP,unknown:eR,date:tR,enum:rR,literal:nR,nan:oR,template_literal:iR,file:sR,success:aR,custom:cR,function:uR,transform:lR,map:dR,set:fR,array:pR,object:mR,union:G_,intersection:hR,tuple:gR,record:yR,nullable:vR,nonoptional:wR,default:_R,prefault:SR,catch:xR,pipe:ER,readonly:$R,promise:IR,optional:X_,lazy:kR};function hu(t,e){if("_idmap"in t){let o=t,n=Sa({...e,processors:J_}),i={};for(let c of o._idmap.entries()){let[u,l]=c;rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;xa(n,l),ur(s,u,Ea(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=Sa({...e,processors:J_});return rt(t,r),xa(r,t),Ea(r,t)}var Y_=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=Sa({processors:J_,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,xa(this.ctx,e);let o=Ea(this.ctx,e),{"~standard":n,...i}=o;return i}};var WF={};var Od={};vt(Od,{ZodAny:()=>ZR,ZodArray:()=>GR,ZodBase64:()=>yS,ZodBase64URL:()=>vS,ZodBigInt:()=>Rd,ZodBigIntFormat:()=>_S,ZodBoolean:()=>Pd,ZodCIDRv4:()=>hS,ZodCIDRv6:()=>gS,ZodCUID:()=>cS,ZodCUID2:()=>uS,ZodCatch:()=>hC,ZodCodec:()=>kh,ZodCreditCard:()=>FR,ZodCustom:()=>Ah,ZodCustomStringFormat:()=>yu,ZodDate:()=>Sh,ZodDefault:()=>uC,ZodDiscriminatedUnion:()=>YR,ZodE164:()=>wS,ZodEmail:()=>oS,ZodEmoji:()=>sS,ZodEnum:()=>kd,ZodExactOptional:()=>ES,ZodFile:()=>iC,ZodFunction:()=>$C,ZodGUID:()=>iS,ZodIBAN:()=>VR,ZodIPv4:()=>pS,ZodIPv6:()=>mS,ZodISODate:()=>Ia,ZodISODateTime:()=>$a,ZodISODuration:()=>Aa,ZodISOTime:()=>ka,ZodInstanceOf:()=>AC,ZodIntersection:()=>QR,ZodJWT:()=>bS,ZodKSUID:()=>fS,ZodLazy:()=>SC,ZodLiteral:()=>oC,ZodMAC:()=>LR,ZodMap:()=>rC,ZodNaN:()=>yC,ZodNanoID:()=>aS,ZodNever:()=>WR,ZodNonOptional:()=>$S,ZodNull:()=>qR,ZodNullable:()=>cC,ZodNumber:()=>Td,ZodNumberFormat:()=>vu,ZodObject:()=>xh,ZodOptional:()=>wu,ZodPipe:()=>Ih,ZodPrefault:()=>dC,ZodPreprocess:()=>vC,ZodPromise:()=>EC,ZodReadonly:()=>wC,ZodRecord:()=>Id,ZodSet:()=>nC,ZodString:()=>Ad,ZodStringFormat:()=>at,ZodSuccess:()=>mC,ZodSymbol:()=>BR,ZodTemplateLiteral:()=>_C,ZodTransform:()=>sC,ZodTuple:()=>eC,ZodType:()=>we,ZodULID:()=>lS,ZodURL:()=>bh,ZodUUID:()=>Ci,ZodUndefined:()=>HR,ZodUnion:()=>Eh,ZodUnknown:()=>KR,ZodVoid:()=>JR,ZodXID:()=>dS,ZodXor:()=>XR,_ZodString:()=>nS,_default:()=>lC,_function:()=>rB,any:()=>jV,array:()=>Te,base64:()=>yV,base64url:()=>vV,bigint:()=>CV,boolean:()=>Lt,catch:()=>gC,check:()=>nB,cidrv4:()=>hV,cidrv6:()=>gV,codec:()=>YV,creditCard:()=>bV,cuid:()=>aV,cuid2:()=>cV,currencyCode:()=>IV,custom:()=>IS,date:()=>UV,describe:()=>oB,discriminatedUnion:()=>$h,e164:()=>wV,email:()=>XF,emoji:()=>iV,enum:()=>fr,exactOptional:()=>aC,file:()=>WV,float32:()=>AV,float64:()=>TV,function:()=>rB,guid:()=>YF,hash:()=>kV,hex:()=>$V,hostname:()=>EV,httpUrl:()=>oV,iban:()=>_V,instanceof:()=>sB,int:()=>tS,int32:()=>PV,int64:()=>OV,intersection:()=>Cd,invertCodec:()=>QV,ipv4:()=>fV,ipv6:()=>mV,json:()=>cB,jwt:()=>SV,keyof:()=>LV,ksuid:()=>dV,lazy:()=>xC,literal:()=>G,looseObject:()=>dr,looseRecord:()=>HV,mac:()=>pV,map:()=>qV,meta:()=>iB,nan:()=>XV,nanoid:()=>sV,nativeEnum:()=>KV,never:()=>SS,nonoptional:()=>pC,null:()=>_h,nullable:()=>wh,nullish:()=>JV,number:()=>Ke,object:()=>B,optional:()=>st,partialRecord:()=>BV,pipe:()=>rS,prefault:()=>fC,preprocess:()=>Th,promise:()=>tB,readonly:()=>bC,record:()=>ct,refine:()=>IC,set:()=>ZV,strictObject:()=>FV,string:()=>I,stringFormat:()=>xV,stringbool:()=>aB,success:()=>GV,superRefine:()=>kC,symbol:()=>DV,templateLiteral:()=>eB,transform:()=>xS,tuple:()=>tC,uint32:()=>RV,uint64:()=>NV,ulid:()=>uV,undefined:()=>zV,union:()=>nt,unknown:()=>dt,url:()=>nV,uuid:()=>QF,uuidv4:()=>eV,uuidv6:()=>tV,uuidv7:()=>rV,void:()=>MV,xid:()=>lV,xor:()=>VV});var Q_={};vt(Q_,{endsWith:()=>hd,gt:()=>Pi,gte:()=>On,includes:()=>pd,length:()=>mu,lowercase:()=>dd,lt:()=>Ti,lte:()=>Cn,maxLength:()=>pu,maxSize:()=>ba,mime:()=>yd,minLength:()=>js,minSize:()=>Ri,multipleOf:()=>wa,negative:()=>M_,nonnegative:()=>L_,nonpositive:()=>U_,normalize:()=>vd,overwrite:()=>Mo,positive:()=>j_,properties:()=>gd,property:()=>F_,regex:()=>ld,size:()=>fu,slugify:()=>Sd,startsWith:()=>md,toLowerCase:()=>bd,toUpperCase:()=>_d,trim:()=>wd,uppercase:()=>fd});var JF=new WeakSet([Object.prototype,Error.prototype]);function eS(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 GF=(t,e)=>{cT.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);JF.has(r)||(JF.add(r),eS(r,"format",o=>n=>km(o,n)),eS(r,"flatten",o=>n=>Im(o,n)),eS(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,Ll,2)}),eS(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,Ll,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Gde=S("ZodError",GF),yn=S("ZodError",GF,void 0,{Parent:Error});var AR=ql(yn),TR=Zl(yn),PR=Kl(yn),RR=Jl(yn),CR=Sw(yn),OR=xw(yn),NR=Ew(yn),DR=$w(yn),zR=Iw(yn),jR=kw(yn),MR=Aw(yn),UR=Tw(yn);function Yde(){Qt.localeError||Nt(s_())}function gu(){Qt.memoizer||Nt({memoizer:Hm()})}var we=S("ZodType",(t,e)=>(Yde(),ae.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(A.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 Ze(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(IC(t,e))},superRefine(t,e){return this.check(kC(t,e))},overwrite(t){return this.check(Mo(t))},optional(){return st(this)},exactOptional(){return aC(this)},nullable(){return wh(this)},nullish(){return st(wh(this))},nonoptional(t){return pC(this,t)},array(){return Te(this)},or(t){return nt([this,t])},and(t){return Cd(this,t)},transform(t){return rS(this,xS(t))},default(t){return lC(this,t)},prefault(t){return fC(this,t)},catch(t){return gC(this,t)},pipe(t){return rS(this,t)},readonly(){return bC(this)},describe(t){let e=this.clone();return lr.add(e,{description:t}),e},meta(...t){if(t.length===0)return lr.get(this);let e=this.clone();return lr.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 A.hide(this,"~standard",{...Lw(this),jsonSchema:{input:xd(this,"input"),output:xd(this,"output")}})},set"~standard"(t){A.own(this,"~standard",t)},parse:function t(e,r){return AR(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await TR(this,e,r,{callee:t})},safeParse(t,e){return PR(this,t,e)},async safeParseAsync(t,e){return RR(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){A.own(this,"spa",t)},validate(t,e){return Xl(this,t,e)},validateAsync(t,e){return Yl(this,t,e)},encode:function t(e,r){return CR(this,e,r,{callee:t})},decode:function t(e,r){return OR(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await NR(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await DR(this,e,r,{callee:t})},safeEncode(t,e){return zR(this,t,e)},safeDecode(t,e){return jR(this,t,e)},async safeEncodeAsync(t,e){return MR(this,t,e)},async safeDecodeAsync(t,e){return UR(this,t,e)},toJSONSchema(t){return FP(this,{})(t)},get description(){return lr.get(this)?.description},get _def(){return this._zod.def}}),nS=S("_ZodString",(t,e)=>{va.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HP(t,r,o,n)},A.derived({format:t=>Jt(t).format??null,minLength:t=>Jt(t).minimum??null,maxLength:t=>Jt(t).maximum??null},{regex(...t){return this.check(ld(...t))},includes(...t){return this.check(pd(...t))},startsWith(...t){return this.check(md(...t))},endsWith(...t){return this.check(hd(...t))},min(...t){return this.check(js(...t))},max(...t){return this.check(pu(...t))},length(...t){return this.check(mu(...t))},nonempty(...t){return this.check(js(1,...t))},lowercase(t){return this.check(dd(t))},uppercase(t){return this.check(fd(t))},trim(){return this.check(wd())},normalize(...t){return this.check(vd(...t))},toLowerCase(){return this.check(bd())},toUpperCase(){return this.check(_d())},slugify(){return this.check(Sd())}})),Ad=S("ZodString",(t,e)=>{va.init(t,e),nS.init(t,e)},{email(t){return this.check(Zm(oS,t))},url(t){return this.check(ud(bh,t))},jwt(t){return this.check(fh(bS,t))},emoji(t){return this.check(Ym(sS,t))},guid(t){return this.check(Km(iS,t))},uuid(t){return this.check(Wm(Ci,t))},uuidv4(t){return this.check(Jm(Ci,t))},uuidv6(t){return this.check(Gm(Ci,t))},uuidv7(t){return this.check(Xm(Ci,t))},nanoid(t){return this.check(Qm(aS,t))},cuid(t){return this.check(eh(cS,t))},cuid2(t){return this.check(th(uS,t))},ulid(t){return this.check(rh(lS,t))},base64(t){return this.check(uh(yS,t))},base64url(t){return this.check(lh(vS,t))},xid(t){return this.check(nh(dS,t))},ksuid(t){return this.check(oh(fS,t))},ipv4(t){return this.check(ih(pS,t))},ipv6(t){return this.check(sh(mS,t))},cidrv4(t){return this.check(ah(hS,t))},cidrv6(t){return this.check(ch(gS,t))},e164(t){return this.check(dh(wS,t))},datetime(t){return this.check(ph($a,t))},date(t){return this.check(mh(Ia,t))},time(t){return this.check(hh(ka,t))},duration(t){return this.check(gh(Aa,t))}});function I(t){return m_(Ad,t)}var at=S("ZodStringFormat",(t,e)=>{Ge.init(t,e),nS.init(t,e)}),$a=S("ZodISODateTime",(t,e)=>{yP.init(t,e),at.init(t,e)}),Ia=S("ZodISODate",(t,e)=>{vP.init(t,e),at.init(t,e)}),ka=S("ZodISOTime",(t,e)=>{wP.init(t,e),at.init(t,e)}),Aa=S("ZodISODuration",(t,e)=>{bP.init(t,e),at.init(t,e)}),oS=S("ZodEmail",(t,e)=>{Bw.init(t,e),at.init(t,e)});function XF(t){return Zm(oS,t)}var iS=S("ZodGUID",(t,e)=>{Fw.init(t,e),at.init(t,e)});function YF(t){return Km(iS,t)}var Ci=S("ZodUUID",(t,e)=>{Vw.init(t,e),at.init(t,e)});function QF(t){return Wm(Ci,t)}function eV(t){return Jm(Ci,t)}function tV(t){return Gm(Ci,t)}function rV(t){return Xm(Ci,t)}var bh=S("ZodURL",(t,e)=>{Kw.init(t,e),at.init(t,e)});function nV(t){return ud(bh,t)}function oV(t){return ud(bh,{protocol:Am,hostname:RT,...A.normalizeParams(t)})}var sS=S("ZodEmoji",(t,e)=>{Ww.init(t,e),at.init(t,e)});function iV(t){return Ym(sS,t)}var aS=S("ZodNanoID",(t,e)=>{Jw.init(t,e),at.init(t,e)});function sV(t){return Qm(aS,t)}var cS=S("ZodCUID",(t,e)=>{Gw.init(t,e),at.init(t,e)});function aV(t){return eh(cS,t)}var uS=S("ZodCUID2",(t,e)=>{Xw.init(t,e),at.init(t,e)});function cV(t){return th(uS,t)}var lS=S("ZodULID",(t,e)=>{Yw.init(t,e),at.init(t,e)});function uV(t){return rh(lS,t)}var dS=S("ZodXID",(t,e)=>{Qw.init(t,e),at.init(t,e)});function lV(t){return nh(dS,t)}var fS=S("ZodKSUID",(t,e)=>{eb.init(t,e),at.init(t,e)});function dV(t){return oh(fS,t)}var pS=S("ZodIPv4",(t,e)=>{tb.init(t,e),at.init(t,e)});function fV(t){return ih(pS,t)}var LR=S("ZodMAC",(t,e)=>{nb.init(t,e),at.init(t,e)});function pV(t){return h_(LR,t)}var mS=S("ZodIPv6",(t,e)=>{rb.init(t,e),at.init(t,e)});function mV(t){return sh(mS,t)}var hS=S("ZodCIDRv4",(t,e)=>{ob.init(t,e),at.init(t,e)});function hV(t){return ah(hS,t)}var gS=S("ZodCIDRv6",(t,e)=>{sb.init(t,e),at.init(t,e)});function gV(t){return ch(gS,t)}var yS=S("ZodBase64",(t,e)=>{cb.init(t,e),at.init(t,e)});function yV(t){return uh(yS,t)}var vS=S("ZodBase64URL",(t,e)=>{lb.init(t,e),at.init(t,e)});function vV(t){return lh(vS,t)}var wS=S("ZodE164",(t,e)=>{db.init(t,e),at.init(t,e)});function wV(t){return dh(wS,t)}var FR=S("ZodCreditCard",(t,e)=>{pb.init(t,e),at.init(t,e)});function bV(t){return g_(FR,t)}var VR=S("ZodIBAN",(t,e)=>{hb.init(t,e),at.init(t,e)});function _V(t){return y_(VR,t)}var bS=S("ZodJWT",(t,e)=>{yb.init(t,e),at.init(t,e)});function SV(t){return fh(bS,t)}var yu=S("ZodCustomStringFormat",(t,e)=>{vb.init(t,e),at.init(t,e)});function xV(t,e,r={}){return _a(yu,t,e,r)}function EV(t){return _a(yu,"hostname",PT,t)}function $V(t){return _a(yu,"hex",qT,t)}function IV(t){return _a(yu,"currency_code",OT,t)}function kV(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Rn[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return _a(yu,o,n,e)}var Td=S("ZodNumber",(t,e)=>{jm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qP(t,r,o,n),t.isFinite=!0},A.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=Jt(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=Jt(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=Jt(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>Jt(t).format??null},{gt(t,e){return this.check(Pi(t,e))},gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},lt(t,e){return this.check(Ti(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},int(t){return this.check(tS(t))},safe(t){return this.check(tS(t))},positive(t){return this.check(Pi(0,t))},nonnegative(t){return this.check(On(0,t))},negative(t){return this.check(Ti(0,t))},nonpositive(t){return this.check(Cn(0,t))},multipleOf(t,e){return this.check(wa(t,e))},step(t,e){return this.check(wa(t,e))},finite(){return this}}));function Ke(t){return v_(Td,t)}var vu=S("ZodNumberFormat",(t,e)=>{wb.init(t,e),Td.init(t,e)});function tS(t){return w_(vu,t)}function AV(t){return b_(vu,t)}function TV(t){return __(vu,t)}function PV(t){return S_(vu,t)}function RV(t){return x_(vu,t)}var Pd=S("ZodBoolean",(t,e)=>{td.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ZP(t,r,o,n)});function Lt(t){return E_(Pd,t)}var Rd=S("ZodBigInt",(t,e)=>{Mm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>KP(t,r,o,n)},A.derived({minValue:t=>Jt(t).minimum??null,maxValue:t=>Jt(t).maximum??null,format:t=>Jt(t).format??null},{gte(t,e){return this.check(On(t,e))},min(t,e){return this.check(On(t,e))},gt(t,e){return this.check(Pi(t,e))},lt(t,e){return this.check(Ti(t,e))},lte(t,e){return this.check(Cn(t,e))},max(t,e){return this.check(Cn(t,e))},positive(t){return this.check(Pi(BigInt(0),t))},negative(t){return this.check(Ti(BigInt(0),t))},nonpositive(t){return this.check(Cn(BigInt(0),t))},nonnegative(t){return this.check(On(BigInt(0),t))},multipleOf(t,e){return this.check(wa(t,e))}}));function CV(t){return $_(Rd,t)}var _S=S("ZodBigIntFormat",(t,e)=>{bb.init(t,e),Rd.init(t,e)});function OV(t){return I_(_S,t)}function NV(t){return k_(_S,t)}var BR=S("ZodSymbol",(t,e)=>{_b.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WP(t,r,o,n)});function DV(t){return A_(BR,t)}var HR=S("ZodUndefined",(t,e)=>{Sb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>GP(t,r,o,n)});function zV(t){return T_(HR,t)}var qR=S("ZodNull",(t,e)=>{xb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JP(t,r,o,n)});function _h(t){return P_(qR,t)}var ZR=S("ZodAny",(t,e)=>{Eb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>QP(t,r,o,n)});function jV(){return R_(ZR)}var KR=S("ZodUnknown",(t,e)=>{$b.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>eR(t,r,o,n)});function dt(){return C_(KR)}var WR=S("ZodNever",(t,e)=>{Ib.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>YP(t,r,o,n)});function SS(t){return O_(WR,t)}var JR=S("ZodVoid",(t,e)=>{kb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XP(t,r,o,n)});function MV(t){return N_(JR,t)}var Sh=S("ZodDate",(t,e)=>{Ab.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>tR(t,r,o,n),t.min=(r,o)=>t.check(On(r,o)),t.max=(r,o)=>t.check(Cn(r,o))},A.derived({minDate:t=>{let{minimum:e}=Jt(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=Jt(t);return e?new Date(e):null}},{}));function UV(t){return D_(Sh,t)}var GR=S("ZodArray",(t,e)=>{gu(),Tb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pR(t,r,o,n),t.element=e.element},{min(t,e){return this.check(js(t,e))},nonempty(t){return this.check(js(1,t))},max(t,e){return this.check(pu(t,e))},length(t,e){return this.check(mu(t,e))},unwrap(){return this.element}});function Te(t,e){return UP(GR,t,e)}function LV(t){let e=t._zod.def.shape;return fr(Object.keys(e))}var xh=S("ZodObject",(t,e)=>{gu(),_P.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mR(t,r,o,n),A.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return fr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(A.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(A.mergeDefs(this._zod.def,{catchall:dt()}))},loose(){return this.clone(A.mergeDefs(this._zod.def,{catchall:dt()}))},strict(){return this.clone(A.mergeDefs(this._zod.def,{catchall:SS()}))},strip(){return this.clone(A.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return A.extend(this,t)},safeExtend(t){return A.safeExtend(this,t)},merge(t){return A.merge(this,t)},pick(t){return A.pick(this,t)},omit(t){return A.omit(this,t)},partial(...t){return A.partial(wu,this,t[0])},exactPartial(...t){return A.partial(ES,this,t[0],"exactPartial")},required(...t){return A.required($S,this,t[0])}});function B(t,e){let r={type:"object",shape:t??{},...A.normalizeParams(e)};return new xh(r)}function FV(t,e){return new xh({type:"object",shape:t,catchall:SS(),...A.normalizeParams(e)})}function dr(t,e){return new xh({type:"object",shape:t,catchall:dt(),...A.normalizeParams(e)})}var Eh=S("ZodUnion",(t,e)=>{rd.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.options=e.options});function nt(t,e){return new Eh({type:"union",options:t,...A.normalizeParams(e)})}var XR=S("ZodXor",(t,e)=>{Eh.init(t,e),Rb.init(t,e),t._zod.processJSONSchema=(r,o,n)=>G_(t,r,o,n),t.options=e.options});function VV(t,e){return new XR({type:"union",options:t,inclusive:!1,...A.normalizeParams(e)})}var YR=S("ZodDiscriminatedUnion",(t,e)=>{Eh.init(t,e),Cb.init(t,e)});function $h(t,e,r){return new YR({type:"union",options:e,discriminator:t,...A.normalizeParams(r)})}var QR=S("ZodIntersection",(t,e)=>{Ob.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hR(t,r,o,n)});function Cd(t,e){return new QR({type:"intersection",left:t,right:e})}var eC=S("ZodTuple",(t,e)=>{gu(),Um.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gR(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 wu({type:"optional",innerType:e}))})}});function tC(t,e,r){let o=e instanceof ae,n=o?r:e,i=o?e:null;return new eC({type:"tuple",items:t,rest:i,...A.normalizeParams(n)})}var Id=S("ZodRecord",(t,e)=>{gu(),Nb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function ct(t,e,r){return!e||!e._zod?new Id({type:"record",keyType:I(),valueType:t,...A.normalizeParams(e)}):new Id({type:"record",keyType:t,valueType:e,...A.normalizeParams(r)})}function BV(t,e,r){return new Id({type:"record",keyType:t,valueType:e,...A.normalizeParams(r),partial:!0})}function HV(t,e,r){return new Id({type:"record",keyType:t,valueType:e,mode:"loose",...A.normalizeParams(r)})}var rC=S("ZodMap",(t,e)=>{gu(),Db.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>dR(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Ri(...r)),t.nonempty=r=>t.check(Ri(1,r)),t.max=(...r)=>t.check(ba(...r)),t.size=(...r)=>t.check(fu(...r))});function qV(t,e,r){return new rC({type:"map",keyType:t,valueType:e,...A.normalizeParams(r)})}var nC=S("ZodSet",(t,e)=>{gu(),zb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fR(t,r,o,n),t.min=(...r)=>t.check(Ri(...r)),t.nonempty=r=>t.check(Ri(1,r)),t.max=(...r)=>t.check(ba(...r)),t.size=(...r)=>t.check(fu(...r))});function ZV(t,e){return new nC({type:"set",valueType:t,...A.normalizeParams(e)})}var kd=S("ZodEnum",(t,e)=>{jb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(o,n,i)=>rR(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 kd({...e,checks:[],...A.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 kd({...e,checks:[],...A.normalizeParams(n),entries:i})}});function fr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new kd({type:"enum",entries:r,...A.normalizeParams(e)})}function KV(t,e){return new kd({type:"enum",entries:t,...A.normalizeParams(e)})}var oC=S("ZodLiteral",(t,e)=>{Mb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>nR(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 oC({type:"literal",values:Array.isArray(t)?t:[t],...A.normalizeParams(e)})}var iC=S("ZodFile",(t,e)=>{Ub.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>sR(t,r,o,n),t.min=(r,o)=>t.check(Ri(r,o)),t.max=(r,o)=>t.check(ba(r,o)),t.mime=(r,o)=>t.check(yd(Array.isArray(r)?r:[r],o))});function WV(t){return V_(iC,t)}var sC=S("ZodTransform",(t,e)=>{gu(),Lb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>lR(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new ya(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A.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(A.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 xS(t){return new sC({type:"transform",transform:t})}var wu=S("ZodOptional",(t,e)=>{Lm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>X_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function st(t){return new wu({type:"optional",innerType:t})}var ES=S("ZodExactOptional",(t,e)=>{Fb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>X_(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function aC(t){return new ES({type:"optional",innerType:t})}var cC=S("ZodNullable",(t,e)=>{Vb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function wh(t){return new cC({type:"nullable",innerType:t})}function JV(t){return st(wh(t))}var uC=S("ZodDefault",(t,e)=>{Bb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function lC(t,e){return new uC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var dC=S("ZodPrefault",(t,e)=>{Hb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function fC(t,e){return new dC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():A.shallowClone(e)}})}var $S=S("ZodNonOptional",(t,e)=>{qb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function pC(t,e){return new $S({type:"nonoptional",innerType:t,...A.normalizeParams(e)})}var mC=S("ZodSuccess",(t,e)=>{Zb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>aR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function GV(t){return new mC({type:"success",innerType:t})}var hC=S("ZodCatch",(t,e)=>{Kb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function gC(t,e){return new hC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:A.constantCatch(e)})}var yC=S("ZodNaN",(t,e)=>{Wb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>oR(t,r,o,n)});function XV(t){return z_(yC,t)}var Ih=S("ZodPipe",(t,e)=>{Fm.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ER(t,r,o,n),t.in=e.in,t.out=e.out});function rS(t,e){return new Ih({type:"pipe",in:t,out:e})}var kh=S("ZodCodec",(t,e)=>{Ih.init(t,e),nd.init(t,e)});function YV(t,e,r){return new kh({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function QV(t){let e=t._zod.def;return new kh({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var vC=S("ZodPreprocess",(t,e)=>{Ih.init(t,e),xP.init(t,e)}),wC=S("ZodReadonly",(t,e)=>{Jb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$R(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function bC(t){return new wC({type:"readonly",innerType:t})}var _C=S("ZodTemplateLiteral",(t,e)=>{Gb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>iR(t,r,o,n)});function eB(t,e){return new _C({type:"template_literal",parts:t,...A.normalizeParams(e)})}var SC=S("ZodLazy",(t,e)=>{od.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kR(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function xC(t){return new SC({type:"lazy",getter:t})}var EC=S("ZodPromise",(t,e)=>{Yb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IR(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function tB(t){return new EC({type:"promise",innerType:t})}var $C=S("ZodFunction",(t,e)=>{Xb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>uR(t,r,o,n)});function rB(t){return new $C({type:"function",input:Array.isArray(t?.input)?tC(t?.input):t?.input??Te(dt()),output:t?.output??dt()})}var Ah=S("ZodCustom",(t,e)=>{Qb.init(t,e),we.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cR(t,r,o,n)});function nB(t){let e=new it({check:"custom"});return e._zod.check=t,e}function IS(t,e){return B_(Ah,t??(()=>!0),e)}function IC(t,e={}){return H_(Ah,t,e)}function kC(t,e){return q_(t,e)}var oB=Z_,iB=K_,AC=S("ZodInstanceOf",(t,e)=>{Ah.init(t,e)},{properties(t,e){return this.check(gd(t,e))}});function sB(t,e={}){let r=new AC({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...A.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 aB=(...t)=>W_({Codec:kh,Boolean:Pd,String:Ad},...t);function cB(t){let e=xC(()=>nt([I(t),Ke(),Lt(),_h(),Te(e),ct(I(),e)]));return e}function Th(t,e){return new vC({type:"pipe",in:xS(t),out:e})}var Qde={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 efe(t){Nt({customError:t})}function tfe(){return Nt().customError}var TC;TC||(TC={});var bu={};vt(bu,{ZodISODate:()=>Ia,ZodISODateTime:()=>$a,ZodISODuration:()=>Aa,ZodISOTime:()=>ka,date:()=>nfe,datetime:()=>rfe,duration:()=>ife,time:()=>ofe});function rfe(t){return ph($a,t)}function nfe(t){return mh(Ia,t)}function ofe(t){return hh(ka,t)}function ife(t){return gh(Aa,t)}var F={...Od,...Q_,iso:bu},sfe=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 afe(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 uB(t,e){return t.map((r,o)=>o<e?r:r.optional())}function cfe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ufe(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:cfe(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 lfe(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 PC(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=PC(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=PC(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 dfe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),ffe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Ph(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(Ph):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>dfe.has(e)?Ph(r):!ffe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(Ph))}function lB(t){return t===1?"element":"elements"}function pfe(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=PC(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 ${lB(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 ${lB(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function dB(t,e){if(t!==!1)return t===void 0||t===!0?F.any():en(t,e)}var mfe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function fB(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=ufe(n,e),s=en(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 fB(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(mfe)):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"?en(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=en(p,e);ur(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let h of p){let y=en(d[h],e),w=F.string().regex(new RegExp(h));f.push(F.looseRecord(w,y))}let m=[];if(Object.keys(n).length>0&&m.push(F.object(n).passthrough()),m.push(...f),m.length===0)o=F.object({}).passthrough();else if(m.length===1)o=m[0];else{let h=F.intersection(m[0],m[1]);for(let y=2;y<m.length;y++)h=F.intersection(h,m[y]);o=h}if(t.additionalProperties===!1){let h=Object.keys(n),y=p.map(b=>new RegExp(b)),w=o;o=o.check(b=>{if(!Yn(b.value))return;let _=[];for(let E of Object.keys(b.value))h.includes(E)||y.some(k=>k.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 p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=en(p,e)}o=lfe(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=>en(d,e)),c=uB(a,s),u=Array.isArray(i)?void 0:dB(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=>en(d,e)),c=uB(a,s),u=dB(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=en(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=pfe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?en(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 en(t,e){if(typeof t=="boolean")return t?F.any():F.never();let r=fB(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=>en(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=>en(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:en(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=F.intersection(a,en(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&&!Ph(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&&!Ph(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))sfe.has(a)||ur(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function pB(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=afe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??lr};return en(r,i)}var mB=Symbol("z.visit/resolving");function Rh(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===mB)return new od({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,mB);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let m of l){let h=n(u[m]);h!==u[m]&&(d=!0),p[m]=h}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?Ze(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:Ze(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let m=n(f);m!==f&&(l=!0),d.push(m)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?Ze(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:Ze(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:Ze(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?Ze(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:Ze(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:Ze(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:Ze(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:Ze(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return Ze(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 hB(t){return Rh(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:nt(r.options)}})}function hfe(t,e){if(!e?.length)return t;let r=t._zod.def;return Ze(t,Xn(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function gB(t){return hfe(t.out,t.checks)}function gfe(t){return t.in._zod.traits.has("$ZodTransform")?gB(t):t.in}function yB(t){return Rh(t,{pipe:e=>gfe(e._zod.def),default:(e,r)=>r?st(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function vB(t){return Rh(t,{pipe:e=>gB(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var RC={};vt(RC,{bigint:()=>bfe,boolean:()=>wfe,date:()=>_fe,number:()=>vfe,string:()=>yfe});function yfe(t){return OP(Ad,t)}function vfe(t){return DP(Td,t)}function wfe(t){return zP(Pd,t)}function bfe(t){return jP(Rd,t)}function _fe(t){return MP(Sh,t)}var Ch={name:"@tomato414941/foundation",version:"2.1.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 Nd=new TextEncoder,Dd=new TextDecoder,wB=new TextDecoder("utf-8",{fatal:!0}),kS=2**32;function tn(...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 CC(t,e,r){if(e<0||e>=kS)throw new RangeError(`value must be >= 0 and <= ${kS-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OC(t){let e=Math.floor(t/kS),r=t%kS,o=new Uint8Array(8);return CC(o,e,0),CC(o,r,4),o}function AS(t){let e=new Uint8Array(4);return CC(e,t),e}var xfe=/[^\x00-\x7f]/;function pr(t){if(typeof t=="string"&&t.length>=128){if(xfe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return Nd.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 bB(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 _B(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 TS(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Ms=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 _u=class extends Ms{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},ut=class extends Ms{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Ta=class extends Ms{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},M=class extends Ms{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},xt=class extends Ms{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var Oh=class extends Ms{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var PS=class extends Ms{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var Efe="The input to be decoded is not correctly encoded.";function Su(t){try{return _B(typeof t=="string"?t:Dd.decode(t),!0)}catch(e){throw new TypeError(Efe,{cause:e})}}function Tt(t){return bB(typeof t=="string"?Nd.encode(t):t,!0)}function Nn(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function Bt(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 Pa(...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 eo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function vn(t,e,r){try{return Su(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function RS(t,e,r){try{return pr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function zd(t,e,r){let o;try{o=JSON.parse(wB.decode(Su(t)))}catch{throw new e(r)}if(!Bt(o))throw new e(r);return o}var CS={__proto__:null,b64:!0},OS={__proto__:null};function Nh(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 NS(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 Ra(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 ut(`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 DS(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new xt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function xu(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(!Bt(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var $fe=t=>t[Symbol.toStringTag],Ife=(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 Lo(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(Bt(e)){if(s=UC(e),typeof s.kty!="string")throw SB(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(Ife(t,s,r),s.kty==="oct")return Su(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!zC(e))throw SB(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${$fe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(Ca(e))return e;if(a=e,a.type==="secret")return a.export()}NC||=new WeakMap;let c=e,u=NC.get(c);if(u?.[o])return u[o];if(u||NC.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=kfe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await Md(t,s)}var NC,kfe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function jS(t){if(!Ca(t))throw new Error("CryptoKey instance expected")}var Ca=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},DC=t=>t?.[Symbol.toStringTag]==="KeyObject",zC=t=>Ca(t)||DC(t);function xB(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 Us=(t,...e)=>xB("Key must be ",t,...e);function SB(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(xB(`Key for the ${t} algorithm must be `,e,...o))}var zS=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function jC(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function jd(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 MC(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw zS(e.name);if(e.hash&&o.hash?.name!==e.hash)throw zS(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw zS(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw zS(e.length,"algorithm.length");jC(t,r)}function MS(t){return{__proto__:null,...t}}function UC(t){let e=MS(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 US(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function Md(t,e,r){if(!t.kty.includes(e.kty))throw new ut('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 Fo(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),MC(t,e,r),t}var Eu=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function LS(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 Afe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function EB(t,e){if(e.length<<3!==t.ivBits)throw new M("Invalid Initialization Vector length")}async function $B(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Us(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 IB(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function Tfe(t,e,r,o,n){let[i,s,a]=await $B(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=tn(n,o,c,OC(n.length*8)),l=await IB(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function Pfe(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 Rfe(t,e,r,o,n,i){let[s,a,c]=await $B(t,e,"decrypt"),u=tn(i,o,r,OC(i.length*8)),l=await IB(a,u,c);try{if(await Pfe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Ta}async function FS(t,e,r,o,n){if(!Ca(r)&&!(r instanceof Uint8Array))throw new TypeError(Us(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?EB(t,o):o=Afe(t),r instanceof Uint8Array&&LS(r,t.cekBits),t.cbc)return Tfe(t,e,r,o,n);let i=await Fo(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 VS(t,e,r,o,n,i){if(!Ca(e)&&!(e instanceof Uint8Array))throw new TypeError(Us(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(EB(t,o),e instanceof Uint8Array&&LS(e,t.cekBits),t.cbc)return Rfe(t,e,r,o,n,i);let s=await Fo(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,tn(r,n)))}catch{throw new Ta}}function Dh(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var Cfe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Ofe=[[],["deriveBits"]],qS=[[],[]];function BS(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:Cfe,ops:["wrapKey","unwrapKey"]}}function HS(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 ut('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:Ofe,ops:[void 0,"deriveBits"]}}function Ud(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:qS,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function LC(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:qS,ops:["deriveBits","deriveBits"]}}var Ls=Dh({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:qS,ops:["encrypt","decrypt"]},"RSA-OAEP":BS(1),"RSA-OAEP-256":BS(256),"RSA-OAEP-384":BS(384),"RSA-OAEP-512":BS(512),"ECDH-ES":HS("direct-key-agreement"),"ECDH-ES+A128KW":HS("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":HS("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":HS("key-agreement-with-key-wrapping"),A128KW:Ud(128),A192KW:Ud(192),A256KW:Ud(256),A128GCMKW:Ud(128,!0),A192GCMKW:Ud(192,!0),A256GCMKW:Ud(256,!0),"PBES2-HS256+A128KW":LC(),"PBES2-HS384+A192KW":LC(),"PBES2-HS512+A256KW":LC()}),Nfe=["encrypt","decrypt"];function Ld(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:qS,ops:Nfe,cekBits:t,ivBits:e?128:96,cbc:e}}var Dfe=Dh({A128GCM:Ld(128),A192GCM:Ld(192),A256GCM:Ld(256),"A128CBC-HS256":Ld(256,!0),"A192CBC-HS384":Ld(384,!0),"A256CBC-HS512":Ld(512,!0)});function kB(t,e){throw new ut(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Vo(t){return(typeof t=="string"?Ls[t]:void 0)??kB("alg","Algorithm")}function Bo(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function $u(t){return(typeof t=="string"?Dfe[t]:void 0)??kB("enc","Encryption Algorithm")}function AB(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");jC(t,e)}async function zfe(t,e,r){let o=await Fo(e,Vo(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 jfe(t,e,r){let o=await Fo(e,Vo(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 PB(t,e,r){MC(e,Vo(t).subtle,r),jd(t,e)}async function RB(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=tn(pr(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 Fo(o,Vo(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function FC(t){return tn(AS(t.length),t)}async function Mfe(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 TS("sha256",tn(AS(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function CB(t,e,r,o,n=new Uint8Array,i=new Uint8Array){AB(t),AB(e,"deriveBits");let s=tn(FC(pr(r)),FC(n),FC(i),AS(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 Mfe(a,o,s)}function OB(t){jS(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new ut("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function ZS(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 vn(r,e,M)}}function NB(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 Ufe(t){if(t===void 0)throw new M("JWE Encrypted Key missing")}function TB(t){if(t!==void 0)throw new M("Encountered unexpected JWE Encrypted Key")}function Lfe(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 DB(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return TB(o),r;let c=a==="direct-key-agreement";switch(c?TB(o):Ufe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!Bt(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');OB(r);let l=await Md(t,u),d=ZS(n,"apu"),p=ZS(n,"apv");NB(d,p);let f=await CB(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return jS(r),PB(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');Lfe(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=vn(n.p2s,"p2s",M);r=await RB(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=vn(n.iv,"iv",M),l=vn(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 VS($u(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return jfe(s.slice(-6),r,o)}async function KS(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=Bo(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Lo(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??Eu(e):void 0;l&&LS(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{OB(u);let{apu:f,apv:m}=i;f!==void 0&&Nn(f,'"apu"'),m!==void 0&&Nn(m,'"apv"');let h=f??ZS(o,"apu"),y=m??ZS(o,"apv");NB(h,y);let w;i.epk!==void 0?w=await Lo(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:k,crv:O,kty:H}=await b.exportKey("jwk",_),te=a==="direct-key-agreement",ke=await CB(u,w,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),h,y),Ee={x:E,crv:O,kty:H};if(H==="EC"&&(Ee.y=k),p={epk:Ee},f!==void 0&&(p.apu=Tt(f)),m!==void 0&&(p.apv=Tt(m)),te)return[ke,void 0,p];u=ke;break}case"RSA-OAEP":{jS(u),PB(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:m=crypto.getRandomValues(new Uint8Array(16))}=i;u=await RB(m,s,f,u),p={p2c:f,p2s:Tt(m)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let m=await FS($u(s.slice(0,-2)),l,u,f,new Uint8Array);d=m.ciphertext,p={iv:Tt(m.iv),tag:Tt(m.tag)}}}if(d??=await zfe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function WS(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new ut('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 zB(t){if(typeof globalThis[t]>"u")throw new ut(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function jB(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 tn(...n)}async function MB(t){return zB("CompressionStream"),jB(new CompressionStream("deflate-raw"),t)}async function UB(t,e){return zB("DecompressionStream"),jB(new DecompressionStream("deflate-raw"),t,e)}function LB(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&&!Bt(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 FB(t){let e,r;try{let{header:o}=t;if(Bt(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 VB(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&&!Bt(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 VC(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=zd(e,M,"JWE Protected Header is invalid")),[s,vn(r,"ciphertext",M),o!==void 0?vn(o,"iv",M):void 0,n!==void 0?vn(n,"tag",M):void 0,RS((e??"")+(i!==void 0?`.${i}`:""),"aad",M)]}function JS(t){return[t&&Nh("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&Nh("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function BC(t,e,r,o=VC(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Pa(n,u,l))throw new M("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,m,h,y,w]=e,{encrypted_key:b}=t;Ra(M,OS,h,n,p),WS(p,n);let{alg:_,enc:E}=p;if(typeof _!="string"||!_)throw new M("missing JWE Algorithm (alg) in JWE Header");let k=Ls[_];if(b===""&&(!k||!Bo(k)))throw new M("JWE Encrypted Key incorrect type");let O=k?.mode==="integrated-encryption";if(!O&&(typeof E!="string"||!E))throw new M("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(_)||!f&&_.startsWith("PBES2"))throw new _u('"alg" (Algorithm) Header Parameter value not allowed');let H;if(O){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 _u('"enc" (Encryption Algorithm) Header Parameter value not allowed');H=$u(E)}let te;if(b!==void 0)try{te=vn(b,"encrypted_key",M)}catch(Ae){if(!k||!Bo(k))throw Ae;te=new Uint8Array}let ke=!1;typeof r=="function"&&(r=await r(n,t),ke=!0);let Ee=k??Vo(_);Bo(Ee)&&te===void 0&&(te=new Uint8Array);let tt=await Lo(Ee.mode==="direct-encryption"?H:Ee,r,"decrypt"),Ve;if(Ee.mode==="integrated-encryption")Ve=await Ee.decrypt(tt,te,i,c,n,p);else{let Ae=H,J;try{J=await DB(Ee,Ae,tt,te,p,y),Bo(Ee)&&J instanceof Uint8Array&&J.byteLength<<3!==Ae.cekBits&&(J=Eu(Ae))}catch(kt){if(kt instanceof TypeError||kt instanceof M||kt instanceof ut)throw kt;J=Eu(Ae)}Ve=await VS(Ae,J,i,s,a,c)}if(p.zip==="DEF"){let Ae=w??25e4;if(Ae===0)throw new ut('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Ae!==1/0&&(!Number.isSafeInteger(Ae)||Ae<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");Ve=await UB(Ve,Ae).catch(J=>{throw J instanceof M?J:new M("Failed to decompress plaintext",{cause:J})})}return{plaintext:Ve,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:vn(d,"aad",M)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...ke&&{key:tt}}}async function BB(t,e,r){if(t instanceof Uint8Array&&(t=Dd.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 BC({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function zh(t,e,r){return BB(t,JS(r),e)}async function HC(t,e,r){if(!Bt(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(Bt))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=JS(r),s=LB(t),a=VC(s)}catch{throw new Ta}let c=n.map(u=>FB(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Ls[l]:void 0;if(d&&!Bo(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 VB(l),await BC(l,i,e,a)}catch{}throw new Ta}function GS(t,e,r){if(!Pa(t,e,r))throw new M("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function qC(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&&Nn(s,"JWE Additional Authenticated Data"),a!==void 0&&Nn(a,"JWE Content Encryption Key"),c!==void 0&&Nn(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=xu(M,o)[0],t[1]=o),n!==void 0&&(n=xu(M,n)[0],t[2]=n),!r&&i!==void 0&&(i=xu(M,i)[0],t[3]=i),u!==void 0&&!Bt(u))throw new TypeError("JWE Key Management Parameters must be an object");GS(o,n,i);let d={...o,...n,...i};NS(M,o),Ra(M,OS,l,o,d),WS(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new M('JWE "alg" (Algorithm) Header Parameter missing or invalid');let m=Ls[p];if(m?.mode==="integrated-encryption"){if(f!==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 ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,m]}if(typeof f!="string"||!f)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,$u(f),m]}async function ZC(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,m]=t,h=a,y=c,w=i??Vo(o.alg),b,_,E;w.mode==="integrated-encryption"?E=await Lo(w,r,"encrypt"):[E,b,_]=await KS(w,n,r,o,d,f),_&&(m?y=y?{...y,..._}:_:h=h?{...h,..._}:_,GS(h,y,u));let k=h?Tt(JSON.stringify(h)):"",O=l?.byteLength?Tt(l):void 0,H=pr(O?`${k}.${O}`:k),te=s;o.zip==="DEF"&&(te=await MB(te).catch(Ae=>{throw new M("Failed to compress plaintext",{cause:Ae})}));let ke,Ee,tt;w.mode==="integrated-encryption"?[b,ke]=await w.encrypt(E,te,H,h,o,f):{ciphertext:ke,tag:Ee,iv:tt}=await FS(n,te,E,p,H);let Ve={ciphertext:Tt(ke)};return tt&&(Ve.iv=Tt(tt)),Ee&&(Ve.tag=Tt(Ee)),b?.byteLength&&(Ve.encrypted_key=Tt(b)),O&&(Ve.aad=O),h&&(Ve.protected=k),u&&(Ve.unprotected=u),y&&(Ve.header=y),Ve}async function HB(t,e,r){return ZC(t,qC(t,r),e)}function qB(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var KC=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return eo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return eo(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}},jh=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new KC(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return eo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return eo(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");Nn(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let m of this.#t){let[h,y,w,b]=m.state,_=[this.#e,o,h,n,this.#o,void 0,void 0,y,b,e],E=qC(_,void 0,i.length>0);i.length||(o=_[1],n=_[3]),i.push([_,E,w]);let[{alg:k,enc:O},,H]=E;if(e&&H&&!Bo(H))throw new M(`"${k}" alg may only have a single recipient`);if(!r)r=O;else if(r!==O)throw new M('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,m]of i)m[2]??=Vo(m[0].alg);let[s,a,c]=i[0],u=e?Eu(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await ZC(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let m=1;m<i.length;m++){let[h,[y,w,b],_]=i[m],E=h[2],[,k,O]=await KS(b,w,_,y,u,h[7]),H={encrypted_key:Tt(k)};if(E||O){let te={...E,...O};O&&GS(h[1],te,h[3]),H.header=te}f.recipients.push(H)}return f}};var Mh=[["verify"],["sign"]];function WC(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Mh}}function Fd(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:Mh,minRsaBits:2048}}function JC(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Mh}}function ZB(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Mh}}function GC(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Mh}}var XC=Dh({HS256:WC(256),HS384:WC(384),HS512:WC(512),RS256:Fd(256),RS384:Fd(384),RS512:Fd(512),PS256:Fd(256,32),PS384:Fd(384,48),PS512:Fd(512,64),ES256:JC("P-256",256),ES384:JC("P-384",384),ES512:JC("P-521",512),EdDSA:ZB(),Ed25519:ZB(),"ML-DSA-44":GC(44),"ML-DSA-65":GC(65),"ML-DSA-87":GC(87)});function XS(t){let e=typeof t=="string"?XC[t]:void 0;if(!e)throw new ut(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function KB(t){return[t&&Nh("algorithms",t.algorithms),t?.crit]}function Ffe(t){return t===void 0?{}:zd(t,xt,"JWS Protected Header is invalid")}function Vfe(t){try{return pr(t)}catch{throw new xt("JWS Compact Serialization payload must use only ASCII characters")}}async function Bfe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??Ffe(i);if(!Pa(c,s))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=DS(c,Ra(xt,CS,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new _u('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new xt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new xt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let m=XS(d),h=tn(i!==void 0?pr(i):new Uint8Array,pr("."),typeof p=="string"?e[2]??=RS(p,"payload",xt):p),y=vn(t.signature,"signature",xt),w=await Lo(m,r,"verify"),b=await Fo(w,m.subtle,"verify");m.minRsaBits&&jd(m.alg,b);let _=!1;try{_=await crypto.subtle.verify(m.signing,b,y,h)}catch{}if(!_)throw new PS;let E={payload:typeof p=="string"?vn(p,"payload",xt):p};return i!==void 0&&(E.protectedHeader=c),s!==void 0&&(E.unprotectedHeader=s),f?[{...E,key:w},l]:[E,l]}async function WB(t,e,r){if(t instanceof Uint8Array&&(t=Dd.decode(t)),typeof t!="string")throw new xt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new xt("Invalid Compact JWS");return Bfe({payload:n,protected:o,signature:i},e,r,Vfe)}async function YC(t,e,r){let[o]=await WB(t,KB(r),e);return o}var Vd=class{#e;constructor(e){Nn(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return eo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return eo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return eo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return eo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return qB(await HB([...this.#e],e,r))}};async function Hfe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let w=xu(xt,n);n=w[0],a=Tt(w[1])}if(i!==void 0&&(i=xu(xt,i)[0]),!n&&!i)throw new xt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Pa(n,i))throw new xt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};NS(xt,n);let u=DS(n,Ra(xt,CS,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new xt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=XS(l),p="",f=o,m;if(u){let w=t[4];w?(p=w[0]??=Tt(o),f=w[1]??=pr(p)):(p=Tt(o),m=Nd.encode(`${a}.${p}`))}m??=tn(pr(a),pr("."),f);let h=await Fo(await Lo(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&jd(d.alg,h);let y={signature:Tt(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:p};return n&&(y.protected=a),i&&(y.header=i),[y,u]}async function JB(t,e,r,o,n){let[i]=await Hfe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Uh=class{#e;#t;constructor(e){Nn(e,"payload"),this.#e=e}setProtectedHeader(e){return eo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return JB(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var QC='"alg" (Algorithm)';function eO(t='JWK "alg" (Algorithm) Parameter'){throw new ut(`Invalid or unsupported ${t} value`)}function Lh(t,e){return(typeof t=="string"?XC[t]??Ls[t]:void 0)??eO(e)}async function Oa(t){if(DC(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:Tt(t)};if(!Ca(t))throw new TypeError(Us(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 Fs=(t,e)=>{if(typeof t!="string"||!t)throw new Oh(`${e} missing or invalid`)};async function tO(t,e){let r;if(Bt(t)){if(r=MS(t),typeof r.kty!="string")throw new TypeError(Us(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(zC(t))r=MS(await Oa(t));else throw new TypeError(Us(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":Fs(r.alg,'"alg" (Algorithm) Parameter'),Fs(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Fs(r.crv,'"crv" (Curve) Parameter'),Fs(r.x,'"x" (X Coordinate) Parameter'),Fs(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Fs(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Fs(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Fs(r.e,'"e" (Exponent) Parameter'),Fs(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 Oh('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new ut('"kty" (Key Type) Parameter missing or unsupported')}let n=pr(JSON.stringify(o));return Tt(await TS(e,n))}async function to(t,e,r){if(!Bt(t))throw new TypeError("JWK must be an object");let o=UC(t),n=US(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 Su(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 Md(Lh(e),o,n)}case"RSA":case"EC":case"OKP":return Md(Lh(e),o,n);default:throw new ut('Unsupported "kty" (Key Type) Parameter value')}}function rO(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 zd(e,TypeError,r)}function qfe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new ut("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Fh(t,e){let r=US(e?.extractable),o=Lh(t,QC);o.secret&&eO(QC);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new ut("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 ut(`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:qfe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}typeof window<"u"&&g.config({jitless:!0});var $=g.uuid(),le=g.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),ot=g.iso.datetime(),ro=g.json(),Iu=g.record(g.string(),ro),XB=g.enum(["ja","en"]),YB=g.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var QB=g.enum(["variable","connection","service","method","app","object","environment","function"]),Nr=g.object({kty:g.literal("EC"),crv:g.literal("P-256"),x:g.string().min(40).max(50),y:g.string().min(40).max(50)}).strict(),Zfe=g.object({alg:g.literal("dir"),enc:g.literal("A256GCM"),sub:$}).strict(),ex=g.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(rO(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ho=g.object({protected:g.string().max(2048),iv:g.string().max(64),ciphertext:g.string().max(2e6),tag:g.string().max(64),aad:g.string().max(2048).optional(),recipients:g.array(g.object({encrypted_key:g.string().max(2048),header:g.object({kid:$,epk:Nr.optional(),alg:g.string().optional()}).passthrough()})).min(1).max(100)}).strict(),T2e=g.object({id:$,name:le,publicKey:Nr}),Bd=g.object({id:$,name:le,owner:g.object({id:$,name:le}).nullable(),createdAt:ot,permissions:g.array(YB),createKinds:g.array(QB),publicKey:Nr.nullable()}),eH=g.object({id:$,kind:g.enum(["passkey","email","key"]),name:g.string(),createdAt:ot,lastUsedAt:ot.nullable(),expiresAt:ot.nullable(),canOpen:g.boolean()}),tH=g.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),Kfe=g.object({subjectId:$,relation:tH,objectId:$}).strict(),P2e=Kfe.extend({objectType:g.enum(["principal",...QB.options]),subjectName:le,objectName:le,createdAt:ot}),R2e=g.object({error:g.object({code:g.string(),message:g.string(),details:ro.optional()})}),C2e=g.object({ok:g.literal(!0)}),rH=g.object({name:g.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:g.string(),secret:g.boolean().optional(),required:g.boolean().optional(),placeholder:g.string().optional(),note:g.string().optional(),pattern:g.string().optional()}),nH=g.record(g.string().regex(/^[A-Z_][A-Z0-9_]*$/),g.string()),Wfe=g.object({values:g.array(g.object({id:g.string(),name:g.string(),description:g.string().optional()})).optional(),default:g.array(g.string()).default([]),separator:g.string().default(" "),docs:g.url().optional()}),YS=g.string().min(1).max(4096),GB=g.union([g.string(),g.array(g.string()).min(1)]),oH=g.object({issuer:g.url().optional(),authorizeUrl:YS,tokenUrl:YS,identity:g.object({url:YS.optional(),from:g.enum(["token","app"]).optional(),method:g.enum(["GET","POST"]).default("GET"),id:GB.default("/id"),name:GB.default("/name"),headers:g.record(g.string(),g.string()).default({})}).optional(),revoke:g.object({url:YS,style:g.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:g.enum(["body","basic","none"]).optional()}).optional(),clientAuth:g.enum(["body","basic","none"]).default("body"),pkce:g.boolean().default(!0),tokenFormat:g.enum(["form","json"]).default("form"),okPointer:g.string().optional(),authorizeParams:g.record(g.string(),g.string()).default({}),tokenParams:g.record(g.string(),g.string()).default({}),defaults:g.record(g.string(),g.string()).default({}),scopes:Wfe.default({default:[],separator:" "}),fields:g.array(rH).default([]),outputs:nH.default({ACCESS_TOKEN:"/accessToken"}),adapter:g.enum(["google","github","ebay","openrouter","cloudflare","slack"]).optional(),keep:g.array(g.string()).default([]),hint:g.string().optional()}),iH=g.object({fields:g.array(rH).min(1),outputs:nH,console:g.url().optional(),instructions:g.string().optional(),hint:g.string().optional()}),oO=g.enum(["oauth","token","role"]),sH=g.object({kind:g.literal("aws"),hint:g.string().optional()}),iO={name:le,docs:g.url().optional(),console:g.url().optional()},aH=g.object({...iO,kind:g.literal("oauth"),config:oH}).strict(),cH=g.object({...iO,kind:g.literal("token"),config:iH}).strict(),uH=g.object({...iO,kind:g.literal("role"),config:sH}).strict(),ku=g.discriminatedUnion("kind",[aH,cH,uH]),nO={id:g.string().min(1),builtin:g.boolean(),availability:g.enum(["ready","app-required","unavailable"])},sO=g.discriminatedUnion("kind",[aH.extend(nO),cH.extend(nO),uH.extend(nO)]),aO=g.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),tx=g.object({name:le,logo:g.string().regex(/^[a-z0-9-]+$/).optional(),api:g.url().optional(),docs:g.url().optional(),console:g.url().optional()}).strict(),Jfe=tx.extend({auth:g.object({oauth:oH.optional(),token:iH.optional(),role:sH.optional()}).strict()}).strict(),Gfe=tx.extend({methods:g.record(aO,g.string().min(1))}).strict(),Xfe=tx.extend({methods:g.record(aO,g.union([g.string().min(1),ku]))}).strict(),lH=g.union([Xfe,Jfe]),O2e=tx.extend({id:g.string(),builtin:g.boolean(),methods:g.record(aO,sO)}),dH=g.object({id:$,output:g.string().min(1).max(100).optional()}).strict(),cO=g.object({name:g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:dH,format:g.enum(["text","file","json"]).default("text"),pointer:g.string().optional()}).strict(),Yfe=g.object({pointer:g.string().max(500),parts:g.array(g.union([g.string().max(8192),dH])).min(1).max(32)}).strict(),Au=g.object({url:g.string().max(4096),method:g.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:g.record(g.string(),g.string().max(8192)).default({}),body:g.string().max(1e6).optional(),json:ro.optional(),form:g.record(g.string(),g.string()).optional(),bindings:g.array(Yfe).max(32).default([])}).strict(),Vh=g.object({description:g.string().max(2e3).default(""),request:Au,parameters:g.array(g.object({name:g.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:g.string().max(100),required:g.boolean().default(!0),default:g.string().optional()})).max(32).default([]),save:g.record(g.string(),le).default({}),outputOwnerId:$.optional()}).strict(),Na={id:$,ownerId:$,name:le,createdAt:ot,updatedAt:ot,version:g.number().int().positive(),permissions:g.array(YB)},Qfe=g.enum(["starting","running","stopping","stopped","failed"]),epe=g.object({state:g.enum(["pending","failed","complete"]),error:g.string().nullable()}),tpe=g.object({idleSeconds:g.number().int().min(60).max(86400).default(3600),maxSeconds:g.number().int().min(60).max(86400).default(3600)}).strict(),fH=g.object({image:g.string().min(1).max(300).optional(),size:g.enum(["small","medium","large"]).default("small"),lifetime:tpe.default({idleSeconds:3600,maxSeconds:3600})}).strict(),uO={recipients:g.array($).default([]),executors:g.array($).default([]),custodyRevision:g.number().int().positive().nullable().default(null)},rpe=g.object({...Na,kind:g.literal("variable"),data:g.object({...uO,bytes:g.number().int().nonnegative()})}),npe=g.object({...Na,kind:g.literal("connection"),data:g.object({...uO,methodId:g.string(),methodName:g.string(),methodKind:oO,services:g.array(g.object({id:g.string(),name:le})).default([]),account:g.string(),accountId:g.string().nullable().default(null),accountVerified:g.boolean().default(!1),scopes:g.array(g.string()),scopesStatus:g.enum(["unknown","requested","reported"]).default("unknown"),outputs:g.array(g.string()),state:g.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:$.nullable(),generation:$.optional(),authorizationDigest:g.string().optional()})}),ope=g.object({...Na,kind:g.literal("service"),data:Gfe}),ipe=g.object({...Na,kind:g.literal("method"),data:ku}),spe=g.object({...Na,kind:g.literal("app"),data:g.object({...uO,methodId:g.string(),clientId:g.string(),fields:g.record(g.string(),g.string()).default({}),generation:$.optional()})}),ape=g.object({...Na,kind:g.literal("object"),data:g.object({size:g.number().int().nonnegative(),contentType:g.string()})}),cpe=g.object({...Na,kind:g.literal("environment"),data:fH.extend({executorId:$.optional(),operatorId:$.optional(),driver:g.enum(["attached","managed"]).optional(),capabilities:g.array(g.string()).optional(),isolation:g.enum(["process","container"]).optional(),manifestDigest:g.string().optional(),awsPrincipal:g.string().optional(),state:Qfe,deletion:epe.optional(),startedAt:ot.nullable(),stoppedAt:ot.nullable(),lastActiveAt:ot,error:g.string().nullable()})}),upe=g.object({...Na,kind:g.literal("function"),data:Vh}),no=g.discriminatedUnion("kind",[rpe,npe,ope,ipe,spe,ape,cpe,upe]),N2e=g.discriminatedUnion("kind",[g.object({kind:g.literal("service"),name:le,definition:lH}).strict(),g.object({kind:g.literal("method"),name:le,definition:ku}).strict(),g.object({kind:g.literal("environment"),name:le.optional(),options:fH}).strict(),g.object({kind:g.literal("function"),name:le,definition:Vh}).strict()]),D2e=g.object({version:g.number().int().positive(),name:le.optional(),definition:g.union([lH,ku,Vh]).optional()}).strict(),rx=g.object({command:g.array(g.string().max(8192)).min(1).max(100),stdin:g.string().max(1e6).optional(),timeoutSeconds:g.number().int().min(1).max(3600).default(60),inputs:g.array(cO).max(32).default([])}).strict(),pH=g.object({method:g.enum(["GET","POST","PUT","PATCH","DELETE","CONNECT"]),path:g.string().startsWith("/api/").max(2048),body:ro.optional(),inputs:g.array(g.object({pointer:g.string(),label:g.string().min(1).max(100),secret:g.boolean().default(!1),multiline:g.boolean().default(!1),site:g.url().optional()})).max(16).default([])}).strict(),lpe=g.object({ja:g.string(),en:g.string()}).strict(),mH=g.object({ownerId:g.union([$,g.literal("$approver")]),methodId:g.string().min(1).max(200),connectionId:$.optional(),environmentId:$.optional(),name:le.optional()}).strict(),hH=g.object({to:$.optional(),message:g.string().max(1e3).default(""),operations:g.array(pH).min(1).max(8),expiresInMinutes:g.number().int().min(1).max(1440).default(30)}).strict(),QS=g.object({id:$,name:le}),dpe=g.discriminatedUnion("kind",[g.object({kind:g.literal("line"),subject:QS,relation:tH,object:QS}),g.object({kind:g.literal("transfer"),item:QS,to:QS})]),Da=g.object({id:$,from:Bd.pick({id:!0,name:!0}),to:Bd.pick({id:!0,name:!0}).nullable(),message:g.string(),proposal:dpe.nullable(),operations:g.array(pH.extend({title:lpe})),state:g.enum(["pending","running","approved","declined","cancelled","expired"]),results:g.array(ro.nullable()),createdAt:ot,expiresAt:ot,url:g.url(),code:g.string().optional(),continueUrl:g.url().nullable(),returnUrl:g.url().nullable(),refreshUrl:g.url().nullable(),canRespond:g.boolean()}),z2e=g.object({id:$,name:le,publicKey:Nr,state:g.enum(["pending","approving","approved"]),principalId:$.nullable(),createdAt:ot,expiresAt:ot}),j2e=g.object({available:g.boolean(),required:g.boolean(),active:g.boolean(),payer:Bd.pick({id:!0,name:!0}).nullable()}),M2e=g.object({storageBytes:g.number().nonnegative(),storageLimit:g.number().positive(),computeSeconds:g.number().nonnegative(),computeLimit:g.number().positive(),month:g.string()}),U2e=g.object({id:g.string(),actorId:$.nullable(),action:g.string(),targetId:$.nullable(),createdAt:ot,details:Iu}),L2e=g.object({returnUrl:g.url().optional(),refreshUrl:g.url().optional()}).strict(),za=t=>g.object({items:g.array(t),next:g.string().nullable().default(null)}),F2e=g.object({id:$}),V2e=g.object({owner:$}),fpe=g.object({limit:g.coerce.number().int().min(1).max(200).default(100),after:g.string().optional()}),B2e=fpe.extend({object:$.optional(),subject:$.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var ppe=new TextEncoder,mpe=new TextDecoder,Bh="ECDH-ES+A256KW",lO="A256GCM",ft=t=>ppe.encode(t),Tu=t=>mpe.decode(t);function ja(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 gH(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function nx(){let t=await Fh(Bh,{crv:"P-256",extractable:!0});return{publicKey:Nr.parse(await Oa(t.publicKey)),privateKey:await Oa(t.privateKey)}}async function Pu(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 jh(t).setProtectedHeader({enc:lO}).setAdditionalAuthenticatedData(ft(r));for(let n of e)o.addRecipient(await to(n.publicKey,Bh)).setUnprotectedHeader({alg:Bh,kid:n.id});return Ho.parse(await o.encrypt())}async function Oi(t,e,r,o){if(t.aad!==ja(ft(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 to(e,Bh);return(await HC({...t,recipients:[n]},i,{keyManagementAlgorithms:[Bh],contentEncryptionAlgorithms:[lO]})).plaintext}async function hpe(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:ft("Foundation"),info:ft("passkey encryption key")},e,256))}async function yH(t,e,r){let o=await zh(t,await hpe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[lO]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Tu(o.plaintext))}var mr=g.string().regex(/^[A-Za-z0-9_-]{43}$/),Dn=g.string().min(100).max(4e6),vH=Nr.extend({d:g.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Hh=g.object({encryption:vH,signing:vH}).strict(),hr=g.object({id:$,principalId:$,generation:g.number().int().positive(),previous:mr.nullable(),encryption:Nr,signing:Nr}).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 Hd(t){return tO(Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function ye(t){return ja(new Uint8Array(await crypto.subtle.digest("SHA-256",ft(R(t)))))}async function ix(){let[t,e]=await Promise.all([nx(),Fh("ES256",{crv:"P-256",extractable:!0})]),r=await Oa(e.privateKey);return Hh.parse({encryption:t.privateKey,signing:r})}function ox(t){return Nr.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function sx(t,e){return hr.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:ox(e.encryption),signing:ox(e.signing)})}async function wn(t,e,r){let o=e instanceof CryptoKey?e:await to(e,"ES256");return new Uh(ft(R(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function oo(t,e,r,o){if(R(await dO(e,r,o))!==R(t))throw new Error("The signature does not authorize this content.")}async function dO(t,e,r){let o=await YC(t,await to(Nr.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 Ni=g.object({binding:hr,signature:Dn}).strict();async function qh(t,e){if(await Ma(t),await Hd(e.encryption)!==await Hd(t.encryption)||await Hd(e.signing)!==await Hd(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await wn(t,e.signing,"key-binding")}}async function Ma(t){let e=hr.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await Hd(e.encryption)===await Hd(e.signing))throw new Error("Use separate encryption and signing keys.");await to(e.encryption,"ECDH-ES+A256KW"),await to(e.signing,"ES256")}async function fO(t){let{binding:e,signature:r}=Ni.parse(t);return await Ma(e),await oo(e,r,e.signing,"key-binding"),e}var qd=g.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."),Me={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632"},gpe=g.enum([Me.value,Me.tokenSet,Me.clientCredential]),pe={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},ax=g.enum([pe.http,pe.command,pe.function,pe.connect,pe.refresh,pe.revoke]);var ype={[Me.value]:[pe.http,pe.command,pe.function],[Me.tokenSet]:[pe.http,pe.command,pe.function,pe.refresh,pe.revoke],[Me.clientCredential]:[pe.connect,pe.refresh,pe.revoke]},pO=t=>ype[t],mO=t=>t===Me.tokenSet,vpe=g.object({actor:hr,executor:hr,operations:g.array(ax).min(1).max(6),functionDigests:g.array(mr).max(100).default([]),origins:g.array(qd).max(100).default([]),callerProgram:g.boolean().default(!1),expiresAt:ot}).strict(),Di=g.object({format:g.literal(2),origin:qd,id:$,ownerId:$,contentType:gpe,revision:g.number().int().positive(),authorities:g.array(hr).min(1).max(100),readers:g.array(hr).min(1).max(100),grants:g.array(vpe).max(100),observers:g.array($).max(100).optional(),producers:g.array(g.object({executor:hr,runId:$,expiresAt:ot,materialRevision:g.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),wH=g.object({ownerId:$,authorities:g.array(hr).min(1).max(100)}).strict(),bH=g.object({origin:qd,id:$,revision:g.number().int().positive(),from:wH,to:wH,policyDigest:mr,previous:mr.nullable(),signerId:$}).strict(),wpe=bH.extend({signature:Dn}),hO=g.array(wpe).max(16),Zh=g.object({policy:Di,authorityId:$,signature:Dn,lineage:hO.optional()}).strict(),io=g.object({policy:Di,authorityId:$,authorization:Dn,lineage:hO.optional(),materialRevision:g.number().int().positive(),updatedAt:ot,creationRunId:$.nullable(),metadata:Iu,sealed:Ho,signerId:$,signature:Dn}).strict(),Ru=t=>({ownerId:t.ownerId,authorities:t.authorities});async function _H(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||R(r.to)!==R(o.from))||o.previous!==(r?await ye(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 oo(i,n,s.signing,"authority-handoff"),r=o}if(r&&R(r.to)!==R(Ru(t)))throw new Error("Use the authorities approved by the latest handoff.")}function gO(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 SH(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=R(Ru(t));return r===R(Ru(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&R(o.from)===r)}async function xH(t,e,r,o){let n=[...t?.lineage??[]];if(t&&R(Ru(t.policy))!==R(Ru(e))){if(await qo(t),!t.policy.authorities.some(s=>R(s)===R(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=bH.parse({origin:e.origin,id:e.id,revision:e.revision,from:Ru(t.policy),to:Ru(e),policyDigest:await ye(e),previous:n.length?await ye(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await wn(i,o.signing,"authority-handoff")})}return n.length?{lineage:hO.parse(n)}:{}}async function cx(t){let e=Di.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 Ma(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(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!pO(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if(n.operations.some(i=>i===pe.http||i===pe.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(pe.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function ux(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function Zd(t,e){return R({purpose:"resource",policyDigest:await ye(t),materialRevision:e})}async function yO(t,e,r,o,n,i,s){if(t.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let a=await cx(e),c=await xH(s,a,o,n);if(!a.authorities.some(p=>R(p)===R(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Pu(t,ux(a).map(p=>({id:p.id,publicKey:p.encryption})),await Zd(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await wn(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===Me.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=io.parse({...l,signature:await wn(l,n.signing,"resource")});return await qo(d),d}async function qo(t){let e=io.parse(t),{signature:r,...o}=e;await cx(e.policy),await _H(e.policy,e.lineage);let n=gO(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await ye(e.policy))throw new Error("The handoff approves a different access policy.");await oo(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??(mO(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(pe.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 oo(o,r,s.signing,"resource");let a=ux(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!==ja(ft(await Zd(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function EH(t,e,r,o,n=t.metadata){let i=await qo(t);if(!mO(i.policy.contentType)||!(i.policy.authorities.some(p=>R(p)===R(r))||i.policy.grants.some(p=>R(p.executor)===R(r)&&p.operations.includes(pe.refresh)&&Date.parse(p.expiresAt)>Date.now())))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Pu(e,ux(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await Zd(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 wn(l,o.signing,"resource")};return await qo(d),d}async function lx(t,e,r,o){let n=await cx(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 xH(o,n,e,r),authorityId:e.id,signature:await wn(n,r.signing,"access-policy")};return await Kd(i),i}async function Kd(t){let e=Zh.parse(t);await cx(e.policy),await _H(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await ye(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 oo(e.policy,e.signature,o.signing,"access-policy"),e}async function dx(t,e,r,o,n,i){let s=await Kd(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&R(p.executor)===R(o)&&Date.parse(p.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 Pu(t,ux(a).map(p=>({id:p.id,publicKey:p.encryption})),await Zd(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 wn(l,n.signing,"resource")};return await qo(d),d}async function vO(t,e,r){let o=await qo(t);if(!o.policy.readers.some(n=>R(n)===R(e)))throw new Error("This identity cannot reveal the content.");return Oi(o.sealed,r,e.id,await Zd(o.policy,o.materialRevision))}var bpe=g.object({id:$,policyDigest:mr,materialRevision:g.number().int().positive(),authorizationDigest:mr.optional()}).strict();async function wO(t,e){return e.id===t.policy.id&&e.policyDigest===await ye(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||mO(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var fx=g.object({format:g.literal(2),id:$,origin:qd,ownerId:$,approval:g.object({id:$,index:g.number().int().min(0).max(7)}).strict().optional(),actor:hr,environmentId:$,executor:hr,environmentDigest:mr,operation:ax,functionDigest:mr.nullable(),operationDigest:mr,sources:g.array(bpe).max(100),resultRecipients:g.array(hr).min(1).max(100),createdAt:ot,expiresAt:ot}).strict(),px=g.object({intent:fx,signature:Dn,sealed:Ho}).strict();async function Cu(t,e){return R({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await ye(t)})}async function $H(t,e,r){if(fx.parse(t),await ye(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Pu(ft(R(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await Cu(t,"input"))};return px.parse({...o,signature:await wn(o,r.signing,"run")})}async function _pe(t,e=Date.now()){let r=px.parse(t),{signature:o,...n}=r;await oo(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!==ja(ft(await Cu(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function IH(t,e,r){let o=await _pe(t);if(R(o.intent.executor)!==R(e))throw new Error("This operation belongs to another executor.");let n=await Oi(o.sealed,r.encryption,e.id,await Cu(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(R(s)!==i||await ye(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function Ou(t,e,r={}){let o=await qo(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await wO(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===pe.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==pe.command&&e.operation!==pe.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function Ua(t,e,r,o={}){return await Ou(t,e,o),Oi(t.sealed,r.encryption,e.executor.id,await Zd(t.policy,t.materialRevision))}var Spe=g.object({email:g.boolean(),environments:g.boolean(),objects:g.boolean(),payments:g.boolean()}),mx=g.object({principal:Bd.nullable(),credentialId:$.nullable(),wrappedKey:ex.nullable(),requestId:$.nullable(),server:g.object({name:le}),features:Spe,principals:g.array(Bd)}),s6e=g.object({email:g.email().max(254),returnTo:g.string().max(2048).optional(),locale:XB.default("ja"),principalId:$.optional()}).strict(),a6e=g.object({intent:g.enum(["register","authenticate"]),name:le.optional(),principalId:$.optional(),returnTo:g.string().max(2048).optional()}).strict(),c6e=g.object({challengeId:$,credential:g.json(),publicKey:Nr.optional(),existingPublicKey:Nr.optional(),wrappedKey:ex.optional()}).strict();var xpe=g.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/[\w+=,.@/-]{1,200}$/),AH=g.object({format:g.literal(3),id:$,origin:qd,ownerId:$,name:le,executor:hr,operatorId:$,driver:g.enum(["attached","managed"]),capabilities:g.array(ax).min(1).max(6),isolation:g.enum(["process","container"]),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:xpe.optional(),revision:g.number().int().positive()}).strict(),bO=g.object({manifest:AH,signature:Dn}).strict();async function _O(t,e){let r=AH.parse(t),o={manifest:r,signature:await wn(r,e.signing,"environment")};return await Wd(o),o}async function Wd(t){let e=bO.parse(t),{manifest:r}=e;if(await Ma(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(pe.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(pe.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await oo(r,e.signature,r.executor.signing,"environment"),e}async function hx(t,e){let{manifest:r}=await Wd(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await ye(r)||R(e.executor)!==R(r.executor)||!r.capabilities.includes(e.operation))throw new Error("This environment does not authorize the requested execution.")}var Epe=g.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),TH=g.object({ok:g.boolean(),result:ro.nullable(),error:g.object({code:g.string().max(100),message:g.string().max(1e3)}).nullable()}).strict(),Wh=g.object({id:$,intentDigest:mr,executorId:$,state:g.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:ot,sealed:Ho,signature:Dn}).strict(),Kh=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Jd(t,e,r,o){let n=TH.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");let i=ft(R(n));if(i.byteLength>14e5)throw new Kh;let s=await Pu(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await Cu(t,"result")),a={id:t.id,intentDigest:await ye(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Wh.parse({...a,signature:await wn(a,o.signing,"receipt")})}async function $pe(t,e){let r=Wh.parse(t),{signature:o,...n}=r;if(await oo(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await ye(e)||r.executorId!==e.executor.id||r.sealed.aad!==ja(ft(await Cu(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 PH(t,e,r,o){await $pe(t,e);let n=await Oi(t.sealed,o.encryption,r,await Cu(e,"result")),i=TH.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 Ipe=g.enum(["http","command","function","connect","refresh","revoke"]),zn=g.object({id:$,ownerId:$,actorId:$,environmentId:$,kind:Ipe,state:Epe,intent:fx,requestSignature:Dn,receipt:Wh.nullable(),error:g.string().nullable(),createdAt:ot,startedAt:ot.nullable(),finishedAt:ot.nullable()}).strict(),kH=g.object({name:le,approval:Zh}).strict(),Gd=g.discriminatedUnion("kind",[g.object({kind:g.literal("http"),request:Au,save:g.record(g.string(),kH).default({})}).strict(),g.object({kind:g.literal("command"),...rx.shape}).strict(),g.object({kind:g.literal("function"),definition:Vh,arguments:g.record(g.string(),g.string()).default({}),outputs:g.record(g.string(),kH).default({})}).strict(),g.object({kind:g.enum(["connect","refresh","revoke"]),input:ro}).strict()]);var La=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},Vs=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=g.object({error:g.object({code:g.string(),message:g.string()})}).parse(await n.json())}catch{throw new La("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new La(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",{},mx)}};import{chmod as kpe,lstat as Ape,mkdir as Tpe,open as SO,readFile as CH,rename as Ppe,rm as Rpe}from"node:fs/promises";import{dirname as Cpe,join as xO,resolve as Ope}from"node:path";import{homedir as Npe}from"node:os";import{randomUUID as Dpe}from"node:crypto";var EO=g.object({origin:g.url(),principalId:g.uuid(),token:g.string().min(20),keys:Hh.nullable(),binding:hr.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),OH=g.object({current:g.uuid(),identities:g.array(EO).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function Bs(){return xO(process.env.XDG_CONFIG_HOME||xO(Npe(),".config"),"foundation","identity.json")}function Fa(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 gx(t){let e;try{let n=Bs(),i=await Ape(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await kpe(n,384);let s=OH.parse(JSON.parse(await CH(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=Fa(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==Fa(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 EO.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!==Fa(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 Jh(t){let e=Bs(),r;try{r=OH.parse(JSON.parse(await CH(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=EO.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Xd(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
|
|
129
129
|
`,!!r)}async function RH(t){if(process.platform==="win32")return;let e=await SO(t,"r");try{await e.sync()}finally{await e.close()}}async function Xd(t,e,r){let o=Ope(t),n=Cpe(o);if(await Tpe(n,{recursive:!0,mode:448}),!r){let s=await SO(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await RH(n);return}let i=xO(n,".foundation-"+Dpe());try{let s=await SO(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await Ppe(i,o),await RH(n)}finally{await Rpe(i,{force:!0})}}import{spawn as Lpe}from"node:child_process";import{chmod as Fpe,mkdtemp as Vpe,rm as Bpe,writeFile as Hpe}from"node:fs/promises";import{tmpdir as qpe}from"node:os";import{join as jH}from"node:path";import{StringDecoder as Zpe}from"node:string_decoder";import{spawn as NH}from"node:child_process";import{mkdir as zpe,mkdtemp as jpe,rm as Mpe,writeFile as DH}from"node:fs/promises";import{tmpdir as Upe}from"node:os";import{join as Gh}from"node:path";import{StringDecoder as zH}from"node:string_decoder";function yx(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 vx=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 jpe(Gh(Upe(),"foundation-job-")),n=Gh(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a={exitCode:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},c=!1;try{await zpe(n,{mode:448});let u={...e.environment};for(let[d,p]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d))throw new Error("Use valid file variable names.");await DH(Gh(n,d),Buffer.from(p,"base64"),{mode:384,flag:"wx"}),u[d]=s?"/run/foundation/"+d:Gh(n,d)}let l=e.command;if(s){if(Object.entries(u).some(([p,f])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(p)||/[\r\n\0]/.test(f)))throw new Error("Use file inputs for multiline container values.");let d=Gh(o,"environment");await DH(d,Object.entries(u).map(([p,f])=>p+"="+f).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 p=NH(l[0],l.slice(1),{env:yx(s?{}:u),cwd:this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),f={stdout:new zH("utf8"),stderr:new zH("utf8")},m=0,h=!1,y=(E,k)=>{let O=Math.max(0,1e6-m);k.length>O&&(a.truncated=!0);let H=k.subarray(0,O);m+=H.length,a[E]+=f[E].write(H)};p.stdout.on("data",E=>y("stdout",E)),p.stderr.on("data",E=>y("stderr",E)),p.stdin.on("error",()=>{}),p.stdin.end(e.stdin??"");let w=()=>{c=!0;try{p.pid&&process.platform!=="win32"?process.kill(-p.pid,"SIGKILL"):p.kill("SIGKILL")}catch{}},b=setTimeout(()=>{a.timedOut=!0,w()},e.timeoutSeconds*1e3);b.unref();let _=()=>{h||(h=!0,clearTimeout(b),r.removeEventListener("abort",w),a.stdout+=f.stdout.end(),a.stderr+=f.stderr.end(),d())};r.addEventListener("abort",w,{once:!0}),r.aborted&&w(),p.once("error",()=>{a.exitCode=127,a.stderr="The command could not be started.",_()}),p.once("close",E=>{a.exitCode=E,_()})}),a}finally{s&&c&&await new Promise(u=>{let l=NH("docker",["rm","-f",i],{env:yx(),stdio:"ignore"});l.once("close",()=>u()),l.once("error",()=>u()),setTimeout(()=>{l.kill("SIGKILL"),u()},1e4).unref()}),await Mpe(o,{recursive:!0,force:!0})}}};function Kpe(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 wx=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 Zpe("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 MH(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await Vpe(jH(qpe(),"foundation-"));await Fpe(r,448);try{let o=yx(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=jH(r,i);await Hpe(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=Lpe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=Kpe(n),u=new wx(c,m=>process.stdout.write(m)),l=new wx(c,m=>process.stderr.write(m));a.stdout.on("data",m=>u.write(m)),a.stderr.on("data",m=>l.write(m));let d=m=>{if(a.pid)try{process.platform==="win32"?a.kill(m):process.kill(-a.pid,m)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(m,h)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(m??(h==="SIGINT"?130:h==="SIGTERM"?143:1))})})}finally{await Bpe(r,{recursive:!0,force:!0})}}import{dirname as dAe,join as E4}from"node:path";var bx=g.record(g.string().max(100),g.string().max(16384)),Va=g.object({format:g.literal(1),methodId:g.string().min(1),generation:$,clientId:g.string().max(1e3),clientSecret:g.string().max(16384).optional(),fields:bx}).strict();function Nu(t){return t.kind==="oauth"&&t.config.adapter!=="openrouter"}var Wpe=g.object({accessToken:g.string().min(1).max(16384),refreshToken:g.string().min(1).max(16384).optional(),expiresAt:g.number().nullable(),refreshExpiresAt:g.number().optional(),scopes:g.array(g.string()),account:g.string(),accountName:g.string(),accountVerified:g.boolean().optional(),scopesStatus:g.enum(["unknown","requested","reported"]).optional(),extra:bx,facts:Iu}).strict(),Ba=g.object({format:g.literal(1),methodId:g.string().min(1),method:ku,generation:$,appId:$.nullable(),appGeneration:$.nullable(),state:g.literal("reconnect").optional(),oauth:Wpe.optional(),fields:bx.optional(),role:g.object({arn:g.string().regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),externalId:g.string().min(16).max(1e3),region:g.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/)}).strict().optional()}).strict().superRefine((t,e)=>{(t.method.kind==="oauth"&&(!t.oauth||Nu(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."})}),B6e=g.object({methodId:g.string().min(1).max(200),clientId:g.string().max(1e3),generation:$}).strict(),Jpe=g.object({methodId:g.string().min(1).max(200),methodKind:oO,generation:$,authorizationDigest:mr,appId:$.nullable(),accountId:g.string().max(2e3).nullable(),accountVerified:g.boolean(),scopes:g.array(g.string().max(1e3)).max(200),scopesStatus:g.enum(["unknown","requested","reported"]),outputs:g.array(g.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:g.enum(["ready","reconnect"])}).strict();async function Du(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 ye({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,...t.state?{state:t.state}:{}});return Jpe.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:r,appId:t.appId,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:t.state??"ready"})}var UH=g.object({methodName:le,account:g.string().max(2e3)}).strict();function _x(t){return{methodName:t.method.name,account:t.oauth?.accountName??t.role?.arn??t.method.name}}var Gpe=g.object({action:g.literal("start"),flowId:$,name:le,methodId:g.string().min(1),method:ku,appId:$.nullable(),fields:bx.default({}),scopes:g.array(g.string().max(1e3)).max(200).default([]),redirectUri:g.url().optional(),role:Ba.shape.role}).strict(),Sx=g.discriminatedUnion("action",[Gpe,g.object({action:g.literal("exchange"),flowId:$,parameters:g.string().max(16384)}).strict(),g.object({action:g.literal("commit"),flowId:$,authorizationDigest:mr,approval:Zh}).strict(),g.object({action:g.literal("refresh"),id:$}).strict(),g.object({action:g.literal("revoke"),id:$}).strict()]);var LH=Ni.extend({name:le}),FH=g.object({id:$,index:g.number().int().min(0).max(7),input:mH.extend({ownerId:$})}).strict(),X6e=g.object({bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ni,token:g.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),VH=g.object({id:$,executorId:$,ownerId:$,name:le,origin:g.url(),bootstrap:g.string().regex(/^[A-Za-z0-9_-]{43}$/),commandImage:g.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),Y6e=Ni.extend({previousSignature:Dn.optional()}).strict(),Q6e=g.object({name:le,content:io,labels:UH.optional(),version:g.number().int().positive().optional()}).strict(),BH=g.object({content:io,version:g.number().int().positive()}).strict(),HH=g.object({id:$,reason:g.enum(["grantExpired"])}).strict(),eFe=g.record($,g.object({version:g.number().int().positive(),content:io}).strict()),tFe=g.object({id:$,name:le,version:g.number().int().positive(),content:io,policy:Di}).strict(),qH=g.object({registration:bO,stoppedAt:g.iso.datetime().nullable(),heartbeatAt:g.iso.datetime().nullable()}).strict(),ZH=g.object({lease:$,request:px,sources:g.array(io).max(100)}).strict().nullable(),Xpe=g.object({lease:$}).strict(),rFe=Xpe.extend({receipt:Wh}).strict(),Xh=g.object({id:$,resource_id:$,executor_id:$,expected_revision:g.number().int().positive(),state:g.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:g.string().regex(/^\d+$/),result:io.nullable()}),nFe=g.object({id:$,resourceId:$,expectedRevision:g.number().int().positive()}).strict(),Ype=g.object({fence:g.string().regex(/^\d+$/)}).strict(),oFe=Ype.extend({content:io}).strict(),iFe=g.object({id:$,runId:$,stateDigest:mr,expiresAt:ot}).strict(),xx=g.object({id:$,runId:$,context:g.string(),sealed:Ho.nullable(),expiresAt:ot,receivedAt:ot.nullable()}).strict(),KH=(t,e)=>"oauth-callback:"+t+":"+e;var qs=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"}},Qpe=class extends qs{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"}},eme=class extends qs{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},tme=class extends qs{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"}},rme=class extends qs{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"}},nme=class extends qs{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},ome=class extends qs{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"}},ime=class extends qs{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},$x=class extends qs{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},$O=class extends $x{constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},sme=class extends $x{offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},ame=class extends $x{prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},WH=class extends $x{constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},cme=class extends qs{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"}},ume=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},lme=class extends ume{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"}},dme=["","+",".","/",";","?","&","#"],tq={"":{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}},fme=new TextEncoder,JH="0123456789ABCDEF",GH=t=>qa(Dr(48,57),Dr(65,70),Dr(97,102))(t.charCodeAt(0)),eg=(t,e)=>t[e]==="%"&&e+2<t.length&&GH(t[e+1])&&GH(t[e+2]);function IO(t,e){let r=t[e];return r==null?0:qa(rq,nq,zu("_"))(r)?1:eg(t,e)?3:0}function pme(t,e){if(eg(t,e))return 3;let{char:r,size:o}=tg(t,e);return hme(r)?o:0}function tg(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 PO=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&eg(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=tg(e,o);r+=qa(oq,s=>t&&mme(s))(n)?n:iq(n),o+=i}return r};function Yd(t){let e="";for(let r=0;r<t.length;){if(eg(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=tg(t,r);e+=oq(o)?o:iq(o),r+=n}return e}function Yh(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(eg(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=tg(t,n);r+=i,n+=s}return r}var rq=t=>qa(Dr(65,90),Dr(97,122))(t.charCodeAt(0)),nq=t=>Dr(48,57)(t.charCodeAt(0)),oq=t=>qa(rq,nq,e=>"-._~".includes(e))(t),mme=t=>":/?#[]@!$&'()*+,;=".includes(t),hme=t=>gme(t.codePointAt(0)),gme=t=>t!=null&&qa(zu(33),Dr(35,36),zu(38),Dr(40,59),zu(61),Dr(63,91),zu(93),zu(95),Dr(97,122),zu(126),yme,vme)(t);function yme(t){if(t<65536)return qa(Dr(160,55295),Dr(63744,64975),Dr(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var vme=t=>qa(Dr(57344,63743),Dr(983040,1048573),Dr(1048576,1114109))(t),iq=t=>Array.from(fme.encode(t)).map(e=>`%${JH[e>>4]}${JH[e&15]}`).join(""),Dr=(t,e)=>r=>t<=r&&r<=e,zu=t=>e=>t===e,qa=(...t)=>e=>t.some(r=>r(e));function sq(t,e,r){return t.map(o=>o.kind==="literal"?o.text:wme(o.vars,o.operator,e,r)).join("")}function wme(t,e,r,o){let n=tq[e],i=t.flatMap(s=>bme(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function bme(t,e,r,o){if(e==null)return[];if(Ame(e)){let n=Eme(e,r.allowReserved);return n.length<1?[]:XH(t,"list",o)?Sme(t,n,r):[]}if(kme(e)){let n=$me(e,r.allowReserved);return n.length<1?[]:XH(t,"associative",o)?xme(t,n,r):[]}return _me(t,e,r)}function _me(t,e,r){let o=String(e),n=t.prefix==null?o:Yh(o,t.prefix),i=PO(r.allowReserved)(n);return r.named?[Qh(Yd(t.name),i,r)]:[i]}function Sme(t,e,r){let o=Yd(t.name);if(t.explode)return r.named?e.map(i=>Qh(o,i,r)):[...e];let n=e.join(",");return r.named?[Qh(o,n,r)]:[n]}function xme(t,e,r){if(t.explode)return e.map(([n,i])=>Qh(n,i,r));let o=e.flat(1).join(",");return r.named?[Qh(Yd(t.name),o,r)]:[o]}var Qh=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,Eme=(t,e)=>t.filter(r=>r!=null).map(String).map(PO(e)),$me=(t,e)=>Object.entries(t).map(([r,o])=>[r,Ime(o)]).filter(([,r])=>r!=null).map(r=>r.map(PO(e)));function Ime(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 kme=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ame=t=>Array.isArray(t);function XH(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new lme(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function Tme(t,e,r){return kO(t,e,r,0,0,{})}function kO(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=rhe(i);return sq(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?kO(t,e,r,o+1,n+s.text.length,i):null;for(let a of Pme(t,e,o,n)){let c=e.slice(n,a);for(let u of Cme(s.vars,s.operator,c)){let l=RO(i,u);if(l==null)continue;let d=kO(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*Pme(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*Rme(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*Rme(t,e){for(let r=t;r>=e;r--)yield r}function*Cme(t,e,r){if(r===""){yield*Ome(t,e);return}let o=tq[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?Vme(t,o,n):Nme(t,o,n)}var Ome=(t,e)=>(e===""||e==="+")&&t.length===1?[Ha(t[0],"")]:[{}],Nme=(t,e,r)=>AO(t,e,CO(r,e.sep),0,0);function*AO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of Dme(i,e,r,n))for(let a of AO(t,e,r,o+1,s.index)){let c=RO(s.bindings,a);c!=null&&(yield c)}yield*AO(t,e,r,o+1,n)}function*Dme(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 zme(t,e,s))yield{bindings:a,index:o+i}}}function*zme(t,e,r){let o=aq(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*jme(t,e,r)),yield*o}function*jme(t,e,r){let o=cq(r,e.allowReserved);if(o==null)return;let n=Mme(r,e);n!=null&&(yield Ha(t,n)),yield Ha(t,o)}var Mme=(t,e)=>Ume(t.join(e.sep),e);function Ume(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=Lme(t,i,e.sep),a=Hs(t.slice(o,n),e.allowReserved),c=Hs(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 Lme(t,e,r){for(let o=e;o<t.length;o++)if(Fme(t,o,r))return o;return t.length}var Fme=(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*aq(t,e,r){let o=Hs(r,e.allowReserved);if(o==null)return;let n=Ha(t,o);if(t.prefix!=null){yield n;return}let i=CO(r,",");if(i.length<2){yield n;return}let s=cq(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?Xme(i,e.allowReserved):null;a!=null&&(yield Ha(t,a)),yield Ha(t,s),yield n}var Vme=(t,e,r)=>TO(t,e,CO(r,e.sep).map(Gme),0,0);function*TO(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of Bme(i,e,r,n,t))for(let a of TO(t,e,r,o+1,s.index)){let c=RO(s.bindings,a);c!=null&&(yield c)}yield*TO(t,e,r,o+1,n)}function*Bme(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*qme(t,e,r,o,n);return}yield*Hme(t,e,r,o)}}function*Hme(t,e,r,o){let n=r[o];if(n.name===Yd(t.name))for(let i of aq(t,e,n.value))yield{bindings:i,index:o+1}}function*qme(t,e,r,o,n){yield*Zme(t,e,r,o),yield*Wme(t,e,r,o,n)}function*Zme(t,e,r,o){let n=[...Kme(Yd(t.name),e,r,o)];n.length>0&&(yield{bindings:Ha(t,n),index:o+n.length})}function*Kme(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=Hs(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*Wme(t,e,r,o,n){let i=[...Jme(e,r,o,new Set(n.map(s=>Yd(s.name))))];i.length>0&&(yield{bindings:Ha(t,Object.fromEntries(i)),index:o+i.length})}function*Jme(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=Hs(i.name,t.allowReserved),a=Hs(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function Gme(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function Xme(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=Hs(t[o],e),i=Hs(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function cq(t,e){let r=[];for(let o of t){let n=Hs(o,e);if(n==null)return null;r.push(n)}return r}function Hs(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var Ha=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function RO(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=Yme(i,n);if(s==null)return null;r[o]=s}return r}var Yme=(t,e)=>Ex(t)||Ex(e)?Qme(t,e):ehe(t.value,e.value)?t:null;function Qme(t,e){let r=YH(t.value),o=YH(e.value);if(r==null||o==null)return null;let n=Ex(t),i=Ex(e);if(!n&&!i)return null;if(n&&!i)return Yh(o,t.prefix)===r?e:null;if(!n&&i)return Yh(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Yh(o,s)===r?e:null:Yh(r,a)===o?t:null}var Ex=t=>t.prefix!=null,YH=t=>typeof t=="string"?t:null;function ehe(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):QH(t)?QH(e)&&the(Object.entries(t),Object.entries(e)):t===e}var the=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),QH=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),rhe=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),CO=(t,e)=>e===""?[t]:t.split(e),nhe=["=",",","!","@","|"];function ohe(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new nme(e,r));let n=t[0];if(che(n))return o(new ome(e,r+1,n));if(!eq(n)&&IO(t,0)<1)return o(new ime(e,r+1,n));let i=eq(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:ihe(t,e,r+1,s)}}function ihe(t,e,r,o){if(o>=t.length)throw new $O(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new WH(e,r+i):new $O(e,r+i);let s=i,a=she(t,i);if(a===s)throw new $O(e,r+i);let c=t.slice(s,a);i=a;let u=ahe(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new cme(e,r+i,t[i]):new sme(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 WH(e,r+i-1)}return n}function she(t,e){let r=e,o=!0;for(;r<t.length;){let n=IO(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||IO(t,r+1)<1)break;r++,o=!0}return r}function ahe(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&&uhe(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new ame(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function eq(t){return dme.includes(t)&&t!==""}function che(t){return nhe.includes(t)}function uhe(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function lhe(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 Qpe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new tme(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(ohe(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new eme(t,i)),n(s),i++;continue}let a=pme(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=tg(t,i);r(new rme(t,i,c)),n(c),i+=u}return o}var Ix=class uq{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=hhe(r),this.#e=dhe(lhe(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new uq(e,r)}get tokens(){return this.#e}expand=e=>sq(this.#e,e,this.#t);match=e=>Tme(this.#e,e,this.#t);toString=()=>this.uriTemplate},dhe=t=>Object.freeze(t.map(fhe)),fhe=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(phe))}),phe=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),mhe=()=>{},hhe=({strict:t,report:e})=>(e??=mhe,t??=!0,e=t?ghe(e):e,{strict:t,report:e}),ghe=t=>e=>{throw t(e),e};function kx(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 Ix(t.request.url).expand(r),i=Au.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 Ax=class extends Error{constructor(r,o){super(o);this.code=r}code},OO=class extends Error{constructor(r){super("The execution request is saved locally. Check execution "+r+" before starting another operation.");this.id=r}id},Tx=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 Ax("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/"+$.parse(e)+"/binding",{},Ni);return await fO(r),{...r,fingerprint:await ye(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new Ax("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/"+$.parse(e)+"/registration",{},qH);if(await Wd(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/"+$.parse(e)+"/bound-recipients",{},za(LH));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 fO(n),await this.trusted(n.binding);return r.map(o=>o.binding)}async read(e){let r=await this.api.json("/api/resources/"+$.parse(e)+"/custody",{},BH);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await qo(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=gO(o);await this.trusted(n);let i=await this.trust.checkpoint(r),s=i&&Di.safeParse(i.policy).success?i:null;if(s){if(o.policy.revision<s.policy.revision||o.materialRevision<s.materialRevision||o.policy.revision===s.policy.revision&&R(o.policy)!==R(s.policy)||o.materialRevision===s.materialRevision&&await ye(o)!==s.digest)throw new Error("The encrypted content is older than this device has already observed.");if(o.policy.revision>s.policy.revision&&!SH(s.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 vO((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&&Date.parse(c.expiresAt)>Date.now()):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...pO(r)],origins:[],functionDigests:[],callerProgram:r!==Me.clientCredential,expiresAt:s});return Di.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&R(o)===R({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await yO(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}:{}}},no);return await this.trust.rememberContent(s),a}async pass(e,r,o,n){let i=await yO(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},g.union([no,Da]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},za(HH))).items}async reprotect(e){let r=await this.read(e),{policy:o}=r.content,n=Date.now(),i=o.grants.filter(c=>Date.parse(c.expiresAt)>n);if(i.length===o.grants.length||o.producers.some(c=>Date.parse(c.expiresAt)>n))return null;let s=await this.api.json("/api/resources/"+o.id,{},no),a=await vO(r.content,this.binding,this.keys.encryption);return this.save(s.name,a,{...o,revision:o.revision+1,grants:i,producers:[]},{metadata:r.content.metadata,previous:r})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id)&&e.push(o.id)}catch{r.push(o.id)}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===Me.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},za(no));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,Me.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await lx(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=await this.environment(r),s=Gd.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"?kx(s.definition,s.arguments):null;if(s.kind==="http"||s.kind==="function"){let m=s.kind==="function"?s.definition.save:n.save??{};if(s.kind==="function"&&Object.keys(m).length&&s.definition.outputOwnerId!==e)throw new Error("Run this function for its approved output owner.");let h=Object.fromEntries(await Promise.all(Object.entries(m).map(async([y,w])=>[y,await this.output(e,w,a,i,c)])));s.kind==="http"?s.save=h:s.outputs=h}let l=s.kind==="command"?s.inputs.map(m=>m.source.id):u?u.bindings.flatMap(m=>m.parts.flatMap(h=>typeof h=="string"?[]:[h.id])):[],d=await this.sourceContents([...l,...n.sourceIds??[]]),p={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:i.manifest.executor,environmentDigest:await ye(i.manifest),operation:pe[s.kind],operationDigest:await ye(s),...n.approval?{approval:n.approval}:{},functionDigest:s.kind==="function"?await ye(s.definition):null,sources:await Promise.all(d.map(async m=>({id:m.policy.id,materialRevision:m.materialRevision,policyDigest:await ye(m.policy),...m.policy.contentType===Me.tokenSet&&typeof m.metadata.authorizationDigest=="string"?{authorizationDigest:m.metadata.authorizationDigest}:{}}))),resultRecipients:[this.binding],createdAt:new Date().toISOString(),expiresAt:c};await hx(i,p);let f=m=>m.policy.contentType===Me.clientCredential;for(let m of d)await Ou(m,f(m)&&p.operation!==pe.connect&&p.operation!==pe.revoke?{...p,operation:pe.refresh}:p,f(m)?{}:{destination:u?.url});return $H(p,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},zn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new OO(e.intent.id)}}async resume(e){let r=await this.trust.run($.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 dO(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?PH(e.receipt,e.intent,this.binding.id,this.keys):null}};import{lstat as yhe,mkdir as vhe,readFile as whe,readdir as bhe}from"node:fs/promises";import{join as lq}from"node:path";var dq=g.string().regex(/^(run|oauth|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),ju=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:dq.parse(e)})}async read(e){let r=this.context(e),o=lq(this.directory,e+".json");try{let n=await yhe(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=g.string().max(32e6).parse(JSON.parse(await whe(o,"utf8"))),s=await zh(i,await to(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(Tu(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await oo({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 wn(n,this.privateKeys.signing,"journal"),s=ft(R({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new Vd(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await to(this.binding.encryption,"ECDH-ES+A256KW"));await vhe(this.directory,{recursive:!0,mode:448}),await Xd(lq(this.directory,e+".json"),R(a),!0)}async keys(e){let r;try{r=await bhe(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=>dq.parse(o.name.slice(0,-5)))}};var Px=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async rememberBinding(e){await Ma(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 ye(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 Ct=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function V(t,e,r,o){throw new Ct(t,e,r,o)}var Rx=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 Ct(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}},g.object({active:g.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}},zn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},g.object({id:$}))}connections(){let e=this.api;return{relay:r=>e.json("/api/oauth/relays",{method:"POST",body:r},xx),capture:(r,o,n)=>this.capture(r,o,n),prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},Xh),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},Xh),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},io),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}},Xh),state:r=>e.json("/api/connections/"+r+"/operation",{},Xh.nullable())}}};var dne=St(Oq(),1);import{randomBytes as lne,randomUUID as S4}from"node:crypto";function ng(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 ji(t,e){for(let r of ng(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function VO(t,e,r){let o=ng(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 tf(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 og(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 Vge}from"node:crypto";var BO;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BO="oauth4webapi/v3.8.8");function cg(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 Mi="ERR_INVALID_ARG_VALUE",Ui="ERR_INVALID_ARG_TYPE";function Ht(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var YO=Symbol(),qhe=Symbol(),Zhe=Symbol(),QO=Symbol();var Fx=Symbol();var Khe=new TextEncoder,Whe=new TextDecoder;function HO(t){return typeof t=="string"?Khe.encode(t):Whe.decode(t)}var qO;Uint8Array.prototype.toBase64?qO=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):qO=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 ZO;Uint8Array.fromBase64?ZO=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Ht("The input to be decoded is not correctly encoded.",Mi,e)}}:ZO=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 Ht("The input to be decoded is not correctly encoded.",Mi,e)}};function KO(t){return typeof t=="string"?ZO(t):qO(t)}var rf=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Sge,Error.captureStackTrace?.(this,this.constructor)}},ig=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 he(t,e,r){return new ig(t,{code:e,cause:r})}function Jhe(t){return t.toLowerCase().replace(/^application\//,"")}function sg(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function eN(t){cg(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(BO&&!e.has("user-agent")&&e.set("user-agent",BO),e.has("authorization"))throw Ht('"options.headers" must not include the "authorization" header name',Mi);return e}function Ghe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Ht('"options.signal" must return or be an instance of AbortSignal',Ui);return e}}function Vx(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Ht(`${r} must be a number`,Ui,n);if(t>0)return;if(e){if(t!==0)throw Ht(`${r} must be a non-negative number`,Mi,n);return}throw Ht(`${r} must be a positive number`,Mi,n)}catch(i){throw o?he(i.message,o,n):i}}function yr(t,e,r,o){try{if(typeof t!="string")throw Ht(`${e} must be a string`,Ui,o);if(t.length===0)throw Ht(`${e} must not be empty`,Mi,o)}catch(n){throw r?he(n.message,r,o):n}}function zq(t){Yhe(t,"application/json")}function Xhe(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 he(r,Ege,t)}function Yhe(t,e){if(Vq(t)!==e)throw Xhe(t,e)}async function jq(t){return yr(t,"codeVerifier"),KO(await crypto.subtle.digest("SHA-256",HO(t)))}function tN(t){let e=t?.[qhe];return typeof e=="number"&&Number.isFinite(e)?e:0}function rN(t){let e=t?.[Zhe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Mq(){return Math.floor(Date.now()/1e3)}function Lu(t){if(typeof t!="object"||t===null)throw Ht('"as" must be an object',Ui);yr(t.issuer,'"as.issuer"')}function Fu(t){if(typeof t!="object"||t===null)throw Ht('"client" must be an object',Ui);yr(t.client_id,'"client.client_id"')}function Nq(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 Uq(t){return yr(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Lq(t){return yr(t,'"clientSecret"'),(e,r,o,n)=>{let i=Nq(r.client_id),s=Nq(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function Fq(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var Qhe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function ege(t,e){if(e&&t.protocol!=="https:")throw he("only requests to HTTPS are allowed",Ige,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw he("only HTTP and HTTPS requests are allowed",kge,t)}function Dq(t,e,r,o){let n;if(typeof t!="string"||!(n=Qhe(t)))throw he(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?Age:Tge,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return ege(n,o),n}function nN(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Dq(t.mtls_endpoint_aliases[e],e,r,o):Dq(t[e],e,r,o)}var WO=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=_ge,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)}},ag=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=xge,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)}},JO=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=bge,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Bx="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",tge="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",rge='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',nge="("+Bx+")\\s*=\\s*"+rge,oge="("+Bx+")\\s*=\\s*("+Bx+")",ige=new RegExp("^[,\\s]*("+Bx+")"),sge=new RegExp("^[,\\s]*"+nge+"[,\\s]*(.*)"),age=new RegExp("^[,\\s]*"+oge+"[,\\s]*(.*)"),cge=new RegExp("^("+tge+")(?:$|[,\\s])(.*)");function uge(t){if(!cg(t,Response))throw Ht('"response" must be an instance of Response',Ui);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(ige),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(sge)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(age)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(cge)){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 lge(t){if(t.status>399&&t.status<500){Zx(t),zq(t);try{let e=await t.clone().json();if(sg(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function oN(t,e,r){if(t.status!==e){fge(t);let o;throw(o=await lge(t))?(await t.body?.cancel(),new WO("server responded with an error in the response body",{cause:o,response:t})):he(`"response" is not a conform ${r} response (unexpected HTTP status code)`,$ge,t)}}function dge(t){if(!aN.has(t))throw Ht('"options.DPoP" is not a valid DPoPHandle',Mi)}function Vq(t){return t.headers.get("content-type")?.split(";")[0]}async function iN(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?.[QO]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Ghe(o,s?.signal)})}async function Bq(t,e,r,o,n,i){let s=nN(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[YO]!==!0);n.set("grant_type",o);let a=eN(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(dge(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await iN(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Hq(t,e,r,o,n){Lu(t),Fu(e),yr(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),Bq(t,e,r,"refresh_token",i,n)}var qq=new WeakMap,Zq=new WeakMap;function Kq(t){if(!t.id_token)return;let e=qq.get(t);if(!e)throw Ht('"ref" was already garbage collected or did not resolve from the proper sources',Mi);return e}async function sN(t,e,r,o,n,i){if(Lu(t),Fu(e),!cg(r,Response))throw Ht('"response" must be an instance of Response',Ui);await oN(r,200,"Token Endpoint"),Zx(r);let s=await dZ(r);if(yr(s.access_token,'"response" body "access_token" property',Je,{body:s}),yr(s.token_type,'"response" body "token_type" property',Je,{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;Vx(a,!0,'"response" body "expires_in" property',Je,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&yr(s.refresh_token,'"response" body "refresh_token" property',Je,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw he('"response" body "scope" property must be a string',Je,{body:s});if(s.id_token!==void 0){yr(s.id_token,'"response" body "id_token" property',Je,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Vx(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await hge(t,e,s.id_token,a,n);yge(e,c),gge(c),Zq.set(r,u),qq.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 rf("unsupported `token_type` value",{cause:{body:s}});return s}function fge(t){let e;if(e=uge(t))throw new JO("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Wq(t,e,r,o){return sN(t,e,r,void 0,o?.[Fx],o?.recognizedTokenTypes)}function Jq(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw he('unexpected JWT "aud" (audience) claim value',nf,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw he('unexpected JWT "aud" (audience) claim value',nf,{expected:t,claims:e.claims,claim:"aud"});return e}function Gq(t,e){let r=t[Oge]?.(e)??t.issuer;if(e.claims.iss!==r)throw he('unexpected JWT "iss" (issuer) claim value',nf,{expected:r,claims:e.claims,claim:"iss"});return e}var aN=new WeakSet;function pge(t){return aN.add(t),t}var cN=Symbol();async function Xq(t,e,r,o,n,i,s){if(Lu(t),Fu(e),!aN.has(o))throw Ht('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Mi);yr(n,'"redirectUri"');let a=Uu(o,"code");if(!a)throw he('no authorization code in "callbackParameters"',Je);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==cN&&(yr(i,'"codeVerifier"'),c.set("code_verifier",i)),Bq(t,e,r,"authorization_code",c,s)}var Yq={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 Qq(t,e){for(let r of t)if(e.claims[r]===void 0)throw he(`JWT "${r}" (${Yq[r]}) claim missing`,Je,{claims:e.claims});return e}function mge(t,e){if(typeof e.claims[t]!="string")throw he(`unexpected JWT "${t}" (${Yq[t]}) claim type`,Je,{claims:e.claims});return e}function hge(t,e,r,o,n){return cZ(r,uZ.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),tN(e),rN(e),n).then(Qq.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(Gq.bind(void 0,t)).then(Jq.bind(void 0,e.client_id)).then(mge.bind(void 0,"sub"))}function eZ(t,e){if(e===qx)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?qx:(Vx(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function gge(t){t.auth_time!==void 0&&Vx(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Je,{claims:t})}function tZ(t,e,r){if(r===qx)return;let o=Mq()+tN(t),n=rN(t);if(e.auth_time+r<o-n)throw he("too much time has elapsed since the last End-User authentication",XO,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function rZ(t,e){let r=e===Hx?void 0:e;if(t.nonce!==r)throw he('unexpected ID Token "nonce" claim value',nf,{expected:r,claims:t,claim:"nonce"})}function yge(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw he('ID Token "aud" (audience) claim includes additional untrusted audiences',nf,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw he('unexpected ID Token "azp" (authorized party) claim value',nf,{expected:t.client_id,claims:e,claim:"azp"})}}var Hx=Symbol(),qx=Symbol();async function nZ(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?vge(t,e,r,o.expectedNonce,o.maxAge,o[Fx],o.recognizedTokenTypes):wge(t,e,r,o?.maxAge,o?.[Fx],o?.recognizedTokenTypes)}async function vge(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=Hx;break;case Hx:break;default:yr(o,'"expectedNonce" argument'),a.push("nonce")}n=eZ(e,n),n!==qx&&a.push("auth_time");let c=await sN(t,e,r,a,i,s);yr(c.id_token,'"response" body "id_token" property',Je,{body:c});let u=Kq(c);return tZ(e,u,n),rZ(u,o),c}async function wge(t,e,r,o,n,i){let s=await sN(t,e,r,void 0,n,i),a=Kq(s);return a&&(tZ(e,a,eZ(e,o)),rZ(a,Hx)),s}var bge="OAUTH_WWW_AUTHENTICATE_CHALLENGE",_ge="OAUTH_RESPONSE_BODY_ERROR",Sge="OAUTH_UNSUPPORTED_OPERATION",xge="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var GO="OAUTH_PARSE_ERROR",Je="OAUTH_INVALID_RESPONSE";var Ege="OAUTH_RESPONSE_IS_NOT_JSON",$ge="OAUTH_RESPONSE_IS_NOT_CONFORM",Ige="OAUTH_HTTP_REQUEST_FORBIDDEN",kge="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",XO="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",nf="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var Age="OAUTH_MISSING_SERVER_METADATA",Tge="OAUTH_INVALID_SERVER_METADATA";function Pge(t,e){if(typeof e.header.typ!="string"||Jhe(e.header.typ)!==t)throw he('unexpected JWT "typ" header parameter value',Je,{header:e.header});return e}async function oZ(t,e,r,o,n){Lu(t),Fu(e),yr(o,'"token"');let i=nN(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[YO]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=eN(n?.headers);return a.delete("accept"),iN(t,e,r,i,s,a,n)}async function iZ(t){if(!cg(t,Response))throw Ht('"response" must be an instance of Response',Ui);await oN(t,200,"Revocation Endpoint")}function Zx(t){if(t.bodyUsed)throw Ht('"response" body has been used already',Mi)}async function sZ(t,e,r,o,n){Lu(t),Fu(e),yr(o,'"token"');let i=nN(t,"introspection_endpoint",e.use_mtls_endpoint_aliases,n?.[YO]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=eN(n?.headers);return n?.requestJwtResponse??e.introspection_signed_response_alg?a.set("accept","application/token-introspection+jwt"):a.set("accept","application/json"),iN(t,e,r,i,s,a,n)}async function aZ(t,e,r,o){if(Lu(t),Fu(e),!cg(r,Response))throw Ht('"response" must be an instance of Response',Ui);await oN(r,200,"Introspection Endpoint");let n;if(Vq(r)==="application/token-introspection+jwt"){Zx(r);let{claims:i,jwt:s}=await cZ(await r.text(),uZ.bind(void 0,e.introspection_signed_response_alg,t.introspection_signing_alg_values_supported,"RS256"),tN(e),rN(e),o?.[Fx]).then(Pge.bind(void 0,"token-introspection+jwt")).then(Qq.bind(void 0,["aud","iat","iss"])).then(Gq.bind(void 0,t)).then(Jq.bind(void 0,e.client_id));if(Zq.set(r,s),!sg(i.token_introspection))throw he('JWT "token_introspection" claim must be a JSON object',Je,{claims:i});n=i.token_introspection}else Zx(r),n=await dZ(r);if(typeof n.active!="boolean")throw he('"response" body "active" property must be a boolean',Je,{body:n});return n}async function cZ(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 rf("JWE decryption is not configured",{cause:t});if(a!==3)throw he("Invalid JWT",Je,t);let c;try{c=JSON.parse(HO(KO(i)))}catch(d){throw he("failed to parse JWT Header body as base64url encoded JSON",GO,d)}if(!sg(c))throw he("JWT Header must be a top level object",Je,t);if(e(c),c.crit!==void 0)throw new rf('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(HO(KO(s)))}catch(d){throw he("failed to parse JWT Payload body as base64url encoded JSON",GO,d)}if(!sg(u))throw he("JWT Payload must be a top level object",Je,t);let l=Mq()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw he('unexpected JWT "exp" (expiration time) claim type',Je,{claims:u});if(u.exp<=l-o)throw he('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',XO,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw he('unexpected JWT "iat" (issued at) claim type',Je,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw he('unexpected JWT "iss" (issuer) claim type',Je,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw he('unexpected JWT "nbf" (not before) claim type',Je,{claims:u});if(u.nbf>l+o)throw he('unexpected JWT "nbf" (not before) claim value',XO,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw he('unexpected JWT "aud" (audience) claim type',Je,{claims:u});return{header:c,claims:u,jwt:t}}function uZ(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw he('unexpected JWT "alg" header parameter',Je,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw he('unexpected JWT "alg" header parameter',Je,{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 he('unexpected JWT "alg" header parameter',Je,{header:o,expected:r,reason:"default value"});return}throw he('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Uu(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw he(`"${e}" parameter must be provided only once`,Je);return r}var Rge=Symbol(),Cge=Symbol();function lZ(t,e,r,o){if(Lu(t),Fu(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Ht('"parameters" must be an instance of URLSearchParams, or URL',Ui);if(Uu(r,"response"))throw he('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Je,{parameters:r});let n=Uu(r,"iss"),i=Uu(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw he('response parameter "iss" (issuer) missing',Je,{parameters:r});if(n&&n!==t.issuer)throw he('unexpected "iss" (issuer) response parameter value',Je,{expected:t.issuer,parameters:r});switch(o){case void 0:case Cge:if(i!==void 0)throw he('unexpected "state" response parameter encountered',Je,{expected:void 0,parameters:r});break;case Rge:break;default:if(yr(o,'"expectedState" argument'),i!==o)throw he(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Je,{expected:o,parameters:r})}if(Uu(r,"error"))throw new ag("authorization response from the server is an error",{cause:r});let a=Uu(r,"id_token"),c=Uu(r,"token");if(a!==void 0||c!==void 0)throw new rf("implicit and hybrid flows are not supported");return pge(new URLSearchParams(r))}async function dZ(t,e=zq){let r;try{r=await t.json()}catch(o){throw e(t),he('failed to parse "response" body as JSON',GO,o)}if(!sg(r))throw he('"response" body must be a top level object',Je,{body:r});return r}var Oge=Symbol();import{lookup as Dge}from"node:dns/promises";import{isIP as mZ}from"node:net";import{request as zge}from"node:https";import{brotliDecompressSync as jge,gunzipSync as Mge,inflateSync as Uge}from"node:zlib";var Wx=St(pZ(),1),Lge=Wx.default.IPv6.parseCIDR("2000::/3"),Fge=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function hZ(t){if(!mZ(t)||t.includes("%"))return!1;let e=Wx.default.parse(t);return Fge.has(e.range())&&(!(e instanceof Wx.default.IPv6)||e.match(Lge))}function of(t,e){let r;try{r=new URL(t)}catch{V(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)&&V(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||mZ(o)&&!hZ(o))&&V(400,"private_destination","Choose a public HTTPS destination."),r}var Jx=class{constructor(e){this.origin=e}origin;async send(e){let r=of(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&V(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))&&V(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await Dge(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!hZ(u.address)))&&V(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(f,m,h)=>{m.all?h(null,[a]):h(null,a.address,a.family)}},p=zge(r,d,f=>{let m=[],h=0;f.on("data",y=>{h+=y.length,h>n?f.destroy(new Ct(413,"body_limit","The response body is too large.")):m.push(y)}),f.on("error",l),f.on("end",()=>{try{let y=Buffer.concat(m),w=f.headers["content-encoding"];if(w&&w!=="identity"){let _=w==="gzip"?Mge:w==="deflate"?Uge:w==="br"?jge:null;if(!_)throw new Ct(502,"invalid_response","The service returned an unsupported response.");y=_(y,{maxOutputLength:n})}let b={};for(let[_,E]of Object.entries(f.headers))E!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(_)&&(b[_]=Array.isArray(E)?E.join(", "):E);u({status:f.statusCode??502,headers:b,body:new Uint8Array(y)})}catch(y){l(y)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof Ct)throw s;e.signal?.aborted&&V(409,"cancelled","The operation was cancelled."),V(502,"service_unavailable","The service could not be reached. Try again.")}}};function ug(t){let e;try{e=JSON.parse(Buffer.from(t.body).toString("utf8"))}catch{V(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&V(502,"invalid_response","The service returned an invalid response."),e}var gZ=t=>Vge("sha256").update(t).digest("hex");function sf(t,e){try{return of(new Ix(t).expand(e)).href}catch{V(400,"invalid_service_url","Check the service URL and its required fields.")}}var uN=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],lN=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&V(502,"invalid_response","The service returned an invalid expiry."),e},yZ=Object.assign(Object.create(null),{dpop:()=>V(502,"invalid_response","The service returned an unsupported token.")}),Bge=Object.assign(Object.create(null),yZ,{"user access token":()=>{}}),Gx=class{constructor(e){this.transport=e}transport;async authorize(e,r,o,n,i,s){let a=new URL(sf(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 jq(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(sf(e.authorizeUrl,r.fields)).origin,token_endpoint:sf(e.tokenUrl,r.fields)};return e.issuer&&of(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?Fq():(e.clientSecret||V(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Lq(e.clientSecret):Uq(e.clientSecret))}options(e="form"){return{[QO]: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 ug({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&ji(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&V(409,"reconnect_required","Reconnect this service to renew access."),r===429&&V(503,"service_rate_limit","The service is busy. Try again later."),V(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&V(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=lN(u.expires_in));try{let d=await(n?Wq:nZ)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:e.adapter==="ebay"?Bge:yZ});return{...i,...d}}catch(l){if(l instanceof Ct)throw l;V(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))&&V(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+lN(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&V(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?uN(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()+lN(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 p=o.parameters;(p.getAll("state").length!==1||p.get("state")!==o.state||p.getAll("code").length!==1||!p.get("code"))&&V(400,"invalid_state","Start the connection again.");let f=await this.transport.send({url:sf(e.tokenUrl,r.fields),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.tokenParams,code:p.get("code"),code_verifier:n,code_challenge_method:"S256"})});u=this.checkResponse(e,f.status,ug(f))}else{let{server:p,client:f}=this.configuration(e,r),m;try{let h=lZ(p,f,o.parameters,o.state);m=await Xq(p,f,this.authentication(r,e.clientAuth),h,e.adapter==="ebay"?r.fields.ruName:i,e.pkce?n:cN,{...this.options(e.tokenFormat),additionalParameters:e.tokenParams})}catch(h){throw(h instanceof ig||h instanceof ag)&&V(400,"invalid_state","Start the connection again."),h}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"&&V(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())&&V(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Hq(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&&V(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 sZ({...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 aZ(u,l,Response.json(await this.json(d),{status:d.status}))}catch{V(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())&&V(409,"reconnect_required","Reconnect this service to renew access."),{...o,account:i.sub,accountName:typeof i.username=="string"?i.username:i.sub,scopes:uN(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=ug(u),(u.status!==200||!i.data||typeof i.data!="object")&&V(409,"reconnect_required","Reconnect this service to renew access.");let l=i.data;return{...o,account:gZ(o.accessToken),accountName:typeof l.label=="string"?l.label:"OpenRouter",facts:l}}if(e.identity?.url){let u=await this.transport.send({url:sf(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=ug(u),(u.status===401||u.status===403)&&V(409,"reconnect_required","Reconnect this service to renew access."),u.status>=400&&V(502,"invalid_response","The service account could not be verified."),e.adapter==="github"&&u.headers["x-oauth-scopes"]!==void 0&&(o.scopes=uN(u.headers["x-oauth-scopes"].replaceAll(","," ")),o.scopesStatus="reported"),e.adapter==="google"&&i.email_verified!==!0&&V(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=ji(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||gZ(o.accessToken);return(!c||c.length>1e3)&&V(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||V(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=sf(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),p=await oZ({...u,revocation_endpoint:n},l,d,o.refreshToken??o.accessToken,this.options());try{await iZ(p)}catch{V(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&&V(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,tf(ji(n,s))]))}};function Ws(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Xx(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=ft(tf(ji(JSON.parse(Ws(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Ws(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}function Hge(t,e){return t.policy.contentType===Me.value?e.output===void 0:t.policy.contentType===Me.tokenSet&&e.output!==void 0}var Ka=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}},Yx=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 Jd(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Jd(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 ye(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Jd(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await IH(r.request,this.binding,this.keys);await hx(this.environment,p.intent);let f=Gd.parse(p.operation);if(pe[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await this.preflight(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let m=await this.execute(f,o,r.sources,c);d=await Jd(o,"succeeded",{ok:!0,result:m,error:null},this.keys)}catch(p){if(p instanceof Ka)throw p;p instanceof Kh&&(p=new Ct(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||!(p instanceof Ct)||["service_unavailable","connection_uncertain","lease_lost"].includes(p.code));d=await Jd(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof Ct?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){return e.kind==="http"?e.request:e.kind==="function"?kx(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 qo(s);let a=r.sources.find(u=>u.id===s.policy.id);if(!a||!await wO(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 ye(e.definition)!==r.functionDigest)throw new Error("Run the exact function authorized by this intent.");let n=this.request(e);if(n){if(of(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=ng(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.");VO(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(ng(a),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let u=await Kd(c.approval);if(R(u.policy.authorities.find(l=>l.id===u.authorityId))!==R(r.actor)||u.policy.origin!==r.origin||u.policy.contentType!==Me.value||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||!Hge(a,s))throw new Error("Use the input named in the signed request.");await Ou(a,r,{...n?{destination:n.url}:{}}),await Ua(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 f=>{let m=o.find(y=>y.policy.id===f.id);if(m.policy.contentType===Me.value)return Ua(m,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");a.has(f.id)||a.set(f.id,this.extension.outputs(m,r,o,n,i?.url));let h=await a.get(f.id);if(!f.output||!Object.hasOwn(h,f.output))throw new Error("Choose an available connection output.");return ft(h[f.output])};if(e.kind==="command"){let f=await Xx(e.inputs,c),m=await this.commands.execute({command:e.command,timeoutSeconds:e.timeoutSeconds,...e.stdin===void 0?{}:{stdin:e.stdin},environment:f.environment,files:f.files},n);return{...m,stdout:og(m.stdout,f.sensitive),stderr:og(m.stderr,f.sensitive)}}let u=structuredClone(i);for(let f of u.bindings){let m="";for(let h of f.parts)if(typeof h=="string")m+=h;else{let y=Ws(await c(h));s.push(y,Buffer.from(y).toString("base64"),Buffer.from(y).toString("base64url")),m+=y}VO(u,f.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}),p=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};if(Object.keys(p).length){if(d.status>=400)throw new Ct(502,"service_response","The service returned an unsuccessful response.");let f={};for(let[m,h]of Object.entries(p)){let y=d.body;if(m!==""){let b=ji(JSON.parse(Ws(y)),m);if(b===void 0)throw new Ct(400,"invalid_pointer","The response value was not found.");y=ft(typeof b=="string"?b:JSON.stringify(b))}let w=await dx(y,h.approval,r.id,this.binding,this.keys,{bytes:y.length});f[h.name]=(await this.broker.capture(h.name,w)).id}return{status:d.status,saved:f}}return{status:d.status,headers:Object.fromEntries(Object.entries(d.headers).map(([f,m])=>[f,og(m,s)])),body:og(Ws(d.body),s)}}};var aa=St(cne(),1);import{randomUUID as uAe}from"node:crypto";function lAe(t){let e=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(t);return e?`arn:${e[1]}:iam::${e[2]}:role/${e[3]}`:/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/.+$/.test(t)?t:null}async function une(t=3e3){let e=new aa.STSClient({region:process.env.AWS_REGION||"us-east-1"});try{let r=await e.send(new aa.GetCallerIdentityCommand({}),{abortSignal:AbortSignal.timeout(t)});return r.Arn?lAe(r.Arn):null}catch{return null}finally{e.destroy()}}var wk=class{async obtain(e,r,o){let n=new aa.STSClient({region:o});try{let s=(await n.send(new aa.AssumeRoleCommand({RoleArn:e,RoleSessionName:"foundation-"+uAe().slice(0,8),ExternalId:r,DurationSeconds:3600}))).Credentials;(!s?.AccessKeyId||!s.SecretAccessKey||!s.SessionToken)&&V(502,"invalid_response","AWS did not return credentials.");let a=new aa.STSClient({region:o,credentials:{accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken}});try{(await a.send(new aa.GetCallerIdentityCommand({}))).Account!==e.split(":")[4]&&V(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 Ct)throw i;V(502,"role_denied","Check the IAM role and its trust policy for this executor.")}finally{n.destroy()}}};function x4(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]&&V(400,"missing_field","Complete the required service fields."),o[n.name]?.includes("\0")&&V(400,"invalid_field","Check the service fields."),n.pattern&&(n.pattern.length>200||!(0,dne.default)(n.pattern))&&V(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))&&V(400,"invalid_field","Check the service fields.");return Object.keys(e).some(n=>!r.some(i=>i.name===n))&&V(400,"invalid_field","Remove unrecognized service fields."),o}var Pp=class{constructor(e,r,o,n,i,s=new wk){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 Gx({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.contentType===r);return n||V(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=Ba.parse(JSON.parse(Ws(await Ua(e,r,this.keys,{destination:o}))));return(await Du(n)).authorizationDigest!==e.metadata.authorizationDigest&&V(409,"connection_changed","Approve the current service account and permissions before using this connection."),n.state==="reconnect"&&r.operation!==pe.revoke&&V(409,"reconnect_required","Reconnect this service before using it."),n}async app(e,r,o,n){let i=this.source(e,Me.clientCredential,n),s=Va.parse(JSON.parse(Ws(await Ua(i,o,this.keys))));return s.methodId!==r&&V(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(!Nu(e.method))return Va.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===pe.revoke?pe.revoke:pe.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&V(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)&&V(409,"connection_expired","Start the connection again."),o}async validate(e,r,o){let n=Sx.parse(e),i=pe[n.action==="refresh"||n.action==="revoke"?n.action:"connect"];if(r.operation!==i&&V(400,"wrong_operation","Use the approved connection operation."),n.action==="start")if(n.method.kind==="oauth"){(Nu(n.method)&&!n.appId||!n.redirectUri)&&V(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)))&&V(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):Va.parse({format:1,methodId:n.methodId,generation:n.flowId,clientId:"",fields:{}});x4(n.method,a.fields),Nu(n.method)&&n.method.config.clientAuth!=="none"&&!a.clientSecret&&V(409,"app_required","Add a client secret to this OAuth application.")}else n.method.kind==="token"?x4(n.method,n.fields):n.role||V(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 Kd(n.approval);(!s.material||n.authorizationDigest!==(await Du(s.material)).authorizationDigest||a.policy.contentType!==Me.tokenSet||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()))&&V(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)&&V(409,"app_changed","Start the connection again with the current application.")}}else{let s=this.source(n.id,Me.tokenSet,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=Sx.parse(e),s="flowId"in i?i.flowId:i.id;this.active.has(s)&&V(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,Me.tokenSet,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 Du(u)}}return c.method.kind!=="oauth"&&V(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 Du(r.material),..._x(r.material)}}}async start(e,r,o){let n="oauth_"+e.flowId;await this.journal.read(n)&&V(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):Va.parse({format:1,methodId:e.methodId,generation:e.flowId,clientId:"",fields:{}}),state:lne(32).toString("base64url"),verifier:lne(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=Ba.parse({format:1,methodId:e.methodId,method:e.method,generation:S4(),appId:null,appGeneration:null,...e.method.kind==="role"?{role:e.role}:{fields:x4(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 ye(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))&&V(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)&&V(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=Ba.parse({format:1,methodId:n.input.methodId,method:n.input.method,generation:S4(),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)||V(409,"approval_required","Review this connection before saving."),o.content?(R(o.content.policy)!==R(e.approval.policy)||o.content.creationRunId!==r.id)&&V(409,"connection_uncertain","Finish saving the previously approved connection before starting another save."):(o.content=await dx(ft(R(o.material)),e.approval,r.id,this.binding,this.keys,await Du(o.material)),o.phase="committing",await this.journal.write(n,o));let i;try{i=await this.broker.capture(o.input.name,o.content,_x(o.material))}catch(s){throw s instanceof Ct&&s.status<500?s:new Ka}return o.phase="committed",await this.journal.write(n,o),{kind:"connected",id:i.id}}async recover(e,r){let o=Sx.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,_x(i.material))}catch(s){if(s instanceof Ct&&s.status<500)return null;throw new Ka}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,tf(ji(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)&&V(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=Ba.parse({...e.material,oauth:r}),n=await Du(o);return n.authorizationDigest!==e.previous.metadata.authorizationDigest&&V(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=o,e.content=await EH(e.previous,ft(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 Ou(e,{...o,operation:pe.refresh},{destination:s})}catch{V(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let a=await this.connectionApp(r,o,n),c=S4(),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(p,f)=>{l.checkpoint={token:p,response:f},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 Ct&&["connection_review","reconnect_required","account_changed"].includes(d.code))throw d;V(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 Hr(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=E4(dAe(Bs()),"custody",r.id),i=new ju(E4(n,"client"),o,r,e),s=new Tx(t,o,r,e,new Px(i)),a=new Rx(t),c=new Jx(o),u=new Pp(r,e,a.connections(),new ju(E4(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 fne(t,e){let{custody:r,keys:o,binding:n,connections:i}=Hr(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await ye(n),operation:pe.command,functionDigest:null,operationDigest:await ye(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await ye(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===Me.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Xx(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===Me.value)return Ua(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return ft(d[u.output])})}import{mkdir as mAe}from"node:fs/promises";import{join as hne}from"node:path";import{setTimeout as hAe}from"node:timers/promises";import{spawn as fAe}from"node:child_process";import{constants as $4}from"node:fs";import{open as pne,rm as pAe}from"node:fs/promises";async function mne(t){if(process.platform!=="linux"){let r=await pne(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 pAe(t,{force:!0})}}let e=await pne(t,$4.O_CREAT|$4.O_WRONLY|$4.O_NOFOLLOW,384);try{let r=fAe("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 bk(t,e){let{directory:r,keys:o,binding:n,broker:i,transport:s}=Hr(t),a=$.parse(e.id??crypto.randomUUID()),c=hne(r,"executors",a);await mAe(c,{recursive:!0,mode:448});let u=await mne(hne(c,"process.lock")),l=new AbortController,d=()=>l.abort();process.on("SIGINT",d),process.on("SIGTERM",d);try{let p=new ju(c,t.identity.origin,n,o),f=await p.read("environment_"+a),m=await une();if(f){if(await Wd(f),f.manifest.ownerId!==e.ownerId||R(f.manifest.executor)!==R(n))throw new Error("Use the owner and identity originally registered for this executor.");if((f.manifest.awsPrincipal??null)!==m){let{awsPrincipal:w,...b}=f.manifest;f=await _O({...b,...m?{awsPrincipal:m}:{},revision:b.revision+1},o),await p.write("environment_"+a,f)}}else f=await _O({format:3,id:a,origin:t.identity.origin,ownerId:e.ownerId,name:e.name,executor:n,operatorId:n.principalId,driver:e.managed?"managed":"attached",capabilities:Object.values(pe),isolation:e.isolation,...e.image?{commandImage:e.image}:{},...m?{awsPrincipal:m}:{},revision:1},o),await p.write("environment_"+a,f);await t.json("/api/environments/"+a+"/registration",{method:"PUT",body:f}),process.stdout.write(JSON.stringify({environmentId:a,identityId:n.principalId,fingerprint:await ye(n),isolation:f.manifest.isolation,...f.manifest.awsPrincipal?{awsPrincipal:f.manifest.awsPrincipal}:{},...f.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
|
|
131
131
|
`);let h=new Pp(n,o,i.connections(),p,s),y=new Yx(f,o,i,p,s,new vx({isolation:f.manifest.isolation,image:f.manifest.commandImage}),h);do{let w=[...await h.reconcile(),...await y.reconcile()];w.length&&process.stderr.write(JSON.stringify({event:"reconciliation_pending",ids:w})+`
|