alran 0.9.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ALRAN_TOOLS_NOTICES.md +11 -0
- package/README.md +11 -16
- package/assets/agents/alran/skills/alran-code-product/SKILL.md +3 -3
- package/assets/agents/alran/skills/alran-code-product/references/account-models.md +19 -16
- package/chunks/{account-commands-JZ6NXTTK.js → account-commands-GW7N3MYC.js} +1 -1
- package/chunks/{anthropic-MN33DP4E.js → anthropic-63VE6MAE.js} +1 -1
- package/chunks/{application-ITGAJ4HC.js → application-WPPTE6LU.js} +1 -1
- package/chunks/{auth-command-V3RVPLZO.js → auth-command-36RMNQZW.js} +1 -1
- package/chunks/azure-openai-responses-OIP3KVKJ.js +2 -0
- package/chunks/chunk-2K5H5GA7.js +2 -0
- package/chunks/chunk-3GGKARES.js +2 -0
- package/chunks/chunk-5RIMHTEU.js +207 -0
- package/chunks/{chunk-EYK25HWR.js → chunk-5Y76VFHY.js} +1 -1
- package/chunks/{chunk-QIN5ZBE2.js → chunk-6DOVXX7W.js} +1 -1
- package/chunks/{chunk-E3GLGDGC.js → chunk-6PFI65C6.js} +1 -1
- package/chunks/{chunk-4PDIO3M6.js → chunk-6UXSIWCB.js} +1 -1
- package/chunks/{chunk-OQNU3VPS.js → chunk-C6LAAFG2.js} +2 -2
- package/chunks/{chunk-33CNY6GP.js → chunk-CUG7F2FN.js} +1 -1
- package/chunks/chunk-DFMYLGVU.js +249 -0
- package/chunks/{chunk-IIE366LR.js → chunk-G5MOGPZ3.js} +490 -485
- package/chunks/{chunk-FC4M2B7E.js → chunk-IC6A323Q.js} +1 -1
- package/chunks/{chunk-4X22UJQH.js → chunk-IN2Z5SSJ.js} +1 -1
- package/chunks/chunk-JSTSFMGK.js +70 -0
- package/chunks/{chunk-WWNUAU4P.js → chunk-LCC45PCZ.js} +1 -1
- package/chunks/{chunk-7QLAXRD2.js → chunk-MPQ6G7LH.js} +254 -254
- package/chunks/{chunk-FUERW2DW.js → chunk-MUXNNOSQ.js} +1 -1
- package/chunks/{chunk-44VPC5LA.js → chunk-NBONSNQZ.js} +1 -1
- package/chunks/chunk-NMKRNU5O.js +2 -0
- package/chunks/chunk-NVPGGFT3.js +2 -0
- package/chunks/chunk-NZXJAHTO.js +9 -0
- package/chunks/{chunk-6255CZPL.js → chunk-PCL2CVVE.js} +1 -1
- package/chunks/chunk-PXH4SBCS.js +3 -0
- package/chunks/chunk-RLJVY75P.js +28 -0
- package/chunks/{chunk-WYANV3IX.js → chunk-RLND4AYL.js} +1 -1
- package/chunks/chunk-TJC4LPRQ.js +2 -0
- package/chunks/chunk-U4PFHJ7Z.js +27 -0
- package/chunks/chunk-V2SB4U4D.js +2 -0
- package/chunks/chunk-VGKKKM2W.js +6 -0
- package/chunks/{chunk-XFCC2CI2.js → chunk-VUISZDXX.js} +1 -1
- package/chunks/chunk-XVGPB7TW.js +21 -0
- package/chunks/{chunk-CJM7ZJ6W.js → chunk-ZDI22NOK.js} +1 -1
- package/chunks/{data-dir-LDVKDCJ2.js → data-dir-OEPRRIOO.js} +1 -1
- package/chunks/{dist-2BRD4JFU.js → dist-VKYZJYR6.js} +1 -1
- package/chunks/{dist-EXKHRFQO.js → dist-WGTMUM3E.js} +1 -1
- package/chunks/{ffi-OUPK6AY6.js → ffi-EFLUAAVX.js} +1 -1
- package/chunks/{ffi-M5UP5J6C.js → ffi-QKKA5HYI.js} +1 -1
- package/chunks/{google-UJAPMFAB.js → google-RCR46TTQ.js} +1 -1
- package/chunks/{google-vertex-VLSF55PW.js → google-vertex-Y26T7YYR.js} +1 -1
- package/chunks/{install-source-JTIUC4G4.js → install-source-63OVVBMK.js} +1 -1
- package/chunks/launcher-2UG3JPYF.js +63 -0
- package/chunks/lifecycle-5IPJRP2V.js +2 -0
- package/chunks/{main-TQGGRHTS.js → main-7SGOQBHZ.js} +2 -2
- package/chunks/{mistral-ZJZUEF2X.js → mistral-NEBDKUEI.js} +1 -1
- package/chunks/{module-6F3E5H7Y-BN7QWGYB.js → module-6F3E5H7Y-FIMLNSCK.js} +1 -1
- package/chunks/{module-asyncify-R6PWJ6ZV-P4FWSBAY.js → module-asyncify-R6PWJ6ZV-Q2HJ3NOC.js} +1 -1
- package/chunks/{multipart-parser-L6M455MS.js → multipart-parser-JVSLI2CL.js} +1 -1
- package/chunks/{network-proxy-U72JCK2I.js → network-proxy-AJO7ZW3O.js} +1 -1
- package/chunks/openai-codex-responses-L2CIGCKO.js +2 -0
- package/chunks/openai-completions-C4PHW6MD.js +2 -0
- package/chunks/openai-responses-5NVFOW4Y.js +2 -0
- package/chunks/{openrouter-G2EHY5BD.js → openrouter-BKUGQT7Z.js} +1 -1
- package/chunks/{otel-OHXIZ666.js → otel-DRJM2PIX.js} +1 -1
- package/chunks/plugin-command-CIDTOPNB.js +2 -0
- package/chunks/provider-command-UZ7KQFAC.js +2 -0
- package/chunks/run-acp-command-AKDLHKMR.js +59 -0
- package/chunks/{run-exec-command-5ADSQR2Z.js → run-exec-command-UXTPS7LC.js} +1 -1
- package/chunks/{skills-command-XXXEZAG6.js → skills-command-57TF53NO.js} +1 -1
- package/chunks/src-5PSNGHHD.js +2 -0
- package/chunks/{src-IBHIRTD7.js → src-YZ26EVSY.js} +1 -1
- package/chunks/telemetry-3NXMCOVD.js +2 -0
- package/chunks/{telemetry-command-COQG2AKK.js → telemetry-command-CMDERYNN.js} +1 -1
- package/chunks/{tools-WDBB2JKV.js → tools-CRJR35HS.js} +1 -1
- package/chunks/{undici-TUGHZJSA.js → undici-O4OQVZ6I.js} +1 -1
- package/chunks/{update-NB6OD572.js → update-ACFAGV6F.js} +1 -1
- package/cli.js +2 -3
- package/embedded/alran-tools/cli.mjs +1 -5
- package/embedded/alran-tools/manifest.json +1 -1
- package/image-preview-worker.js +1 -1
- package/matrix-mcp-stdio.js +1 -1
- package/package.json +1 -1
- package/quickjs-worker.js +1 -1
- package/chunks/azure-openai-responses-OWHMUNKC.js +0 -2
- package/chunks/chunk-C3CMJAAV.js +0 -3
- package/chunks/chunk-ENHOPPS7.js +0 -16
- package/chunks/chunk-FSNYOJPJ.js +0 -2
- package/chunks/chunk-FXOH6TEQ.js +0 -21
- package/chunks/chunk-GRXX6I72.js +0 -2
- package/chunks/chunk-GSYHBK5Q.js +0 -6
- package/chunks/chunk-IWK7PZP7.js +0 -207
- package/chunks/chunk-KCLRJQ53.js +0 -59
- package/chunks/chunk-M7GW4VMR.js +0 -27
- package/chunks/chunk-QFUV5PX6.js +0 -2
- package/chunks/chunk-TW23QKAD.js +0 -3
- package/chunks/chunk-U7U3DJHF.js +0 -2
- package/chunks/chunk-WTAJMYF2.js +0 -249
- package/chunks/chunk-YLQXZBEL.js +0 -2
- package/chunks/chunk-Z6BHCXKT.js +0 -25
- package/chunks/chunk-Z6HBNJCA.js +0 -8
- package/chunks/launcher-FCZ3EDBF.js +0 -61
- package/chunks/lifecycle-GY435YMF.js +0 -2
- package/chunks/openai-codex-responses-FPCDNRL5.js +0 -2
- package/chunks/openai-completions-D32YW6KL.js +0 -2
- package/chunks/openai-responses-ZCGSENM4.js +0 -2
- package/chunks/plugin-command-OSAFHS7C.js +0 -2
- package/chunks/provider-command-SKTCHD4E.js +0 -2
- package/chunks/run-acp-command-SG2BDMFJ.js +0 -2
- package/chunks/src-DNIDEMVV.js +0 -2
- package/chunks/telemetry-J7ZLGF5X.js +0 -2
- /package/chunks/{chunk-EOR6EDNR.js → chunk-2AYWJZ72.js} +0 -0
- /package/chunks/{chunk-YPV2X2RG.js → chunk-4XP5XUIZ.js} +0 -0
- /package/chunks/{chunk-NWB7LFOK.js → chunk-5DQTVSQV.js} +0 -0
- /package/chunks/{chunk-OIQ336YE.js → chunk-EJN3SE5B.js} +0 -0
- /package/chunks/{chunk-A7GMJNA2.js → chunk-K5DTFR6D.js} +0 -0
- /package/chunks/{chunk-ZQOALVGL.js → chunk-R44C5DM6.js} +0 -0
- /package/chunks/{chunk-PNXZWSWT.js → chunk-UJCAE7SG.js} +0 -0
- /package/chunks/{chunk-J3KCPYZT.js → chunk-W5ZOLW7T.js} +0 -0
- /package/chunks/{chunk-XAGZ6ZEU.js → chunk-XLVABFJC.js} +0 -0
- /package/chunks/{chunk-N5SVBCUB.js → chunk-XSEU4WQD.js} +0 -0
- /package/chunks/{chunk-CSOUJVKM.js → chunk-Z5HOCNTZ.js} +0 -0
- /package/chunks/{emscripten-module-ZS3PMSDF.js → emscripten-module-3WGSFZYF.js} +0 -0
- /package/chunks/{emscripten-module-XPTEOIWW.js → emscripten-module-74WUXTHL.js} +0 -0
- /package/chunks/{emscripten-module-WYNDFH3N.js → emscripten-module-MCN4Y3N4.js} +0 -0
- /package/chunks/{emscripten-module-RD6P2XH5.js → emscripten-module-NEAT5LGD.js} +0 -0
- /package/chunks/{ffi-ORLOPBB3.js → ffi-JIGPPPF7.js} +0 -0
- /package/chunks/{ffi-IO7WZQNG.js → ffi-RLX77WFG.js} +0 -0
- /package/chunks/{pdfjs-SHZAF7PF.js → pdfjs-2UOWBGC2.js} +0 -0
- /package/chunks/{photon_rs-C52RL4CI.js → photon_rs-MVWYTYTO.js} +0 -0
package/chunks/chunk-GSYHBK5Q.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
-
var x;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t;r.arrayToEnum=a=>{const s={};for(const i of a){s[i]=i}return s};r.getValidEnumValues=a=>{const s=r.objectKeys(a).filter(o=>typeof a[a[o]]!=="number");const i={};for(const o of s){i[o]=a[o]}return r.objectValues(i)};r.objectValues=a=>{return r.objectKeys(a).map(function(s){return a[s]})};r.objectKeys=typeof Object.keys==="function"?a=>Object.keys(a):a=>{const s=[];for(const i in a){if(Object.prototype.hasOwnProperty.call(a,i)){s.push(i)}}return s};r.find=(a,s)=>{for(const i of a){if(s(i))return i}return void 0};r.isInteger=typeof Number.isInteger==="function"?a=>Number.isInteger(a):a=>typeof a==="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i==="string"?`'${i}'`:i).join(s)}r.joinValues=n;r.jsonStringifyReplacer=(a,s)=>{if(typeof s==="bigint"){return s.toString()}return s}})(x||(x={}));var $e;(function(r){r.mergeShapes=(e,t)=>{return{...e,...t}}})($e||($e={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var E=r=>{const e=typeof r;switch(e){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray(r)){return f.array}if(r===null){return f.null}if(r.then&&typeof r.then==="function"&&r.catch&&typeof r.catch==="function"){return f.promise}if(typeof Map!=="undefined"&&r instanceof Map){return f.map}if(typeof Set!=="undefined"&&r instanceof Set){return f.set}if(typeof Date!=="undefined"&&r instanceof Date){return f.date}return f.object;default:return f.unknown}};var u=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var ir=r=>{const e=JSON.stringify(r,null,2);return e.replace(/"([^"]+)":/g,"$1:")};var O=class r extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[];this.addIssue=n=>{this.issues=[...this.issues,n]};this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;if(Object.setPrototypeOf){Object.setPrototypeOf(this,t)}else{this.__proto__=t}this.name="ZodError";this.issues=e}format(e){const t=e||function(s){return s.message};const n={_errors:[]};const a=s=>{for(const i of s.issues){if(i.code==="invalid_union"){i.unionErrors.map(a)}else if(i.code==="invalid_return_type"){a(i.returnTypeError)}else if(i.code==="invalid_arguments"){a(i.argumentsError)}else if(i.path.length===0){n._errors.push(t(i))}else{let o=n;let c=0;while(c<i.path.length){const p=i.path[c];const g=c===i.path.length-1;if(!g){o[p]=o[p]||{_errors:[]}}else{o[p]=o[p]||{_errors:[]};o[p]._errors.push(t(i))}o=o[p];c++}}}};a(this);return n}static assert(e){if(!(e instanceof r)){throw new Error(`Not a ZodError: ${e}`)}}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={};const n=[];for(const a of this.issues){if(a.path.length>0){const s=a.path[0];t[s]=t[s]||[];t[s].push(e(a))}else{n.push(e(a))}}return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};O.create=r=>{const e=new O(r);return e};var kt=(r,e)=>{let t;switch(r.code){case u.invalid_type:if(r.received===f.undefined){t="Required"}else{t=`Expected ${r.expected}, received ${r.received}`}break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case u.invalid_union:t=`Invalid input`;break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:t=`Invalid function arguments`;break;case u.invalid_return_type:t=`Invalid function return type`;break;case u.invalid_date:t=`Invalid date`;break;case u.invalid_string:if(typeof r.validation==="object"){if("includes"in r.validation){t=`Invalid input: must include "${r.validation.includes}"`;if(typeof r.validation.position==="number"){t=`${t} at one or more positions greater than or equal to ${r.validation.position}`}}else if("startsWith"in r.validation){t=`Invalid input: must start with "${r.validation.startsWith}"`}else if("endsWith"in r.validation){t=`Invalid input: must end with "${r.validation.endsWith}"`}else{x.assertNever(r.validation)}}else if(r.validation!=="regex"){t=`Invalid ${r.validation}`}else{t="Invalid"}break;case u.too_small:if(r.type==="array")t=`Array must contain ${r.exact?"exactly":r.inclusive?`at least`:`more than`} ${r.minimum} element(s)`;else if(r.type==="string")t=`String must contain ${r.exact?"exactly":r.inclusive?`at least`:`over`} ${r.minimum} character(s)`;else if(r.type==="number")t=`Number must be ${r.exact?`exactly equal to `:r.inclusive?`greater than or equal to `:`greater than `}${r.minimum}`;else if(r.type==="bigint")t=`Number must be ${r.exact?`exactly equal to `:r.inclusive?`greater than or equal to `:`greater than `}${r.minimum}`;else if(r.type==="date")t=`Date must be ${r.exact?`exactly equal to `:r.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(r.minimum))}`;else t="Invalid input";break;case u.too_big:if(r.type==="array")t=`Array must contain ${r.exact?`exactly`:r.inclusive?`at most`:`less than`} ${r.maximum} element(s)`;else if(r.type==="string")t=`String must contain ${r.exact?`exactly`:r.inclusive?`at most`:`under`} ${r.maximum} character(s)`;else if(r.type==="number")t=`Number must be ${r.exact?`exactly`:r.inclusive?`less than or equal to`:`less than`} ${r.maximum}`;else if(r.type==="bigint")t=`BigInt must be ${r.exact?`exactly`:r.inclusive?`less than or equal to`:`less than`} ${r.maximum}`;else if(r.type==="date")t=`Date must be ${r.exact?`exactly`:r.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(r.maximum))}`;else t="Invalid input";break;case u.custom:t=`Invalid input`;break;case u.invalid_intersection_types:t=`Intersection results could not be merged`;break;case u.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError;x.assertNever(r)}return{message:t}};var z=kt;var Me=z;function pr(r){Me=r}function ue(){return Me}var m;(function(r){r.errToObj=e=>typeof e==="string"?{message:e}:e||{};r.toString=e=>typeof e==="string"?e:e?.message})(m||(m={}));var ge=r=>{const{data:e,path:t,errorMaps:n,issueData:a}=r;const s=[...t,...a.path||[]];const i={...a,path:s};if(a.message!==void 0){return{...a,path:s,message:a.message}}let o="";const c=n.filter(p=>!!p).slice().reverse();for(const p of c){o=p(i,{data:e,defaultError:o}).message}return{...a,path:s,message:o}};var gr=[];function l(r,e){const t=ue();const n=ge({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===z?void 0:z].filter(a=>!!a)});r.common.issues.push(n)}var w=class r{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){const n=[];for(const a of t){if(a.status==="aborted")return h;if(a.status==="dirty")e.dirty();n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const a of t){const s=await a.key;const i=await a.value;n.push({key:s,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const a of t){const{key:s,value:i}=a;if(s.status==="aborted")return h;if(i.status==="aborted")return h;if(s.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(s.value!=="__proto__"&&(typeof i.value!=="undefined"||a.alwaysSet)){n[s.value]=i.value}}return{status:e.value,value:n}}};var h=Object.freeze({status:"aborted"});var q=r=>({status:"dirty",value:r});var A=r=>({status:"valid",value:r});var Oe=r=>r.status==="aborted";var Se=r=>r.status==="dirty";var F=r=>r.status==="valid";var de=r=>typeof Promise!=="undefined"&&r instanceof Promise;var N=class{constructor(e,t,n,a){this._cachedPath=[];this.parent=e;this.data=t;this._path=n;this._key=a}get path(){if(!this._cachedPath.length){if(Array.isArray(this._key)){this._cachedPath.push(...this._path,...this._key)}else{this._cachedPath.push(...this._path,this._key)}}return this._cachedPath}};var ze=(r,e)=>{if(F(e)){return{success:true,data:e.value}}else{if(!r.common.issues.length){throw new Error("Validation failed but no issues detected.")}return{success:false,get error(){if(this._error)return this._error;const t=new O(r.common.issues);this._error=t;return this._error}}}};function _(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:a}=r;if(e&&(t||n)){throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`)}if(e)return{errorMap:e,description:a};const s=(i,o)=>{const{message:c}=r;if(i.code==="invalid_enum_value"){return{message:c??o.defaultError}}if(typeof o.data==="undefined"){return{message:c??n??o.defaultError}}if(i.code!=="invalid_type")return{message:o.defaultError};return{message:c??t??o.defaultError}};return{errorMap:s,description:a}}var v=class{get description(){return this._def.description}_getType(e){return E(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(de(t)){throw new Error("Synchronous parse encountered promise.")}return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};const a=this._parseSync({data:e,path:n.path,parent:n});return ze(n,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};if(!this["~standard"].async){try{const n=this._parseSync({data:e,path:[],parent:t});return F(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered")){this["~standard"].async=true}t.common={issues:[],async:true}}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>F(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};const a=this._parse({data:e,path:n.path,parent:n});const s=await(de(a)?a:Promise.resolve(a));return ze(n,s)}refine(e,t){const n=a=>{if(typeof t==="string"||typeof t==="undefined"){return{message:t}}else if(typeof t==="function"){return t(a)}else{return t}};return this._refinement((a,s)=>{const i=e(a);const o=()=>s.addIssue({code:u.custom,...n(a)});if(typeof Promise!=="undefined"&&i instanceof Promise){return i.then(c=>{if(!c){o();return false}else{return true}})}if(!i){o();return false}else{return true}})}refinement(e,t){return this._refinement((n,a)=>{if(!e(n)){a.addIssue(typeof t==="function"?t(n,a):t);return false}else{return true}})}_refinement(e){return new C({schema:this,typeName:d.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync;this._def=e;this.parse=this.parse.bind(this);this.safeParse=this.safeParse.bind(this);this.parseAsync=this.parseAsync.bind(this);this.safeParseAsync=this.safeParseAsync.bind(this);this.spa=this.spa.bind(this);this.refine=this.refine.bind(this);this.refinement=this.refinement.bind(this);this.superRefine=this.superRefine.bind(this);this.optional=this.optional.bind(this);this.nullable=this.nullable.bind(this);this.nullish=this.nullish.bind(this);this.array=this.array.bind(this);this.promise=this.promise.bind(this);this.or=this.or.bind(this);this.and=this.and.bind(this);this.transform=this.transform.bind(this);this.brand=this.brand.bind(this);this.default=this.default.bind(this);this.catch=this.catch.bind(this);this.describe=this.describe.bind(this);this.pipe=this.pipe.bind(this);this.readonly=this.readonly.bind(this);this.isNullable=this.isNullable.bind(this);this.isOptional=this.isOptional.bind(this);this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return j.create(this,this._def)}nullable(){return M.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return V.create(this)}promise(){return W.create(this,this._def)}or(e){return ee.create([this,e],this._def)}and(e){return te.create(this,e,this._def)}transform(e){return new C({..._(this._def),schema:this,typeName:d.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e==="function"?e:()=>e;return new ie({..._(this._def),innerType:this,defaultValue:t,typeName:d.ZodDefault})}brand(){return new _e({typeName:d.ZodBranded,type:this,..._(this._def)})}catch(e){const t=typeof e==="function"?e:()=>e;return new oe({..._(this._def),innerType:this,catchValue:t,typeName:d.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ve.create(this,e)}readonly(){return ce.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};var wt=/^c[^\s-]{8,}$/i;var At=/^[0-9a-z]+$/;var Tt=/^[0-9A-HJKMNP-TV-Z]{26}$/i;var Ot=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;var St=/^[a-z0-9_-]{21}$/i;var Pt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;var Nt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;var jt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;var Ct=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;var Pe;var Zt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;var Dt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;var Rt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;var Et=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;var It=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;var $t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;var Ve=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;var Mt=new RegExp(`^${Ve}$`);function Fe(r){let e=`[0-5]\\d`;if(r.precision){e=`${e}\\.\\d{${r.precision}}`}else if(r.precision==null){e=`${e}(\\.\\d+)?`}const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function zt(r){return new RegExp(`^${Fe(r)}$`)}function Lt(r){let e=`${Ve}T${Fe(r)}`;const t=[];t.push(r.local?`Z?`:`Z`);if(r.offset)t.push(`([+-]\\d{2}:?\\d{2})`);e=`${e}(${t.join("|")})`;return new RegExp(`^${e}$`)}function Vt(r,e){if((e==="v4"||!e)&&Zt.test(r)){return true}if((e==="v6"||!e)&&Rt.test(r)){return true}return false}function Ft(r,e){if(!Pt.test(r))return false;try{const[t]=r.split(".");if(!t)return false;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"=");const a=JSON.parse(atob(n));if(typeof a!=="object"||a===null)return false;if("typ"in a&&a?.typ!=="JWT")return false;if(!a.alg)return false;if(e&&a.alg!==e)return false;return true}catch{return false}}function Ut(r,e){if((e==="v4"||!e)&&Dt.test(r)){return true}if((e==="v6"||!e)&&Et.test(r)){return true}return false}var U=class r extends v{_parse(e){if(this._def.coerce){e.data=String(e.data)}const t=this._getType(e);if(t!==f.string){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_type,expected:f.string,received:s.parsedType});return h}const n=new w;let a=void 0;for(const s of this._def.checks){if(s.kind==="min"){if(e.data.length<s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_small,minimum:s.value,type:"string",inclusive:true,exact:false,message:s.message});n.dirty()}}else if(s.kind==="max"){if(e.data.length>s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_big,maximum:s.value,type:"string",inclusive:true,exact:false,message:s.message});n.dirty()}}else if(s.kind==="length"){const i=e.data.length>s.value;const o=e.data.length<s.value;if(i||o){a=this._getOrReturnCtx(e,a);if(i){l(a,{code:u.too_big,maximum:s.value,type:"string",inclusive:true,exact:true,message:s.message})}else if(o){l(a,{code:u.too_small,minimum:s.value,type:"string",inclusive:true,exact:true,message:s.message})}n.dirty()}}else if(s.kind==="email"){if(!jt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"email",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="emoji"){if(!Pe){Pe=new RegExp(Ct,"u")}if(!Pe.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"emoji",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="uuid"){if(!Ot.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"uuid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="nanoid"){if(!St.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"nanoid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="cuid"){if(!wt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"cuid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="cuid2"){if(!At.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"cuid2",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="ulid"){if(!Tt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"ulid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="url"){try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a);l(a,{validation:"url",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="regex"){s.regex.lastIndex=0;const i=s.regex.test(e.data);if(!i){a=this._getOrReturnCtx(e,a);l(a,{validation:"regex",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="trim"){e.data=e.data.trim()}else if(s.kind==="includes"){if(!e.data.includes(s.value,s.position)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:{includes:s.value,position:s.position},message:s.message});n.dirty()}}else if(s.kind==="toLowerCase"){e.data=e.data.toLowerCase()}else if(s.kind==="toUpperCase"){e.data=e.data.toUpperCase()}else if(s.kind==="startsWith"){if(!e.data.startsWith(s.value)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:{startsWith:s.value},message:s.message});n.dirty()}}else if(s.kind==="endsWith"){if(!e.data.endsWith(s.value)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:{endsWith:s.value},message:s.message});n.dirty()}}else if(s.kind==="datetime"){const i=Lt(s);if(!i.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:"datetime",message:s.message});n.dirty()}}else if(s.kind==="date"){const i=Mt;if(!i.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:"date",message:s.message});n.dirty()}}else if(s.kind==="time"){const i=zt(s);if(!i.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:"time",message:s.message});n.dirty()}}else if(s.kind==="duration"){if(!Nt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"duration",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="ip"){if(!Vt(e.data,s.version)){a=this._getOrReturnCtx(e,a);l(a,{validation:"ip",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="jwt"){if(!Ft(e.data,s.alg)){a=this._getOrReturnCtx(e,a);l(a,{validation:"jwt",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="cidr"){if(!Ut(e.data,s.version)){a=this._getOrReturnCtx(e,a);l(a,{validation:"cidr",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="base64"){if(!It.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"base64",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="base64url"){if(!$t.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"base64url",code:u.invalid_string,message:s.message});n.dirty()}}else{x.assertNever(s)}}return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(a=>e.test(a),{validation:t,code:u.invalid_string,...m.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){if(typeof e==="string"){return this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e})}return this._addCheck({kind:"datetime",precision:typeof e?.precision==="undefined"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string"){return this._addCheck({kind:"time",precision:null,message:e})}return this._addCheck({kind:"time",precision:typeof e?.precision==="undefined"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e}get maxLength(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e}};U.create=r=>{return new U({checks:[],typeName:d.ZodString,coerce:r?.coerce??false,..._(r)})};function Bt(r,e){const t=(r.toString().split(".")[1]||"").length;const n=(e.toString().split(".")[1]||"").length;const a=t>n?t:n;const s=Number.parseInt(r.toFixed(a).replace(".",""));const i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}var H=class r extends v{constructor(){super(...arguments);this.min=this.gte;this.max=this.lte;this.step=this.multipleOf}_parse(e){if(this._def.coerce){e.data=Number(e.data)}const t=this._getType(e);if(t!==f.number){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_type,expected:f.number,received:s.parsedType});return h}let n=void 0;const a=new w;for(const s of this._def.checks){if(s.kind==="int"){if(!x.isInteger(e.data)){n=this._getOrReturnCtx(e,n);l(n,{code:u.invalid_type,expected:"integer",received:"float",message:s.message});a.dirty()}}else if(s.kind==="min"){const i=s.inclusive?e.data<s.value:e.data<=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:false,message:s.message});a.dirty()}}else if(s.kind==="max"){const i=s.inclusive?e.data>s.value:e.data>=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:false,message:s.message});a.dirty()}}else if(s.kind==="multipleOf"){if(Bt(e.data,s.value)!==0){n=this._getOrReturnCtx(e,n);l(n,{code:u.not_multiple_of,multipleOf:s.value,message:s.message});a.dirty()}}else if(s.kind==="finite"){if(!Number.isFinite(e.data)){n=this._getOrReturnCtx(e,n);l(n,{code:u.not_finite,message:s.message});a.dirty()}}else{x.assertNever(s)}}return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,m.toString(t))}gt(e,t){return this.setLimit("min",e,false,m.toString(t))}lte(e,t){return this.setLimit("max",e,true,m.toString(t))}lt(e,t){return this.setLimit("max",e,false,m.toString(t))}setLimit(e,t,n,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e}get maxValue(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null;let t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf"){return true}else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}}return Number.isFinite(t)&&Number.isFinite(e)}};H.create=r=>{return new H({checks:[],typeName:d.ZodNumber,coerce:r?.coerce||false,..._(r)})};var Y=class r extends v{constructor(){super(...arguments);this.min=this.gte;this.max=this.lte}_parse(e){if(this._def.coerce){try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}}const t=this._getType(e);if(t!==f.bigint){return this._getInvalidInput(e)}let n=void 0;const a=new w;for(const s of this._def.checks){if(s.kind==="min"){const i=s.inclusive?e.data<s.value:e.data<=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message});a.dirty()}}else if(s.kind==="max"){const i=s.inclusive?e.data>s.value:e.data>=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message});a.dirty()}}else if(s.kind==="multipleOf"){if(e.data%s.value!==BigInt(0)){n=this._getOrReturnCtx(e,n);l(n,{code:u.not_multiple_of,multipleOf:s.value,message:s.message});a.dirty()}}else{x.assertNever(s)}}return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);l(t,{code:u.invalid_type,expected:f.bigint,received:t.parsedType});return h}gte(e,t){return this.setLimit("min",e,true,m.toString(t))}gt(e,t){return this.setLimit("min",e,false,m.toString(t))}lte(e,t){return this.setLimit("max",e,true,m.toString(t))}lt(e,t){return this.setLimit("max",e,false,m.toString(t))}setLimit(e,t,n,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e}get maxValue(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e}};Y.create=r=>{return new Y({checks:[],typeName:d.ZodBigInt,coerce:r?.coerce??false,..._(r)})};var G=class extends v{_parse(e){if(this._def.coerce){e.data=Boolean(e.data)}const t=this._getType(e);if(t!==f.boolean){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.boolean,received:n.parsedType});return h}return A(e.data)}};G.create=r=>{return new G({typeName:d.ZodBoolean,coerce:r?.coerce||false,..._(r)})};var K=class r extends v{_parse(e){if(this._def.coerce){e.data=new Date(e.data)}const t=this._getType(e);if(t!==f.date){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_type,expected:f.date,received:s.parsedType});return h}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_date});return h}const n=new w;let a=void 0;for(const s of this._def.checks){if(s.kind==="min"){if(e.data.getTime()<s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_small,message:s.message,inclusive:true,exact:false,minimum:s.value,type:"date"});n.dirty()}}else if(s.kind==="max"){if(e.data.getTime()>s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_big,message:s.message,inclusive:true,exact:false,maximum:s.value,type:"date"});n.dirty()}}else{x.assertNever(s)}}return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e!=null?new Date(e):null}};K.create=r=>{return new K({checks:[],coerce:r?.coerce||false,typeName:d.ZodDate,..._(r)})};var le=class extends v{_parse(e){const t=this._getType(e);if(t!==f.symbol){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.symbol,received:n.parsedType});return h}return A(e.data)}};le.create=r=>{return new le({typeName:d.ZodSymbol,..._(r)})};var Q=class extends v{_parse(e){const t=this._getType(e);if(t!==f.undefined){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.undefined,received:n.parsedType});return h}return A(e.data)}};Q.create=r=>{return new Q({typeName:d.ZodUndefined,..._(r)})};var X=class extends v{_parse(e){const t=this._getType(e);if(t!==f.null){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.null,received:n.parsedType});return h}return A(e.data)}};X.create=r=>{return new X({typeName:d.ZodNull,..._(r)})};var B=class extends v{constructor(){super(...arguments);this._any=true}_parse(e){return A(e.data)}};B.create=r=>{return new B({typeName:d.ZodAny,..._(r)})};var L=class extends v{constructor(){super(...arguments);this._unknown=true}_parse(e){return A(e.data)}};L.create=r=>{return new L({typeName:d.ZodUnknown,..._(r)})};var R=class extends v{_parse(e){const t=this._getOrReturnCtx(e);l(t,{code:u.invalid_type,expected:f.never,received:t.parsedType});return h}};R.create=r=>{return new R({typeName:d.ZodNever,..._(r)})};var pe=class extends v{_parse(e){const t=this._getType(e);if(t!==f.undefined){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.void,received:n.parsedType});return h}return A(e.data)}};pe.create=r=>{return new pe({typeName:d.ZodVoid,..._(r)})};var V=class r extends v{_parse(e){const{ctx:t,status:n}=this._processInputParams(e);const a=this._def;if(t.parsedType!==f.array){l(t,{code:u.invalid_type,expected:f.array,received:t.parsedType});return h}if(a.exactLength!==null){const i=t.data.length>a.exactLength.value;const o=t.data.length<a.exactLength.value;if(i||o){l(t,{code:i?u.too_big:u.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:a.exactLength.message});n.dirty()}}if(a.minLength!==null){if(t.data.length<a.minLength.value){l(t,{code:u.too_small,minimum:a.minLength.value,type:"array",inclusive:true,exact:false,message:a.minLength.message});n.dirty()}}if(a.maxLength!==null){if(t.data.length>a.maxLength.value){l(t,{code:u.too_big,maximum:a.maxLength.value,type:"array",inclusive:true,exact:false,message:a.maxLength.message});n.dirty()}}if(t.common.async){return Promise.all([...t.data].map((i,o)=>{return a.type._parseAsync(new N(t,i,t.path,o))})).then(i=>{return w.mergeArray(n,i)})}const s=[...t.data].map((i,o)=>{return a.type._parseSync(new N(t,i,t.path,o))});return w.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};V.create=(r,e)=>{return new V({type:r,minLength:null,maxLength:null,exactLength:null,typeName:d.ZodArray,..._(e)})};function J(r){if(r instanceof S){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=j.create(J(n))}return new S({...r._def,shape:()=>e})}else if(r instanceof V){return new V({...r._def,type:J(r.element)})}else if(r instanceof j){return j.create(J(r.unwrap()))}else if(r instanceof M){return M.create(J(r.unwrap()))}else if(r instanceof $){return $.create(r.items.map(e=>J(e)))}else{return r}}var S=class r extends v{constructor(){super(...arguments);this._cached=null;this.nonstrict=this.passthrough;this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape();const t=x.objectKeys(e);this._cached={shape:e,keys:t};return this._cached}_parse(e){const t=this._getType(e);if(t!==f.object){const p=this._getOrReturnCtx(e);l(p,{code:u.invalid_type,expected:f.object,received:p.parsedType});return h}const{status:n,ctx:a}=this._processInputParams(e);const{shape:s,keys:i}=this._getCached();const o=[];if(!(this._def.catchall instanceof R&&this._def.unknownKeys==="strip")){for(const p in a.data){if(!i.includes(p)){o.push(p)}}}const c=[];for(const p of i){const g=s[p];const P=a.data[p];c.push({key:{status:"valid",value:p},value:g._parse(new N(a,P,a.path,p)),alwaysSet:p in a.data})}if(this._def.catchall instanceof R){const p=this._def.unknownKeys;if(p==="passthrough"){for(const g of o){c.push({key:{status:"valid",value:g},value:{status:"valid",value:a.data[g]}})}}else if(p==="strict"){if(o.length>0){l(a,{code:u.unrecognized_keys,keys:o});n.dirty()}}else if(p==="strip"){}else{throw new Error(`Internal ZodObject error: invalid unknownKeys value.`)}}else{const p=this._def.catchall;for(const g of o){const P=a.data[g];c.push({key:{status:"valid",value:g},value:p._parse(new N(a,P,a.path,g)),alwaysSet:g in a.data})}}if(a.common.async){return Promise.resolve().then(async()=>{const p=[];for(const g of c){const P=await g.key;const Ae=await g.value;p.push({key:P,value:Ae,alwaysSet:g.alwaysSet})}return p}).then(p=>{return w.mergeObjectSync(n,p)})}else{return w.mergeObjectSync(n,c)}}get shape(){return this._def.shape()}strict(e){m.errToObj;return new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{const a=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:m.errToObj(e).message??a};return{message:a}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){const t=new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:d.ZodObject});return t}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){const t={};for(const n of x.objectKeys(e)){if(e[n]&&this.shape[n]){t[n]=this.shape[n]}}return new r({...this._def,shape:()=>t})}omit(e){const t={};for(const n of x.objectKeys(this.shape)){if(!e[n]){t[n]=this.shape[n]}}return new r({...this._def,shape:()=>t})}deepPartial(){return J(this)}partial(e){const t={};for(const n of x.objectKeys(this.shape)){const a=this.shape[n];if(e&&!e[n]){t[n]=a}else{t[n]=a.optional()}}return new r({...this._def,shape:()=>t})}required(e){const t={};for(const n of x.objectKeys(this.shape)){if(e&&!e[n]){t[n]=this.shape[n]}else{const a=this.shape[n];let s=a;while(s instanceof j){s=s._def.innerType}t[n]=s}}return new r({...this._def,shape:()=>t})}keyof(){return Ue(x.objectKeys(this.shape))}};S.create=(r,e)=>{return new S({shape:()=>r,unknownKeys:"strip",catchall:R.create(),typeName:d.ZodObject,..._(e)})};S.strictCreate=(r,e)=>{return new S({shape:()=>r,unknownKeys:"strict",catchall:R.create(),typeName:d.ZodObject,..._(e)})};S.lazycreate=(r,e)=>{return new S({shape:r,unknownKeys:"strip",catchall:R.create(),typeName:d.ZodObject,..._(e)})};var ee=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);const n=this._def.options;function a(s){for(const o of s){if(o.result.status==="valid"){return o.result}}for(const o of s){if(o.result.status==="dirty"){t.common.issues.push(...o.ctx.common.issues);return o.result}}const i=s.map(o=>new O(o.ctx.common.issues));l(t,{code:u.invalid_union,unionErrors:i});return h}if(t.common.async){return Promise.all(n.map(async s=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a)}else{let s=void 0;const i=[];for(const c of n){const p={...t,common:{...t.common,issues:[]},parent:null};const g=c._parseSync({data:t.data,path:t.path,parent:p});if(g.status==="valid"){return g}else if(g.status==="dirty"&&!s){s={result:g,ctx:p}}if(p.common.issues.length){i.push(p.common.issues)}}if(s){t.common.issues.push(...s.ctx.common.issues);return s.result}const o=i.map(c=>new O(c));l(t,{code:u.invalid_union,unionErrors:o});return h}}get options(){return this._def.options}};ee.create=(r,e)=>{return new ee({options:r,typeName:d.ZodUnion,..._(e)})};var I=r=>{if(r instanceof re){return I(r.schema)}else if(r instanceof C){return I(r.innerType())}else if(r instanceof ne){return[r.value]}else if(r instanceof ae){return r.options}else if(r instanceof se){return x.objectValues(r.enum)}else if(r instanceof ie){return I(r._def.innerType)}else if(r instanceof Q){return[void 0]}else if(r instanceof X){return[null]}else if(r instanceof j){return[void 0,...I(r.unwrap())]}else if(r instanceof M){return[null,...I(r.unwrap())]}else if(r instanceof _e){return I(r.unwrap())}else if(r instanceof ce){return I(r.unwrap())}else if(r instanceof oe){return I(r._def.innerType)}else{return[]}};var Ne=class r extends v{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object){l(t,{code:u.invalid_type,expected:f.object,received:t.parsedType});return h}const n=this.discriminator;const a=t.data[n];const s=this.optionsMap.get(a);if(!s){l(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]});return h}if(t.common.async){return s._parseAsync({data:t.data,path:t.path,parent:t})}else{return s._parseSync({data:t.data,path:t.path,parent:t})}}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const a=new Map;for(const s of t){const i=I(s.shape[e]);if(!i.length){throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`)}for(const o of i){if(a.has(o)){throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`)}a.set(o,s)}}return new r({typeName:d.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,..._(n)})}};function je(r,e){const t=E(r);const n=E(e);if(r===e){return{valid:true,data:r}}else if(t===f.object&&n===f.object){const a=x.objectKeys(e);const s=x.objectKeys(r).filter(o=>a.indexOf(o)!==-1);const i={...r,...e};for(const o of s){const c=je(r[o],e[o]);if(!c.valid){return{valid:false}}i[o]=c.data}return{valid:true,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length){return{valid:false}}const a=[];for(let s=0;s<r.length;s++){const i=r[s];const o=e[s];const c=je(i,o);if(!c.valid){return{valid:false}}a.push(c.data)}return{valid:true,data:a}}else if(t===f.date&&n===f.date&&+r===+e){return{valid:true,data:r}}else{return{valid:false}}}var te=class extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);const a=(s,i)=>{if(Oe(s)||Oe(i)){return h}const o=je(s.value,i.value);if(!o.valid){l(n,{code:u.invalid_intersection_types});return h}if(Se(s)||Se(i)){t.dirty()}return{status:t.value,value:o.data}};if(n.common.async){return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i))}else{return a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}};te.create=(r,e,t)=>{return new te({left:r,right:e,typeName:d.ZodIntersection,..._(t)})};var $=class r extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array){l(n,{code:u.invalid_type,expected:f.array,received:n.parsedType});return h}if(n.data.length<this._def.items.length){l(n,{code:u.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"});return h}const a=this._def.rest;if(!a&&n.data.length>this._def.items.length){l(n,{code:u.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"});t.dirty()}const s=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;if(!c)return null;return c._parse(new N(n,i,n.path,o))}).filter(i=>!!i);if(n.common.async){return Promise.all(s).then(i=>{return w.mergeArray(t,i)})}else{return w.mergeArray(t,s)}}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};$.create=(r,e)=>{if(!Array.isArray(r)){throw new Error("You must pass an array of schemas to z.tuple([ ... ])")}return new $({items:r,typeName:d.ZodTuple,rest:null,..._(e)})};var Ce=class r extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object){l(n,{code:u.invalid_type,expected:f.object,received:n.parsedType});return h}const a=[];const s=this._def.keyType;const i=this._def.valueType;for(const o in n.data){a.push({key:s._parse(new N(n,o,n.path,o)),value:i._parse(new N(n,n.data[o],n.path,o)),alwaysSet:o in n.data})}if(n.common.async){return w.mergeObjectAsync(t,a)}else{return w.mergeObjectSync(t,a)}}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof v){return new r({keyType:e,valueType:t,typeName:d.ZodRecord,..._(n)})}return new r({keyType:U.create(),valueType:e,typeName:d.ZodRecord,..._(t)})}};var fe=class extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map){l(n,{code:u.invalid_type,expected:f.map,received:n.parsedType});return h}const a=this._def.keyType;const s=this._def.valueType;const i=[...n.data.entries()].map(([o,c],p)=>{return{key:a._parse(new N(n,o,n.path,[p,"key"])),value:s._parse(new N(n,c,n.path,[p,"value"]))}});if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const p=await c.key;const g=await c.value;if(p.status==="aborted"||g.status==="aborted"){return h}if(p.status==="dirty"||g.status==="dirty"){t.dirty()}o.set(p.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of i){const p=c.key;const g=c.value;if(p.status==="aborted"||g.status==="aborted"){return h}if(p.status==="dirty"||g.status==="dirty"){t.dirty()}o.set(p.value,g.value)}return{status:t.value,value:o}}}};fe.create=(r,e,t)=>{return new fe({valueType:e,keyType:r,typeName:d.ZodMap,..._(t)})};var me=class r extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set){l(n,{code:u.invalid_type,expected:f.set,received:n.parsedType});return h}const a=this._def;if(a.minSize!==null){if(n.data.size<a.minSize.value){l(n,{code:u.too_small,minimum:a.minSize.value,type:"set",inclusive:true,exact:false,message:a.minSize.message});t.dirty()}}if(a.maxSize!==null){if(n.data.size>a.maxSize.value){l(n,{code:u.too_big,maximum:a.maxSize.value,type:"set",inclusive:true,exact:false,message:a.maxSize.message});t.dirty()}}const s=this._def.valueType;function i(c){const p=new Set;for(const g of c){if(g.status==="aborted")return h;if(g.status==="dirty")t.dirty();p.add(g.value)}return{status:t.value,value:p}}const o=[...n.data.values()].map((c,p)=>s._parse(new N(n,c,n.path,p)));if(n.common.async){return Promise.all(o).then(c=>i(c))}else{return i(o)}}min(e,t){return new r({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};me.create=(r,e)=>{return new me({valueType:r,minSize:null,maxSize:null,typeName:d.ZodSet,..._(e)})};var Ze=class r extends v{constructor(){super(...arguments);this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function){l(t,{code:u.invalid_type,expected:f.function,received:t.parsedType});return h}function n(o,c){return ge({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ue(),z].filter(p=>!!p),issueData:{code:u.invalid_arguments,argumentsError:c}})}function a(o,c){return ge({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ue(),z].filter(p=>!!p),issueData:{code:u.invalid_return_type,returnTypeError:c}})}const s={errorMap:t.common.contextualErrorMap};const i=t.data;if(this._def.returns instanceof W){const o=this;return A(async function(...c){const p=new O([]);const g=await o._def.args.parseAsync(c,s).catch(Te=>{p.addIssue(n(c,Te));throw p});const P=await Reflect.apply(i,this,g);const Ae=await o._def.returns._def.type.parseAsync(P,s).catch(Te=>{p.addIssue(a(P,Te));throw p});return Ae})}else{const o=this;return A(function(...c){const p=o._def.args.safeParse(c,s);if(!p.success){throw new O([n(c,p.error)])}const g=Reflect.apply(i,this,p.data);const P=o._def.returns.safeParse(g,s);if(!P.success){throw new O([a(g,P.error)])}return P.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:$.create(e).rest(L.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){const t=this.parse(e);return t}strictImplement(e){const t=this.parse(e);return t}static create(e,t,n){return new r({args:e?e:$.create([]).rest(L.create()),returns:t||L.create(),typeName:d.ZodFunction,..._(n)})}};var re=class extends v{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);const n=this._def.getter();return n._parse({data:t.data,path:t.path,parent:t})}};re.create=(r,e)=>{return new re({getter:r,typeName:d.ZodLazy,..._(e)})};var ne=class extends v{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);l(t,{received:t.data,code:u.invalid_literal,expected:this._def.value});return h}return{status:"valid",value:e.data}}get value(){return this._def.value}};ne.create=(r,e)=>{return new ne({value:r,typeName:d.ZodLiteral,..._(e)})};function Ue(r,e){return new ae({values:r,typeName:d.ZodEnum,..._(e)})}var ae=class r extends v{_parse(e){if(typeof e.data!=="string"){const t=this._getOrReturnCtx(e);const n=this._def.values;l(t,{expected:x.joinValues(n),received:t.parsedType,code:u.invalid_type});return h}if(!this._cache){this._cache=new Set(this._def.values)}if(!this._cache.has(e.data)){const t=this._getOrReturnCtx(e);const n=this._def.values;l(t,{received:t.data,code:u.invalid_enum_value,options:n});return h}return A(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values){e[t]=t}return e}get Values(){const e={};for(const t of this._def.values){e[t]=t}return e}get Enum(){const e={};for(const t of this._def.values){e[t]=t}return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};ae.create=Ue;var se=class extends v{_parse(e){const t=x.getValidEnumValues(this._def.values);const n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){const a=x.objectValues(t);l(n,{expected:x.joinValues(a),received:n.parsedType,code:u.invalid_type});return h}if(!this._cache){this._cache=new Set(x.getValidEnumValues(this._def.values))}if(!this._cache.has(e.data)){const a=x.objectValues(t);l(n,{received:n.data,code:u.invalid_enum_value,options:a});return h}return A(e.data)}get enum(){return this._def.values}};se.create=(r,e)=>{return new se({values:r,typeName:d.ZodNativeEnum,..._(e)})};var W=class extends v{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===false){l(t,{code:u.invalid_type,expected:f.promise,received:t.parsedType});return h}const n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return A(n.then(a=>{return this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})}))}};W.create=(r,e)=>{return new W({type:r,typeName:d.ZodPromise,..._(e)})};var C=class extends v{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===d.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);const a=this._def.effect||null;const s={addIssue:i=>{l(n,i);if(i.fatal){t.abort()}else{t.dirty()}},get path(){return n.path}};s.addIssue=s.addIssue.bind(s);if(a.type==="preprocess"){const i=a.transform(n.data,s);if(n.common.async){return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return h;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});if(c.status==="aborted")return h;if(c.status==="dirty")return q(c.value);if(t.value==="dirty")return q(c.value);return c})}else{if(t.value==="aborted")return h;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});if(o.status==="aborted")return h;if(o.status==="dirty")return q(o.value);if(t.value==="dirty")return q(o.value);return o}}if(a.type==="refinement"){const i=o=>{const c=a.refinement(o,s);if(n.common.async){return Promise.resolve(c)}if(c instanceof Promise){throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.")}return o};if(n.common.async===false){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return h;if(o.status==="dirty")t.dirty();i(o.value);return{status:t.value,value:o.value}}else{return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>{if(o.status==="aborted")return h;if(o.status==="dirty")t.dirty();return i(o.value).then(()=>{return{status:t.value,value:o.value}})})}}if(a.type==="transform"){if(n.common.async===false){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!F(i))return h;const o=a.transform(i.value,s);if(o instanceof Promise){throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`)}return{status:t.value,value:o}}else{return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>{if(!F(i))return h;return Promise.resolve(a.transform(i.value,s)).then(o=>({status:t.value,value:o}))})}}x.assertNever(a)}};C.create=(r,e,t)=>{return new C({schema:r,typeName:d.ZodEffects,effect:e,..._(t)})};C.createWithPreprocess=(r,e,t)=>{return new C({schema:e,effect:{type:"preprocess",transform:r},typeName:d.ZodEffects,..._(t)})};var j=class extends v{_parse(e){const t=this._getType(e);if(t===f.undefined){return A(void 0)}return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(r,e)=>{return new j({innerType:r,typeName:d.ZodOptional,..._(e)})};var M=class extends v{_parse(e){const t=this._getType(e);if(t===f.null){return A(null)}return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};M.create=(r,e)=>{return new M({innerType:r,typeName:d.ZodNullable,..._(e)})};var ie=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;if(t.parsedType===f.undefined){n=this._def.defaultValue()}return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ie.create=(r,e)=>{return new ie({innerType:r,typeName:d.ZodDefault,defaultValue:typeof e.default==="function"?e.default:()=>e.default,..._(e)})};var oe=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);const n={...t,common:{...t.common,issues:[]}};const a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(de(a)){return a.then(s=>{return{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new O(n.common.issues)},input:n.data})}})}else{return{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new O(n.common.issues)},input:n.data})}}}removeCatch(){return this._def.innerType}};oe.create=(r,e)=>{return new oe({innerType:r,typeName:d.ZodCatch,catchValue:typeof e.catch==="function"?e.catch:()=>e.catch,..._(e)})};var he=class extends v{_parse(e){const t=this._getType(e);if(t!==f.nan){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.nan,received:n.parsedType});return h}return{status:"valid",value:e.data}}};he.create=r=>{return new he({typeName:d.ZodNaN,..._(r)})};var Ar=Symbol("zod_brand");var _e=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);const n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};var ve=class r extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){const a=async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(s.status==="aborted")return h;if(s.status==="dirty"){t.dirty();return q(s.value)}else{return this._def.out._parseAsync({data:s.value,path:n.path,parent:n})}};return a()}else{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(a.status==="aborted")return h;if(a.status==="dirty"){t.dirty();return{status:"dirty",value:a.value}}else{return this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}}static create(e,t){return new r({in:e,out:t,typeName:d.ZodPipeline})}};var ce=class extends v{_parse(e){const t=this._def.innerType._parse(e);const n=a=>{if(F(a)){a.value=Object.freeze(a.value)}return a};return de(t)?t.then(a=>n(a)):n(t)}unwrap(){return this._def.innerType}};ce.create=(r,e)=>{return new ce({innerType:r,typeName:d.ZodReadonly,..._(e)})};function Le(r,e){const t=typeof r==="function"?r(e):typeof r==="string"?{message:r}:r;const n=typeof t==="string"?{message:t}:t;return n}function Wt(r,e={},t){if(r)return B.create().superRefine((n,a)=>{const s=r(n);if(s instanceof Promise){return s.then(i=>{if(!i){const o=Le(e,n);const c=o.fatal??t??true;a.addIssue({code:"custom",...o,fatal:c})}})}if(!s){const i=Le(e,n);const o=i.fatal??t??true;a.addIssue({code:"custom",...i,fatal:o})}return});return B.create()}var Tr={object:S.lazycreate};var d;(function(r){r["ZodString"]="ZodString";r["ZodNumber"]="ZodNumber";r["ZodNaN"]="ZodNaN";r["ZodBigInt"]="ZodBigInt";r["ZodBoolean"]="ZodBoolean";r["ZodDate"]="ZodDate";r["ZodSymbol"]="ZodSymbol";r["ZodUndefined"]="ZodUndefined";r["ZodNull"]="ZodNull";r["ZodAny"]="ZodAny";r["ZodUnknown"]="ZodUnknown";r["ZodNever"]="ZodNever";r["ZodVoid"]="ZodVoid";r["ZodArray"]="ZodArray";r["ZodObject"]="ZodObject";r["ZodUnion"]="ZodUnion";r["ZodDiscriminatedUnion"]="ZodDiscriminatedUnion";r["ZodIntersection"]="ZodIntersection";r["ZodTuple"]="ZodTuple";r["ZodRecord"]="ZodRecord";r["ZodMap"]="ZodMap";r["ZodSet"]="ZodSet";r["ZodFunction"]="ZodFunction";r["ZodLazy"]="ZodLazy";r["ZodLiteral"]="ZodLiteral";r["ZodEnum"]="ZodEnum";r["ZodEffects"]="ZodEffects";r["ZodNativeEnum"]="ZodNativeEnum";r["ZodOptional"]="ZodOptional";r["ZodNullable"]="ZodNullable";r["ZodDefault"]="ZodDefault";r["ZodCatch"]="ZodCatch";r["ZodPromise"]="ZodPromise";r["ZodBranded"]="ZodBranded";r["ZodPipeline"]="ZodPipeline";r["ZodReadonly"]="ZodReadonly"})(d||(d={}));var Or=(r,e={message:`Input not instance of ${r.name}`})=>Wt(t=>t instanceof r,e);var qt=U.create;var Jt=H.create;var Sr=he.create;var Pr=Y.create;var Ht=G.create;var Nr=K.create;var jr=le.create;var Cr=Q.create;var Zr=X.create;var Dr=B.create;var Rr=L.create;var Er=R.create;var Ir=pe.create;var $r=V.create;var Mr=S.create;var zr=S.strictCreate;var Lr=ee.create;var Vr=Ne.create;var Fr=te.create;var Ur=$.create;var Br=Ce.create;var Wr=fe.create;var qr=me.create;var Jr=Ze.create;var Hr=re.create;var Yr=ne.create;var Gr=ae.create;var Kr=se.create;var Qr=W.create;var Xr=C.create;var en=j.create;var tn=M.create;var rn=C.createWithPreprocess;var nn=ve.create;var an=()=>qt().optional();var sn=()=>Jt().optional();var on=()=>Ht().optional();var cn={string:(r=>U.create({...r,coerce:true})),number:(r=>H.create({...r,coerce:true})),boolean:(r=>G.create({...r,coerce:true})),bigint:(r=>Y.create({...r,coerce:true})),date:(r=>K.create({...r,coerce:true}))};var un=h;var We=Symbol("Let zodToJsonSchema decide on which parser to use");var Be={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:true,rejectedAdditionalProperties:false,definitionPath:"definitions",target:"jsonSchema7",strictUnions:false,definitions:{},errorMessages:false,markdownDescription:false,patternStrategy:"escape",applyRegexFlags:false,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};var qe=r=>typeof r==="string"?{...Be,name:r}:{...Be,...r};var xe=(r,e)=>{let t=0;for(;t<r.length&&t<e.length;t++){if(r[t]!==e[t])break}return[(r.length-t).toString(),...e.slice(t)].join("/")};function k(r){if(r.target!=="openAi"){return{}}const e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];r.flags.hasReferencedOpenAiAnyType=true;return{$ref:r.$refStrategy==="relative"?xe(e,r.currentPath):e.join("/")}}function De(r,e,t,n){if(!n?.errorMessages)return;if(t){r.errorMessage={...r.errorMessage,[e]:t}}}function b(r,e,t,n,a){r[e]=t;De(r,e,n,a)}function Je(r,e){const t={type:"array"};if(r.type?._def&&r.type?._def?.typeName!==d.ZodAny){t.items=y(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})}if(r.minLength){b(t,"minItems",r.minLength.value,r.minLength.message,e)}if(r.maxLength){b(t,"maxItems",r.maxLength.value,r.maxLength.message,e)}if(r.exactLength){b(t,"minItems",r.exactLength.value,r.exactLength.message,e);b(t,"maxItems",r.exactLength.value,r.exactLength.message,e)}return t}function He(r,e){const t={type:"integer",format:"int64"};if(!r.checks)return t;for(const n of r.checks){switch(n.kind){case"min":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"minimum",n.value,n.message,e)}else{b(t,"exclusiveMinimum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMinimum=true}b(t,"minimum",n.value,n.message,e)}break;case"max":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"maximum",n.value,n.message,e)}else{b(t,"exclusiveMaximum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMaximum=true}b(t,"maximum",n.value,n.message,e)}break;case"multipleOf":b(t,"multipleOf",n.value,n.message,e);break}}return t}function Ye(){return{type:"boolean"}}function be(r,e){return y(r.type._def,e)}var Ge=(r,e)=>{return y(r.innerType._def,e)};function Re(r,e,t){const n=t??e.dateStrategy;if(Array.isArray(n)){return{anyOf:n.map((a,s)=>Re(r,e,a))}}switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Yt(r,e)}}var Yt=(r,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3"){return t}for(const n of r.checks){switch(n.kind){case"min":b(t,"minimum",n.value,n.message,e);break;case"max":b(t,"maximum",n.value,n.message,e);break}}return t};function Ke(r,e){return{...y(r.innerType._def,e),default:r.defaultValue()}}function Qe(r,e){return e.effectStrategy==="input"?y(r.schema._def,e):k(e)}function Xe(r){return{type:"string",enum:Array.from(r.values)}}var Gt=r=>{if("type"in r&&r.type==="string")return false;return"allOf"in r};function et(r,e){const t=[y(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),y(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:false}:void 0;const a=[];t.forEach(s=>{if(Gt(s)){a.push(...s.allOf);if(s.unevaluatedProperties===void 0){n=void 0}}else{let i=s;if("additionalProperties"in s&&s.additionalProperties===false){const{additionalProperties:o,...c}=s;i=c}else{n=void 0}a.push(i)}});return a.length?{allOf:a,...n}:void 0}function tt(r,e){const t=typeof r.value;if(t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"){return{type:Array.isArray(r.value)?"array":"object"}}if(e.target==="openApi3"){return{type:t==="bigint"?"integer":t,enum:[r.value]}}return{type:t==="bigint"?"integer":t,const:r.value}}var Ee=void 0;var Z={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Ee===void 0){Ee=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}return Ee},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ke(r,e){const t={type:"string"};if(r.checks){for(const n of r.checks){switch(n.kind){case"min":b(t,"minLength",typeof t.minLength==="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":b(t,"maxLength",typeof t.maxLength==="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":D(t,"email",n.message,e);break;case"format:idn-email":D(t,"idn-email",n.message,e);break;case"pattern:zod":T(t,Z.email,n.message,e);break}break;case"url":D(t,"uri",n.message,e);break;case"uuid":D(t,"uuid",n.message,e);break;case"regex":T(t,n.regex,n.message,e);break;case"cuid":T(t,Z.cuid,n.message,e);break;case"cuid2":T(t,Z.cuid2,n.message,e);break;case"startsWith":T(t,RegExp(`^${Ie(n.value,e)}`),n.message,e);break;case"endsWith":T(t,RegExp(`${Ie(n.value,e)}$`),n.message,e);break;case"datetime":D(t,"date-time",n.message,e);break;case"date":D(t,"date",n.message,e);break;case"time":D(t,"time",n.message,e);break;case"duration":D(t,"duration",n.message,e);break;case"length":b(t,"minLength",typeof t.minLength==="number"?Math.max(t.minLength,n.value):n.value,n.message,e);b(t,"maxLength",typeof t.maxLength==="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{T(t,RegExp(Ie(n.value,e)),n.message,e);break}case"ip":{if(n.version!=="v6"){D(t,"ipv4",n.message,e)}if(n.version!=="v4"){D(t,"ipv6",n.message,e)}break}case"base64url":T(t,Z.base64url,n.message,e);break;case"jwt":T(t,Z.jwt,n.message,e);break;case"cidr":{if(n.version!=="v6"){T(t,Z.ipv4Cidr,n.message,e)}if(n.version!=="v4"){T(t,Z.ipv6Cidr,n.message,e)}break}case"emoji":T(t,Z.emoji(),n.message,e);break;case"ulid":{T(t,Z.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{D(t,"binary",n.message,e);break}case"contentEncoding:base64":{b(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{T(t,Z.base64,n.message,e);break}}break}case"nanoid":{T(t,Z.nanoid,n.message,e)}case"toLowerCase":case"toUpperCase":case"trim":break;default:(a=>{})(n)}}}return t}function Ie(r,e){return e.patternStrategy==="escape"?Qt(r):r}var Kt=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Qt(r){let e="";for(let t=0;t<r.length;t++){if(!Kt.has(r[t])){e+="\\"}e+=r[t]}return e}function D(r,e,t,n){if(r.format||r.anyOf?.some(a=>a.format)){if(!r.anyOf){r.anyOf=[]}if(r.format){r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}});delete r.format;if(r.errorMessage){delete r.errorMessage.format;if(Object.keys(r.errorMessage).length===0){delete r.errorMessage}}}r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})}else{b(r,"format",e,t,n)}}function T(r,e,t,n){if(r.pattern||r.allOf?.some(a=>a.pattern)){if(!r.allOf){r.allOf=[]}if(r.pattern){r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}});delete r.pattern;if(r.errorMessage){delete r.errorMessage.pattern;if(Object.keys(r.errorMessage).length===0){delete r.errorMessage}}}r.allOf.push({pattern:rt(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})}else{b(r,"pattern",rt(e,n),t,n)}}function rt(r,e){if(!e.applyRegexFlags||!r.flags){return r.source}const t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")};const n=t.i?r.source.toLowerCase():r.source;let a="";let s=false;let i=false;let o=false;for(let c=0;c<n.length;c++){if(s){a+=n[c];s=false;continue}if(t.i){if(i){if(n[c].match(/[a-z]/)){if(o){a+=n[c];a+=`${n[c-2]}-${n[c]}`.toUpperCase();o=false}else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)){a+=n[c];o=true}else{a+=`${n[c]}${n[c].toUpperCase()}`}continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){a+=`(^|(?<=[\r
|
|
3
|
-
]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
|
|
4
|
-
]))`;continue}}if(t.s&&n[c]==="."){a+=i?`${n[c]}\r
|
|
5
|
-
`:`[${n[c]}\r
|
|
6
|
-
]`;continue}a+=n[c];if(n[c]==="\\"){s=true}else if(i&&n[c]==="]"){i=false}else if(!i&&n[c]==="["){i=true}}try{new RegExp(a)}catch{console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);return r.source}return a}function we(r,e){if(e.target==="openAi"){console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.")}if(e.target==="openApi3"&&r.keyType?._def.typeName===d.ZodEnum){return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,a)=>({...n,[a]:y(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??k(e)}),{}),additionalProperties:e.rejectedAdditionalProperties}}const t={type:"object",additionalProperties:y(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3"){return t}if(r.keyType?._def.typeName===d.ZodString&&r.keyType._def.checks?.length){const{type:n,...a}=ke(r.keyType._def,e);return{...t,propertyNames:a}}else if(r.keyType?._def.typeName===d.ZodEnum){return{...t,propertyNames:{enum:r.keyType._def.values}}}else if(r.keyType?._def.typeName===d.ZodBranded&&r.keyType._def.type._def.typeName===d.ZodString&&r.keyType._def.type._def.checks?.length){const{type:n,...a}=be(r.keyType._def,e);return{...t,propertyNames:a}}return t}function nt(r,e){if(e.mapStrategy==="record"){return we(r,e)}const t=y(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||k(e);const n=y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||k(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function at(r){const e=r.values;const t=Object.keys(r.values).filter(s=>{return typeof e[e[s]]!=="number"});const n=t.map(s=>e[s]);const a=Array.from(new Set(n.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function st(r){return r.target==="openAi"?void 0:{not:k({...r,currentPath:[...r.currentPath,"not"]})}}function it(r){return r.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var ye={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ct(r,e){if(e.target==="openApi3")return ot(r,e);const t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in ye&&(!n._def.checks||!n._def.checks.length))){const n=t.reduce((a,s)=>{const i=ye[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=t.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===t.length){const a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:t.reduce((s,i)=>{return s.includes(i._def.value)?s:[...s,i._def.value]},[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum")){return{type:"string",enum:t.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])}}return ot(r,e)}var ot=(r,e)=>{const t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,a)=>y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function ut(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length)){if(e.target==="openApi3"){return{type:ye[r.innerType._def.typeName],nullable:true}}return{type:[ye[r.innerType._def.typeName],"null"]}}if(e.target==="openApi3"){const n=y(r.innerType._def,{...e,currentPath:[...e.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:true};return n&&{...n,nullable:true}}const t=y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function dt(r,e){const t={type:"number"};if(!r.checks)return t;for(const n of r.checks){switch(n.kind){case"int":t.type="integer";De(t,"type",n.message,e);break;case"min":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"minimum",n.value,n.message,e)}else{b(t,"exclusiveMinimum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMinimum=true}b(t,"minimum",n.value,n.message,e)}break;case"max":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"maximum",n.value,n.message,e)}else{b(t,"exclusiveMaximum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMaximum=true}b(t,"maximum",n.value,n.message,e)}break;case"multipleOf":b(t,"multipleOf",n.value,n.message,e);break}}return t}function lt(r,e){const t=e.target==="openAi";const n={type:"object",properties:{}};const a=[];const s=r.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0){continue}let p=er(c);if(p&&t){if(c._def.typeName==="ZodOptional"){c=c._def.innerType}if(!c.isNullable()){c=c.nullable()}p=false}const g=y(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});if(g===void 0){continue}n.properties[o]=g;if(!p){a.push(o)}}if(a.length){n.required=a}const i=Xt(r,e);if(i!==void 0){n.additionalProperties=i}return n}function Xt(r,e){if(r.catchall._def.typeName!=="ZodNever"){return y(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})}switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function er(r){try{return r.isOptional()}catch{return true}}var pt=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString()){return y(r.innerType._def,e)}const t=y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:k(e)},t]}:k(e)};var ft=(r,e)=>{if(e.pipeStrategy==="input"){return y(r.in._def,e)}else if(e.pipeStrategy==="output"){return y(r.out._def,e)}const t=y(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});const n=y(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(a=>a!==void 0)}};function mt(r,e){return y(r.type._def,e)}function ht(r,e){const t=y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]});const n={type:"array",uniqueItems:true,items:t};if(r.minSize){b(n,"minItems",r.minSize.value,r.minSize.message,e)}if(r.maxSize){b(n,"maxItems",r.maxSize.value,r.maxSize.message,e)}return n}function yt(r,e){if(r.rest){return{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:y(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}}else{return{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}}function gt(r){return{not:k(r)}}function _t(r){return k(r)}var vt=(r,e)=>{return y(r.innerType._def,e)};var xt=(r,e,t)=>{switch(e){case d.ZodString:return ke(r,t);case d.ZodNumber:return dt(r,t);case d.ZodObject:return lt(r,t);case d.ZodBigInt:return He(r,t);case d.ZodBoolean:return Ye();case d.ZodDate:return Re(r,t);case d.ZodUndefined:return gt(t);case d.ZodNull:return it(t);case d.ZodArray:return Je(r,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return ct(r,t);case d.ZodIntersection:return et(r,t);case d.ZodTuple:return yt(r,t);case d.ZodRecord:return we(r,t);case d.ZodLiteral:return tt(r,t);case d.ZodEnum:return Xe(r);case d.ZodNativeEnum:return at(r);case d.ZodNullable:return ut(r,t);case d.ZodOptional:return pt(r,t);case d.ZodMap:return nt(r,t);case d.ZodSet:return ht(r,t);case d.ZodLazy:return()=>r.getter()._def;case d.ZodPromise:return mt(r,t);case d.ZodNaN:case d.ZodNever:return st(t);case d.ZodEffects:return Qe(r,t);case d.ZodAny:return k(t);case d.ZodUnknown:return _t(t);case d.ZodDefault:return Ke(r,t);case d.ZodBranded:return be(r,t);case d.ZodReadonly:return vt(r,t);case d.ZodCatch:return Ge(r,t);case d.ZodPipeline:return ft(r,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return void 0;default:return(n=>void 0)(e)}};function y(r,e,t=false){const n=e.seen.get(r);if(e.override){const o=e.override?.(r,e,n,t);if(o!==We){return o}}if(n&&!t){const o=tr(n,e);if(o!==void 0){return o}}const a={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,a);const s=xt(r,r.typeName,e);const i=typeof s==="function"?y(s(),e):s;if(i){rr(r,e,i)}if(e.postProcess){const o=e.postProcess(i,r,e);a.jsonSchema=i;return o}a.jsonSchema=i;return i}var tr=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:xe(e.currentPath,r.path)};case"none":case"seen":{if(r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)){console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`);return k(e)}return e.$refStrategy==="seen"?k(e):void 0}}};var rr=(r,e,t)=>{if(r.description){t.description=r.description;if(e.markdownDescription){t.markdownDescription=r.description}}return t};var bt=r=>{const e=qe(r);const t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:false},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};var nr=(r,e)=>{const t=bt(e);let n=typeof e==="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[p,g])=>({...c,[p]:y(g._def,{...t,currentPath:[...t.basePath,t.definitionPath,p]},true)??k(t)}),{}):void 0;const a=typeof e==="string"?e:e?.nameStrategy==="title"?void 0:e?.name;const s=y(r._def,a===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,a]},false)??k(t);const i=typeof e==="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;if(i!==void 0){s.title=i}if(t.flags.hasReferencedOpenAiAnyType){if(!n){n={}}if(!n[t.openAiAnyTypeName]){n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}}}const o=a===void 0?n?{...s,[t.definitionPath]:n}:s:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,a].join("/"),[t.definitionPath]:{...n,[a]:s}};if(t.target==="jsonSchema7"){o.$schema="http://json-schema.org/draft-07/schema#"}else if(t.target==="jsonSchema2019-09"||t.target==="openAi"){o.$schema="https://json-schema.org/draft/2019-09/schema#"}if(t.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))){console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.")}return o};export{x as a,$e as b,f as c,E as d,u as e,ir as f,O as g,z as h,pr as i,ue as j,ge as k,gr as l,l as m,w as n,h as o,q as p,A as q,Oe as r,Se as s,F as t,de as u,v,Lt as w,U as x,H as y,Y as z,G as A,K as B,le as C,Q as D,X as E,B as F,L as G,R as H,pe as I,V as J,S as K,ee as L,Ne as M,te as N,$ as O,Ce as P,fe as Q,me as R,Ze as S,re as T,ne as U,ae as V,se as W,W as X,C as Y,j as Z,M as _,ie as $,oe as aa,he as ba,Ar as ca,_e as da,ve as ea,ce as fa,Wt as ga,Tr as ha,d as ia,Or as ja,qt as ka,Jt as la,Sr as ma,Pr as na,Ht as oa,Nr as pa,jr as qa,Cr as ra,Zr as sa,Dr as ta,Rr as ua,Er as va,Ir as wa,$r as xa,Mr as ya,zr as za,Lr as Aa,Vr as Ba,Fr as Ca,Ur as Da,Br as Ea,Wr as Fa,qr as Ga,Jr as Ha,Hr as Ia,Yr as Ja,Gr as Ka,Kr as La,Qr as Ma,Xr as Na,en as Oa,tn as Pa,rn as Qa,nn as Ra,an as Sa,sn as Ta,on as Ua,cn as Va,un as Wa,nr as Xa};
|
package/chunks/chunk-IWK7PZP7.js
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
-
import{a as me,c as K}from"./chunk-EYK25HWR.js";import{Ca as pe,Da as fe,a as Ge}from"./chunk-FXOH6TEQ.js";import{e as qe}from"./chunk-XQK7JM66.js";var m="alran-public";var h=["agent.default"];var y="agent-backend";var ye="alran-public";var W=["openid","profile","email","agent.default"];var Z="agent-backend";var or="auth.ottili.one";var ge={dev:"http://127.0.0.1:18360",prod:"https://platform.ottili.one"};function sr(r){if(r==="dev"){const t=process.env.ALRAN_PLATFORM_BASE_URL_DEV;if(t?.trim())return t.trim();return ge.dev}const e=process.env.ALRAN_PLATFORM_BASE_URL_PROD??process.env.ALRAN_PLATFORM_BASE_URL;if(e?.trim())return e.trim();return ge.prod}var Je="http://127.0.0.1:18370/callback";function ar(r){const e=process.env.ALRAN_OIDC_CALLBACK_URI?.trim();if(e)return e;const t=r==="dev"?process.env.ALRAN_OIDC_CALLBACK_URI_DEV:process.env.ALRAN_OIDC_CALLBACK_URI_PROD;if(t?.trim())return t.trim();return Je}function Ae(r){let e;try{e=new URL(r)}catch{throw new Error(`OIDC callback URI "${r}" is not an absolute URL.`)}if(e.protocol!=="http:"&&e.protocol!=="https:"){throw new Error(`OIDC callback URI "${r}" must use http or https.`)}if(e.username!==""||e.password!==""){throw new Error(`OIDC callback URI "${r}" must not carry credentials.`)}if(e.search!==""||e.hash!==""){throw new Error(`OIDC callback URI "${r}" must not carry a query or fragment.`)}if(e.pathname===""||e.pathname==="/"){throw new Error(`OIDC callback URI "${r}" must name a callback path.`)}const t=e.port?Number(e.port):e.protocol==="https:"?443:80;const n=e.hostname;const i=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return{uri:`${e.origin}${e.pathname}`,origin:e.origin,host:i,port:t,path:e.pathname}}import{createHash as Ye}from"node:crypto";import{join as w,resolve as We}from"node:path";function Q(r){const e=w(We(r.dataDir),"auth");const t=w(e,r.buildEnv,r.region,m);const n=`com.alran.oauth.${r.buildEnv}.${r.region}`;const i=Ye("sha256").update(`${e}\0${m}`).digest("base64url");return{authHome:e,namespaceHome:t,lockPath:w(t,"auth.lock"),statePath:w(t,"auth-state.json"),credentialPath:w(t,"auth.json"),legacyLockPath:w(e,"auth.lock"),legacyStatePath:w(e,"auth-state.json"),legacyEncryptedCredentialPath:w(e,"credentials.enc"),buildEnv:r.buildEnv,region:r.region,credentialKey:{service:n,account:i}}}import{readFile as st}from"node:fs/promises";import{chmod as Se,mkdir as Xe,open as et,rename as tt,unlink as rt}from"node:fs/promises";import{randomUUID as nt}from"node:crypto";import{dirname as it}from"node:path";import{setTimeout as ot}from"node:timers/promises";import{AsyncLocalStorage as Ze}from"node:async_hooks";var F=new Ze;var X=class extends Error{constructor(t,n){super("Failed to save authentication credentials. Please retry.",{cause:n});this.authDiagnostic=t;this.name="AuthCredentialSaveError"}authDiagnostic;code="AUTH_CREDENTIAL_SAVE_FAILED"};function L(r,e,t,n,i=0){const o={...r,pid:process.pid,timeMs:Date.now(),outcome:t,retryCount:i,...Qe(n)};try{e?.(o)}catch{}return o}function we(r,e){const t=F.getStore();if(!t)return;t.retryCount=e;L(t.context,t.observer,"retry",r,e)}async function ve(r,e,t){return F.run({context:r,observer:e,retryCount:0},async()=>{try{const n=await t();L(r,e,"success",void 0,F.getStore()?.retryCount);return n}catch(n){const i=L(r,e,"failure",n,F.getStore()?.retryCount);throw new X(i,n)}})}function Qe(r){if(!r||typeof r!=="object")return{};const e=r;return{...typeof e.name==="string"&&/^[A-Za-z]{1,64}$/u.test(e.name)?{errorName:e.name}:{},...typeof e.code==="string"&&/^[A-Za-z_]{1,64}$/u.test(e.code)?{code:e.code}:{},...typeof e.errno==="number"&&Number.isFinite(e.errno)?{errno:e.errno}:{},...typeof e.syscall==="string"&&/^[a-z]{1,32}$/u.test(e.syscall)?{syscall:e.syscall}:{},...typeof e.httpStatus==="number"&&Number.isInteger(e.httpStatus)?{httpStatus:e.httpStatus}:{}}}async function z(r){await Xe(r,{recursive:true,mode:448});if(process.platform!=="win32")await Se(r,448)}async function V(r,e){const t=it(r);await z(t);const n=`${r}.${process.pid}.${nt()}.tmp`;const i=await et(n,"wx",384);try{try{await i.writeFile(e,{encoding:"utf8"});await i.sync()}finally{await i.close()}if(process.platform!=="win32")await Se(n,384);for(let o=0;;o+=1){try{await tt(n,r);break}catch(s){const a=s.code;if(o>=3||!["EPERM","EACCES","EBUSY"].includes(a??""))throw s;we(s,o+1);await ot(40*2**o)}}}catch(o){await rt(n).catch(()=>void 0);throw o}}var b=2;var at=1;var ct=/access[_-]?token|refresh[_-]?token|device[_-]?code|code[_-]?verifier/iu;function be(r){if(typeof r!=="object"||r===null)return;for(const[e,t]of Object.entries(r)){if(ct.test(e)){throw new TypeError("Sensitive OAuth fields cannot be persisted in auth-state.json.")}be(t)}}function Ee(r){if(typeof r!=="object"||r===null||Array.isArray(r)){throw new TypeError("Invalid OAuth state.")}const e=r;const t=typeof e.schemaVersion==="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=at&&e.schemaVersion<=b&&["anonymous","authorizing","authenticated","refreshing","scope_upgrade_required","logging_out","logout_pending","expired","error"].includes(e.status)&&(e.schemaVersion===1&&(e.storeKind==="os-keyring"||e.storeKind==="file")||e.schemaVersion===b&&e.storeKind==="file")&&e.clientId==="alran-public"&&Array.isArray(e.scopes)&&e.scopes.every(n=>typeof n==="string")&&e.audience==="agent-backend"&&dt(e.buildEnv,e.region)&&(e.expiresAtMs===void 0||typeof e.expiresAtMs==="number"&&Number.isFinite(e.expiresAtMs))&&Number.isSafeInteger(e.generation)&&e.generation>=0&&(e.authorization===void 0||ut(e.authorization))&&(e.refresh===void 0||lt(e.refresh));if(!t)throw new TypeError("Invalid OAuth state.");be(e);return e}function dt(r,e){if(r===void 0&&e===void 0)return true;return(r==="dev"||r==="test"||r==="staging"||r==="prod")&&(e==="cn"||e==="en")}function lt(r){if(typeof r!=="object"||r===null||Array.isArray(r))return false;const e=r;if(typeof e.id!=="string"||!e.id.length)return false;if(e.owner===void 0)return true;if(typeof e.owner!=="object"||e.owner===null)return false;const t=e.owner;return Number.isSafeInteger(t.pid)&&t.pid>0&&Number.isSafeInteger(t.startedAtMs)&&t.startedAtMs>0}function ut(r){if(typeof r!=="object"||r===null||Array.isArray(r))return false;const e=r;return typeof e.leaseId==="string"&&e.leaseId.length>0&&typeof e.leaseExpiresAtMs==="number"&&Number.isFinite(e.leaseExpiresAtMs)&&ee(e.userCode)&&ee(e.verificationUri)&&ee(e.verificationUriComplete)}function ee(r){return r===void 0||typeof r==="string"}var _=class{constructor(e){this.path=e}path;async read(){let e;try{e=await st(this.path,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}try{return Ee(JSON.parse(e))}catch(t){if(t instanceof TypeError)throw t;throw new TypeError("Invalid OAuth state.")}}async write(e){const t=Ee(e);await V(this.path,`${JSON.stringify(t,null,2)}
|
|
3
|
-
`)}};import{createHash as At,randomBytes as Re}from"node:crypto";import{createHash as ht,randomBytes as pt}from"node:crypto";var ft="urn:ietf:params:oauth:grant-type:device_code";var l=class extends Error{constructor(t,n,i){super(n??`The OAuth server rejected the request (${t}${i?`, HTTP ${i}`:""}).`);this.code=t;this.httpStatus=i;this.name="OAuthProtocolError"}code;httpStatus};var te=class{constructor(e){this.options=e;this.fetchImpl=e.fetchImpl??fetch;this.sleep=e.sleep??(t=>new Promise(n=>setTimeout(n,t)));this.now=e.now??Date.now}options;fetchImpl;sleep;now;async startDeviceAuthorization(e={}){const t=pt(32).toString("base64url");const n=ht("sha256").update(t,"ascii").digest("base64url");const i=await this.postForm(this.options.deviceAuthorizationEndpoint,{client_id:m,scope:h.join(" "),audience:y,code_challenge:n,code_challenge_method:"S256"},{headers:this.options.deviceAuthorizationHeaders,signal:e.signal});const o=p(i,"user_code");const s=p(i,"device_code");const a=$(i,"expired_in");const c=!s&&Boolean(o)&&a!==void 0;const u=s??(c?o:void 0);const d=p(i,"verification_uri")??p(i,"verification_url");const g=$(i,"expires_in")??yt(a,this.now());const Y=$(i,"interval");const $e=c&&Y!==void 0?Y/1e3:Y??5;if(!u||!o||!d||!g){throw new l("invalid_device_authorization_response")}return{deviceCode:u,codeVerifier:t,...c?{tokenPollingParameter:"user_code"}:{},userCode:o,verificationUri:d,...p(i,"verification_uri_complete")||c?{verificationUriComplete:p(i,"verification_uri_complete")??d}:{},expiresInSec:g,intervalSec:$e}}async pollDeviceToken(e,t={}){const n=this.now()+e.expiresInSec*1e3;let i=e.intervalSec*1e3;while(this.now()<n){t.signal?.throwIfAborted();const o=e.tokenPollingParameter==="user_code"?{user_code:e.userCode}:{device_code:e.deviceCode};const s=await this.postFormAllowOAuthError(this.options.tokenEndpoint,{grant_type:ft,...o,client_id:m,code_verifier:e.codeVerifier},{signal:t.signal});const a=p(s.body,"status");if(s.ok&&a==="pending"){await B(this.sleep,i,t.signal);continue}if(s.ok&&a==="slow_down"){i+=5e3;await B(this.sleep,i,t.signal);continue}if(s.ok&&(a==="denied"||a==="access_denied")){throw new l("access_denied")}if(s.ok&&(a==="expired"||a==="expired_token")){throw new l("expired_token")}if(s.ok)return _e(s.body);if(s.error==="authorization_pending"){await B(this.sleep,i,t.signal);continue}if(s.error==="slow_down"){i+=5e3;await B(this.sleep,i,t.signal);continue}throw new l(s.error??"device_authorization_failed",void 0,s.status)}throw new l("expired_token","The OAuth device authorization expired.")}async refreshToken(e){const t=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:m,scope:h.join(" "),audience:y});return _e(t,e)}async revokeToken(e){const t=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:m},{allowEmptySuccess:true});if(!t.ok)throw new l(t.error??"oauth_request_failed",void 0,t.status)}async postForm(e,t,n={}){const i=await this.postFormAllowOAuthError(e,t,n);if(!i.ok)throw new l(i.error??"oauth_request_failed",void 0,i.status);return i.body}async postFormAllowOAuthError(e,t,n={}){const i=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...n.headers},body:new URLSearchParams(t),signal:n.signal});const o=q(await i.json().catch(()=>void 0));if(!o&&i.ok&&n.allowEmptySuccess)return{ok:true,status:i.status,body:{}};if(!o)throw new l("invalid_json_response",void 0,i.status);const s=p(o,"error");return{ok:i.ok&&!s,status:i.status,body:o,...s?{error:s}:{}}}};async function B(r,e,t){if(!t){await r(e);return}t.throwIfAborted();let n;const i=()=>n(t.reason);const o=new Promise((s,a)=>{n=a});t.addEventListener("abort",i,{once:true});try{await Promise.race([r(e),o])}finally{t.removeEventListener("abort",i)}}function _e(r,e){const t=p(r,"access_token");const n=p(r,"refresh_token")??e;const i=p(r,"token_type");const o=$(r,"expires_in");const s=t?mt(t):void 0;const a=gt(r.scope??s?.scope??s?.scp);if(!t||!n||i?.toLowerCase()!=="bearer"||!o||!a.includes(h[0])){throw new l("invalid_token_response")}return{accessToken:t,refreshToken:n,tokenType:"Bearer",scopes:a,audience:y,expiresInSec:o,...p(s,"sub")?{subject:p(s,"sub")}:{},...p(s,"account_id")?{accountId:p(s,"account_id")}:{}}}function mt(r){const e=r.split(".");if(e.length!==3||!e[1])return void 0;try{return q(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return void 0}}function gt(r){if(typeof r==="string")return r.split(/\s+/u).filter(Boolean);if(Array.isArray(r)&&r.every(e=>typeof e==="string"))return r;return[]}function q(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function p(r,e){const t=q(r);const n=t?.[e];return typeof n==="string"&&n.trim()?n.trim():void 0}function $(r,e){const t=q(r);const n=t?.[e];return typeof n==="number"&&Number.isFinite(n)&&n>0?n:void 0}function yt(r,e){if(r===void 0)return void 0;if(r<1e12)return r;const t=r-e;return t>0?Math.ceil(t/1e3):void 0}var Pe=class{constructor(e){this.options=e;this.fetchImpl=e.fetchImpl??fetch;this.redirectUri=e.redirectUri;this.clientId=e.clientId??ye;this.scopes=e.scopes?[...e.scopes]:[...W];this.audience=e.audience??Z}options;fetchImpl;redirectUri;clientId;scopes;audience;async startAuthorizationCodeFlow(){const e=Re(32).toString("base64url");const t=At("sha256").update(e,"ascii").digest("base64url");const n=Re(16).toString("base64url");const i=new URL(this.options.authorizationEndpoint);i.searchParams.set("response_type","code");i.searchParams.set("client_id",this.clientId);i.searchParams.set("redirect_uri",this.redirectUri);i.searchParams.set("scope",this.scopes.join(" "));i.searchParams.set("state",n);i.searchParams.set("code_challenge",t);i.searchParams.set("code_challenge_method","S256");if(this.audience)i.searchParams.set("audience",this.audience);return{authorizeUrl:i.toString(),codeVerifier:e,state:n}}async exchangeCodeForToken(e,t,n,i){if(n!==void 0&&i!==void 0&&i!==n){throw new l("state_mismatch")}const o=await this.postForm(this.options.tokenEndpoint,{grant_type:"authorization_code",code:e,redirect_uri:this.redirectUri,client_id:this.clientId,code_verifier:t});return ke(o)}async refreshToken(e){const t=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:this.clientId,scope:this.scopes.join(" "),audience:this.audience});return ke(t,e)}async revokeToken(e){const t=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:this.clientId},{allowEmptySuccess:true});if(!t.ok){throw new l(t.error??"oauth_request_failed",void 0,t.status)}}async postForm(e,t,n={}){const i=await this.postFormAllowOAuthError(e,t,n);if(!i.ok)throw new l(i.error??"oauth_request_failed",void 0,i.status);return i.body}async postFormAllowOAuthError(e,t,n={}){const i=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...n.headers},body:new URLSearchParams(t),signal:n.signal});const o=G(await i.json().catch(()=>void 0));if(!o&&i.ok&&n.allowEmptySuccess)return{ok:true,status:i.status,body:{}};if(!o)throw new l("invalid_json_response",void 0,i.status);const s=v(o,"error");return{ok:i.ok&&!s,status:i.status,body:o,...s?{error:s}:{}}}};function ke(r,e){const t=v(r,"access_token");const n=v(r,"refresh_token")??e;const i=v(r,"token_type");const o=St(r,"expires_in");const s=t?wt(t):void 0;const a=vt(r.scope??s?.scope??s?.scp);if(!t||!n||i?.toLowerCase()!=="bearer"||!o||!a.includes(W[0])){throw new l("invalid_token_response")}return{accessToken:t,refreshToken:n,tokenType:"Bearer",scopes:a,audience:Z,expiresInSec:o,...v(s,"sub")?{subject:v(s,"sub")}:{},...v(s,"account_id")?{accountId:v(s,"account_id")}:{}}}function wt(r){const e=r.split(".");if(e.length!==3||!e[1])return void 0;try{return G(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return void 0}}function vt(r){if(typeof r==="string")return r.split(/\s+/u).filter(Boolean);if(Array.isArray(r)&&r.every(e=>typeof e==="string"))return r;return[]}function G(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function v(r,e){const t=G(r);const n=t?.[e];return typeof n==="string"&&n.trim()?n.trim():void 0}function St(r,e){const t=G(r);const n=t?.[e];return typeof n==="number"&&Number.isFinite(n)&&n>0?n:void 0}import{createServer as Et}from"node:http";function Ce(r){const e=new URLSearchParams({return_to:r.callback});if(r.prompt)e.set("prompt",r.prompt);return`${r.platformOrigin.replace(/\/+$/,"")}/v2/auth/oidc/login?${e}`}async function Oe(r,e=fetch){const t=await e(`${r.platformBaseUrl.replace(/\/+$/,"")}/v2/auth/sessions/handoff`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:r.code})});if(!t.ok){throw Object.assign(new Error(`Platform OIDC handoff refused: HTTP ${t.status}`),{status:t.status,code:"platform_handoff_refused"})}const n=await t.json().catch(()=>({}));const i=n.data;const o=i!==null&&typeof i==="object"?i:n;const s=typeof o.session_id==="string"?o.session_id:void 0;const a=typeof o.company_id==="string"?o.company_id:void 0;const c=typeof o.subject_id==="string"?o.subject_id:void 0;const u=typeof o.base_url==="string"&&o.base_url.length>0?o.base_url:r.platformBaseUrl.replace(/\/+$/,"");if(!s||!a){throw new l("platform_handoff_invalid","The Platform handoff response is missing session_id or company_id.")}return{sessionId:s,companyId:a,subjectId:c??"",baseUrl:u,via:"oidc"}}function bt(r){return`<!DOCTYPE html>
|
|
4
|
-
<html lang="en">
|
|
5
|
-
<head>
|
|
6
|
-
<meta charset="utf-8" />
|
|
7
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
8
|
-
<title>Sign in \u2013 Alran Code</title>
|
|
9
|
-
<link rel="stylesheet" href="https://unpkg.com/@ottili/foundation-ui@2.0.0-alpha.1/dist/styles.css" />
|
|
10
|
-
<style>
|
|
11
|
-
:root {
|
|
12
|
-
--ottili-auth-max-width: 380px;
|
|
13
|
-
--ottili-auth-card-radius: var(--ottili-radius-md, 12px);
|
|
14
|
-
}
|
|
15
|
-
html, body { height: 100%; margin: 0; }
|
|
16
|
-
body {
|
|
17
|
-
font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
|
|
18
|
-
background: var(--ottili-color-surface-canvas, #f4f5f7);
|
|
19
|
-
color: var(--ottili-color-text-primary, #16181d);
|
|
20
|
-
display: flex;
|
|
21
|
-
align-items: center;
|
|
22
|
-
justify-content: center;
|
|
23
|
-
min-height: 100vh;
|
|
24
|
-
}
|
|
25
|
-
.ottili-auth-shell {
|
|
26
|
-
width: min(var(--ottili-auth-max-width), calc(100vw - 32px));
|
|
27
|
-
}
|
|
28
|
-
.ottili-auth-shell__sign-in {
|
|
29
|
-
background: var(--ottili-color-surface-raised, #ffffff);
|
|
30
|
-
border: 1px solid var(--ottili-color-border-default, #d9dce3);
|
|
31
|
-
border-radius: var(--ottili-auth-card-radius);
|
|
32
|
-
padding: var(--ottili-space-page, 32px);
|
|
33
|
-
box-shadow: var(--ottili-elevation-raised, 0 4px 6px -1px rgb(0 0 0 / 0.1));
|
|
34
|
-
}
|
|
35
|
-
.ottili-auth-heading {
|
|
36
|
-
font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
|
|
37
|
-
font-size: var(--ottili-type-h2-size, 22px);
|
|
38
|
-
line-height: var(--ottili-type-h2-line, 1.3);
|
|
39
|
-
margin: 0 0 8px;
|
|
40
|
-
color: var(--ottili-color-text-primary, #16181d);
|
|
41
|
-
}
|
|
42
|
-
.ottili-auth-shell__sign-in p {
|
|
43
|
-
margin: 0 0 24px;
|
|
44
|
-
color: var(--ottili-color-text-secondary, #4a5060);
|
|
45
|
-
line-height: var(--ottili-type-body-line, 1.5);
|
|
46
|
-
}
|
|
47
|
-
.ottili-auth-button {
|
|
48
|
-
width: 100%;
|
|
49
|
-
display: block;
|
|
50
|
-
text-align: center;
|
|
51
|
-
padding: 10px 14px;
|
|
52
|
-
border-radius: var(--ottili-radius-sm, 8px);
|
|
53
|
-
background: var(--ottili-color-text-primary, #0a7d3b);
|
|
54
|
-
color: var(--ottili-color-text-inverse, #ffffff);
|
|
55
|
-
border: none;
|
|
56
|
-
font-family: inherit;
|
|
57
|
-
font-size: var(--ottili-type-body-size, 14px);
|
|
58
|
-
font-weight: 600;
|
|
59
|
-
cursor: pointer;
|
|
60
|
-
text-decoration: none;
|
|
61
|
-
}
|
|
62
|
-
.ottili-auth-button:hover {
|
|
63
|
-
opacity: 0.9;
|
|
64
|
-
}
|
|
65
|
-
.ottili-auth-button:focus-visible {
|
|
66
|
-
outline: 2px solid var(--ottili-color-focus-ring, #0a7d3b);
|
|
67
|
-
outline-offset: 2px;
|
|
68
|
-
}
|
|
69
|
-
.hint {
|
|
70
|
-
margin-top: 24px;
|
|
71
|
-
font-size: 12px;
|
|
72
|
-
color: var(--ottili-color-text-secondary, #6b7180);
|
|
73
|
-
}
|
|
74
|
-
</style>
|
|
75
|
-
</head>
|
|
76
|
-
<body>
|
|
77
|
-
<div class="ottili-auth-shell" data-ottili-state="signed_out">
|
|
78
|
-
<div class="ottili-auth-shell__sign-in">
|
|
79
|
-
<h2 class="ottili-auth-heading">Sign in</h2>
|
|
80
|
-
<p>You'll be redirected to the Ottili Platform to complete sign-in.</p>
|
|
81
|
-
<a class="ottili-auth-button" href="${U(r)}">Continue to sign-in</a>
|
|
82
|
-
<p class="hint">If you're not redirected automatically, click the button above.</p>
|
|
83
|
-
</div>
|
|
84
|
-
</div>
|
|
85
|
-
<script>
|
|
86
|
-
(function() {
|
|
87
|
-
const url = "${U(r)}";
|
|
88
|
-
if (url) window.location.replace(url);
|
|
89
|
-
})();
|
|
90
|
-
</script>
|
|
91
|
-
</body>
|
|
92
|
-
</html>`}function _t(){return`<!DOCTYPE html>
|
|
93
|
-
<html lang="en">
|
|
94
|
-
<head>
|
|
95
|
-
<meta charset="utf-8" />
|
|
96
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
97
|
-
<title>Signed in \u2013 Alran Code</title>
|
|
98
|
-
<link rel="stylesheet" href="https://unpkg.com/@ottili/foundation-ui@2.0.0-alpha.1/dist/styles.css" />
|
|
99
|
-
<style>
|
|
100
|
-
:root {
|
|
101
|
-
--ottili-auth-max-width: 380px;
|
|
102
|
-
--ottili-auth-card-radius: var(--ottili-radius-md, 12px);
|
|
103
|
-
}
|
|
104
|
-
html, body { height: 100%; margin: 0; }
|
|
105
|
-
body {
|
|
106
|
-
font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
|
|
107
|
-
background: var(--ottili-color-surface-canvas, #f4f5f7);
|
|
108
|
-
color: var(--ottili-color-text-primary, #16181d);
|
|
109
|
-
display: flex;
|
|
110
|
-
align-items: center;
|
|
111
|
-
justify-content: center;
|
|
112
|
-
min-height: 100vh;
|
|
113
|
-
}
|
|
114
|
-
.ottili-auth-shell {
|
|
115
|
-
width: min(var(--ottili-auth-max-width), calc(100vw - 32px));
|
|
116
|
-
}
|
|
117
|
-
.ottili-auth-shell__sign-in {
|
|
118
|
-
background: var(--ottili-color-surface-raised, #ffffff);
|
|
119
|
-
border: 1px solid var(--ottili-color-border-default, #d9dce3);
|
|
120
|
-
border-radius: var(--ottili-auth-card-radius);
|
|
121
|
-
padding: var(--ottili-space-page, 32px);
|
|
122
|
-
box-shadow: var(--ottili-elevation-raised, 0 4px 6px -1px rgb(0 0 0 / 0.1));
|
|
123
|
-
text-align: center;
|
|
124
|
-
}
|
|
125
|
-
.ottili-auth-heading {
|
|
126
|
-
font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
|
|
127
|
-
font-size: var(--ottili-type-h2-size, 22px);
|
|
128
|
-
line-height: var(--ottili-type-h2-line, 1.3);
|
|
129
|
-
margin: 0 0 16px;
|
|
130
|
-
color: var(--ottili-color-text-primary, #16181d);
|
|
131
|
-
}
|
|
132
|
-
.ottili-auth-shell__sign-in p {
|
|
133
|
-
margin: 0;
|
|
134
|
-
color: var(--ottili-color-text-secondary, #4a5060);
|
|
135
|
-
line-height: var(--ottili-type-body-line, 1.5);
|
|
136
|
-
}
|
|
137
|
-
</style>
|
|
138
|
-
</head>
|
|
139
|
-
<body>
|
|
140
|
-
<div class="ottili-auth-shell" data-ottili-state="active">
|
|
141
|
-
<div class="ottili-auth-shell__sign-in">
|
|
142
|
-
<h2 class="ottili-auth-heading" style="color: var(--ottili-color-text-primary, #15803d);">Signed in</h2>
|
|
143
|
-
<p>You can close this window and return to Alran Code.</p>
|
|
144
|
-
</div>
|
|
145
|
-
</div>
|
|
146
|
-
<script>
|
|
147
|
-
window.close?.();
|
|
148
|
-
</script>
|
|
149
|
-
</body>
|
|
150
|
-
</html>`}function N(r){return`<!DOCTYPE html>
|
|
151
|
-
<html lang="en">
|
|
152
|
-
<head>
|
|
153
|
-
<meta charset="utf-8" />
|
|
154
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
155
|
-
<title>Sign-in failed \u2013 Alran Code</title>
|
|
156
|
-
<link rel="stylesheet" href="https://unpkg.com/@ottili/foundation-ui@2.0.0-alpha.1/dist/styles.css" />
|
|
157
|
-
<style>
|
|
158
|
-
:root {
|
|
159
|
-
--ottili-auth-max-width: 380px;
|
|
160
|
-
--ottili-auth-card-radius: var(--ottili-radius-md, 12px);
|
|
161
|
-
}
|
|
162
|
-
html, body { height: 100%; margin: 0; }
|
|
163
|
-
body {
|
|
164
|
-
font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
|
|
165
|
-
background: var(--ottili-color-surface-canvas, #f4f5f7);
|
|
166
|
-
color: var(--ottili-color-text-primary, #16181d);
|
|
167
|
-
display: flex;
|
|
168
|
-
align-items: center;
|
|
169
|
-
justify-content: center;
|
|
170
|
-
min-height: 100vh;
|
|
171
|
-
}
|
|
172
|
-
.ottili-auth-shell {
|
|
173
|
-
width: min(var(--ottili-auth-max-width), calc(100vw - 32px));
|
|
174
|
-
}
|
|
175
|
-
.ottili-auth-shell__sign-in {
|
|
176
|
-
background: var(--ottili-color-surface-raised, #ffffff);
|
|
177
|
-
border: 1px solid var(--ottili-color-border-danger, #f3b8b2);
|
|
178
|
-
border-radius: var(--ottili-auth-card-radius);
|
|
179
|
-
padding: var(--ottili-space-page, 32px);
|
|
180
|
-
box-shadow: var(--ottili-elevation-raised, 0 4px 6px -1px rgb(0 0 0 / 0.1));
|
|
181
|
-
}
|
|
182
|
-
.ottili-auth-heading {
|
|
183
|
-
font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
|
|
184
|
-
font-size: var(--ottili-type-h2-size, 22px);
|
|
185
|
-
line-height: var(--ottili-type-h2-line, 1.3);
|
|
186
|
-
margin: 0 0 16px;
|
|
187
|
-
color: var(--ottili-color-text-danger, #8a1c12);
|
|
188
|
-
}
|
|
189
|
-
.ottili-auth-shell__sign-in p {
|
|
190
|
-
margin: 0;
|
|
191
|
-
color: var(--ottili-color-text-secondary, #4a5060);
|
|
192
|
-
line-height: var(--ottili-type-body-line, 1.5);
|
|
193
|
-
white-space: pre-wrap;
|
|
194
|
-
}
|
|
195
|
-
</style>
|
|
196
|
-
</head>
|
|
197
|
-
<body>
|
|
198
|
-
<div class="ottili-auth-shell" data-ottili-state="signed_out">
|
|
199
|
-
<div class="ottili-auth-shell__sign-in">
|
|
200
|
-
<h2 class="ottili-auth-heading">Sign-in failed</h2>
|
|
201
|
-
<p>${U(r)}</p>
|
|
202
|
-
</div>
|
|
203
|
-
</div>
|
|
204
|
-
</body>
|
|
205
|
-
</html>`}function U(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Te(r){return r.includes(":")&&!r.startsWith("[")?`[${r}]`:r}var xe=class{server=null;listenedPort=null;host;baseUrl;callbackUri;callbackPath;client=null;expectedState;platformOidc;onLogin;onError;startResult=null;resolveLogin=null;rejectLogin=null;constructor(e){const t=e.callbackUri?Ae(e.callbackUri):null;this.listenedPort=t?.port??e.port??0;this.host=t?.host??e.host??"127.0.0.1";this.baseUrl=e.baseUrl;this.callbackUri=t?.uri;this.callbackPath=t?.path??"/callback";this.expectedState=e.expectedState;this.platformOidc=e.platformOidc;this.onLogin=e.onLogin;this.onError=e.onError;if(e.client)this.setClient(e.client)}setClient(e){this.client=e}get port(){return this.listenedPort}async start(){const e=this.listenedPort??0;return new Promise((t,n)=>{this.server=Et((i,o)=>{void this.handleRequest(i,o)});this.server.once("error",n);this.server.listen(e,this.host,()=>{this.server.once("error",()=>{});const i=this.server.address();if(i&&typeof i==="object"){this.listenedPort=i.port}t(`${this.baseUrl.split("://")[0]}://${Te(this.host)}:${this.listenedPort}`)})})}async beginLogin(){if(!this.client)throw new Error("Authorization code client not set.");this.startResult=await this.client.startAuthorizationCodeFlow();return this.startResult.authorizeUrl}platformOidcAuthorizeUrl(){if(!this.platformOidc)throw new Error("Platform OIDC is not configured.");const e=this.listenedPort??0;const t=this.callbackUri??`http://${Te(this.host)}:${e}/callback`;return Ce({platformOrigin:this.platformOidc.platformBaseUrl,callback:t})}waitForLogin(){return new Promise((e,t)=>{this.resolveLogin=e;this.rejectLogin=t})}close(){if(!this.server)return Promise.resolve();return new Promise(e=>{this.server.close(()=>{this.server=null;e()})})}async handleRequest(e,t){const n=new URL(e.url??"/",`http://${this.host}`);const i=n.pathname;t.setHeader("Content-Type","text/html; charset=utf-8");t.setHeader("Cache-Control","no-store");try{if(i==="/login"){let o;if(this.platformOidc){o=this.platformOidcAuthorizeUrl()}else{if(!this.startResult){await this.beginLogin()}o=this.startResult.authorizeUrl}t.statusCode=200;t.end(bt(o));return}if(i===this.callbackPath||i==="/callback"){await this.handleCallback(n,t);return}if(i==="/"){t.statusCode=200;t.end('<html><body><p>Alran Code OAuth callback server.</p><p><a href="/login">Sign in</a></p></body></html>');return}t.statusCode=404;t.end("Not found")}catch(o){const s=o;t.statusCode=500;t.end(N(s.message));void this.onError?.(s);if(this.rejectLogin){this.rejectLogin(s);this.rejectLogin=null;this.resolveLogin=null}}}async handleCallback(e,t){const n=e.searchParams.get("code")??void 0;const i=e.searchParams.get("ottili_handoff")??n;const o=e.searchParams.get("state")??void 0;const s=e.searchParams.get("error")??void 0;const a=e.searchParams.get("error_description")??void 0;if(s){const d=a??s;t.statusCode=400;t.end(N(`The auth server returned an error: ${U(d)}`));const g=new l(s,d);void this.onError?.(g);if(this.rejectLogin){this.rejectLogin(g);this.rejectLogin=null;this.resolveLogin=null}return}const c=this.platformOidc?i:n;if(!c){t.statusCode=400;t.end(N("Missing authorization code or handoff code."));const d=new Error("Missing authorization code or handoff code.");void this.onError?.(d);if(this.rejectLogin){this.rejectLogin(d);this.rejectLogin=null;this.resolveLogin=null}return}if(!this.platformOidc){if(!o||o!==this.expectedState){t.statusCode=400;t.end(N("State mismatch \u2014 possible CSRF attack."));const d=new l("state_mismatch");void this.onError?.(d);if(this.rejectLogin){this.rejectLogin(d);this.rejectLogin=null;this.resolveLogin=null}return}}let u;try{if(this.platformOidc){const d=await Oe({platformBaseUrl:this.platformOidc.platformBaseUrl,code:i});u={platformSession:d}}else{const d=await this.client.exchangeCodeForToken(n,this.startResult?.codeVerifier??"",this.expectedState??"",o??"");u={accessToken:d.accessToken,refreshToken:d.refreshToken,expiresInSec:d.expiresInSec,scopes:d.scopes,...d.subject?{subject:d.subject}:{},...d.accountId?{accountId:d.accountId}:{}}}}catch(d){const g=d;t.statusCode=500;t.end(N(`Failed to complete sign in: ${U(g.message)}`));void this.onError?.(g);if(this.rejectLogin){this.rejectLogin(g);this.rejectLogin=null;this.resolveLogin=null}return}try{await this.onLogin?.(u)}catch(d){const g=d;t.statusCode=500;t.end(N(`Failed to save the sign-in session: ${U(g.message)}`));void this.onError?.(g);if(this.rejectLogin){this.rejectLogin(g);this.rejectLogin=null;this.resolveLogin=null}return}t.statusCode=200;t.end(_t());if(this.resolveLogin){this.resolveLogin(u);this.resolveLogin=null;this.rejectLogin=null}}};var Ie=class r{credentials;fetchImpl;constructor(e,t=fetch){this.credentials=e;this.fetchImpl=t}withCompany(e){return new r({...this.credentials,companyId:e},this.fetchImpl)}get baseUrl(){return this.credentials.baseUrl}async call(e){const t=new URL(e.path,this.credentials.baseUrl);if(e.query){for(const[a,c]of Object.entries(e.query)){t.searchParams.set(a,c)}}const n={"x-ottili-session":this.credentials.sessionId,"x-ottili-company":this.credentials.companyId,Accept:"application/json"};if(e.body!==void 0){n["Content-Type"]="application/json"}if(e.idempotencyKey){n["idempotency-key"]=e.idempotencyKey}let i;try{i=await this.fetchImpl(t.toString(),{method:e.method,headers:n,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}})}catch(a){return{ok:false,status:0,problem:{code:"platform_unreachable",detail:a instanceof Error?a.message:String(a)}}}let o;let s;try{const a=await i.json().catch(()=>({}));const c=typeof a==="object"&&a!==null&&!Array.isArray(a)?a:{};if(i.ok&&!c.error){o=a}else{s={code:typeof c.error==="string"?c.error:typeof c.code==="string"?c.code:"platform_error",detail:typeof c.message==="string"?c.message:void 0}}}catch{if(!i.ok){s={code:`http_${i.status}`,detail:i.statusText}}}return{ok:i.ok,status:i.status,data:o,problem:s}}async get(e,t){return this.call({...t,method:"GET",path:e})}async post(e,t){return this.call({...t??{},method:"POST",path:e,body:t?.body})}async delete(e,t){return this.call({...t,method:"DELETE",path:e})}};function Mr(){return`k-${crypto.randomUUID()}`}var Rt={cn:{dev:"https://account-test.example.invalid",test:"https://account-test.example.invalid",staging:"https://account-pre.example.invalid",prod:"https://api.ottili.one"},en:{dev:"https://account-overseas-test.example.invalid",test:"https://account-overseas-test.example.invalid",staging:"https://account-overseas-pre.example.invalid",prod:"https://api.ottili.one"}};function Hr(r,e){const t=[r.ALRAN_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT,r.ALRAN_OAUTH_TOKEN_ENDPOINT,r.ALRAN_OAUTH_REVOCATION_ENDPOINT];if(t.every(s=>!s?.trim())){const s=Rt[e.region][e.buildEnv];return{deviceAuthorizationEndpoint:`${s}/oauth2/device/code`,...Le(e.buildEnv),tokenEndpoint:`${s}/oauth2/token`,revocationEndpoint:`${s}/oauth2/revoke`}}const n=re(r.ALRAN_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT);const i=re(r.ALRAN_OAUTH_TOKEN_ENDPOINT);const o=re(r.ALRAN_OAUTH_REVOCATION_ENDPOINT);if(!n||!i||!o){throw new TypeError("Shared Alran OAuth requires all three public OAuth endpoints to be configured.")}return{deviceAuthorizationEndpoint:n,...Le(e.buildEnv),tokenEndpoint:i,revocationEndpoint:o}}function Le(r){return r==="staging"?{deviceAuthorizationHeaders:{"X-User-Pre":"1"}}:{}}function re(r){if(!r?.trim())return void 0;try{const e=new URL(r);if(e.protocol!=="https:"||e.username||e.password||e.hash)return void 0;return e.toString()}catch{return void 0}}var Pt=1;var kt=1;var A=class extends Error{code="CREDENTIAL_RECORD_CORRUPT";constructor(){super("The stored OAuth credential record is invalid.");this.name="CredentialRecordCorruptError"}};var J=class extends Error{code="AUTH_CREDENTIAL_STORE_PERMISSION";constructor(){super("The OAuth credential file permissions are not private.");this.name="CredentialStorePermissionError"}};function ne(r){return r===void 0||typeof r==="string"}function ie(r){if(typeof r!=="object"||r===null||Array.isArray(r)){throw new A}const e=r;const t=e.scopes;const n=Array.isArray(t)&&t.every(o=>typeof o==="string");const i=typeof e.schemaVersion==="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=kt&&e.schemaVersion<=Pt&&typeof e.accessToken==="string"&&e.accessToken.length>0&&typeof e.refreshToken==="string"&&e.refreshToken.length>0&&e.tokenType==="Bearer"&&e.clientId===m&&n&&e.audience===y&&typeof e.expiresAtMs==="number"&&Number.isFinite(e.expiresAtMs)&&Number.isSafeInteger(e.generation)&&e.generation>=0&&ne(e.subject)&&ne(e.accountId)&&ne(e.loginEpoch);if(!i)throw new A;return e}import{randomUUID as j}from"node:crypto";import{watchFile as Lt,unwatchFile as Nt}from"node:fs";import{unlink as Ut}from"node:fs/promises";import{join as Me}from"node:path";var Ne=qe(Ge(),1);import{open as Ct}from"node:fs/promises";import{dirname as Ot}from"node:path";var R=class{constructor(e,t={}){this.lockPath=e;this.staleMs=t.staleMs??3e4;this.retries=t.retries??120}lockPath;staleMs;retries;async withLock(e){await z(Ot(this.lockPath));const t=await Ct(this.lockPath,"a",384);await t.close();let n;const i=await Ne.default.lock(this.lockPath,{realpath:false,stale:this.staleMs,retries:{retries:this.retries,factor:1.15,minTimeout:5,maxTimeout:250},onCompromised:o=>{n??=o}});try{return await e()}finally{try{await i()}catch(o){if(!n)throw o}if(n)throw n}}};import{readFile as Tt,stat as Ue}from"node:fs/promises";import{join as xt}from"node:path";var se=1;function oe(r){return`${r.service}\0${r.account}`}function De(r){if(typeof r!=="object"||r===null||Array.isArray(r)){throw new A}const e=r;if(e.schemaVersion!==se||typeof e.records!=="object"||e.records===null||Array.isArray(e.records)){throw new A}const t=Object.fromEntries(Object.entries(e.records).map(([n,i])=>[n,ie(i)]));return{schemaVersion:se,records:t}}var D=class{kind="file";authHome;path;constructor(e){this.authHome=e.authHome;this.path=xt(e.authHome,"auth.json")}async get(e){const t=await this.readPayload();return t.records[oe(e)]??null}async put(e,t){const n=await this.readPayload();n.records[oe(e)]=ie(t);await this.writePayload(n)}async delete(e){const t=await this.readPayload();delete t.records[oe(e)];await this.writePayload(t)}async healthCheck(){await z(this.authHome);await this.assertPrivatePermissions()}async readPayload(){let e;try{await this.assertPrivatePermissions();e=await Tt(this.path,"utf8")}catch(t){if(t.code==="ENOENT"){return{schemaVersion:se,records:{}}}throw t}try{return De(JSON.parse(e))}catch(t){if(t instanceof A)throw t;throw new A}}async assertPrivatePermissions(){if(process.platform==="win32")return;try{const[e,t]=await Promise.all([Ue(this.authHome),Ue(this.path)]);if((e.mode&63)!==0||(t.mode&63)!==0){throw new J}}catch(e){if(e.code==="ENOENT")return;throw e}}async writePayload(e){const t=De(e);await V(this.path,`${JSON.stringify(t,null,2)}
|
|
206
|
-
`)}};import{performance as It}from"node:perf_hooks";var ae={pid:process.pid,startedAtMs:Math.trunc(It.timeOrigin)};function ze(){return{...ae}}function ce(r){if(!r)return true;if(r.pid===ae.pid)return r.startedAtMs===ae.startedAtMs;try{process.kill(r.pid,0);return true}catch(e){return e.code!=="ESRCH"}}var Dt=10*60*1e3;var zt=250;var O=class extends Error{code="AUTH_REFRESH_COMMIT_PENDING";constructor(){super("OAuth refresh recovery is pending. Retry, or explicitly sign in again if recovery is unavailable.");this.name="AuthRefreshCommitPendingError"}};var f=class extends Error{code="AUTH_REQUIRED";constructor(e){super("Alran authentication is required.",e);this.name="AuthRequiredError"}};var T=class extends Error{code="AUTH_LOGIN_CANCELLED";constructor(){super("Alran OAuth device authorization was cancelled.");this.name="AuthLoginCancelledError"}};var E=class extends Error{code="AUTH_SESSION_CHANGED";constructor(){super("The login changed while this request was in progress.");this.name="AuthSessionChangedError"}};function Mt(r,e){if(!r||r!==e)throw new E}var x=class extends Error{constructor(t){super("The current Alran authorization does not include the required scope.");this.missingScopes=t;this.name="AuthScopeUpgradeRequiredError"}missingScopes;code="AUTH_SCOPE_UPGRADE_REQUIRED"};var I=class extends Error{code="AUTH_RESOURCE_CONTRACT_MISMATCH";constructor(){super("The stored credential does not match the Alran resource contract.");this.name="AuthResourceContractMismatchError"}};function je(r){return r instanceof f||r instanceof x||r instanceof I}var le=class extends Error{constructor(t,n){super(`Alran is signed in to ${t.buildEnv}/${t.region}; sign out before using ${n.buildEnv}/${n.region}.`);this.active=t;this.requested=n;this.name="AuthDomainConflictError"}active;requested;code="AUTH_DOMAIN_CONFLICT"};var ue=class{constructor(e){this.options=e;this.stateStore=new _(e.namespace.statePath);this.lock=new R(e.namespace.lockPath);this.refreshStore=new D({authHome:Me(e.namespace.namespaceHome,"refresh")});this.now=e.now??Date.now;this.sleep=e.sleep??(t=>new Promise(n=>setTimeout(n,t)));this.authorizationLeaseMs=e.authorizationLeaseMs??Dt;this.statePollIntervalMs=e.statePollIntervalMs??zt;this.createLeaseId=e.createLeaseId??j}options;stateStore;lock;now;sleep;authorizationLeaseMs;statePollIntervalMs;createLeaseId;loginPromise;loginAbortController;initializePromise;refreshStore;pendingRefresh;pendingRefreshRollback;pendingRefreshInvalidation;async getStatus(){await this.initialize();const e=await this.stateStore.read();if(!e)return{status:"anonymous",generation:0,scopes:[]};if(e.status==="authorizing"||e.status==="refreshing"||this.matchesPendingInvalidation(e)){const t=await this.recoverInterruptedCredentialCommit(e);return P(t)}if(e.status==="authenticated"||e.status==="expired"){const t=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!t||t.generation!==e.generation){return P({...e,status:"error"})}try{S(t,[...h])}catch(i){if(i instanceof x){return P({...M(t,this.options.credentialStore.kind,this.options.namespace),status:"scope_upgrade_required"})}if(i instanceof I){return P({...e,status:"error"})}throw i}const n=M(t,this.options.credentialStore.kind,this.options.namespace);if(e.status==="expired"||t.expiresAtMs<=this.now()){return P({...n,status:"expired"})}return P(n)}return P(e)}login(e={}){if(!this.loginPromise){const t=new AbortController;const n=this.initialize().then(()=>this.runLogin(e,t.signal)).finally(()=>{if(this.loginPromise!==n)return;this.loginPromise=void 0;this.loginAbortController=void 0});this.loginAbortController=t;this.loginPromise=n}return this.loginPromise}async cancelLogin(){const e=this.loginAbortController;const t=this.loginPromise;if(!e||!t)return;e.abort();try{await t}catch(n){if(!(n instanceof T))throw n}}async getAccessToken(e){await this.initialize();Ft(e.requiredScopes);try{const t=await this.readUsableCredential(e.requiredScopes);if(this.satisfiesMinValidity(t,e.minValidityMs)){return de(t.credential)}}catch(t){if(!(t instanceof f)&&!(t instanceof O))throw t}return this.lock.withLock(async()=>{const t=await this.readUsableCredential(e.requiredScopes,true);if(this.satisfiesMinValidity(t,e.minValidityMs)){return de(t.credential)}return this.refreshCredential(t)})}satisfiesMinValidity(e,t){if(e.state.status!=="authenticated")return false;const n=e.credential.expiresAtMs-this.now();return n>0&&n>=t}async handleUnauthorized(e){await this.initialize();try{return await this.lock.withLock(async()=>{const t=await this.readUsableCredential([...h],true);if(e.loginEpoch!==void 0){Mt(e.loginEpoch,t.credential.loginEpoch)}else if(t.credential.generation>e.generation){throw new E}if(t.credential.generation>e.generation)return"retry";if(t.credential.generation<e.generation)return"logout";await this.refreshCredential(t,{rejected:true});return"retry"})}catch(t){if(je(t))return"logout";throw t}}async logout(e){await this.initialize();return this.lock.withLock(async()=>{const t=await this.stateStore.read();const n=await this.options.credentialStore.get(this.options.namespace.credentialKey);const i=t?.refresh&&await this.readPendingRefresh(t)||n;const o=Math.max(t?.generation??0,i?.generation??0);if(!i&&(!t||t.status==="anonymous")){return{status:"anonymous",generation:o}}const s=o+1;await this.stateStore.write({...C({status:"logging_out",generation:s,storeKind:this.options.credentialStore.kind},this.options.namespace),...t?.refresh?{refresh:t.refresh}:{}});if(e.revoke&&i){try{await this.options.oauthClient.revokeToken(i.refreshToken)}catch{await this.stateStore.write({...C({status:"logout_pending",generation:s,storeKind:this.options.credentialStore.kind},this.options.namespace),...t?.refresh?{refresh:t.refresh}:{}});return{status:"logout_pending",generation:s}}}await this.options.credentialStore.delete(this.options.namespace.credentialKey);await this.stateStore.write(C({status:"anonymous",generation:s,storeKind:this.options.credentialStore.kind},this.options.namespace));await this.clearPendingRefresh();return{status:"anonymous",generation:s}})}watch(e){let t=0;let n=0;let i=false;const o=()=>{const s=++t;void this.getStatus().then(a=>{if(i||s<n)return;n=s;e(a)}).catch(()=>void 0)};Lt(this.options.namespace.statePath,{interval:this.statePollIntervalMs},o);return()=>{i=true;Nt(this.options.namespace.statePath,o)}}initialize(){this.initializePromise??=(async()=>{await this.options.initialize?.();await this.options.credentialStore.healthCheck()})().catch(e=>{this.initializePromise=void 0;throw e});return this.initializePromise}async runLogin(e,t){while(true){k(t);const n=this.createLeaseId();const i=await this.lock.withLock(async()=>{let o=await this.stateStore.read();Vt(o,this.options.namespace);if(o?.status==="refreshing"&&o.refresh){try{o=await this.resumeRefreshCommit(o)}catch(c){if(!(c instanceof O)&&!(c instanceof f))throw c}}const s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(o&&s&&o.generation===s.generation&&(o.status==="authenticated"||o.status==="expired"||o.status==="refreshing")){try{S(s,[...h]);if(o.status==="authenticated"&&s.expiresAtMs>this.now()){return{kind:"authenticated",generation:s.generation}}return{kind:"refresh",generation:s.generation}}catch(c){if(!(c instanceof x)&&!(c instanceof I)){throw c}}}if(o?.status==="authorizing"&&o.authorization&&o.authorization.leaseExpiresAtMs>this.now()){return{kind:"wait",leaseExpiresAtMs:o.authorization.leaseExpiresAtMs}}const a=Math.max(o?.generation??0,s?.generation??0);await this.stateStore.write({...C({status:"authorizing",generation:a,storeKind:this.options.credentialStore.kind},this.options.namespace),authorization:{leaseId:n,leaseExpiresAtMs:this.now()+this.authorizationLeaseMs}});await this.clearPendingRefresh();return{kind:"owner"}});if(i.kind==="authenticated"){return{status:"authenticated",generation:i.generation}}if(i.kind==="refresh"){try{await this.lock.withLock(async()=>{const s=await this.readUsableCredential([...h],true);if(s.credential.generation>i.generation&&this.satisfiesMinValidity(s,1))return;await this.refreshCredential(s)})}catch(s){if(je(s))continue;throw s}const o=await this.stateStore.read();if(o?.status==="authenticated"){return{status:"authenticated",generation:o.generation}}continue}if(i.kind==="wait"){const o=await this.waitForAuthorization(i.leaseExpiresAtMs,e.onDeviceAuthorization,t);if(o)return o;continue}try{const o=await this.options.oauthClient.startDeviceAuthorization({signal:t});await this.publishAuthorizationProgress(n,o);e.onDeviceAuthorization?.(Kt(o));const s=await this.options.oauthClient.pollDeviceToken(o,{signal:t});return await this.commitLogin(n,s,t)}catch(o){const s=t.aborted;await this.releaseAuthorizationLease(n,s?"anonymous":"error");if(s)throw new T;throw o}}}async commitLogin(e,t,n){return this.lock.withLock(async()=>{k(n);const i=await this.stateStore.read();if(i?.status!=="authorizing"||i.authorization?.leaseId!==e){throw new f}const o=await this.options.credentialStore.get(this.options.namespace.credentialKey);k(n);const s=Math.max(i.generation,o?.generation??0)+1;const a=He(t,s,this.now(),j());await this.options.credentialStore.put(this.options.namespace.credentialKey,a);try{k(n);await this.stateStore.write(M(a,this.options.credentialStore.kind,this.options.namespace));k(n)}catch(c){if(c instanceof T){await this.stateStore.write(i);if(o){await this.options.credentialStore.put(this.options.namespace.credentialKey,o)}else{await this.options.credentialStore.delete(this.options.namespace.credentialKey)}}throw c}return{status:"authenticated",generation:s}})}async waitForAuthorization(e,t,n){let i=false;while(this.now()<e){k(n);const o=await this.stateStore.read();if(!i&&o?.status==="authorizing"&&o.authorization?.userCode&&o.authorization.verificationUri){t?.({userCode:o.authorization.userCode,verificationUri:o.authorization.verificationUri,...o.authorization.verificationUriComplete?{verificationUriComplete:o.authorization.verificationUriComplete}:{},expiresInSec:Math.max(1,Math.ceil((o.authorization.leaseExpiresAtMs-this.now())/1e3))});i=true}if(o?.status==="authenticated"){const s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(s&&s.generation===o.generation){S(s,[...h]);return{status:"authenticated",generation:o.generation}}}if(o?.status!=="authorizing")return void 0;await Ht(this.sleep,this.statePollIntervalMs,n)}return void 0}async publishAuthorizationProgress(e,t){await this.lock.withLock(async()=>{const n=await this.stateStore.read();if(n?.status!=="authorizing"||n.authorization?.leaseId!==e){throw new f}await this.stateStore.write({...n,authorization:{...n.authorization,userCode:t.userCode,verificationUri:t.verificationUri,...t.verificationUriComplete?{verificationUriComplete:t.verificationUriComplete}:{}}})})}async releaseAuthorizationLease(e,t){await this.lock.withLock(async()=>{const n=await this.stateStore.read();if(n?.status!=="authorizing"||n.authorization?.leaseId!==e)return;await this.stateStore.write(C({status:t,generation:n.generation,storeKind:this.options.credentialStore.kind},this.options.namespace))})}async recoverInterruptedCredentialCommit(e){if(this.matchesPendingInvalidation(e)){return this.lock.withLock(async()=>{const n=await this.stateStore.read();const i=this.pendingRefreshInvalidation;if(!n||!i||!this.matchesPendingInvalidation(n))return n??e;return this.observeRefreshInvalidation(i)})}if(e.status==="refreshing"&&e.refresh){const n=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(n?.generation!==e.generation&&!await this.readPendingRefresh(e)&&this.pendingRefreshRollback?.id!==e.refresh.id&&ce(e.refresh.owner)){return e}return this.lock.withLock(async()=>{const i=await this.stateStore.read();if(i?.status!=="refreshing"||!i.refresh)return i??e;try{return await this.resumeRefreshCommit(i)}catch(o){if(o instanceof f&&this.matchesPendingInvalidation(i)){return this.refreshInvalidatedState(i)}throw o}})}const t=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!t||t.generation<=e.generation){return e}S(t,[...h]);return this.lock.withLock(async()=>{const n=await this.stateStore.read();const i=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!n||!i||n.status!=="authorizing"&&n.status!=="refreshing"||i.generation<=n.generation){return n??e}S(i,[...h]);const o=M(i,this.options.credentialStore.kind,this.options.namespace);await this.stateStore.write(o);return o})}async readUsableCredential(e,t=false){let n=await this.stateStore.read();const i=this.pendingRefreshInvalidation;if(n&&i&&this.matchesPendingInvalidation(n)){if(t)await this.finishRefreshInvalidation(i);throw new f}if(!n||n.status!=="authenticated"&&n.status!=="expired"&&n.status!=="refreshing"){throw new f}let o=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(n.status==="refreshing"&&n.refresh){if(!t)throw new O;n=await this.resumeRefreshCommit(n);if(n.status==="anonymous")throw new f;o=await this.options.credentialStore.get(this.options.namespace.credentialKey)}if(!o||n.generation!==o.generation)throw new f;S(o,e);return{state:n,credential:o}}async refreshCredential(e,t={}){const n=j();const i={...e.state,status:"refreshing",generation:Math.max(e.state.generation,e.credential.generation)+1,refresh:{id:n,owner:ze()}};await this.persistRefresh(i,"prepare_refresh","auth-state.json",null,()=>this.stateStore.write(i));let o;try{o=await this.options.oauthClient.refreshToken(e.credential.refreshToken);L({phase:"refresh_response",file:"oauth",correlationId:n,generation:i.generation,refreshResponseSucceeded:true},this.options.onDiagnostic,"success")}catch(a){L({phase:"refresh_response",file:"oauth",correlationId:n,generation:i.generation,refreshResponseSucceeded:false},this.options.onDiagnostic,"failure",a);if(jt(a)){this.pendingRefreshInvalidation={state:i,refreshResponseSucceeded:false};await this.finishRefreshInvalidation(this.pendingRefreshInvalidation);throw new f({cause:a})}else{const c=!t.rejected&&e.state.status==="authenticated"&&e.credential.expiresAtMs>this.now();this.pendingRefreshRollback={id:n,state:{...e.state,status:c?"authenticated":"expired"}};await this.resumeRefreshCommit(i)}throw a}const s=He(o,i.generation,this.now(),e.credential.loginEpoch);this.pendingRefresh={id:n,credential:s};await this.resumeRefreshCommit(i);return de(s)}async readPendingRefresh(e){if(!e.refresh)return null;return this.pendingRefresh?.id===e.refresh.id?this.pendingRefresh.credential:this.refreshStore.get({...this.options.namespace.credentialKey,account:e.refresh.id})}async resumeRefreshCommit(e){const t=e.refresh?.id;if(!t)throw new O;await this.assertRefreshCurrent(e);const n=this.pendingRefreshInvalidation;if(n?.state.refresh?.id===t){return this.finishRefreshInvalidation(n)}const i=this.pendingRefreshRollback;if(i?.id===t){await this.persistRefresh(e,"restore_state","auth-state.json",false,()=>this.stateStore.write(i.state));this.pendingRefreshRollback=void 0;return i.state}const o=await this.options.credentialStore.get(this.options.namespace.credentialKey);const s=o?.generation===e.generation?o:await this.readPendingRefresh(e);if(!s||s.generation!==e.generation){if(!ce(e.refresh?.owner)){this.pendingRefreshInvalidation={state:e,refreshResponseSucceeded:null};return this.finishRefreshInvalidation(this.pendingRefreshInvalidation)}throw new O}S(s,[...h]);if(o?.generation!==e.generation){this.pendingRefresh={id:t,credential:s};const c={...this.options.namespace.credentialKey,account:t};const u=await this.refreshStore.get(c);if(u?.generation!==s.generation||u.accessToken!==s.accessToken||u.refreshToken!==s.refreshToken||u.loginEpoch!==s.loginEpoch){await this.persistRefresh(e,"stage_credentials","refresh/auth.json",true,()=>this.refreshStore.put(c,s))}await this.assertRefreshCurrent(e);await this.persistRefresh(e,"commit_credentials","auth.json",true,()=>this.options.credentialStore.put(this.options.namespace.credentialKey,s))}const a=M(s,this.options.credentialStore.kind,this.options.namespace);await this.assertRefreshCurrent(e);await this.persistRefresh(e,"commit_state","auth-state.json",true,()=>this.stateStore.write(a));await this.clearPendingRefresh();return a}refreshInvalidatedState(e){return C({status:"anonymous",generation:e.generation,storeKind:this.options.credentialStore.kind},this.options.namespace)}matchesPendingInvalidation(e){const t=this.pendingRefreshInvalidation?.state;return t!==void 0&&e.generation===t.generation&&(e.status==="anonymous"||e.status==="refreshing"&&e.refresh?.id===t.refresh?.id)}async finishRefreshInvalidation(e){const{state:t,refreshResponseSucceeded:n}=e;const i=this.refreshInvalidatedState(t);try{const o=await this.stateStore.read();if(!o||!this.matchesPendingInvalidation(o))throw new E;if(o.status!=="anonymous"){await this.persistRefresh(t,"invalidate_state","auth-state.json",n,()=>this.stateStore.write(i))}const s=await this.stateStore.read();if(s?.status!=="anonymous"||s.generation!==t.generation){throw new E}await this.persistRefresh(t,"delete_credentials","auth.json",n,()=>this.options.credentialStore.delete(this.options.namespace.credentialKey))}catch(o){if(o instanceof E)throw o;throw new f({cause:o})}await this.clearPendingRefresh();return i}async observeRefreshInvalidation(e){try{return await this.finishRefreshInvalidation(e)}catch(t){if(t instanceof f)return this.refreshInvalidatedState(e.state);throw t}}persistRefresh(e,t,n,i,o){return ve({phase:t,file:n,correlationId:e.refresh?.id??j(),generation:e.generation,refreshResponseSucceeded:i},this.options.onDiagnostic,o)}async assertRefreshCurrent(e){const t=await this.stateStore.read();if(t?.status!=="refreshing"||t.generation!==e.generation||t.refresh?.id!==e.refresh?.id){throw new E}}async clearPendingRefresh(){this.pendingRefresh=void 0;this.pendingRefreshRollback=void 0;this.pendingRefreshInvalidation=void 0;await Ut(Me(this.options.namespace.namespaceHome,"refresh","auth.json")).catch(()=>void 0)}};function k(r){if(r?.aborted)throw new T}function jt(r){return r instanceof l&&r.code==="invalid_grant"&&r.httpStatus===400}async function Ht(r,e,t){if(!t){await r(e);return}k(t);let n;const i=()=>n(new T);const o=new Promise((s,a)=>{n=a});t.addEventListener("abort",i,{once:true});try{await Promise.race([r(e),o])}finally{t.removeEventListener("abort",i)}}function Kt(r){return{userCode:r.userCode,verificationUri:r.verificationUri,...r.verificationUriComplete?{verificationUriComplete:r.verificationUriComplete}:{},expiresInSec:r.expiresInSec}}function C(r,e){return{schemaVersion:b,status:r.status,storeKind:r.storeKind,clientId:m,scopes:[...h],audience:y,buildEnv:e.buildEnv,region:e.region,generation:r.generation}}function M(r,e,t){return{...C({status:"authenticated",generation:r.generation,storeKind:e},t),scopes:r.scopes,expiresAtMs:r.expiresAtMs}}function He(r,e,t,n=j()){const i={schemaVersion:1,accessToken:r.accessToken,refreshToken:r.refreshToken,tokenType:r.tokenType,clientId:m,scopes:r.scopes,audience:y,expiresAtMs:t+r.expiresInSec*1e3,generation:e,loginEpoch:n,...r.subject?{subject:r.subject}:{},...r.accountId?{accountId:r.accountId}:{}};S(i,[...h]);if(r.audience!==y)throw new I;return i}function Ft(r){const e=r.filter(t=>!h.includes(t));if(e.length>0)throw new x(e)}function S(r,e){if(r.clientId!==m||r.audience!==y||r.tokenType!=="Bearer"){throw new I}const t=e.filter(n=>!r.scopes.includes(n));if(t.length>0)throw new x(t)}function P(r){return{status:r.status,generation:r.generation,scopes:r.scopes,...r.buildEnv===void 0?{}:{buildEnv:r.buildEnv},...r.region===void 0?{}:{region:r.region},...r.expiresAtMs===void 0?{}:{expiresAtMs:r.expiresAtMs}}}function Vt(r,e){if(!r||r.status==="anonymous"||r.buildEnv===void 0||r.region===void 0||r.buildEnv===e.buildEnv&&r.region===e.region){return}throw new le({buildEnv:r.buildEnv,region:r.region},{buildEnv:e.buildEnv,region:e.region})}function de(r){return{accessToken:r.accessToken,...r.loginEpoch?{loginEpoch:r.loginEpoch}:{},expiresAtMs:r.expiresAtMs,generation:r.generation,scopes:h,audience:y}}function Bt(r){return new D(r)}async function $t(r){const e=await qt(r);const t=new _(r.statePath);const n=new R(r.lockPath);await n.withLock(async()=>{const i=await t.read();if(i?.schemaVersion===b)return;const o=i??e;if(!o)return;await t.write(Jt(o,r))})}async function qt(r){const e=new _(r.legacyStatePath);const t=new R(r.legacyLockPath);return t.withLock(async()=>{const n=await e.read();if(!Gt(n,r))return null;const{authorization:i,...o}=n;await e.write({...o,status:"error"});return n})}function Gt(r,e){return r!==null&&r.status!=="error"&&r.buildEnv===e.buildEnv&&r.region===e.region}function Jt(r,e){return{schemaVersion:b,status:"anonymous",storeKind:"file",clientId:"alran-public",scopes:["agent.default"],audience:"agent-backend",buildEnv:e.buildEnv,region:e.region,generation:r.generation+1}}import Zt from"node:fs";import H from"node:fs";import Ke from"node:path";var Fe="preferences";var Yt="alran-region.json";function Ve(r,e){try{const t=JSON.parse(H.readFileSync(Be(r),"utf8"));if(t.version!==1||!t.regions||typeof t.regions!=="object"){return void 0}const n=t.regions[e];return n==="cn"||n==="en"?n:void 0}catch{return void 0}}function Qn(r,e){const t=Ke.join(r,Fe);H.mkdirSync(t,{recursive:true,mode:448});const n=Be(r);const i=Wt(n);const o={version:1,regions:{...i,[e.buildEnv]:e.region},updatedAtMs:Date.now()};const s=`${n}.${process.pid}.${Date.now()}.tmp`;H.writeFileSync(s,`${JSON.stringify(o,null,2)}
|
|
207
|
-
`,{encoding:"utf8",mode:384});H.renameSync(s,n);return n}function Be(r){return Ke.join(r,Fe,Yt)}function Wt(r){try{const e=JSON.parse(H.readFileSync(r,"utf8"));if(e.version!==1||!e.regions||typeof e.regions!=="object")return{};return Object.fromEntries(Object.entries(e.regions).filter(([t,n])=>(t==="dev"||t==="test"||t==="staging"||t==="prod")&&(n==="cn"||n==="en")))}catch{return{}}}var Qt=/^[A-Za-z0-9._-]+$/u;var he="--env";var Xt=new Set(["--lane","--resume","--tui-mode","-m","--model","--system-prompt","--system-prompt-file","--append-system-prompt","--append-system-prompt-file"]);var er=Object.freeze({test:"test",pre:"staging",staging:"staging",prod:"prod"});function oi(r={}){pe(false);fe(false);const{target:e=process.env,dataDir:t,startupBuildEnvironment:n,...i}=r;if(n)me(n);const o=K(i);const s=t?Ve(t,o.buildEnv):void 0;const a=t?rr(t,o.buildEnv):void 0;const c=ir(e.ALRAN_REGION);const u=K({...i,runtimeRegion:i.runtimeRegion??c??s??a?.region??"en"});if(t){e.ALRAN_DATA_DIR=t;e.ALRAN_DATA_DIR=t}e.ALRAN_REGION=u.region;e.ALRAN_BUILD_ENV=u.buildEnv;e.__ALRAN_RUNTIME_MANAGED="1";return u}function tr(r){const e=er[r.trim()];if(!e){throw new Error("--env must be test, staging, pre, or prod.")}return e}function si(r,e){const t=[];for(let n=0;n<r.length;n+=1){const i=r[n];if(i===void 0)continue;if(i==="--")break;if(i===he){const o=r[n+1];if(!o||o.startsWith("-"))throw new Error("--env requires a value.");t.push(o);n+=1;continue}if(i.startsWith(`${he}=`)){t.push(i.slice(he.length+1));continue}if(Xt.has(i)){n+=1;continue}if(i==="--session"&&r[n+1]&&!r[n+1]?.startsWith("-")){n+=1;continue}if(!i.startsWith("-"))break}if(t.length===0)return void 0;if(!e){throw new Error("--env is only available in the internal Alran package.")}if(t.length>1)throw new Error("--env may only be specified once.");return tr(t[0]??"")}function ai(r,e=K().buildEnv){if(r===void 0)return void 0;if(e!=="test"&&e!=="staging"){throw new Error("--lane is only supported in test or staging builds.")}const t=r.trim();if(!Qt.test(t)){throw new Error("--lane only accepts letters, numbers, dot, underscore, and hyphen.")}return t}function rr(r,e){const t=["cn","en"].filter(i=>{try{const o=Q({dataDir:r,buildEnv:e,region:i});const s=JSON.parse(Zt.readFileSync(o.statePath,"utf8"));return s.buildEnv===e&&s.region===i&&nr(s.status)}catch{return false}});const n=t.length===1?t[0]:void 0;return n?{buildEnv:e,region:n}:void 0}function nr(r){return r==="authorizing"||r==="authenticated"||r==="refreshing"||r==="scope_upgrade_required"||r==="expired"}function ir(r){return r==="cn"||r==="en"?r:void 0}export{h as a,ye as b,W as c,Z as d,or as e,sr as f,ar as g,Ae as h,Q as i,_ as j,$t as k,te as l,Pe as m,xe as n,Ie as o,Mr as p,Hr as q,Pt as r,E as s,je as t,ue as u,Bt as v,Qn as w,oi as x,tr as y,si as z,ai as A};
|