@tinycloud/web-sdk 3.12.0-beta.7 → 3.12.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/delegations-issued.cjs +1 -1
- package/dist/delegations-issued.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/modules/tcw.d.ts +5 -2
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,a={d:(e,t)=>{for(var s in t)a.o(t,s)&&!a.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},s={};a.r(s),a.d(s,{queryAllIssued:()=>ct,queryIssued:()=>dt,revokeIssued:()=>ut}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},e.getValidEnumValues=t=>{const a=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of a)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},e.find=(e,t)=>{for(const a of e)if(t(a))return a},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const n=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return n.undefined;case"string":return n.string;case"number":return Number.isNaN(e)?n.nan:n.number;case"boolean":return n.boolean;case"function":return n.function;case"bigint":return n.bigint;case"symbol":return n.symbol;case"object":return Array.isArray(e)?n.array:null===e?n.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?n.promise:"undefined"!=typeof Map&&e instanceof Map?n.map:"undefined"!=typeof Set&&e instanceof Set?n.set:"undefined"!=typeof Date&&e instanceof Date?n.date:n.object;default:return n.unknown}},r=e.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"]);class o extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},a={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,s=0;for(;s<n.path.length;){const a=n.path[s];s===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],s++}}};return s(this),a}static assert(e){if(!(e instanceof o))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,e.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},a=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else a.push(e(s));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}}o.create=e=>new o(e);const d=(t,a)=>{let s;switch(t.code){case r.invalid_type:s=t.received===n.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case r.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case r.unrecognized_keys:s=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case r.invalid_union:s="Invalid input";break;case r.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case r.invalid_enum_value:s=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case r.invalid_arguments:s="Invalid function arguments";break;case r.invalid_return_type:s="Invalid function return type";break;case r.invalid_date:s="Invalid date";break;case r.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):s="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case r.too_small:s="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case r.too_big:s="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case r.custom:s="Invalid input";break;case r.invalid_intersection_types:s="Intersection results could not be merged";break;case r.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case r.not_finite:s="Number must be finite";break;default:s=a.defaultError,e.assertNever(t)}return{message:s}};let c=d;var u;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(u||(u={}));function l(e,t){const a=c,s=(e=>{const{data:t,path:a,errorMaps:s,issueData:n}=e,i=[...a,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=s.filter(e=>!!e).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===d?void 0:d].filter(e=>!!e)});e.common.issues.push(s)}class h{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const a=[];for(const s of t){if("aborted"===s.status)return p;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){const a=[];for(const e of t){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return h.mergeObjectSync(e,a)}static mergeObjectSync(e,t){const a={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return p;if("aborted"===n.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(a[t.value]=n.value)}return{status:e.value,value:a}}}const p=Object.freeze({status:"aborted"}),m=e=>({status:"dirty",value:e}),f=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,g=e=>"dirty"===e.status,y=e=>"valid"===e.status,v=e=>"undefined"!=typeof Promise&&e instanceof Promise;class k{constructor(e,t,a,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const x=(e,t)=>{if(y(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new o(e.common.issues);return this._error=t,this._error}}};function b(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:s,description:n}=e;if(t&&(a||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??a??n.defaultError}},description:n}}class w{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(v(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 a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){const a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},s=this._parseSync({data:e,path:a.path,parent:a});return x(a,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return y(a)?{value:a.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>y(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},s=this._parse({data:e,path:a.path,parent:a}),n=await(v(s)?s:Promise.resolve(s));return x(a,n)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:r.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((a,s)=>!!e(a)||(s.addIssue("function"==typeof t?t(a,s):t),!1))}_refinement(e){return new be({schema:this,typeName:Ze.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:e=>this["~validate"](e)}}optional(){return we.create(this,this._def)}nullable(){return Te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this)}promise(){return xe.create(this,this._def)}or(e){return ce.create([this,e],this._def)}and(e){return le.create(this,e,this._def)}transform(e){return new be({...b(this._def),schema:this,typeName:Ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Oe({...b(this._def),innerType:this,defaultValue:t,typeName:Ze.ZodDefault})}brand(){return new Ne({typeName:Ze.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ie({...b(this._def),innerType:this,catchValue:t,typeName:Ze.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return Se.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const T=/^c[^\s-]{8,}$/i,O=/^[0-9a-z]+$/,I=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A=/^[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,N=/^[a-z0-9_-]{21}$/i,E=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,S=/^[-+]?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)?)??$/,R=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let C;const Z=/^(?:(?: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])$/,j=/^(?:(?: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])$/,D=/^(([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]))$/,P=/^(([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])$/,$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,L=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,F="((\\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])))",V=new RegExp(`^${F}$`);function U(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function M(e){return new RegExp(`^${U(e)}$`)}function z(e){let t=`${F}T${U(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function K(e,t){return!("v4"!==t&&t||!Z.test(e))||!("v6"!==t&&t||!D.test(e))}function B(e,t){if(!E.test(e))return!1;try{const[a]=e.split(".");if(!a)return!1;const s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(s));return!("object"!=typeof n||null===n||"typ"in n&&"JWT"!==n?.typ||!n.alg||t&&n.alg!==t)}catch{return!1}}function W(e,t){return!("v4"!==t&&t||!j.test(e))||!("v6"!==t&&t||!P.test(e))}class q extends w{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==n.string){const e=this._getOrReturnCtx(t);return l(e,{code:r.invalid_type,expected:n.string,received:e.parsedType}),p}const a=new h;let s;for(const n of this._def.checks)if("min"===n.kind)t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if("max"===n.kind)t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if("length"===n.kind){const e=t.data.length>n.value,i=t.data.length<n.value;(e||i)&&(s=this._getOrReturnCtx(t,s),e?l(s,{code:r.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&l(s,{code:r.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),a.dirty())}else if("email"===n.kind)R.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"email",code:r.invalid_string,message:n.message}),a.dirty());else if("emoji"===n.kind)C||(C=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),C.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"emoji",code:r.invalid_string,message:n.message}),a.dirty());else if("uuid"===n.kind)A.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"uuid",code:r.invalid_string,message:n.message}),a.dirty());else if("nanoid"===n.kind)N.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"nanoid",code:r.invalid_string,message:n.message}),a.dirty());else if("cuid"===n.kind)T.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"cuid",code:r.invalid_string,message:n.message}),a.dirty());else if("cuid2"===n.kind)O.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"cuid2",code:r.invalid_string,message:n.message}),a.dirty());else if("ulid"===n.kind)I.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"ulid",code:r.invalid_string,message:n.message}),a.dirty());else if("url"===n.kind)try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),l(s,{validation:"url",code:r.invalid_string,message:n.message}),a.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"regex",code:r.invalid_string,message:n.message}),a.dirty())):"trim"===n.kind?t.data=t.data.trim():"includes"===n.kind?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),a.dirty()):"toLowerCase"===n.kind?t.data=t.data.toLowerCase():"toUpperCase"===n.kind?t.data=t.data.toUpperCase():"startsWith"===n.kind?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:{startsWith:n.value},message:n.message}),a.dirty()):"endsWith"===n.kind?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:{endsWith:n.value},message:n.message}),a.dirty()):"datetime"===n.kind?z(n).test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:"datetime",message:n.message}),a.dirty()):"date"===n.kind?V.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:"date",message:n.message}),a.dirty()):"time"===n.kind?M(n).test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{code:r.invalid_string,validation:"time",message:n.message}),a.dirty()):"duration"===n.kind?S.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"duration",code:r.invalid_string,message:n.message}),a.dirty()):"ip"===n.kind?K(t.data,n.version)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"ip",code:r.invalid_string,message:n.message}),a.dirty()):"jwt"===n.kind?B(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"jwt",code:r.invalid_string,message:n.message}),a.dirty()):"cidr"===n.kind?W(t.data,n.version)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"cidr",code:r.invalid_string,message:n.message}),a.dirty()):"base64"===n.kind?$.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"base64",code:r.invalid_string,message:n.message}),a.dirty()):"base64url"===n.kind?L.test(t.data)||(s=this._getOrReturnCtx(t,s),l(s,{validation:"base64url",code:r.invalid_string,message:n.message}),a.dirty()):e.assertNever(n);return{status:a.value,value:t.data}}_regex(e,t,a){return this.refinement(t=>e.test(t),{validation:t,code:r.invalid_string,...u.errToObj(a)})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...u.errToObj(e)})}url(e){return this._addCheck({kind:"url",...u.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...u.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...u.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...u.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...u.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...u.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...u.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...u.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...u.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...u.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...u.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...u.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...u.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...u.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...u.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...u.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...u.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...u.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...u.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...u.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...u.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...u.errToObj(t)})}nonempty(e){return this.min(1,u.errToObj(e))}trim(){return new q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function H(e,t){const a=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=a>s?a:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}q.create=e=>new q({checks:[],typeName:Ze.ZodString,coerce:e?.coerce??!1,...b(e)});class J extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==n.number){const e=this._getOrReturnCtx(t);return l(e,{code:r.invalid_type,expected:n.number,received:e.parsedType}),p}let a;const s=new h;for(const n of this._def.checks)"int"===n.kind?e.isInteger(t.data)||(a=this._getOrReturnCtx(t,a),l(a,{code:r.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):"multipleOf"===n.kind?0!==H(t.data,n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(a=this._getOrReturnCtx(t,a),l(a,{code:r.not_finite,message:n.message}),s.dirty()):e.assertNever(n);return{status:s.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,a,s){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:u.toString(s)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:u.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:u.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:u.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:u.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&e.isInteger(t.value))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}}J.create=e=>new J({checks:[],typeName:Ze.ZodNumber,coerce:e?.coerce||!1,...b(e)});class Q extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==n.bigint)return this._getInvalidInput(t);let a;const s=new h;for(const n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(a=this._getOrReturnCtx(t,a),l(a,{code:r.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):e.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,a,s){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:a,message:u.toString(s)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>new Q({checks:[],typeName:Ze.ZodBigInt,coerce:e?.coerce??!1,...b(e)});class G extends w{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==n.boolean){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.boolean,received:t.parsedType}),p}return f(e.data)}}G.create=e=>new G({typeName:Ze.ZodBoolean,coerce:e?.coerce||!1,...b(e)});class X extends w{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==n.date){const e=this._getOrReturnCtx(t);return l(e,{code:r.invalid_type,expected:n.date,received:e.parsedType}),p}if(Number.isNaN(t.data.getTime()))return l(this._getOrReturnCtx(t),{code:r.invalid_date}),p;const a=new h;let s;for(const n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),a.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),l(s,{code:r.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),a.dirty()):e.assertNever(n);return{status:a.value,value:new Date(t.data.getTime())}}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:u.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:u.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}X.create=e=>new X({checks:[],coerce:e?.coerce||!1,typeName:Ze.ZodDate,...b(e)});class Y extends w{_parse(e){if(this._getType(e)!==n.symbol){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.symbol,received:t.parsedType}),p}return f(e.data)}}Y.create=e=>new Y({typeName:Ze.ZodSymbol,...b(e)});class ee extends w{_parse(e){if(this._getType(e)!==n.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.undefined,received:t.parsedType}),p}return f(e.data)}}ee.create=e=>new ee({typeName:Ze.ZodUndefined,...b(e)});class te extends w{_parse(e){if(this._getType(e)!==n.null){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.null,received:t.parsedType}),p}return f(e.data)}}te.create=e=>new te({typeName:Ze.ZodNull,...b(e)});class ae extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return f(e.data)}}ae.create=e=>new ae({typeName:Ze.ZodAny,...b(e)});class se extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return f(e.data)}}se.create=e=>new se({typeName:Ze.ZodUnknown,...b(e)});class ne extends w{_parse(e){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.never,received:t.parsedType}),p}}ne.create=e=>new ne({typeName:Ze.ZodNever,...b(e)});class ie extends w{_parse(e){if(this._getType(e)!==n.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.void,received:t.parsedType}),p}return f(e.data)}}ie.create=e=>new ie({typeName:Ze.ZodVoid,...b(e)});class re extends w{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),s=this._def;if(t.parsedType!==n.array)return l(t,{code:r.invalid_type,expected:n.array,received:t.parsedType}),p;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(l(t,{code:e?r.too_big:r.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),a.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(l(t,{code:r.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),a.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(l(t,{code:r.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map((e,a)=>s.type._parseAsync(new k(t,e,t.path,a)))).then(e=>h.mergeArray(a,e));const i=[...t.data].map((e,a)=>s.type._parseSync(new k(t,e,t.path,a)));return h.mergeArray(a,i)}get element(){return this._def.type}min(e,t){return new re({...this._def,minLength:{value:e,message:u.toString(t)}})}max(e,t){return new re({...this._def,maxLength:{value:e,message:u.toString(t)}})}length(e,t){return new re({...this._def,exactLength:{value:e,message:u.toString(t)}})}nonempty(e){return this.min(1,e)}}function oe(e){if(e instanceof de){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=we.create(oe(s))}return new de({...e._def,shape:()=>t})}return e instanceof re?new re({...e._def,type:oe(e.element)}):e instanceof we?we.create(oe(e.unwrap())):e instanceof Te?Te.create(oe(e.unwrap())):e instanceof he?he.create(e.items.map(e=>oe(e))):e}re.create=(e,t)=>new re({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ze.ZodArray,...b(t)});class de extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),a=e.objectKeys(t);return this._cached={shape:t,keys:a},this._cached}_parse(e){if(this._getType(e)!==n.object){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.object,received:t.parsedType}),p}const{status:t,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ne&&"strip"===this._def.unknownKeys))for(const e in a.data)i.includes(e)||o.push(e);const d=[];for(const e of i){const t=s[e],n=a.data[e];d.push({key:{status:"valid",value:e},value:t._parse(new k(a,n,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof ne){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)d.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)o.length>0&&(l(a,{code:r.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const s=a.data[t];d.push({key:{status:"valid",value:t},value:e._parse(new k(a,s,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of d){const a=await t.key,s=await t.value;e.push({key:a,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>h.mergeObjectSync(t,e)):h.mergeObjectSync(t,d)}get shape(){return this._def.shape()}strict(e){return u.errToObj,new de({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,a)=>{const s=this._def.errorMap?.(t,a).message??a.defaultError;return"unrecognized_keys"===t.code?{message:u.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ze.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(t){const a={};for(const s of e.objectKeys(t))t[s]&&this.shape[s]&&(a[s]=this.shape[s]);return new de({...this._def,shape:()=>a})}omit(t){const a={};for(const s of e.objectKeys(this.shape))t[s]||(a[s]=this.shape[s]);return new de({...this._def,shape:()=>a})}deepPartial(){return oe(this)}partial(t){const a={};for(const s of e.objectKeys(this.shape)){const e=this.shape[s];t&&!t[s]?a[s]=e:a[s]=e.optional()}return new de({...this._def,shape:()=>a})}required(t){const a={};for(const s of e.objectKeys(this.shape))if(t&&!t[s])a[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof we;)e=e._def.innerType;a[s]=e}return new de({...this._def,shape:()=>a})}keyof(){return ye(e.objectKeys(this.shape))}}de.create=(e,t)=>new de({shape:()=>e,unknownKeys:"strip",catchall:ne.create(),typeName:Ze.ZodObject,...b(t)}),de.strictCreate=(e,t)=>new de({shape:()=>e,unknownKeys:"strict",catchall:ne.create(),typeName:Ze.ZodObject,...b(t)}),de.lazycreate=(e,t)=>new de({shape:e,unknownKeys:"strip",catchall:ne.create(),typeName:Ze.ZodObject,...b(t)});class ce extends w{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map(async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map(e=>new o(e.ctx.common.issues));return l(t,{code:r.invalid_union,unionErrors:a}),p});{let e;const s=[];for(const n of a){const a={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:a});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:a}),a.common.issues.length&&s.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new o(e));return l(t,{code:r.invalid_union,unionErrors:n}),p}}get options(){return this._def.options}}function ue(t,a){const s=i(t),r=i(a);if(t===a)return{valid:!0,data:t};if(s===n.object&&r===n.object){const s=e.objectKeys(a),n=e.objectKeys(t).filter(e=>-1!==s.indexOf(e)),i={...t,...a};for(const e of n){const s=ue(t[e],a[e]);if(!s.valid)return{valid:!1};i[e]=s.data}return{valid:!0,data:i}}if(s===n.array&&r===n.array){if(t.length!==a.length)return{valid:!1};const e=[];for(let s=0;s<t.length;s++){const n=ue(t[s],a[s]);if(!n.valid)return{valid:!1};e.push(n.data)}return{valid:!0,data:e}}return s===n.date&&r===n.date&&+t===+a?{valid:!0,data:t}:{valid:!1}}ce.create=(e,t)=>new ce({options:e,typeName:Ze.ZodUnion,...b(t)});class le extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=(e,s)=>{if(_(e)||_(s))return p;const n=ue(e.value,s.value);return n.valid?((g(e)||g(s))&&t.dirty(),{status:t.value,value:n.data}):(l(a,{code:r.invalid_intersection_types}),p)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}le.create=(e,t,a)=>new le({left:e,right:t,typeName:Ze.ZodIntersection,...b(a)});class he extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.array)return l(a,{code:r.invalid_type,expected:n.array,received:a.parsedType}),p;if(a.data.length<this._def.items.length)return l(a,{code:r.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&a.data.length>this._def.items.length&&(l(a,{code:r.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...a.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new k(a,e,a.path,t)):null}).filter(e=>!!e);return a.common.async?Promise.all(s).then(e=>h.mergeArray(t,e)):h.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new he({...this._def,rest:e})}}he.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new he({items:e,typeName:Ze.ZodTuple,rest:null,...b(t)})};class pe extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.object)return l(a,{code:r.invalid_type,expected:n.object,received:a.parsedType}),p;const s=[],i=this._def.keyType,o=this._def.valueType;for(const e in a.data)s.push({key:i._parse(new k(a,e,a.path,e)),value:o._parse(new k(a,a.data[e],a.path,e)),alwaysSet:e in a.data});return a.common.async?h.mergeObjectAsync(t,s):h.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,a){return new pe(t instanceof w?{keyType:e,valueType:t,typeName:Ze.ZodRecord,...b(a)}:{keyType:q.create(),valueType:e,typeName:Ze.ZodRecord,...b(t)})}}class me extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.map)return l(a,{code:r.invalid_type,expected:n.map,received:a.parsedType}),p;const s=this._def.keyType,i=this._def.valueType,o=[...a.data.entries()].map(([e,t],n)=>({key:s._parse(new k(a,e,a.path,[n,"key"])),value:i._parse(new k(a,t,a.path,[n,"value"]))}));if(a.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const a of o){const s=await a.key,n=await a.value;if("aborted"===s.status||"aborted"===n.status)return p;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const a of o){const s=a.key,n=a.value;if("aborted"===s.status||"aborted"===n.status)return p;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}me.create=(e,t,a)=>new me({valueType:t,keyType:e,typeName:Ze.ZodMap,...b(a)});class fe extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.set)return l(a,{code:r.invalid_type,expected:n.set,received:a.parsedType}),p;const s=this._def;null!==s.minSize&&a.data.size<s.minSize.value&&(l(a,{code:r.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&a.data.size>s.maxSize.value&&(l(a,{code:r.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const a=new Set;for(const s of e){if("aborted"===s.status)return p;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const d=[...a.data.values()].map((e,t)=>i._parse(new k(a,e,a.path,t)));return a.common.async?Promise.all(d).then(e=>o(e)):o(d)}min(e,t){return new fe({...this._def,minSize:{value:e,message:u.toString(t)}})}max(e,t){return new fe({...this._def,maxSize:{value:e,message:u.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}fe.create=(e,t)=>new fe({valueType:e,minSize:null,maxSize:null,typeName:Ze.ZodSet,...b(t)});class _e extends w{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}_e.create=(e,t)=>new _e({getter:e,typeName:Ze.ZodLazy,...b(t)});class ge extends w{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:r.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ye(e,t){return new ve({values:e,typeName:Ze.ZodEnum,...b(t)})}ge.create=(e,t)=>new ge({value:e,typeName:Ze.ZodLiteral,...b(t)});class ve extends w{_parse(t){if("string"!=typeof t.data){const a=this._getOrReturnCtx(t),s=this._def.values;return l(a,{expected:e.joinValues(s),received:a.parsedType,code:r.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),a=this._def.values;return l(e,{received:e.data,code:r.invalid_enum_value,options:a}),p}return f(t.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 ve.create(e,{...this._def,...t})}exclude(e,t=this._def){return ve.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ve.create=ye;class ke extends w{_parse(t){const a=e.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==n.string&&s.parsedType!==n.number){const t=e.objectValues(a);return l(s,{expected:e.joinValues(t),received:s.parsedType,code:r.invalid_type}),p}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(a);return l(s,{received:s.data,code:r.invalid_enum_value,options:t}),p}return f(t.data)}get enum(){return this._def.values}}ke.create=(e,t)=>new ke({values:e,typeName:Ze.ZodNativeEnum,...b(t)});class xe extends w{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.promise&&!1===t.common.async)return l(t,{code:r.invalid_type,expected:n.promise,received:t.parsedType}),p;const a=t.parsedType===n.promise?t.data:Promise.resolve(t.data);return f(a.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(e,t)=>new xe({type:e,typeName:Ze.ZodPromise,...b(t)});class be extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:a,ctx:s}=this._processInputParams(t),n=this._def.effect||null,i={addIssue:e=>{l(s,e),e.fatal?a.abort():a.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(s.data,i);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===a.value)return p;const t=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===a.value?m(t.value):t});{if("aborted"===a.value)return p;const t=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===a.value?m(t.value):t}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const t=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===t.status?p:("dirty"===t.status&&a.dirty(),e(t.value),{status:a.value,value:t.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&a.dirty(),e(t.value).then(()=>({status:a.value,value:t.value}))))}if("transform"===n.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!y(e))return p;const t=n.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:t}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>y(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:a.value,value:e})):p)}e.assertNever(n)}}be.create=(e,t,a)=>new be({schema:e,typeName:Ze.ZodEffects,effect:t,...b(a)}),be.createWithPreprocess=(e,t,a)=>new be({schema:t,effect:{type:"preprocess",transform:e},typeName:Ze.ZodEffects,...b(a)});class we extends w{_parse(e){return this._getType(e)===n.undefined?f(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(e,t)=>new we({innerType:e,typeName:Ze.ZodOptional,...b(t)});class Te extends w{_parse(e){return this._getType(e)===n.null?f(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:Ze.ZodNullable,...b(t)});class Oe extends w{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===n.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:Ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Ie extends w{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return v(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new o(a.common.issues)},input:a.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new o(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Ze.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class Ae extends w{_parse(e){if(this._getType(e)!==n.nan){const t=this._getOrReturnCtx(e);return l(t,{code:r.invalid_type,expected:n.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Ae.create=e=>new Ae({typeName:Ze.ZodNaN,...b(e)}),Symbol("zod_brand");class Ne extends w{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ee extends w{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),m(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})();{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(e,t){return new Ee({in:e,out:t,typeName:Ze.ZodPipeline})}}class Se extends w{_parse(e){const t=this._def.innerType._parse(e),a=e=>(y(e)&&(e.value=Object.freeze(e.value)),e);return v(t)?t.then(e=>a(e)):a(t)}unwrap(){return this._def.innerType}}function Re(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function Ce(e,t={},a){return e?ae.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Re(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Re(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}}):ae.create()}var Ze;Se.create=(e,t)=>new Se({innerType:e,typeName:Ze.ZodReadonly,...b(t)}),de.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ze||(Ze={}));const je=q.create,De=J.create,Pe=(Ae.create,Q.create,G.create),$e=(X.create,Y.create,ee.create,te.create,ae.create,se.create),Le=(ne.create,ie.create,re.create),Fe=de.create,Ve=(de.strictCreate,ce.create,le.create,he.create,pe.create),Ue=(me.create,fe.create,_e.create,ge.create),Me=ve.create,ze=(ke.create,xe.create,be.create,we.create,Te.create,be.createWithPreprocess,Ee.create,e=>X.create({...e,coerce:!0}));var Ke=Fe({kty:je(),crv:je().optional(),x:je().optional(),y:je().optional(),d:je().optional(),e:je().optional(),n:je().optional(),kid:je().optional(),alg:je().optional(),use:je().optional(),key_ops:Le(je()).optional()}),Be=Me(["main","session","ingested"]),We=Fe({id:je(),did:je(),type:Be,jwk:Ke.optional(),priority:De()}),qe=(Fe({code:je(),message:je(),service:Ue("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Ce(t=>t instanceof e,t))(Error).optional(),meta:Ve(je(),$e()).optional()}),{AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_EXPIRED:"AUTH_EXPIRED",NOT_INITIALIZED:"NOT_INITIALIZED",NOT_FOUND:"NOT_FOUND",REVOKED:"REVOKED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",CREATION_FAILED:"CREATION_FAILED",REVOCATION_FAILED:"REVOCATION_FAILED",INVALID_TOKEN:"INVALID_TOKEN",KV_SERVICE_UNAVAILABLE:"KV_SERVICE_UNAVAILABLE",DATA_FETCH_FAILED:"DATA_FETCH_FAILED",VALIDATION_ERROR:"VALIDATION_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",CHAIN_TOO_DEEP:"CHAIN_TOO_DEEP",INVALID_CURSOR:"INVALID_CURSOR"}),He=Fe({cid:je(),delegateDID:je(),spaceId:je(),path:je(),actions:Le(je()),caveats:Le(Ve(je(),$e())).optional(),expiry:ze(),isRevoked:Pe(),delegatorDID:je().optional(),createdAt:ze().optional(),parentCid:je().optional(),allowSubDelegation:Pe().optional(),authHeader:je().optional()}),Je=(Fe({cid:je().min(1),status:Me(["active","revoked","expired","unavailable","not_found"]),exists:Pe(),active:Pe(),revoked:Pe(),expired:Pe()}).strict().superRefine((e,t)=>{("active"===e.status?e.exists&&e.active&&!e.revoked&&!e.expired:"revoked"===e.status?e.exists&&!e.active&&e.revoked&&!e.expired:"expired"===e.status?e.exists&&!e.active&&!e.revoked&&e.expired:"unavailable"===e.status?e.exists&&!e.active&&!e.revoked&&!e.expired:!(e.exists||e.active||e.revoked||e.expired))||t.addIssue({code:r.custom,message:"delegation status flags do not match status"})}),Fe({revoked:Ue(!0),cid:je().min(1)}).strict()),Qe=Fe({resource:je().min(1),actions:Le(je()),caveats:Le(Ve(je(),$e()))}).strict(),Ge=je().datetime({offset:!0}).transform(e=>new Date(e)),Xe=Fe({cid:je().min(1),direction:Me(["granted","received"]),delegatorDid:je().min(1),delegateDid:je().min(1),resources:Le(Qe),parents:Le(je()),issuedAt:Ge.nullable(),notBefore:Ge.nullable(),expiresAt:Ge.nullable(),status:Me(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:Ge.nullable().optional(),revokedBy:je().optional(),revokedAncestorCid:je().optional()}).strict(),Ye=Fe({schemaVersion:Ue(2),items:Le(Xe),nextCursor:je().optional()}).strict(),et=(Fe({direction:Me(["granted","received","all","issued"]).optional(),status:Me(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:je().trim().min(1).optional(),limit:De().int().min(1).max(100).optional(),cursor:je().min(1).optional()}).strict(),Fe({resource:je(),action:je(),keys:Le(We),delegation:He,expiresAt:ze().optional()}),Fe({cid:je(),spaceId:je(),delegator:je(),delegatee:je(),keyId:je().optional(),path:je(),actions:Le(je()),expiry:ze().optional(),notBefore:ze().optional(),isRevoked:Pe(),createdAt:ze(),parentCid:je().optional()}),Fe({delegateDID:je(),path:je(),actions:Le(je()),expiry:ze().optional(),disableSubDelegation:Pe().optional(),statement:je().optional()}),Le(He),Fe({root:He,chain:Le(He),leaf:He}),Me(["granted","received","all"])),tt=(Fe({direction:et.optional(),path:je().optional(),actions:Le(je()).optional(),includeRevoked:Pe().optional(),delegator:je().optional(),delegatee:je().optional(),validAt:ze().optional(),limit:De().optional(),cursor:je().optional()}),Me(["owned","delegated"])),at=(Fe({id:je(),name:je().optional(),owner:je(),type:tt,permissions:Le(je()).optional(),expiresAt:ze().optional()}),Me(["base64","compact","ipfs"]));Fe({token:je(),url:je(),delegation:He,schema:at,expiresAt:ze().optional(),description:je().optional()}),Fe({data:$e(),delegation:He,spaceId:je(),path:je()}),Fe({persist:Pe().optional(),validateChain:Pe().optional(),keyName:je().optional(),createSessionKey:Pe().optional(),priority:De().optional()}),Fe({path:je(),actions:Le(je()).optional(),expiry:ze().optional(),schema:at.optional(),description:je().optional(),baseUrl:je().optional(),allowSubDelegation:Pe().optional()}),Fe({hosts:Le(je()),accountSpaceId:je().min(1).optional(),session:$e().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:$e().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:$e().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:Ce().optional(),sessionInvocationSigner:Ce().optional(),fetch:$e().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Fe({createSessionKey:$e().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:$e().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:$e().refine(e=>"function"==typeof e,{message:"Expected a function"})}),Fe({siwe:je(),signature:je(),version:De(),cid:je().optional()});var st=Fe({service:je(),space:je(),path:je(),actions:Le(je()),caveats:Le(Ve(je(),$e())).optional()}),nt=(Fe({session:$e().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:je(),spaceId:je(),abilities:Ve(je(),Ve(je(),Le(je()))),expirationSecs:De(),notBeforeSecs:De().optional(),disableSubDelegation:Pe().optional()}),Fe({delegation:je(),cid:je(),delegateDID:je(),expiry:ze(),resources:Le(st)}),{REVOKE:"tinycloud.delegation/revoke",STATUS:"tinycloud.delegation/status",LIST:"tinycloud.delegation/list",GET:"tinycloud.delegation/get",CHECK:"tinycloud.delegation/check"});function it(e,t,a,s){return{code:e,message:t,service:"delegation",cause:a,meta:s}}var rt="delegation-issued-query-v1";async function ot(e,t,a){const s=await async function(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}(e),n={...a,status:e.status};return 401===e.status||403===e.status?it(qe.PERMISSION_DENIED,""===s?"The node refused the request":s,void 0,n):400===e.status&&s.includes("invalid delegation query cursor")?it(qe.INVALID_CURSOR,"The node rejected the page cursor; list again from the start",void 0,n):503===e.status?it(qe.CHAIN_TOO_DEEP,"This delegation chain is too long for the node to check right now; try again later",void 0,{...n,retryable:!0}):it(qe.NETWORK_ERROR,`${t}: ${e.status} - ${s}`,void 0,n)}async function dt(e,t){const a=e.sessionInvocationSigner;if(!a)return{ok:!1,error:it(qe.NOT_INITIALIZED,"Listing issued delegations needs a session key signer")};try{const s=await async function(e){if(e.state.issuedQuerySupported)return{ok:!0,data:!0};const t=await e.fetchFn(`${e.host}/info`);if(!t.ok)return{ok:!1,error:it(qe.NETWORK_ERROR,`Couldn't read the node's info: ${t.status}`,void 0,{status:t.status})};const a=await t.json();return e.state.issuedQuerySupported=Array.isArray(a.features)&&a.features.includes(rt),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!s.ok)return s;if(!s.data)return{ok:!1,error:it(qe.UNSUPPORTED_OPERATION,"This node doesn't support listing issued delegations yet",void 0,{feature:rt})};const n=await a.sign({[`${a.did()}/delegation`]:{[nt.LIST]:[{}]}}),i=await e.fetchFn(`${e.host}/delegation/query`,{method:"POST",headers:{Authorization:n,"content-type":"application/json"},body:JSON.stringify(t)});if(!i.ok)return{ok:!1,error:await ot(i,"Failed to query issued delegations",{})};const r=Ye.safeParse(await i.json());return r.success?{ok:!0,data:r.data}:{ok:!1,error:it(qe.INVALID_TOKEN,"Node returned an invalid delegation query response")}}catch(e){return{ok:!1,error:it(qe.NETWORK_ERROR,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function ct(e,t){const{pageSize:a=100,maxItems:s,untilCid:n,...i}=t;if(void 0!==s&&(!Number.isInteger(s)||s<1))return{ok:!1,error:it(qe.INVALID_INPUT,"maxItems must be a positive integer")};const r=[],o=new Set;let d;do{const t=Math.min(a,void 0===s?a:s-r.length),n=await e({...i,direction:"issued",limit:t,...void 0===d?{}:{cursor:d}});if(!n.ok)return n;if(r.push(...n.data.items),d=n.data.nextCursor,void 0!==d){if(o.has(d))return{ok:!1,error:it(qe.INVALID_TOKEN,"The node returned the same page cursor twice while listing issued delegations")};o.add(d)}}while(void 0!==d&&(void 0===s||r.length<s)&&(void 0===n||!r.some(e=>e.cid===n)));return{ok:!0,data:void 0===s?r:r.slice(0,s)}}async function ut(e,t){if(!t)return{ok:!1,error:it(qe.INVALID_INPUT,"cid is required")};const a=e.sessionInvocationSigner;if(!a)return{ok:!1,error:it(qe.NOT_INITIALIZED,"Revoking an issued delegation needs a session key signer")};try{const s=await a.sign({[`urn:cid:${t}`]:{[nt.REVOKE]:[{}]}}),n=await e.fetchFn(`${e.host}/revoke`,{method:"POST",headers:{Authorization:s}});if(!n.ok)return 404===n.status?{ok:!1,error:it(qe.NOT_FOUND,`Delegation not found: ${t}`)}:{ok:!1,error:await ot(n,"Failed to revoke delegation",{cid:t})};const i=Je.safeParse(await n.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:it(qe.REVOCATION_FAILED,"Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return{ok:!1,error:it(qe.NETWORK_ERROR,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}module.exports=s})();
|
|
1
|
+
(()=>{"use strict";var e={290(e){var t,r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(a,{DecryptTransportResponseError:()=>o}),e.exports=(t=a,((e,t,a,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of n(t))i.call(e,a)||void 0===a||r(e,a,{get:()=>t[a],enumerable:!(o=s(t,a))||o.enumerable});return e})(r({},"__esModule",{value:!0}),t));var o=class extends Error{constructor(e,t,r){super("Node decrypt request failed"),this.status=e,this.permissionHint=t,this.notFoundMessage=r,this.name="DecryptTransportResponseError"}}}},t={};function r(s){var n=t[s];if(void 0!==n)return n.exports;var i=t[s]={exports:{}};return e[s](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s,n,i={};r.r(i),r.d(i,{queryAllIssued:()=>yi,queryIssued:()=>pi,revokeIssued:()=>fi}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(s||(s={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(n||(n={}));const a=s.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),o=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return Number.isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},c=s.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"]);class u extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof u))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,s.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}u.create=e=>new u(e);const d=(e,t)=>{let r;switch(e.code){case c.invalid_type:r=e.received===a.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case c.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,s.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:r=`Unrecognized key(s) in object: ${s.joinValues(e.keys,", ")}`;break;case c.invalid_union:r="Invalid input";break;case c.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${s.joinValues(e.options)}`;break;case c.invalid_enum_value:r=`Invalid enum value. Expected ${s.joinValues(e.options)}, received '${e.received}'`;break;case c.invalid_arguments:r="Invalid function arguments";break;case c.invalid_return_type:r="Invalid function return type";break;case c.invalid_date:r="Invalid date";break;case c.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:s.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case c.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case c.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case c.custom:r="Invalid input";break;case c.invalid_intersection_types:r="Intersection results could not be merged";break;case c.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case c.not_finite:r="Number must be finite";break;default:r=t.defaultError,s.assertNever(e)}return{message:r}};let l=d;var h;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(h||(h={}));function p(e,t){const r=l,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],a={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const c=s.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===d?void 0:d].filter(e=>!!e)});e.common.issues.push(s)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return f;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,s=await e.value;r.push({key:t,value:s})}return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return f;if("aborted"===n.status)return f;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const f=Object.freeze({status:"aborted"}),m=e=>({status:"dirty",value:e}),g=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,_=e=>"dirty"===e.status,k=e=>"valid"===e.status,E=e=>"undefined"!=typeof Promise&&e instanceof Promise;class b{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const T=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new u(e.common.issues);return this._error=t,this._error}}};function w(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class N{get description(){return this._def.description}_getType(e){return o(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(E(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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},s=this._parseSync({data:e,path:r.path,parent:r});return T(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return k(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(E(s)?s:Promise.resolve(s));return T(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:c.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new Oe({schema:this,typeName:Ke.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:e=>this["~validate"](e)}}optional(){return Re.create(this,this._def)}nullable(){return Ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ce.create(this)}promise(){return Ne.create(this,this._def)}or(e){return le.create([this,e],this._def)}and(e){return fe.create(this,e,this._def)}transform(e){return new Oe({...w(this._def),schema:this,typeName:Ke.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ie({...w(this._def),innerType:this,defaultValue:t,typeName:Ke.ZodDefault})}brand(){return new De({typeName:Ke.ZodBranded,type:this,...w(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Se({...w(this._def),innerType:this,catchValue:t,typeName:Ke.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Pe.create(this,e)}readonly(){return Ce.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const O=/^c[^\s-]{8,}$/i,R=/^[0-9a-z]+$/,A=/^[0-9A-HJKMNP-TV-Z]{26}$/i,I=/^[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,S=/^[a-z0-9_-]{21}$/i,x=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,D=/^[-+]?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)?)??$/,P=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let C;const U=/^(?:(?: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])$/,L=/^(?:(?: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])$/,K=/^(([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]))$/,$=/^(([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])$/,V=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,M="((\\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])))",F=new RegExp(`^${M}$`);function j(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function H(e){return new RegExp(`^${j(e)}$`)}function B(e){let t=`${M}T${j(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Z(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!K.test(e))}function W(e,t){if(!x.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return!("object"!=typeof n||null===n||"typ"in n&&"JWT"!==n?.typ||!n.alg||t&&n.alg!==t)}catch{return!1}}function G(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!$.test(e))}class z extends N{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==a.string){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.string,received:t.parsedType}),f}const t=new y;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:c.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:c.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const s=e.data.length>n.value,i=e.data.length<n.value;(s||i)&&(r=this._getOrReturnCtx(e,r),s?p(r,{code:c.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&p(r,{code:c.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"email",code:c.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)C||(C=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),C.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"emoji",code:c.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)I.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"uuid",code:c.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)S.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"nanoid",code:c.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)O.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"cuid",code:c.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"cuid2",code:c.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)A.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"ulid",code:c.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),p(r,{validation:"url",code:c.invalid_string,message:n.message}),t.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"regex",code:c.invalid_string,message:n.message}),t.dirty())):"trim"===n.kind?e.data=e.data.trim():"includes"===n.kind?e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),p(r,{code:c.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty()):"toLowerCase"===n.kind?e.data=e.data.toLowerCase():"toUpperCase"===n.kind?e.data=e.data.toUpperCase():"startsWith"===n.kind?e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),p(r,{code:c.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty()):"endsWith"===n.kind?e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),p(r,{code:c.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty()):"datetime"===n.kind?B(n).test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:c.invalid_string,validation:"datetime",message:n.message}),t.dirty()):"date"===n.kind?F.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:c.invalid_string,validation:"date",message:n.message}),t.dirty()):"time"===n.kind?H(n).test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:c.invalid_string,validation:"time",message:n.message}),t.dirty()):"duration"===n.kind?D.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"duration",code:c.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?Z(e.data,n.version)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"ip",code:c.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?W(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"jwt",code:c.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?G(e.data,n.version)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"cidr",code:c.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?V.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"base64",code:c.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?q.test(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{validation:"base64url",code:c.invalid_string,message:n.message}),t.dirty()):s.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:c.invalid_string,...h.errToObj(r)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function J(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}z.create=e=>new z({checks:[],typeName:Ke.ZodString,coerce:e?.coerce??!1,...w(e)});class Q extends N{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)),this._getType(e)!==a.number){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.number,received:t.parsedType}),f}let t;const r=new y;for(const n of this._def.checks)"int"===n.kind?s.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:c.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==J(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:c.not_finite,message:n.message}),r.dirty()):s.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,r,s){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:h.toString(s)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&s.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Q.create=e=>new Q({checks:[],typeName:Ke.ZodNumber,coerce:e?.coerce||!1,...w(e)});class Y extends N{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)}if(this._getType(e)!==a.bigint)return this._getInvalidInput(e);let t;const r=new y;for(const n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):s.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.bigint,received:t.parsedType}),f}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,r,s){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:h.toString(s)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Y.create=e=>new Y({checks:[],typeName:Ke.ZodBigInt,coerce:e?.coerce??!1,...w(e)});class X extends N{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.boolean,received:t.parsedType}),f}return g(e.data)}}X.create=e=>new X({typeName:Ke.ZodBoolean,coerce:e?.coerce||!1,...w(e)});class ee extends N{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==a.date){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.date,received:t.parsedType}),f}if(Number.isNaN(e.data.getTime()))return p(this._getOrReturnCtx(e),{code:c.invalid_date}),f;const t=new y;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:c.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:c.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):s.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ee.create=e=>new ee({checks:[],coerce:e?.coerce||!1,typeName:Ke.ZodDate,...w(e)});class te extends N{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.symbol,received:t.parsedType}),f}return g(e.data)}}te.create=e=>new te({typeName:Ke.ZodSymbol,...w(e)});class re extends N{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.undefined,received:t.parsedType}),f}return g(e.data)}}re.create=e=>new re({typeName:Ke.ZodUndefined,...w(e)});class se extends N{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.null,received:t.parsedType}),f}return g(e.data)}}se.create=e=>new se({typeName:Ke.ZodNull,...w(e)});class ne extends N{constructor(){super(...arguments),this._any=!0}_parse(e){return g(e.data)}}ne.create=e=>new ne({typeName:Ke.ZodAny,...w(e)});class ie extends N{constructor(){super(...arguments),this._unknown=!0}_parse(e){return g(e.data)}}ie.create=e=>new ie({typeName:Ke.ZodUnknown,...w(e)});class ae extends N{_parse(e){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.never,received:t.parsedType}),f}}ae.create=e=>new ae({typeName:Ke.ZodNever,...w(e)});class oe extends N{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.void,received:t.parsedType}),f}return g(e.data)}}oe.create=e=>new oe({typeName:Ke.ZodVoid,...w(e)});class ce extends N{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==a.array)return p(t,{code:c.invalid_type,expected:a.array,received:t.parsedType}),f;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(p(t,{code:e?c.too_big:c.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(p(t,{code:c.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(p(t,{code:c.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new b(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new b(t,e,t.path,r)));return y.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new ce({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new ce({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new ce({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}}function ue(e){if(e instanceof de){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Re.create(ue(s))}return new de({...e._def,shape:()=>t})}return e instanceof ce?new ce({...e._def,type:ue(e.element)}):e instanceof Re?Re.create(ue(e.unwrap())):e instanceof Ae?Ae.create(ue(e.unwrap())):e instanceof me?me.create(e.items.map(e=>ue(e))):e}ce.create=(e,t)=>new ce({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ke.ZodArray,...w(t)});class de extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=s.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.object,received:t.parsedType}),f}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof ae&&"strip"===this._def.unknownKeys))for(const e in r.data)n.includes(e)||i.push(e);const o=[];for(const e of n){const t=s[e],n=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new b(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ae){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(p(r,{code:c.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new b(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new de({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ke.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const r of s.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const r of s.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new de({...this._def,shape:()=>t})}deepPartial(){return ue(this)}partial(e){const t={};for(const r of s.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const r of s.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Re;)e=e._def.innerType;t[r]=e}return new de({...this._def,shape:()=>t})}keyof(){return be(s.objectKeys(this.shape))}}de.create=(e,t)=>new de({shape:()=>e,unknownKeys:"strip",catchall:ae.create(),typeName:Ke.ZodObject,...w(t)}),de.strictCreate=(e,t)=>new de({shape:()=>e,unknownKeys:"strict",catchall:ae.create(),typeName:Ke.ZodObject,...w(t)}),de.lazycreate=(e,t)=>new de({shape:e,unknownKeys:"strip",catchall:ae.create(),typeName:Ke.ZodObject,...w(t)});class le extends N{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new u(e.ctx.common.issues));return p(t,{code:c.invalid_union,unionErrors:r}),f});{let e;const s=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new u(e));return p(t,{code:c.invalid_union,unionErrors:n}),f}}get options(){return this._def.options}}le.create=(e,t)=>new le({options:e,typeName:Ke.ZodUnion,...w(t)});const he=e=>e instanceof ke?he(e.schema):e instanceof Oe?he(e.innerType()):e instanceof Ee?[e.value]:e instanceof Te?e.options:e instanceof we?s.objectValues(e.enum):e instanceof Ie?he(e._def.innerType):e instanceof re?[void 0]:e instanceof se?[null]:e instanceof Re?[void 0,...he(e.unwrap())]:e instanceof Ae?[null,...he(e.unwrap())]:e instanceof De||e instanceof Ce?he(e.unwrap()):e instanceof Se?he(e._def.innerType):[];class pe extends N{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.object)return p(t,{code:c.invalid_type,expected:a.object,received:t.parsedType}),f;const r=this.discriminator,s=t.data[r],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),f)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const s=new Map;for(const r of t){const t=he(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(s.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);s.set(n,r)}}return new pe({typeName:Ke.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...w(r)})}}function ye(e,t){const r=o(e),n=o(t);if(e===t)return{valid:!0,data:e};if(r===a.object&&n===a.object){const r=s.objectKeys(t),n=s.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const s=ye(e[r],t[r]);if(!s.valid)return{valid:!1};i[r]=s.data}return{valid:!0,data:i}}if(r===a.array&&n===a.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=ye(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===a.date&&n===a.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class fe extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(v(e)||v(s))return f;const n=ye(e.value,s.value);return n.valid?((_(e)||_(s))&&t.dirty(),{status:t.value,value:n.data}):(p(r,{code:c.invalid_intersection_types}),f)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}fe.create=(e,t,r)=>new fe({left:e,right:t,typeName:Ke.ZodIntersection,...w(r)});class me extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.array)return p(r,{code:c.invalid_type,expected:a.array,received:r.parsedType}),f;if(r.data.length<this._def.items.length)return p(r,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),f;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new b(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>y.mergeArray(t,e)):y.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new me({...this._def,rest:e})}}me.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new me({items:e,typeName:Ke.ZodTuple,rest:null,...w(t)})};class ge extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.object)return p(r,{code:c.invalid_type,expected:a.object,received:r.parsedType}),f;const s=[],n=this._def.keyType,i=this._def.valueType;for(const e in r.data)s.push({key:n._parse(new b(r,e,r.path,e)),value:i._parse(new b(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?y.mergeObjectAsync(t,s):y.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new ge(t instanceof N?{keyType:e,valueType:t,typeName:Ke.ZodRecord,...w(r)}:{keyType:z.create(),valueType:e,typeName:Ke.ZodRecord,...w(t)})}}class ve extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.map)return p(r,{code:c.invalid_type,expected:a.map,received:r.parsedType}),f;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new b(r,e,r.path,[i,"key"])),value:n._parse(new b(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return f;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return f;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}ve.create=(e,t,r)=>new ve({valueType:t,keyType:e,typeName:Ke.ZodMap,...w(r)});class _e extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.set)return p(r,{code:c.invalid_type,expected:a.set,received:r.parsedType}),f;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(p(r,{code:c.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(p(r,{code:c.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return f;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>n._parse(new b(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new _e({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new _e({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}_e.create=(e,t)=>new _e({valueType:e,minSize:null,maxSize:null,typeName:Ke.ZodSet,...w(t)});class ke extends N{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ke.create=(e,t)=>new ke({getter:e,typeName:Ke.ZodLazy,...w(t)});class Ee extends N{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),f}return{status:"valid",value:e.data}}get value(){return this._def.value}}function be(e,t){return new Te({values:e,typeName:Ke.ZodEnum,...w(t)})}Ee.create=(e,t)=>new Ee({value:e,typeName:Ke.ZodLiteral,...w(t)});class Te extends N{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{expected:s.joinValues(r),received:t.parsedType,code:c.invalid_type}),f}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{received:t.data,code:c.invalid_enum_value,options:r}),f}return g(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 Te.create(e,{...this._def,...t})}exclude(e,t=this._def){return Te.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Te.create=be;class we extends N{_parse(e){const t=s.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==a.string&&r.parsedType!==a.number){const e=s.objectValues(t);return p(r,{expected:s.joinValues(e),received:r.parsedType,code:c.invalid_type}),f}if(this._cache||(this._cache=new Set(s.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=s.objectValues(t);return p(r,{received:r.data,code:c.invalid_enum_value,options:e}),f}return g(e.data)}get enum(){return this._def.values}}we.create=(e,t)=>new we({values:e,typeName:Ke.ZodNativeEnum,...w(t)});class Ne extends N{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return p(t,{code:c.invalid_type,expected:a.promise,received:t.parsedType}),f;const r=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return g(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:Ke.ZodPromise,...w(t)});class Oe extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ke.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{p(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return f;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?f:"dirty"===s.status||"dirty"===t.value?m(s.value):s});{if("aborted"===t.value)return f;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?f:"dirty"===s.status||"dirty"===t.value?m(s.value):s}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?f:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?f:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!k(e))return f;const s=n.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>k(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):f)}s.assertNever(n)}}Oe.create=(e,t,r)=>new Oe({schema:e,typeName:Ke.ZodEffects,effect:t,...w(r)}),Oe.createWithPreprocess=(e,t,r)=>new Oe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ke.ZodEffects,...w(r)});class Re extends N{_parse(e){return this._getType(e)===a.undefined?g(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:Ke.ZodOptional,...w(t)});class Ae extends N{_parse(e){return this._getType(e)===a.null?g(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ke.ZodNullable,...w(t)});class Ie extends N{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===a.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Ke.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...w(t)});class Se extends N{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return E(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Se.create=(e,t)=>new Se({innerType:e,typeName:Ke.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...w(t)});class xe extends N{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:a.nan,received:t.parsedType}),f}return{status:"valid",value:e.data}}}xe.create=e=>new xe({typeName:Ke.ZodNaN,...w(e)}),Symbol("zod_brand");class De extends N{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Pe extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),m(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Pe({in:e,out:t,typeName:Ke.ZodPipeline})}}class Ce extends N{_parse(e){const t=this._def.innerType._parse(e),r=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return E(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Ue(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Le(e,t={},r){return e?ne.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Ue(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Ue(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):ne.create()}var Ke;Ce.create=(e,t)=>new Ce({innerType:e,typeName:Ke.ZodReadonly,...w(t)}),de.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ke||(Ke={}));const $e=z.create,Ve=Q.create,qe=(xe.create,Y.create,X.create),Me=(ee.create,te.create,re.create,se.create,ne.create,ie.create),Fe=(ae.create,oe.create,ce.create),je=de.create,He=(de.strictCreate,le.create,pe.create),Be=(fe.create,me.create,ge.create),Ze=(ve.create,_e.create,ke.create,Ee.create),We=Te.create,Ge=(we.create,Ne.create,Oe.create,Re.create,Ae.create,Oe.createWithPreprocess,Pe.create,e=>ee.create({...e,coerce:!0}));var ze=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function Je(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function Qe(e){return e.slice(10,e.indexOf("/"))}function Ye(e){return e.slice(e.indexOf("/")+1)}function Xe(e){const t={};for(const r of ze)Qe(r.urn)===e&&(t[Je(Ye(r.urn))]=r.urn);return t}var et=Xe("kv"),tt={...Xe("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},rt={...Xe("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},st=Xe("capabilities"),nt=(Xe("hooks"),Xe("encryption")),it=Xe("space"),at=ze,ot="applications",ct="account",ut="applications/",dt="secrets",lt="default",ht="public",pt="agents",yt="tinycloud.encryption",ft=nt.NETWORK_CREATE,mt=[lt,ot,ct,dt,ht,pt],gt={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:lt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:lt,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:lt,path:"",actions:["read","write"]}]},vt={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:ot,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ot,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:ot,path:"",actions:["read","write"]}]},_t={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ct,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ct,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ct,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ct,path:"account",actions:["read","write","schema"]}]},kt={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:dt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:dt,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:dt,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:dt,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:dt,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:dt,path:"",actions:["read"],skipPrefix:!0}]},Et={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:ht,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ht,path:"",actions:["get","list","metadata"]}]},bt={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:pt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:pt,path:"",actions:["get","put","del","list","metadata"]}]},Tt={[lt]:gt,[ot]:vt,[ct]:_t,[dt]:kt,[ht]:Et,[pt]:bt};function wt(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Nt(e,t,r){return!0===r||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function Ot(e,t,r){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const r=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,s="read"===r||"get"===r?et.GET:"write"===r||"put"===r?et.PUT:"delete"===r||"del"===r?et.DEL:"list"===r?et.LIST:"metadata"===r?et.METADATA:void 0;if(void 0===s)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const n=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${n}`,actions:[s],skipPrefix:!0}})}(e).flatMap(e=>Ot(e,t,r));const s=!0===e.skipPrefix||e.service===yt;return[{service:e.service,space:e.service===yt?"encryption":e.space??r,path:Nt(t,e.path,s),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function Rt(e){const t=new Set(e.filter(e=>e.service!==yt).map(e=>e.space));return function(e){const t=new Map;for(const r of e){const e=`${r.service}\0${r.space}\0${r.path}`,s=t.get(e);if(s)for(const e of r.actions)s.actions.includes(e)||s.actions.push(e);else t.set(e,{...r,actions:[...r.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[st.READ]}))])}function At(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const r=t.includeAccountRegistryPermissions??!0,s=e.map(wt),n=s.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??ot;return(e.permissions??[]).flatMap(e=>Ot(e,t,r))});r&&n.push(...It.map(e=>({...e,actions:[...e.actions]})));const i=new Map;for(const e of s){const t=i.get(e.app_id)??[];t.push(wt(e)),i.set(e.app_id,t)}return{manifests:s,resources:Rt(n),delegationTargets:[],registryRecords:r?[...i.entries()].map(([e,t])=>({key:`${ut}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:s.some(e=>e.includePublicSpace??!0)}}([Tt[e]],{includeAccountRegistryPermissions:!1})}mt.map(e=>({name:e,manifest:Tt[e],persistedAsApplication:e===dt}));var It=Object.freeze([{service:"tinycloud.kv",space:ct,path:ut,actions:[et.GET,et.PUT,et.LIST]},{service:"tinycloud.kv",space:ct,path:"spaces/",actions:[et.GET,et.PUT,et.LIST]},{service:"tinycloud.kv",space:ct,path:"system/bootstrap/complete",actions:[et.GET,et.PUT]},{service:"tinycloud.delegation",space:ct,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ct,path:"account",actions:[tt.READ,tt.WRITE,tt.SCHEMA]},{service:"tinycloud.capabilities",space:ct,path:"",actions:[st.READ]}]),St=At(lt),xt={...St,resources:[...St.resources,...It.map(e=>({...e,actions:[...e.actions]}))]},Dt=Object.freeze(Object.fromEntries(mt.map(e=>[e,e===lt?xt:At(e)]))),Pt=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ft]}]);Object.freeze(mt.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:Dt[e].resources,...e===ct?{rawAbilities:Pt}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[it.HOST]}]));var Ct=r(290),Ut={NOT_FOUND:"NOT_FOUND",AUTH_EXPIRED:"AUTH_EXPIRED",AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_DELEGATION_REVOKED:"AUTH_DELEGATION_REVOKED",AUTH_DELEGATION_ANCESTOR_REVOKED:"AUTH_DELEGATION_ANCESTOR_REVOKED",NETWORK_ERROR:"NETWORK_ERROR",NODE_NOT_RESPONDING:"NODE_NOT_RESPONDING",NODE_IDENTITY_MISMATCH:"NODE_IDENTITY_MISMATCH",PARTIAL_NODE_WRITE:"PARTIAL_NODE_WRITE",RESOURCE_NOT_ROUTED:"RESOURCE_NOT_ROUTED",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",NODE_BUSY:"NODE_BUSY",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",OUTCOME_UNKNOWN:"OUTCOME_UNKNOWN",KV_NOT_FOUND:"KV_NOT_FOUND",KV_WRITE_FAILED:"KV_WRITE_FAILED",KV_PRECONDITION_FAILED:"KV_PRECONDITION_FAILED",KV_CONFLICT:"KV_CONFLICT",KV_RESPONSE_TOO_LARGE:"KV_RESPONSE_TOO_LARGE",KV_SYNC_RESET_REQUIRED:"KV_SYNC_RESET_REQUIRED",KV_RETENTION_GRANT_REFUSED:"KV_RETENTION_GRANT_REFUSED",SQL_ERROR:"SQL_ERROR",SQL_PERMISSION_DENIED:"SQL_PERMISSION_DENIED",SQL_DATABASE_NOT_FOUND:"SQL_DATABASE_NOT_FOUND",SQL_RESPONSE_TOO_LARGE:"SQL_RESPONSE_TOO_LARGE",SQL_QUOTA_EXCEEDED:"SQL_QUOTA_EXCEEDED",SQL_INVALID_STATEMENT:"SQL_INVALID_STATEMENT",SQL_SCHEMA_ERROR:"SQL_SCHEMA_ERROR",SQL_READONLY_VIOLATION:"SQL_READONLY_VIOLATION",STORAGE_QUOTA_EXCEEDED:"STORAGE_QUOTA_EXCEEDED",STORAGE_LIMIT_REACHED:"STORAGE_LIMIT_REACHED",STORAGE_STATUS_UNAVAILABLE:"STORAGE_STATUS_UNAVAILABLE",DUCKDB_ERROR:"DUCKDB_ERROR",DUCKDB_PERMISSION_DENIED:"DUCKDB_PERMISSION_DENIED",DUCKDB_DATABASE_NOT_FOUND:"DUCKDB_DATABASE_NOT_FOUND",DUCKDB_RESPONSE_TOO_LARGE:"DUCKDB_RESPONSE_TOO_LARGE",DUCKDB_QUOTA_EXCEEDED:"DUCKDB_QUOTA_EXCEEDED",DUCKDB_INVALID_STATEMENT:"DUCKDB_INVALID_STATEMENT",DUCKDB_SCHEMA_ERROR:"DUCKDB_SCHEMA_ERROR",DUCKDB_READONLY_VIOLATION:"DUCKDB_READONLY_VIOLATION"},Lt=(Ut.NODE_BUSY,Ut.REQUEST_TIMEOUT,"telemetry.span");function Kt(e){return{ok:!0,data:e}}function $t(e){return{ok:!1,error:e}}function Vt(e,t,r,s){return{code:e,message:t,service:r,cause:s?.cause,meta:s?.meta}}var qt="[REDACTED]",Mt=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),Ft=new Set(["authenticated","ok","persisted","purgePending"]),jt={source:["replica","network","none"],reason:["hit","absent","deleted","content_missing","coverage_incomplete","not_covered","pending_write","grant_missing","grant_expired","grant_revoked","grant_not_yet_valid","stale","replica_error","runtime_unsupported","replica_unavailable","unsupported_option","network_cursor","cursor_restart","aborted","REPLICA_BEHIND_OWN_WRITES","REPLICA_UNPROVEN_SINCE_START","NETWORK_REQUESTED","replica_gated","sign_out","account_switch","consent_expired","startup"],op:["get","list","put","delete","batchPut"],trigger:["start","interval","stale_read","manual","peer"],origin:["peer"],outcome:["found","not_found","error","committed","failed","ambiguous","ok","busy","aborted"],class:["offline","authority","storage","node","lifecycle"],state:["opened","grant_installed","grant_missing","runtime_unsupported","unavailable","revoked","recreated","purged","purge_failed","pending_store_error","pinned","pending_cleared","closed","idle","ready","gated"],action:["minted","renewed","renewal_refused","renewal_deferred","capped","expired","consent_deadline_reached","denied","deny_stale","deny_failed","database_deleted","marker_set","marker_cleared","unguarded","drained","erased","erase_failed","activation_blocked","activated","recovered"],gate:["not_established","stamp_stale","principal_mismatch","purge_pending","logout_pending","gate_unavailable"],kind:["value","missing_local","extra_local","keys","order"],coverage:["empty","bootstrapping","complete"],authority:["valid","expired","revoked","not-yet-valid"],code:["NETWORK_ERROR","TIMEOUT","ABORTED","REPLICA_BUSY","REPLICA_BEHIND_OWN_WRITES","REPLICA_UNPROVEN_SINCE_START","NETWORK_REQUESTED","INTEGRITY_ERROR","STORAGE_ERROR","REPLICA_CLOSED","RUNTIME_UNSUPPORTED","GRANT_EXPIRED","GRANT_REVOKED","GRANT_NOT_YET_VALID","GRANT_MISSING","GRANT_INVALID","SOURCE_CHANGED","PROTOCOL_ERROR","SCOPE_VIOLATION","NODE_ERROR","CONTENT_MISMATCH","STORAGE_FULL","REPLICA_GATED","RESET_REQUIRED","STORAGE_BUDGET","CONSENT_EXPIRED"],pendingState:["in_flight","committed","ambiguous"],strategy:["session","minted","installed"],verify:["match","diverged","error","aborted"]};function Ht(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Bt(e,t){try{return e[t]}catch{return qt}}function Zt(e){if(null==e)return e;if("object"!=typeof e)return qt;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return qt;const t={};for(const r of Mt){const s=Ht(Bt(e,r));void 0!==s&&(t[r]=s)}for(const r of Ft){const s=Bt(e,r);"boolean"==typeof s&&(t[r]=s)}for(const[r,s]of Object.entries(jt)){const n=Bt(e,r);"string"==typeof n&&s.includes(n)&&(t[r]=n)}void 0!==Bt(e,"url")&&(t.url=qt);const r=Bt(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=Ht(Bt(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return qt}}var Wt="TinyCloud_debug";function Gt(){return globalThis}function zt(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function Jt(e){return!0===e||"true"===e||"1"===e}function Qt(){const e=globalThis.process;return e?.env?.[Wt]}function Yt(){if(Gt().window===globalThis)try{return globalThis.localStorage}catch{return}}function Xt(e){const t=Yt();if(t)try{e?t.setItem(Wt,"true"):t.removeItem(Wt)}catch{}}var er=new class{constructor(){this.enabled=Jt(Gt()[Wt])||Jt(function(){const e=Yt();if(e)try{return e.getItem(Wt)}catch{return}}())||Jt(Qt()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||Jt(Gt()[Wt])||Jt(Qt())}enable(e={}){this.enabled=!0,Gt()[Wt]=!0,!1!==e.persist&&Xt(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,Gt()[Wt]=!1,!1!==e.persist&&Xt(!1)}clear(){this.events=[]}getLogs(){return[...this.events]}log(e,t,r){if(this.isEnabled())return this.record({event:e,data:t,message:r,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}startTimer(e,t){if(!this.isEnabled())return{stop:()=>{}};const r=zt();return this.log(`${e}.start`,t),{stop:t=>{const s=zt();return this.record({event:`${e}.end`,data:t,durationMs:s-r,startedAt:r,endedAt:s,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}}}async timeAsync(e,t,r){if(!this.isEnabled())return t();const s=this.startTimer(e,r);try{const e=await t();return s.stop({ok:!0}),e}catch(e){throw s.stop({ok:!1,error:e}),e}}time(e,t,r){if(!this.isEnabled())return t();const s=this.startTimer(e,r);try{const e=t();return s.stop({ok:!0}),e}catch(e){throw s.stop({ok:!1,error:e}),e}}record(e){const t={...e,...void 0===e.data?{}:{data:Zt(e.data)},...void 0===e.message?{}:{message:"[REDACTED]"},sequence:++this.sequence};this.events.push(t),this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);try{globalThis.console?.debug?.("[TinyCloud]",t.event,t)}catch{}return t}};function tr(e){return er.enable(e),er}function rr(e){return er.disable(e),er}function sr(){return er.getLogs()}function nr(){er.clear()}!function(){const e=Gt();e.TinyCloudDebug=er,e.enableTinyCloudDebug=tr,e.disableTinyCloudDebug=rr,e.getTinyCloudDebugLogs=sr,e.clearTinyCloudDebugLogs=nr}();var ir=je({code:$e(),message:$e(),service:$e(),cause:Me().optional(),meta:je({}).passthrough().optional()});function ar(e,t=ir){return He("ok",[je({ok:Ze(!0),data:e}),je({ok:Ze(!1),error:t})])}ar(Me(),ir);var or,cr=je({etag:$e().optional(),contentType:$e().optional(),lastModified:$e().optional(),contentLength:Ve().optional()});function ur(e){try{return JSON.parse(e)}catch{return{}}}function dr(e,t,r,s,n){return n.message?hr(n.message):/<!doctype html/i.test(i=s)||/<html[\s>]/i.test(i)?524===r||/524\s*[:-]/i.test(s)||/a timeout occurred/i.test(s)?`${e} ${t} failed: upstream request timed out. Please retry.`:`${e} ${t} failed: upstream service returned an HTML error page (${r}).`:`${e} ${t} failed: ${r} - ${hr(s)}`;var i}function lr(e,t,r){const s={status:e,statusText:t},n=hr(r);return n&&(s.responseSnippet=n.slice(0,300)),s}function hr(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}or=Me(),je({data:or,headers:cr}),ar(je({keys:Fe($e()),truncated:qe().optional(),nextCursor:$e().optional()})),je({service:$e(),action:$e(),span:$e().optional(),key:$e().optional(),timestamp:Ve()}),je({service:$e(),action:$e(),span:$e().optional(),ok:qe(),duration:Ve(),durationMs:Ve().optional(),status:Ve().optional()}),je({service:$e(),span:$e().optional(),error:ir}),je({service:$e(),attempt:Ve().int().positive(),maxAttempts:Ve().int().positive(),error:ir}),je({span:$e(),ok:qe(),durationMs:Ve(),service:$e().optional(),action:$e().optional(),status:Ve().optional(),error:ir.optional()}),je({maxAttempts:Ve().int().positive(),backoff:We(["none","linear","exponential"]),baseDelayMs:Ve().nonnegative(),maxDelayMs:Ve().nonnegative(),retryableErrors:Fe($e()),maxTotalMs:Ve().positive().optional()}),je({delegationHeader:je({Authorization:$e()}),delegationCid:$e(),spaceId:$e(),verificationMethod:$e(),jwk:je({}).passthrough()});var pr="urn:tinycloud:encryption:",yr=/^[a-z0-9][a-z0-9-]*$/,fr=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,mr=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function gr(e){if("string"!=typeof e||0===e.length)throw new mr("networkId must be a non-empty string");if(!e.startsWith(pr))throw new mr(`networkId must start with ${pr} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new mr(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const s=t.slice(0,r),n=t.slice(r+1);if(!s.startsWith("did:"))throw new mr(`networkId ownerDid must be a DID (got ${JSON.stringify(s)})`);const i=s.split(":");if(i.length<3||i.some(e=>0===e.length))throw new mr(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(s)})`);if(!yr.test(n))throw new mr(`networkId name ${JSON.stringify(n)} must match ${yr.source}`);return{networkId:e,ownerDid:s,name:n}}function vr(e){const t=e.lastIndexOf(":"),r=e.slice(t+1),s=r.indexOf("/"),n=-1===s?r:r.slice(0,s),i=gr(-1===s?e:`${e.slice(0,t+1)}${n}`);if(-1===s)return i;const a=r.slice(s+1),o=a.split("/"),c=a.endsWith("/");if(0===a.length||/[\u0000-\u001f\u007f\\]/.test(a)||o.some((e,t)=>"."===e||".."===e||0===e.length&&!(c&&t===o.length-1)))throw new mr(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...i,keyPath:a}}function _r(e){const t=e.match(fr);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function kr(e,t){const r=_r(e),s=_r(t);return r&&s?r.chainId===s.chainId&&r.address===s.address:e===t}Error,Error,Error,Error;var Er={NODE_NOT_RESPONDING:!0,PARTIAL_NODE_WRITE:!0,NODE_IDENTITY_MISMATCH:!0,RESOURCE_NOT_ROUTED:!0,DECRYPTION_DEPENDENCY_UNAVAILABLE:!0,registry_unavailable:!0,node_not_found:!0,node_registry_entry_exists:!0};function br(e){if("object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"string"==typeof e.code&&"string"==typeof e.message&&(t=e.code,Object.prototype.hasOwnProperty.call(Er,t))){const t="meta"in e?e.meta:void 0;let r="object"!=typeof t||null===t||Array.isArray(t)?void 0:t;return"NODE_NOT_RESPONDING"===e.code&&"hosts"in e&&Array.isArray(e.hosts)?r={...r,hosts:e.hosts}:"PARTIAL_NODE_WRITE"===e.code&&"succeeded"in e&&Array.isArray(e.succeeded)&&"failed"in e&&Array.isArray(e.failed)&&(r={...r,succeeded:e.succeeded,failed:e.failed}),{code:e.code,message:e.message,...e instanceof Error?{cause:e}:{},...r?{meta:r}:{}}}var t}function Tr(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t=e;if(Object.keys(t).sort().some(e=>!["actions","path","service","space"].includes(e)))return;if("tinycloud.kv"!==t.service&&"tinycloud.encryption"!==t.service)return;if("string"!=typeof t.path||0===t.path.length||t.path.includes("*"))return;if("tinycloud.kv"===t.service&&("string"!=typeof t.space||0===t.space.length||!t.path.startsWith("vault/")||t.path.endsWith("/")))return;if("tinycloud.encryption"===t.service&&(void 0!==t.space||!t.path.startsWith("urn:tinycloud:encryption:")||t.path.endsWith(":")))return;if(!Array.isArray(t.actions)||1!==t.actions.length||"string"!=typeof t.actions[0]||t.actions[0].includes("*"))return;const r="tinycloud.kv"===t.service?"tinycloud.kv/get":"tinycloud.encryption/decrypt";if(t.actions[0]!==r)return;const s="string"==typeof t.space?t.space:void 0;return{service:t.service,...void 0===s?{}:{space:s},path:t.path,actions:[t.actions[0]]}}function wr(e){return{code:Ut.AUTH_REQUIRED,message:"Authentication required. Please sign in first.",service:e}}function Nr(e,t,r,s){const n=s.trim(),[,i,a]=/^([a-z_]+)(?::\s*([a-z_]+):)?/.exec(n)??[];let o;if(503!==r.status||"sql_busy"!==i&&"unavailable_retryable"!==i&&"read_audit_busy"!==i)if(503===r.status&&"request_timeout"===i)o=Ut.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==i)return;o=Ut.OUTCOME_UNKNOWN}else o=Ut.NODE_BUSY;const c=o!==Ut.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return Vt(o,t,e,{meta:{...lr(r.status,r.statusText,s),retryable:c,..."sql_busy"===i&&a?{stage:a}:{},...c&&u&&/^\d{1,9}$/.test(u)?{retryAfterMs:1e3*Number(u)}:{}}})}var Or=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function Rr(e){return e instanceof Or||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function Ar(e,t,r){return void 0===t?{code:Ut.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:Ut.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function Ir(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var Sr=new Set(at.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),xr=new Set(at.map(({service:e})=>e.slice(10)));function Dr(e,t,r){if("string"!=typeof e||0===e.length||e.length>1024)return!1;if("encryption"===t&&e.startsWith("urn:tinycloud:encryption:")){if(!/^[A-Za-z0-9_][A-Za-z0-9_.:/-]*$/.test(e)||e.includes("//")||e.split("/").some(e=>"."===e||".."===e))return!1;try{return gr(e),!0}catch{return!1}}const s=function(e,t){if(0===e.length||e.length>1024||!xr.has(t)||/[\s\p{C}*#]/u.test(e)||e.includes("://"))return;const r=e.split("/");if(!/^tinycloud:[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(r[0]))return;const s=r.findIndex((e,t)=>t>0&&xr.has(e));if(s<1||r[s]!==t)return;if(r.slice(1,s).some(e=>0===e.length||"."===e||".."===e))return;const n=r.slice(s+1);return n.some(e=>"."===e||".."===e)||"kv"!==t&&(0===n.length||""===n[n.length-1])?void 0:{space:r.slice(0,s).join("/"),path:n.join("/")}}(e,t);return void 0!==s&&(!s.path.endsWith("/")||"kv"===t&&"tinycloud.kv/list"===r)&&(""!==s.path||"kv"===t&&"tinycloud.kv/list"===r)}function Pr(e){const t=Lr(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let s=e;for(let e=0;e<Cr&&"object"==typeof s&&null!==s&&!r.has(s);e+=1){r.add(s);const e=s,t=Ur(e),n=e.meta;if((401===t||403===t||void 0===t&&e.code===Ut.AUTH_UNAUTHORIZED)&&"object"==typeof n&&null!==n&&!Array.isArray(n)){const t=n,{resource:r,requiredAction:s}=t;if("string"==typeof s&&Sr.has(s)){const n=s.slice(10,s.indexOf("/")),i=void 0===e.service?t.service:e.service;if(Dr(r,n,s)&&(void 0===i||i===n||i===`tinycloud.${n}`))return{resource:r,requiredAction:s}}}s=e.cause}}var Cr=8;function Ur(e){const t=e.meta,r=[e.status,e.statusCode,"object"==typeof t&&null!==t?t.status:void 0];for(const e of r)if("number"==typeof e&&Number.isInteger(e)&&e>=400&&e<=599)return e}function Lr(e){const t=new Set;let r=!1,s=e;for(let e=0;e<Cr&&"object"==typeof s&&null!==s&&!t.has(s);e+=1){t.add(s);const e=s,n=Ur(e);if(401===n)return"unauthenticated";if(403===n)return"forbidden";if(void 0!==n)return"other";e.code===Ut.AUTH_UNAUTHORIZED&&(r=!0),s=e.cause}return r?"forbidden":void 0}function Kr(e){const t=e.match(/Used:\s*(\d+)\s*bytes,\s*Limit:\s*(\d+)\s*bytes/i);if(t)return{usedBytes:parseInt(t[1],10),limitBytes:parseInt(t[2],10)}}var $r={storage_quota_exceeded:!0,storage_limit_reached:!0};function Vr(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function qr(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return Vr(t)&&Vr(r)?{usedBytes:t,limitBytes:r}:void 0}function Mr(e){let t;try{t=JSON.parse(e)}catch{return Kr(e)}if("object"!=typeof t||null===t)return;const r=t,s="string"==typeof r.message?r.message:"",n=qr(r.space)??Kr(s),i="string"==typeof r.error&&!0===$r[r.error];if(!n&&!i)return;const a={...n},o=qr(r.account);if(o){const e=r.account.plan;a.account="string"==typeof e&&""!==e?{...o,plan:e}:o}return a}function Fr(e,t,r,s){const n={...r,...Mr(s)};return 402===t?function(e,t,r){return{code:Ut.STORAGE_QUOTA_EXCEEDED,message:"TinyCloud storage is full, so this change was not saved. Reading still works. Free up space or upgrade your plan to save again.",service:e,meta:r}}(e,0,n):function(e,t,r){return{code:Ut.STORAGE_LIMIT_REACHED,message:"This change is larger than the TinyCloud storage you have left, so it was not saved. Reading still works. Free up space or upgrade your plan to save it.",service:e,meta:r}}(e,0,n)}function jr(e,t,r=Ut.NETWORK_ERROR){const s=br(t);return s?{...s,service:e}:t instanceof Error?Rr(t)?Ar(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:Ut.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?Ar(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var Hr=class{constructor(){this.abortController=new AbortController,this._config={}}get config(){return this._config}initialize(e){this.context=e}onSessionChange(e){}onSignOut(){this.abortController.abort(),this.abortController=new AbortController}get abortSignal(){return this.combineSignals()}get isAuthenticated(){return this.context?.isAuthenticated??!1}get session(){if(!this.context?.session)throw new Error("Not authenticated");return this.context.session}requireAuth(){return this.isAuthenticated}emit(e,t){this.context?.emit(e,t)}emitRequest(e,t){const r=this.getServiceName();this.emit("service.request",{service:r,action:e,span:this.spanName(e),key:t,timestamp:Date.now()})}emitResponse(e,t,r,s){const n=this.getServiceName(),i=Date.now()-r,a=this.spanName(e);this.emit("service.response",{service:n,action:e,span:a,ok:t,duration:i,durationMs:i,status:s}),this.emit(Lt,{span:a,service:n,action:e,ok:t,durationMs:i,status:s})}emitError(e,t){const r=t?this.spanName(t):void 0;this.emit("service.error",{service:this.getServiceName(),...r?{span:r}:{},error:e})}getServiceName(){return this.constructor.serviceName}spanName(e){return`sdk.${this.getServiceName()}.${e}`}combineSignals(...e){const t=new AbortController,r=[this.abortController.signal,this.context?.abortSignal,...e.filter(Boolean)].filter(Boolean);for(const e of r){if(e.aborted)return t.abort(e.reason),t.signal;e.addEventListener("abort",()=>t.abort(e.reason),{once:!0})}return t.signal}invokeWithRetry(e,t,{headers:r,...s}={}){const n=()=>{const e=t();return{method:"POST",...s,headers:Array.isArray(e)?[...e,...Object.entries(r??{})]:{...e,...r}}};return this.context.invokeWithRetry?this.context.invokeWithRetry(e,n):this.context.fetch(e,n())}createRequestSignal(e,t){const r=new AbortController,s=[];let n;const i=()=>{void 0!==n&&(clearTimeout(n),n=void 0);for(const e of s.splice(0))e()},a=e=>{i(),r.abort(e)},o={signal:r.signal,dispose:i},c=[this.abortController.signal,this.context?.abortSignal,this.context?.operationAbortSignal,e].filter(e=>void 0!==e);for(const e of c){if(e.aborted)return a(e.reason),o;const t=()=>a(e.reason);e.addEventListener("abort",t,{once:!0}),s.push(()=>e.removeEventListener("abort",t))}const u=t??this._config.timeout;return"number"==typeof u&&u>0&&u<=2147483647&&(n=setTimeout(()=>a(new Or(u)),u)),o}async withTelemetry(e,t,r){const s=Date.now();this.emitRequest(e,t);try{const t=await r();return t.ok?this.emitResponse(e,!0,s):(this.emitResponse(e,!1,s),this.emitError(t.error,e)),t}catch(t){const r=jr(this.getServiceName(),t);return this.emitResponse(e,!1,s),this.emitError(r,e),$t(r)}}},Br=class e{constructor(e,t){this._kv=e,this._prefix=t.endsWith("/")?t.slice(0,-1):t}get prefix(){return this._prefix}getFullKey(e){const t=e.startsWith("/")?e:`/${e}`;return`${this._prefix}${t}`}async get(e,t){const r=this.getFullKey(e);return this._kv.get(r,{...t,prefix:""})}async batchGet(e,t){const r=await this._kv.batchGet(e.map(e=>this.getFullKey(e)),{...t,prefix:""});return r.ok?Kt({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async put(e,t,r){const s=this.getFullKey(e);return this._kv.put(s,t,{...r,prefix:""})}async batchPut(e,t){return this._kv.batchPut(e.map(e=>({...e,key:this.getFullKey(e.key)})),{...t,prefix:""})}async list(e){const t=e?.removePrefix??!0;return this._kv.list({...e,prefix:this._prefix,removePrefix:t})}async changes(e){if(""===this._prefix.replace(/\/+$/,""))return $t(Vt(Ut.INVALID_INPUT,"KV changes needs a non-empty prefix; this view has none","kv"));const t=`${this._prefix}/`,r=await this._kv.changes({...e,prefix:t});return r.ok?Kt({...r.data,changes:r.data.changes.map(e=>({...e,key:e.key.startsWith(t)?e.key.slice(t.length):e.key}))}):r}async delete(e,t){const r=this.getFullKey(e);return this._kv.delete(r,{...t,prefix:""})}async head(e,t){const r=this.getFullKey(e);return this._kv.head(r,{...t,prefix:""})}async batchHead(e,t){const r=await this._kv.batchHead(e.map(e=>this.getFullKey(e)),{...t,prefix:""});return r.ok?Kt({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async createSignedReadUrl(e,t){const r=this.getFullKey(e);return this._kv.createSignedReadUrl(r,{...t,prefix:""})}withPrefix(t){const r=t.startsWith("/")?t:`/${t}`,s=`${this._prefix}${r}`;return new e(this._kv,s)}},Zr="tinycloud.kv/get",Wr="tinycloud.kv/put",Gr="tinycloud.kv/list",zr="tinycloud.kv/del",Jr="tinycloud.kv/metadata",Qr="tinycloud.kv/sync";function Yr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Xr=new TextEncoder,es=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/;function ts(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function rs(e,t,r,s){if(413!==r)return;const n=s.split(":",1)[0].trim();let i;return i=n===`${e}_request_too_large`||n!==`${e}_response_too_large`&&["batch","executeStatement","import"].includes(t),i?`${e.toUpperCase()}_REQUEST_TOO_LARGE`:void 0}(class extends Hr{constructor(e={}){super(),this.readThrough=null,this.readThroughReady=null,this._config=e}setReadThroughReady(e){const t=e.then(()=>{},()=>{});this.readThroughReady=t,t.then(()=>{this.readThroughReady===t&&(this.readThroughReady=null)})}get config(){return this._config}setReadThrough(e){this.readThrough=e}handleQuotaErrorResponse(e,t,r){if((402===e.status||413===e.status)&&(413!==e.status||Mr(t)))return $t(Fr("kv",e.status,{status:e.status,statusText:e.statusText,key:r},t))}async classifyNotFound(e,t){const r=await e.text();return/space not found/i.test(r)?$t(Vt(Ut.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):$t(Vt(Ut.KV_NOT_FOUND,`Key not found: ${t}`,"kv"))}getFullPath(e,t){const r=t??this._config.prefix??"";return r?""===e?r:`${r}/${e}`:e}get host(){return this.context.hosts[0]}async invokeOperation(e,t,r,s,n){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"kv",e,t),{headers:n,body:r,signal:s})}serializePutValue(e,t){if(e instanceof Blob)return t&&e.type!==t?new Blob([e],{type:t}):e;if(e instanceof ArrayBuffer)return new Blob([e],{type:t??"application/octet-stream"});if(ArrayBuffer.isView(e)){const r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return new Blob([r],{type:t??"application/octet-stream"})}return"string"==typeof e?t?new Blob([e],{type:t}):e:JSON.stringify(e)}serializeBatchPutValue(e){const t=e.contentType;if(e.value instanceof Blob)return t&&e.value.type!==t?new Blob([e.value],{type:t}):e.value;if(e.value instanceof ArrayBuffer)return new Blob([e.value],{type:t??"application/octet-stream"});if(ArrayBuffer.isView(e.value)){const r=e.value,s=new Uint8Array(r.byteLength);return s.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),new Blob([s],{type:t??"application/octet-stream"})}if("string"==typeof e.value)return new Blob([e.value],{type:t??"text/plain;charset=UTF-8"});const r=JSON.stringify(e.value);if(void 0===r)throw new Error(`Cannot JSON serialize KV batch value for key "${e.key}"`);return new Blob([r],{type:t??"application/json"})}normalizeBatchPutResponse(e){if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.written)&&t.written.every(e=>"string"==typeof e)&&"number"==typeof t.count?{written:t.written,count:t.count}:void 0}createResponseHeaders(e){return{etag:e.get("etag")??void 0,contentType:e.get("content-type")??void 0,lastModified:e.get("last-modified")??void 0,contentLength:e.get("content-length")?parseInt(e.get("content-length"),10):void 0,get:t=>e.get(t)}}createBatchResponseHeaders(e){const t=new Map(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t]));return this.createResponseHeaders({get:e=>t.get(e.toLowerCase())??null})}parseBatchValue(e,t,r=!1,s=!1){const n=globalThis.atob(e),i=Uint8Array.from(n,e=>e.charCodeAt(0));if(s)return i;const a=(new TextDecoder).decode(i);if(r)return a;const o=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase())?.[1];return o?.includes("application/json")?JSON.parse(a):a}normalizeBatchReadResponse(e,t,r){if(!e||"object"!=typeof e)return;const s=e.results;if(!Array.isArray(s)||s.length!==t.length)return;for(const e of s){if(!e||"object"!=typeof e||"boolean"!=typeof e.ok)return;if(e.ok&&(!e.headers||"object"!=typeof e.headers||Object.values(e.headers).some(e=>"string"!=typeof e)||r&&"string"!=typeof e.dataBase64))return;if(!(e.ok||e.error&&"string"==typeof e.error.code&&"string"==typeof e.error.message))return}if(s.every(e=>"string"==typeof e.key)){const e=new Map(s.map(e=>[e.key,e]));if(e.size!==s.length)return;const r=[];for(const s of t){const t=e.get(s);if(!t)return;r.push(t)}return r}if(s.some(e=>void 0!==e.key))return;const n=t.map((e,t)=>t).sort((e,r)=>function(e,t){const r=Xr.encode(e),s=Xr.encode(t),n=Math.min(r.length,s.length);for(let e=0;e<n;e++)if(r[e]!==s[e])return r[e]-s[e];return r.length-s.length}(t[e],t[r])),i=new Array(s.length);for(let e=0;e<n.length;e++)i[n[e]]=s[e];return i}async batchRead(e,t,r){if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return $t(wr("kv"));if(0===e.length)return Kt({results:[],count:0});if(e.length>100)return $t(Vt(Ut.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const s=e[0];return Kt({results:[{key:s,result:t===Zr?await this.get(s,r):await this.head(s,r)}],count:1})}if(!this.context.invokeAny)return $t(Vt(Ut.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const s=t===Zr?r:void 0;if(void 0!==s?.maxResponseBytes&&(!Number.isSafeInteger(s.maxResponseBytes)||s.maxResponseBytes<=0))return $t(Vt(Ut.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const n=e.map(e=>this.getFullPath(e,r?.prefix));if(new Set(n).size!==n.length)return $t(Vt(Ut.INVALID_INPUT,"KV batch read received duplicate keys after prefix resolution","kv"));const i=this.createRequestSignal(r?.signal,r?.timeout);try{const r={};void 0!==s?.maxResponseBytes&&(r["x-tinycloud-max-response-bytes"]=String(s.maxResponseBytes));const a=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.session;return this.context.invokeAny(e,n.map(r=>({spaceId:e.spaceId,service:"kv",path:r,action:t})))},{headers:r,signal:i.signal});if(!a.ok){const r=401===a.status||403===a.status?await this.readAuthorizationText(a):await a.text();return 401===a.status||403===a.status?this.authorizationFailure(`Failed to batch read ${e.length} key(s)`,a,r,n,t):413===a.status?$t(Vt(Ut.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:a.status,statusText:a.statusText}})):$t(Vt(Ut.NETWORK_ERROR,`Failed to batch read ${e.length} key(s): ${a.status} - ${r}`,"kv",{meta:{status:a.status,statusText:a.statusText}}))}const o=this.normalizeBatchReadResponse(await a.json(),n,t===Zr);if(!o)return $t(Vt(Ut.NETWORK_ERROR,"KV batch read response did not match the requested keys","kv"));const c=o.map((r,n)=>{if(!r.ok)return{key:e[n],result:$t(Vt(r.error.code,r.error.message,"kv"))};const i=r.headers,a=t===Jr?void 0:this.parseBatchValue(r.dataBase64,i,s?.raw,s?.binary);return{key:e[n],result:Kt({data:a,headers:this.createBatchResponseHeaders(i)})}});return Kt({results:c,count:c.length})}catch(e){return $t(jr("kv",e))}finally{i.dispose()}}async parseResponse(e,t=!1,r=!1){if(!e.ok)return;if(r)return new Uint8Array(await e.arrayBuffer());if(t)return await e.text();const s=e.headers.get("content-type");if(s?.includes("application/json"))return await e.json();if(s?.startsWith("text/"))return await e.text();const n=await e.text();if(n)try{return JSON.parse(n)}catch{return n}}async createSignedReadUrlError(e,t,r){let s=e.statusText;try{const t=await e.text();t&&(s=t)}catch{}return 401===e.status||403===e.status?this.authorizationFailure(`Failed to create signed read URL for key ${JSON.stringify(t)}`,e,s,[r],Zr):$t(Vt(400===e.status?Ut.INVALID_INPUT:Ut.NETWORK_ERROR,`Failed to create signed read URL for key ${JSON.stringify(t)}: ${e.status} - ${s}`,"kv",{meta:{status:e.status,statusText:e.statusText}}))}async readAuthorizationText(e){try{return await e.text()}catch{return""}}authorizationFailure(e,t,r,s,n,i={}){const{resource:a,action:o}=Ir(r),c=s.find(e=>a===e||a===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&o===n?Pr({service:"kv",code:Ut.AUTH_UNAUTHORIZED,meta:{status:t.status,resource:`${this.context.session.spaceId}/kv/${c}`,requiredAction:o}}):void 0,d=r.trim().length>0?r:t.statusText||"authorization failed";return $t((l=`${e}: ${t.status} - ${d}`,h={status:t.status,...i,...u},Vt(Ut.AUTH_UNAUTHORIZED,l,"kv",{meta:h})));var l,h}normalizeSignedReadUrlResponse(e){if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.url&&"string"==typeof t.ticketId&&"string"==typeof t.expiresAt?{url:new URL(t.url,this.host).toString(),relativeUrl:t.url,ticketId:t.ticketId,expiresAt:t.expiresAt}:void 0}async get(e,t){return this.withTelemetry("get",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return $t(wr("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return $t(Vt(Ut.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const r=this.getFullPath(e,t?.prefix),s=this.createRequestSignal(t?.signal,t?.timeout);try{const n=()=>this.getFromNetwork(e,r,t,s.signal);if("network"===t?.source){const e=this.readThrough;if(null===e)return await n();let t="error";const s=Date.now();try{const e=await n();return t=e.ok?"found":e.error.code===Ut.KV_NOT_FOUND?"not_found":"error",e}finally{try{e.observeNetworkRequested({op:"get",space:this.context.session.spaceId,path:r,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:Date.now()-s})}catch{}}}return null===this.readThrough?await n():await this.readThrough.get({space:this.context.session.spaceId,key:e,path:r,options:t,signal:s.signal,network:n})}catch(e){return $t(jr("kv",e))}finally{s.dispose()}})}async getFromNetwork(e,t,r,s){const n=await this.invokeOperation(t,Zr,void 0,s,void 0===r?.maxResponseBytes?void 0:{"x-tinycloud-max-response-bytes":String(r.maxResponseBytes)});if(!n.ok){if(401===n.status||403===n.status){const r=await this.readAuthorizationText(n),s=function(e){try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return;const r=t,s=r.error,n="object"==typeof s&&null!==s?s:void 0;return Tr(r.permissionHint)??Tr(n?.permissionHint)}catch{return}}(r),i="tinycloud.kv"===s?.service&&s.space===this.context.session.spaceId&&s.path===t?Pr({service:"kv",code:Ut.AUTH_UNAUTHORIZED,meta:{status:n.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:Zr}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,n,r,[t],Zr,i?{permissionHint:s,...i}:{})}if(404===n.status)return this.classifyNotFound(n,e);const r=await n.text();if(413===n.status)return $t(Vt(Ut.KV_RESPONSE_TOO_LARGE,`KV value at key ${JSON.stringify(e)} exceeds the requested response limit`,"kv",{meta:{status:n.status,statusText:n.statusText}}));const s=`Failed to get key ${JSON.stringify(e)}: ${n.status} - ${r}`,i=Nr("kv",s,n,r);return $t(i||Vt(Ut.NETWORK_ERROR,s,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return Kt({data:await this.parseResponse(n,r?.raw,r?.binary),headers:this.createResponseHeaders(n.headers),...n.retry&&{retry:n.retry}})}async batchGet(e,t){return this.withTelemetry("batchGet",String(e.length),()=>this.batchRead(e,Zr,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return $t(wr("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return $t(Vt(Ut.INVALID_INPUT,"KV put cannot combine ifMatch and ifNoneMatch","kv"));const s=this.getFullPath(e,r?.prefix),n=this.serializePutValue(t,r?.contentType),i=this.createRequestSignal(r?.signal,r?.timeout);try{const t=()=>this.putToNetwork(e,s,n,r,i.signal);return null===this.readThrough?await t():await this.readThrough.write({op:"put",space:this.context.session.spaceId,entries:[{path:s,body:n}],signal:i.signal,conditional:void 0!==r?.ifMatch||void 0!==r?.ifNoneMatch,network:t})}catch(e){return $t(jr("kv",e))}finally{i.dispose()}})}async putToNetwork(e,t,r,s,n){const i=await this.invokeOperation(t,Wr,r,n,{...void 0===s?.ifMatch?{}:{"if-match":s.ifMatch},...void 0===s?.ifNoneMatch?{}:{"if-none-match":s.ifNoneMatch}});if(401===i.status||403===i.status)return this.authorizationFailure(`Failed to put key ${JSON.stringify(e)}`,i,await this.readAuthorizationText(i),[t],Wr);if(!i.ok){const t=await i.text();if(412===i.status)return $t(Vt(Ut.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:i.status,statusText:i.statusText}}));const r=`Failed to put key ${JSON.stringify(e)}: ${i.status} - ${t}`,s=Nr("kv",r,i,t);if(s)return $t(s);return this.handleQuotaErrorResponse(i,t,e)||$t(Vt(Ut.KV_WRITE_FAILED,r,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return Kt({data:void 0,headers:this.createResponseHeaders(i.headers),...i.retry&&{retry:i.retry}})}async batchPut(e,t){return this.withTelemetry("batchPut",String(e.length),async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return $t(wr("kv"));if(0===e.length)return Kt({written:[],count:0});if(!this.context.invokeAny)return $t(Vt(Ut.INVALID_INPUT,"KV batchPut requires SDK runtime support for multi-resource invocations","kv"));const r=this.context.session,s=e.map(e=>this.getFullPath(e.key,t?.prefix)),n=new Set;for(const e of s){if(n.has(e))return $t(Vt(Ut.INVALID_INPUT,`KV batchPut received duplicate key after prefix resolution: ${e}`,"kv"));n.add(e)}const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=()=>this.batchPutToNetwork(e,s,i.signal);if(null===this.readThrough)return await t();const n=e.map((e,t)=>({path:s[t],body:this.serializeBatchPutValue(e)}));return await this.readThrough.write({op:"batchPut",space:r.spaceId,entries:n,signal:i.signal,network:()=>this.batchPutToNetwork(e,s,i.signal,n)})}catch(e){const t=jr("kv",e);return $t({...t,meta:{...t.meta,requestMayHaveDispatched:!1}})}finally{i.dispose()}})}async batchPutToNetwork(e,t,r,s){const n=this.context.session;let i=!1;try{const a=new FormData;for(let r=0;r<e.length;r++)a.append(ts(t[r]),s?.[r]?.body??this.serializeBatchPutValue(e[r]));const o=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.invokeAny(n,t.map(e=>({spaceId:n.spaceId,service:"kv",path:e,action:Wr})));return i=!0,e},{body:a,signal:r});if(!o.ok){let r;try{r=await o.text()}catch(t){const r=t instanceof Error?t:new Error(String(t));return $t(Vt(Ut.KV_WRITE_FAILED,`Failed to batch put ${e.length} key(s): ${o.status} - <response body could not be read: ${r.message}>`,"kv",{cause:r,meta:{status:o.status,statusText:o.statusText}}))}if(401===o.status||403===o.status)return this.authorizationFailure(`Failed to batch put ${e.length} key(s)`,o,r,t,Wr);return this.handleQuotaErrorResponse(o,r,"batch")||$t(Vt(Ut.KV_WRITE_FAILED,`Failed to batch put ${e.length} key(s): ${o.status} - ${r}`,"kv",{meta:{status:o.status,statusText:o.statusText}}))}let c;try{c=await o.json()}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=Rr(t);return $t(Vt(r?Ut.TIMEOUT:Ut.NETWORK_ERROR,r?`KV batchPut response body did not arrive in time: ${t.message}`:`KV batchPut response was not valid JSON: ${t.message}`,"kv",{cause:t,meta:{...r?{timeoutMs:t.timeoutMs}:{},requestMayHaveDispatched:!0,responseReceived:!0,status:o.status,outcome:"batch-unconfirmed"}}))}const u=this.normalizeBatchPutResponse(c);if(!u)return $t(Vt(Ut.NETWORK_ERROR,"KV batchPut response did not include matching written keys and count","kv",{meta:{requestMayHaveDispatched:!0,responseReceived:!0,status:o.status,outcome:"batch-unconfirmed"}}));const d=new Set(t),l=new Set(u.written);return u.count===t.length&&u.written.length===t.length&&l.size===t.length&&u.written.every(e=>d.has(e))?Kt(u):$t(Vt(Ut.NETWORK_ERROR,`KV batchPut response did not confirm all ${t.length} requested key(s) were written`,"kv",{meta:{requestMayHaveDispatched:!0,responseReceived:!0,status:o.status,outcome:"batch-unconfirmed"}}))}catch(e){const t=jr("kv",e);return $t({...t,meta:{...t.meta,requestMayHaveDispatched:i}})}}async list(e){return this.withTelemetry("list",e?.prefix,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return $t(wr("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return $t(Vt(Ut.INVALID_INPUT,"KV list limit must be an integer from 1 through 1000","kv"));let t=e?.prefix??this._config.prefix??"";e?.path&&(t=t?`${t}/${e.path}`:e.path);const r=this.createRequestSignal(e?.signal,e?.timeout);try{const s=()=>this.listFromNetwork(t,e,r.signal);let n;if("network"===e?.source){const e=this.readThrough;if(null===e)n=await s();else{let r="error";const i=Date.now();try{n=await s(),r=n.ok?"found":"error"}finally{try{e.observeNetworkRequested({op:"list",space:this.context.session.spaceId,path:t,reason:"NETWORK_REQUESTED",outcome:r,latencyMs:Date.now()-i})}catch{}}}}else n=null===this.readThrough?await s():await this.readThrough.list({space:this.context.session.spaceId,listPath:t,options:e,signal:r.signal,network:s});return n.ok?this.finishList(n.data,t,e?.removePrefix):n}catch(e){return $t(jr("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const s=await this.invokeOperation(e,Gr,void 0,r,void 0===t?.limit&&void 0===t?.cursor?void 0:{...void 0===t?.limit?{}:{"x-tinycloud-limit":String(t.limit)},...void 0===t?.cursor?{}:{"x-tinycloud-cursor":t.cursor}});if(!s.ok){if(401===s.status||403===s.status)return this.authorizationFailure("Failed to list keys",s,await this.readAuthorizationText(s),[e],Gr);const t=await s.text(),r=`Failed to list keys: ${s.status} - ${t}`,n=Nr("kv",r,s,t);return $t(n||Vt(Ut.NETWORK_ERROR,r,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return Kt({keys:await this.parseResponse(s,t?.raw)??[],...null===s.headers.get("x-tinycloud-truncated")?{}:{truncated:"true"===s.headers.get("x-tinycloud-truncated")},...null===s.headers.get("x-tinycloud-next-cursor")?{}:{nextCursor:s.headers.get("x-tinycloud-next-cursor")??void 0}})}finishList(e,t,r){let s=e.keys;if(r&&t){const e=t.endsWith("/")?t:`${t}/`;s=s.map(t=>t.startsWith(e)?t.slice(e.length):t)}return Kt({keys:s,...void 0===e.truncated?{}:{truncated:e.truncated},...void 0===e.nextCursor?{}:{nextCursor:e.nextCursor}})}async changes(e){return this.withTelemetry("changes",e?.prefix,async()=>{if(!this.requireAuth())return $t(wr("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return $t(Vt(Ut.INVALID_INPUT,"KV changes prefix must be a non-empty string","kv"));if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return $t(Vt(Ut.INVALID_INPUT,"KV changes limit must be an integer from 1 through 1000","kv"));const t="/"===e.prefix?"":e.prefix,r={};void 0!==e.limit&&(r["x-tinycloud-limit"]=String(e.limit)),void 0!==e.cursor&&(r["x-tinycloud-cursor"]=e.cursor),void 0!==e.retentionGrant&&(r["x-tinycloud-retention-grant"]=e.retentionGrant);const s=this.createRequestSignal(e.signal,e.timeout);try{const n=await this.invokeOperation(t,Qr,void 0,s.signal,r);if(!n.ok)return await this.changesFailure(n,e.prefix,s.signal);const i=await n.text();let a;try{a=JSON.parse(i)}catch{a=void 0}const o=this.normalizeChangesResponse(a,e.prefix);return o?Kt(o):$t(Vt(Ut.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:n.status,statusText:n.statusText}}))}catch(e){return $t(jr("kv",e))}finally{s.dispose()}})}async changesFailure(e,t,r){if(404===e.status)return this.classifyNotFound(e,t);let s;try{s=await e.text()}catch(e){if(r.aborted)throw e;s=""}const n={status:e.status,statusText:e.statusText};let i,a;try{const e=JSON.parse(s),t=Yr(e)?e.error:void 0;Yr(t)&&("string"==typeof t.code&&(a=t.code),"string"==typeof t.reason&&(i=t.reason))}catch{}const o=`Failed to read KV changes for ${JSON.stringify(t)}`;if(410===e.status)return $t(Vt(Ut.KV_SYNC_RESET_REQUIRED,`${o}: the node requires a reset (${i??"reason not given"}); discard sync state and restart without a cursor`,"kv",{meta:{...n,reason:i}}));if(403===e.status&&"RETENTION_GRANT_REFUSED"===a)return $t(Vt(Ut.KV_RETENTION_GRANT_REFUSED,`${o}: the retention grant was refused (${i??"reason not given"})`,"kv",{meta:{...n,reason:i}}));if(401===e.status){const e=function(e){const t=es.exec(e.trim());if(null!==t)return void 0!==t[1]?Ut.AUTH_DELEGATION_REVOKED:Ut.AUTH_DELEGATION_ANCESTOR_REVOKED}(s);if(void 0!==e)return $t(Vt(e,`${o}: 401 - ${s}`,"kv",{meta:n}))}return 401===e.status||403===e.status?this.authorizationFailure(o,e,s,[t],Qr):$t(Vt(400===e.status?Ut.INVALID_INPUT:Ut.NETWORK_ERROR,`${o}: ${e.status} - ${s}`,"kv",{meta:n}))}normalizeChangesResponse(e,t){if(!Yr(e))return;const{changes:r,more:s,cursor:n,source:i,authority:a}=e;if(!Array.isArray(r)||"boolean"!=typeof s||"string"!=typeof n||!Yr(i)||"string"!=typeof i.nodeDid||"string"!=typeof i.space||"string"!=typeof i.prefix||!Yr(a))return;const{notBefore:o,expiresAt:c,retainUntil:u}=a;if(null!==o&&"string"!=typeof o||null!==c&&"string"!=typeof c||null!==u&&"string"!=typeof u)return;const d=[];for(const e of r){if(!Yr(e)||"string"!=typeof e.key)return;if(!0===e.deleted){d.push({key:e.key,deleted:!0});continue}const{metadata:t}=e;if(!1!==e.deleted||"string"!=typeof e.etag||!Yr(t)||!Object.values(t).every(e=>"string"==typeof e))return;d.push({key:e.key,deleted:!1,etag:e.etag,metadata:t})}return{changes:d,more:s,cursor:n,source:{nodeDid:i.nodeDid,space:i.space,prefix:"/"===t&&""===i.prefix?"/":i.prefix},authority:{notBefore:o,expiresAt:c,retainUntil:u}}}async delete(e,t){return this.withTelemetry("delete",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady,!this.requireAuth())return $t(wr("kv"));const r=this.getFullPath(e,t?.prefix),s=this.createRequestSignal(t?.signal,t?.timeout);try{const n=()=>this.deleteFromNetwork(e,r,t,s.signal);return null===this.readThrough?await n():await this.readThrough.write({op:"delete",space:this.context.session.spaceId,entries:[{path:r}],signal:s.signal,conditional:void 0!==t?.ifMatch,network:n})}catch(e){return $t(jr("kv",e))}finally{s.dispose()}})}async deleteFromNetwork(e,t,r,s){const n=await this.invokeOperation(t,zr,void 0,s,void 0===r?.ifMatch?void 0:{"if-match":r.ifMatch});if(!n.ok){if(401===n.status||403===n.status)return this.authorizationFailure(`Failed to delete key ${JSON.stringify(e)}`,n,await this.readAuthorizationText(n),[t],zr);if(404===n.status)return this.classifyNotFound(n,e);const r=await n.text();if(412===n.status)return $t(Vt(Ut.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:n.status,statusText:n.statusText}}));const s=`Failed to delete key ${JSON.stringify(e)}: ${n.status} - ${r}`,i=Nr("kv",s,n,r);return $t(i||Vt(Ut.NETWORK_ERROR,s,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return Kt({data:void 0,headers:this.createResponseHeaders(n.headers),...n.retry&&{retry:n.retry}})}async head(e,t){return this.withTelemetry("head",e,async()=>{if(!this.requireAuth())return $t(wr("kv"));const r=this.getFullPath(e,t?.prefix),s=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,Jr,void 0,s.signal);if(!t.ok){if(401===t.status||403===t.status)return this.authorizationFailure(`Failed to get metadata for key ${JSON.stringify(e)}`,t,await this.readAuthorizationText(t),[r],Jr);if(404===t.status)return await this.classifyNotFound(t,e);const s=await t.text(),n=`Failed to get metadata for key ${JSON.stringify(e)}: ${t.status} - ${s}`,i=Nr("kv",n,t,s);return $t(i||Vt(Ut.NETWORK_ERROR,n,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return Kt({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return $t(jr("kv",e))}finally{s.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,Jr,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return $t(wr("kv"));const r=this.getFullPath(e,t?.prefix),s=this.context.session,n={space:s.spaceId,path:r,ttl_seconds:t?.expiresInSeconds??Math.ceil(300)};void 0!==t?.contentHash&&(n.content_hash=t.contentHash),void 0!==t?.etag&&(n.etag=t.etag);const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeWithRetry(`${this.host}/signed/kv`,()=>this.context.invoke(s,"kv",r,Zr),{headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:i.signal});if(!t.ok)return await this.createSignedReadUrlError(t,e,r);const a=this.normalizeSignedReadUrlResponse(await t.json());return a?Kt(a):$t(Vt(Ut.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return $t(jr("kv",e))}finally{i.dispose()}})}withPrefix(e){return new Br(this,e)}}).serviceName="kv";var ss=class{constructor(e,t){this.service=e,this.dbName=t}apply(e){return this.service.applyMigrationsOnDb(this.dbName,e)}},ns=class{constructor(e,t){this.service=e,this.name=t,this.migrations=new ss(e,t)}async query(e,t,r){return this.service.queryOnDb(this.name,e,t,r)}async execute(e,t,r){return this.service.executeOnDb(this.name,e,t,r)}async batch(e,t){return this.service.batchOnDb(this.name,e,t)}async executeStatement(e,t,r){return this.service.executeStatementOnDb(this.name,e,t,r)}async export(e){return this.service.exportDb(this.name,e)}},is={READ:tt.READ,WRITE:tt.WRITE,SCHEMA:tt.SCHEMA,ADMIN:tt.ADMIN,SELECT:tt.SELECT,EXECUTE:tt.EXECUTE,EXPORT:tt.EXPORT,ALL:tt.ALL},as=new Set(["alter","create","drop"]),os="__tinycloud_sql_migrations",cs=`CREATE TABLE IF NOT EXISTS ${os} (\n key TEXT PRIMARY KEY,\n namespace TEXT NOT NULL,\n id TEXT NOT NULL,\n applied_at TEXT NOT NULL,\n statement_count INTEGER NOT NULL\n)`,us="tinycloud.sql.migrations",ds="000_metadata";function ls(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function hs(e){return/no such table/i.test(e)}function ps(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function ys(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends Hr{constructor(e={}){super(),this.migrationLocks=new Map,this._config=e}get config(){return this._config}get defaultDbName(){return this._config.defaultDatabase??"default"}get host(){return this.context.hosts[0]}db(e){return new ns(this,e??this.defaultDbName)}async query(e,t,r){return this.queryOnDb(this.defaultDbName,e,t,r)}async execute(e,t,r){return this.executeOnDb(this.defaultDbName,e,t,r)}async batch(e,t){return this.batchOnDb(this.defaultDbName,e,t)}async applyMigrationsOnDb(e,t){const r=function(e){if(!e||"object"!=typeof e)return"SQL migrations require options";if(!e.namespace||"string"!=typeof e.namespace)return"SQL migrations require a non-empty namespace";if(!Array.isArray(e.migrations))return"SQL migrations require an ordered migrations array";const t=new Set;for(const r of e.migrations){if(!r.id||"string"!=typeof r.id)return"SQL migrations require every migration to have a non-empty id";if(t.has(r.id))return`Duplicate SQL migration id: ${r.id}`;if(t.add(r.id),!Array.isArray(r.sql))return`SQL migration ${r.id} requires a sql array`;for(const e of r.sql)if("string"!=typeof e){if(!e||"string"!=typeof e.sql||""===e.sql.trim())return`SQL migration ${r.id} contains an invalid statement`}else if(""===e.trim())return`SQL migration ${r.id} contains an empty statement`}return null}(t);if(r)return $t(Vt(Ut.INVALID_INPUT,r,"sql"));const s=`${e}\0${t.namespace}`,n=this.migrationLocks.get(s);if(n)return n;const i=this.applyMigrationsOnDbUnlocked(e,t);this.migrationLocks.set(s,i);try{return await i}finally{this.migrationLocks.delete(s)}}async queryOnDb(e,t,r,s){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return $t(wr("sql"));const n=this.createRequestSignal(s?.signal);try{const i={action:"query",sql:t,params:ls(r??[])};void 0!==s?.maxRows&&(i.maxRows=s.maxRows),void 0!==s?.maxBytes&&(i.maxBytes=s.maxBytes);const a=this.actionForSql(t,is.READ),o=await this.invokeSQL(e,a,i,n.signal);if(!o.ok){const t=await this.handleErrorResponse(o,"query",e,[a]);return this.redactFailure(t,s?.redactErrors,o.status)}return Kt(await o.json())}catch(e){return this.redactFailure($t(jr("sql",e)),s?.redactErrors)}finally{n.dispose()}})}async executeOnDb(e,t,r,s){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return $t(wr("sql"));const n=this.createRequestSignal(s?.signal);try{const i={action:"execute",sql:t,params:ls(r??[])};s?.schema&&(i.schema=s.schema);const a=[this.actionForSql(t,is.WRITE),...(s?.schema??[]).map(e=>this.actionForSql(e,is.SCHEMA))],o=this.dedupeActions(a),c=await this.invokeSQL(e,o,i,n.signal);if(!c.ok){const t=await this.handleErrorResponse(c,"execute",e,o);return this.redactFailure(t,s?.redactErrors,c.status)}return Kt(await c.json())}catch(e){return this.redactFailure($t(jr("sql",e)),s?.redactErrors)}finally{n.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return $t(wr("sql"));const s=this.createRequestSignal(r?.signal);try{const n=this.actionsForSqlBatch(t),i=await this.invokeSQL(e,n,{action:"batch",statements:t},s.signal);if(!i.ok){const t=await this.handleErrorResponse(i,"batch",e,n);return this.redactFailure(t,r?.redactErrors,i.status)}return Kt(await i.json())}catch(e){return this.redactFailure($t(jr("sql",e)),r?.redactErrors)}finally{s.dispose()}})}async executeStatementOnDb(e,t,r,s){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return $t(wr("sql"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeSQL(e,is.WRITE,{action:"execute_statement",name:t,params:r??[]},n.signal);return s.ok?Kt(await s.json()):await this.handleErrorResponse(s,"executeStatement",e,[is.WRITE])}catch(e){return $t(jr("sql",e))}finally{n.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return $t(wr("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,is.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[is.READ]);const s=t;return"function"==typeof s.blob?Kt(await s.blob()):Kt(await t.text())}catch(e){return $t(jr("sql",e))}finally{r.dispose()}})}async applyMigrationsOnDbUnlocked(e,t){return this.withTelemetry("migrations.apply",e,async()=>{const r=await this.queryOnDb(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${os}'`,[],{signal:t.signal});let s=r.ok?0===r.data.rows.length:r.error.code===Ut.SQL_DATABASE_NOT_FOUND||hs(r.error.message);if(!r.ok&&!s)return r;const n=new Set;if(!s){const r=await this.queryOnDb(e,`SELECT id FROM ${os} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(s=!r.ok&&(r.error.code===Ut.SQL_DATABASE_NOT_FOUND||hs(r.error.message)),!r.ok&&!s)return r;if(r.ok)for(const e of r.data.rows){const t=ys(e,0);"string"==typeof t&&n.add(t)}}const i=t.migrations.filter(e=>n.has(e.id)).map(e=>e.id),a=t.migrations.filter(e=>!n.has(e.id)),o=[];if(a.length>0&&s){const r=await this.ensureMigrationsTable(e,t.signal);if(!r.ok)return r}for(const r of a){const s=await this.applyOneMigration(e,t.namespace,r,t.signal);if(!s.ok)return s;o.push(r.id)}return Kt({database:e,namespace:t.namespace,status:o.length>0?"applied":"already_current",applied:o,skipped:i})})}async applyOneMigration(e,t,r,s){const n=[...r.sql.map(e=>"string"==typeof e?{sql:e}:e),{sql:`INSERT OR REPLACE INTO ${os} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[ps(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],i=await this.batchOnDb(e,n,{signal:s});return i.ok?Kt(void 0):i}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:cs},{sql:`INSERT OR REPLACE INTO ${os} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[ps(us,ds),us,ds,(new Date).toISOString(),1]}],{signal:t});return r.ok?Kt(void 0):r}async invokeSQL(e,t,r,s){const n=Array.isArray(t)?t:[t];return this.invokeWithRetry(`${this.host}/invoke`,()=>{const t=this.context.session;return 1===n.length?this.context.invoke(t,"sql",e,n[0]):this.invokeSQLAny(t,e,n)},{headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:s})}actionForSql(e,t){const r=function(e){let t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(e.startsWith("--",t)){const r=e.indexOf("\n",t+2);if(-1===r)return;t=r+1;continue}if(e.startsWith("/*",t)){const r=e.indexOf("*/",t+2);if(-1===r)return;t=r+2;continue}break}const r=/^[A-Za-z_]+/.exec(e.slice(t));return r?.[0].toLowerCase()}(e);return"pragma"===r?is.ADMIN:void 0!==r&&as.has(r)?is.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,is.WRITE)))}dedupeActions(e){return[...new Set(e)]}invokeSQLAny(e,t,r){if(!this.context.invokeAny)throw new Error(`SQL operation requires multiple permissions (${r.join(", ")}) but this SDK runtime does not support multi-resource invocations`);return this.context.invokeAny(e,r.map(r=>({spaceId:e.spaceId,service:"sql",path:t,action:r})))}redactFailure(e,t,r){if(!t||e.ok)return e;const s=e.error.code,n="string"==typeof s&&Object.prototype.hasOwnProperty.call(Ut,s)?s:Ut.SQL_ERROR,i="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return $t(Vt(n,"SQL operation failed","sql",void 0===i?void 0:{meta:{status:i}}))}async handleErrorResponse(e,t,r,s){const n=await e.text(),i=lr(e.status,e.statusText,n);if(402===e.status)return $t(Fr("sql",402,i,n));if(413===e.status&&Mr(n))return $t(Fr("sql",413,i,n));const a=Nr("sql",`SQL ${t} failed: ${e.status} - ${n}`,e,n);if(a)return $t(a);const o=ur(n),c=rs("sql",t,e.status,n)??this.mapHttpStatusToErrorCode(e.status,o.error),u=dr("SQL",t,e.status,n,o);if(401===e.status){const{action:e}=Ir(n);e&&s.includes(e)&&(i.requiredAction=e,i.resource=`${this.context.session.spaceId}/sql/${r}`)}return $t(Vt(c,u,"sql",{meta:i}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return Ut.SQL_ERROR;case 401:return Ut.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?Ut.SQL_READONLY_VIOLATION:Ut.SQL_PERMISSION_DENIED;case 404:return Ut.SQL_DATABASE_NOT_FOUND;case 413:return Ut.SQL_RESPONSE_TOO_LARGE;case 429:return Ut.SQL_QUOTA_EXCEEDED;default:return Ut.NETWORK_ERROR}}}).serviceName="sql";var fs=class{constructor(e,t){this.service=e,this.name=t}async query(e,t,r){return this.service.queryOnDb(this.name,e,t,r)}async queryArrow(e,t,r){return this.service.queryArrowOnDb(this.name,e,t,r)}async execute(e,t,r){return this.service.executeOnDb(this.name,e,t,r)}async batch(e,t){return this.service.batchOnDb(this.name,e,t)}async executeStatement(e,t,r){return this.service.executeStatementOnDb(this.name,e,t,r)}async describe(e){return this.service.describeDb(this.name,e)}async export(e){return this.service.exportOnDb(this.name,e)}async import(e,t){return this.service.importOnDb(this.name,e,t)}},ms={READ:rt.READ,WRITE:rt.WRITE,ADMIN:rt.ADMIN,DESCRIBE:rt.DESCRIBE,EXPORT:rt.EXPORT,IMPORT:rt.IMPORT,EXECUTE:rt.EXECUTE,ALL:rt.ALL};(class extends Hr{constructor(e={}){super(),this._config=e}get config(){return this._config}get defaultDbName(){return this._config.defaultDatabase??"default"}get host(){return this.context.hosts[0]}db(e){return new fs(this,e??this.defaultDbName)}async query(e,t,r){return this.queryOnDb(this.defaultDbName,e,t,r)}async queryArrow(e,t,r){return this.queryArrowOnDb(this.defaultDbName,e,t,r)}async execute(e,t,r){return this.executeOnDb(this.defaultDbName,e,t,r)}async batch(e,t){return this.batchOnDb(this.defaultDbName,e,t)}async queryOnDb(e,t,r,s){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeDuckDb(e,ms.READ,{action:"query",sql:t,params:r??[]},n.signal);return s.ok?Kt(await s.json()):await this.handleErrorResponse(s,"query")}catch(e){return $t(jr("duckdb",e))}finally{n.dispose()}})}async queryArrowOnDb(e,t,r,s){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeDuckDb(e,ms.READ,{action:"query",sql:t,params:r??[]},n.signal,{Accept:"application/vnd.apache.arrow.stream"});return s.ok?Kt(await s.arrayBuffer()):await this.handleErrorResponse(s,"queryArrow")}catch(e){return $t(jr("duckdb",e))}finally{n.dispose()}})}async executeOnDb(e,t,r,s){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const n=this.createRequestSignal(s?.signal);try{const i={action:"execute",sql:t,params:r??[]};s?.schema&&(i.schema=s.schema);const a=await this.invokeDuckDb(e,ms.WRITE,i,n.signal);return a.ok?Kt(await a.json()):await this.handleErrorResponse(a,"execute")}catch(e){return $t(jr("duckdb",e))}finally{n.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const s=this.createRequestSignal(r?.signal);try{const n={action:"batch",statements:t};void 0!==r?.transactional&&(n.transactional=r.transactional);const i=await this.invokeDuckDb(e,ms.WRITE,n,s.signal);return i.ok?Kt(await i.json()):await this.handleErrorResponse(i,"batch")}catch(e){return $t(jr("duckdb",e))}finally{s.dispose()}})}async executeStatementOnDb(e,t,r,s){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const n=this.createRequestSignal(s?.signal);try{const s=await this.invokeDuckDb(e,ms.WRITE,{action:"executeStatement",name:t,params:r??[]},n.signal);return s.ok?Kt(await s.json()):await this.handleErrorResponse(s,"executeStatement")}catch(e){return $t(jr("duckdb",e))}finally{n.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,ms.READ,{action:"describe"},r.signal);return t.ok?Kt(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return $t(jr("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,ms.EXPORT,{action:"export"},r.signal);return t.ok?Kt(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return $t(jr("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return $t(wr("duckdb"));const s=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,ms.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:s.signal});return r.ok?Kt(void 0):await this.handleErrorResponse(r,"import")}catch(e){return $t(jr("duckdb",e))}finally{s.dispose()}})}async invokeDuckDb(e,t,r,s,n){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,t),{headers:{"Content-Type":"application/json",...n},body:JSON.stringify(r),signal:s})}async handleErrorResponse(e,t){const r=await e.text(),s=lr(e.status,e.statusText,r);if(402===e.status)return $t(Fr("duckdb",402,s,r));if(413===e.status&&Mr(r))return $t(Fr("duckdb",413,s,r));const n=Nr("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(n)return $t(n);const i=ur(r),a=rs("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,i.error),o=dr("DuckDB",t,e.status,r,i);if(401===e.status){const{resource:e,action:t}=Ir(r);t&&(s.requiredAction=t),e&&(s.resource=e)}return $t(Vt(a,o,"duckdb",{meta:s}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return Ut.DUCKDB_ERROR;case 401:return Ut.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?Ut.DUCKDB_READONLY_VIOLATION:Ut.DUCKDB_PERMISSION_DENIED;case 404:return Ut.DUCKDB_DATABASE_NOT_FOUND;case 413:return Ut.DUCKDB_RESPONSE_TOO_LARGE;case 429:return Ut.DUCKDB_QUOTA_EXCEEDED;default:return Ut.NETWORK_ERROR}}}).serviceName="duckdb";var gs=class{constructor(){this.values=[],this.waiters=[],this.closed=!1}[Symbol.asyncIterator](){return this}push(e){if(this.closed)return;const t=this.waiters.shift();t?t.resolve({value:e,done:!1}):this.values.push(e)}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const e=this.waiters.shift();e?.resolve({value:void 0,done:!0})}}fail(e){if(!this.closed)for(this.closed=!0,this.failure=e;this.waiters.length>0;){const t=this.waiters.shift();t?.reject(e)}}next(){if(this.values.length>0){const e=this.values.shift();return Promise.resolve({value:e,done:!1})}return void 0!==this.failure?Promise.reject(this.failure):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function vs(e,t){const r=Cs(t);return r?`${e}/${r}`:e}function _s(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends Hr{constructor(e={}){super(),this._subscribers=new Set,this._supervising=!1,this._sessionGeneration=0,this._streamGeneration=0,this._config=e}get config(){return this._config}get host(){return this._config.host??this.context.hosts[0]}async*subscribe(e,t={}){if(!this.requireAuth())throw new Error("Authentication required for hooks subscription");if(0===e.length)throw new Error("At least one hook subscription is required");const r=e.map(xs),s={requested:r,signatures:r.map(Ds),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new gs},n=()=>{this._subscribers.delete(s),s.queue.close(),this.wake()},{signal:i}=t;if(!i?.aborted){i?.addEventListener("abort",n,{once:!0}),this._subscribers.add(s),this.wake(),this._readyStream&&this.notifyReady(s,this._readyStream);try{for await(const e of s.queue)yield e}finally{i?.removeEventListener("abort",n),n()}}}async register(e){if(!this.requireAuth())return $t(wr("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return $t(Vt(Ut.INVALID_INPUT,"Webhook secret is required","hooks",{meta:{field:"secret"}}));try{const t=await this.invokeWithRetry(`${this.host}/hooks/webhooks`,()=>this.createHookHeaders("tinycloud.hooks/register",vs(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:Cs(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return $t(await Us("hooks","failed to register webhook",t));const r=$s(await t.json());return r?Kt(r):$t(jr("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return $t(jr("hooks",e))}}async list(e={}){if(!this.requireAuth())return $t(wr("hooks"));try{const t=new URLSearchParams;if(e.space&&t.set("space",e.space),e.service&&t.set("service",e.service),e.pathPrefix){const r=Cs(e.pathPrefix);r&&t.set("prefix",r)}const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks${t.size>0?`?${t.toString()}`:""}`,()=>this.createHookHeaders("tinycloud.hooks/list",e.service?vs(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return $t(await Us("hooks","failed to list webhooks",r));const s=function(e){if(Array.isArray(e))return e.map(e=>$s(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=Vs(t.webhooks)??Vs(t.subscriptions)??Vs(t.hooks)??Vs(t.data);if(r)return r;const s=qs(t);return s?[s]:null}(await r.json());return s?Kt(s):$t(jr("hooks",new Error("Webhook list response did not include records")))}catch(e){return $t(jr("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return $t(wr("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?vs(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?Kt(void 0):$t(await Us("hooks","failed to unregister webhook",r))}catch(e){return $t(jr("hooks",e))}}wake(){const e=this._phase;e&&e.key!==this.plan()?.key&&e.interrupt.abort(),this._supervising||0===this._subscribers.size||(this._supervising=!0,this.supervise().catch(()=>this.collapse()))}async supervise(){let e=0;for(;;){const t=this.plan();if(!t)return void(this._supervising=!1);const r={openedAt:0,delivered:!1},s=await this.phase(t.key,e=>this.attempt(t,e,r));(r.delivered||r.openedAt>0&&performance.now()-r.openedAt>=5e3)&&(e=0),s&&this.plan()?.key===t.key&&("stopped"!==s.kind?"refused"===s.kind&&s.terminal?(this.release(s.error),this.report(s.error)):("ended"!==s.kind&&this.report(s.error),e+=1,await this.phase(t.key,t=>this.pause(e,t))):this.release())}}async phase(e,t){const r=new AbortController;this._phase={key:e,interrupt:r};try{this.plan()?.key!==e&&r.abort();const s=await t(r.signal);return r.signal.aborted?void 0:s}finally{this._phase=void 0,r.abort()}}async attempt(e,t,r){let s,n="mint";const i=++this._streamGeneration,a=()=>!t.aborted&&!s?.signal.aborted&&this.plan()?.key===e.key;try{const o=this.context,c=o.abortSignal;if(this._lastContextSignal=c,!o.isAuthenticated||c?.aborted)return{kind:"stopped"};s=this.createRequestSignal(t,0);const u=this.host,d=await Es(s.signal,()=>{return o.fetch(`${u}/hooks/tickets`,{method:"POST",headers:{...(t=this.createInvokeHeaders(e.subscriptions),Array.isArray(t)?Object.fromEntries(t):{...t}),"content-type":"application/json"},body:JSON.stringify({subscriptions:e.subscriptions,ttlSeconds:e.ttlSeconds}),signal:s.signal});var t});if(!a())return{kind:"stopped"};if(!d.ok){const e=d.status,t=await Es(s.signal,()=>Us("hooks","failed to mint hook ticket",d));return a()?{kind:"refused",terminal:_s(e),error:t}:{kind:"stopped"}}const l=await Es(s.signal,()=>d.json());if(!a())return{kind:"stopped"};const h=null!==l&&"object"==typeof l&&"ticket"in l?l.ticket:void 0;if("string"!=typeof h||0===h.length)throw new Error("Hook ticket response did not include a ticket");if(n="open",!a())return{kind:"stopped"};const p=await Es(s.signal,()=>o.fetch(`${u}/hooks/events?ticket=${encodeURIComponent(h)}`,{method:"GET",headers:{accept:"text/event-stream"},signal:s.signal}));if(!a())return{kind:"stopped"};if(!p.ok)return{kind:"refused",terminal:!1,error:Ts(p.status)};r.openedAt=performance.now();const y=async function*(e,t){if(!e)throw new Error("Hook stream response does not expose a readable body");const r=new TextDecoder;let s="";for await(const n of async function*(e,t){const r=e;if("function"==typeof r?.[Symbol.asyncIterator]){const e=r[Symbol.asyncIterator](),s=()=>{try{const t=e.return?.();t&&Promise.resolve(t).then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",s,{once:!0});try{for(;!t?.aborted;){const t=await e.next();if(t.done)break;yield t.value}}finally{t?.removeEventListener("abort",s),s()}return}const s=e;if("function"!=typeof s.getReader)throw new Error("Unsupported hook stream body type");const n=s.getReader(),i=()=>{try{const e=n.cancel?.();e&&e.then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",i,{once:!0});try{for(;!t?.aborted;){const{done:e,value:t}=await n.read();if(e)break;t&&(yield t)}}finally{t?.removeEventListener("abort",i),i(),n.releaseLock?.()}}(e,t)){s+=r.decode(n,{stream:!0}).replace(/\r\n/g,"\n");let e=s.indexOf("\n\n");for(;e>=0;){const t=s.slice(0,e);s=s.slice(e+2);const r=Ls(t);r&&(yield r),e=s.indexOf("\n\n")}}s+=r.decode();const n=Ls(s.trim());n&&(yield n)}(p.body,s.signal)[Symbol.asyncIterator]();try{for(;;){const t=await Es(s.signal,()=>y.next());if(!a())return{kind:"stopped"};if(t.done)break;const n=t.value;if(!n.data)continue;if("ready"===n.event){const t=JSON.parse(n.data);if(null!==t&&"object"==typeof t&&"type"in t&&"ready"===t.type){this._readyStream={key:e.key,generation:i};for(const e of this._subscribers)this.notifyReady(e,this._readyStream)}continue}const o=Ks(n);if(!a())return{kind:"stopped"};this.dispatch(o),r.delivered=!0}}finally{const e=y.return?.();e&&Promise.resolve(e).then(()=>{},()=>{})}return a()?{kind:"ended"}:{kind:"stopped"}}catch(e){return s?.signal.aborted||e===ks?{kind:"stopped"}:{kind:"failed",error:Ns(n,e)}}finally{this._readyStream?.generation===i&&(this._readyStream=void 0)}}async pause(e,t){try{this._lastContextSignal=this.context.abortSignal}catch{}const r=this._lastContextSignal,s=[],n=[];try{const r=this._config.streamRetry,n=r?.delay?.(e)??function(e){const t=Math.min(250*2**Math.max(0,e-1),3e4);return t/2+Math.random()*(t/2)}(e);s.push((r?.wait??Is)(n,e,t))}catch{s.push(Promise.resolve())}n.push(Ss(t)),r&&n.push(Ss(r));try{await Promise.race([...s,...n.map(({promise:e})=>e)])}catch{}finally{for(const e of n)e.dispose()}await new Promise(e=>setTimeout(e,0))}plan(){if(0===this._subscribers.size)return;const e=new Map;let t;for(const r of this._subscribers)r.requested.forEach((t,s)=>e.set(r.signatures[s],t)),"number"==typeof r.ttlSeconds&&(t=Math.min(r.ttlSeconds,t??1/0));const r=[...e.keys()].sort();return{key:JSON.stringify([this._sessionGeneration,r,t??null]),subscriptions:r.map(t=>e.get(t)),ttlSeconds:t}}notifyReady(e,t){if(this._subscribers.has(e)&&e.readyGeneration!==t.generation&&this.plan()?.key===t.key&&!this._phase?.interrupt.signal.aborted){e.readyGeneration=t.generation;try{e.onReady?.()}catch{this.report(Vt(Ut.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)Ps(e,t.requested)&&t.queue.push(e)}release(e){const t=[...this._subscribers];this._subscribers.clear();for(const{queue:r}of t)e?r.fail(e):r.close()}report(e){e.meta&&"object"==typeof e.meta&&Object.freeze(e.meta),Object.freeze(e);try{this.emitError(e,"stream")}catch{}}collapse(){this._supervising=!1,this._phase?.interrupt.abort(),this._phase=void 0;const e=Vt(Ut.NETWORK_ERROR,"hook stream supervisor stopped unexpectedly","hooks");this.report(e),this.release(e)}onSessionChange(e){super.onSessionChange(e),this._sessionGeneration+=1,this.wake()}onSignOut(){super.onSignOut(),this.release(),this.wake()}createHookHeaders(e,t){return this.context.invoke(this.session,"hooks",t,e)}createInvokeHeaders(e){const t=e.map(e=>({spaceId:e.space,service:"hooks",path:e.pathPrefix?`${e.service}/${e.pathPrefix}`:e.service,action:"tinycloud.hooks/subscribe"}));if(this.context.invokeAny)return this.context.invokeAny(this.session,t);if(1===t.length){const e=t[0];return this.context.invoke(this.session,e.service,e.path,e.action)}throw new Error("This SDK runtime does not support multi-scope hook invocations")}}).serviceName="hooks";var ks=Symbol("hooks attempt superseded");async function Es(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(bs,()=>{}),ks;const r="function"==typeof t?t():t;return new Promise((t,s)=>{let n=!1;const i=()=>e.removeEventListener("abort",a),a=()=>{n||(n=!0,i(),s(ks))};e.addEventListener("abort",a,{once:!0}),r.then(e=>{n?bs(e):(n=!0,i(),t(e))},e=>{n||(n=!0,i(),s(e))})})}function bs(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function Ts(e){const t="number"==typeof e?e:void 0;return Vt(Ut.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var ws=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function Ns(e,t){const r=As(t,"name"),s="string"==typeof r&&ws.has(r)?r:"Error",n=Rs(As(t,"code"))??Rs(As(As(t,"cause"),"code"));return Vt(Ut.NETWORK_ERROR,`hook stream ${e} failed: ${s}${n?` (${n})`:""}`,"hooks",{meta:{phase:e,errorName:s,...n?{errorCode:n}:{}}})}var Os=new Set(["ECONNREFUSED","ECONNRESET","ECONNABORTED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","EADDRNOTAVAIL","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CLOSED","UND_ERR_ABORTED","UND_ERR_RESPONSE_STATUS_CODE","ERR_TLS_CERT_ALTNAME_INVALID","CERT_HAS_EXPIRED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","ERR_SSL_WRONG_VERSION_NUMBER"]);function Rs(e){return"string"==typeof e&&Os.has(e)?e:void 0}function As(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var Is=(e,t,r)=>((e,t,r=!1)=>new Promise(s=>{const n=()=>{clearTimeout(i),t.removeEventListener("abort",n),s()},i=setTimeout(n,e);r&&i.unref?.(),t.aborted?n():t.addEventListener("abort",n)}))(e,r,!0);function Ss(e){let t;const r=new Promise(e=>{t=e}),s=()=>t();return e.aborted?t():e.addEventListener("abort",s,{once:!0}),{promise:r,dispose:()=>e.removeEventListener("abort",s)}}function xs(e){return{...e,pathPrefix:"kv"===e.service?Cs(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function Ds(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function Ps(e,t){return t.some(t=>function(e,t){if(e.space!==t.space)return!1;if(e.service!==t.service)return!1;if("sql"===e.service||"duckdb"===e.service){const r=t.pathPrefix,s=e.databasePath??e.path;if(r&&"/"!==r&&(!s||(r.endsWith("/")?!s.startsWith(r):s!==r)))return!1}else if(t.pathPrefix){const r=t.pathPrefix.endsWith("/")?t.pathPrefix:`${t.pathPrefix}/`;if(e.path&&e.path!==t.pathPrefix&&!e.path.startsWith(r))return!1}const r=t.abilities??[];return!(r.length>0&&!r.includes(e.ability))}(e,t))}function Cs(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function Us(e,t,r){let s=r.statusText;try{const e=await r.text();e&&(s=e)}catch{}return Vt(408===r.status||504===r.status?Ut.TIMEOUT:Ut.NETWORK_ERROR,`${t}: ${r.status} ${s}`,e,{meta:{status:r.status,statusText:r.statusText}})}function Ls(e){if(!e)return null;let t,r="message";const s=[];for(const n of e.split("\n")){if(!n||n.startsWith(":"))continue;const[e,...i]=n.split(":"),a=i.join(":").replace(/^ /,"");switch(e){case"event":r=a;break;case"id":t=a;break;case"data":s.push(a)}}return 0===s.length?null:{event:r,id:t,data:s.join("\n")}}function Ks(e){const t=JSON.parse(e.data);return{type:"write",id:t.id??e.id??"",space:t.space??"",service:t.service??"",ability:t.ability??"",path:t.path,databasePath:"string"==typeof t.databasePath?t.databasePath:void 0,actor:t.actor??"",epoch:t.epoch??"",eventIndex:t.eventIndex??0,timestamp:t.timestamp??""}}function $s(e){if(!e||"object"!=typeof e)return null;const t=e;return qs(t)??$s(t.webhook)??$s(t.hook)??$s(t.subscription)??$s(t.data)??null}function Vs(e){return Array.isArray(e)?e.map(e=>$s(e)).filter(e=>null!==e):null}function qs(e){const t=Ms(e,"id"),r=Ms(e,"space")??Ms(e,"spaceId"),s=Ms(e,"service"),n=Ms(e,"callbackUrl")??Ms(e,"callback_url");return t&&r&&s&&n?{id:t,space:r,service:s,pathPrefix:Fs(e,"pathPrefix")??Fs(e,"path_prefix"),abilities:Hs(e,"abilities")??Bs(e,"abilitiesJson")??Bs(e,"abilities_json"),callbackUrl:n,active:js(e,"active")??!0,createdAt:Ms(e,"createdAt")??Ms(e,"created_at")??(new Date).toISOString(),subscriberDid:Fs(e,"subscriberDid")??Fs(e,"subscriber_did")}:null}function Ms(e,t){const r=e[t];return"string"==typeof r?r:void 0}function Fs(e,t){return Ms(e,t)}function js(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function Hs(e,t){const r=e[t];if(!Array.isArray(r))return;const s=r.filter(e=>"string"==typeof e);return s.length===r.length?s:void 0}function Bs(e,t){const r=e[t];if("string"==typeof r)try{const e=JSON.parse(r);if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e);return t.length===e.length?t:void 0}catch{return}}function Zs(e){return void 0===e?"":Ws(e)}function Ws(e){if(null===e)return"null";switch(typeof e){case"boolean":case"number":case"string":return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(Ws).join(",")}]`;const t=Object.keys(e).sort(),r=[];for(const s of t){const t=e[s];void 0!==t&&r.push(`${JSON.stringify(s)}:${Ws(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var Gs="0123456789abcdef";function zs(e){let t="";for(let r=0;r<e.length;r++){const s=e[r];t+=Gs[s>>4&15]+Gs[15&s]}return t}function Js(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<e.length;s+=3){const n=e[s],i=s+1<e.length?e[s+1]:0,a=s+2<e.length?e[s+2]:0;r+=t[n>>2&63],r+=t[63&(n<<4|i>>4)],r+=s+1<e.length?t[63&(i<<2|a>>6)]:"=",r+=s+2<e.length?t[63&a]:"="}return r}function Qs(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),r=t.length;if(r%4!=0)throw new Error("invalid base64 input");const s=r/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),n=new Uint8Array(s),i={};for(let e=0;e<64;e++)i["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let a=0;for(let e=0;e<r;e+=4){const r=i[t[e]]??0,o=i[t[e+1]]??0,c="="===t[e+2]?0:i[t[e+2]]??0,u=r<<2|o>>4,d=(15&o)<<4|c>>2,l=(3&c)<<6|("="===t[e+3]?0:i[t[e+3]]??0);a<s&&(n[a++]=u),a<s&&(n[a++]=d),a<s&&(n[a++]=l)}return n}function Ys(e){return(new TextEncoder).encode(e)}function Xs(e,t){return zs(e(Ys(Zs(t))))}var en={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},tn="x-vault-version",rn="x-vault-cipher",sn="x-vault-key-id",nn="x-vault-content-type",an="x-vault-kdf",on="x-vault-key-rotation",cn="x-vault-grant-version",un="x-vault-grantor",dn="signatures",ln="__wrap_key__";function hn(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function pn(){return new Promise((e,t)=>{const r=indexedDB.open("tinycloud-vault-cache",1);r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(dn)||e.createObjectStore(dn)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function yn(e,t){return new Promise((r,s)=>{const n=e.transaction(dn,"readonly").objectStore(dn).get(t);n.onsuccess=()=>r(n.result),n.onerror=()=>s(n.error)})}function fn(e,t,r){return new Promise((s,n)=>{const i=e.transaction(dn,"readwrite").objectStore(dn).put(r,t);i.onsuccess=()=>s(),i.onerror=()=>n(i.error)})}function mn(e,t){return new Promise((r,s)=>{const n=e.transaction(dn,"readwrite").objectStore(dn).delete(t);n.onsuccess=()=>r(),n.onerror=()=>s(n.error)})}async function gn(e){const t=await yn(e,ln);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await fn(e,ln,r),r}function vn(e){return`sig:${e}`}async function _n(e){if(!hn())return null;try{const t=await pn(),r=await yn(t,vn(e));if(!r)return null;const s=await gn(t);return await async function(e,t){const r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.iv},e,t.ciphertext);return new Uint8Array(r)}(s,r)}catch{return null}}async function kn(e,t){if(hn())try{const r=await pn(),s=await gn(r),n=await async function(e,t){const r=crypto.getRandomValues(new Uint8Array(12));return{iv:r,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t))}}(s,t);await fn(r,vn(e),n)}catch{}}async function En(e){if(hn())try{const t=await pn();if(e)await mn(t,vn(e));else{const e=await function(e){return new Promise((t,r)=>{const s=e.transaction(dn,"readonly").objectStore(dn).getAllKeys();s.onsuccess=()=>t(s.result.filter(e=>"string"==typeof e)),s.onerror=()=>r(s.error)})}(t);for(const r of e)r.startsWith("sig:")&&await mn(t,r)}}catch{}}function bn(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function Tn(e){return(new TextEncoder).encode(e)}function wn(e){return(new TextDecoder).decode(e)}function Nn(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function On(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Rn(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function An(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function In(e){return"number"==typeof e.meta?.status}function Sn(e){switch(e.code){case"DECRYPTION_FAILED":return e.message??"Decryption failed";case"KEY_NOT_FOUND":return e.message??`Key not found: ${e.key}`;case"INTEGRITY_ERROR":return e.message??"Integrity check failed";case"GRANT_NOT_FOUND":return e.message??`Grant not found: ${e.grantor} / ${e.key}`;case"VAULT_LOCKED":return e.message??"Vault is locked";case"PUBLIC_KEY_NOT_FOUND":return e.message??`Public key not found for ${e.did}`;case"STORAGE_ERROR":return e.message??e.cause.message;case"ALREADY_EXISTS":return e.message??`A value already exists at ${e.key}`;case"AUTH_UNAUTHORIZED":case"PERMISSION_DENIED":case"AAD_MISMATCH":case"ETAG_MISMATCH":case"INVALID_ETAG":case"OUTCOME_UNKNOWN":case"NODE_BUSY":case"STORAGE_QUOTA_EXCEEDED":case"STORAGE_LIMIT_REACHED":return e.message;default:return e.message??e.code}}function xn(e){return{ok:!1,error:{...e,service:"vault",message:Sn(e)}}}function Dn(e){return Object.assign(new Error(e.message),{name:"ServiceError",code:e.code,service:e.service,...void 0!==e.meta?{meta:e.meta}:{},...void 0!==e.cause?{cause:e.cause}:{}})}function Pn(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function Cn(e,t,r){const s=e;if("object"!=typeof s||null===s||Array.isArray(s)||!["networkId","alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"].every(e=>"string"==typeof s[e]&&""!==s[e])||!Number.isInteger(s.keyVersion)||void 0!==s.aad&&"string"!=typeof s.aad)return"corrupt";let n="";try{"string"==typeof s.aad&&(n=wn(Qs(s.aad)))}catch{}const i=`:${r}`;return n.endsWith(i)&&Pn(n.slice(0,-i.length))===Pn(`tinycloud.vault:${t}`)?"ok":"mismatch"}var Un=[500,502,503,504,520,522,524];function Ln(e,t){const r=br(t);if(r)return xn(r);if(t.code===Ut.STORAGE_QUOTA_EXCEEDED||t.code===Ut.STORAGE_LIMIT_REACHED)return xn({code:t.code,message:t.message,meta:t.meta});const s=`${e}: ${t.message}`;return t.code===Ut.AUTH_UNAUTHORIZED?xn({code:"unauthenticated"===Lr(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:s,...void 0!==t.meta?{meta:t.meta}:{},cause:Dn(t)}):xn({code:"STORAGE_ERROR",cause:new Error(s,{cause:Dn(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}(class extends Hr{constructor(e){super(),this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1,this.unlockInFlight=null,this.vaultConfig=e,this._config=e}get config(){return this._config}get isUnlocked(){return this.usesNetworkEncryption||this._isUnlocked}get publicKey(){if(this.usesNetworkEncryption)throw new Error("Network-encrypted vaults do not expose a local public key");if(!this.encryptionIdentity)throw new Error("Vault is locked");return this.encryptionIdentity.publicKey}get crypto(){return this.vaultConfig.crypto}get tc(){return this.vaultConfig.tc}get networkEncryption(){return this.vaultConfig.encryption}get usesNetworkEncryption(){return void 0!==this.networkEncryption}get host(){return this.tc.hosts[0]}async decryptCapabilityProof(){const e=this.networkEncryption?.decryptCapabilityProof;return"function"==typeof e?await e():e??{proofs:[]}}serializeValue(e,t){let r;return r=e instanceof Uint8Array?e:t?.serialize?t.serialize(e):Tn("string"==typeof e?e:JSON.stringify(e)),{plaintext:r,contentType:t?.contentType??(e instanceof Uint8Array?"application/octet-stream":"application/json")}}deserializeValue(e,t,r){return r?.raw?e:r?.deserialize?r.deserialize(e):"application/json"===t?JSON.parse(wn(e)):e}async unlock(e){if(this.usesNetworkEncryption)return this._isUnlocked=!0,{ok:!0,data:void 0};const t=function(e){return"object"==typeof e&&null!==e&&"function"==typeof e.signMessage}(e)?e:void 0;if(this._isUnlocked&&this.masterKey&&(this.encryptionIdentity||!t))return{ok:!0,data:void 0};if(this.unlockInFlight)return this.unlockInFlight;this.unlockInFlight=this.withTelemetry("unlock",void 0,async()=>{const e=this.vaultConfig.spaceId,r=en,s=`vault-master:${e}`,n=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let n=await _n(s);if(!n){if(!t)return xn({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});n=Tn(await t.signMessage(r.masterMessage(e))),await kn(s,n)}this.masterKey=this.crypto.deriveKey(n,this.crypto.sha256(Tn(e)),Tn("vault-master"))}const i=this.tc.makePublicSpaceId(this.tc.address,this.tc.chainId);let a=null;try{const e=await this.tc.readPublicSpace(this.host,i,".well-known/vault-pubkey");e.ok&&e.data&&(a=e.data)}catch{}if(a)this.encryptionIdentity={publicKey:Rn(a),privateKey:new Uint8Array(0)};else{let e=await _n(n);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,Kt(void 0);e=Tn(await t.signMessage(r.identityMessage)),await kn(n,e)}const s=this.crypto.deriveKey(e,Tn("tinycloud-x25519"),Tn("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(s);try{const e=On(this.encryptionIdentity.publicKey);await this.tc.ensurePublicSpace(),await this.tc.publicKV.put(".well-known/vault-pubkey",e),await this.tc.publicKV.put(".well-known/vault-version","1"),await this.tc.publicKV.put(".well-known/vault-space",this.vaultConfig.spaceId)}catch{}}return this._isUnlocked=!0,Kt(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,xn({code:"STORAGE_ERROR",cause:bn(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await En(`vault-master:${e}`):await En()}lock(){this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1}onSignOut(){this.lock(),super.onSignOut()}async putNetworkEncrypted(e,t,r){const s=this.networkEncryption;if(!s)return xn({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return xn({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return xn({code:"INVALID_ETAG",key:e,message:r.ifMatch.startsWith("W/")?'ifMatch is a weak etag (W/"..."): the node only issues strong etags, so the etag was weakened in transit (a proxy or CDN rewrote it). Read it from a connection that preserves strong ETags':"ifMatch must be the strong, quoted ETag returned by a network read (VaultEntry.etag), passed exactly as returned"})}try{const{plaintext:n,contentType:i}=this.serializeValue(t,r),a={[tn]:"2",[rn]:"tinycloud-network-envelope",[nn]:i,...r?.metadata??{}},o=Tn(`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`),c=await s.service.encryptToNetwork(s.networkId,n,{aad:o,metadata:a});if(!c.ok){const e=br(c.error);return xn(e||{code:"STORAGE_ERROR",cause:new Error(c.error.message)})}const u=`vault/${e}`,d=JSON.stringify(c.data),l=void 0!==r?.ifMatch?{ifMatch:r.ifMatch}:void 0!==r?.ifNoneMatch?{ifNoneMatch:r.ifNoneMatch}:void 0,h=void 0!==l?await this.tc.kv.put(u,d,l):await this.tc.kv.put(u,d);if(!h.ok){if(void 0!==r?.ifNoneMatch&&h.error.code===Ut.KV_PRECONDITION_FAILED)return xn({code:"ALREADY_EXISTS",key:e,...void 0!==h.error.meta?{meta:h.error.meta}:{},cause:Dn(h.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,s=t.code===Ut.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===Ut.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===Ut.OUTCOME_UNKNOWN||t.code===Ut.KV_WRITE_FAILED&&"number"==typeof r&&Un.includes(r)||(t.code===Ut.NETWORK_ERROR||t.code===Ut.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===Ut.NODE_BUSY||t.code===Ut.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==s)return xn({code:s,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:Dn(t)})}(e,h.error);if(void 0!==t)return t}return Ln("Failed to store encrypted value",h.error)}return{ok:!0,data:void 0}}catch(e){const t=br(e);return xn(t||{code:"STORAGE_ERROR",cause:bn(e)})}}async getNetworkEncrypted(e,t){const r=this.networkEncryption;if(!r)return xn({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!s.ok){const t=br(s.error);return xn(t||{code:"KEY_NOT_FOUND",key:e})}const n=An(s.data),i="string"==typeof n?JSON.parse(n):n;if(!0===t?.expectAad){const t=Cn(i,this.vaultConfig.spaceId,e);if("corrupt"===t)return xn({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===t)return xn({code:"AAD_MISMATCH",key:e,message:`Envelope at ${e} is not bound to this space and key`})}const a=await this.decryptCapabilityProof(),o=await r.service.decryptEnvelope(i,a);if(!o.ok){const e=br(o.error);return xn(e||{code:"DECRYPTION_FAILED",message:o.error.message})}const c=i.metadata??{},u=c[nn]??"application/json",d=c[sn]??i.encryptedSymmetricKeyHash.slice(0,16),l=this.deserializeValue(o.data,u,t),h="network"===t?.source?s.data.headers?.etag:void 0;return{ok:!0,data:{value:l,metadata:c,keyId:d,...void 0===h?{}:{etag:h}}}}catch(e){const t=br(e);return xn(t||{code:"STORAGE_ERROR",cause:bn(e)})}}async readNetworkEncrypted(e,t){const r=this.networkEncryption;if(!r||!this.requireAuth())return{status:"read_failed"};let s,n,i;try{s=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"})}catch(e){if(br(e))throw e;return{status:"node_unreachable"}}if(!s.ok){if(br(s.error))throw s.error;const e=Tr(s.error.meta?.permissionHint);return"AUTH_UNAUTHORIZED"===s.error.code&&void 0!==e?{status:"permission_required",hint:e}:"NOT_FOUND"!==s.error.code&&"KV_NOT_FOUND"!==s.error.code||In(s.error)?"NODE_NOT_RESPONDING"===s.error.code||"NETWORK_ERROR"===s.error.code||"TIMEOUT"===s.error.code||"ABORTED"===s.error.code?In(s.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=An(s.data);n="string"==typeof e?JSON.parse(e):e}catch{return{status:"corrupt_envelope"}}if(!0===t?.expectAad){const t=Cn(n,this.vaultConfig.spaceId,e);if("ok"!==t)return{status:"corrupt"===t?"corrupt_envelope":"aad_mismatch"}}try{const e=await this.decryptCapabilityProof();i=await r.service.decryptEnvelope(n,e)}catch(e){if(br(e))throw e;return{status:"decrypt_failed"}}if(!i.ok){if(br(i.error))throw i.error;const e=Tr(i.error.permissionHint);return"DECRYPT_DENIED"===i.error.code&&void 0!==e?{status:"permission_required",hint:e}:"INVALID_ENVELOPE"===i.error.code?{status:"corrupt_envelope"}:"NODE_NOT_RESPONDING"===i.error.code||"TRANSPORT_ERROR"===i.error.code?{status:"node_unreachable"}:{status:"decrypt_failed"}}try{const e=n.metadata??{},r=e[nn]??"application/json",a=e[sn]??n.encryptedSymmetricKeyHash.slice(0,16),o=this.deserializeValue(i.data,r,t),c=s.data.headers?.etag;return{status:"ok",entry:{value:o,metadata:e,keyId:a,...void 0===c?{}:{etag:c}}}}catch{return{status:"invalid_payload"}}}async headNetworkEncrypted(e){if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return xn({code:"KEY_NOT_FOUND",key:e});const r=An(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(this.usesNetworkEncryption)return this.putNetworkEncrypted(e,t,r);if(void 0!==r?.ifNoneMatch)return xn({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return xn({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{let s;s=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):Tn("string"==typeof t?t:JSON.stringify(t));const n=r?.contentType??(t instanceof Uint8Array?"application/octet-stream":"application/json"),i=this.crypto.randomBytes(32),a=Nn(this.crypto.sha256(i)).slice(0,16),o=this.crypto.encrypt(i,s),c=this.crypto.encrypt(this.masterKey,i),u={[tn]:"1",[rn]:"aes-256-gcm",[sn]:a,[nn]:n,[an]:"hkdf-sha256",[on]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},d=JSON.stringify({keyId:a,contentType:n,...u}),l=JSON.stringify({key:On(c),metadata:d}),h=await this.tc.kv.put(`keys/${e}`,l);if(!h.ok)return Ln("Failed to store key blob",h.error);const p=JSON.stringify({data:On(o),metadata:u}),y=await this.tc.kv.put(`vault/${e}`,p);return y.ok?Kt(void 0):Ln("Failed to store encrypted value",y.error)}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return xn({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.tc.kv.get(`keys/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!r.ok)return xn({code:"KEY_NOT_FOUND",key:e});const s=Rn(JSON.parse(r.data.data).key),n=this.crypto.decrypt(this.masterKey,s),i=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!i.ok)return xn({code:"KEY_NOT_FOUND",key:e});const a=JSON.parse(i.data.data),o=Rn(a.data),c=this.crypto.decrypt(n,o),u=a.metadata??{},d=u[nn]??"application/json",l=u[sn]??"";let h;return h=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===d?JSON.parse(wn(c)):c,Kt({value:h,metadata:u,keyId:l})}catch(e){return e instanceof Error&&e.message.includes("decryption")?xn({code:"DECRYPTION_FAILED",message:e.message}):xn({code:"STORAGE_ERROR",cause:bn(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=br(t.error);return xn(r||{code:"KEY_NOT_FOUND",key:e})}return Kt(void 0)}const[t,r]=await Promise.all([this.tc.kv.delete(`keys/${e}`),this.tc.kv.delete(`vault/${e}`)]);if(!t.ok&&!r.ok){const s=br(t.error)??br(r.error);return xn(s||{code:"KEY_NOT_FOUND",key:e})}return Kt(void 0)}catch(e){const t=br(e);return xn(t||{code:"STORAGE_ERROR",cause:bn(e)})}})}async list(e){const t=await this.listPage(e);return t.ok?{ok:!0,data:t.data.keys}:t}async listPage(e){return this.withTelemetry("list",e?.prefix,async()=>{if(!this.isUnlocked)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=e?.prefix?`vault/${e.prefix}`:"vault/",r=await this.tc.kv.list({prefix:t,removePrefix:!0,...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.source?{}:{source:e.source},...void 0===e?.cursor?{}:{cursor:e.cursor}});if(!r.ok){const e=br(r.error);return xn(e||{code:"STORAGE_ERROR",cause:new Error(`Failed to list vault keys: ${r.error.message}`)})}let s=r.data.keys;if(e?.removePrefix&&e.prefix){const t=e.prefix.endsWith("/")?e.prefix:`${e.prefix}/`;s=s.map(e=>e.startsWith(t)?e.slice(t.length):e)}return Kt({keys:s,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=br(e);return xn(t||{code:"STORAGE_ERROR",cause:bn(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return xn({code:"KEY_NOT_FOUND",key:e});return Kt(JSON.parse(t.data.data).metadata??{})}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}})}async putMany(e){return Promise.all(e.map(e=>this.put(e.key,e.value,e.options)))}async getMany(e,t){return Promise.all(e.map(e=>this.get(e,t)))}async reencrypt(e,t,r){return this.withTelemetry("reencrypt",e,async()=>{if(this.usesNetworkEncryption)return xn({code:"STORAGE_ERROR",cause:new Error("Vault key grants are deprecated for network-encrypted vaults; grant tinycloud.encryption/decrypt on the network plus KV access to vault data.")});if(!this._isUnlocked||!this.masterKey)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await this.resolvePublicKey(t);if(!s.ok)return s;const n=s.data,i=await this.tc.kv.get(`keys/${e}`,{raw:!0});if(!i.ok)return xn({code:"KEY_NOT_FOUND",key:e});const a=Rn(JSON.parse(i.data.data).key),o=this.crypto.decrypt(this.masterKey,a),c=this.crypto.randomBytes(32),u=this.crypto.x25519FromSeed(c),d=this.crypto.x25519Dh(u.privateKey,n),l=this.crypto.deriveKey(d,Tn("tinycloud-x25519"),Tn("vault-grant")),h=this.crypto.encrypt(l,o),p=function(...e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let s=0;for(const t of e)r.set(t,s),s+=t.length;return r}(u.publicKey,h),y=JSON.stringify({grant:On(p),spaceId:this.vaultConfig.spaceId,metadata:{[cn]:"1",[un]:this.tc.did,...r?.metadata??{}}}),f=await this.tc.kv.put(`grants/${t}/${e}`,y);return f.ok?Kt(void 0):Ln("Failed to store grant",f.error)}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}})}async grant(e,t,r){return this.reencrypt(e,t,r)}async getShared(e,t,r){return this.withTelemetry("getShared",t,async()=>{if(!0===r?.expectAad)return xn({code:"STORAGE_ERROR",cause:new Error("expectAad is not supported by getShared: the AAD binds the grantor's space, which this vault does not know")});if(this.usesNetworkEncryption){const e=r?.kv;if(!e)return xn({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const s=this.networkEncryption;if(!s)return xn({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=await e.get(`vault/${t}`,{raw:!0});if(!n.ok)return xn({code:"KEY_NOT_FOUND",key:t});const i=An(n.data),a="string"==typeof i?JSON.parse(i):i,o=await this.decryptCapabilityProof(),c=await s.service.decryptEnvelope(a,o);if(!c.ok)return xn({code:"DECRYPTION_FAILED",message:c.error.message});const u=a.metadata??{},d=u[nn]??"application/json",l=u[sn]??a.encryptedSymmetricKeyHash.slice(0,16);return{ok:!0,data:{value:this.deserializeValue(c.data,d,r),metadata:u,keyId:l}}}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=this.tc.did,n=r?.kv;if(!n)return xn({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv. Use useDelegation() to get delegated access, then pass { kv: access.kv }.")});const i=await n.get(`grants/${s}/${t}`,{raw:!0});if(!i.ok)return xn({code:"GRANT_NOT_FOUND",grantor:e,key:t});const a=Rn(("string"==typeof i.data?.data?JSON.parse(i.data.data):i.data?.data).grant),o=a.slice(0,32),c=a.slice(32),u=this.crypto.x25519Dh(this.encryptionIdentity.privateKey,o),d=this.crypto.deriveKey(u,Tn("tinycloud-x25519"),Tn("vault-grant")),l=this.crypto.decrypt(d,c),h=await n.get(`vault/${t}`,{raw:!0});if(!h.ok)return xn({code:"KEY_NOT_FOUND",key:t});const p="string"==typeof h.data?.data?JSON.parse(h.data.data):h.data?.data,y=Rn(p.data),f=this.crypto.decrypt(l,y),m=p.metadata??{},g=m[nn]??"application/json",v=m[sn]??"";let _;return _=r?.raw?f:r?.deserialize?r.deserialize(f):"application/json"===g?JSON.parse(wn(f)):f,Kt({value:_,metadata:m,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?xn({code:"DECRYPTION_FAILED",message:e.message}):xn({code:"STORAGE_ERROR",cause:bn(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return xn({code:"PUBLIC_KEY_NOT_FOUND",did:e});const r=this.tc.makePublicSpaceId(t.address,t.chainId),s=await this.tc.readPublicSpace(this.host,r,".well-known/vault-pubkey");return s.ok?{ok:!0,data:Rn(s.data)}:xn({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return xn({code:"PUBLIC_KEY_NOT_FOUND",did:e})}}async listGrants(e){return this.withTelemetry("listGrants",e,async()=>{if(this.usesNetworkEncryption)return{ok:!0,data:[]};if(!this._isUnlocked)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return xn({code:"STORAGE_ERROR",cause:new Error(`Failed to list grants: ${t.error.message}`)});const r=[];for(const s of t.data.keys)if(s.endsWith(`/${e}`)){const t=s.slice(0,s.length-e.length-1);t&&r.push(t)}return Kt(r)}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return xn({code:"STORAGE_ERROR",cause:new Error("Vault key grants are deprecated for network-encrypted vaults; revoke KV and tinycloud.encryption/decrypt grants instead.")});if(!this._isUnlocked||!this.masterKey)return xn({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return xn({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.listGrants(e);if(!r.ok)return r;const s=r.data.filter(e=>e!==t),n=(await this.tc.kv.delete(`grants/${t}/${e}`),await this.get(e));if(!n.ok)return n;const i=n.data,a=this.crypto.randomBytes(32),o=Nn(this.crypto.sha256(a)).slice(0,16);let c;c=i.value instanceof Uint8Array?i.value:Tn(JSON.stringify(i.value));const u=this.crypto.encrypt(a,c),d=this.crypto.encrypt(this.masterKey,a),l={...i.metadata,[sn]:o},h=JSON.stringify({key:On(d),metadata:JSON.stringify({keyId:o,...l})}),p=await this.tc.kv.put(`keys/${e}`,h);if(!p.ok)return Ln("Failed to store rotated key blob",p.error);const y=JSON.stringify({data:On(u),metadata:l}),f=await this.tc.kv.put(`vault/${e}`,y);if(!f.ok)return Ln("Failed to store re-encrypted value",f.error);for(const t of s)(await this.reencrypt(e,t)).ok;return Kt(void 0)}catch(e){return xn({code:"STORAGE_ERROR",cause:bn(e)})}})}parseDID(e){const t=e.split(":");if(5!==t.length||"did"!==t[0]||"pkh"!==t[1]||"eip155"!==t[2])return null;const r=parseInt(t[3],10),s=t[4];return isNaN(r)||!s?null:{address:s,chainId:r}}}).serviceName="vault",Object.freeze(["default","global","scoped"]);var Kn="tinycloud.encryption.decrypt/v1",$n="tinycloud.encryption.decrypt-result/v1";function Vn(e){switch(e.code){case"NETWORK_NOT_FOUND":return e.message??`Network not found: ${e.networkId??e.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return e.message??`Network not active (state=${e.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return e.message;case"RESPONSE_SIGNATURE_INVALID":return e.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return e.message??`Node response binding mismatch on field ${JSON.stringify(e.field)}`;case"TRANSPORT_ERROR":return e.message??e.cause.message;default:return e.message??e.code}}function qn(e){return{...e,service:"encryption",message:Vn(e)}}function Mn(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function Fn(e,t,r,s){let n;try{n=gr(e.networkId)}catch(e){return{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(n.name!==s||!kr(n.ownerDid,r))return{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:`descriptor networkId ${JSON.stringify(e.networkId)} does not match expected ${JSON.stringify(t)}`})};const i=function(e){if("string"==typeof e.ownerDid&&e.ownerDid.length>0)return e.ownerDid;const t=e;return"string"==typeof t.principal&&t.principal.length>0?t.principal:void 0}(e);return void 0!==i&&kr(i,r)&&kr(i,n.ownerDid)?e.name!==s?{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:i}}:{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function jn(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:qn({code:"NETWORK_NOT_ACTIVE",state:e.state})}}function Hn(e){return{ok:!0,data:e}}function Bn(e){return{ok:!1,error:e}}function Zn(e){return qn("NODE_NOT_RESPONDING"===e.code||"TRANSPORT_ERROR"===e.code&&"AbortError"!==e.cause.name?{...e,code:"DECRYPTION_DEPENDENCY_UNAVAILABLE",message:"The decryption service isn't responding right now. Please try again."}:e)}(class extends Hr{constructor(e){super(),this._config=e}get config(){return this._config}get crypto(){return this._config.crypto}async discoverNetwork(e,t){this.assertActive();const r=await async function(e){let t,r,s;try{if(e.identifier.startsWith("urn:tinycloud:encryption:")){const n=gr(e.identifier);t=n.networkId,r=n.ownerDid,s=n.name}else{if(void 0===e.ownerDid)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"discoverNetwork requires `ownerDid` when identifier is a bare network name"})};t=`urn:tinycloud:encryption:${e.ownerDid}:${e.identifier}`;const n=gr(t);r=n.ownerDid,s=n.name}}catch(e){if(e instanceof mr)return{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:e.message})};throw e}if(void 0!==e.node)try{const n=await e.node.fetchByNetworkId(t);if(null!==n){const e=Fn(n,t,r,s);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=br(e);if(t)return{ok:!1,error:qn(t)}}if(void 0!==e.wellKnown)try{const n=await e.wellKnown.fetchWellKnown(r,function(e){if(!yr.test(e))throw new mr(`network name ${JSON.stringify(e)} must match ${yr.source}`);return`.well-known/encryption/network/${e}`}(s));if(null!==n){const e=Fn(n,t,r,s);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=br(e);if(t)return{ok:!1,error:qn(t)}}return{ok:!1,error:qn({code:"NETWORK_NOT_FOUND",networkId:t,name:s})}}({identifier:e,...void 0!==t?{ownerDid:t}:{},...void 0!==this._config.node?{node:this._config.node}:{},...void 0!==this._config.wellKnown?{wellKnown:this._config.wellKnown}:{}});return this.assertActive(),r.ok?Hn(r.data.descriptor):r}async encryptToNetwork(e,t,r){try{this.assertActive();const s=await this.discoverNetwork(e);if(!s.ok)return s;const n=jn(s.data);if(!n.ok)return n;const i=n.data,a=Qs(i.publicEncryptionKey);return Hn(function(e,t){if(vr(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new mr("keyPath must name an exact encryption key");const r=t.alg??"x25519-aes256gcm/v1",s=t.keyVersion??1,n=e.randomBytes(32),i=e.authEncrypt(n,t.plaintext,t.aad),a=Js(e.sealToNetworkKey(t.networkPublicKey,n)),o=Xs(e.sha256,a);return{envelope:{v:1,networkId:t.networkId,...void 0!==t.keyPath?{keyPath:t.keyPath}:{},alg:r,keyVersion:s,encryptedSymmetricKey:a,encryptedSymmetricKeyHash:o,ciphertext:Js(i),...void 0!==t.aad?{aad:Js(t.aad)}:{},...void 0!==t.metadata?{metadata:t.metadata}:{}},symmetricKey:n}}(this.crypto,{networkId:i.networkId,...void 0!==r?.keyPath?{keyPath:r.keyPath}:{},networkPublicKey:a,plaintext:t,...void 0!==r?.aad?{aad:r.aad}:{},alg:r?.alg??i.alg,keyVersion:r?.keyVersion??i.keyVersion,...void 0!==r?.metadata?{metadata:r.metadata}:{}}).envelope)}catch(e){const t=br(e);return Bn(qn(t||{code:"TRANSPORT_ERROR",cause:Mn(e)}))}}async decryptEnvelope(e,t,r){try{this.assertActive();const n=function(e,t){if(null===t||"object"!=typeof t)return{ok:!1,error:qn({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const r=t;if(1!==r.v)return{ok:!1,error:qn({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${r.v})`})};try{if(void 0!==vr(r.networkId).keyPath)throw new Error("networkId must identify the network root");if(void 0!==r.keyPath){if("string"!=typeof r.keyPath)throw new Error("keyPath must be a string");if(vr(`${r.networkId}/${r.keyPath}`).keyPath!==r.keyPath||r.keyPath.endsWith("/"))throw new Error("keyPath must name an exact encryption key")}}catch(e){return{ok:!1,error:qn({code:"INVALID_ENVELOPE",message:`envelope encryption resource is malformed: ${e instanceof Error?e.message:String(e)}`})}}for(const e of["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"])if("string"!=typeof r[e]||0===r[e].length)return{ok:!1,error:qn({code:"INVALID_ENVELOPE",message:`envelope.${e} must be a non-empty string`})};return"number"==typeof r.keyVersion&&Number.isInteger(r.keyVersion)?Xs(e.sha256,r.encryptedSymmetricKey)!==r.encryptedSymmetricKeyHash?{ok:!1,error:qn({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})}:{ok:!0,data:r}:{ok:!1,error:qn({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})}}(this.crypto,e);if(!n.ok)return n;if(void 0!==r?.aad&&n.data.aad!==Js(r.aad))return Bn(qn({code:"INVALID_INPUT",message:"decryptEnvelope aad does not match the envelope"}));let i;if(void 0!==r?.descriptor)i=r.descriptor;else{const t=await this.discoverNetwork(e.networkId);if(!t.ok)return Bn(Zn(t.error));i=t.data}const a=jn(i);if(!a.ok)return a;const o=this._config.resolveTargetNode?await this._config.resolveTargetNode(e.networkId):r?.targetNode??i.members[0]?.nodeId;if(void 0===o)return Bn(qn({code:"INVALID_INPUT",message:"no target node available from descriptor"}));if(this._config.resolveTargetNode&&(void 0!==r?.targetNode&&r.targetNode!==o||!i.members.some(e=>e.nodeId===o)))return Bn(qn({code:"INVALID_INPUT",message:"Encryption destination does not match the registry"}));const c=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:this.crypto}),u=Js(c.publicKey),d=Xs(this.crypto.sha256,u),l={type:Kn,targetNode:o,networkId:e.networkId,...void 0!==e.keyPath?{keyPath:e.keyPath}:{},alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:u,receiverPublicKeyHash:d},h={canonicalBody:Zs((s={crypto:this.crypto,body:l,receiverPublicKey:c.publicKey}).body),bodyHash:Xs(s.crypto.sha256,s.body),receiverPublicKeyHash:Xs(s.crypto.sha256,s.body.receiverPublicKey)},p=function(e){const t=void 0!==e.canonicalBody?zs(e.crypto.sha256(Ys(e.canonicalBody))):Xs(e.crypto.sha256,e.body),r=Xs(e.crypto.sha256,e.body.receiverPublicKey);return{type:Kn,targetNode:e.body.targetNode,networkId:e.body.networkId,...void 0!==e.body.keyPath?{keyPath:e.body.keyPath}:{},bodyHash:t,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:r,alg:e.body.alg,keyVersion:e.body.keyVersion}}({crypto:this.crypto,body:l,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:c.publicKey,canonicalBody:h.canonicalBody}),y=await async function(e,t,r){const s=function(e,t){if(t.body.type!==Kn)return{ok:!1,error:qn({code:"INVALID_INPUT",message:`body.type must be ${Kn}`})};if(t.facts.type!==Kn)return{ok:!1,error:qn({code:"INVALID_INPUT",message:`facts.type must be ${Kn}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.targetNode must equal targetNode — the UCAN audience binds the request to a single node"})};if(t.body.targetNode!==t.targetNode)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==vr(t.networkId).keyPath)throw new mr("networkId must identify the network root")}catch(e){return{ok:!1,error:qn({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if(vr(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new mr("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:qn({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=Zs(t.body);return Xs(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:qn({code:"INVALID_INPUT",message:"facts.bodyHash does not match the canonical body hash"})}:{ok:!0,data:t,canonicalBody:r}}(e,r);if(!s.ok)return s;try{const e=await t.signDecryptInvocation(s.data);return e.authorization&&e.invocationCid?e.canonicalBody!==s.canonicalBody?{ok:!1,error:qn({code:"INVALID_INPUT",message:"decrypt-invocation signer returned a canonicalBody that does not match the SDK's canonicalization — signer must use the SDK-provided body"})}:{ok:!0,data:e}:{ok:!1,error:qn({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:qn({code:"TRANSPORT_ERROR",cause:e instanceof Error?e:new Error(String(e)),message:`failed to sign decrypt invocation: ${e instanceof Error?e.message:String(e)}`})}}}(this.crypto,this._config.signer,{targetNode:o,networkId:e.networkId,body:l,facts:p,proof:t});if(this.assertActive(),!y.ok)return"TRANSPORT_ERROR"!==y.error.code?y:Bn(qn({code:"INVALID_INPUT",message:"Unable to build decrypt request"}));let f;try{f=await this._config.transport.postDecrypt({targetNode:o,networkId:e.networkId,authorization:y.data.authorization,canonicalBody:y.data.canonicalBody,signal:this.abortSignal}),this.assertActive()}catch(t){const r=br(t);return r?Bn(Zn(r)):t instanceof Ct.DecryptTransportResponseError?Bn(qn(404===t.status?{code:"NETWORK_NOT_FOUND",networkId:e.networkId,message:t.notFoundMessage}:401===t.status||403===t.status?{code:"DECRYPT_DENIED",message:"Node denied decrypt request",...void 0===t.permissionHint?{}:{permissionHint:t.permissionHint}}:{code:"INVALID_RESPONSE",message:"Node decrypt request failed"})):Bn(Zn({code:"TRANSPORT_ERROR",cause:Mn(t)}))}const m=function(e){const{crypto:t,request:r,facts:s,invocationCid:n,requestBodyHash:i,response:a}=e;if(a.type!==$n)return{ok:!1,error:qn({code:"INVALID_RESPONSE",message:`response.type must be ${$n}`})};if(a.targetNode!==r.targetNode)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(a.networkId!==r.networkId)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(a.nodeId!==r.targetNode)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(a.alg!==r.alg)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(a.keyVersion!==r.keyVersion)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(a.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(a.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(a.invocationCid!==n)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const o=zs(t.sha256(Ys(`${n}${i}`)));if(a.requestHash!==o)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(s.encryptedSymmetricKeyHash!==a.encryptedSymmetricKeyHash||s.receiverPublicKeyHash!==a.receiverPublicKeyHash||s.networkId!==a.networkId||s.targetNode!==a.targetNode||s.alg!==a.alg||s.keyVersion!==a.keyVersion)return{ok:!1,error:qn({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return Zs(r)}(a)),u=Qs(a.nodeSignature);return t.verifyNodeSignature(a.nodeId,c,u)?{ok:!0,data:a}:{ok:!1,error:qn({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:this.crypto,request:l,facts:p,invocationCid:y.data.invocationCid,requestBodyHash:p.bodyHash,response:f});if(!m.ok)return m;const g=function(e,t,r){const s=Qs(r.wrappedKey);return e.openWithReceiverKey(t,s)}(this.crypto,c.privateKey,m.data),v=function(e,t,r){const s=Qs(t.ciphertext),n=void 0!==t.aad?Qs(t.aad):void 0;return e.authDecrypt(r,s,n)}(this.crypto,e,g);return Hn(v)}catch(e){const t=br(e);return Bn(t?Zn(t):qn({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var s}assertActive(){this._config.assertActive?.()}}).serviceName="encryption";var Wn=je({kty:$e(),crv:$e().optional(),x:$e().optional(),y:$e().optional(),d:$e().optional(),e:$e().optional(),n:$e().optional(),kid:$e().optional(),alg:$e().optional(),use:$e().optional(),key_ops:Fe($e()).optional()}),Gn=We(["main","session","ingested"]),zn=je({id:$e(),did:$e(),type:Gn,jwk:Wn.optional(),priority:Ve()}),Jn=(je({code:$e(),message:$e(),service:Ze("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Le(t=>t instanceof e,t))(Error).optional(),meta:Be($e(),Me()).optional()}),{AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_EXPIRED:"AUTH_EXPIRED",NOT_INITIALIZED:"NOT_INITIALIZED",NOT_FOUND:"NOT_FOUND",REVOKED:"REVOKED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",CREATION_FAILED:"CREATION_FAILED",REVOCATION_FAILED:"REVOCATION_FAILED",INVALID_TOKEN:"INVALID_TOKEN",KV_SERVICE_UNAVAILABLE:"KV_SERVICE_UNAVAILABLE",DATA_FETCH_FAILED:"DATA_FETCH_FAILED",VALIDATION_ERROR:"VALIDATION_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",CHAIN_TOO_DEEP:"CHAIN_TOO_DEEP",INVALID_CURSOR:"INVALID_CURSOR"}),Qn=je({cid:$e(),delegateDID:$e(),spaceId:$e(),path:$e(),actions:Fe($e()),caveats:Fe(Be($e(),Me())).optional(),expiry:Ge(),isRevoked:qe(),delegatorDID:$e().optional(),createdAt:Ge().optional(),parentCid:$e().optional(),allowSubDelegation:qe().optional(),authHeader:$e().optional()}),Yn=(je({cid:$e().min(1),status:We(["active","revoked","expired","unavailable","not_found"]),exists:qe(),active:qe(),revoked:qe(),expired:qe()}).strict().superRefine((e,t)=>{("active"===e.status?e.exists&&e.active&&!e.revoked&&!e.expired:"revoked"===e.status?e.exists&&!e.active&&e.revoked&&!e.expired:"expired"===e.status?e.exists&&!e.active&&!e.revoked&&e.expired:"unavailable"===e.status?e.exists&&!e.active&&!e.revoked&&!e.expired:!(e.exists||e.active||e.revoked||e.expired))||t.addIssue({code:c.custom,message:"delegation status flags do not match status"})}),je({revoked:Ze(!0),cid:$e().min(1)}).strict()),Xn=je({resource:$e().min(1),actions:Fe($e()),caveats:Fe(Be($e(),Me()))}).strict(),ei=$e().datetime({offset:!0}).transform(e=>new Date(e)),ti=je({cid:$e().min(1),direction:We(["granted","received"]),delegatorDid:$e().min(1),delegateDid:$e().min(1),resources:Fe(Xn),parents:Fe($e()),issuedAt:ei.nullable(),notBefore:ei.nullable(),expiresAt:ei.nullable(),status:We(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:ei.nullable().optional(),revokedBy:$e().optional(),revokedAncestorCid:$e().optional()}).strict(),ri=je({schemaVersion:Ze(2),items:Fe(ti),nextCursor:$e().optional()}).strict(),si=(je({direction:We(["granted","received","all","issued"]).optional(),status:We(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:$e().trim().min(1).optional(),limit:Ve().int().min(1).max(100).optional(),cursor:$e().min(1).optional()}).strict(),je({resource:$e(),action:$e(),keys:Fe(zn),delegation:Qn,expiresAt:Ge().optional()}),je({cid:$e(),spaceId:$e(),delegator:$e(),delegatee:$e(),keyId:$e().optional(),path:$e(),actions:Fe($e()),expiry:Ge().optional(),notBefore:Ge().optional(),isRevoked:qe(),createdAt:Ge(),parentCid:$e().optional()}),je({delegateDID:$e(),path:$e(),actions:Fe($e()),expiry:Ge().optional(),disableSubDelegation:qe().optional(),statement:$e().optional()}),Fe(Qn),je({root:Qn,chain:Fe(Qn),leaf:Qn}),We(["granted","received","all"])),ni=(je({direction:si.optional(),path:$e().optional(),actions:Fe($e()).optional(),includeRevoked:qe().optional(),delegator:$e().optional(),delegatee:$e().optional(),validAt:Ge().optional(),limit:Ve().optional(),cursor:$e().optional()}),We(["owned","delegated"])),ii=(je({id:$e(),name:$e().optional(),owner:$e(),type:ni,permissions:Fe($e()).optional(),expiresAt:Ge().optional()}),We(["base64","compact","ipfs"]));je({token:$e(),url:$e(),delegation:Qn,schema:ii,expiresAt:Ge().optional(),description:$e().optional()}),function(e){je({data:e,delegation:Qn,spaceId:$e(),path:$e()})}(Me()),je({persist:qe().optional(),validateChain:qe().optional(),keyName:$e().optional(),createSessionKey:qe().optional(),priority:Ve().optional()}),je({path:$e(),actions:Fe($e()).optional(),expiry:Ge().optional(),schema:ii.optional(),description:$e().optional(),baseUrl:$e().optional(),allowSubDelegation:qe().optional()}),je({hosts:Fe($e()),accountSpaceId:$e().min(1).optional(),session:Me().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:Me().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:Me().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:Le().optional(),sessionInvocationSigner:Le().optional(),resourceTransport:Le().optional(),fetch:Me().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),je({createSessionKey:Me().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:Me().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:Me().refine(e=>"function"==typeof e,{message:"Expected a function"})}),je({siwe:$e(),signature:$e(),version:Ve(),cid:$e().optional()});var ai=je({service:$e(),space:$e(),path:$e(),actions:Fe($e()),caveats:Fe(Be($e(),Me())).optional()}),oi=(je({session:Me().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:$e(),spaceId:$e(),abilities:Be($e(),Be($e(),Fe($e()))),expirationSecs:Ve(),notBeforeSecs:Ve().optional(),disableSubDelegation:qe().optional()}),je({delegation:$e(),cid:$e(),delegateDID:$e(),expiry:Ge(),resources:Fe(ai)}),{REVOKE:"tinycloud.delegation/revoke",STATUS:"tinycloud.delegation/status",LIST:"tinycloud.delegation/list",GET:"tinycloud.delegation/get",CHECK:"tinycloud.delegation/check"});function ci(e,t,r,s){return{code:e,message:t,service:"delegation",cause:r,meta:s}}var ui="delegation-issued-query-v1";async function di(e,t,r){const s=await async function(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}(e),n={...r,status:e.status};return 401===e.status||403===e.status?ci(Jn.PERMISSION_DENIED,""===s?"The node refused the request":s,void 0,n):400===e.status&&s.includes("invalid delegation query cursor")?ci(Jn.INVALID_CURSOR,"The node rejected the page cursor; list again from the start",void 0,n):503===e.status?ci(Jn.CHAIN_TOO_DEEP,"This delegation chain is too long for the node to check right now; try again later",void 0,{...n,retryable:!0}):ci(Jn.NETWORK_ERROR,`${t}: ${e.status} - ${s}`,void 0,n)}var li=class extends Error{};function hi(){return{ok:!1,error:ci(Jn.UNSUPPORTED_OPERATION,"This node doesn't support listing issued delegations yet",void 0,{feature:ui})}}async function pi(e,t){const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:ci(Jn.NOT_INITIALIZED,"Listing issued delegations needs a session key signer")};try{const s=async(e,s,n)=>e(`${s}/delegation/query`,{method:"POST",headers:{Authorization:await r.sign({[`${r.did()}/delegation`]:{[oi.LIST]:[{}]}},n),"content-type":"application/json"},body:JSON.stringify(t),redirect:"error"});let n;if(e.resourceTransport)n=await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>{const t=e.nodeInfo.features;if(!Array.isArray(t)||!t.includes(ui))throw new li;return s(e.fetch,e.url,e.nodeDid)},{nodeLocal:!0});else{const t=await async function(e){if(e.state.issuedQuerySupported)return{ok:!0,data:!0};const t=await e.fetchFn(`${e.host}/info`,{redirect:"error"});if(!t.ok)return{ok:!1,error:ci(Jn.NETWORK_ERROR,`Couldn't read the node's info: ${t.status}`,void 0,{status:t.status})};const r=await t.json();return e.state.issuedQuerySupported=Array.isArray(r.features)&&r.features.includes(ui),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!t.ok)return t;if(!t.data)return hi();n=await s(e.fetchFn,e.host)}if(!n.ok)return{ok:!1,error:await di(n,"Failed to query issued delegations",{})};const i=ri.safeParse(await n.json());return i.success?{ok:!0,data:i.data}:{ok:!1,error:ci(Jn.INVALID_TOKEN,"Node returned an invalid delegation query response")}}catch(e){return br(e)?{ok:!1,error:{...jr("delegation",e),service:"delegation"}}:e instanceof li?hi():{ok:!1,error:ci(Jn.NETWORK_ERROR,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function yi(e,t){const{pageSize:r=100,maxItems:s,untilCid:n,...i}=t;if(void 0!==s&&(!Number.isInteger(s)||s<1))return{ok:!1,error:ci(Jn.INVALID_INPUT,"maxItems must be a positive integer")};const a=[],o=new Set;let c;do{const t=Math.min(r,void 0===s?r:s-a.length),n=await e({...i,direction:"issued",limit:t,...void 0===c?{}:{cursor:c}});if(!n.ok)return n;if(a.push(...n.data.items),c=n.data.nextCursor,void 0!==c){if(o.has(c))return{ok:!1,error:ci(Jn.INVALID_TOKEN,"The node returned the same page cursor twice while listing issued delegations")};o.add(c)}}while(void 0!==c&&(void 0===s||a.length<s)&&(void 0===n||!a.some(e=>e.cid===n)));return{ok:!0,data:void 0===s?a:a.slice(0,s)}}async function fi(e,t){if(!t)return{ok:!1,error:ci(Jn.INVALID_INPUT,"cid is required")};const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:ci(Jn.NOT_INITIALIZED,"Revoking an issued delegation needs a session key signer")};try{const s=async(e,s,n)=>e(`${s}/revoke`,{method:"POST",headers:{Authorization:await r.sign({[`urn:cid:${t}`]:{[oi.REVOKE]:[{}]}},n)},redirect:"error"}),n=e.resourceTransport?await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>s(e.fetch,e.url,e.nodeDid),{nodeLocal:!0}):await s(e.fetchFn,e.host);if(!n.ok)return 404===n.status?{ok:!1,error:ci(Jn.NOT_FOUND,`Delegation not found: ${t}`)}:{ok:!1,error:await di(n,"Failed to revoke delegation",{cid:t})};const i=Yn.safeParse(await n.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:ci(Jn.REVOCATION_FAILED,"Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return br(e)?{ok:!1,error:{...jr("delegation",e),service:"delegation"}}:{ok:!1,error:ci(Jn.NETWORK_ERROR,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}module.exports=i})();
|